Day3.6 - ODU Computer Science

advertisement
ASP.Net Application Security
Chapter 18 (Freeman and Jones)
CS795/895
ASP.Net Configuration Files
•
•
•
ASP.NET configuration data is stored in XML text files, each named Web.config.
These include important security settings, such as the user authentication
mechanism to use and the code-access security policy to apply to an ASP.net
application.
Web.config files can appear in multiple directories in ASP.NET applications.
It implements a hierarchically configured file structure.
–
–
–
–
The main source of configuration is the machine.config file
Each folder in an ASP.net application’s virtual path can contain a configuration file named web.config. It
provides configuration settings for the application resources located in the folder.
Child folders inherit the configuration of their parent folder.
The web.config in a child folder overrides those configured higher up in the folder hierarchy.
ASP.Net Configuration Files (cont.)
•
•
ASP.Net security-related configuration elements
<location>: Specifies the resource that specified configuration settings
apply to.
<configuration>
<location path="Logon.aspx">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
<configuration>
<location path="UploadPage.aspx">
<httpRuntime maxRequestLength="128"/> /*Max size can be 128K for uploading */
</location>
</configuration>
<configuration>
<location allowOverride="false"/> /* child directory web.config settings cannot override this*/
</configuration>
ASP.Net Configuration Files (cont.)
•
•
<machinekey>: Configures keys to use for encryption and decryption of forms authentication
cookie data and view-state data, and for verification of out-of-process session state identification.
Example to set both the validationKey and decryptionKey attributes to AutoGenerate. The
isolateApps value is specified to generate unique keys for each application on the server.
<machineKey
validationKey="AutoGenerate,IsolateApps" [String]
decryptionKey="AutoGenerate,IsolateApps" [String]
validation="SHA1" [SHA1 | MD5 | 3DES | AES]
decryption="Auto" [Auto | DES | 3DES | AES]
/>
– validationKey: Specifies the key used to validate encrypted data. It is is used when
enableViewStateMAC is true in order to create a message authentication code (MAC) to
ensure that view state has not been tampered with. It is also used to generate out-of-process,
application-specific session IDs to ensure that session state variables are isolated between
sessions.
– decryptionKey: Specifies the key that is used to encrypt and decrypt data or the process by
which the key is generated. This attribute is used for forms authentication encryption and
decryption, and for view-state encryption when validation is set to the TripleDES field.
– validation: Specifies the type of encryption that is used to validate data.
– decryption: Specifies the type of hashing algorithm that is used for decrypting data.
ASP.Net Configuration Files (cont.)
•
<authentication>: Configures the ASP.NET authentication scheme that is used to identify users
who view an ASP.NET application.
<authentication
mode="[Windows|Forms|Passport|None]“
>
<forms>...</forms>
<passport/>
</authentication>
Example:
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="401kApp" loginUrl="/login.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
ASP.Net Configuration Files (cont.)
•
<authorization>: determines whether an identity should be granted access to a specific resource.
In ASP.NET, there are two ways to authorize access to a given resource.
– File authorization checks the access control list (ACL) of the .aspx or .asmx handler file to
determine whether a user should have access to the file. ACL permissions are verified for the
user's Windows identity (if Windows authentication is enabled) or for the Windows identity of
the ASP.NET process.
– URL authorization maps users and roles to URLs in ASP.NET applications. This module can
be used to selectively allow or deny access to arbitrary parts of an application (typically
directories) for specific users or roles. --- With URL authorization, you explicitly allow or deny
access to a particular directory by user name or role.
<authorization>
<allow verbs="GET" users="*"/>
<allow verbs="POST" users="Kim"/>
<deny verbs="POST" users="*"/>
</authorization>
* means all users, both authenticated and anonymous
? means anonymous users
<authorization>
<allow users="Kim"/>
<allow roles="Admins"/>
<deny users="John"/>
<deny users="?"/>
</authorization>
ASP.Net Configuration Files (cont.)
•
<identity>: Configures the identity of the Web application. This element can be declared at any
level in the configuration file hierarchy.
–
–
–
username: Specifies the user name to use, if the impersonate attribute is true.
Password: Specifies the password to use, if the impersonate attribute is true.
Example: userName="registry:HKLM\Software\AspNetProcess,Name"password="registry:HKLM\Software\AspNetProcess,Pwd"
<identity impersonate="true|false"
userName="domain\username"
password="<secure password>"/>
ASP.Net Configuration Files (cont.)
•
<securityPolicy>: Defines a collection of mappings between security policy files and the trust level
names for the security policy files.
<securityPolicy>
<trustLevel name="Full" policyFile="internal"/>
<trustLevel name="High" policyFile="web_hightrust.config"/>
<trustLevel name="Medium" policyFile="web_mediumtrust.config"/>
<trustLevel name="Low" policyFile="web_lowtrust.config"/>
<trustLevel name="Minimal" policyFile="web_minimaltrust.config"/>
<trustLevel
name="CustomTrustLevel"
policyFile="customtrust.config"/>
</securityPolicy>
ASP.Net Configuration Files (cont.)
•
<processModel> Configures the ASP.NET process model settings on a Microsoft Internet Information Services
(IIS) Web server. The processModel section can be set only within the Machine.config file and affects all ASP.NET
applications that are running on the server.
<processModel
enable="true"
timeout="Infinite"
idleTimeout="Infinite"
shutdownTimeout="00:00:05"
requestLimit="Infinite"
requestQueueLimit="5000"
restartQueueLimit="10"
memoryLimit="60"
webGarden="false"
cpuMask="0xffffffff"
userName="machine"
password="AutoGenerate"
logLevel="Errors"
clientConnectedCheck="00:00:05"
comAuthenticationLevel="Connect"
comImpersonationLevel="Impersonate"
responseDeadlockInterval="00:03:00"
responseRestartDeadlockInterval="00:03:00"
autoConfig="true"
maxWorkerThreads="20"
maxIoThreads="20"
minWorkerThreads="1"
minIoThreads="1"
serverErrorMessageFile=""
pingFrequency="Infinite"
pingTimeout="Infinite"
asyncOption="20"
maxAppDomains="2000"
/>
Configuring ASP.net Worker Process Identity
•
http://etutorials.org/Programming/Programming+.net+security/Part+IV+.NET+Application+Frameworks/Chapter+18.+ASP.NET+Applicatio
n+Security/18.2+Configuring+the+ASP.NET+Worker+Process+Identity/
•
•
ASP.net uses a pool of worker processes to handle ASP.net application requests.
By default, each worker process executes in the context of a special windows account named
ASP.NET.
ASP.NET account is assigned a limited set of Windows privileges and permissions.
We can change the account under which ASP.NET worker processes run by configuring the
username and password attribute of the <processModel> element in the machine.config file.
– This change affects all ASP.NET applications running on the machine.
– userName =Machine---default value; runs as ASP.NET account
– username=System---causes ASP.NET worker process to run as the same account under
which IIS is running; by default this will be the built-in Windows System account.
– username=SomeUser---specify the name of an account under which the worker process
should run.
<configuration>
<processModel userName="System" password="AutoGenerate"/>
</configuration>
•
•
<configuration>
<processModel userName="SomeUser" password="secret"/>
</configuration>
<configuration>
<processModel userName="registry:HKLM\Software\OReilly\AspNet,Name"
ASP.Net authentication: IIS Authentication Modes
•
•
•
•
ASP.NET provides the following authentication modes:
– None (No authentication)
– Windows Authentication (needs IIS Authentication)
– Forms Authentication
– Extending Forms Authentication
– .Net Passport Authentication
The authentication modes for different ASP.NET applications may be configured by settings in the
application’s web.config file. It can ONLY be set at the application level.
Before a client request reaches the ASP.NET application, it must pass through IIS authentication.
For Windows authentication---IIS authentication provides the application with the information
about the authenticated Windows user.
ASP.Net authentication: IIS Authentication Modes (cont.)
•
•
•
For None, Forms, and Passport authentication modes---IIS authentication is turned off by enabling
anonymous access to IIS.
For Windows authentication mode---IIS authentication is used (with 5 options)
Unless the impersonation option is enabled, ASP.NET authentication has no effect on the
Windows user context under which the ASP.NET application executes.
ASP.Net authentication: IIS Authentication Modes (cont.)
ASP.Net authentication: IIS Authentication Modes (cont.)
•
Configuring IIS Authentication Modes: Anonymous authentication
– By default, IIS enables anonymous authentication and uses the IUSR_machinename user
account with the password controlled by IIS.
– Anonymous authentication gives users access to the public areas of your Web site
without prompting them for a user name or password. Here, the client is not required to
supply any credentials. Instead, IIS provides stored credentials to Windows using a
special user account, IUSR_machinename. By default, IIS controls the password for this
account.
– Pros of anonymous authentication
• Offers the best performance because Anonymous authentication imposes no
appreciable overhead.
• Does not require management of individual user accounts.
• If IIS does not control the password, can access network resources.
– Cons of anonymous authentication
• Does not authenticate clients on an individual basis.
• If IIS does not control the password, account must have local logon ability.
ASP.Net authentication: IIS Authentication Modes(cont.)
•
Configuring IIS Authentication Modes: Basic authentication
– When a client requests a resource protected by Basic authentication, IIS challenges the
client to provide a username and a password.
– The client responds by sending the username and password details across the network in
clear text. Hence, it is not appropriate for secure applications unless SSL or TLS are
used providing a secure connection between the client and the server.
– Procedure:
• IIS obtains logon info from an HTTP client via the familiar windows dialog box to
obtain username and password
• The information is then transmitted to the web server
• It then attempts to login to the windows account with the username and password
• It also checks if the account is allowed to access the requested file/directory
• If successful, the response rendered by web server is returned to the HTTP client
• Weakness: Username + password data between client and server is encoded into a
string that intruders may have access to. So it is preferable to use if SSL-like secure
mechanism is used in between.
ASP.Net authentication: IIS Authentication Modes(cont.)
•
Configuring IIS Authentication Modes: Digest authentication
– Similar to Basic authentication, but the client passes a hash of the user’s
password across the network instead of the clear text password.
– But this requires the IIS server to be a member of a Windows domain that uses
Active Directory to contain its user accounts.
– Only Active directory allows IIS to access a user’s password in such a way as
to allow IIS to verify the hashed password provided by the client.
– Procedure:
• Like basic authentication, it requires user to enter username/password.
• Instead of sending the password in clear, it sends a digest of the password.
» The HTTP client creates a hash value of the password, the nonce
sent by the HTTP server, and some other values. This hash is the
digest
» The HTTP server uses the stored password for the username to
generate the hash (digest) and verifies it.
ASP.Net authentication: IIS Authentication Modes(cont.)
•
Configuring IIS Authentication Modes: Integrated Windows authentication
– When IIS challenges a client to provide user credentials, the client application
does not prompt the user for account information; instead, it extracts the
necessary etails from the OS based on the currently logged-on used.
– Credentials are communicated using Windows authentication protocols.--ensuring that passwords are not sent across the network.
– Procedure:
• Most popular among the simple authentication schemes
• For users who have already logged into a Windows machine
• Provides WAN or LAN based internet applications with an authentication
practice that is virtually invisible to the user
• A domain controller provides user credentials to the client station where
user log in.
• These credentials are in turn transferred to the IIS at the request server
•
Configuring IIS Authentication Modes: Client Certificate authentication
– Requires each client to have an X.509 digital certificate.
– Each certificate maps to a specific Windows user account.
– When a client makes a request, it contains the client’s certificate.
– IIS validates the certificate and determines which Windows user is making the request.
ASP.Net Authentication: No authentication
•
No authentication
– If we are not concerned about authenticating users, or intend to use some
custom authentication mechanism implemented within the ASP.NET
application, we can turn off ASP.NET authentication.
< configuration>
<system.web>
<authentication mode=“None">
</authentication>
</system.web>
</configuration>
– Even if we are not concerned about using ASP.NET authentication
mechanisms, we can still enable IIS authentication so that we can allow ONLY
permitted Windows users to access the application.
– To truly allow unrestricted access to the application, enable anonymous access
to IIS.
ASP.Net Authentication: Windows Authentication
•
Windows authentication
–
–
–
Relies on IIS to authenticate any inbound requests. IIS can use any of its built-in Basic, Digest, Integrated, or client
certificate authentication mechanisms before the request reaches the ASP.net application.
Only if IIS anonymous authentication is not enabled, IIS will ensure that the requesting user has a valid Windows
account and pass the authenticated user’s information to the ASP.net application.
In this case, ASP.net application principal is set to an instance of System.Principal.WindowsPrincipal configured to
represent the authenticated Windows user.
< configuration>
<system.web>
<authentication mode=“Windows">
</authentication>
</system.web>
</configuration>
ASP.Net Authentication: Windows authentication (cont.)
•
Windows authentication
– Advantages:
• Little work for programmer
• Integrates well with IIS security
• Integration with windows client machine---no need for a user to authenticate for an
application if already done so initially by the windows OS
– Disadvantages:
• Tied to windows users
• Tied to windows client M/C
• Lack of flexibility
– Result:
• This creates a WindowsPrincipal object and a WindowsIdentity object, with each
request
• User.Identity.Name provides user name
• WindowsPrincipal.IsInRole methods lets us test if the user has a specific role
ASP.Net Authentication: Forms Authentication
•
•
•
•
Windows authentication requires users of ASP.net applications to have Windows user
accounts. For large web-based and cross-platform applications, this may not be
feasible or desirable.
Forms authentication allows us to implement a custom authentication mechanism
where we can authenticate users against any type of authority.
Note: To use Forms authentication, we should enable IIS anonymous access.
Otherwise, IIS will force users to first authenticate with whatever mechanism it is set
to.
It works as follows:
– When request is made to a page protected by forms authentication, the user is
redirected to a login page. The URL of the original request is preserved.
– Login page contains a form for users to enter their credentials (e.g., username
and password)
– If the details the user entered are correct, an “Authentication ticket” is created.
The ticket contains the encrypted details of the user. The ticket is written into a
cookie and sent to the client machine. The credentials are authenticated by the
application in whichever way it prefers (e.g., database). Thus responsibility to
authenticate completely depends on the application developer.
– The user is then redirected back to the URL they originally requested. Now the
authentication cookie is added to the request by the browser and picked up by
the authentication module.
– The URL authorization module uses the details to verify user and provide access
ASP.Net Authentication: Forms Authentication (cont.)
<authentication mode="Forms">
<forms name="SavingsPlan" loginUrl="/Login.aspx">
<credentials passwordFormat="SHA1">
<user name="Kim"
password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/>
<user name="John"
password="BA56E5E0366D003E98EA1C7F04ABF8FCB3753889"/>
</credentials>
</forms>
</authentication>
ASP.Net Authentication: Forms Authentication (cont.)
For details of steps 1-10, refer to http://msdn.microsoft.com/en-us/library/ff647070.aspx
ASP.Net Authentication: Forms Authentication (cont.)
•
Pros:
– Keeps all authentication code within the application
– We have full control over the appearance of the login form
– Works for users with any browser
– Allows us to decide how to store user information (by default stored in
web.config file but can be stored anywhere)
• Cons:
– We have to create our own interface for users to log in
– We have to maintain user details ourselves
– Resources protected by forms authentication must be processed
by ASP.Net (i.e., anonymous access bypassing ASP.Net is not
possible)
ASP.Net Authentication: Forms Authentication (cont.)
• Procedure:
– Step 1: Configure forms authentication in the web.config file: (See Table 18.2,
Freeman&Jones, page 470)
<authentication mode="Forms" >
<forms name="MyASPXFORMSAUTH“--- unique name for the cookie
loginUrl="Login.aspx“---page to which user should be directed
timeout="15“”---length of time in minutes an authentication cookie is valid
path="/ “---path for the cookie for the browsers
protection="All"> ---do both encryption and a MAC for the cookie
<credentials passwordFormat="MD5">
<user name="bethb"
password="26E13F4ECF73413D5DC9A99FDDD34C84" />
</credentials>
</forms>
</authentication>
ASP.Net Authentication: Forms Authentication (cont.)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
cookieless ASP.NET 2.0 Forms Authentication can store the forms authentication ticket in either a cookie, or in a cookie-less
representation on the URL. The default value of UseDeviceProfile means that ASP.NET determines where to store the ticket based on
pre-computed browser profiles. The AutoDetect option causes ASP.NET to dynamically determine if the browser supports cookies or not.
UseUri and UseCookies force cookieless and cookied tickets respectively.
defaultUrl Specifies the default URL to which the request is redirected after a successful login. This value is used if a redirect URL is not
available to Forms Authentication when redirecting after login.
domain Specifies the value of the Domain property on the HttpCookie containing the forms authentication ticket. Explicitly setting this
attribute allows applications to share the same cookie as long as the applications share a common portion of a DNS namespace (e.g.
appA.contoso.com and appB.contoso.com could share a cookie if the domain attribute is set to "contoso.com").
enableCrossAppRedirects In ASP.NET 2.0, Forms Authentication allows you to pass the forms authentication ticket across applications in
either a query-string variable or in a forms POST variable. Setting this attribute to true enables the FormsAuthenticationModule to extract
the ticket from either the query-string or forms POST variables.
loginUrl Specifies the URL to which the request is redirected for unauthenticated users. This can be on the same computer or a remote
one. If it is on a remote computer, both computers need to be using the same value for the decryptionkey and validationKey attributes
found in the machineKey configuration element.
name Name of the HTTP cookie to use for authentication purposes. Note that if more than one application wants to use forms-based
authentication services on a single computer, and each application wants the forms authentication cookie to be isolated by application,
then they should each configure a unique cookie value. In order to avoid causing dependencies in URLs, ASP.NET also uses "/" as the
Path value when setting authentication cookies, so that they are sent back to every application on the site.
path Path to use for the issued cookie. The default value is "/" to avoid difficulties with mismatched case in paths, since browsers are
strictly case-sensitive when returning cookies. Applications in a shared-server environment should use this directive to maintain private
cookies. (Alternatively, they can specify the path at runtime using the APIs to issue cookies.)
protection Method used to protect cookie data. Valid values are as follows: ##All: Use both data validation and encryption to protect the
cookie. The configured data validation algorithm is based on the <machinekey> element. AES is used by default for encryption, and if the
key is long enough (48 characters). All is the default (and suggested) value.
##None: Use for sites that are only using cookies for personalization and have weaker security requirements. Both encryption and
validation can be disabled. Although you should use caution if you use cookies in this way, this setting provides the best performance of
any method of doing personalization using the .NET Framework.
##Encryption: Encrypts the cookie using AES, TripleDES or DES, but data validation is not done on the cookie. This type of cookie can be
subject to chosen plaintext attacks.
##Validation: Does not encrypt the contents of the cookie, but validates that the cookie data has not been altered in transit. To create the
cookie, the validation key is concatenated in a buffer with the cookie data and a MAC is computed and appended to the outgoing cookie.
requireSSL If set to true, Forms Authentication sets the secure bit on the forms authentication cookie. Compliant browers will only send
the cookie back to ASP.NET over an SSL connection. Note that this setting has no effect when using cookieless forms authentication.
slidingExpiration If set to true, Forms Authentication will periodically update the time to live for the forms authentication ticket. This occurs
regardless of whether or not the ticket is contained in a cookie, or in a cookieless format on the URL.
timeout Amount of time in integer minutes, after which the cookie expires. The default value is 30. The timeout attribute is a sliding value,
expiring n minutes from the time the last request was received. In order to avoid adversely affecting performance and to avoid multiple
browser warnings for those who have cookies warnings turned on, the cookie is updated if the time is more than half gone. (This means a
loss of possible precision in some cases.)
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/security/formsauth.aspx
ASP.Net Authentication: Forms Authentication (cont.)
• Procedure:
•
•
•
•
Step 2: Create a login page. This is the page where ASP.NET redirects all
unauthenticated user requests.
Note that client requests containing a valid authentication cookie are routed directly
to the requested application resource; only those without an authentication cookie
are redirected to the login page.
In the we,config file, under the <forms> element, the loginURL attribute specifies
the URL of the login page.form to enable users to enter their credentials.
(For more info:
http://www.ondotnet.com/pub/a/dotnet/2003/01/06/formsauthp1.html)
ASP.Net Authentication: Forms Authentication (cont.)
•
C# Code for logon.aspx (http://edc.tversu.ru/elib/inf/0087/0596004427_prognetsec-chp-18-sect-3.html)
<html>
<script language="C#" runat="server">
void Logon_Click(Object sender, EventArgs e) {
// Perform authentication of the user credentials.
// Use the static FormsAuthentication.Authenticate method
// to authenticate the credentials against those contained
// in the <credentials> element of Web.config.
if (FormsAuthentication.Authenticate(Name.Text,Password.Text)) {
// Credentials OK, redirect to originally requested page.
FormsAuthentication.RedirectFromLoginPage(Name.Text,true);}}
</script>
<body>
<h2>Forms Authentication Example - Logon Page</h2>
<form id="LogonForm" method="post" runat="server">
<table>
<tr align="right">
<td>User Name : </td>
<td><asp:TextBox id="Name" runat="server"/></td>
</tr>
<tr align="right">
<td>Password : </td>
<td><asp:TextBox id="Password" runat="server"/></td>
</tr>
<tr align="center">
<td colspan="2">
<asp:Button id="Logon" runat="server" Text="Logon"
OnClick="Logon_Click"/>
</td>
</tr>
</table>
</form>
</body>
</html>
ASP.NET Authorization
•
•
•
Authorization determines whether an authenticated entity can access the resource it
requested.
ASP.Net provides two types of authorizations:
– File authorization
– URL authorization
File authorization:
– File authorization is enforced automatically when we enable ASP.NET windows
authentication, and cannot be disabled or configured.
– After IIS authenticates the user, but before ASP.NET hands the request to the
File authorization is performed by the FileAuthorizationModule. It checks the
access control list (ACL) of the .aspx or .asmx handler file to determine whether
a user should have access to the file.
– ACL permissions are verified for the user's Windows identity (if Windows
authentication is enabled) or for the Windows identity of the ASP.NET process.
– If the user has permission, ASP.NET will hand the request to the application for
processing; otherwise, it will refuse the request.
ASP.NET Authorization: File Authorization
1.
2.
Create a new web application. Name the form Index.aspx
Place the following code under the <form> tag:
<a href =“AuthorizedFile.aspx”> Click here for AuthorizedFile </a> <br>
<a href =“UnAuthorizedFile.aspx”> Click here for UnAuthorizedFile </a>
3. Add two new web forms: AuthorizedFile.aspx and UnAuthorizedFile.aspx
4. Under <form> tag in AuthorizedFile type: <h2> You have access to the file </h2>
Under <form> tag in UnAuthorziedFile type: <h2> You do not have access to the file
</h2>
5. Build the solution and run: Clicking the links, the messages will appear
6. Create three different users: user1, user2, user3
7. Provide the following access rights to UnauthorizedFile.aspx: user1: Full access;
user2: Read and Execute; user3: Deny All
8. Login as user3 and click on UnAuthorizedFile link; it will be denied access
ASP.Net Authorization: URL authorization
•
With URL authorization, you explicitly allow or deny access to a particular directory by user name
or role. To do so, you create an authorization section in the configuration file for that directory. To
enable URL authorization, you specify a list of users or roles in the allow or deny elements of the
authorization section of a configuration file. The permissions established for a directory also apply
to its subdirectories, unless configuration files in a subdirectory override them.
<authorization> //grants access to the Kim identity and members of the Admins role, and denies
//access to the John identity (unless the John identity is included in the Admins role)
//and to all anonymous users:
<allow users="Kim"/>
<allow roles="Admins"/>
<deny users="John"/>
<deny users="?"/>
</authorization>
<authorization>
<allow users="John"/> //allow access to the John identity and deny access to all other users:
<deny users="*"/>
</authorization>
<authorization>
<allow verbs="GET" users="*"/>
<allow verbs="POST" users="Kim"/>
<deny verbs="POST" users="*"/>
</authorization>
ASP.NET Impersonation
•
•
•
•
•
When authorizing access to a resource, ASP.NET will only search until it finds the
first <allow> or <deny> element that appears to the current identity. Hence, the order
of the elements is important.
Authorization restrictions created lower down the application hierarchy take
precedence over those defines higher up.
“?” all unauthenticated users
“*” all users, authenticated and unauthenticated
Impersonation:
– Impersonation allows an ASP.NET application to run in the context of the
authenticated Windows user that made the web request..
– Thus, all server-side resources accessed by the ASP.net occur in the context of
the authenticated user.
<configuration>
<system.web>
<identity impersonate="true"/> //control impersonation using
//the identity configuration element.
</system.web>
</configuration>
<identity impersonate="true"
userName="contoso\Jane"
password="********" />
ASP.NET Impersonation (cont.)
•
•
Impersonation may be configured at any level of the configuration hierarchy; it can be configured differently for
individual applications or application resources, if needed.
When IIS anonymous authentication is used, if impersonation is enabled, the ASP.NET application will
impersonate the user account configured in IIS for anonymous access; by default it is IUSR_MACHINENAME user
account.
IPrincipal Interface
• HttpContext.Current.User property returns an
instance of IPrincipal
• It is part of System.Security.Principal
• Has a single property: Identity: Gets the IIdentity
of the current Principal: Example:
HttpContext.Current.User.Identity.Name
• Has single method: IsInRole(roleName As
String): Example: if
(HttpContext.Current.User.IsInRole(“Admin”)
{…..}
IIdentity Interface
• Provides current user’s identity
• Four identity classes included in .Net:
– System.Web.Security.WindowsIdentity
– System.Web.Security.FormsIdentity
– System.Web.Security.PassportIdentity
– System.Web.Security.GenericIdentity
How Identity and Principal are
used?
• Types of identities: depending on authentication used:
WindowsIdentity, FormsIdentity, PassportIdentity, GenericIdentity
• All these implement IIdentity interface (part of
System.Security.Principal namespace)
• An application may always find the user attached to the current
thread using Identity object
• Principal: a combination of user and groups the user belongs to
(Identity+roles)
• Principal types: WindowsPrincipal and GeneraicPrincipal
• Both implement IPrincipal interface (part of
System.Security.Principal namespace)
• IPrincipal provides the following:
• IIdentity Identity (get): to get the underlying object
• IsInRole(string role): to determine whether the user belongs to a certain role
How .Net Security Works
• Users who log in to the application are granted a principal and an
identity, based on the credentials they have provided.
• Principal object: Represents the group or role membership of the
authenticated user, i.e. security context of the current user. It is
possible to create a generic principal object using data from a
database. Httpcontext.Current.User property returns an instance of
IPrincipal.
• Identity object represents the authenticated user. Windows
authentication uses WindowsIdentity while forms authentication
uses FormsIdentity object.
• http://www.developerland.com/Web/Security/215
.aspx
Role-based Security
• In general, authorization requirements are as follows:
– Users should have proper credentials to access a resource
– Certain users need to be denied access to particular resources
– Only certain users should be allowed to access particular
resources
• If you intend to use RBS, you must either assign an
IPrincipal to a thread manually or configure the runtime
to create one automatically
• Use System.AppDomain.SetThreadPrincipal to
automatically generate for each thread, or
– Set current thread’s IPrincipal manually using
System.Thredaing.Thread.CurrentPrincipal property.
Making Role-based Security Demands
• Do not result in a stack walk---based solely on identity and roles of
the active thread’s principal
• Imperative role-based security statements:
– Commonly used constructor: PrincipalPermission
– Each PrincipalPermission can specify only a single role name.
“null” means no matching is needed
– Public PrincipalPermission(string name, string role)
PrincipalPermission p1 = new PrincipalPermission(“John”, “Manager”);
p1.Demand();
PrincipalPermission p2 = new PrincipalPermission(null, “Programmer”);
p2.Demand();
PrincipalPermission p3 = new PrincipalPermission(“Kevin”, null);
p3.Demand();
PrinciplaPermission Explanationhttp://msdn.microsoft.com/enus/library/system.security.permissions.principalpermission.aspx
Making Role-based Security Demands (cont.)
• Using Declarative role-based security
statements:
– PrincipalPermissionAttribute may be applied to
classes, methods, properties, or events to force
declarative demands
– This cannot be applied at the assemble level
– Demand, LinkDemand, and InheritanceDemand are
the only RBS statements allowed
[PrincipalPermission(SecurityAction.Demand, Name=“John”, Role=“Manager”)]
[PrincipalPermission(SecurityAction.Demand, Role=“Programmer”)]
[PrincipalPermission(SecurityAction.Demand, Name=“Kevin”)]
File Authorization
•
•
•
1.
2.
FileAuthorizationModule class uses the underlying ACLs of the
file system to control access to ASPX pages
This works only in conjunction with Windows Authentication
Example:
Create a new web application. Name the form Index.aspx
Place the following code under the <form> tag:
<a href =“AuthorizedFile.aspx”> Click here for AuthorizedFile </a> <br>
<a href =“UnAuthorizedFile.aspx”> Click here for UnAuthorizedFile </a>
3. Add two new web forms: AuthorizedFile.aspx and UnAuthorizedFile.aspx
4. Under <form> tag in AuthorizedFile type: <h2> You have access to the file </h2>
Under <form> tag in UnAuthorziedFile type: <h2> You do not have access to the file </h2>
5. Build the solution and run: Clicking the links, the messages will appear
6. Create three different users: user1, user2, user3
7. Provide the following access rights to UnauthorizedFile.aspx: user1: Full access; user2: Read and
Execute; user3: Deny All
8. Login as user3 and click on UnAuthorizedFile link; it will be denied access
• Authorization for a specific file or folder (using
web.config):
<location path=“UnAuthorizedFile.aspx”>
<system.web>
<authorization>
<deny users = “\localhost\user3” />
</authorization>
</system.web>
</location>
(This overrides what the OS says about the permissions)
Calculation of Permissions
• The default permission is to allow access for all users
• Upon calculation of a merged rule set, the system checks the rules
until it finds a match: either allow or deny
• When a deny is encountered, the system throws a 401 error:
Unauthorized access
• Example:
At the application level, include in web.config: <authorization> <allow
users=“localhost\user1, \localhost\user2” /> <deny users = “?”/>
</authorization>
At a particular page level, we can add this to web.config:
<location path=“UnAuthorizedFile.aspx”> <system.web>
<authorization><deny roles = “users” /> </authorization>
</system.web> </location>
Denies access to this page to any windows user.
Authorization Checks in Code
• We can control access even at a button level
using checks in the code
• If {user1, user2} are made into a single group
called validgroup, then:
if
(Thread.CurrentPrincipal.IsInRole(“localhost\vali
dgroup”))
{Response.Write (“You have access”);}
else
{Response.Redirect(“AuthorizationError.aspx”);}
Demanding Credentials
try
{ PrincipalPermission pp = new PrincipalPermission(“user1”, “validgroup”);
pp.Demand();
Response.Write(“PrincipalPermission successful”);
}
Catch (SecurityException se)
{Response.Write (“PrincipalPermission Denied”);
}
Merging PrincipalPermission objects:
try
{PrincipalPermission pp1 = new PrincipalPermission(“user1”, “validgroup”);
{PrincipalPermission pp2 = new PrincipalPermission(“user2”, “validgroup”);
{PrincipalPermission pp3 = (PrincipalPermission)p1.Union (p2);
pp3.Demand();
Response.Write(“PrincipalPermission successful”);
}
Catch (SecurityException se)
{Response.Write (“PrincipalPermission Denied”);
}
PrincipalPermissionAttribute:
Another way to Authorize
• Place the following code above the
method declaration:
[PrincipalPermissionAttribute(SecurityAction.Demand, Name=“user1”,
Role = “validusers”)]
Or
[PrincipalPermissionAttribute(SecurityAction.Demand, Role =
“validusers”)]
Download