ASP.NET Forms Authentication Best Practices for Software Developers



Similar documents
Using Foundstone CookieDigger to Analyze Web Session Management

Proof of Concept. A New Data Validation Technique for Microsoft ASP.NET Web Applications. Foundstone Professional Services

1. Introduction. 2. Web Application. 3. Components. 4. Common Vulnerabilities. 5. Improving security in Web applications

Security API Cookbook

TIBCO Spotfire Web Player 6.0. Installation and Configuration Manual

Top 10 Security Vulnerabilities in.net Configuration Files Are your web applications vulnerable?

AJAX Storage: A Look at Flash Cookies and Internet Explorer Persistence

Secure Web Development Teaching Modules 1. Threat Assessment

Hack Proof Your Webapps

OWASP Top Ten Tools and Tactics

Adobe Systems Incorporated

The purpose of this report is to educate our prospective clients about capabilities of Hackers Locked.

The Top Web Application Attacks: Are you vulnerable?

What is Web Security? Motivation

Application Security Testing. Generic Test Strategy

Where every interaction matters.

Web Application Report

ASP.NET MVC Secure Coding 4-Day hands on Course. Course Syllabus

WHITE PAPER. FortiWeb and the OWASP Top 10 Mitigating the most dangerous application security threats

Single sign-on for ASP.Net and SharePoint

BASELINE SECURITY TEST PLAN FOR EDUCATIONAL WEB AND MOBILE APPLICATIONS

External Vulnerability Assessment. -Technical Summary- ABC ORGANIZATION

Criteria for web application security check. Version

Thick Client Application Security

SECURITY DOCUMENT. BetterTranslationTechnology

Check list for web developers

How to break in. Tecniche avanzate di pen testing in ambito Web Application, Internal Network and Social Engineering

Click Studios. Passwordstate. Installation Instructions

FileCloud Security FAQ

Web Application Security Considerations

FINAL DoIT v.4 PAYMENT CARD INDUSTRY DATA SECURITY STANDARDS APPLICATION DEVELOPMENT AND MAINTENANCE PROCEDURES

Web Plus Security Features and Recommendations

Detecting Web Application Vulnerabilities Using Open Source Means. OWASP 3rd Free / Libre / Open Source Software (FLOSS) Conference 27/5/2008

SCAAS: A Secure Authentication and Access Control System for Web Application Development

Threat Modeling. Categorizing the nature and severity of system vulnerabilities. John B. Dickson, CISSP

Cross Site Scripting in Joomla Acajoom Component

Secure Web Development Teaching Modules 1. Security Testing. 1.1 Security Practices for Software Verification

(WAPT) Web Application Penetration Testing

multiple placeholders bound to one definition, 158 page approval not match author/editor rights, 157 problems with, 156 troubleshooting,

Chapter 1 Web Application (In)security 1

An Insight into Cookie Security

Web Application Security

Web Application Security. Vulnerabilities, Weakness and Countermeasures. Massimo Cotelli CISSP. Secure

Design Authorization Systems Using SecureUML

ArcGIS Server Security Threats & Best Practices David Cordes Michael Young

elearning for Secure Application Development

FINAL DoIT v.8 APPLICATION SECURITY PROCEDURE

Click Studios. Passwordstate. Upgrade Instructions to V7 from V5.xx

A Server and Browser-Transparent CSRF Defense for Web 2.0 Applications. Slides by Connor Schnaith

RoomWizard Synchronization Software Manual Installation Instructions

Data Breaches and Web Servers: The Giant Sucking Sound

Thomas Röthlisberger IT Security Analyst

EPiServer Operator's Guide

Secure development and the SDLC. Presented By Jerry

Building a Robust Web Application Security Plan

Web application security: Testing for vulnerabilities

Kentico CMS security facts

qliqdirect Active Directory Guide

1.5.5 Cookie Analysis

National Information Security Group The Top Web Application Hack Attacks. Danny Allan Director, Security Research

Acunetix Web Vulnerability Scanner. Getting Started. By Acunetix Ltd.

JVA-122. Secure Java Web Development

Enterprise Application Security Workshop Series

Introduction to Web Application Security. Microsoft CSO Roundtable Houston, TX. September 13 th, 2006

Web application security

Sitefinity Security and Best Practices

Securing Your Web Application against security vulnerabilities. Ong Khai Wei, IT Specialist, Development Tools (Rational) IBM Software Group

Is Drupal secure? A high-level perspective on web vulnerabilities, Drupal s solutions, and how to maintain site security

Tableau Server Security. Version 8.0

NNT CIS Microsoft SQL Server 2008R2 Database Engine Level 1 Benchmark Report 0514a

WHITE PAPER FORTIWEB WEB APPLICATION FIREWALL. Ensuring Compliance for PCI DSS 6.5 and 6.6

Access Gateway Guide Access Manager 4.0 SP1

Application Layer Encryption: Protecting against Application Logic and Session Theft Attacks. Whitepaper

Web Application Guidelines

Web Application Security

Web Application Firewall on SonicWALL SSL VPN

Web Application Penetration Testing

CrashPlan Security SECURITY CONTEXT TECHNOLOGY

CA Performance Center

Bypassing CAPTCHAs by Impersonating CAPTCHA Providers

Kenna Platform Security. A technical overview of the comprehensive security measures Kenna uses to protect your data

Certified Secure Web Application Security Test Checklist

Columbia University Web Security Standards and Practices. Objective and Scope

NetBrain Security Guidance

Rational AppScan & Ounce Products

Click Studios. Passwordstate. Installation Instructions

Web Application Security Assessment and Vulnerability Mitigation Tests

Authentication Methods

Architecture and Data Flow Overview. BlackBerry Enterprise Service Version: Quick Reference

CRM Setup Factory Installer V 3.0 Developers Guide

Statistics Whitepaper

Chapter 4 Application, Data and Host Security

Virtual Code Authentication User Guide for Administrators

Magento Security and Vulnerabilities. Roman Stepanov

Designing a CA Single Sign-On Architecture for Enhanced Security

Okta/Dropbox Active Directory Integration Guide

WEB SECURITY. Oriana Kondakciu Software Engineering 4C03 Project

SECURITY ADVISORY. December 2008 Barracuda Load Balancer admin login Cross-site Scripting

Ensuring the security of your mobile business intelligence

Zed E-Commerce and WebCRM 7.5. Release Notes 11/29/2011

Transcription:

ASP.NET Forms Authentication Best Practices for Software Developers By Rudolph Araujo, Foundstone Professional Services August 2005

Background ASP.NET does an excellent job of providing out of the box support for multiple forms of authentication using the classes in System.Web.Security namespace. In v1.1 of the framework, there exists support for forms-based, Microsoft Passport based and Integrated Windows (or NTLM) based authentication. These are intended to provide developers with easy access to an intuitive API which they can use to add authentications features to their own applications without having to reinvent it from scratch. As can be seen in listing 1 below, the code to leverage for instance formsbased authentication is fairly short and easily understood. void btnlogin_click(object Source, EventArgs e) // Pull credentials from form fields and try to authenticate the user. if (FormsAuthentication.Authenticate(txtName.Text, txtpassword.text)) // Redirect the client back to the originally requested resource and // create a new persistent cookie that identifies the user. FormsAuthentication.RedirectFromLoginPage(txtName.Text, true); Listing 1 The Authenticate function above validates the credentials submitted by the end user against the user data store for instance the web.config s authentication section to determine if the user should be logged in or not. If the credentials are indeed valid the RedirectFromLoginPage function sets an authentication ticket in the form of a cookie 1 before redirecting the user to whatever page they were trying to login to. This mechanism supports storing the credentials either in the clear or hashed using MD5 or SHA1. Perhaps more often, web applications might use their own custom data store such as an LDAP based directory or SQL / XML database. In this case code like the fragment below could be used: private bool Authenticate(string username, string password) // This method authenticates the user for the application. // In this demonstration application it always returns // true. return true; 1 Cookieless authentication tickets can also be used wherein the ticket is embedded within the URL. These however are even more difficult to secure effectively and hence will not be discussed within this article. www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 1

void btnlogin_click(object Source, EventArgs e) string username = txtusername.text; string password = txtpassword.text; bool ispersistent = chkboxpersist.checked; if(authenticated(username,password)) //This could be used to store information such as what role // the logged on user belongs to string userdata = "ApplicationSpecific data for this user."; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, username, System.DateTime.Now, System.DateTime.Now.AddMinutes(30), ispersistent, userdata, FormsAuthentication.FormsCookiePath); // Encrypt the ticket. string encticket = FormsAuthentication.Encrypt(ticket); encticket)); // Create the cookie. Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, // Redirect back to original URL. Response.Redirect(FormsAuthentication.GetRedirectUrl(username, ispersistent)); Listing 2 Alternatively, it is possible to avoid using the FormsAuthenticationTicket entirely by using the wrappers in the FormsAuthentication class such as SetAuthCookie and RedirectFromLoginPage. The code in Listing 2 explicitly creates the authentication ticket and then cryptographically protects it to prevent tampering attacks. The types of cryptographic protection as well as other parameters are configured via the web.config file. Listing 3 describes all the settings as well as describes the values that those can hold. <forms name="name" loginurl="url" protection="all None Encryption Validation" timeout="30" path="/" requiressl="true false" slidingexpiration="true false"> <credentials passwordformat="format"/> </forms> Listing 3 www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 2

A few of the attributes above merit further explanation. Firstly the protection attribute is used to cryptographically protect the authentication ticket. By setting this attribute to All provides both confidentiality and integrity. The requiressl attribute determines if the ticket is passed back and forth as a secure HTTP cookie i.e. this informs the browser not to transmit the cookie when the request is being made over vanilla HTTP as opposed to over HTTPS. Finally, slidingexpiration if set to true, resets an active authentication cookie's time to expiration upon each request during a single session. Thus, the authentication timeout specified in the timeout attribute is ignored in this case so long as the session is active. The default values for these and other security sensitive attributes in the different versions of the.net framework as well as recommended values are provided later in this article. While the timeout mechanism can be used to log the user out, developers do have the option to explicitly log the user out, for instance in response to the user clicking an logout button or link. This is achieved using the SignOut method on the FormsAuthentication class as shown below: // The LogOffBtn_Click event handler uses the SignOut method // to remove the authentication ticket from the users computer. void LogOffBtn_Click(Object sender, EventArgs e) FormsAuthentication.SignOut(); Status.Text = "You have been successfully logged out from the application."; Listing 4 The Problem While the FormsAuthentication class represents an excellent interface for developers providing commonly used functionality as part of the framework, it has what we believe to be a major design flaw. Like most cookie based authentication and session management mechanisms, this mechanism is susceptible to cookie replay and hence attacks such as session hijacking and stealing. The problem in this case is exacerbated due to the way the authentication ticket is created and maintained. When such a ticket is created it is only maintained in the cookie. No record or status about this ticket is maintained on the server side including information about expiry after a timeout. All such information is encoded into the ticket. Hence, so long as the user s ticket is valid i.e. the timeout has not expired the ticket can be stolen and misused. Even restarting Internet Information Services or for that matter the computer can not invalidate the ticket. This issue discovered by Foundstone and reported to Microsoft, has been acknowledged and published by Microsoft in KB Article 900111. To compound matters calling the SignOut method simply clears the cookie from the client side as can be seen in the code for the SignOut method shown in Listing 5 and obtained using.net Reflector - but in no manner or means www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 3

invalidates it. Thus the developer can do absolutely nothing to effectively sign a user out and prevent their session from being misused after they have in fact logged out. This therefore represents a problem not only for the developer and team that created the application but also for the end user. Unfortunately the only effective way to effectively sign the user out seems to somehow cause the timeout to expire. This is explained in the recommendations section later in the article. public static void SignOut() FormsAuthentication.Initialize(); HttpContext context1 = HttpContext.Current; HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, ""); cookie1.path = FormsAuthentication._FormsCookiePath; cookie1.expires = new DateTime(0x7cf, 10, 12); cookie1.secure = FormsAuthentication._RequireSSL; context1.response.cookies.removecookie(formsauthentication.formscookiename); context1.response.cookies.add(cookie1); Listing 5 Exploitation Scenarios This bug can manifest itself and will be exploited in 3 basic classes of scenarios described in the Table 1. Cross Site Scripting Vector Network Sniffing Vector Shared Computer Scenario If an application using the forms authentication mechanism is vulnerable to cross-site scripting (XSS), a malicious attacker can use an injected script to steal the authentication ticket of a legitimate and currently logged in user, send that over to his own servers out on the Internet and then use those tickets to impersonate the user until the timeout expires. This is especially significant when the application is vulnerable to a persistent or stored XSS attack. If the vulnerable application does not use SSL for transport security, the cookie can simply be stolen while being transmitted over the network in the clear. Once the attacker has the ticket, they can as described above replay the ticket and URL as described above and steal the legitimate user s session. If the vulnerable application allows creation of a persistent cookie, then this can be misused by other users of the same machine. The attacker can search the browser and/or cookie cache on the shared computer for the persisted authentication ticket and use it until the timeout expires. Table 1 Proof of Concept Application To reproduce this problem as a proof of concept follow the steps outlined in Table 2 below to first build the application. Table 3 has information on running the application. www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 4

1. Create a new ASP.NET web application in Visual Studio.NET 2003 2. Add the following to the web.config file to setup forms authentication: <authentication mode="forms"> <forms name=".aspxuserdemo" loginurl="login.aspx" protection="all" timeout="60" /> </authentication> 3. Rename the default WebForm1.aspx to default.aspx. This page represents the protected resource in this sample application the page the user needs to login to view. 4. Add a page called Login.aspx as shown below: <%@ Import Namespace="System.Web.Security " %> <HTML> <script language="c#" runat="server"> void Login_Click(Object sender, EventArgs E) if (((UserEmail.Value == "joe") && (UserPass.Value == "joe")) ((UserEmail.Value == "admin") && (UserPass.Value == "admin"))) FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked); else Msg.Text = "Invalid Credentials: Please try again"; </script> <body> <form runat="server" ID="Form1"> <h3><font face="verdana">login Page</font></h3> <table> <tr> <td>email:</td> <td><input id="useremail" type="text" runat="server" NAME="UserEmail"></td> <td><asp:requiredfieldvalidator ControlToValidate="UserEmail" Display="Static" ErrorMessage="*" runat="server" ID="Requiredfieldvalidator1" /></td> </tr> <tr> <td>password:</td> <td><input id="userpass" type="password" runat="server" NAME="UserPass"></td> <td><asp:requiredfieldvalidator ControlToValidate="UserPass" Display="Static" ErrorMessage="*" runat="server" ID="Requiredfieldvalidator2" /></td> </tr> <tr> <td>persistent Cookie:</td> <td><asp:checkbox id="persistcookie" runat="server" /> </td> <td></td> </tr> </table> <asp:button text="login" OnClick="Login_Click" runat="server" ID="Button1" /> <p> www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 5

<asp:label id="msg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" /> </form> </P> </body> </HTML> 5. Add a button called Signout to the default.aspx page and create the following event handler: private void Signout_Click(object sender, System.EventArgs e) if(user.identity.name == ) Response.Redirect( login.aspx ); else FormsAuthentication.SignOut(); Response.Redirect( login.aspx ); 6. Add a sensitive operation to the default.aspx page. In our sample we choose to read a file and set the value of a control using the text read from that file. This is illustrated below. If you do use this code ensure that the ASPNET/Network Service account has permissions on the file secret.txt. We also add a link to another admin page UpdateTitle.aspx. private void Page_Load(object sender, System.EventArgs e) if(user.identity.name == "") btnsignin.text = "Signin"; if(user.identity.name!= "admin") hyperlinkupdate.visible = false; string title = "Default"; try StreamReader sr = new StreamReader(Request.MapPath("secret.txt")); title = sr.readline(); sr.close(); catch title = "Exception"; Msg.Text = title; 7. Add a new page UpdateTitle.aspx and add a button called btntitle and a textbox txttitle. Add the following event handlers to complete the code for the proof of concept application. private void Page_Load(object sender, System.EventArgs e) www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 6

if(user.identity.name!= "admin") Response.Redirect("login.aspx"); private void btntitle_click(object sender, System.EventArgs e) StreamWriter sw = new StreamWriter(Request.MapPath("secret.txt")); sw.writeline(txttitle.text); sw.close(); Response.Redirect("default.aspx"); Table 2 1. Download a HTTP proxy such as Fiddler 2 or Paros 3. Configure and start the proxy. 2. Browse to http://localhost/<vdir_name>/default.aspx 3. Login using admin / admin 4. Click the hyperlink to access the administrative resource. 5. Add some text to the textbox and click the button to update the title. This will refresh the home page with the new title. 6. Next click on the Signout button which in turn calls FormsAuthentication.Signout 7. Go into Fiddler and find the second request to UpdateTitle.aspx. This request should have a form POST in the request body. 8. Drag and drop this request into the Request Builder in Fiddler. 9. Edit the value of the txttitle textbox and then click execute in Fiddler when ready. 10. Refresh the homepage and you should see the new title from Step 9 above. That title was saved in secret.txt in Step 9 and is then restored from the secret.txt file. This request succeeds even though the administrator is logged out. Table 3 Recommendations For the most part developers can only partially mitigate the risks described above. The following are widely regarded as best practices: 1. Enable strong cryptographic protection on the forms authentication ticket. This should include both encryption and integrity support. Use SHA1 for HMAC generation and AES for encryption. 2. Ensure transport security is used to protect the authentication tickets while in transit. This should be done by enabling SSL on the web server and enforcing the same with the requiressl attribute. 2 http://www.fiddlertool.com/fiddler/ 3 http://www.parosproxy.org www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 7

3. Minimize the lifetime of the ticket as far as possible. Set the timeout attribute to a small value and disable sliding expiration to ensure a fixed expiration period. 4. Protect authentication cookies from cross-site scripting enabled cookie stealing. This is done by both performing effective data validation and using the HttpOnly mechanism to protect the forms authentication cookie from client side attacks 4. 5. Always use specific cookie names and paths to prevent their unnecessary transmission. 6. Possibly use an HTTP module to provide a server side backing store for authentication ticket that can be checked for expiry. This module can maintain a data structure that keeps track of all outstanding tickets, which user s they belong to and what their current status is i.e. if the user has logged out or the timeout expired etc. Recommended Forms Authentication Settings Setting CookieMode EnableCrossAppRedirects ASP.NET 1.0 Default Value Not supported Not supported ASP.NET 1.1 Default Value Not supported Not supported ASP.NET 2.0 Default Value Recommended Value Justification UseCookies UseCookies Cookieless sessions have greater risk since they use the query string to pass the authentication ticket between the client and the server. Consequently all requests must use SSL and must not be cached. False False Prevent compromise in shared hosting type scenarios. Also ensure the IsolateApps flag is set to true for the machine key autogeneration mechanism. FormsCookiePath / / / Protected Virtual Directory LoginUrl N/A N/A N/A Protected Virtual Directory Set the path to as specific a path as possible to prevent the cookie from being transmitted unnecessarily. Always partition your site into secure and non-secure folders that don t use HTTPS. Ensure the URL for the login page is SSL protected. 4 In ASP.NET 2.0 the forms authentication cookie if created through the framework is HttpOnly by default. www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 8

RequireSSL False False False True Prevent the forms authentication ticket from being transmitted in the clear. SlidingExpiration True True True False Set an absolute session expiry time ensuring that the time period is as small as possible. Protection All All All All Turns on both encryption and integrity checking on the forms authentication ticket. In addition ensure that the encryption and validation keys are auto-generated and IsolateApps is set to true. In a web farm scenario this is not possible and the keys must be hardcoded in the web.config. Ensure that the section of the web.config is then encrypted. Timeout 30 30 30 10-20 minutes or as small as possible. Table 4 Minimize the attack surface by decreasing the amount of time the ticket is vulnerable. Conclusions The biggest concern with the current implementation is that it provides no way for the developer (the user of the API) or the end-user to do the right thing and implement the correct security pattern, thus effectively significantly increasing the attack surface. The analogy here is if you put your car key into the keyhole; closed the door and turned the key you would expect the door to be locked. If someone could now unlock your car by simply knowing what your key looked like you would say it were broken and would not rely on the security of the door. While the risks associated with this issue cannot be completely eliminated, developers should mitigate risks by following the guidelines provided in this whitepaper. www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 9

References 1. KB 900111: A forms authentication cookie can be used to authenticate to a forms authentication ASP.NET application after the FormsAuthentication.SignOut method has been called http://support.microsoft.com/?kbid=900111 2. How To: Protect Forms Authentication in ASP.NET 2.0 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/tmwa.asp www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 10

About Foundstone Professional Services Foundstone Professional Services, a division of McAfee, offers a unique combination of services and education to help organizations continuously and measurably protect the most important assets from the most critical threats. Through a strategic approach to security, Foundstone identifies, recommends, and implements the right balance of technology, people, and process to manage digital risk and leverage security investments more effectively. Foundstone s Secure Software Security Initiative (S3i ) services help organizations design and engineer secure software. By building in security throughout the Software Development Lifecycle, organizations can significantly reduce their risk of malicious attacks and minimize costly remediation efforts. Services include: Source Code Audits Software Design and Architecture Reviews Threat Modeling Web Application Penetration Testing Software Security Metrics and Measurement For more information about Foundstone S3i services, go to www.foundstone.com/s3i. Foundstone S3i training is designed to teach programmers and application developers how to build secure software and to write secure code. Classes include: Writing Secure Code ASP.NET (C#) Building Secure Software Writing Secure Code Java (J2EE) Ultimate Web Hacking For the latest course schedule, go to www.foundstone.com/education. www.foundstone.com 2005 Foundstone, Inc. All Rights Reserved - 11