Click here to Skip to main content
16,021,181 members
Articles / Web Development / ASP.NET
Article

Hack proof your asp.net applications from Session Hijacking

Rate me:
Please Sign up or sign in to vote.
4.84/5 (36 votes)
3 Jan 2015CPOL3 min read 152.3K   1.3K   56   27
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)


Written By
Software Developer
India India
I do believe life is to help others ... So here i am .. in my spare time i learn new things of programming and try to help people with my knowledge .
I'm an energetic, self-motivated and hard-working Developer and Information Technology Professional with experience in projects, website design and development.

Visit My Technical Blog

Comments and Discussions

 
Questionsession hijacking asp.net Pin
Member 1312808622-Feb-21 18:19
Member 1312808622-Feb-21 18:19 
GeneralMy vote of 1 Pin
Member 1338332122-Jan-21 19:39
Member 1338332122-Jan-21 19:39 
Questionis this configuration needed if application is build under FormsAuthentication? Pin
qadevrepublic 00125-Oct-18 2:17
qadevrepublic 00125-Oct-18 2:17 
QuestionWhat if hacker use same browser with same version Pin
ali_parlous23-Feb-18 3:46
ali_parlous23-Feb-18 3:46 
QuestionThe session can still be hacked with this approach Pin
mike1234543215-May-17 2:38
mike1234543215-May-17 2:38 
QuestionPossible alternatives? Pin
DragonOfId9915-Jul-16 4:49
DragonOfId9915-Jul-16 4:49 
AnswerRe: Possible alternatives? Pin
Brian Herbert12-Jun-18 3:00
Brian Herbert12-Jun-18 3:00 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan2-May-16 9:43
professionalAfzaal Ahmad Zeeshan2-May-16 9:43 
GeneralRe: My vote of 5 Pin
DragonOfId9915-Jul-16 4:43
DragonOfId9915-Jul-16 4:43 
QuestionDll Pin
Schatak8-Jan-16 22:50
professionalSchatak8-Jan-16 22:50 
Can you please provide its dll. I am not able to extract it.
QuestionMy vote of 5 Pin
Liju Sankar9-Feb-15 0:47
professionalLiju Sankar9-Feb-15 0:47 
AnswerRe: My vote of 5 Pin
Sarvesh Kushwaha9-Feb-15 17:56
Sarvesh Kushwaha9-Feb-15 17:56 
QuestionThanks Pin
gecko_197126-Jan-15 22:41
gecko_197126-Jan-15 22:41 
AnswerRe: Thanks Pin
Sarvesh Kushwaha27-Jan-15 2:02
Sarvesh Kushwaha27-Jan-15 2:02 
GeneralMy vote of 5 Pin
Oshtri Deka8-Jan-15 4:00
professionalOshtri Deka8-Jan-15 4:00 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha9-Jan-15 15:55
Sarvesh Kushwaha9-Jan-15 15:55 
Questionthanks Pin
Hooman_Kh5-Jan-15 14:48
Hooman_Kh5-Jan-15 14:48 
AnswerRe: thanks Pin
Sarvesh Kushwaha5-Jan-15 15:01
Sarvesh Kushwaha5-Jan-15 15:01 
GeneralMy vote of 5 Pin
Member 18804035-Jan-15 2:37
Member 18804035-Jan-15 2:37 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha5-Jan-15 5:31
Sarvesh Kushwaha5-Jan-15 5:31 
Questionnot really hack-proof Pin
sjelen5-Jan-15 1:02
professionalsjelen5-Jan-15 1:02 
AnswerRe: not really hack-proof Pin
Sarvesh Kushwaha5-Jan-15 5:36
Sarvesh Kushwaha5-Jan-15 5:36 
GeneralRe: not really hack-proof Pin
SaiKiran.Mandhala8-Aug-16 5:02
SaiKiran.Mandhala8-Aug-16 5:02 
QuestionNice explanation. Pin
Arjsrya4-Jan-15 22:33
professionalArjsrya4-Jan-15 22:33 
AnswerRe: Nice explanation. Pin
Sarvesh Kushwaha4-Jan-15 23:46
Sarvesh Kushwaha4-Jan-15 23:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.