Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 18845 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > Session Security in ASP.NET

Session Security in ASP.NET

Article posted by Sudhakarj21 on 12/1/2009 | Views: 16023 | Category: ASP.NET | Level: Beginner red flag


There are many ways to make the web site secure. Below are some of the ways to make web site secure

• Hardware (Firewall rules and ports)
• IIS (CGI and others security restrictions)
• Application Security Considerations

But this article concentrates mostly from Application Considerations in ASP.NET on Session Hijacking. Below are some of the important security attacks on ASP.NET Web Sites.

• Session Hijacking (Filtering)
• SQL Injection
• Cross Site Scripting
• View State Hijacking

Introduction

There are a growing number of security attacks on web sites day by day. Below are the statistics of security attacks as per one of the security report published in 2009.




PC Virus - Statistics are Shown in Above Figure


Web Site Attacks - Statistics are Shown in Above Figure

Most of the attacks on web site are to

 

  • Gather User Information (PI / Email Address / Contacts etc…)
  • Increase the load on web site causing server halt or down
  • Add Malware Software ads on the website

Session Hijacking

Session hijacking is a method of taking over a Web user session by surreptitiously obtaining the session ID and masquerading as the authorized user. Once the user's session ID has been accessed (through session prediction), the attacker can masquerade as that user and do anything the user is authorized to do on the network.

 

There are many malware viruses or network monitoring threats that will observe the Session Cookies that store the user session ID information. Once the virus got the information it will forward the details to hackers and they use the same user cookie to access the session information which may contain PI information which he can use. There is an SSL option which will help to encrypt the data on wire but still the cookie stored on client can be used by hacker. One more option to fix this issue is to use session less mode which is note secure as the Session details will be part of URL and any network monitoring algorithm can get the URL information.

 

Below are some more methods that will be used by Hackers to get Session Information

·         Prediction – Guessing of Session ID. Hackers will analyze one Session ID and will try to Guess the valid Session IDs and tracks all currently active users on server and gathers all their information

·         Fixation – If you are using a default ASP.NET Session ID the detailed related to Session ID generation is documented and it will not be difficult thing to generate a valid Session ID.

Is it possible to maintain Session ID without using Cookie or URL?  It can be using HTTP Headers but still the Headers information can be tracked.

Below diagrams illustrate these security attacks

 

 

 

 

So to make the Session data more secure alternate consideration is to identify and validate client information from request to request. If the request comes from different client for the same Session ID then it can be considered as a Hijack attack.

To identify client below are some information we can have from the Request

 

  • IP Address
  • User Identity Information
  • Browser Information

 

Each of the information has some of the limitations

IP Address

o We cannot depend on IP Address as the Hacker can also use the same proxy to connect to the server

o   For any other reason if the IP Address is changed then even a request from valid user will be considered as attack

·         User Identity Information

o   Can be considered up to some extent. Since the same User and Machine Name matching criteria will be very less. But even the hacker can create the same user name and machine name to Hijack Session.

·         Browser/OS Information

o   Hacker can also use the same Browser and OS

 

If you consider the above set of limitations it may be risky to create Session ID information based on these. But the combination of these may produce better options. Session ID should provide below information which will help to track valid users.

 

·         Browser / OS Information

o   Browser Type & Version

o   OS Type & Version

·         User Identity Information

o   User Details & Identity if any

·         Previous URL

o   URL that caused a Post Back or Redirect. It is not recommended if you have popup and iFrames

·         IP Address

o  Depending on the Application Environment

 

If the cookie holds these information also apart from Session ID or Session ID is generated in such a way that these details or kept in that ID then for each Request that is coming from client should be validated and if the Session data and the Request data doesn’t match then it is a Session Hijack and we can block that Request. Below diagram illustrates this.



This method can be implemented in ASP.NET in a very easy way. Let’s consider that we are going to use the Session ID to maintain validation information. A simple Session ID generated by ASP.NET looks like bo4qhu45ihqco1ftmvprfe55 an Alpha Numeric with 24 Chars Length. So now let’s try to hook up client details to this Session ID as illustrated below.

Session ID Manipulation

Below are the steps

·         Get the ASP.NET_SessionID Cookie and Value

·         Create a HashKey on information on Browser & OS & ClientIdentity & PreviousURL

·         Attach the HashKey to Cookie Value

·         Attach the Cookie to Response

Session ID Validation

Below are the steps

·        Get the ASP.NET_SessionID Cookie and Value

·        Create a HashKey on information on Browser & OS & ClientIdentity

·        Validate the new HashKey againt the value in Cookie

·         Update the Cookie so the Application will understand

Sample ASP.NET Code

These validations on Session can be at HTTP Module level or you can place in Global.asax. Let’s use Global.asax events to do our work.

Below code is to validate the Request. If the Session ID matches with our hash key then only it is considered as valid request.

protected void Application_BeginRequest(object sender, EventArgs e)

        {

            if (Request.Cookies["ASP.NET_SessionId"] != null && Request.Cookies["ASP.NET_SessionId"].Value != null)

            {

                string newSessionID = Request.Cookies["ASP.NET_SessionID"].Value;

                if (newSessionID.Length <= 24)

                {

                    //Log the attack details here

                    throw new HttpException("Invalid Request");

                }

 

                if (GenerateHashKey() != newSessionID.Substring(24))

                {

                    //Log the attack details here

                    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);

            }

        }

Below code is to update Manipulate Session Cookie

protected void Application_EndRequest(object sender, EventArgs e)

        {

            if (Response.Cookies["ASP.NET_SessionId"] != null)

            {

                Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + GenerateHashKey();

            }

        }

A simple code to generate Hash Key based on Browse and User information

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);

        }

Below is the result of the Cookies and Values and it contains Client Information and Session ID

Conclusion


This is just a sample code if you want to use this in production you need to consider lot of details that matches your environment

 

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:7 year(s)
Home page:
Member since:Monday, October 05, 2009
Level:Bronze
Status: [Member]
Biography:
>> Write Response - Respond to this post and get points
Related Posts

This FAQ is like a starter kit. It will help you understand the main aspects of Ajax in a rapid fashion....

SQL Server is a very large subject in itself. Rather than attempting to cover all aspects of SQL Server database access, this article focuses on those areas where you are likely to gain the biggest payoffs.

Vulnerability in ASP.NET Could Allow Information leak, how to solve it and link to good knowledge base post ;)

In this article we will discuss an upcoming code review tool StyleCop. We will understand the basics and do a small sample of code review practically to understand how StyleCop works. I have been writing and recording videos on architecture, design patterns, UML, enterprise blocks, estimation, and code reviews. You can view all my videos on http://www.questpond.com . Any feedbacks do email me at shiv_koirala at yahoo.com You can read my previous article on code reviews using FXCOP http://www.dotnetfunda.com/articles/article175.aspx

I will show you how to implement Password Recovery control with CAPTCHA included and how to handle the background processing.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/19/2013 10:08:50 AM