|
Chapter 8: ASP.NET Security
8 ASP.NET SecurityThis chapter presents guidance and recommendations that will help you build secure ASP.NET Web applications. Much of the guidance and many of the recommendations presented in this chapter also apply to the development of ASP.NET Web services and .NET Remoting objects hosted by ASP.NET.
ASP.NET Security ArchitectureASP.NET works in conjunction with IIS, the .NET Framework, and the underlying security services provided by the operating system, to provide a range of authentication and authorization mechanisms. These are summarized in Figure 8.1 on the next page.Figure 8.1 illustrates the authentication and authorization mechanisms provided by IIS and ASP.NET. When a client issues a Web request, the following sequence of authentication and authorization events occurs:
Figure 8.1 ASP.NET security services
If ASP.NET is configured for Windows authentication, no additional authentication occurs at this point. ASP.NET will accept any token it receives from IIS. If ASP.NET is configured for Forms authentication, the credentials supplied by the caller (using an HTML form) are authenticated against a data store; typically a Microsoft® SQL Server database or Active Directory® directory service. If ASP.NET is configured for Passport authentication, the user is redirected to a Passport site and the Passport authentication service authenticates the user.
The UrlAuthorizationModule (a system provided HTTP module) uses authorization rules configured in Web.config (specifically, the <authorization> element) to ensure that the caller can access the requested file or folder. With Windows authentication, the FileAuthorizationModule (another HTTP module) checks that the caller has the necessary permission to access the requested resource. The caller's access token is compared against the ACL that protects the resource. .NET roles can also be used either declaratively or programmatically to ensure that the caller is authorized to access the requested resource or perform the requested operation.
GatekeepersThe authorization points or gatekeepers within an ASP.NET Web application are provided by IIS and ASP.NET:IIS With anonymous authentication turned off, IIS permits requests only from users that it can authenticate either in its domain or in a trusted domain. For static file types (for example .jpg, .gif and .htm files files that are not mapped to an ISAPI extension), IIS uses the NTFS permissions associated with the requested file to perform access control. ASP.NET The ASP.NET gatekeepers include the UrlAuthorizationModule, FileAuthorizationModule and principal permission demands and role checks. UrlAuthorizationModule You can configure <authorization> elements within your application's Web.config file to control which users and groups of users should have access to the application. Authorization is based on the IPrincipal object stored in HttpContext.User. FileAuthorizationModule For file types mapped by IIS to the ASP.NET ISAPI extension (Aspnet_isapi.dll), automatic access checks are performed using the authenticated user's Windows access token (which may be IUSR_MACHINE) against the ACL attached to the requested ASP.NET file.
The FileAuthorizationModule class only performs access checks against the requested file, and not for files accessed by the code in the requested page, although these are access checked by IIS. For example, if you request Default.aspx and it contains an embedded user control (Usercontrol.ascx), which in turn includes an image tag (pointing to Image.gif), the FileAuthorizationModule performs an access check for Default.aspx and Usercontrol.ascx, because these file types are mapped by IIS to the ASP.NET ISAPI extension. The FileAuthorizationModule does not perform a check for Image.gif, because this is a static file handled internally by IIS. However, as access checks for static files are performed by IIS, the authenticated user must still be granted read permission to the file with an appropriately configured ACL. This scenario is shown in Figure 8.2.
Figure 8.2 IIS and ASP.NET gatekeepers working together In this scenario you can prevent access at the file gate. If you configure the ACL attached to Default.aspx and deny access to a particular user, the user control or any embedded images will not get a chance to be sent to the client by the code in Default.aspx. If the user requests the images directly, IIS performs the access checks itself. Principal Permission Demands and Explicit Role Checks In addition to the IIS and ASP.NET configurable gatekeepers, you can also use principal permission demands (declaratively or programmatically) as an additional fine-grained access control mechanism. Principal permission checks (performed by the PrincipalPermissionAttribute class) allow you to control access to classes, methods, or individual code blocks based on the identity and group membership of individual users, as defined by the IPrincipal object attached to the current thread.
With Windows authentication, ASP.NET automatically attaches a WindowsPrincipal object that represents the authenticated user to the current Web request (using HttpContext.User). Forms and Passport authentication create a GenericPrincipal object with the appropriate identity and no roles and attaches it to the HttpContext.User. More Information
Authentication and Authorization StrategiesASP.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 con.figured to provide varying degrees of granularity; for example, per-user or per-user group (role-based).This section shows you which authorization options (both configurable and programmatic) are available for a set of commonly used authentication options. The authentication options that follow are summarized here:
Available Authorization OptionsThe following table shows you the set of available authorization options. For each one the table indicates whether or not Windows authentication and/or impersonation are required. If Windows authentication is not required, the particular authorization option is available for all other authentication types. Use the table to help refine your authentication/authorization strategy.Table 8.1: Windows authentication and impersonation requirements
Windows Authentication with ImpersonationThe following configuration elements show you how to enable Windows (IIS) authentication and impersonation declaratively in Web.config or Machine.config.
<authentication mode="Windows" /> With this configuration, your ASP.NET application code impersonates the IIS-authenticated caller. Configurable Security When you use Windows authentication together with impersonation, the following authorization options are available to you:
For static files types (not mapped to an ISAPI extension), IIS performs access checks using the caller's access token and ACL attached to the file.
<authorization>
Programmatic Security Programmatic security refers to security checks located within your Web application code. The following programmatic security options are available when you use Windows authentication and impersonation:
PrincipalPermission permCheck = new PrincipalPermission(
[PrincipalPermission(SecurityAction.Demand,
IPrincipal.IsInRole(@"DomainName\WindowsGroup");
ContextUtil.IsCallerInRole("Manager")
When to Use Use Windows authentication and impersonation when:
Before using impersonation within your application, make sure you understand the relative trade-offs of this approach in comparison to using the trusted subsystem model. These were elaborated upon in "Choosing a Resource Access Model" in Chapter 3, "Authentication and Authorization Design." The disadvantages of impersonation include:
More Information
Windows Authentication without ImpersonationThe following configuration elements show how you enable Windows (IIS) authentication with no impersonation declaratively in Web.config.
<authentication mode="Windows" /> Configurable Security When you use Windows authentication without impersonation, the following authorization options are available to you:
For static files types (not mapped to an ISAPI extension) IIS performs access checks using the caller's access token and ACL attached to the file.
<authorization>
Programmatic Security The following programmatic security options are available:
PrincipalPermission permCheck = new PrincipalPermission(
[PrincipalPermission(SecurityAction.Demand,
IPrincipal.IsInRole(@"DomainName\WindowsGroup");
When to Use Use Windows authentication without impersonation when:
More Information
Windows Authentication Using a Fixed IdentityThe <identity> element in Web.config supports optional user name and password attributes, which allows you to configure a specific fixed identity for your application to impersonate. This is shown in the following configuration file fragment.
<identity impersonate="true" This example shows the <identity> element where the credentials are encrypted in the registry using the aspnet_setreg.exe utility. The clear text userName and password attribute values have been replaced with pointers to the secured registry key and named values that contain the encrypted credentials. For details about this utility and to download it, see article Q329290, "HOWTO: Use the ASP.NET Utility to Encrypt Credentials and Session State Connection Strings" in the Microsoft Knowledge Base. When to Use Using a fixed impersonated identity is not recommended when using the .NET Framework 1.0 on Windows 2000 servers. This is because you would need to give the ASP.NET process account the powerful "Act as part of the operating system" privilege. This privilege is required by the ASP.NET process because it performs a LogonUser call using the credentials that you have provided.
Forms AuthenticationThe following configuration elements show how you enable Forms authentication declaratively in Web.config.
<authentication mode="Forms"> Configurable Security When you use Forms authentication, the following authorization options are available to you:
ASP.NET File authorization is not available because it requires Windows authentication.
Configure URL Authorization in Web.config. With Forms authentication, the format of user names is determined by your custom data store; a SQL Server database, or Active Directory.
<authorization>
<authorization>
Programmatic Security The following programmatic security options are available:
PrincipalPermission permCheck = new PrincipalPermission(
[PrincipalPermission(SecurityAction.Demand,
IPrincipal.IsInRole("Manager");
When to Use Forms authentication is most ideally suited to Internet applications. Use Forms authentication when:
More Information
Passport AuthenticationThe following configuration elements show how you enable Passport authentication declaratively in Web.config.
<authentication mode="Passport" /> When to Use Passport authentication is used on the Internet when application users do not have Windows accounts and you want to implement a single-sign-on solution. Users who have previously logged on with a Passport account at a participating Passport site will not have to log on to your site configured with Passport authentication.
Configuring SecurityThis section shows you the practical steps required to configure security for an ASP.NET Web application. These are summarized in Figure 8.3 on the next page.Figure 8.3 Configuring ASP.NET application security
Configure IIS SettingsTo configure IIS security, you must perform the following steps:
For more information, see "How To: Set Up SSL on a Web Server" in the Reference section of this book.
For more information about client certificate mapping, see article Q313070, "How to Configure Client Certificate Mappings in Internet Information Services (IIS) 5.0" in the Microsoft Knowledge Base.
Configure ASP.NET SettingsApplication level configuration settings are maintained in Web.config files, which are located in your application's virtual root directory and optionally within additional subfolders (these settings can sometimes override the parent folder settings).
<authentication mode="Windows|Forms|Passport|None" />
To configure ASP.NET impersonation use the following <identity> element in your application's Web.config.
<identity impersonate="true" />
<authorization>
URL Authorization Notes Take note of the following when you configure URL authorization:
You can use the <location> tag to apply authorization settings to an individual file or directory. The following example shows how you can apply authorization to a specific file (Page.aspx).
<location path="page.aspx" />
User names take the form "DomainName\WindowsUserName" Role names take the form "DomainName\WindowsGroupName"
However, if you use custom authentication, you should create an IPrincipal object with roles and store it into the HttpContext.User. When you subsequently perform URL authorization, it is performed against the user and roles (no matter how they were retrieved) maintained in the IPrincipal object.
URL Authorization Examples The following list shows the syntax for some typical URL authorization examples:
<deny users="?" />
<deny users="*"/>
<deny roles="Manager"/>
<configuration>
Secure Resources
If you are not impersonating, any resource your application is required to access must have an ACL that grants at least read access to the ASP.NET process account. If you are impersonating, files and registry keys must have an ACL that grants at least read access to the authenticated user (or the anonymous Internet user account, if anonymous authentication is in effect).
System: Full Control Administrators: Full Control Process Identity or Impersonated Identity : Read If you are not impersonating the anonymous Internet user account (IUSR_MACHINE), you should deny access to this account.
Locking Configuration Settings Configuration settings are hierarchical. Web.config file settings in subdirectories override Web.config settings in parent directories. Also, Web.config settings override Machine.config settings. You can lock configuration settings to prevent them being overridden at lower levels, by using the <location> element coupled with the allowOverride attribute. For example:
<location path="somepath" allowOverride="false" /> Note that the path may refer to a Web site or virtual directory and it applies to the nominated directory and all subdirectories. If you set allowOverride to false, you prevent any lower level configuration file from overriding the settings specified in the <location> element. The ability to lock down configuration settings applies to all types of setting and not just security settings such as authentication modes. In the context of machine.config, the path must be fully qualified and include the Web site, virtual directory name and optionally a sub directory and filename. For example:
<location path="Web Site Name/VDirName/SubDirName/PageName.aspx" > In the context of web.config, the path is relative from the application's virtual directory. For example:
<location path="SubDirName/PageName.aspx" > Preventing Files from Being Downloaded You can use the HttpForbiddenHandler class to prevent certain file types from being downloaded over the Web. This class is used internally by ASP.NET to prevent the download of certain system level files (for example, configuration files including web.config). For a complete list of file types restricted in this way, see the <httpHandlers> section in machine.config. You should consider using the HttpForbiddenHandler for files that your application uses internally, but are not intended for download.
To use the HttpForbiddenHandler to prevent a particular file type from being downloaded
An example for the .abc file type is shown below.
<httpHandlers>
Secure CommunicationUse a combination of SSL and Internet Protocol Security (IPSec) to secure communication links.More information
Programming SecurityAfter you establish your Web application's configurable security settings, you need to further enhance and fine-tune your application's authorization policy programmatically. This includes using declarative .NET attributes within your assemblies and performing imperative authorizing checks within code.This section highlights the key programming steps required to perform authorization within an ASP.NET Web application.
An Authorization PatternThe following summarizes the basic pattern for authorizing users within your Web application:
Retrieve Credentials You must start by retrieving a set of credentials (user name and password) from the user. If your application does not use Windows authentication, you need to ensure that clear text credentials are properly secured on the network by using SSL. Validate Credentials If you have configured Windows authentication, credentials are validated automatically using the underlying services of the operating system. If you use an alternate authentication mechanism, you must write code to validate credentials against a data store such as a SQL Server database or Active Directory. For more information about how to securely store user credentials in a SQL Server database, see "Authenticating Users Against a Database" within Chapter 12, "Data Access Security." Put Users in Roles Your user data store should also contain a list of roles for each user. You must write code to retrieve the role list for the validated user. Create an IPrincipal Object Authorization occurs against the authenticated user, whose identity and role list is maintained within an IPrincipal object (which flows in the context of the current Web request). If you have configured Windows authentication, ASP.NET automatically constructs a WindowsPrincipal object. This contains the authenticated user's identity together with a role list, which equates to the list of Windows groups to which the user belongs. If you are using Forms, Passport, or custom authentication, you must write code within the Application_AuthenticateRequest event handler in Global.asax to create an IPrincipal object. The GenericPrincipal class is provided by the .NET Framework, and should be used in most scenarios. Put the IPrincipal Object into the Current HTTP Context Attach the IPrincipal object to the current HTTP context (using the HttpContext.User variable). ASP.NET does this automatically when you use Windows authentication. Otherwise, you must attach the object manually. Authorize Based on the User Identity and/or Role Membership Use .NET roles either declaratively (to obtain class or method level authorization), or imperatively within code if your application requires more fine-grained authorization logic. You can use declarative or imperative principal permission demands (using the PrincipalPermission class), or you can perform explicit role checks by calling the IPrincipal.IsInRole() method. The following example assumes Windows authentication and shows a declarative principal permission demand. The method that follows the attribute will only be executed if the authenticated user is a member of the Manager Windows group. If the caller is not a member of this group, a SecurityException is thrown.
[PrincipalPermission(SecurityAction.Demand, The following example shows an explicit role check within code. This example assumes Windows authentication. If a non-Windows authentication mechanism is used, the code remains very similar. Instead of casting the User object to a WindowsPrincipal object, it should be cast to a GenericPrincipal object.
// Extract the authenticated user from the current HTTP context. More Information For a practical implementation of the above pattern for Forms authentication, see the "Forms Authentication" section later in this chapter.
Creating a Custom IPrincipal classThe GenericPrincipal class provided by the .NET Framework should be used in most circumstances when you are using a non-Windows authentication mechanism. This provides role checks using the IPrincipal.IsInRole method.On occasion, you may need to implement your own IPrincipal class. Reasons for implementing your own IPrincipal class include:
CustomPrincipal.IsInAllRoles( "Role", "Role2", "Role3" )
string[] roles = CustomPrincipal.Roles;
CustomPrincipal.IsInHigherRole("Manager");
CustomIdentity id = CustomPrincipal.Identity;
More Information For more information about creating your own IPrincipal class, see "How To: Implement IPrincipal" in the Reference section of this book.
Windows AuthenticationUse Windows authentication when the users of your application have Windows accounts that can be authenticated by the server (for example, in intranet scenarios).If you configure ASP.NET for Windows authentication, IIS performs user authentication by using the configured IIS authentication mechanism. This is shown in Figure 8.4. Figure 8.4 ASP.NET Windows authentication uses IIS to authenticate callers The access token of the authenticated caller (which may be the Anonymous Internet user account if IIS is configured for Anonymous authentication) is made available to the ASP.NET application. Note the following:
Identifying the Authenticated User ASP.NET associates a WindowsPrincipal object with the current Web request. This contains the identity of the authenticated Windows user together with a list of roles that the user belongs to. With Windows authentication, the role list consists of the set of Windows groups to which the user belongs. The following code shows how to obtain the identity of the authenticated Windows user and to perform a simple role test for authorization.
WindowsPrincipal user = User as WindowsPrincipal;
Forms AuthenticationWhen you are using Forms authentication, the sequence of events triggered by an unauthenticated user who attempts to access a secured file or resource (where URL authorization denies the user access), is shown in Figure 8.5.Figure 8.5 Forms authentication sequence of events The following describes the sequence of events shown in Figure 8.5:
IIS allows the request because Anonymous access is enabled. ASP.NET checks the <authorization> elements and finds a <deny users=?" /> element.
ASP.NET checks the <authorization> elements and finds a <deny users=?" /> element. However, this time the user is authenticated. ASP.NET checks the <authorization> elements to ensure the user is in the <allow> element. The user is granted access to Default.aspx.
Development Steps for Forms AuthenticationThe following list highlights the key steps that you must perform to implement Forms authentication:
Configure IIS for Anonymous Access Your application's virtual directory must be configured in IIS for anonymous access. To configure IIS for anonymous access
Configure ASP.NET for Forms Authentication A sample configuration is shown below.
<authentication mode="Forms"> Create a Logon Web Form and Validate the Supplied Credentials Validate credentials against a SQL Server database, or Active Directory. More Information
Retrieve a Role List from the Custom Data Store Obtain roles from a table within a SQL Server database, or groups/distribution lists configured within Active Directory. Refer to the preceding resources for details. Create a Forms Authentication Ticket Store the retrieved roles in the ticket. This is illustrated in the following code.
// This event handler executes when the user clicks the Logon button Create an IPrincipal Object Create the IPrincipal object in the Application_AuthenticationRequest event handler in Global.asax. Use the GenericPrincipal class, unless you need extended role-based functionality. In this case create a custom class that implements IPrincipal. Put the IPrincipal Object into the Current HTTP Context The creation of a GenericPrincipal object is shown below.
protected void Application_AuthenticateRequest(Object sender, EventArgs e) Authorize the User Based on User Name or Role Membership Use declarative principal permission demands to restrict access to methods. Use imperative principal permission demands and/or explicit role checks (IPrincipal.IsInRole) to perform fine-grained authorization within methods.
Forms Implementation Guidelines
In addition to using SSL for the login page, you should also use SSL for other pages, whenever the credentials or the authentication cookie is sent across the network. This is to mitigate the threat associated with cookie replay attacks.
More Information
Hosting Multiple Applications Using Forms AuthenticationIf you are hosting multiple Web applications that use Forms authentication on the same Web server, it is possible for a user who is authenticated in one application to make a request to another application without being redirected to that application's logon page. The URL authorization rules within the second application may deny access to the user, without providing the opportunity to supply logon credentials using the logon form.This only happens if the name and path attributes on the <forms> element are the same across multiple applications and each application uses a common <machineKey> element in Web.config. More Information For more information about this issue, and for resolution techniques, see the following Knowledge Base articles:
Cookieless Forms AuthenticationIf you need a cookieless Forms authentication solution, consider using the approach used by the Microsoft Mobile Internet Toolkit. Mobile Forms Authentication builds upon Forms Authentication but uses the query string to convey the authentication ticket instead of a cookie.More Information For more information about Mobile Forms Authentication, see article Q311568, "INFO: How To Use Mobile Forms Authentication with Microsoft Mobile Internet Toolkit," in the Microsoft Knowledge Base.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||