Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Hack proof your asp.net applications from Session Hijacking

4.84/5 (36 votes)
3 Jan 2015CPOL3 min read 152.4K   1.3K  
This article describes what is session hijacking and how to prevent from session hijacking in asp.net.

Introduction

This article is the Part-5 of my series Hack Proof your asp.net and asp.net mvc applications. In this article, I will describe what exactly Session Hijacking (Man-in the-middle-attack) is and how a hacker exploits it and how we can prevent Session Hijacking attack in asp.net applications.

DownloadSessionHijackingPrevention.zip

Background

You can read previous article of this series from below links :

  1. Secure your ASP.NET applications from SQL Injection
  2. Secure your ASP.NET applications from XSS Attack
  3. Secure your ASP.NET applications from CSRF Attack
  4. Secure your ASP.NET applications from Sensitive Data Exposure and Information Leakage

Session Hijacking 

Before explaining session hijacking i want to tell how asp.net do session management.Whenever a new session is created a cookie is generated for that user , this cookie becomes the session ID , so all the request can serve using that session ID.
 
If somehow a hacker can sniff or steal the session id he can forge the request as a valid user (i.e impersonate as you) .
Image 1

 

Impact of session hijacking is Severe , attacker can do anything what a Authentic user allowed to do on any website.

How is it Exploited :

Below are some ways , How to Session ID can be attacked :

  1. Sniffing of session on less secure network,
  2. Man in the middle attack (Any proxy configuration installed on system example : See your traffic easily on fiddler),
  3. Stealing from Victim machine,
  4. alert cookie using XSS attack,
  5. if url based session is used ,Simply copy and paste session ID from url.

DEMO FOR ASP.NET APPLICATION :

To Demonstrate Session Hijacking I am using two different browsers (Chrome and Mozilla)
different programs with different session.Note : Normally this attack occurs on different machines.

User logged into chrome and generated the Session ID : (Chrome in my case)                                                           Image 2

Attacker sniffed your session ID : (Mozilla)
Attacker now logging into another machine and used your session ID :

Image 3

Result :

Image 4

and you know the consequences of the Session Hijacking.                                                                                        

How to prevent Session Hijacking :

Following are the ways of Preventing session Hijacking in asp.net applications :

1. The idea basically Generate the hashkey which contains the Browser Detail , Browser Version, Browser platform, User Identity, IP address (Additionally/Optional).
And validate this hash key for every Get and POST request.

For that you can use Global.asax Application_BeginRequest and Application_EndRequest , Or Application_AcquireRequestState .

In My Demo i am using the Begin and End request methods of global.asax.

In Application_BeginRequest :

Step1: Check if its a new session or not , if not then do the further checks
Step2: Retrieve the value of ASP.NET_SessionID 
Step3: Generate the Hash Key for this POST/GET request and match with Previous ASP.NET_SessionID 
Step4: If Valid request the remove the Overhead you have added in ASP.NET_SessionID like (IP address , BrowserVersion , Browser Platform ) so application can work smoothly.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //Check If it is a new session or not , if not then do the further checks
            if (Request.Cookies["ASP.NET_SessionId"] != null && Request.Cookies["ASP.NET_SessionId"].Value != null)
            {
                string newSessionID = Request.Cookies["ASP.NET_SessionID"].Value;
                //Check the valid length of your Generated Session ID
                if (newSessionID.Length <= 24)
                {
                    //Log the attack details here
                    Response.Cookies["TriedTohack"].Value = "True";
                    throw new HttpException("Invalid Request");
                }

                //Genrate Hash key for this User,Browser and machine and match with the Entered NewSessionID
                if (GenerateHashKey() != newSessionID.Substring(24))
                {
                    //Log the attack details here
                    Response.Cookies["TriedTohack"].Value = "True";
                    throw new HttpException("Invalid Request");
                }

                //Use the default one so application will work as usual//ASP.NET_SessionId
                Request.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Substring(0, 24);
            }

        } 

In Application_EndRequest :
Just Add again the hash-key and pass to the browser.

protected void Application_EndRequest(object sender, EventArgs e)
        {
            //Pass the custom Session ID to the browser.
            if (Response.Cookies["ASP.NET_SessionId"] != null)
            {
                Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + GenerateHashKey();
            }
         
        }

To Generate Hash-key add this function in your global.asax :

private string GenerateHashKey()
       {
           StringBuilder myStr = new StringBuilder();
           myStr.Append(Request.Browser.Browser);
           myStr.Append(Request.Browser.Platform);
           myStr.Append(Request.Browser.MajorVersion);
           myStr.Append(Request.Browser.MinorVersion);
           //myStr.Append(Request.LogonUserIdentity.User.Value);
           SHA1 sha = new SHA1CryptoServiceProvider();
           byte[] hashdata = sha.ComputeHash(Encoding.UTF8.GetBytes(myStr.ToString()));
           return Convert.ToBase64String(hashdata);
       }

2. Another way of preventing the Session Hijacking force SSL to the entire website and make sure cookies are flagged as secure.
3. Remove your Session Id and Expire the session at the time of log out.

Example : In log out page add this to load of that page 

Session.Abandon(); // Session Expire but cookie do exist
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30); //Delete the cookie

Thanks for reading this article.Alternatively you can donload the whole code from my git repository :

https://github.com/sarveshkushwaha/SessionHijackingPreventionAspNet

References and Further Readings: 

http://stackoverflow.com/questions/22880/what-is-the-best-way-to-prevent-session-hijacking
http://dotnet.dzone.com/articles/aspnet-session-hijacking

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)