Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Security for Developers Web Application Security Steven Borg & Richard Hundhausen Accentient, Inc."— Presentation transcript:

1

2

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

4 Agenda Overview of Web Security ASP.NET Security Architecture Web Service Security Wrap Up

5 This Is Insecure Code! <asp:Button Text="Click Me" OnClick="OnSubmit" runat="server" /> void OnSubmit (Object sender, EventArgs e) { Output.Text = "Hello, " + Input.Text; }

6 Why is This Code Insecure? <asp:Button Text="Click Me" OnClick="OnSubmit" runat="server" /> void OnSubmit (Object sender, EventArgs e) { Output.Text = "Hello, " + Input.Text; } Input is echoed to page without HTML encoding Input is neither validated nor constrained; user can type anything!

7 $ 0.9 Million $ 1 Million $ 2.7 Million $ 4 Million $ 4.3 Million $ 6.7 Million Cost of Security Threats Web site defacement Misuse of public Web applications Telecom fraud Sabotage Unauthorized access Laptop theft $ 7.7 Million Financial fraud $ 10.2 Million Abuse of wireless networks $ 10.6 Million Insider abuse of Net access $ 11.5 Million Theft of proprietary information $ 26.1 Million Denial of service $ 55.1 Million Viruses System penetration

8 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% i http://www.gocsi.com/press/20020407.html 2002 Computer Crime and Security Survey 80% 74% 34% Percentages of companies who participated in the survey

9 How Does This Happen? Session management 79% Common Software Vulnerabilities Percentages 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%

10 Your Dilemma Principle #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.

11 Types of Threats Spoofed packets, etc. Buffer overflows, illicit paths, etc. SQL injection, XSS, input tampering, etc. NetworkHostApplication Threats against the network Threats against the host Threats against the application

12 Intranet vs. Internet Scenario #1: Intranet applications Most accesses occur from behind firewall Serve populations of users defined by Windows user accounts Scenario #2: Internet applications Most accesses occur from outside firewall Serve populations of users not defined by Windows user accounts (such as eBay)

13 Intranet Applications SQL Server Bob Alice Bill IIS ASP.NET Trusted Connection Web serverDatabase server Windows authentication SQL permissions database roles Integrated Windows authentication Windows authentication IPSec A A A A A A ACL authorization authorization

14 Internet Applications SQL Server Bob Alice Bill IISASP.NET Trusted connection Web serverDatabase server Windows authentication Anonymous access (no authentication) Forms authentication IPSec Firewall SQL permissions Database roles URL authorization

15 Agenda Overview of Web Security ASP.NET Security Architecture Web Service Security Wrap Up

16 ASP.NET Security Architecture IIS Security ASP.NET Security Principles and Identities Trust Levels

17 ASP.NET Security Architecture Overview of the ASP.NET Security Architecture AuthenticationAuthorization Process identity (IIS 5 and IIS6) Principle of least privilege Using identity and principles

18 IIS Security AuthenticationAuthentication AuthorizationAuthorization Web Metabase Permissions Windows Access Controls Lists Anonymous Basic Digest SSL/TLSSSL/TLS Who did the request come from? What is the caller allowed to do? IP Restrictions Are calls from this IP address allowed? X.509 Certificates Integrated Windows Passport (IIS 6) Protection and Pooling Where should the code execute? Should traffic be encrypted?

19 ASP.NET Security AuthenticationAuthentication AuthorizationAuthorization ACL authorization URL authorization Windows Passport Forms ImpersonationImpersonation Who did the request come from? What is the caller allowed to do? Use process identity or caller identity?

20 Windows Authentication ACL Ammar IIS ASP.NET A ASPX A 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 Anonymous access disabled Authentication mode="Windows"

21 URL Forms Authentication ASP. NET ASP. NET Ammar ASPX Login Page Login Page T URL ASP. NET ASP. NET Ammar ASPX T First access - Redirect to login page Next access - Authenticated access to ASPX Authentication ticket

22 ASP.NET Authorization ACL authorization Typically combined with Windows auth Uses NTFS permissions to control access to resources based on caller's Windows identity Does not require impersonation! URL authorization Often combined with forms authentication Controls access to resources based on caller's Windows, Passport, or forms identity Applied in Web.config

23 ACL ACL Authorization Bob IIS ASP.NET A ASPX A 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 Authentication mode="Windows"

24 URL Authorization Web.config

25 Process Identity IIS 6 Configurable per application pool Credentials managed by IIS IIS 5 Identity shared by all WPs on Web server Credentials stored in Machine.config <processModel userName="MyDomain\MyUserName" password="..."... />

26 Securing Process Credentials On IIS 5, use Aspnet_setreg ASP.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

27 ASPNET_SetReg

28 Before We Continue… Don’t Forget! IIS 6.0 handles ALL of this for you. You can still use this method, however IIS 6.0 Application Pools are much better. Best Practice: Use IIS 6.0 Application Pools and let IIS manage the credentials.

29 Security Principals Windows represents security principals with access tokens.NET Framework represents security principals with security principal objects Abstracts the authentication type Enables you to write (mostly) generic code to query for user names, do role checks, etc. Principal objects expose useful data about users

30 Authentication Ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1,// Version userInfo.Username, // Identity DateTime.Now, // Time issued DateTime.Now.AddMinutes(30), // Expiration date false, // Is persistent userInfo.RolesArray // User data FormsAuthentication.FormsCookiePath// Path ); String encTicket = FormsAuthentication.Encrypt( ticket ); Response.Cookies.Add( new HttpCookie( FormsAuthentication.FormsCookieName, encTicket));Response.Redirect( FormsAuthentication.GetRedirectUrl( FormsAuthentication.GetRedirectUrl( userInfo.Username, userInfo.Username, false false);

31 AuthenticateRequest Event Capture the current security principal object. Capture the role information from the authentication ticket. Create a new principal object with the roles from the ticket. Change the current user context to the new principal object.

32 Security Principal Objects GenericPrincipal WindowsPrincipal GenericPrincipal WindowsPrincipal IPrincipal FormsIdentity WindowsIdentity PassportIdentity GenericIdentity 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

33 IPrincipal and IIdentity // Find out whether the caller is authenticated if (HttpContext.Current.User.Identity.IsAuthenticated) { // The caller is authenticated } // Get an authenticated caller's user name string name = HttpContext.Current.User.Identity.Name; // Perform a programmatic role check if (HttpContext.Current.User.IsInRole ("Managers") { // The caller is a manager } // Get the caller's access token if (HttpContext.Current.User.Identity is WindowsIdentity) { IntPtr token = ((WindowsIdentity) HttpContext.Current.User.Identity).Token;... }

34 AuthenticateRequest Event 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;}

35 Identity Object Encapsulates information about the user or entity being validated. At their most basic level, identity objects contain: The user’s name. An authentication type (i.e. “Forms”). Implements the IIdentity interface.

36 Principal Object Represents the security context under which code is running, including: That user's identity. Any roles to which the user belongs. Applications grant rights based on the role associated with a principal object. Use the principal object to perform authorization. Implements the IPrincipal interface.

37 Security Principal Instance Identity object's IIdentity interface is exposed as principal object's IPrincipal.Identity property IsInRole()IdentityIsInRole()Identity NameIsAuthenticatedAuthenticationTypeNameIsAuthenticatedAuthenticationType IIdentity IPrincipal

38 Security Events in Page Lifecycle Application.AuthenticateRequest Occurs after BeginRequest. HttpContext is available. Create the identity and principal objects here. Application.AuthorizeRequest Occurs before AquireRequestState. Handle any custom authorization here. Session state does not become accessible until after both of these events.

39 Forms Authentication - Roles Handle AuthenticateRequest event Create GenericPrinciple Attach roles to Identity Assign new Principle to User Sub 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 Sub

40 Authentication Ticket Roles & the Ticket RoleCollection SQL Server 2000 UserData

41 Authentication Ticket You can include role data in the authentication ticket. Authentication ticket is persisted in a cookie. Authentication ticket information is encrypted in the cookie. You should never use a persistent cookie.

42 ASP.NET 2.0 In ASP.NET 2.0, all this is done for you. Membership Service Represents users Provider-based Role Management Service Represents Roles Users map to zero to many roles Provider-based

43 Membership Service Service for managing users and credentials Declarative access via Web Site Admin Tool Programmatic access via Membership and MembershipUser classes Membership class provides base services MembershipUser class represents users and provides additional services Provider-based for flexible data storage

44 Membership Schema Membership API Membership Data Access Other Data Stores Controls Login LoginStatus LoginView AccessMembershipProvider Other Membership Providers Other Membership Providers Membership Providers Membership MembershipUser SqlMembershipProvider SQL Server Other Login Controls Other Login Controls

45 The Membership Class Provides static methods for performing key membership tasks Creating and deleting users Retrieving information about users Generating random passwords Validating logins Also includes read-only static properties for acquiring data about provider settings

46 The MembershipUser Class Represents individual users registered in the membership data store Includes numerous properties for getting and setting user info Includes methods for retrieving, changing, and resetting passwords Returned by Membership methods such as GetUser and CreateUser

47 Membership Providers Membership is provider-based Provider provides interface between membership service and physical data store Beta 1 ships with two providers AccessMembershipProvider (Access)* SqlMembershipProvider (SQL Server) Use custom providers for other data stores * Has been replaced by SQL Express provider in beta 2

48 Role Management Service Role-based security in a box Declarative access via Web Site Admin Tool Programmatic access via Roles class Roles class contains static methods for creating roles, adding users to roles, etc. Maps users to roles on each request Replaces Application_AuthenticateRequest Provider-based for flexible data storage

49 Role Management Schema Roles API Roles Data Access Other Data Stores Controls Login LoginStatus LoginView AccessRoleProvider Other Role Providers Role Providers Roles SqlRoleProvider SQL Server Other Login Controls Other Login Controls

50 The Roles Class Gateway to the Role Management API Provides static methods for performing key role management tasks Creating and deleting roles Adding users to roles Removing users from roles and more Also includes read-only static properties for acquiring data about provider settings

51 Role Caching Role manager offers option for caching role data in cookies Fewer accesses to data store Better performance Controlled via attributes and programmatically exposed thru Roles class Should roles be cached in cookies? Should role cookies be encrypted? How long are role cookies valid?

52 Role Management Providers Role management is provider-based Beta 1 ships with four providers AccessRoleProvider (Access)* AuthorizationStoreRoleProvider (AuthMan) SqlRoleProvider (SQL Server) WindowsTokenRoleProvider (Windows) Use custom providers for other data stores * Will be replaced by SQL Express provider in beta 2

53 ASP.NET Trust Levels Trust Level CAS Restrictions (Cumulative) FullNone High Can't access Windows event log Can't access Windows event log Can't access OLE DB data sources Can't access OLE DB data sources Can't call unmanaged code Can't call unmanaged code Medium Limited access to environment variables Limited access to environment variables File I/O limited to own directory hive File I/O limited to own directory hive Can't access registry Can't access registry Can't perform reflection Can't perform reflection Can't call remote servers Can't call remote servers Can only call local Web services Can only call local Web services Low Can't access environment variables Can't access environment variables File I/O limited to reading from own directory hive File I/O limited to reading from own directory hive Can't access SQL Server databases Can't access SQL Server databases Can't call Web services Can't call Web services Minimal Can't do much of anything Can't do much of anything

54 Full Trust Unmanaged Code Unmanaged Code Registry DNS Environment Variables Environment Variables Web Services Remote Servers Windows Event Log Windows Event Log File System SQL Server OLE DB Application SecurityPermission.- UnmanagedCode RegistryPermission SqlClientPermission OleDbClientPermission FileIOPermission EventLogPermission SocketsPermission WebPermission EnvironmentPermission DnsPermission

55 High Trust Unmanaged Code Unmanaged Code Registry DNS Environment Variables Environment Variables Web Services Remote Servers Windows Event Log Windows Event Log File System SQL Server OLE DB Application RegistryPermission SqlClientPermission FileIOPermission EventLogPermission SocketsPermission WebPermission EnvironmentPermission DnsPermission

56 Restricted Medium Trust Unmanaged Code Unmanaged Code Registry DNS Environment Variables Environment Variables Web Services Remote Servers Windows Event Log Windows Event Log File System SQL Server OLE DB Application SqlClientPermission FileIOPermission WebPermission EnvironmentPermission DnsPermission

57 Low Trust Heavily Restricted Unmanaged Code Unmanaged Code Registry DNS Environment Variables Environment Variables Web Services Remote Servers Windows Event Log Windows Event Log File System SQL Server OLE DB Application FileIOPermission

58 Agenda Overview of Web Security ASP.NET Security Architecture Microsoft Reference Application for OpenHack Web Service Security Wrap Up

59 What is OpenHack? Regular contest sponsored by eWEEK Who can build most hack-resistant Web app? Participants build app to eWEEK specs eWEEK invites all comers to hack it 2002 participants: Microsoft and Oracle i http://www.eweek.com/article2/0,3959,741388,00.asp

60 Microsoft Reference Application for OpenHack Microsoft's entry in the 2002 competition Withstood 80,000+ attacks without a single breach of security Written by Vertigo Software and Microsoft Code updated since the competition You get the latest version! Great example of how to do security right

61 Application Architecture Awards Database Awards Database ASP.NET Validation Layer Data Access Layer Protection Layer IIS Public Registry DPAPI Anonymous access Forms authentication URL authorization Trusted connection Windows authentication Decryption keys Connection strings etc. Private SQL permissions

62 Forms Authentication Two-tiered directory structure Root contains "public" pages (including the login page) "Secure" subdirectory contains pages that require logins Forms authentication cookie Always temporary, never persistent 30-minute time-out Cookie path set to app directory

63 Input Validation User input constrained by validation controls Input and output sanitized by validation layer Pages All Input Sanitize Other Input Validation Controls User Input Output HTML- Encode CleanString

64 Awards Database Security Users One account: webuser (Windows principal) Maps to ASP.NET worker process identity Stored Procedures 30 stored procedures Used for all interaction with database Permissions webuser permitted to call stored procs "public" granted no permissions anywhere

65 Data Access Multitiered data access layer All accesses via stored procedures All accesses performed by webuser Windows authentication to SQL Server Connection string DPAPI-encrypted and stored in ACLed registry key

66 Data Protection Registry secrets HKLM\Software\Microsoft\OpenHack4 DPAPI-encrypted connection string DPAPI-encrypted crypto decryption key DPAPI-encrypted crypto initialization vector (IV) DPAPI entropy value ACL grants full control to admins and SYSTEM, read access to ASP.NET worker process Database secrets Encrypted passwords Encrypted credit card numbers

67 Error Handling and Logging Default error page defaultRedirect points to Error.aspx Provides generic response to errors Application_Error Logs unhandled exceptions in Windows event log Includes stack trace and other rich error info Failed logins Logged separately in Windows event log Aid in forensic analysis and intrusion detection

68 Summary MS Reference Application for OpenHack MRAO scrubs and validates input MRAO accesses data securely MRAO encrypts sensitive data MRAO uses forms authentication and URL authorization MRAO handles errors securely and logs them as appropriate MRAO is a secure application!

69 Agenda Overview of Web Security ASP.NET Security Architecture Microsoft Reference Application for OpenHack Wrap Up

70 Rant Do not store passwords either in clear text or with reversible encryption! Makes me angry.

71 Storing Login Passwords FormatComments Plaintext passwords Exposes entire application if database is compromised Encrypted passwords Better than plaintext, but still vulnerable if decryption key is compromised 1-way password hashes Better than encrypted passwords, but still vulnerable to dictionary attacks Salted password hashes Less vulnerable to dictionary attacks Don't store passwords in login databases Store password hashes for added security Salt hashes to impede dictionary attacks

72 Video Title

73 Partner Title Name Title Group

74 Customer Title Name Title Group

75 Announcement Title

76 Resources Steve’s Blog: http://blog.accentient.comhttp://blog.accentient.com Rich’s Blog: http://blog.hundhausen.comhttp://blog.hundhausen.com MS Security: http://www.microsoft.com/security http://www.microsoft.com/security

77 Your Feedback is Important! Please Fill Out a Survey for This Session on CommNet

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


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

Similar presentations


Ads by Google