Session Fixation in ASP.NET - asp.net

I'm wondering how to prevent Session fixation attacks in ASP.NET (see http://en.wikipedia.org/wiki/Session_fixation)
My approach would to this would normally be to generate and issue a new session id whenever someone logs in. But is this level of control possible in ASP.NET land?

Have been doing more digging on this. The best way to prevent session fixation attacks in any web application is to issue a new session identifier when a user logs in.
In ASP.NET Session.Abandon() is not sufficient for this task. Microsoft state in http://support.microsoft.com/kb/899918 that: ""When you abandon a session, the session ID cookie is not removed from the browser of the user. Therefore, as soon as the session has been abandoned, any new requests to the same application will use the same session ID but will have a new session state instance.""
A bug fix has been requested for this at https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=143361&wa=wsignin1.0&siteid=210#details
There is a workaround to ensure new session ids' are generated detailed at http://support.microsoft.com/kb/899918 this involves calling Session.Abandon and then clearing the session id cookie.
Would be better if ASP.NET didn't rely on developers to do this.

Basically just do this in your Login GET method and your Logout method:
Session.Clear();
Session.Abandon();
Session.RemoveAll();
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
}

If I am assuming right, you are talking about... http://en.wikipedia.org/wiki/Session_fixation. The short answer is yes, you have a lot of ways in which you can secure your cookie as well. You shouldn't be using cookieless session, and while you are using sessions, ensure that you have secured the cookie as well explicitly.
Check this article out... http://blogs.msdn.com/rahulso/archive/2007/06/19/cookies-case-study-with-ssl-and-frames-classic-asp.aspx

It does generate a new session ID when the user logs in, and kills a session when the timeout occurs, or the user navigates away/close the browser. And you can programmably kill it via Abandon() or remove entries via Remove().
So I'm not sure what the issue is?

Related

SessionID is still the same after Session.Abandon call

I'm writing some logging code that is based on SessionID...
However, when I log out (calling Session.Abandon), and log in once again, SessionID is still the same. Basically every browser on my PC has it's own session id "attached", and it won't change for some reason :/
Any ideas what is going on?
My Session config looks like this:
<sessionState
mode="InProc"
timeout="1" />
Thanks, Paweł
Check this article which explains the process on session.abandon
http://support.microsoft.com/kb/899918
Taken from above link -
"When you abandon a session, the session ID cookie is not removed from the browser of the user. Therefore, as soon as the session has been abandoned, any new requests to the same application will use the same session ID but will have a new session state instance"
This is a default behavior by design as stated here:
Session identifiers for abandoned or expired sessions are recycled by default. That is, if a request is made that includes the session identifier for an expired or abandoned session, a new session is started using the same session identifier. You can disable this by setting regenerateExpiredSessionId attribute of the sessionState configuration element to true
You can disable this setting as mentioned above.
EDIT: Setting regenerateExpiredSessionId attribute to true works only for cookieless sessions. To overcome your problem, you can consider to implement a custom class that inherits SessionIDManager class. You can get information about that here and here.
This is an old post but if someone is still looking for answers, here is a complete and step-by-step solution on how to achieve a clean logout with a new session ID every time.
Please note this article applies to cookie-enabled (cookieless=false) sites only.
Step (1) Modify your web.config file & add "regenerateExpiredSessionID" flag as under -
<sessionState mode="InProc" cookieless="false" regenerateExpiredSessionId="true" />
Step (2) Add the following code in your logout event -
Session.Clear();
Session.Abandon();
Response.Cookies.Add(New HttpCookie("ASP.NET_SessionId", ""));
Response.redirect(to you login page);
Step (3) Add the following code in your login page's page_load event -
if(!IsPostBack)
{
Session.Clear();
Session.Abandon();
}
Step 2 and 3 serve one IMPORTANT purpose. This code makes sure a brand new Session ID is generated after you click the "Login" button. This prevents Weak Session Management (Session Fixation vulnerability) which will likely be spotted during a 3rd party Penetration Testing of your site.
Hope this helps.
Here's what worked for me, the only caveat is that this code need to be separated from your login routine.
Response.Cookies("ASP.NET_SessionId").Expires = DateTime.Now.AddYears(-30)
It will not take effect until the page is finished loading. In my application I have a simple security routine, that forces a new ID, like this:
if session("UserID") = "" then
Response.Cookies("ASP.NET_SessionId").Expires = DateTime.Now.AddYears(-30)
Response.Redirect("login.aspx")
end if
You may explicitly clear the session cookie. You should control the cookie name by configuration and use same name while clearing.
Edit:
Clearing session cookie when session is abandoned will force ASP.NET to create new session & sessionid for next request. BTW, yet another way to clear the session cookie is to use SessionIDManager.RemoveSessionID method.

How to detect session timeouts when using cookieless sessions

I'm currently working on a ASP.Net 3.5 project and trying to implement session timeout detection. I know how to do it with enabled session cookies, but without i'm totally lost.
When session timeout occurs i want to redirect the user to some custom page.
Can someone explain me how to do it?
My cookie based solution looks like this and i wan't to reproduce its behaviour:
if (Session.IsNewSession && (Request.Cookies["ASP.NET_SessionId"] != null))
Response.Redirect("...");
Session_End in the global.asax should always be fired, despite the type of session used.
-edit: you might also be interested in
Session.IsNewSession
as this gives you information on new requests whether the previous session could have been timed out.
It looks like i've found a solution. I'm not very happy with it, but for the moment it works.
I've added a hidden field to my page markup
<asp:HiddenField ID="sessionID" runat="server" />
and following code to my CodeBehind
public void Page_Load(object sender, EventArgs eventArgs)
{
if (Context.Session != null) {
if (Context.Session.IsNewSession) {
if (!string.IsNullOrEmpty(sessionID.Value)) {
Response.Redirect("~/Timeout.aspx")
}
}
sessionID.Value = Context.Session.SessionID;
}
}
You also need to add this to your Web.config or ASP ignores all posted form fields
<sessionState cookieless="true" regenerateExpiredSessionId="false"/>
regenerateExpiredSessionId is the important attribute.
It pretty much works the same way - the session service updates a timestamp every time ASP.NET receives a request with that session ID in the URL. When the current time is > n over the timestamp, the session expires.
If you put something in session and check to see if it's there on each request, if it is not, you know the session is fresh (replacing an expired one or a new user).
I'd take a look at the "Database" section of AnthonyWJones' answer to a similar question here:
ASP.Net Session Timeout detection: Is Session.IsNewSession and SessionCookie detection the best way to do this?
In your session start event, you should be able to check a database for the existence of the SessionID - I assume that if I request a page with the SessionID in the URL, then that is the SessionID that I'll use - I've not tested that.
You should make sure you clear this DB down when a user logs out manually to ensure that you store a new instance of your flag.
If you don't like Session_End, you can try a very quick and dirty solution. Set up a Session["Foo"] value in Session_Start in global.asax, then check for Session["Foo"] in your page. If is null, the session is expired..
This is one of the solutions proposed in the Nikhil's Blog. Check it.

how to change session id after login in asp.net

I have a website that's using forms authentication and membership. A user must have cookies enabled to use the site. I've been asked to change the code so that the session id is changed as soon as a user logs in. Aparently this will protect against a Session Fixation attack (http://en.wikipedia.org/wiki/Session_fixation). Does anyone know how I can change the session id without losing the whole session ? PHP has a specific method for doing this but I can't find a .NET equivalent.
Here's a blog post that talks about this:
ASP.NET does not directly support
functionality to regenerate a session
ID. See the documentation regarding
the issue here. There is a not-so
quick and dirty way to do it by
setting the ASPNET_SessionID value to
the empty string and redirecting so
that the value is regenerated.
I have answered a similar question at Generating a new ASP.NET session in the current HTTPContext. Basically we must change some of the SessionStateModule internal state to be able to regenerate session ID without losing objects in the Session. I used reflection to set the _rqId field to the new ID and _rqSessionStateNotFound to true. The downside is we must grant "Full Trust" to the Application.
This is a really old question I'm resurrecting, but here's the solution:
var manager = new SessionIDManager();
bool redirected, isAdded;
manager.SaveSessionID(System.Web.HttpContext.Current,
"5vonjb4mtb1of2fxvhjvkh5d", out redirected, out isAdded);
// sessionId now equals "5vonjb4mtb1of2fxvhjvkh5d"
var sessionId = Session.SessionID;
The method suggested in Microsoft's obsolete KB article 899918 works well even for .NET framework 4.5 Web Forms applications. Here is the archive of the article: https://www.betaarchive.com/wiki/index.php/Microsoft_KB_Archive/899918
How and why session IDs are reused in ASP.NET
Article ID: 899918
Article Last Modified on 9/8/2006
APPLIES TO
Microsoft .NET Framework 1.1
INTRODUCTION
This article describes how and why Microsoft ASP.NET session IDs are used.
MORE INFORMATION
The ASP.NET session state is a technology that lets you store server-side, user-specific data. Web applications can use this data to process requests from the user for which the session state was instantiated. A session state user is identified by a session ID. The session ID is delivered by using one of the following methods:
The session ID is part of a cookie that is sent to the browser of the user.
The session ID is embedded in the URL. This technique is also known as a cookie-less session.
Session IDs are a 120-bit random number that is represented by a 20-character string. The string is formatted so that it can be included in a URL and it does not have to undergo URL encoding. For example, the string may be used in cookie-less sessions. The most commonly used method of delivering session IDs is by using cookies to store the session IDs.
When a user first opens their Web browser and then goes to a Web site that implements ASP.NET session state, a cookie is sent to the browser with the name "ASP.NET_SessionId" and a 20-character value.
When the user browses within the same DNS domain, the Web browser continues to send this cookie to the domain for which it was sourced.
For example, app1.tailspintoys.com and app2.tailspintoys.com are both ASP.NET applications. If the user goes to app1.tailspintoys.com and then goes to app2.tailspintoys.com, both applications would use the same cookie and the same session ID to track the session state of the user within each application. The applications do not share the same session state. The applications only share the session ID.
Therefore, you can reuse session IDs for several reasons. For example, if you reuse session IDs, you do not have to do the following:
Create a new cryptographically unique session ID when you are presented with a valid session ID.
Create a new session ID for every ASP.NET application that is in a single domain.
When the Web application requires a logon and offers a log off page or option, we recommend that you clear the session state when the user has logged off the Web site. To clear the session state, call the Session.Abandon method. The Session.Abandon method lets you flush the session state without waiting for the session state time-out. By default, this time-out is a 20-minute sliding expiration. This expiration is refreshed every time that the user makes a request to the Web site and presents the session ID cookie. The Abandon method sets a flag in the session state object that indicates that the session state should be abandoned. The flag is examined and then acted upon at the end of the page request. Therefore, the user can use session objects within the page after you call the Abandon method. As soon as the page processing is completed, the session is removed.
When you use the in-process session state mode, these session state objects are stored in the HttpCache. The HttpCache supports a callback method when the following conditions are true:
A cache entry is removed.
The Session State Manager registers the Session_OnEnd event handler to be called when the cache entry is removed.
When the Session State Manager removes a session state object that resides in the cache, the HttpCache manager will call any registered callbacks. In effect, this behavior raises the Session_OnEnd event handler.
When you abandon a session, the session ID cookie is not removed from the browser of the user. Therefore, as soon as the session has been abandoned, any new requests to the same application will use the same session ID but will have a new session state instance. At the same time, if the user opens another application within the same DNS domain, the user will not lose their session state after the Abandon method is called from one application.
Sometimes, you may not want to reuse the session ID. If you do and if you understand the ramifications of not reusing the session ID, use the following code example to abandon a session and to clear the session ID cookie:
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.
When a user does not log off from the application and the session state time-out occurs, the application may still use the same session state cookie if the browser is not closed. This behavior causes the user to be directed to the logon page and the session state cookie of the user to be presented. To guarantee that a new session ID is used when you open the logon page (login.aspx), send a null cookie back to the client. To do this, add a cookie to the response collection. Then, send the response collection back to the client. The easiest way to send a null cookie is by using the Response.Redirect method. Because the cookies collection always has a value for the ASP.NET_SessionId, you cannot just test if this cookie exists because you will create a Response.Redirect loop. You can set a query string on the redirect to the logon page.
Or, as illustrated in the following code example, you can use a different cookie to tell if you are already redirected to the logon page. To help enhance security and to make sure that no one tries to open the logon page by using a second cookie together with the ASP.NET cookie, the following code example uses the FormsAuthentication class to encrypt and decrypt the cookie data. Then, the code example sets a 5-second time-out.
private void Page_Load(object sender, System.EventArgs e)
{
if( !IsPostBack && ( Request.Cookies["__LOGINCOOKIE__"] == null || Request.Cookies["__LOGINCOOKIE__"].Value == "" ) )
{
//At this point, we do not know if the session ID that we have is a new
//session ID or if the session ID was passed by the client.
//Update the session ID.
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
//To make sure that the client clears the session ID cookie, respond to the client to tell
//it that we have responded. To do this, set another cookie.
AddRedirCookie();
Response.Redirect( Request.Path );
}
//Make sure that someone is not trying to spoof.
try
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt( Request.Cookies["__LOGINCOOKIE__"].Value );
if( ticket == null || ticket.Expired == true )
throw new Exception();
RemoveRedirCookie();
}
catch
{
//If someone is trying to spoof, do it again.
AddRedirCookie();
Response.Redirect( Request.Path );
}
Response.Write("Session.SessionID="+Session.SessionID+"<br/>");
Response.Write("Cookie ASP.NET_SessionId="+Request.Cookies["ASP.NET_SessionId"].Value+"<br/>");
}
private void RemoveRedirCookie()
{
Response.Cookies.Add(new HttpCookie("__LOGINCOOKIE__", ""));
}
private void AddRedirCookie()
{
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,"Test",DateTime.Now,DateTime.Now.AddSeconds(5), false,"");
string encryptedText = FormsAuthentication.Encrypt( ticket );
Response.Cookies.Add( new HttpCookie( "__LOGINCOOKIE__", encryptedText ) );
}

abandon session in asp.net on browser close..kill session cookie

So I have a website where I use session start and end events to track and limit open instances of our web application, even on the same computer. On page unload i call a session enabled page method which then called session.abandon.
This triggers session end event and clears the session variable but unfortunately does not kill the session cookie!! as a result if other browser instances are open there are problems because their session state just disappeared...and much worse than this when I open the site again with the zombie session still not expired, I get multiple session start and session end events on any subsequent postbacks. This happens on all browsers. so how do I truly kill the session (force the cookie to expire)
I've always used this to make sure the user's session was gone:
HttpContext.Current.Session.Abandon();
If you are using FormsAuthentication you can use:
FormsAuthentication.SignOut();
FormsAuthentication.SignOut(); expires the authentication cookie but doesn't remove session cookie until the timeout period specified in web.config for sessionstate. If you want to remove session immediately, manually expire the session cookie as below.
var myCookie = new HttpCookie("ASP.NET_SessionId") { Expires = DateTime.Now.AddDays(-1D) };
Response.Cookies.Add(myCookie);

Can I abandon an InProc ASP.NET session from a session different than one making the request?

We have an application that does single sign-on using a centralized authentication server (CAS). We'd like to do single sign-out, such that if the user logs out of one application (say a front-end portal), the user is automatically signed out of all applications using the same single sign-on ticket.
The expectation would be that each application would register a sign-out hook (URL) with the CAS at the time of logon to that application. When the CAS receives the sign out request from one of the applications, it invokes the sign-out hook for all the application sharing the SSO ticket.
My question is this: is there a way to abandon an InProc session from a different session? I presume, since the HTTP request will be coming from the CAS server, that it will get its own session, but it is the session of the user that I want to terminate. I have pretty good idea of how to do this using a separate session state server, but I'd like to know if it is possible using InProc session state.
Haha, well... It looks like you can. I was wondering myself if there was any way to do this, turns out, there is.
When you use InProc, the InProcSessionStateStore (internal class) persist the session state in an internal (non public) cache. You can access this cache through reflection and remove the session state manually.
using System;
using System.Reflection;
using System.Web;
object obj = typeof(HttpRuntime).GetProperty("CacheInternal",
BindingFlags.NonPublic | BindingFlags.Static)
.GetValue(null, null);
if (obj != null)
{
MethodInfo remove = obj.GetType()
.GetMethod("Remove", BindingFlags.NonPublic | BindingFlags.Instance,
Type.DefaultBinder, new Type[] { typeof(string) }, null);
object proc = remove.Invoke(obj, new object[] { "j" + state.SessionID });
}
The end result is, that the next request will take on the same SessionID, but the HttpSessionState will be empty. You'll still get the Session_Start and Session_End events.
After doing a bit of digging around and considering the answers provided so far I've come up with an alternative that lets me continue to use InProc session. Basically, it consists of extending the HttpModule that already handles single sign-on to detected CAS sign outs and redirect the browser to the application sign out page.
Outline:
Sign-On:
For each new single sign-on request, create a new SSO cookie and encode a unique value in it to identify the session (not the session id, so it isn't leaked).
Construct the the sign-out callback url, encoded with the identifier, and register it with the CAS server.
Sign-Out:
When a sign-out request is received from the CAS server, decode the identifier and store it in an application-wide cache. This needs to be pinned in the cache at least long enough for the session to expire naturally.
For each request, look for the SSO cookie and check its value against the cached, signed-out session identifiers. If there is a hit, remove the SSO cookie and redirect the browser to the application's sign-out url.
For each sign-out, check to see if there is an SSO cookie, if so, forward the sign-out request to the CAS. In any event, abandon the user's session, and sign them out of the application.
Page_Load:
Check for the presence of the SSO cookie. If there isn't one, redirect to the sign out page.
No can do.
http://forums.asp.net/p/416094/416094.aspx#416094
With InProc SessionState, you won't be able to access the data... With StateServer, you still will have a sticky scenario trying to access the correct API to remove the session.
You will most likely want to use a database backed state solution like the pre-packaged SqlServer state provider or a third party solution like DOTSS: http://codeplex.com/dotss
With the database backed solution, you will be able to lookup the state record in a table by session id and mark it as completed. These techniques will vary based on the provider you choose.

Resources