Top Banner
74

Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Mar 31, 2015

Download

Documents

Katarina Lunn
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.
Page 2: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.
Page 3: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Security for DevelopersSecurity for DevelopersWeb Application SecurityWeb Application Security

Steven Borg & Richard HundhausenSteven Borg & Richard HundhausenAccentient, IncAccentient, Inc

Page 4: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

AgendaAgendaOverview of Web SecurityOverview of Web Security

ASP.NET Security ArchitectureASP.NET Security Architecture

Web Service SecurityWeb Service Security

Wrap UpWrap Up

Page 5: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

This Is Insecure Code!This Is Insecure Code!<html> <body> <form runat="server"> <asp:TextBox ID="Input" runat="server" /> <asp:Button Text="Click Me" OnClick="OnSubmit" runat="server" /> <asp:Label ID="Output" runat="server" /> </form> </body></html>

<script language="C#" runat="server">void OnSubmit (Object sender, EventArgs e){ Output.Text = "Hello, " + Input.Text;}</script>

Page 6: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Why is This Code Insecure?Why is This Code Insecure?

<html> <body> <form runat="server"> <asp:TextBox ID="Input" runat="server" /> <asp:Button Text="Click Me" OnClick="OnSubmit" runat="server" /> <asp:Label ID="Output" runat="server" /> </form> </body></html>

<script language="C#" runat="server">void OnSubmit (Object sender, EventArgs e){ Output.Text = "Hello, " + Input.Text;}</script>

Input is echoed to pagewithout HTML encoding

Input is neither validated norconstrained; user can type anything!

Page 7: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

$ 0.9 Million$ 0.9 Million

$ 0.9 Million$ 0.9 Million

$ 1 Million$ 1 Million

$ 2.7 Million$ 2.7 Million

$ 4 Million$ 4 Million

$ 4.3 Million$ 4.3 Million

$ 6.7 Million$ 6.7 Million

Cost of Security ThreatsCost of Security Threats

Web site defacement

Misuse of public Web applications

Telecom fraud

Sabotage

Unauthorized access

Laptop theft

$ 7.7 Million$ 7.7 MillionFinancial fraud

$ 10.2 Million$ 10.2 MillionAbuse of wireless networks

$ 10.6 Million$ 10.6 MillionInsider abuse of Net access

$ 11.5 Million$ 11.5 MillionTheft of proprietary information

$ 26.1 Million$ 26.1 MillionDenial of service

$ 55.1 Million$ 55.1 MillionViruses

System penetration

Page 8: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Why Security?Why Security?

Reported security breaches in the last 12 months

Acknowledged financial losses as a result

Identified Internet connection as frequent source of attacks

Reported intrusions to authorities

90%

ihttp://www.gocsi.com/press/20020407.html

2002 Computer Crime and Security Survey

80%

74%

34%

Percentages of companies who participated in the survey

Page 9: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

How Does This Happen?How Does This Happen?

Session management 79%

Common Software VulnerabilitiesPercentages of apps that have "serious design flaws" in the indicated areas

Access control 64%

Cryptographic algorithms 61%

Parameter manipulation 73%

Handling of sensitive data 41%

Input validation 32%

Administrative controls 36%

Page 10: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Your DilemmaYour DilemmaPrinciple #1: The defender must defend all points; the attacker can choose the weakest point.

Principle #2: The defender can defend only against known attacks; the attacker can probe for unknown vulnerabilities.

Principle #3: The defender must be constantly vigilant; the attacker can strike at will.

Principle #4: The defender must play by the rules; the attacker can play dirty.

Page 11: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Types of ThreatsTypes of Threats

Spoofed packets, etc.

Buffer overflows, illicit paths, etc.

SQL injection, XSS, input tampering, etc.

Network Host Application

Threats againstthe network

Threats against the host

Threats against the application

Page 12: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Intranet vs. InternetIntranet vs. Internet

Scenario #1: Intranet applicationsScenario #1: Intranet applicationsMost accesses occur from behind firewallMost accesses occur from behind firewall

Serve populations of users defined by Serve populations of users defined by Windows user accountsWindows user accounts

Scenario #2: Internet applicationsScenario #2: Internet applicationsMost accesses occur from outside firewallMost accesses occur from outside firewall

Serve populations of users Serve populations of users notnot defined by defined by Windows user accounts (such as eBay)Windows user accounts (such as eBay)

Page 13: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Intranet ApplicationsIntranet Applications

SQL Server

Bob

Alice

BillIIS ASP.NET

TrustedConnection

Web server Database server

Windowsauthentication

SQL permissionsdatabase roles

Integrated Windowsauthentication

Windowsauthentication

IPSec

A

A

A

A

A

A

ACLACL authorizationauthorization

Page 14: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Internet ApplicationsInternet Applications

SQL Server

Bob

Alice

BillIIS ASP.NET

Trustedconnection

Web server Database server

Windowsauthentication

Anonymous access(no authentication)

Formsauthentication

IPSec

Firew

allF

irewall

SQL permissionsDatabase rolesURL authorizationURL authorization

Page 15: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

AgendaAgendaOverview of Web SecurityOverview of Web Security

ASP.NET Security ArchitectureASP.NET Security Architecture

Web Service SecurityWeb Service Security

Wrap UpWrap Up

Page 16: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ASP.NET Security ArchitectureASP.NET Security Architecture

IIS SecurityIIS Security

ASP.NET SecurityASP.NET Security

Principles and IdentitiesPrinciples and Identities

Trust LevelsTrust Levels

Page 17: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ASP.NET Security ArchitectureASP.NET Security Architecture

Overview of the ASP.NET Security Overview of the ASP.NET Security ArchitectureArchitecture

AuthenticationAuthentication

AuthorizationAuthorization

Process identity (IIS 5 and IIS6)Process identity (IIS 5 and IIS6)

Principle of least privilegePrinciple of least privilege

Using identity and principlesUsing identity and principles

Page 18: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

IIS SecurityIIS Security

AuthenticationAuthenticationAuthenticationAuthentication

AuthorizationAuthorizationAuthorizationAuthorizationWeb Metabase PermissionsWindows Access Controls Lists

AnonymousBasicDigest

SSL/TLSSSL/TLSSSL/TLSSSL/TLS

Who did the request come from?

What is the caller allowed to do?

IP RestrictionsIP RestrictionsIP RestrictionsIP Restrictions Are calls from this IP address allowed?

X.509 CertificatesIntegrated WindowsPassport (IIS 6)

Protection and PoolingProtection and PoolingProtection and PoolingProtection and PoolingWhere should the code execute?

Should traffic be encrypted?

Page 19: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ASP.NET SecurityASP.NET Security

AuthenticationAuthenticationAuthenticationAuthentication

AuthorizationAuthorizationAuthorizationAuthorizationACL authorizationURL authorization

WindowsPassportForms

ImpersonationImpersonationImpersonationImpersonation

Who did the request come from?

What is the caller allowed to do?

Use process identity or caller identity?

Page 20: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Windows AuthenticationWindows Authentication

ACLACL

Ammar IISIIS ASP.NET ASP.NET A ASPXASPXA

IIS creates access token identifying Ammar and passes it to ASP.NET

ASP.NET checks ACL on requested file and fails request if Ammar lacks read permission

Anonymousaccess disabled

Authenticationmode="Windows"

Page 21: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

URLURL

Forms AuthenticationForms Authentication

ASP.NET

ASP.NET

Ammar ASPXASPXLoginPage

LoginPage T

URLURL

ASP.NET

ASP.NET

Ammar ASPXASPXT

First access - Redirect to login page

Next access - Authenticated access to ASPX

Authentication ticket

Page 22: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ASP.NET AuthorizationASP.NET AuthorizationACL authorizationACL authorization

Typically combined with Windows authTypically combined with Windows auth

Uses NTFS permissions to control access to Uses NTFS permissions to control access to resources based on caller's Windows resources based on caller's Windows identityidentity

Does not require impersonation!Does not require impersonation!

URL authorizationURL authorizationOften combined with forms authenticationOften combined with forms authentication

Controls access to resources based on Controls access to resources based on caller's Windows, Passport, or forms identitycaller's Windows, Passport, or forms identity

Applied in Web.configApplied in Web.config

Page 23: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ACLACL

ACL AuthorizationACL Authorization

Bob IISIIS ASP.NETASP.NETA ASPXASPXA

IIS creates access token identifying Bob and passes it to ASP.NET

ASP.NET checks ACL on requested file and fails request if Bob lacks read permission

A

Anonymous access not permitted

Authenticationmode="Windows"

Page 24: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

URL AuthorizationURL Authorization

<!-- Deny access to anonymous/unauthenticated users --><deny users="?" />

<!-- Grant access to Bob and Alice but no one else --><allow users="Bob, Alice" /><deny users="*" />

<!-- Grant access to everyone EXCEPT Bob and Alice --><deny users="John, Alice" /><allow users="*" />

<!-- Grant access to any manager --><allow roles="Manager" /><deny users="*" />

Web.config

Page 25: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Process IdentityProcess Identity

IIS 6IIS 6Configurable per application poolConfigurable per application pool

Credentials managed by IISCredentials managed by IIS

IIS 5IIS 5Identity shared by all WPs on Web serverIdentity shared by all WPs on Web server

Credentials stored in Machine.configCredentials stored in Machine.config

<processModel userName="MyDomain\MyUserName" password="..." ... />

Page 26: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Securing Process CredentialsSecuring Process Credentials

On IIS 5, use Aspnet_setregOn IIS 5, use Aspnet_setreg

ASP.NET 1.1 only; hotfix for 1.0ASP.NET 1.1 only; hotfix for 1.0

<processModel ... userName="registry:HKLM\SOFTWARE\App\Identity\ASPNET_SETREG,userName" password="registry:HKLM\SOFTWARE\App\Identity\ASPNET_SETREG,password"/>

Machine.config

Registry

Page 27: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ASPNET_SetRegASPNET_SetReg

Page 28: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Before We Continue…Before We Continue… Don’t Forget! Don’t Forget!

IIS 6.0 handles ALL of this for you.IIS 6.0 handles ALL of this for you.

You can still use this method, however You can still use this method, however IIS 6.0 Application Pools are much IIS 6.0 Application Pools are much better.better.

Best Practice: Use IIS 6.0 Application Best Practice: Use IIS 6.0 Application Pools and let IIS manage the Pools and let IIS manage the credentials.credentials.

Page 29: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Security PrincipalsSecurity Principals

Windows represents security principals Windows represents security principals with access tokenswith access tokens

.NET Framework represents security .NET Framework represents security principals with security principal principals with security principal objectsobjects

Abstracts the authentication typeAbstracts the authentication type

Enables you to write (mostly) generic code Enables you to write (mostly) generic code to query for user names, do role checks, to query for user names, do role checks, etc.etc.

Principal objects expose useful data Principal objects expose useful data about usersabout users

Page 30: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Authentication TicketAuthentication TicketFormsAuthenticationTicket ticket = new FormsAuthenticationTicket( FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

1,1, // Version// VersionuserInfo.Username, userInfo.Username, // Identity// IdentityDateTime.Now, DateTime.Now, // Time issued// Time issuedDateTime.Now.AddMinutes(30), DateTime.Now.AddMinutes(30), // Expiration date// Expiration datefalse, false, // Is persistent// Is persistentuserInfo.RolesArray userInfo.RolesArray // User data// User dataFormsAuthentication.FormsCookiePathFormsAuthentication.FormsCookiePath // Path// Path););

String encTicket = FormsAuthentication.Encrypt( ticket );String encTicket = FormsAuthentication.Encrypt( ticket );

Response.Cookies.Add(Response.Cookies.Add(new HttpCookie( FormsAuthentication.FormsCookieName,new HttpCookie( FormsAuthentication.FormsCookieName,

encTicketencTicket))

););

Response.Redirect( Response.Redirect( FormsAuthentication.GetRedirectUrl(FormsAuthentication.GetRedirectUrl( userInfo.Username,userInfo.Username, false false

););

Page 31: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

AuthenticateRequest EventAuthenticateRequest Event

Capture the current security principal Capture the current security principal object.object.

Capture the role information from the Capture the role information from the authentication ticket.authentication ticket.

Create a new principal object with the Create a new principal object with the roles from the ticket.roles from the ticket.

Change the current user context to the Change the current user context to the new principal object.new principal object.

Page 32: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Security Principal ObjectsSecurity Principal Objects

GenericPrincipalWindowsPrincipal

GenericPrincipalWindowsPrincipal

IPrincipalFormsIdentityWindowsIdentityPassportIdentityGenericIdentity

IIdentity

A

Identity object encapsulates Windows access token if type is WindowsIdentity

Identity object's IIdentity interface exposed as principal object's IPrincipal.Identity property

Page 33: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

IPrincipal and IIdentityIPrincipal and IIdentity// Find out whether the caller is authenticatedif (HttpContext.Current.User.Identity.IsAuthenticated) { // The caller is authenticated}

// Get an authenticated caller's user namestring name = HttpContext.Current.User.Identity.Name;

// Perform a programmatic role checkif (HttpContext.Current.User.IsInRole ("Managers") { // The caller is a manager}

// Get the caller's access tokenif (HttpContext.Current.User.Identity is WindowsIdentity) { IntPtr token = ((WindowsIdentity) HttpContext.Current.User.Identity).Token; ...}

Page 34: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

AuthenticateRequest EventAuthenticateRequest Event

if(context.User.Identity.IsAuthenticated){if(context.User.Identity.IsAuthenticated){ GenericPrincipal oldPrincipal = HttpContext.Current.User;GenericPrincipal oldPrincipal = HttpContext.Current.User;

FormsIdentity formsIdent = FormsIdentity formsIdent = (FormsIdentity)oldPrincipal.Identity;(FormsIdentity)oldPrincipal.Identity;

FormsAuthenticationTicket ticket = FormsAuthenticationTicket ticket = FormsAuthenticationTicket = formsIdent.Ticket;FormsAuthenticationTicket = formsIdent.Ticket;

GenericPrincipal newPrincipal = new GenericPrincipal(GenericPrincipal newPrincipal = new GenericPrincipal( oldPrincipal.Identity, oldPrincipal.Identity,

ticket.UserData.Split(";")ticket.UserData.Split(";")););

HttpContext.Current.User = newPrincipal;HttpContext.Current.User = newPrincipal;}}

Page 35: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Identity ObjectIdentity Object

Encapsulates information about the Encapsulates information about the user or entity being validated. user or entity being validated.

At their most basic level, identity At their most basic level, identity objects contain:objects contain:

The user’s name.The user’s name.

An authentication type (i.e. “Forms”).An authentication type (i.e. “Forms”).

Implements the IIdentity interface.Implements the IIdentity interface.

Page 36: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Principal ObjectPrincipal Object

Represents the security context under Represents the security context under which code is running, including:which code is running, including:

That user's identity.That user's identity.

Any roles to which the user belongs.Any roles to which the user belongs.

Applications grant rights based on the Applications grant rights based on the role associated with a principal object .role associated with a principal object .

Use the principal object to perform Use the principal object to perform authorization.authorization.

Implements the IPrincipal interface.Implements the IPrincipal interface.

Page 37: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Security Principal InstanceSecurity Principal Instance

Identity object's IIdentity interface is Identity object's IIdentity interface is exposed as principal object's exposed as principal object's IPrincipal.Identity propertyIPrincipal.Identity property

IsInRole()IsInRole()IdentityIdentityIsInRole()IsInRole()IdentityIdentity

NameNameIsAuthenticatedIsAuthenticatedAuthenticationTypeAuthenticationType

NameNameIsAuthenticatedIsAuthenticatedAuthenticationTypeAuthenticationType

IIdentityIIdentity

IPrincipalIPrincipal

Page 38: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Security Events in Page Security Events in Page LifecycleLifecycle

Application.AuthenticateRequestApplication.AuthenticateRequestOccurs after BeginRequest.Occurs after BeginRequest.HttpContext is available.HttpContext is available.Create the identity and principal objects Create the identity and principal objects here.here.

Application.AuthorizeRequestApplication.AuthorizeRequestOccurs before AquireRequestState.Occurs before AquireRequestState.Handle any custom authorization here.Handle any custom authorization here.

Session state does not become Session state does not become accessible until after both of these accessible until after both of these events.events.

Page 39: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Forms Authentication - RolesForms Authentication - RolesHandle AuthenticateRequest eventHandle AuthenticateRequest event

Create GenericPrincipleCreate GenericPrinciple

Attach roles to IdentityAttach roles to Identity

Assign new Principle to UserAssign new Principle to UserSub Application_AuthenticateRequest(s As Object,

e As EventArgs) If Not (User Is Nothing) Then If User.Identity.AuthenticationType = "Forms" Then Dim Roles(1) As String Roles(0) = "Admin" User = new GenericPrinciple(User.Identity,Roles) End If End IfEnd Sub

Page 40: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Authentication TicketAuthentication Ticket

Roles & the TicketRoles & the Ticket

RoleRoleCollectionCollection

SQL Server 2000SQL Server 2000

UserDataUserData

Page 41: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Authentication TicketAuthentication Ticket

You can include role data in the You can include role data in the authentication ticket.authentication ticket.

Authentication ticket is persisted in a Authentication ticket is persisted in a cookie.cookie.

Authentication ticket information is Authentication ticket information is encrypted in the cookie.encrypted in the cookie.

You should never use a persistent You should never use a persistent cookie.cookie.

Page 42: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ASP.NET 2.0ASP.NET 2.0

In ASP.NET 2.0, all this is done for you.In ASP.NET 2.0, all this is done for you.

Membership ServiceMembership ServiceRepresents usersRepresents users

Provider-basedProvider-based

Role Management ServiceRole Management ServiceRepresents RolesRepresents Roles

Users map to zero to many rolesUsers map to zero to many roles

Provider-basedProvider-based

Page 43: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Membership ServiceMembership ServiceService for managing users and Service for managing users and credentialscredentials

Declarative access via Web Site Admin Declarative access via Web Site Admin ToolTool

Programmatic access via Membership and Programmatic access via Membership and MembershipUser classesMembershipUser classes

Membership class provides base Membership class provides base servicesservices

MembershipUser class represents MembershipUser class represents users and provides additional servicesusers and provides additional services

Provider-based for flexible data storageProvider-based for flexible data storage

Page 44: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Membership SchemaMembership Schema

Membership API

MembershipData

Access OtherData Stores

Controls LoginLogin LoginStatusLoginStatus LoginViewLoginView

AccessMembershipProviderAccessMembershipProvider Other MembershipProviders

Other MembershipProviders

Membership Providers

MembershipMembership MembershipUserMembershipUser

SqlMembershipProviderSqlMembershipProvider

SQL Server

Other LoginControls

Other LoginControls

Page 45: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

The Membership ClassThe Membership Class

Provides static methods for performing Provides static methods for performing key membership taskskey membership tasks

Creating and deleting usersCreating and deleting users

Retrieving information about usersRetrieving information about users

Generating random passwordsGenerating random passwords

Validating loginsValidating logins

Also includes read-only static Also includes read-only static properties for acquiring data about properties for acquiring data about provider settingsprovider settings

Page 46: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

The MembershipUser ClassThe MembershipUser Class

Represents individual users registered Represents individual users registered in the membership data storein the membership data store

Includes numerous properties for Includes numerous properties for getting and setting user infogetting and setting user info

Includes methods for retrieving, Includes methods for retrieving, changing, and resetting passwordschanging, and resetting passwords

Returned by Membership methods Returned by Membership methods such as GetUser and CreateUsersuch as GetUser and CreateUser

Page 47: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Membership ProvidersMembership Providers

Membership is provider-basedMembership is provider-basedProvider provides interface between Provider provides interface between membership service and physical data membership service and physical data storestore

Beta 1 ships with two providersBeta 1 ships with two providersAccessMembershipProvider (Access)*AccessMembershipProvider (Access)*

SqlMembershipProvider (SQL Server)SqlMembershipProvider (SQL Server)

Use custom providers for other data Use custom providers for other data storesstores

* Has been replaced by SQL Express provider in beta 2

Page 48: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Role Management ServiceRole Management ServiceRole-based security in a boxRole-based security in a box

Declarative access via Web Site Admin ToolDeclarative access via Web Site Admin Tool

Programmatic access via Roles classProgrammatic access via Roles class

Roles class contains static methods for Roles class contains static methods for creating roles, adding users to roles, etc.creating roles, adding users to roles, etc.

Maps users to roles on each requestMaps users to roles on each requestReplaces Application_AuthenticateRequestReplaces Application_AuthenticateRequest

Provider-based for flexible data storageProvider-based for flexible data storage

Page 49: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Role Management SchemaRole Management Schema

Roles API

Roles Data

AccessOther

Data Stores

Controls LoginLogin LoginStatusLoginStatus LoginViewLoginView

AccessRoleProviderAccessRoleProvider Other Role ProvidersOther Role Providers

Role Providers

RolesRoles

SqlRoleProviderSqlRoleProvider

SQL Server

Other LoginControls

Other LoginControls

Page 50: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

The Roles ClassThe Roles Class

Gateway to the Role Management APIGateway to the Role Management API

Provides static methods for performing Provides static methods for performing key role management taskskey role management tasks

Creating and deleting rolesCreating and deleting roles

Adding users to rolesAdding users to roles

Removing users from roles and moreRemoving users from roles and more

Also includes read-only static Also includes read-only static properties for acquiring data about properties for acquiring data about provider settingsprovider settings

Page 51: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Role CachingRole CachingRole manager offers option for caching Role manager offers option for caching role data in cookiesrole data in cookies

Fewer accesses to data storeFewer accesses to data store

Better performanceBetter performance

Controlled via <roleManager> attributes Controlled via <roleManager> attributes and programmatically exposed thru and programmatically exposed thru Roles classRoles class

Should roles be cached in cookies?Should roles be cached in cookies?

Should role cookies be encrypted?Should role cookies be encrypted?

How long are role cookies valid?How long are role cookies valid?

Page 52: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Role Management ProvidersRole Management Providers

Role management is provider-basedRole management is provider-based

Beta 1 ships with four providersBeta 1 ships with four providersAccessRoleProvider (Access)*AccessRoleProvider (Access)*

AuthorizationStoreRoleProvider (AuthMan)AuthorizationStoreRoleProvider (AuthMan)

SqlRoleProvider (SQL Server)SqlRoleProvider (SQL Server)

WindowsTokenRoleProvider (Windows)WindowsTokenRoleProvider (Windows)

Use custom providers for other data Use custom providers for other data storesstores

* Will be replaced by SQL Express provider in beta 2

Page 53: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ASP.NET Trust LevelsASP.NET Trust Levels

Trust LevelTrust Level CAS Restrictions (Cumulative)CAS Restrictions (Cumulative)FullFull NoneNone

HighHigh Can't access Windows event logCan't access Windows event log

Can't access OLE DB data sourcesCan't access OLE DB data sources

Can't call unmanaged codeCan't call unmanaged code

MediumMedium Limited access to environment variablesLimited access to environment variables

File I/O limited to own directory hiveFile I/O limited to own directory hive

Can't access registryCan't access registry

Can't perform reflectionCan't perform reflection

Can't call remote serversCan't call remote servers

Can only call local Web servicesCan only call local Web services

LowLow Can't access environment variablesCan't access environment variables

File I/O limited to reading from own directory hiveFile I/O limited to reading from own directory hive

Can't access SQL Server databasesCan't access SQL Server databases

Can't call Web servicesCan't call Web services

MinimalMinimal Can't do much of anythingCan't do much of anything

Page 54: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Full TrustFull Trust

UnmanagedCode

UnmanagedCode

RegistryRegistry

DNSDNS

EnvironmentVariables

EnvironmentVariables

Web ServicesWeb Services Remote ServersRemote Servers

WindowsEvent Log

WindowsEvent Log

File SystemFile System

SQL ServerSQL Server

OLE DBOLE DB

ApplicationApplication

SecurityPermission.-UnmanagedCode

RegistryPermission

SqlClientPermission

OleDbClientPermission

FileIOPermission

EventLogPermission

SocketsPermission

WebPermission

EnvironmentPermission

DnsPermission

Page 55: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

High TrustHigh Trust

UnmanagedCode

UnmanagedCode

RegistryRegistry

DNSDNS

EnvironmentVariables

EnvironmentVariables

Web ServicesWeb Services Remote ServersRemote Servers

WindowsEvent Log

WindowsEvent Log

File SystemFile System

SQL ServerSQL Server

OLE DBOLE DB

ApplicationApplication

RegistryPermission

SqlClientPermission

FileIOPermission

EventLogPermission

SocketsPermission

WebPermission

EnvironmentPermission

DnsPermission

Page 56: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Restricted

Restricted

Restricted

Medium TrustMedium Trust

UnmanagedCode

UnmanagedCode

RegistryRegistry

DNSDNS

EnvironmentVariables

EnvironmentVariables

Web ServicesWeb Services Remote ServersRemote Servers

WindowsEvent Log

WindowsEvent Log

File SystemFile System

SQL ServerSQL Server

OLE DBOLE DB

ApplicationApplication

SqlClientPermission

FileIOPermission

WebPermission

EnvironmentPermission

DnsPermission

Page 57: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Low TrustLow Trust

Heavily Restricted

UnmanagedCode

UnmanagedCode

RegistryRegistry

DNSDNS

EnvironmentVariables

EnvironmentVariables

Web ServicesWeb Services Remote ServersRemote Servers

WindowsEvent Log

WindowsEvent Log

File SystemFile System

SQL ServerSQL Server

OLE DBOLE DB

ApplicationApplication

FileIOPermission

Page 58: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

AgendaAgendaOverview of Web SecurityOverview of Web Security

ASP.NET Security ArchitectureASP.NET Security Architecture

Microsoft Reference Application for Microsoft Reference Application for OpenHackOpenHack

Web Service SecurityWeb Service Security

Wrap UpWrap Up

Page 59: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

What is OpenHack?What is OpenHack?

Regular contest sponsored by eWEEKRegular contest sponsored by eWEEK

Who can build most hack-resistant Web Who can build most hack-resistant Web app?app?

Participants build app to eWEEK specsParticipants build app to eWEEK specs

eWEEK invites all comers to hack iteWEEK invites all comers to hack it

2002 participants: Microsoft and Oracle2002 participants: Microsoft and Oracle

ihttp://www.eweek.com/article2/0,3959,741388,00.asp

Page 60: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Microsoft Reference Microsoft Reference Application for OpenHackApplication for OpenHack

Microsoft's entry in the 2002 Microsoft's entry in the 2002 competitioncompetition

Withstood 80,000+ attacks without a Withstood 80,000+ attacks without a single breach of securitysingle breach of security

Written by Vertigo Software and Written by Vertigo Software and MicrosoftMicrosoft

Code updated since the competitionCode updated since the competition

You get the latest version!You get the latest version!

Great example of Great example of how to do security how to do security rightright

Page 61: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Application ArchitectureApplication Architecture

AwardsDatabase

AwardsDatabase

ASP.NETASP.NET

ValidationLayer

Data AccessLayer

ProtectionLayer

IISIIS

Public

RegistryRegistry DPAPIDPAPI

Anonymousaccess

Forms authenticationURL authorization

Trustedconnection

Windowsauthentication

Decryptionkeys

Connectionstrings etc.

Private

SQLpermissions

Page 62: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Forms AuthenticationForms Authentication

Two-tiered directory structureTwo-tiered directory structureRoot contains "public" pages (including Root contains "public" pages (including the login page)the login page)

"Secure" subdirectory contains pages that "Secure" subdirectory contains pages that require loginsrequire logins

Forms authentication cookieForms authentication cookieAlways temporary, never persistentAlways temporary, never persistent

30-minute time-out30-minute time-out

Cookie path set to app directoryCookie path set to app directory

Page 63: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Input ValidationInput ValidationUser input constrained by validation User input constrained by validation controlscontrols

Input and output sanitized by validation Input and output sanitized by validation layerlayer

PagesPages

All Input

Sanitize

Other Input

ValidationControls

User Input

Output

HTML-Encode

CleanStringCleanString

Page 64: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Awards Database SecurityAwards Database SecurityUsersUsers

One account: webuser (Windows One account: webuser (Windows principal)principal)

Maps to ASP.NET worker process identityMaps to ASP.NET worker process identity

Stored ProceduresStored Procedures30 stored procedures30 stored procedures

Used for all interaction with databaseUsed for all interaction with database

PermissionsPermissionswebuser permitted to call stored procswebuser permitted to call stored procs

"public" granted no permissions anywhere"public" granted no permissions anywhere

Page 65: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Data AccessData Access

Multitiered data access layerMultitiered data access layer

All accesses via stored proceduresAll accesses via stored procedures

All accesses performed by webuserAll accesses performed by webuser

Windows authentication to SQL ServerWindows authentication to SQL Server

Connection string DPAPI-encrypted Connection string DPAPI-encrypted and stored in ACLed registry keyand stored in ACLed registry key

Page 66: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Data ProtectionData ProtectionRegistry secretsRegistry secrets

HKLM\Software\Microsoft\OpenHack4HKLM\Software\Microsoft\OpenHack4DPAPI-encrypted connection stringDPAPI-encrypted connection string

DPAPI-encrypted crypto decryption keyDPAPI-encrypted crypto decryption key

DPAPI-encrypted crypto initialization vector (IV)DPAPI-encrypted crypto initialization vector (IV)

DPAPI entropy valueDPAPI entropy value

ACL grants full control to admins and ACL grants full control to admins and SYSTEM, read access to ASP.NET worker SYSTEM, read access to ASP.NET worker processprocess

Database secretsDatabase secretsEncrypted passwordsEncrypted passwords

Encrypted credit card numbersEncrypted credit card numbers

Page 67: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Error Handling and LoggingError Handling and LoggingDefault error pageDefault error page

defaultRedirect points to Error.aspxdefaultRedirect points to Error.aspx

Provides generic response to errorsProvides generic response to errors

Application_ErrorApplication_ErrorLogs unhandled exceptions in Windows Logs unhandled exceptions in Windows event logevent log

Includes stack trace and other rich error Includes stack trace and other rich error infoinfo

Failed loginsFailed loginsLogged separately in Windows event logLogged separately in Windows event log

Aid in forensic analysis and intrusion Aid in forensic analysis and intrusion detectiondetection

Page 68: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

SummarySummaryMS Reference Application for OpenHackMS Reference Application for OpenHack

MRAO scrubs and validates inputMRAO scrubs and validates input

MRAO accesses data securelyMRAO accesses data securely

MRAO encrypts sensitive dataMRAO encrypts sensitive data

MRAO uses forms authentication and MRAO uses forms authentication and URL authorizationURL authorization

MRAO handles errors securely and MRAO handles errors securely and logs them as appropriatelogs them as appropriate

MRAO is a secure application!MRAO is a secure application!

Page 69: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

AgendaAgendaOverview of Web SecurityOverview of Web Security

ASP.NET Security ArchitectureASP.NET Security Architecture

Microsoft Reference Application for Microsoft Reference Application for OpenHackOpenHack

Wrap UpWrap Up

Page 70: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

RantRantDo not store passwords either in clear Do not store passwords either in clear text or with reversible encryption!text or with reversible encryption!

Makes me angry.Makes me angry.

Page 71: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Storing Login PasswordsStoring Login Passwords

FormatFormat CommentsCommentsPlaintext passwordsPlaintext passwords Exposes entire application if database is Exposes entire application if database is

compromisedcompromised

Encrypted passwordsEncrypted passwords Better than plaintext, but still vulnerable if Better than plaintext, but still vulnerable if decryption key is compromiseddecryption key is compromised

1-way password 1-way password hasheshashes

Better than encrypted passwords, but still Better than encrypted passwords, but still vulnerable to dictionary attacksvulnerable to dictionary attacks

Salted password Salted password hasheshashes Less vulnerable to dictionary attacksLess vulnerable to dictionary attacks

Don't store passwords in login databasesDon't store passwords in login databases

Store password hashes for added Store password hashes for added securitysecurity

Salt hashes to impede dictionary attacksSalt hashes to impede dictionary attacks

Page 72: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

ResourcesResources

Steve’s Blog: http://blog.accentient.com

Rich’s Blog: http://blog.hundhausen.com

MS Security: http://www.microsoft.com/security

Page 73: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

Your FeedbackYour Feedbackis Important!is Important!

Please Fill Out a Survey forPlease Fill Out a Survey forThis Session on CommNetThis Session on CommNet

Page 74: Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc.

© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.