security for developers web application security steven borg & richard hundhausen accentient,...
TRANSCRIPT
Security for DevelopersSecurity for DevelopersWeb Application SecurityWeb Application Security
Steven Borg & Richard HundhausenSteven Borg & Richard HundhausenAccentient, IncAccentient, Inc
AgendaAgendaOverview of Web SecurityOverview of Web Security
ASP.NET Security ArchitectureASP.NET Security Architecture
Web Service SecurityWeb Service Security
Wrap UpWrap Up
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>
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!
$ 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
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
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%
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.
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
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)
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
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
AgendaAgendaOverview of Web SecurityOverview of Web Security
ASP.NET Security ArchitectureASP.NET Security Architecture
Web Service SecurityWeb Service Security
Wrap UpWrap Up
ASP.NET Security ArchitectureASP.NET Security Architecture
IIS SecurityIIS Security
ASP.NET SecurityASP.NET Security
Principles and IdentitiesPrinciples and Identities
Trust LevelsTrust Levels
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
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?
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?
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"
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
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
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"
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
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="..." ... />
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
ASPNET_SetRegASPNET_SetReg
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.
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
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
););
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.
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
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; ...}
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;}}
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.
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.
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
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.
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
Authentication TicketAuthentication Ticket
Roles & the TicketRoles & the Ticket
RoleRoleCollectionCollection
SQL Server 2000SQL Server 2000
UserDataUserData
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.
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
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
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
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
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
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
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
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
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
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?
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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!
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
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.
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
ResourcesResources
Steve’s Blog: http://blog.accentient.com
Rich’s Blog: http://blog.hundhausen.com
MS Security: http://www.microsoft.com/security
Your FeedbackYour Feedbackis Important!is Important!
Please Fill Out a Survey forPlease Fill Out a Survey forThis Session on CommNetThis Session on CommNet
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.