ASP.Net Application Security Chapter 18 (Freeman and Jones) CS795/895.

Slides:



Advertisements
Similar presentations
Enabling Secure Internet Access with ISA Server
Advertisements

Forms Authentication, Users, Roles, Membership Ventsislav Popov Crossroad Ltd.
ASP.Net Security Chapter 10 Jeff Prosise’s Book. Authentication To ascertain the caller’s identity –Windows authentication –Forms authentication –Passport.
1 Configuring Internet- related services (April 22, 2015) © Abdou Illia, Spring 2015.
DESIGNING A PUBLIC KEY INFRASTRUCTURE
1 Configuring Web services (Week 15, Monday 4/17/2006) © Abdou Illia, Spring 2006.
70-290: MCSE Guide to Managing a Microsoft Windows Server 2003 Environment Chapter 5: Managing File Access.
Authenticating Users in an ASP.NET Application. Web Site Administration Tool From VS 2008, click Website/ ASP.Net Configuration to open Web Site Administration.
Security in.NET Jørgen Thyme Microsoft Denmark. Topics & non-topics  Cryptography  App domains  Impersonation / delegation  Authentication  Authorization.
Microsoft ASP.NET Security Venkat Chilakala Support Professional Microsoft Corporation.
(Remote Access Security) AAA. 2 Authentication User named "flannery" dials into an access server that is configured with CHAP. The access server will.
ASP.NET 2.0 Chapter 6 Securing the ASP.NET Application.
Chapter 13 – Site Security. Internet Information Server ASP.NET Applications.NET Framework Windows NT/2000 Operating System Forms Passport Windows Certificates.
Jonas Thomsen, Ph.d. student Computer Science University of Aarhus Best Practices and Techniques for Building Secure Microsoft.
Role based Security in.NET By By Aasia Riasat Aasia RiasatCS-795.
1 Chapter Overview Creating User and Computer Objects Maintaining User Accounts Creating User Profiles.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
Internet Information Server 6.0. Overview  What’s New in IIS 6.0?  Built-in Accounts and IIS 6.0  IIS Pass-Through Authentication  Securing Web Traffic.
Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. ASP.NET Authentication.
1 ASP.NET SECURITY Presenter: Van Nguyen. 2 Introduction Security is an integral part of any Web-based application. Understanding ASP.NET security will.
Edwin Sarmiento Microsoft MVP – Windows Server System Senior Systems Engineer/Database Administrator Fujitsu Asia Pte Ltd
Ins and Outs of Authenticating Users Requests to IIS 6.0 and ASP.NET Chris Adams Program Manager IIS Product Unit Microsoft Corporation.
.Net Security and Performance -has security slowed down the application By Krishnan Ganesh Madras.
Session 11: Security with ASP.NET
Authentication and Authorization CS795/895. How.Net Security Works Users who log in to the application are granted a principal and an identity, based.
Forms Authentication, Users, Roles, Membership Svetlin Nakov Telerik Corporation
70-290: MCSE Guide to Managing a Microsoft Windows Server 2003 Environment, Enhanced Chapter 5: Managing File Access.
Copyright 2000 eMation SECURITY - Controlling Data Access with
State Management. What is State management Why State management ViewState QueryString Cookies.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Securing a Microsoft ASP.NET Web Application.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
1 Web services and security ---discuss different ways to enforce security Presenter: Han, Xue.
Chapter 8 Cookies And Security JavaScript, Third Edition.
.Net and Web Services Security CS795. Web Services A web application Does not have a user interface (as a traditional web application); instead, it exposes.
Module 5 Configuring Authentication. Module Overview Lesson 1: Understanding Classic SharePoint Authentication Providers Lesson 2: Understanding Federated.
Dr. Mustafa Cem Kasapbaşı Security in ASP.NET. Determining Security Requirements Restricted File Types.
Effective Security in ASP.Net Applications Jatin Sharma: Summer 2005.
Securing Your ASP.NET Application Presented by: Rob Bagby Developer Evangelist Microsoft ( )
SECURITY ISSUES. Introduction The.NET Framework includes a comprehensive set of security tools –Low-level classes and an overall framework –Managing code.
The.NET Runtime and IIS Presented by Chris Dickey – cdickey.net consulting
PROG Advanced Web Applications With.NET PROG Advanced Web Applications With.NET User Authentication & Authorization.
1 CS 3870/CS 5870: Note 07 Lab 3 Lab 4 Test 1: Two Tables.
STATE MANAGEMENT.  Web Applications are based on stateless HTTP protocol which does not retain any information about user requests  The concept of state.
Module 11: Securing a Microsoft ASP.NET Web Application.
Slide 1 ASP Authentication There are basically three authentication modes Windows Passport Forms There are others through WCF You choose an authentication.
Guide to MCSE , Second Edition, Enhanced1 The Windows XP Security Model User must logon with: Valid user ID Password User receives access token Access.
MCDST : Supporting Users and Troubleshooting a Microsoft Windows XP Operating System Chapter 11: Managing Access to File System Resources.
Ins and Outs of Authenticating Users Requests to IIS 6.0 and ASP.NET Chris Adams Program Manager IIS Product Unit Microsoft Corporation.
ASP.Net Role-based Security Chapter 10 (Freeman and Jones) CS795/895.
MEMBERSHIP AND IDENTITY Active server pages (ASP.NET) 1 Chapter-4.
GUDURU PRAVEEN REDDY.NET IMPERSONATION. Contents Introduction Impersonation Enabled Impersonation Disabled Impersonation Class Libraries Impersonation.
IIS and.Net security -Vasudha Bhat. What is IIS? Why do we need IIS? Internet Information Services (IIS) is a Web server, its primary job is to accept.
Configuring and Troubleshooting Identity and Access Solutions with Windows Server® 2008 Active Directory®
Impersonation Bharat Kadia CS-795. What is Impersonation ? Dictionary-: To assume the character or appearance of someone ASP.NET-: Impersonation is the.
1 Chapter Overview Creating Web Sites and FTP Sites Creating Virtual Directories Managing Site Security Troubleshooting IIS.
The world leader in serving science Overview of Thermo 21 CFR Part 11 tools Overview of software used by multiple business units within the Spectroscopy.
Security E-Learning Chapter 08. Security Control access to your web site –3 Techinques for Identifying users Giving users access to your site Securing.
Configuring and Deploying Web Applications Lesson 7.
Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. Configuration.
Securing Web Applications Lesson 4B / Slide 1 of 34 J2EE Web Components Pre-assessment Questions 1. Identify the correct return type returned by the doStartTag()
19 Copyright © 2008, Oracle. All rights reserved. Security.
Unit 7 Learning Objectives
Agenda Introduction Security flow for a request Authentication
Security Basics and ASP.NET Support
Configuring and Troubleshooting Routing and Remote Access
Security mechanisms and vulnerabilities in .NET
Created by : Asst. Prof. Ashish Shah
Configuring Internet-related services
ASP.Net Security Framework
Presentation transcript:

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 : Specifies the resource that specified configuration settings apply to. /*Max size can be 128K for uploading */ /* child directory web.config settings cannot override this*/

ASP.Net Configuration Files (cont.) : 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. enableViewStateMAC –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.) : Configures the ASP.NET authentication scheme that is used to identify users who view an ASP.NET application. <authentication mode="[Windows|Forms|Passport|None]“ >... Example:

ASP.Net Configuration Files (cont.) : 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. * means all users, both authenticated and anonymous ? means anonymous users

ASP.Net Configuration Files (cont.) : 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=" "/>

ASP.Net Configuration Files (cont.) : Defines a collection of mappings between security policy files and the trust level names for the security policy files. <trustLevel name="CustomTrustLevel" policyFile="customtrust.config"/>

ASP.Net Configuration Files (cont.) 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 n+Security/18.2+Configuring+the+ASP.NET+Worker+Process+Identity/ 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 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. <processModel userName="registry:HKLM\Software\OReilly\AspNet,Name" password="registry:HKLM\Software\OReilly\AspNet,Password"/>

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.)

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. –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.

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.) <user name="Kim" password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/> <user name="John" password="BA56E5E0366D003E98EA1C7F04ABF8FCB "/>

ASP.Net Authentication: Forms Authentication (cont.) For details of steps 1-10, refer to

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) <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 <user name="bethb" password="26E13F4ECF73413D5DC9A99FDDD34C84" />

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 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.)

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 element, the loginURL attribute specifies the URL of the login page.form to enable users to enter their credentials. (For more info:

ASP.Net Authentication: Forms Authentication (cont.) C# Code for logon.aspx ( 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 element of Web.config. if (FormsAuthentication.Authenticate(Name.Text,Password.Text)) { // Credentials OK, redirect to originally requested page. FormsAuthentication.RedirectFromLoginPage(Name.Text,true);}} Forms Authentication Example - Logon Page User Name : Password : <asp:Button id="Logon" runat="server" Text="Logon" OnClick="Logon_Click"/>

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.FileAuthorizationModule –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.Create a new web application. Name the form Index.aspx 2.Place the following code under the tag: Click here for AuthorizedFile Click here for UnAuthorizedFile 3. Add two new web forms: AuthorizedFile.aspx and UnAuthorizedFile.aspx 4. Under tag in AuthorizedFile type: You have access to the file Under tag in UnAuthorziedFile type: You do not have access to the file 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. // 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 access to the John identity and deny access to all other users:

ASP.NET Impersonation When authorizing access to a resource, ASP.NET will only search until it finds the first or 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. //control impersonation using //the identity configuration element.identity <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.

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/en- us/library/system.security.permissions.principalpermission.aspxhttp://msdn.microsoft.com/en- us/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 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: 1.Create a new web application. Name the form Index.aspx 2.Place the following code under the tag: Click here for AuthorizedFile Click here for UnAuthorizedFile 3. Add two new web forms: AuthorizedFile.aspx and UnAuthorizedFile.aspx 4. Under tag in AuthorizedFile type: You have access to the file Under tag in UnAuthorziedFile type: You do not have access to the file 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): (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: At a particular page level, we can add this to web.config: 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”)]