Saturday, December 25, 2010

Guarding Against Session Hijacking in ASP.NET

In this tutorial we're going to be looking at something all .Net developers need to be aware of and guard against, and that is prevent session hijacking. Session hijacking is a form of hacking attack that involves accessing a users session state. While the damage can be as small as having access to someone's shopping cart data, or as severe as hijacking a session that contains a users personal, or financial, information. This kind of attack is generally carried out in two forms:
•ID Guessing
•Solen ID's
Session ID guessing is harder for an ASP.NET website because ASP.NET employs a random 120-bit number, but stealing a session ID is more prevalent. There are three main ways hackers steal session ID's:
•Cross-Site Scripting (XSS)
•Main-In-The-Middle Attack
•Gain access to the users cookie
The main reason stealing session ID's from an ASP.NET application takes such little skill from the hacker is because ASP.NET doesn't encode any information in the session cookie other than the ID itself. If the server receives a Request with a valid ID it accepts the Request, no questions asked. Though it is impossible to create a fool-proof defense against such attacks, the developer can take certain steps to make them harder to pull off, and that is what this tutorial looks at.
In this tutorial we will look at intercepting the session cookie (before ASP.NET sees it), taking the MAC (Message Authentication Code), and creating our own MAC, based on the session ID, the users IP address and their User Agent. Our class will also rely on a validation key that is stored in the web.config file. The key will be based on a MD5 hash of a string, and should be different for all applications this is used for. Make sure your key is long and random, shorter keys are easier to guess. We will also be creating a custom Exception that will be used in the class.
Before we start, here's a short method you can use to create the MD5 hash for your validation key. It employs the MD5CryptoServiceProvider Class in the System.Security.Cryptography Namespace:
view sourceprint?
01 /// <summary> 
02 /// method to generate a MD5 hash of a string 
03 /// </summary> 
04 /// <param name="strToHash">string to hash</param> 
05 /// <returns>hashed string</returns> 
06 public string GenerateMD5(string str) 
07 { 
08     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 
09   
10     byte[] byteArray = Encoding.ASCII.GetBytes(str); 
11   
12     byteArray = md5.ComputeHash(byteArray); 
13   
14     string hashedValue = ""; 
15   
16     foreach (byte b in byteArray) 
17     { 
18         hashedValue += b.ToString("x2"); 
19     } 
20   
21     return hashedValue; 
22 }
Now that we have the creation of the key covered, lets start making our secure session class. First and foremost, as with all classes you write, you need to make sure you have the proper Namespace's for your class, in this case we need seven of them:
view sourceprint?
1 using System; 
2 using System.Web; 
3 using System.Text; 
4 using System.Web.Security; 
5 using System.Configuration; 
6 using System.Security.Cryptography; 
7 using System.Globalization;
Now we need any global variables, in this case we have a single global, the variable that will hold the value of
our key
view sourceprint?
1 private static string secretKey = null;
This class is designed to operate completely silent, meaning it works in the background with zero interaction
from the developer whatsoever. Our class inherits the IHttpModule Interface.
First thing we will do is call the Init() and Dispose() Methods of the IHttpModule. In the Init() Method we will
first check the value of our global variable secretKey, if it doesn't have a value we will initialize it.
We then wire up two Event Handlers, these will handle the BeginRequest Event and the EndRequest Event of
the HttpApplication Class. The Dispose() method is a blank method, but it is required when inheriting from the
IHttpModule Interface.
view sourceprint?
01 /// <summary> 
02 /// method to initialize our class when the page is initialized 
03 /// </summary> 
04 /// <param name="application"></param> 
05 public void Init(HttpApplication application) 
06 { 
07     //find out of we have a validation key, if we dont initialize it 
08     if (secretKey == null) secretKey = GetKey(); 
09   
10     //register event handlers for the BeginRequest and EndRequest events 
11     application.BeginRequest += new EventHandler(onbeginRequest); 
12     application.EndRequest += new EventHandler(onendRequest); 
13 } 
14   
15 public void Dispose()  
16 {  
17 }
Now the Event Handler, we have two to write up:
•onbeginRequest: Handles all transactions at the start of the request cycle
•onendRequest: Handles all transactions at the very end of the request cycle
onbeginRequest is where we do the bulk of our work. The first thing we do is grab the current Request, this
allows us access to all the information we need, including the current ASP.NET_SessionID cookie. Once we
have the cookie in our possession we first check it's length, if it's less than 24 long we throw an exception
because that tells us the cookie doesn't have a MAC attached. If we make it past that check we then grad
the session ID and the MAC value off of the cookie (using string manipulation), then compare the MAC value
with our generated MAC. If they don't match we throw an exception because something's happened to the
cookie. Barring any errors we quickly assign the session ID to the value of the cookie, all before ASP.NET
see's it.
onbeginRequest:
view sourceprint?
01 /// <summary> 
02 /// method for handling the HttpApplication.BeginRequest event 
03 /// </summary> 
04 /// <param name="sender"></param> 
05 /// <param name="e"></param> 
06 public void onbeginRequest(Object sender, EventArgs e) 
07 { 
08     //get the current Request 
09     HttpRequest currentRequest = ((HttpApplication)sender).Request; 
10   
11     //get the ASP.NET_SessionId cookie from the Request object 
12     HttpCookie requestCookie = RetrieveRequestCookie(currentRequest, "ASP.NET_SessionId"); 
13   
14     //check to see if the cookie exists (if == null) 
15     if (requestCookie != null) 
16     { 
17         //if the length is less than 24 we dont have a MAC so we need to throw an exception
            (our custom exception) 
18         if (requestCookie.Value.Length <= 24) throw new SessionerrorException("Invalid Session"); 
19   
20         //get the session id
21         string sessionID = requestCookie.Value.Substring(0, 24); 
22   
23         //get the MAC 
24         string mac = requestCookie.Value.Substring(24); 
25   
26         //create a new MAC based on the session id and some of the users info (user agent, etc) 
27         string macCompare = CreateMAC(sessionID, currentRequest.UserHostAddress,
                                                                                              currentRequest.UserAgent, secretKey); 
28   
29         //check to see if the MAC's match, if not we have a problem 
30         if (String.CompareOrdinal(mac, macCompare) != 0)
                                           throw new SessionerrorException("Invalid Session"); 
31   
32         //set the cookies value to the session id
33         requestCookie.Value = sessionID; 
34     } 
35 }
In the onendRequest we grab the response cookie and make sure it isn't null (that would mean someone
has hijacked the session), if all is OK we append our newly created MAC value to the end of the cookie,
and this can be compared during the next BeginRequest Event, which will be the next page load for the
application.
onendRequest:
view sourceprint?
01 /// <summary> 
02 /// method for handling the HttpApplication.EndRequest event 
03 /// </summary> 
04 /// <param name="sender"></param> 
05 /// <param name="e"></param> 
06 public void onendRequest(Object sender, EventArgs e) 
07 { 
08     //capture the current request 
09     HttpRequest currentRequest = ((HttpApplication)sender).Request; 
10   
11     //get the session cookie 
12     HttpCookie sessionCookie = RetrieveResponseCookie(((HttpApplication)sender).Response,
                                                                                                                                   "ASP.NET_SessionId"); 
13   
14     //make sure the cookie isnt null 
15     if (sessionCookie != null) 
16     { 
17         //add our newly generated MAC to the cookie at the end of the request 
18         sessionCookie.Value += CreateMAC(sessionCookie.Value, currentRequest.UserHostAddress,
                                                            currentRequest.UserAgent, secretKey); 
19     } 
20 }
In our Init() we called a method GetKey, which we use to initialize our secretKey variable. This method
simply checks the web.config file for the SessionKey section and returns the value. An exception will be
thrown if this value doesn't exist in the web.config:
view sourceprint?
01 /// <summary> 
02 /// method for retrieving the validation key from the web.config 
03 /// </summary> 
04 /// <returns></returns> 
05 private string GetKey() 
06 { 
07     //get the key 
08     string validationKey = ConfigurationManager.AppSettings["SessionKey"]; 
09   
10     //check for a null or empty key. If so throw our exception 
11     if (validationKey == null || validationKey == String.Empty)
                                            throw new SessionerrorException("SessionKey not found. Application  
12   
13 ending"); 
14   
15     //return the key 
16     return validationKey; 
17 }
We have four more methods to look at in this class (before we get to our custom Exception class).
They are
•RetrieveRequestCookie: Used to retrieve the current Request cookie.
•RetrieveResponseCookie: Used to retrieve the current Response cookie.
•FindTheCookie: Used to find a cookie by it's name.
•CreateMAC: Used to generate our custom MAC value for the session cookie.
view sourceprint?
01 /// <summary> 
02 /// method for retrieving the Request cookies 
03 /// </summary> 
04 /// <param name="currentRequest"></param> 
05 /// <param name="cookieName"></param> 
06 /// <returns></returns> 
07 private HttpCookie RetrieveRequestCookie(HttpRequest currentRequest, string cookieName) 
08 { 
09     HttpCookieCollection cookieCollection = currentRequest.Cookies; 
10     return FindTheCookie(cookieCollection, cookieName); 
11 } 
12   
13 /// <summary> 
14 /// method for retrieving the Response cookies 
15 /// </summary> 
16 /// <param name="currentResponse"></param> 
17 /// <param name="cookieName"></param> 
18 /// <returns></returns> 
19 private HttpCookie RetrieveResponseCookie(HttpResponse currentResponse, string cookieName) 
20 { 
21     HttpCookieCollection cookies = currentResponse.Cookies; 
22     return FindTheCookie(cookies, cookieName); 
23 }
FindTheCookie takes an HttpCookieCollection and a name as a parameter. From there it loops the length
of the HttpCookieCollection passed to it comparing each cookie name with the name provided. If it finds
a match it returns that HttpCookie, otherwise it returns null
view sourceprint?
01 /// <summary> 
02 /// method for retrieving a cookie by it's name 
03 /// </summary> 
04 /// <param name="cookieCollection">the cookie collection to search</param> 
05 /// <param name="cookieName">the cookie we're looking for</param> 
06 /// <returns></returns> 
07 private HttpCookie FindTheCookie(HttpCookieCollection cookieCollection, string cookieName) 
08 { 
09     for (int i = 0; i < cookieCollection.Count; i++) 
10     { 
11         if (string.Compare(cookieCollection[i].Name, cookieName, true, CultureInfo.InvariantCulture) == 0) 
12             return cookieCollection[i]; 
13     } 
14   
15     return null; 
16 }
Now we just need to generate a MAC for our session cookie. This is done by appending the current session
id with the first segment of the users IP address and his User Agent. We then use the HMACSHA1 Class to
generate a new MAC for the cookie:
view sourceprint?
01 /// <summary> 
02 /// method for generating a new MAC for our session cookie 
03 /// </summary> 
04 /// <param name="id">current session id</param> 
05 /// <param name="ipAddress">ip address of the current Request</param> 
06 /// <param name="userAgent">current user's User Agent</param> 
07 /// <param name="validationKey">validation key from the web.config</param> 
08 /// <returns></returns> 
09 private string CreateMAC(string id, string ipAddress, string userAgent, string validationKey) 
10 { 
11     //create an instance of the StringBuilder with a max length of 512 
12     StringBuilder sb = new StringBuilder(id, 512); 
13   
14     //append the first segment of the user's ip address to the string 
15     sb.Append(ipAddress.Substring(0, ipAddress.IndexOf('.', ipAddress.IndexOf('.') + 1))); 
16   
17     //append the users User Agent to the string 
18     sb.Append(userAgent); 
19   
20     using (HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(validationKey))) 
21     { 
22         return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()))); 
23     } 
24 }
Creating a custom Exception class is fairly straight forward so I am just going to post the code with little or
no explanation. For more information on creating your own exception classes, read this on Creating Custom
Exception In .Net, it has some pretty good information in it.
view sourceprint?
01 [Serializable] 
02 public class SessionerrorException : Exception 
03 { 
04     public SessionerrorException() : base("Invalid Session") { }  
05   
06     public SessionerrorException(string message) : base(message) { } 
07   
08     public SessionerrorException(string message, Exception inner) : base(message, inner) { } 
09   
10     protected SessionerrorException(SerializationInfo info, StreamingContext context)
                                                                                                                : base(info, context) { } 
11 }
Now that we have the coding part done, that is creating the module and the custom Exception, there
are some things we need to add to the web.config file in order to wrap this up. First is the validation
key, which should be a long random string generated with a MD5 hash. This should be placed in the
<appSettings> section of your web.config file, and should look like this
view sourceprint?
1 <appSettings> 
2     <add key="SessionKey" value="3595381625A3DCC07E84E626939254834E0FD16B"/> 
3 </appSettings>
My particular key is a MD5 hash based on a 11 character word (that will remain a secret). The last thing
we need to do is register this HttpModule in our web.config. As you can image this needs to go in the
<httpModules> section of the web.config. That looks like this
view sourceprint?
1 <httpModules> 
2     <add name="SecureSession" type="RLM.Core.Components.Security.SecureSession, SecureSession"/> 
3 </httpModules>
The syntax for registering a module is
Quote
<httpModules>
<add name="YourName" type="YourNamespace.YourClassName, YourProjectName"/>
</httpModules>
There you have it, a way to fight session hijacking in your ASP.NET applications. Remember, there is no
100% foolproof way to prevent this, this class is simply meant as one way to make it harder for hackers
to hijack your users sessions, and thus giving them access to the users information.

No comments :

Post a Comment