ASP.NET 13 - Security

Post on 08-Jan-2017

2.019 views 1 download

Transcript of ASP.NET 13 - Security

Chapter 13Security, Membership, and Role Management

If thou be’st not immortal, look about you: security gives way to conspiracy. The mighty gods defend thee!William Shakespeare, Julius Caesar, Act II, Scene 3

2 Security2Overview

This chapter is about security in ASP.NET.

It covers: how security is built into ASP.NET concepts of authentication,

authorization, and trust. the different levels of security in an

ASP.NET Web application. the two principal forms of

authentication available to ASP.NET developers: Windows Authentication and forms authentication.

the provider model. the Membership and the Role

Management systems the login controls introduced with

ASP.NET 2.0

3 SecurityIntro to ASP.NET Security

By default, a Web application is available to anyone who can access its Web server.

However, almost every Web site has some resources within the site that are not meant to be publicly available. E.g., configuration files, subscription-

only content, and administration pages .

The principal focus of Web application security is to restrict access to site resources to the appropriate users.

4 SecurityIntro to ASP.NET Security

ASP.NET provides a multilayered approach to security: ASP.NET .NET Framework IIS Windows

5 SecuritySecurity Concepts

Authentication the process of verifying the identity of

the user. This is typically achieved by having

the user enter credentials, such as a user name and password.

If the credentials are valid (usually by checking them against a database or a list of operating system user accounts), the entity that submitted the credentials is considered an authenticated identity.

6 SecuritySecurity Concepts

Authorization the process of determining whether

the authenticated identity (i.e., the user) has permission to access certain resources.

The most common approach for authorization is role-based authorization

authorization based not on the user but on the role or group to which the user belongs.

Thus, permissions are assigned to different roles, and then users are assigned to different roles.

7 SecurityIIS Security

The first level of security checks is that imposed by IIS. Recall that all HTTP requests for

ASP.NET Web application resources are initially handled by IIS.

The request is first checked by IIS to see if the IP address of the request is allowed access to the domain of the requested resource.

The next check is to authenticate the user if necessary. If successful, the request is passed on

to ASP.NET. If either of these two checks fails, the

user receives an access denied response.

8 SecurityIIS Security

By default, IIS allows anonymous access to a Web application. This means the user of the request

does not actually have to be authenticated.

However, a Web application can be configured to require IIS authentication

9 SecurityIIS Authentication

IIS supports several types of authentication: Basic

The user name and password are encoded and transmitted in an HTTP header.

The user and password are checked to see if they match a Windows account on the server.

Should only be used with HTTPS Digest

The password is subjected to a special calculation (a hash), the result of which is sent to the server.

the server performs the same calculation and compares it to the received value.

Hashing algorithms are not encryption.

10 SecurityIIS Authentication

IIS supports several types of authentication: Certificate

uses certificates as a means of verifying the identity of a given site.

In public-key cryptography, a certificate uses a digital signature to bind together a public key with an identity

The certificate is then used to verify that a public key belongs to an individual.

Certificates must be purchased (generally for about $100 to $500 a year) from a known certificate authority.

11 SecurityIIS Authentication

IIS supports several types of authentication: Integrated Windows Authentication

IIS authenticates the user against a Windows user account.

When used within a corporate intranet, Windows Authentication allows IIS to determine the requester’s identity based on her Windows login.

12 SecurityASP.NET Security

ASP.NET can also be configured to perform its own security checks.

13 SecurityImpersonation

Impersonation refers to the process by which a Web application “pretends” to be a different account than the actual account that is running the application.

14 SecurityImpersonation Impersonation refers to the process

by which a Web application “pretends” to be a different account than the actual account that is running the application.

When impersonation is enabled for a Web application (in the web.config file), the application runs under an identity specified by a security token that is passed by IIS.

This might be used in Web applications that rely on IIS to

authenticate the user, for server environments that host

applications from different customers. Impersonation is often used in such a

situation, because each Web application could be provided with a separate Windows account to absolutely prevent one application from accessing another application’s resources

15 SecurityImpersonation

By default, impersonation is disabled. When disabled, all ASP.NET requests

runs under the default process identity for ASP.NET applications typically either ASPNET (for IIS 5) or

NETWORK SERVICE (for IIS 6). The ASPNET user account is a local

account created when the .NET Framework is installed

the NETWORK SERVICE account is predefined in Windows Server 2003 and has the same set of somewhat limited permissions as the ASPNET account.

16 SecurityCode Access Security

One of the principal security features in .NET is the support in the CLR for code access security. code in an assembly is given a

security zone classification that constrains what types of things the code can do when executing.

Because ASP.NET assemblies are dynamically generated, security policies can be specified declaratively in a trust level.

Thus, a trust level is a declarative set of rules that define what .NET Framework classes your ASP.NET application can use.

Trust levels can be set using the trust element in the application’s Web.config file or globally via the machine.config file.

17 SecurityTrust Levels 17

Trust Name Description

Full The application is fully trusted. All .NET code is allowed to run and thus any .NET classes can be used (however, still subject to operating system and Windows ACL limitations).

This is the default.

High Code can use most of the .NET Framework. The limitations are no unmanaged code, no enterprise services, and limited use of reflection.

Medium Permissions are limited to what the application can access in its own folder structure. Thus, although a medium trust application can access a SQL Server database, it cannot access files or folders outside its own virtual directory hierarchy. As well, it has no reflection permissions, so those applications that require reflection (such as the typical object/relational mapper) may not work.

Intended to be used for hosting environments that contain multiple customers’ sites.

Low Models a read-only application because no network access to other servers is allowed.

Minimal No capability to interact with resources. Intended for sites with little dynamic content.

18 SecurityASP.NET Authentication

Like IIS, ASP.NET has its own authentication methods.

When IIS receives a request for an ASP.NET resource such as an .aspx file, it performs its own authentication and then passes on the request and a security token to the ASP.NET runtime.

The ASP.NET authentication mode is set in the web.config file

<system.web> … <authentication mode="Windows" /></system.web>

19 SecurityASP.NET Authentication ASP.NET supports the following

authentication modes: None

ASP.NET does not perform any authentication. Windows

Uses the result of the configured IIS authentication mechanism.

Generally only makes sense for intranet applications with a known set of users existing in the operating system’s user list.

Forms allows you to authenticate the user via a login

Web form that you create. Unauthenticated requests are redirected to

this login page, where the user can provide credentials and submit the form.

With this mode, the Web application, not the underlying operating system, must authenticate the request.

Because the Web application will perform the authentication, you generally configure IIS to enable anonymous access for this application.

20 SecurityForms Authentication

<system.web> … <authentication mode="Forms" > <forms loginUrl="Login.aspx" /> </authentication>

<authorization> <deny users="?"/> </authorization></system.web>

21 SecurityForms Authentication

You can customize the authentication approach used in your Web application on a folder-by-folder basis by using a separate Web.config file in each folder in your application.

22 SecurityWhere to store user credentials? Application-defined source

Database, etc Within web.config file

Only makes sense for sites with a few users

Use the built-in Membership Provider Uses either SQL Server or Windows

ACL

23 SecurityForm Authentication After the user has been authenticated, any

subsequent requests for allowable ASP.NET resources are processed without requiring authentication again.

When the server receives the request for pageB.aspx, how does the server “know” that the user has already been authenticated? HTTP is a stateless protocol, so some type of

state mechanism must be working behind the scenes

24 SecurityHow does it work?

By default, forms authentication in ASP.NET makes use of a browser cookie to maintain the state of the user’s authentication across requests. The cookie contains an encrypted and

hashed instance of something called a forms authentication ticket.

This ticket contains information that is used by the forms authentication module to identify a previously authenticated user.

25 SecurityHow does it work?

26 SecurityCookieless Tickets

In ASP.NET 2.0, applications can be configured to use cookieless authentication tickets. In this case, the ticket information is

embedded within the URL. A cookie-based ticket can be persistent.

that is, it can last far beyond the individual user session.

This can be a great usability improvement for sites in which their users infrequently visit

Cookieless authentication tickets are especially vulnerable to replay attacks.

E.g., user bookmarks a page on a public computer, then someone else can log-in,

Need to make cookieless authentication timeout values very low (say 60 minutes).

27 SecurityProvider Model

The provider model is one of the chief architectural features of ASP.NET 2.0.

A provider is a software class (or classes) that provide a uniform programming interface between a service and a data source. Thus, a provider is a contract between

the service and its implementation in that it implements a guaranteed interface.

Instead of programming directly against data sources, key ASP.NET services now use providers to read and write data.

28 SecurityProviders

Providers are an abstraction of the physical storage medium. As such, the use of providers makes a

given service very extensible, because you can create your own providers or purchase them from third-party sources.

29 SecurityProvider Model

30 SecurityBenefits of Provider Model

it enforces a separation between the code for accessing a service and the code that implements the service.

makes it easier to implement a division of labor amongst the developers on a project. Back-end developers can work on

custom providers, whereas page developers need only worry about working with the API of the provider.

you can change the specific provider used by a Web application for a service declaratively in the Web.config file without any programming changes.

31 SecurityProvider-based Services

Service Description

Encryption Handles encryption and decryption of sections of the ASP.NET configuration files.

Membership Manages user accounts.

Profile Manages user preferences and user information across visits.

Role management

Handles role-based security.

Session state Maintains user state between requests.

Site map Provides a description of a site’s structure.

Web events Used by ASP.NET health monitoring subsystem that allows the monitoring of a Web application.

Web Parts Manages the special set of controls for creating Web sites that enable end users to modify the content, appearance, and behavior of Web pages directly within the browser.

32 SecurityProvider Classes

33 SecurityMembership Provider

The Membership Provider is a set of classes built on top of the forms authentication system that allows the developer to more easily implement the typical functionality a site needs for managing and authenticating users.

It can be used to: Create new users Store membership information in

Microsoft SQL Server, Active Directory, or some other data source

Authenticates users Use role-based security Manage passwords, which includes

creating, changing, and resetting them

34 SecuritySqlMembership Provider

The default membership provider is the SqlMembershipProvider. It requires some configuration steps

before you can use it in your site. Easiest way to do this is via the

Website Administration Tool (WAT). This is a browser-based application that

can be launched from Visual Studio that allows you to view and modify security, application, and provider configuration settings in the application’s Web.config file.

The WAT creates a SQL Server 2005 Express database file in the Web application’s APP_DATA folder.

35 SecurityWAT

36 SecurityMembership API

The Membership API works quite seamlessly with the ASP.NET login controls. As a result, it is possible to implement

many of the most common security-related user display tasks (such as logging in and out, displaying the current user, and creating a user) without any programming.

For special tasks, such as user management (deleting, renaming, listing), the Membership API can be used.

37 SecurityMembership ClassName DescriptionCreateUser Adds a new user to the membership data store.

DeleteUser Deletes an existing user from the membership data store.

FindUsersByEmail

Returns a MembershipUserCollection of users whose email matches the passed email.

FindUsersByName

Returns a MembershipUserCollection of users whose user name matches the passed user name.

GeneratePassword

Generates a random password of the specified length.

GetAllUsers Returns a MembershipUserCollection of all users.

GetNumberOfUsersOnline

Gets the number of users that is currently accessing the application.

GetUser Returns a MembershipUser object for the current logged on user.

GetUserNameByEmail

Returns the user name for the specified email.

UpdateUser Updates the data source with the information contained in the specified MembershipUser object.

ValidateUser Returns true if the specified user name and password are valid (i.e., exist in the data store).

38 SecurityRole Management Provider

The Role Management Provider and API allows developers to associate users with roles and performs role checks declaratively and programmatically.

Role management lets you treat groups of users as a unit by assigning users to roles that you create, such as administrator, editor, or member.

Default Role provider is the SqlRoleProvider, and can be configured via the WAT.

You can also programmatically manipulate roles via the Role Management API.

39 SecurityLogin Controls

The new ASP.NET login controls work in conjunction with the membership system and provide a quick solution to the typical user interface features needed for authenticating users.

These new controls encapsulate virtually all of the logic required to prompt users for credentials and validate the credentials in the membership system.

40 SecurityLogin Controls

Name Description

ChangePassword Lets users change their password.

CreateUserWizard Based on the Wizard control covered in Chapter 4. A multistep process for gathering the user name, password, email address, and password question and answer.

Login Displays a customizable user interface for gathering user credentials.

LoginName Displays the name of the authenticated user.

LoginStatus Displays a login link for nonauthenticated users and a logout link for authenticated users.

LoginView Displays one of two possible interfaces: one for authenticated users and one for anonymous users.

PasswordRecovery Allows user passwords to be retrieved and sent to the email for that account.

41 SecurityLogin Control

<asp:Login ID="logSignin2" runat="server" TextLayout="TextOnTop" CssClass="loginStyle">

<TitleTextStyle CssClass="loginTitle" /> <InstructionTextStyle Font-Italic="True" ForeColor="Black" /> <TextBoxStyle Font-Size="0.8em" /> <LoginButtonStyle CssClass="buttonStyle" />

</asp:Login>

42 SecurityOther Controls

LoginName Displays the name of the

authenticated user. LoginStatus

displays a login link for nonauthenticated users and a logout link for authenticated users.

43 SecurityLoginName and LoginStatus Controls

<asp:LoginName ID="logName" runat="server" FormatString="Welcome {0}" />

<asp:LoginStatus ID="logStat" runat="server" LoginImageUrl="images/btn_login.gif" LogoutImageUrl="images/btn_logout.gif" LogoutAction="Refresh" />

44 SecurityLoginView Control

allows you to specify a user interface for authenticated users and a different user interface for anonymous users. also allows you to customize the user

interface based on the authenticated user’s role.

For instance, this control could allow you to define content for administrators, content for members, and content for unauthenticated visitors.

45 SecurityLoginView Controls

<asp:LoginView ID="logView" runat="server"> <AnonymousTemplate> <strong>For more features</strong><br /> <asp:LoginStatus ID="logStat" runat="server" LoginImageUrl="images/btn_login.gif" LogoutImageUrl="images/btn_logout.gif" LogoutAction="Refresh" /> </AnonymousTemplate>

<LoggedInTemplate> <strong>Rate this book</strong><br /> <asp:RadioButtonList ID="radList" runat="server"> <asp:ListItem Selected="true"> No Rating</asp:ListItem> <asp:ListItem> <img src='images/stars1.gif'/></asp:ListItem> <asp:ListItem> <img src='images/stars2.gif'/></asp:ListItem> <asp:ListItem> <img src='images/stars3.gif'/></asp:ListItem> <asp:ListItem> <img src='images/stars4.gif'/></asp:ListItem> <asp:ListItem> <img src='images/stars5.gif'/></asp:ListItem> </asp:RadioButtonList> <asp:Button ID="btnRate" runat="server" Text="Rate Book" /> </LoggedInTemplate></asp:LoginView>

46 SecurityChangePassword Control

allows users to change their password.

The control works regardless of whether the user is or is not already authenticated. the control can ask the user for the

user name as well as the old and new passwords.

47 SecurityChangePassword

<asp:ChangePassword ID="chngPass" runat="server" CssClass="passChangeStyle" >

<CancelButtonStyle CssClass="buttonStyle" /> <ChangePasswordButtonStyle CssClass="buttonStyle" /> <ContinueButtonStyle CssClass="buttonStyle" /> <TitleTextStyle CssClass="titleStyle" /> <TextBoxStyle CssClass="textboxStyle" />

</asp:ChangePassword>

48 SecurityPasswordRecovery Control

allows a member’s passwords to be retrieved and sent to the email address for that account.

However, users can only recover passwords when the membership provider supports clear text or encrypted passwords. hashed passwords can only be reset

49 SecurityPasswordRecovery

<asp:PasswordRecovery ID="passRec" runat="server" CssClass="passRecovStyle">

<InstructionTextStyle CssClass="instructionStyle" /> <SuccessTextStyle CssClass="instructionStyle" /> <TextBoxStyle CssClass="textboxStyle" /> <TitleTextStyle CssClass="titleStyle" /> <SubmitButtonStyle CssClass="buttonStyle" />

<MailDefinition From="abc@abc.net" Subject="Password Recovery" />

</asp:PasswordRecovery>

50 SecurityCreateUserWizard Control

provides a multistep process for creating a new user.

It is a subclass of the Wizard control

51 SecurityCreateUserWizard Control

<asp:CreateUserWizard ID="createUser" runat="server" … >

<WizardSteps> <asp:WizardStep > … </asp:WizardStep> <asp:WizardStep > … </asp:WizardStep> </WizardSteps>

</asp:CreateUserWizard>