You are on page 1of 78

Security in .

Net

Course Objectives
To introduce the participants to Security architecture in .NET To explain the Authentication and Authorization To explain cryptography and xml encryption To explain how to write secure coding To discuss partial trust development and Code Access Security To introduce to Windows CardSpace

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Agenda
IIS and ASP.Net Security Authentication Implementing Authorization Cryptography XML encryption Secure Coding Code Access Security Windows CardSpace

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

IIS and ASP.NET Security

ASP.NET Security Architecture


IIS is the gateway to ASP.NET ASP.NET runs under the ASPNET account which has minimal privileges

Web Clients

ASP.NET Applications

IIS

.NET Framework

Windows Server 2003 family operation Systems

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

All Web clients communicate with ASP.NET applications through Microsoft Internet Information Services (IIS). IIS authenticates the request if required and then locates the requested resource (such as an ASP.NET application). If the client is authorized, the resource is made available. ASP.NET security settings are configured in the Machine.config and Web.config files. As with other configuration information, base settings and default settings are established in the Machine.config file in the Config subdirectory of the current .NET Framework installation.

Authentication Mechanisms with IIS & ASP.NET


IIS Authentication: Anonymous Login Guest Login Basic Authentication Digest Authentication Integrated Windows Authentication Certificate based Authentication ASP.NET Authentication Windows Forms Passport None

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

IIS Authentication - Anonymous


Enables access to the public areas of a Web site without prompting users for a user name or password No end-user authentication occurs in either IIS or ASP.NET By default, the IUSR_computername account is used to allow anonymous access. Works with all browsers Gives highest performance, but lowest security Pros Offers the best performance Does not require management of individual user accounts No browser restrictions Cons Does not authenticate clients on an individual basis, least secure

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

With Anonymous authentication, the server does not request the client to send user credentials. It is a good choice when your site or service is publicly available and you do not need to know the identity of the caller. Additionally, there are typically no browser restrictions which stem from incompatibilities with supported authentication mechanisms. When a site is configured for Anonymous authentication, all users are allowed access. It is important to note that although you may have IIS configured for Anonymous authentication, you may be authenticating at the ASP.NET layer, which is not true Anonymous authentication. This section assumes that both IIS and the application do not require a logon. Pros Offers the best performance Does not require management of individual user accounts No browser restrictions Cons Does not authenticate clients on an individual basis, least secure Usage Good choice for publicly available web sites that do not require the identity of the caller The account used for Anonymous Authentication can be changed at the Web site, virtual directory or file level

IIS Authentication - Integrated Windows


Uses either NTLM challenge/response or Kerberos to authenticate users with a Windows NT Domain or Active Directory account A Hash of the credentials is sent, the password is not sent across the network Delegation not possible with NTLM challenge/response Pros
Best suited for intranet More secure since password is not sent across the network Works out-of-the-box Provides automatic logon/no logon dialog box

Cons
Cannot be used on internet Delegation possible only with Kerberos Enterprise only does not work through Proxy Servers (keep-alive connection required) Configured to be compatible with older clients

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Integrated Windows authentication (using either NTLM challenge/response or Kerberos) involves authenticating a user with a Windows NT Domain or Active Directory account. Unlike Basic and Digest authentication, the encrypted password is not sent across the network, which makes this method very secure. If Active Directory Services is installed on the server and the browser is compatible with the Kerberos V5 authentication protocol, both the Kerberos V5 protocol and the challenge/response protocol are used; otherwise only the challenge/response protocol is used. It is best suited for an intranet environment, where both user and Web server computers are in the same domain and where administrators can ensure that every computer is running Microsoft Internet Explorer version 3.01 or later.

IIS Authentication - Basic Authentication


This slide left blank for notes continued from previous page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

When IIS is configured for Basic authentication, it instructs the browser to send the users credentials over HTTP. Passwords and user names are encoded using Base64 encoding. Although the password is encoded, it is considered insecure due its ability to be deciphered relatively easily. The browser prompts the user with a dialog box, and then reissues the original anonymous request with the supplied credentials, including the user name and password. A pop-up logon dialog box may or may not be appropriate, depending on your user interface design requirements. Most Internet browsers support Basic authentication. Base64 encoding is the scheme used to transmit binary data. Base64 processes data as 24-bit groups, mapping this data to four encoded characters. Base64 encoding is sometimes referred to as 3-to-4 encoding. Each 6 bits of the 24-bit group is used as an index into a mapping table (the base64 alphabet) to obtain a character for the encoded data. The encoded data has line lengths that are limited to 76 characters. In the Default domain box, either type the domain name you want to use, or click Select to browse to a new default logon domain. If the Default domain box is filled in, the name is used as the default domain. If the Default domain box is left empty, IIS uses the domain of the computer that is running IIS as the default domain. However, the domain specified by DefaultLogonDomain is used only when a client does not specify a domain in the logon dialog box that appears on the client computer. Optionally, you can enter a value in the Realm box, which configures the value of the Realm Metabase Property. If the Realm property is set, its value appears on the clients logon dialog box, when Basic authentication is used. The value of Realm is sent to the client for informational purposes only, and is not used to authenticate clients using Basic authentication

IIS Authentication - Basic Authentication


This slide is left blank for notes continued from previous page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

IIS Authentication - Basic Authentication: Authentication process: IIS instructs the browser to send the users credentials over HTTP Browser prompts the user with a dialog box User name and password entered by the user are Base64 encoded (which is NOT secure) Most browsers support Basic authentication as it is a part of the HTTP 1.0 specification Delegation is possible using Basic authentication Combine Basic authentication with SSL to prevent passwords from being deciphered Pros Least common denominator: All HTTP clients support Basic authentication Makes it possible to track individual users Delegation of security credentials possible If IIS does not control the password, can access network resources Cons Is inherently insecure unless using SSL/TLS, which impacts performance Clear text password (Base64 Encoded) Over the wire and on the server Needs to be protected via SSL (continued on next slide)

10

IIS Authentication - Digest Authentication


This slide is left blank for notes continued from previous page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Usage Consider Basic authentication when you require: Users to have Windows NT Domain or Active Directory accounts Support for multiple browsers Support for authentication over the Internet Access to the clear text password in your application code Delegation Do not use Basic authentication when you require: Secure logon while not using a secure channel, such as Secure Sockets Layer (SSL) Storage of information in a custom database A customized form presented to the user as a logon page IIS Authentication - Digest Authentication: New to Windows 2000 and IIS 5.0 (HTTP 1.1 specification) Digest authentication sends credentials across the network as a Message Digest 5 (MD5) hash. The actual password is never sent. Platform requirements for Digest authentication Clients: Internet Explorer 5.x (or later) Server: running Active Directory with user accounts configured for Digest authentication (continued on next slide)

11

IIS Authentication - Digest Authentication


This slide is left blank for notes continued from previous page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Password needs to be stored in clear text on separate server which is the biggest constraint Digest authentication is more secure than Basic authentication alone Pros More secure since password is not sent on network. Does not require SSL/TLS for the sake of password protection. Works through proxies Password is not known to IIS Cons Cannot delegate security credentials Is only supported by Internet Explorer 5.0 and later Passwords have to be stored in the AD using reversible encryption. Domain Controller has to be secured. Medium secure Supported by Internet Explorer 5 and higher Is subject to replay attacks unless you use SSL/TLS Usage Can be used as an alternative to Basic Authentication, when SSL/TLS cannot be used for protecting data traveling over the wire.

12

IIS Authentication Mechanisms - Comparison


Au t h M e t h od ( Se cu r it y Le ve l) Anonym ous aut hent icat ion ( None) Basic aut hent icat ion ( Low ) H ow Pa ssw or d Ar e Se n t N/ A Clie n t Re qu ir e m e n t s Any brow ser Se r ve r Re qu ir e m e nts I USR_com pu t er nam e account Valid dom ain account s Cr osse s Pr ox y Se r ve r s a n d Fir e w a lls Yes Com m e n t s Used for public areas of I nt ernet w eb sit es Clear Tex t Passw or d, use only w it h SSL

Base64 encoded clear t ext

HTTP 1.0 com pliant brow sers

Yes, but sending passw ords across a proxy server or firew all in clear t ex t is a securit y risk because Base64 encoded clear t ex t is not encr ypt ed. Yes

Digest aut hent icat ion ( High) I nt egr at ed Window s aut hent icat ion ( High)

Hashed

I nt ernet Explorer 5 or lat er I nt ernet Explorer 2. 0 or lat er for NTLM; Window s 2000 or lat er w it h int ernet Explorer 5 or lat er for Kerberos

Reversible encry pt ion in AD Valid dom ain account s

Hashed w hen NTLM is used; Ker beros t icket w hen Ker beros is used.

No, unless used over a PPTP connect ion

Used m ainly for I nt ranet s

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

13

Authentication Mechanisms in ASP.Net


Windows Authentication (via IIS)
Basic, Digest, NTLM/ Kerberos, IIS Certificate Support

Forms-based (Cookie) Authentication


Application credential verification

Microsoft Passport Authentication

To enable a specified authentication provider for an ASP.NET application, create an entry in the application' configuration file as follows: s
// web.config file <authentication mode = "[Windows/Forms/Passport/None]"> </authentication

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

ASP.NET provides a number of declarative and programmatic authorization mechanisms that can be used in conjunction with a variety of authentication schemes. This allows you to develop an in depth authorization strategy and one that can be configured to provide varying degrees of granularity; for example, per-user or per-user group (role-based).

14

ASP.NET Authentication - Windows


The Windows authentication provider relies upon IIS to perform the required authentication of a client After IIS authenticates a client, it passes a security token to ASP.NET Based on the security token that it receives from IIS, ASP.NET then constructs and attaches an object to the application context Pros Authenticates using Windows accounts, so you do not need to write any custom authentication code Cons May require the use and management of individual Windows user accounts

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

15

ASP.NET Authentication - Forms


To configure Forms Authentication Set the authentication mode in Web.config to Forms Create a Web form to collect logon information Create a file or database to store user names and passwords Write code to add new users to the user file or database Write code to authenticate users against the user file or database <authentication mode= "Forms"> <forms name=".ASPXAUTH" loginUrl="login.aspx" protection="all" timeout="30" path="/" cookieless="UseDeviceProfile" /> </authentication>
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Forms authentication generally refers to a system in which unauthenticated requests are redirected to an HTML form, using HTTP client-side redirection. Forms authentication is a good choice if your application needs to collect its own user credentials at logon time through HTML forms. The user provides credentials and submits the form. If the application authenticates the request, the system issues a cookie that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the cookie in the request headers. The requests are authenticated and authorized by an ASP.NET event handler using whatever validation method the application specifies. Note that forms authentication is often used for personalization, where content is customized for a known user. In some of these cases, identification is the issue rather than authentication, so it is enough merely to store the user name in a durable cookie and use that cookie to access the users personalization information.

16

Forms Authentication Configuration


This slide is left blank for notes continued from previous page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

The following list highlights the key steps that you must perform to implement Forms authentication: 1. Configure IIS for anonymous access. 2. Configure ASP.NET for Forms authentication. 3. Create a logon Web form and validate the supplied credentials. 4. Retrieve a role list from the custom data store. 5. Create a Forms authentication ticket (store roles in the ticket). 6. Create an IPrincipal object. 7. Put the IPrincipal object into the current HTTP context. 8. Authorize the user based on user name/role membership.

17

Forms Authentication Configuration This slide is left blank for notes continued
from previous page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

protection Specifies the type of encryption, if any, to use for cookies. All Specifies that the application uses both data validation and encryption to help protect the cookie. This option uses the configured data validation algorithm (based on the <machineKey> element). Triple-DES (3DES) is used for encryption, if available and if the key is long enough (48 bytes or more). All is the default (and recommended) value. timeout Specifies the amount of time, in integer minutes, after which the cookie expires. The default value is 30. If the SlidingExpiration attribute is true, the timeout attribute is a sliding value, expiring at the specified number of minutes after the time the last request was received. To prevent compromised performance, and to avoid multiple browser warnings for users that have cookie warnings turned on, the cookie is updated when more than half the specified time has elapsed. This might result in a loss of precision. Persistent cookies do not time out. path Specifies the path for cookies issued by the application. The default value is a slash (/), because most browsers are case-sensitive and will not send cookies back if there is a path case mismatch. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL This feature is controlled by the cookieless attribute of the forms element Attribute takes four parameters UseUri: Forces the authentication ticket to be stored in the URL. UseCookies: Forces the authentication ticket to be stored in the cookie (same as ASP.NET 1.0 behavior). AutoDetect: Automatically detects whether the browser/device does or does not support cookies. UseDeviceProfile: Chooses to use cookies or not based on the device profile settings from machine.config.

18

Forms Authentication Custom Validation


Users are configured in the database (or other Data Source)
<authentication mode= "Forms"> <forms loginUrl="login.aspx" path="/ /> </authentication>

Authentication code in the Login Form (login.aspx by default)


if (ValidateUser(txtUserName.Text, txtPassword.Text)) // If the user is valid, display the applications Start page. FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true); else //Custom error handling

In the above code sample, the ValidateUser() is a custom method that validates the supplied User Id and Password against the Data Source The FormsAuthentication classs RedirectFromLoginPage method displays the applications start page on successful log on (in the code above)
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

19

Membership Provider Model : New feature from ASP.NET 2.0


The ASP.NET 2.0 includes a new feature Membership Facilitates the creation and management of users. Membership works in conjunction with Role manager Role Manager provides the infrastructure for creating roles and assigning users to roles Both Membership and Role Manager have been designed with a provider-based model Membership providers provide the interface between ASP.NET' s membership service and membership data sources Storing membership information (user names, passwords, and supporting data) in Microsoft SQL Server, Active Directory, or an alternative data store Managing passwords, which includes creating, changing, and resetting them Specifying a custom membership provider, which allows to substitute code to manage membership and maintain membership data in a custom data store
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

ASP.NET membership The ASP.NET 2.0 includes new feature Membership which facilitates the creation and management of users. The Membership feature works in conjunction with another new feature called Role Manager. Role Manager provides the infrastructure for creating roles and assigning users to roles. When the Membership and Role Manager features are used in conjunction with Forms Authentication, ASP.NET 2.0 provides end-to-end support for creating, authenticating and authorizing users. In ASP.NET 2.0 microsoft included membership provider along with other providers like profile,roles etc.Web developers will no longer need to write and re-write the code to store and validate credentials. Instead, ASP.NET 2.0 provides membership and role providers as secure and extensible implementations for managing roles and membership in our web applications.Membership providers provide the interface between ASP.NETs membership service and membership data sources.

20

Login Controls introduced in ASP.NET 2.0


Provide a standard set of controls that are well built, secure and easily reusable
Control Name Login Description Provides the functionality for a user to login and logout of the application The LoginView control automatically detects a users authentication status Provides the standard registration page for a new user to register Provides a highly configurable control to perform a set of actions when the user forgets his password Provides a way for the users to change their passwords Provides the authenticated users registered name, which can be displayed back to the user in the application Determines the authentication status of the user and can accordingly display the login or the logout link

LoginView CreateUserWizard PasswordRecovery ChangePassword LoginName LoginStatus

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

LoginProvides :the functionality for a user to login and logout of the application CreateUserWizardProvides the standard registration page for a new user to register. The functionality can be easily extended. For instance a registration email with necessary information can be sent after the registration is completed PasswordRecoveryProvides a highly configurable control to perform a set of actions when the user forgets his password. The actions performed range from emailing a password reminder to sending the existing password itself in clear text. ChangePasswordProvides a way for the users to change their passwords. The MailDefinition property will notify the user once the password has been updated LoginNameProvides the authenticated users registered name, which can be displayed back to the user in the application LoginStatusDetermines the authentication status of the user and can accordingly display the login or the logout link LoginViewManages the view of the user depending on the role and privilege of the current user

21

Configuration File Encryption


Configuration File Encryption In the .NET Framework 2.0, developers will be able to encrypt sensitive parts of the web.config file using the aspnet_regiis utility. The decryption is done transparently The DPAPI protected configuration provider supports machine-level and user-level stores for key storage

aspnet_regiis.exe -pef "connectionStrings" C:\VirtualDirectory\Path

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

In the .NET Framework 2.0, developers will be able to encrypt sensitive parts of the web.config file (if containing password or keys, for instance) using the aspnet_regiis utility. The decryption is done transparently. The DPAPI protected configuration provider supports machine-level and user-level stores for key storage. The choice of store depends largely on whether or not the application shares state with other applications and whether or not sensitive data must be kept private for each application. If the application is deployed in the Web farm scenario, developers should use RSAProtectedConfigurationProvider to leverage the ease with which RSA keys can be exported on multiple systems. It uses RSA public key cryptography to provide data confidentiality. DPAPI - Data Protection Application Programming Interface The DPAPI is a pretty well thought-out mechanism to allow any application to do simple and yet powerful encryption for its data. It has good recovery methods.

22

Web Site Administration Tool


The ASP.NET Web Site Administration Tool allows you to view and manage Web site configuration through a simple Web interface. The Web Site Administration tool can be used to create new users and roles and control access to folders and individual pages of the Web application. The aspnet_regiis tool can be used to control access to the Web site administration tool

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Web Site Administration ToolThe ASP.NET Web Site Administration Tool allows you to view and manage your Web site configuration through a simple Web interface. The Web Site Administration tool can be used to create new users and roles and control access to folders and individual pages of the Web application. The aspnet_regiis tool can be used to control access to the Web site administration tool. One instance would be to only allow access to the administration tool on the local machine.

23

Factors in Choosing an Authentication Method


Server and client operating systems Client browser type Number of users, location and type of user name and password database Deployment considerations (Internet vs. intranet and firewalls) Application type (interactive Web site or non-interactive Web service) Sensitivity of data being protected Performance and scalability factors Application authorization requirements (all users, or restricted areas)

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

You should consider some or all of the following factors when choosing an authentication method: Server and client operating systems The client browser type The number of users, and the location and type of the user name and password database Deployment considerations, such as whether your application is Internet or intranet based and whether it is located behind a firewall The application type; for example, is it an interactive Web site or a non-interactive Web service Sensitivity of the data you are protecting Performance and scalability factors Application authorization requirements; for example, you may want your application to be available to all users, or you may need to restrict certain areas to registered users, and other areas to administrators only.

24

Implementing Authorization

Authorization
What is Authorization? Defining what authenticated clients are allowed to see and do within the application. Few important concepts Identities and Principal
.NET Framework uses identity and principal objects to represent users They provide the backbone of .NET role-based authorization.

Impersonation & Delegation


Techniques used by the server application to access resources on behalf of the client.

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Authorization - Defining what authenticated clients are allowed to see and do within the application. The .NET Framework uses identity and principal objects to represent users when .NET code is running and together they provide the backbone of .NET role-based authorization.

26

Identities and Principal


.NET security is based on IPrincipal and IIdentity objects. Identities: An identity represents a certain user Identity is established through authentication Processes run code under an identity Use following code to get the username of the current user Response.Write (User.Identity.Name) Principal: Describes a user and its role Two Types: WindowsPrincipal (has UID and role info) GenericPrincipal (has UID and role info)

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Principal: Describes a user and its role Two Types: GenericPrincipal (has UID and role info)

Wraps a GenericIdentity (has UID info only) Allows extensibility to non-Windows platforms and scenarios (eg: database centric credentials)
WindowsPrincipal (has UID and role info)

Wraps a WindowsIdentity (has UID info only)

27

.NET Framework classes


Use FCL classes or create custom implementation
Identity class WindowsIdentity GenericIdentity PassportIdentity FormsIdentity Principal class WindowsPrincipal GenericPrincipal

Custom implementations should implement IIdentity and IPrincipal interfaces present in the System.Security.Principal namespace Principal objects can be acquired in two ways
WindowsIdentity.GetCurrent() method, then create WindowsPrincipal Thread.CurrentPrincipal property ASP.NET only: HttpContext.Current.User
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Identities and Principal


The IPrincipal interface allows you to test role membership through an IsInRole method and also provides access to an associated IIdentity object The IIdentity interface provides additional authentication details such as the name and authentication type.
public interface IPrincipal{ bool IsInRole( string role ); IIdentity Identity {get;} } public interface IIdentity{ string authenticationType {get;} bool IsAuthenticated {get;} string Name {get;} }
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

PrincipalPermission
Allows a check against the active principal using the language constructs defined for both declarative and imperative security actions Since active Principal describes both Identity and Role information, we can demand either or both Demands on PrincipalPermission can be made Demands on the PrincipalPermission
Declarative Demand [PrincipalPermission (SecurityAction.Demand,Role=@BUILTIN\Administrators)] Imperative Demand: PrincipalPermission p = new PrincipalPermission (null, BUILTIN\Administrator) p.Demand()

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Unlike most other permission objects, PrincipalPermission does not extend CodeAccessPermission. It does, however, implement the IPermission interface. This is because PrincipalPermission is not a code access permission, that is, it does not protect or control access to any system resource. Instead, it allows code to perform actions (Demand, Union, Intersect, and so on) against the current user identity in a manner consistent with the way those actions are performed for code access and code identity permissions. Manual role checks. For fine-grained authorization, you can call the IPrincipal.IsInRole method to authorize access to specific code blocks based on the role membership of the caller. Both AND and OR logic can be used when checking role membership. Declarative role checks (gates to your methods). You can annotate methods with the PrincipalPermissionAttribute class (which can be shortened to PrincipalPermission), to declaratively demand role membership. These support OR logic only. For example you can demand that a caller is in at least one specific role (for example, the caller must be a teller or a manager). You cannot specify that a caller must be a manager and a teller using declarative checks. Imperative role checks (checks within your methods). You can call PrincipalPermission.Demand within code to perform fine-grained authorization logic. Logical AND and OR operations are supported.

30

Impersonation
Impersonation allows ASP.NET applications to execute with a client' identity s By enabling impersonation, ASP.NET receives the security token to impersonate from IIS Impersonation is configured in the Web.config file. There are 3 options for this setting: 1. Impersonation is disabled 2. Impersonation is enabled 3. Impersonation is enabled and a specific impersonation identity is specified
<identity impersonate="true"/> Or <identity impersonate="false"/> //To impersonate a particular identity <identity impersonate="true" username="joydip" password="jude"/>

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

With impersonation, ASP.NET applications can optionally execute with the identity of the client on whose behalf theyre operating. Impersonation is usually performed for resource access control. You should carefully consider whether or not impersonation is required, because it consumes additional server resources. Delegation is a more powerful form of impersonation and allows remote resources to be accessed by the server process while acting as the client. If impersonation is enabled, ASP.NET will receive the token to impersonate from IIS. You have more granular control of impersonation in a Web application when using ASP.NET in comparison to traditional Active Server Pages (ASP). This is controlled by specifying a value in the applications Web.config file. You have the following three options when specifying the required impersonation setting: Impersonation enabled. In this instance, ASP.NET will impersonate the token passed to it by IIS, which will either be an authenticated user or the anonymous Internet user account. <identity impersonate="true"/> Impersonation enabled, with a specific impersonation identity specified. In this instance, ASP.NET will impersonate the token generated using the configured identity. In this case the client token, if applicable, is not used. <identity impersonate="true" name="domain\user" password="pwd"/> Impersonation is disabled. This is the default setting for backward compatibility with ASP. In this instance, the ASP.NET thread will run using the process token of the application worker process, which by default is the IIS system account, regardless of which combination of IIS and ASP.NET authentication have been used. <identity impersonate="false"/> If the application resides on a UNC share, ASP.NET will always impersonate the IIS UNC token to access that share unless a configured account is used. If an explicitly configured account is provided, ASP.NET will use that account in preference to the IIS UNC token.

31

Delegation
In the Impersonation/Delegation Model the service or component impersonates the clients identity before it accesses the next downstream service. If the next service in line is on the same computer, impersonation is sufficient. Delegation is required if the downstream service is located on a remote computer
App Server
Computer 1 (impersonating)

Impersonation
Computer 2

Delegation

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Impersonation and Delegation


Below table shows the various IIS authentication types and indicates if the security context of the authenticated caller can be delegated
Auth. Type Anonymous Basic Integrated (NTLM) Integrated (Kerberos) Client certificates Can Delegate Yes Yes No Yes Depends Both user account and server account must be configured for delegation Can be delegated is used with IIS certificate mapping Comment Use either domain account or mirrored local account Use either domain accounts or mirrored local accounts

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Kerberos delegation under Windows 2000 is unconstrained. A user may be able to make multiple network hops across multiple remote computers. To close this potential security risk, limit the scope of the domain accounts reach by removing the account from the Domain Users group and allow the account to be used only to log on to specific computers.

33

Authorization Strategies
Role Based Users are partitioned into application-defined, logical roles Members of a particular role share the same privileges within the application. Access to operations (typically expressed by method calls) is authorized based on the role-membership of the caller. Resources are accessed using fixed identities Eg: using .Net Roles, URL based authorization Resource Based Individual resources are secured using Windows ACLs. The application impersonates the caller prior to accessing resources, which allows the operating system to perform standard access checks. Resources are accessed using the original callers identity (using impersonation). Eg: File Authorization
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Using URL Authorization


Example: allow Admins or WebServiceUsers and deny all others

<!-- * is all users, ? is anonymous users --> <!---> <authorization> <allow verbs="POST" Roles="Admins" /> <allow Roles="WebServiceUsers"/> <deny users="*" /> </authorization>
Example: deny anonymous users

<authorization> <deny users="?" /> </authorization>


In the .NET Framework 2.0, this has been extended to non-ASP.NET file types as well for instance .jpg or .html.
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

URL Authorization. This is an authorization mechanism, configured by settings within machine and application configuration files. URL Authorization allows you to restrict access to specific files and folders within your applications Uniform Resource Identifier (URI) namespace. For example, you can selectively deny or allow access to specific files or folders (addressed by means of a URL) to nominated users. You can also restrict access based on the users role membership and the type of HTTP verb used to issue a request (GET, POST, and so on). URL Authorization requires an authenticated identity. This can be obtained by a Windows or ticket-based authentication scheme. rolesIdentifies a targeted role for this element. The associated IPrincipal object for the request determines the role membership. You can attach arbitrary IPrincipal objects to the context for a given request and they can determine role membership in whatever way you like. For example, the default WindowsPrincipal class uses Microsoft Windows NT groups to determine role membership.usersIdentifies the targeted identities for this element.verbsDefines the HTTP verbs to which the action applies, such as GET, HEAD, and POST. To establish the conditions for access to a particular directory, you must place a configuration file that contains an <authorization> section in that directory. The conditions set for that directory also apply to its subdirectories, unless configuration files in a subdirectory override them. The general syntax for this section is as follows At run time, the authorization module iterates through the <allow> and <deny> tags until it finds the first access rule that fits a particular user. It then grants or denies access to a URL resource depending on whether the first access rule found is an <allow> or a <deny> rule. The default authorization rule in the Machine.config file is <allow users="*"/> so, by default, access is allowed unless configured otherwise.

35

.Net Roles - Role based Authorization


.Net Roles is a typical usage if Role based authorization Revolve around IPrincipal objects that contain the list of roles that an authenticated identity belongs to. Ways to perform authorization using .Net roles declaratively, using PrincipalPermission demands programmatically, using imperative PrincipalPermission demands or the IPrincipal.IsInRole method. .Net Roles can be used with Windows authentication Non-Windows authentication

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

.Net Roles with Windows Authentication: ASP.NET automatically constructs a WindowsPrincipal that is attached to the context of the current Web request (using HttpContext.User). After the authentication process is complete and ASP.NET has attached to object to the current request, it is used for all subsequent .NET role-based authorization. .Net Roles with Non-Windows authentication - write code to create a GenericPrincipal object (or a custom IPrincipal object) and populate it with a set of roles obtained from a custom authentication data store such as a SQL Server database. The custom IPrincipal object (containing roles obtained from a custom data store) is attached to the current request context (using HttpContext.User), basic role-checking functionality is ensured.

36

.Net Roles
Using Windows Authentication ASP.NET constructs a WindowsPrincipal object and the Windows group membership of the user determines the associated role set. Using Non-Windows Authentication Capture the users credentials. Validate the users credentials against a custom data store such as a SQL Server database. Retrieve a role list, construct a GenericPrincipal object and associate it with the current Web request. Replace HttpContext.User with custom IPrincipal or GenericPrincipal

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Using Windows Authentication - ASP.NET constructs a WindowsPrincipal object and the Windows group membership of the user determines the associated role set. Using Non-Windows Authentication Capture the user s credentials. Validate the user s credentials against a custom data store such as a SQL Server database. Retrieve a role list, construct a GenericPrincipal object and associate it with the current Web request. Replace HttpContext.User with custom IPrincipal or GenericPrincipal The Principal object (Windows or Generic) which represents the authenticated user can be used for subsequent .Net Role checks Manual : By calling the IPrincipal.IsInRole method Declarative role checks using the PrincipalPermission Imperative role checks - using the PrincipalPermission

37

Cryptography
Cryptography helps protect data from being viewed or modified and helps provide a secure means of communication over otherwise insecure channels Cryptography is used to provide the following: Confidentiality Data integrity Authentication

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Cryptography helps protect data from being viewed or modified and helps provide a secure means of communication over otherwise insecure channels Cryptography is used to provide the following: Confidentiality. To ensure data remains private. Confidentiality is usually achieved using encryption. Data integrity. To ensure data is protected from accidental or deliberate (malicious) modification. Integrity is usually provided by hashes. Authentication. To assure that data originates from a particular party. Digital certificates are used to provide authentication. The System.Security.Cryptography namespace in .Net provides cryptographic services, including secure encoding and decoding of data, hashing, random number generation, and message authentication

38

Cryptography (Contd)
This slide is left blank for notes continued from previous page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Encryption - Process of transforming information so that it is unintelligible to anyone but the intended recipient. Decryption - Process of transforming encrypted information so that it is intelligible again. Cipher text :Encrypted messages are called cipher text. Cryptographic Algorithm - also called a cipher, is a mathematical function used for encryption or decryption like RSA. Symmetric Key Encryption Same key is used to encrypt and decrypt Asymmetric Key Encryption - Two keys are used. One for encryption and the other for decryption. Any one can be used to encrypt or decrypt. If one encrypts, only the other key can decrypt. Hashing Algorithm Is a mathematical function, when acted upon a text(message) will produce a hash, which is supposed to be unique. IV (used as salt) : Takes Input Block size and Generates SHA-1 hashed value by taking system time and a randomly selected number input (a random number to make it a little harder to fin dout when the IV was generated). A plain random number doesn'contain letters, so a hash i preferre t d as a pseudorandom generator. Output: Returns the number of chars as blocksize

39

Symmetric Cryptography Overview


Same key used to encrypt and decrypt data Problem: exchanging keys

Encryption Your Data Encode


Binary plaintext (byte array/stream)

Decryption
Binary ciphertext (byte array/stream)

Key

Decrypt
Binary plaintext (byte array/stream)

Encrypt
Binary ciphertext (byte array/stream)
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Decode Your Data

System.Security.Cryptography namespace provides classes for the below Symmetric Algorithm implementation. DES (Data Encryption Standard) System.Security.Cryptography.DES Triple DES (aka 3DES) System.Security.Cryptography.TripleDES Modified DES with 3x key size (key size = 56 bits) RC2 (Ron s Code 2 Ron Rivest of RSA) System.Security.Cryptography.RC2 Intended as replacement for DES Rijndael (rhine doll) System.Security.Cryptography.Rijndael Official (in US) successor to DES Reportedly around 3 times faster than 3DES

40

Asymmetric Cryptography Overview


Key pair one key used to encrypt, other to decrypt

Solves key exchange problem Can be used for both encryption and digital signatures

Encryption

Decryption
Binary ciphertext (byte array/stream)

Your Data Encode


Binary plaintext (byte array/stream)
Private Key

Decrypt
Binary plaintext (byte array/stream)

Encrypt
Binary ciphertext (byte array/stream)

ey Public K

Decode Your Data

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

System.Security.Cryptography namespace provides classes for the below Asymmetric Algorithm implementation. Asymmetric Algorithms RSA Signature and Encryption System.Security.Cryptography.RSA DSA Signature only System.Security.Cryptography.DSA

41

XML Encryption in .Net


XML Encryption allows to encrypt arbitrary data This feature is driven through the new EncryptedXml class. There are three approaches to Xml Encryption Encrypt the xml using symmetric encryption only Encrypt the xml using a combination of asymmetric and symmetric encryption Encrypt the xml using a X.509 Certificate

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

One of the new features being introduced with the Whidbey version of the .Net framework is XML encryption. XML Encryption allows you to encrypt arbitrary data, and have the result be an XML element. Much as XML digital signatures are driven through the SignedXml class, this feature is driven through the new EncryptedXml class. In order to allow this feature to work well with XML digital signatures, there is a special transform included with the framework, that allows the digital signature engine to decrypt the encryption document, and compute the signature over only that portion. There are three approaches to Xml Encryption. 1. Encrypt the xml using symmetric encryption only Only one session key is used and it s the same key that encrypts the xml which is used to decrypt it. The key is not stored with the encrypted xml and so the key needs to be loaded during the process and protected when stored. 2. Encrypt the xml using a combination of asymmetric and symmetric encryption The dual approach requires a symmetric session key to encrypt the data and an asymmetric key to protect the session key. Both the encrypted session key and the encrypted data are stored together in the xml document. The public asymmetric key is used to encrypt the session key while the private asymmetric key is used to decrypt the key. 3. Encrypt the xml using a X.509 Certificate This approach uses a X.509 certificate as the symmetrical key. X.509 certificates are provided by a third party vendor such as VeriSign.

42

XML Encryption in .Net


//The XML Document <?xml version="1.0" ?> <article> <articleinfo> <title>XPath Queries on XmlDocument objects </title> <abstract> <para>This article covers the basics</para> </abstract> <author> <honorific>Mr.</honorific> <firstname>George</firstname> <surname>James</surname> <email>gjames@doman.com</email> </author> </articleinfo> </article>

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

One of the new features being introduced with the Whidbey version of the .Net framework is XML encryption. XML Encryption allows you to encrypt arbitrary data, and have the result be an XML element. Much as XML digital signatures are driven through the SignedXml class, this feature is driven through the new EncryptedXml class. In order to allow this feature to work well with XML digital signatures, there is a special transform included with the framework, that allows the digital signature engine to decrypt the encryption document, and compute the signature over only that portion.

43

XML Encryption in .Net


//The XML Document after encryption
<?xml version="1.0" ?> <article> <articleinfo> <title>XPath Queries on XmlDocument objects </title> <abstract> <para>This article covers the basics.</para> <para>This article does not cover.</para> </abstract> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" /> <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#"> <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" /> <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> <KeyName>session</KeyName> </KeyInfo> <CipherData> <CipherValue>r4f7SI1aZKSvibbCipherValue> </CipherData> </EncryptedKey> </KeyInfo> <CipherData> <CipherValue>sGNhKqcSovipJdOFCFKYEEMRFd</CipherValue> </CipherData> </EncryptedData> </articleinfo> </article>

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

One of the new features being introduced with the Whidbey version of the .Net framework is XML encryption. XML Encryption allows you to encrypt arbitrary data, and have the result be an XML element. Much as XML digital signatures are driven through the SignedXml class, this feature is driven through the new EncryptedXml class. In order to allow this feature to work well with XML digital signatures, there is a special transform included with the framework, that allows the digital signature engine to decrypt the encryption document, and compute the signature over only that portion.

44

Secure Coding

Security Attacks and Vulnerabilities


Buffer Overruns The most common and dangerous security risk ,primarily a C/C++ issue Occurs when data exceeds the expected size and overwrites other values Use managed codeand use /GS compile option in Microsoft Visual C++ .NET with existing C and C++ code Cross-Site Scripting Cross-site scripting allows hackers to execute arbitrary script in a clients Web browser Any Web site that renders dynamic HTML based on content that users submit is susceptible Hackers can steal Web session information and modify what is displayed on the users screen

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

1. During normal execution, when a procedure is called, a return address that marks the location of the calling code is placed on the stack. As a result, when the procedure finishes executing, control returns to the original location. 2. With buffer overruns, there is not a strict limit on the amount of data that can be placed on the buffer. Hackers can overwrite nearly anything on the stack. To make matters worse, the hacker can control the values that are placed on the stack, like the return address. 3. This is very dangerous, because if the return address is overwritten with the address of a malicious procedure, that procedure executes with the same privileges as the original program. Cross-site scripting involves Web applications that dynamically generate HTML pages. If these applications embed user input in the pages they generate, hackers can manipulate them to include content in the pages that allows malicious script to be executed in client browsers. This is not a vendor-specific issue. It affects every Web server and browser currently on the market. There is no single patch to fix it. Scripting tags that can be embedded in this way include <script>, <object>, <applet>, and <embed>. The browser executes the malicious script in the security context of the site from which it believes the script came. The malicious script can perform a variety of actions, such as monitoring the user' Web s session and forwarding data to the hacker. The script can also modify what is displayed on the user' screen, giving them incorrect information. The script can make itself s persistent so that, the next time the user returns to the Web site, the malicious script runs again.

46

SQL Injection
SQL injection occurs when users control the criteria of SQL statements and enter values that alter the original intention of the SQL statement Examples of SQL injection: Bypassing authorization Executing multiple SQL statements Calling built-in stored procedures Example of a susceptible SQL statement :
SELECT * FROM users WHERE & _ userID = '" & inputUserID & " & _ AND password = '" & inputPassword & "'"

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Bypassing authorization

SELECT * from users where username=Administrator-- AND password=

SELECT * from users where username= OR 1=1-- AND password=

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Canonicalization Issues
Avoid making a decision based on a file name if possible There is more than one way to name something
MyLongFile.txt MyLongFile.txt. MyLong~1.txt MyLongFile.txt::$DATA

Alternate representations exists for URLs:


http://www.microsoft.com/technet/security http://www%2emicrosoft%2ecom%2ftechnet%2fsecurity http://www.microsoft.com%c0%aftechnet%c0%afsecurity http://www%25%32%65microsoft.com/technet/security http://172.43.122.12 = http://2888530444

Hackers use directory traversal to change directories Multiple filenames using Parent Paths: C:\Windows\Foo\Secret\cmd.exe is the same as:
C:\Windows\Foo\Secret\Bar\Temp\..\..\cmd.exe C:\Windows\Foo\Secret\Bar\..\cmd.exe C:\Windows\Foo\..\Foo\Secret\Bar\..\cmd.exe ER/CORP/CRS/NE-PRBRIDGE-ED92/003

On the Internet, there are many ways to represent and misrepresent characters that are used in URLs and Web pages. This includes US-ASCII, hexadecimal escapes, legal and illegal UTF-8, double hexadecimal escapes, and dotless IP addresses. zhttp://www%2emicrosoft%2ecom%2ftechnet%2fsecurity This is an example of a hexadecimal escape. %2e is the hexadecimal escape sequence for a period (.), and %2f is the hexadecimal escape sequence for a backslash (/). http://www.microsoft.com%c0%aftechnet%c0%afsecurity UTF-8 can be misrepresented by using varying byte sizes to represent the same character. This is an example of an alternate form of UTF-8. %c0%af is the double-byte UTF-8 representation of a backslash (/). http://www%25%32%65microsoft.com/technet/security This is an example of double escaping the period (.), which is first escaped to %2e and then escaped again as follows: %25 is the hexadecimal escape sequence for the percent sign (%), %32 is the hexadecimal escape sequence for 2, and %65 is the hexadecimal escape sequence for e. http://172.43.122.12 = http://2888530444 This is the alternate IP address for a Web site. This is an example of a dotless IP address. You can calculate a dotless IP address with the following formula: (1st octet X 224) + (2nd octet X 216) + (3rd octet X 28) + (4th octet). References RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax (http://www.ietf.org/rfc/rfc2396.txt) RFC 2279 UTF-8, a transformation format of ISO 10646 (http://www.ietf.org/rfc/rfc2279.txt)

49

Defending against Canonicalization Issues


Dont Make Decisions Based on Names Use a Regular Expression to Restrict Whats Allowed in a Name Stop 8.3 Filename Generation Canonicalize the filename and then make decisions. Get as close as possible to the canonical representation and reject the name incase it does not look valid.

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

You should also consider preventing the file system from generating short filenames. This is not a programmatic optionit s an administrative setting. You can stop Windows from creating 8.3 filenames by adding the following setting to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem registry key: NtfsDisable8dot3NameCreation : REG_DWORD : 1 This option does not remove previously generated 8.3 filenames.

50

Denial of Service Attacks


Denial of service (DoS) attacks are some of the most difficult attacks to protect against Application or operating system failure Applications may contain methods that cause the application to crash or cause faults with the operating system CPU starvation results when applications are forced to repeat intensive calculations or processes Memory starvation results when applications consume excessive amounts of memory Resource starvation results when a application consumes a particular resource, such as threads or database connections Network starvation results when an application floods a network with superfluous data

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

A denial of service (DoS) attack exploits the need to have a service available ie the application should be in a position to respond to requests. Applications may contain methods that cause the application to crash or cause faults with the operating system. CPU starvation results when applications are forced to repeat intensive calculations or processes. Memory starvation results when applications consume excessive amounts of memory Resource starvation results when a application consumes a particular resource, such as threads or database connections. Network starvation results when an application floods a network with superfluous data.

51

Defending against Denial of Service Attacks


Profiling the parts of your application that can really hurt performance Coupling profiling with thorough function-level testing To defend against Network bandwidth attacks, validate the request before sending an error response

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Profiling the parts of your application that can really hurt performance Coupling profiling with thorough function-level testing can reduce your chances of having to deal with a DoS bug Combinations of quotas and intelligently applied timeouts to address the risks against a DoS attack. However, the best strategy would depend on the specific details of the application and users To defend against Network bandwidth attacks, validate the request before sending an error response. If the packet arriving at your service doesn t look like something that you ought to be processing, the best policy is to just drop it and not respond

52

Recap
IIS and ASP.Net Security Implementing Authorization Cryptography XML encryption Secure Coding

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Code Access Security

Code Access Security


The Common Language Runtime (CLR) allows code to perform only those operations that the code has permission to perform. CAS is the CLR' security system that enforces security policies by s preventing unauthorized access to protected resources and operations. Using the Code Access Security, you can do the following: Restrict what code can do Restrict which code can call other code Identify code

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

In the .NET Framework, code access security performs the following functions: Defines permissions and permission sets that represent the right to access various system resources. Enables administrators to configure security policy by associating sets of permissions with groups of code (code groups). Enables code to request the permissions it requires in order to run, as well as the permissions that would be useful to have, and specifies which permissions the code must never have.

55

Code Access Security


Code access security consists of the following elements Permissions - They describe one or more resources and associated rights, and implement methods for demanding and asserting access Permission Set - A permission set is a collection of permissions. A permission set can include any number of permissions. Full Trust, Local Intranet, Internet, Execution and Nothing are some of the built in permission sets in .NET Framework. Code Groups used to assign permissions to assemblies. A code group Consists of two elements:

A membership condition A permission set


Evidence - Is used by the security system to identify assemblies This can come from a variety of sources resident within an assembly like signature, code origin, publisher identity Policy Security policy is the configurable set of rules that the CLR follows when determining the permissions to grant to code.
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Grants permissions to each assembly that is loaded, based on the permissions requested by the code and on the operations permitted by security policy. Enables code to demand that its callers have specific permissions. Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular organization or site to call the protected code. Enforces restrictions on code at run time by comparing the granted permissions of every caller on the call stack to the permissions that callers must have.

56

Stack Walk Behavior


Each assembly has a set of corresponding grants Call Stack Grows Down

Assembly A1 G1 Assembly A2 G2 Assembly A3 G3

P P P
P is compared with grants of all callers on the stack above A4

Method in Assembly A4 demands a permission P

Assembly A4 G4

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

The demand for the permission is satisfied only if all the callers (at the assembly level) in the call stack have the corresponding resource permission.

57

Code Access Security - Permissions


This slide is left blank for notes continued from notes page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Request Requesting permissions is the way you let the runtime know what your code needs to be allowed to do. You request permissions for an assembly by placing attributes (declarative syntax) in the assembly scope of your code. When the assembly is created, the language compiler stores the requested permissions in the assembly manifest. At load time, the runtime examines the permission requests, and applies security policy rules to determine which permissions to grant to the assembly. Requests only influence the runtime to deny permissions to your code and never influence the runtime to give more permissions to your code. The local administration policy always has final control over the maximum permissions your code is granted. Minimum permissions (RequestMinimum) : Permissions your code must have in order to run. Optional permissions (RequestOptional) :Permissions your code can use, but can run effectively without. This request implicitly refuses all other permissions not specifically requested. Refused permissions (RequestRefuse) :Permissions that you want to ensure will never be granted to your code, even if security policy allows them to be granted.

58

Code Access Security - Permissions


This slide is left blank for notes continued from notes page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Demands You can use the security demand call declaratively or imperatively to specify the permissions that direct or indirect callers must have to access your library. Direct callers explicitly call static or instance methods of your library, while indirect callers call static or instance methods of another library that calls your library. When you use a demand, any application that includes your code will only execute if all direct and indirect callers have the permissions that the demand specifies. Demands are particularly useful in situations in which your class library uses protected resources that you do not want to be accessed by untrusted code. Demands can be placed in code using either imperative or declarative syntax. Overrides Normally, a security check examines every caller in the call stack to ensure that each caller has been granted the specified permission. However, you can override the outcome of security checks by calling Assert, Deny, or PermitOnly on an individual permission object or a permission set object. Depending on which of these methods you call, you can cause the security check to succeed or fail, even though the permissions of all callers on the stack might not have been checked. Assert: Assert is a method that can be called on code access permission classes and on the PermissionSet class. You can use Assert to enable your code (and downstream callers) to perform actions that your code has permission to do, but its callers might not have permission to do. A security assertion changes the normal process that the runtime performs during a security check. When you assert a permission, it tells the security system not to check the callers of your code for the asserted permission .

59

Code Access Security - Permissions


This slide is left blank for notes continued from notes page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Deny Calling Deny prevents access to the resource specified by the denied permission. If your code calls Deny and a downstream caller subsequently demands the denied permission, the security check will fail, even if all callers have permission to access that resource. The permission being demanded and the permission being denied do not have to match exactly for the Deny to take effect, and the demanded permission does not have to be a subset of the denied permission. Permit only Calling PermitOnly has essentially the same effect as calling Deny, but is a different way of specifying the conditions under which the security check should fail. Instead of saying that a specified resource cannot be accessed, as Deny does, PermitOnly says that only the resources you specify can be accessed. Therefore, calling PermitOnly on permission X is the same as calling Deny on all permissions except permission X. If you call PermitOnly, your code can be used to access only the resources protected by the permissions that you specify when you call PermitOnly. You use PermitOnly instead of Deny when it is more convenient to describe resources that can be accessed instead of resources that cannot be accessed.

60

Code Access Security Call syntax


Declarative Syntax Declarative demands place information into code' metadata using s attributes Attributes can be placed at the assembly, class, or member level, to indicate the type of request, demand, or override you want to use
[CustomPermissionAttribute(SecurityAction.Demand, Unrestricted = true)] public static string ReadData() { //Read from a custom resource. }

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Declarative security syntax uses attributes to place security information into the metadata of your code. Attributes can be placed at the assembly, class, or member level, to indicate the type of request, demand, or override you want to use. Requests are used in applications that target the common language runtime to inform the runtime security system about the permissions that your application needs or does not want. Demands and overrides are used in libraries to protect resources from callers or override default security behavior. In order to use declarative security calls, you must initialize the state data of the permission object so that it represents the particular form of permission you need. Every built-in permission has an attribute that is passed a SecurityAction enumeration to describe the type of security operation you want to perform.

61

Code Access Security Call syntax


Imperative Syntax A permission object is instantiated and a security call is involved Useful when considerations for permitting depend on run-time parameters
FileIOPermission filePermission = new FileIOPermission (FileIOPermissionAccess.AllAccess, @"C:\helloworld.txt"); try { filePermission.Demand(); MessageBox.Show ("Permission demand successful"); } catch( SecurityException securityEx ) { MessageBox.Show( securityEx.Message, "Security Exception" ); }
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

62

Code Access Security Enhancements in .NET 2.0


Full Trust GAC Security Transparency ClickOnce Deployment TrustManager ApplicationSecurityManager

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Full Trust GAC Grants assemblies in the GAC full trust regardless of how the security policy is configured for them. However the assembly level declarative security will still work as expected. If assembly decides to RequestRefuse or RequestOptional even when it is present in the GAC the grant set will not be full trust. But to state the obvious any assembly placed in the GAC will start with full trust irrespective of the policy set. This update obviously requires the users to be much more careful about importing an untrusted assembly in GAC. Security TransparencyTransparent code is code that voluntarily gives up its ability to elevate the permissions of the call stack. Due to these restrictions, transparent code has the effect of running with either the set of permissions it was granted or the set of permissions its callers were granted, whichever is smaller. Because of that, fully trusted transparent code essentially runs in the same security context of its callers, since the caller' s permissions are necessarily less than or equal to full trust. This is particularly useful if you want to let your assembly be used by partially trusted callers. ClickOnce DeploymentClickOnce provides a trustworthy deployment model for users to be able to download and execute applications from centrally managed servers without requiring administrator privileges on the client machine. Applications deployed using ClickOnce are ensured not to interfere with any other application or corrupt any data on the system. Furthermore, ClickOnce applications are run in secure execution context whose permissions are limited based on where the application is coming from or the trust assigned to the originator of that application. It is possible to override the location-based policy with custom security policy on the system that depends on the content-based evidence. TrustManagerThis is the default UI within System.Windows.Forms.dll that allows end-users to make ClickOnce trust decisions about allowing code that requires higher privileges than what the current policy and zone allow to be installed on the local machine. Trust Managers can be locked down and configured to allow only applications in certain zones to elevate privileges. Additionally, it is possible to configure only trusted applications to be allowed to elevate privileges. Another option is to deploy a trust license from a trusted license authority that will allow elevated privilege action without prompting the user. ApplicationSecurityManagerHelps determine and cache trust decisions during the ClickOnce process and can also be used to point to a custom trust manager if used. The applications trust decisions are cached in an XML file that can be accessed using the ApplicationSecurityManager class. This makes it possible to enumerate the application trust of other applications and add and remove security application trust. GacMembershipConditionA new evidence based membership condition has been added to the Framework. The GacMembershipCondition is satisfied by all assemblies that are installed into the GAC. These assemblies have explicit full trust permissions and are no longer tied to the local machine policy

63

Windows CardSpace

WCS - Windows CardSpace


Is a piece of client software that enables users to provide their digital identity to online services Enables users to provide their digital identity to online services in a simple, secure and trusted way Available for Windows Vista, Windows XP, and Windows Server 2003 Different roles in the digital identity system User Identity Provider Relying Party A digital identity is represented by an InfoCard that the user can present to a relying party
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

digital identities come in all shapes and sizes. An e-mail account with Yahoo - identified by an e-mail address. Accounts in Various commercial organizations, such as Amazon or eBay identified by a username At work - identified by your network login. Every digital identity is associated with some information. When transmitted on the network, every digital identity is represented by some kind of security token common security token formats username, X.509 certificates, and Kerberos tickets Infocard contains information like what identity provider to contact to acquire a security token for this identity, what kind of tokens this identity provider can issue, and exactly what claims these tokens can contain. 1. 2. User Also known as the subject, the user is the entity that is associated with a digital identity. Users are often people, but organizations, applications, machines, and other things can also have digital identities. Identity provider An identity provider is just what the name suggests: something that provides a digital identity for a user. For the digital identity assigned to you by your employer, for example, the identity provider is typically a system such as Active Directory. For the digital identity you use with Amazon, the identity provider is effectively you, since you define your own username and password. Digital identities created by different identity providers can carry different information and provide different levels of assurance that the user really is who he claims to be. Relying party A relying party is an application that in some way relies on a digital identity. A relying party will frequently use an identity (that is, the information contained in the claims that make up this identity' security token) to authenticate a user, and then s make an authorization decision, such as allowing this user to access some information. A relying party might also use the identity to get a credit card number, to verify that the same user is accessing it at different times, or for other purposes. Typical examples of relying parties include Internet websites such as online bookstore and auction sites, and any application that accepts requests through Web services.

3.

65

WCS - Windows CardSpace


CardSpace allows replacing password-based Web login with a stronger mechanism The CardSpace UI enables users to create Personal cards and associate a limited set of identity data When the user chooses a card, a request in the form of a web service call goes to the relevant provider, and a signed and encrypted security token is returned The user, in control of the flow of information at all times, then decides whether to release this information to the requesting online service If the user approves then the token is sent on to this relying party where the token is processed and the user is authenticated.

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Replacing password-based Web login Password-based schemes where user chooses username & password for access to sites, may use SSL for encrypted communication but still are vulnerable to a kind of attack called phishing. By sending deceptive e-mail messages, attackers attempt to trick users into logging in to spurious copies of real sites, revealing their passwords and perhaps other personal information. If passwords weren'the t dominant authentication mechanism on the Web, however, this kind of phishing would be less of a threat there would be no passwords to steal. CardSpace allows replacing password-based Web login with a stronger mechanism. Rather than authenticating users with passwords, a relying party such as a website might instead authenticate users with security tokens. Where users choose their own usernames and passwords, CardSpace includes a self-issued identity provider. As Figure 5 shows, this self-issued identity provider runs on the local Windows system, and it can produce information cards just like any other identity provider. Information cards created by the self-issued identity provider can contain only basic information, such as the user' name, postal s address, e-mail address, and phone number. When a user chooses to submit one of these cards to a relying party, the self-issued identity provider on that user' system generates a Security Assertion Markup Language (SAML) token containing the information s the user has placed in this card. The self-issued identity provider also generates a public/private key pair, signing the security token with the private key. To prevent an attacker from reusing it, this token contains a timestamp and other information as well, making it useless to anyone except its original user. The application then sends this signed token, together with its associated public key, to the relying party. The relying party can use the public key to validate the security token' digital signature, thus ensuring that the token is s being presented by its rightful owner. To make it impossible for relying parties to get together and track a user' activities by s comparing that user' public key, the self-issued identity provider creates a different key pair for every relying party that' accessed s s with this card (although this detail is hidden from the user, who sees only a single information card for this identity).

66

T h e W in d o w I n f o r m a t io n G o t o C

s C a r d c a r d s . P

S p a c e a n d

o n t r o l

a n e l W

a p p l e t s C

a l l o w a r d S

a n a g i n g c o n t r o l b e e n p a n e l a p p l e t o r

o n t r o l

a n e l

l a u n c h

t h e

i n d o w

p a c e

L a u n c h i n g I m p o r t e d ,

t h e a p p l e t f o r t h e f i r s t t im e , w h e n n o c a r d s h a v e b r in g s u p t h e S e l e c t a c a r d t o p r e v i e w d i a l o g .

c r e a t e d

WCS contd.

C a r d S p a c e w in d o w s a r e r u n n i n g o n a s e p a r a te , C a r d S p a c e w i n d o w s a p p e a r s f r o z e n a n d g r a y e d p r o c e s s e s i n c lu d i n g T a s k M a n a g e r u n t i l y o u

s e c u r e d e s k t o p . T h e d e s k t o p b e h i n d o u t a n d y o u c a n n o t a c c e s s o t h e r e x i t f r o m t h e C a r d S p a c e U I .

I f c li c k o n A d d a c a r d , y o u c a n c r e a t e p e r s o n a l c a r d s o r i n s t a l l m a n a g e d c a r d s . A d d a p e r s o n a l c a r d , w i t h y o u r f i r s t n a m e , l a s t n a m e , a n d a n e m a i l a d d r e s s ( d o e s n t h a v e t o b e r e a l ) . C h o o s e a u n i q u e p i c t u r e f o r t h e c a r d , s o y o u w il l b e a b l e t o i d e n t i f y i t l a t e r . . W h e n y o u h a v e f i n is h e d e x p e r im e n ti n g w i th t h e U I , s a v e th e c a r d .

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

How any digital identity system can be supported First, the application gets the security token requirements of the relying party that the user wishes to access. This information is contained in the relying partys policy, and it includes things such as what security token formats the relying party will accept, and exactly what claims those tokens must contain. Once it has the details of the security token this relying party requires, the application passes this information to CardSpace, asking it to request a token from an appropriate identity provider. Once this security token has been received, CardSpace gives it to the application, which passes it on to the relying party. The relying party can then use this token to authenticate the user or for some other purpose.

67

Summary
IIS and ASP.Net Security Authentication Implementing Authorization Cryptography XML encryption Secure Coding Code Access Security Windows CardSpace

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Thank You!
ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Appendix

Basics of Security

Securing a system various aspects of security

Security is one of the primary concerns for both developers and application architects As there are lots of different types of website, Applications with varying security needs,
the developers need to know how the security works Infrastructure Security Application Security

SYSTEM

Database Security

Security Policies

In this course we would primarily be discussing Application Security


ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Infrastructure Security : Security features of the OS Network Security Firewall Physical Data Center Gaining maximum benefit from built-in Windows 2000 security features and tools Application Security : Code Level Security Encryption Digital Certificates Digital Signing Security policies : Mapping out effective domain security policies Database Security: Securing the access to the database

72

Application Security
Key aspects for Application Security: Authentication IIS Authentication ASP.Net Authentication Authorization Secure communication Cryptography Before we get into these, lets understand the various threats that an application faces.

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Authentication Positively identifying the clients of your application; clients might include end-users, services, processes or computers. Authorization Defining what authenticated clients are allowed to see and do within the application. Secure Communication Ensuring that messages remain private and unaltered as they cross networks. Encryption The process of coding plaintext to create ciphertext is called encryption and the process of decoding ciphertext to produce the plaintext is called decryption. Principle of least privilege The principle of least privilege has been described as important for meeting integrity objectives. The principle of least privilege requires that a user be given no more privilege than necessary to perform a job. Ensuring least privilege requires identifying what the users job is, determining the minimum set of privileges required to perform that job, and restricting the user to a domain with those privileges and nothing more.

73

Security (Contd.)
This slide is left blank for notes continued from notes page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Impersonation This is the technique used by a server application to access resources on behalf of a client. The clients security context is used for access checks performed by the server. Delegation An extended form of impersonation that allows a server process that is performing work on behalf of a client, to access resources on a remote computer. Natively provided by Kerberos on Microsoft Windows 2000 and later operating systems. Conventional impersonation (for example, that provided by NTLM) allows only a single network hop. When NTLM impersonation is used, the one hop is used between the client and server computers, restricting the server to local resource access while impersonating. NTLM Abbreviation for Windows NT LAN Manager . The NTLM protocol was the default for network authentication in the Windows NT 4.0 operating system. NTLM uses a challenge-response mechanism for authentication, in which clients are able to prove their identities without sending a password to the server. It consists of three messages, commonly referred to as Type 1 (negotiation), Type 2 (challenge) and Type 3 (authentication). The protocol continues to be supported in Windows 2000 but has been replaced by Microsoft Kerberos as the default/standard Kerberos An authentication system developed at the Massachusetts Institute of Technology (MIT). Kerberos is designed to enable two parties to exchange private information across an otherwise open network. It works by assigning a unique key, called a ticket, to each user that logs on to the network. The ticket is then embedded in messages to identify the sender of the message. For more details- http://www.microsoft.com/windows2000/docs/kerberos.doc

74

Threats to an application
STRIDE - Taxonomy used at Microsoft to analyze threats to an application Spoofing Tampering Repudiation Information disclosure Denial of Service Elevation of privilege

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

STRIDE Threats faced by the application can be categorized based on the goals and purposes of the attacks. A working knowledge of these categories of threats can help you organize a security strategy so that you have planned responses to threats. STRIDE is the acronym used at Microsoft to categorize different threat types. STRIDE stands for: Spoofing. Spoofing is attempting to gain access to a system by using a false identity. This can be accomplished using stolen user credentials or a false IP address. After the attacker successfully gains access as a legitimate user or host, elevation of privileges or abuse using authorization can begin. Tampering. Tampering is the unauthorized modification of data, for example as it flows over a network between two computers. Repudiation. Repudiation is the ability of users (legitimate or otherwise) to deny that they performed specific actions or transactions. Without adequate auditing, repudiation attacks are difficult to prove.

75

Threats to an application
This slide is left blank for notes continued from notes page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Information disclosure. Information disclosure is the unwanted exposure of private data. For example, a user views the contents of a table or file he or she is not authorized to open, or monitors data passed in plaintext over a network. Some examples of information disclosure vulnerabilities include the use of hidden form fields, comments embedded in Web pages that contain database connection strings and connection details, and weak exception handling that can lead to internal system level details being revealed to the client. Any of this information can be very useful to the attacker. Denial of service. Denial of service is the process of making a system or application unavailable. For example, a denial of service attack might be accomplished by bombarding a server with requests to consume all available system resources or by passing it malformed input data that can crash an application process. Elevation of privilege. Elevation of privilege occurs when a user with limited privileges assumes the identity of a privileged user to gain privileged access to an application. For example, an attacker with limited privileges might elevate his or her privilege level to compromise and take control of a highly privileged and trusted process or account.

76

Threats and Countermeasures


Spoofing user identity Tampering with data Repudiation Information disclosure Denial of service Elevation of privilege

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Spoofing user identity Authentication. Encryption. SSL Tampering with data Hashing and Signing. Authorization. SSL. Repudiation Secure logging Digital signatures. Information disclosure Authorization. Encryption. SSL Denial of service Resource Throttling Bandwidth Throttling. Packet Filtering. Elevation of privilege Principle of least privilege Threat Countermeasures Spoofing user identity Use strong authentication. Do not store secrets (for example, passwords) in plaintext. Do not pass credentials in plaintext over the wire. Protect authentication cookies with Secure Sockets Layer (SSL). Tampering with data Use data hashing and signing. Use digital signatures. Use strong authorization. Use tamper-resistant protocols across communication links. Secure communication links with protocols that provide message integrity. Repudiation Create secure audit trails. Use digital signatures. Information disclosure Use strong authorization. Use strong encryption. Secure communication links with protocols that provide message confidentiality.

77

Threats and Countermeasures


This slide is left blank for notes continued from notes page

ER/CORP/CRS/NE-PRBRIDGE-ED92/003

Threat Countermeasures Spoofing user identity Use strong authentication. Do not store secrets (for example, passwords) in plaintext. Do not pass credentials in plaintext over the wire. Protect authentication cookies with Secure Sockets Layer (SSL). Tampering with data Use data hashing and signing. Use digital signatures. Use strong authorization. Use tamper-resistant protocols across communication links. Secure communication links with protocols that provide message integrity. Repudiation Create secure audit trails. Use digital signatures. Information disclosure Use strong authorization. Use strong encryption. Secure communication links with protocols that provide message confidentiality. Do not store secrets (for example, passwords) in plaintext. Denial of service Use resource and bandwidth throttling techniques. Validate and filter input. Elevation of privilege Follow the principle of least privilege and use least privileged service accounts to run processes and access resources.

78

You might also like