How does RememberMe setting work with WebSecurity in an MVC project? - c#

In a sample/default MVC 4 project, I can see that when the User logs in with Remember Me checkbox on, the persistCookie parameter of the WebSecurity.Login method is set to true.
How exactly does that work? Where exactly is the value of persistCookie is saved? I looked through the tables that are created for the Security feature and do not see anywhere that the user is set to persist login.
What mechanism enables the user to log in? Is it simply the presence of the .ASPXAUTH cookie? Or does it actually compare the cookie value to something that I am not seeing.

How exactly does that work?
By creating a persistent cookie.
Where exactly is the value of persistCookie is saved?
As a file on the client machine so that it survives browser restarts.
What mechanism enables the user to log in?
This mechanism is called persistent cookie. A cookie is considered persistent if when being set the Expires property is being set to some date in the future. In this case the browser will store the cookie on the client computer as a file instead of keeping it in memory.
Here's an example of how creating a persistent cookie looks like in terms of the HTTP protocol:
Set-Cookie: CookieName=CookieValue;Path=/;Expires=Wed, 12-Oct-2016 21:47:09 GMT;
And here's how a setting a session cookie looks like which will not survive browser restarts:
Set-Cookie: CookieName=CookieValue;Path=/;
Now go ahead, download Fiddler and inspect the network traffic to see the difference.

The identity is stored in the cookie and decrypted upon each request.
Persistent cookie means that the cookie will be automatically attached to requests by the browser for some period of time.
No magic and also no need to store open sessions at the server side. As long as a cookie decrypts correctly, it is accepted as the server assumes that no one is able to forge a cookie on its own. This requires that the cookie value is encrypted or at least signed.

Related

What happens when I modify a session Id?

I'm exploring cookies and sessions [I'm using them with respect to ASP.NET C# microsoft framework]
Learnt how sessions and cookies work here and here.
My take on it is like,
Once a user logs in and establishes a session, he or she is given a session id to track them further.
Also, this sessionId can be stored on a Server, like SQL Server or a InProc, meaning it is stored on the issuing server or on a cache, Redis Cache.
My question is like,
I can understand that the sessionId is stored in a memory and being sent with every request (since HttpSessions are stateless) as HttpHeaders.
When we talk about storing sessions in a memory, which memory are we talking about ?
If we are storing them in a cookie, what If I go and modify the cookie ?
If I can modify them, what If I change the sessionId and supply in a new sessionId ?
1. When we talk about storing sessions in a memory, which memory are we talking about ?
Ans: InProc mode, which stores session state in memory on the Web server (RAM). This is the default.
2. If we are storing them in a cookie, what If I go and modify the cookie ?
Ans : Only session id is stored in cookie. If you don't want to use cookies for session tracking, asp.net framework also supports it by appending it in the URL. If you change the cookie value, the server will not be able to identify the request with the stored session data. You need to understand the http is a stateless protocol, sessionid is the identifier of a browser for the request during roundtrips. If you change the cookie value, server will not be able to identify the request.
By luck if you supply a valid sessionid, server will serve the content stored in session against that id. This is called session hijacking
https://en.wikipedia.org/wiki/Session_hijacking
3. If I can modify them, what If I change the sessionId and supply in a new sessionId ?
Ans: If you are taking about the SessionId of System.Web.SessionState. It can't be changed as it is readonly. But you are free to change anything at the client side (Cookie or URL)
Namespace: System.Web.SessionState
Assembly: System.Web (in System.Web.dll)
public string SessionID { get; }
The session data is stored on the server, either in memory or in a database. This data is looked up with a sessionId that is stored in a cookie.
2/3. Modifying the sessionId is known as session hijacking, and allows you to "be" that user. This is commonly exploited with attacks like cross-site scripting (XSS).
To protect against hijacking make sure that:
The cookie is encrypted. There are ways for ASP.NET to do this for you, but this way it cannot be tampered with
The cookie is set to HttpOnly. This ensures that the cookie can only be sent over http requests and things like javascript - and thus XSS attacks - don't have access to the cookie.
If you are using something like ASP.NET Session State, change the default name of the cookie so it is not easily recognizable

Cookie safety issues

How can I remember a user that is logged in without having a security issue? Currently, I am storing the id and a guid into two different cookies and compare them when there is no session alive. If it match then I re-create the session. Btw, both id and guid are nore encrypted.
Is this method safe enough, or should I follow a rather distinct way?
Since cookies can be easily stolen by use of XSS, does not matter if you place information in just one cookie or two, because a theft will take them all.
I have solved with a more complex procedure: I place one encrypted cookie divided in 2 parts (but 2 cookies will work as well), one fixed and the other variable each session. Both are saved also on server side to check: they are only session identifiers, no sensible information contained in the cookie, the correspondence with the user id is saved on the server.
If a fake user enters the account with a stolen cookie, the variable part (or cookie) will change, so when real user connects again he will not be able to enter and you will have the proof that an unauthorized access occurred: then you can delete the permanent session on server side (defined by the fixed part or cookie) in order to avoid any further access by the theft. The real user will re-login and create a new permanent session with a new cookie. You can also warn him that you saw a security flaw, suggesting him to reset password (operation that should never be accessible directly from cookie) or to use another browser for unsafe navigation.
If you save additional user information (user-agent, IP by location) you can check cookie validity also on them in order to avoid even the first entrance of the fake user.
I would recommend you using forms authentication for tracking logged in users in an ASP.NET application.

if cookies are disabled, does asp.net store the cookie as a session cookie instead or not?

basically, if cookeis are disabled on the client, im wondering if this...
dim newCookie = New HttpCookie("cookieName", "cookieValue")
newCookie.Expires = DateTime.Now.AddDays(1)
response.cookies.add(newCookie)
notice i set a date, so it should be stored on disk, if cookies are disabled does asp.net automatically store this cookie as a session cookie (which is a cookie that lasts in browser memory until the user closes the browser, if i am not mistaken).... OR does asp.net not add the cookie at all (anywhere) in which case i would have to re-add the cookie to the collection without the date (which stores as a session cookie)... of course, this would require me doing the addition of a cookie twice... perhaps the second time unnecessarily if it is being stored in browsers memory anyway... im just trying not to store it twice as it's just bad code!! any ideas if i need to write another line or not? (which would be)...
response.cookies.add(New HttpCookie("cookieName", "cookieValue") ' session cookie in client browser memory
thanks guys
This MSDN article seems to indicate that there is no built in mechanism for compensating with the user disabling cookies. It also indicates that session state does not work without at least some level of cookies being enabled.
I thought that there was a mechanism for passing a query variable for the session id but skimming the article (quickly) I did not see this.
Hope that helps.
EDIT: It does say that you can use cookieless sessions (I thought you could). They use a separate mechanism to embed session ID in the pages and url links.
To follow up on GrayWizardx's reply, much of what was said is completely accurate.
If you are using a Cookie'd version of Session, and cookies are disabled then you are out of luck. But you have the option to have a cookieless version of the Session, which adds a string to the URL that shows the users session id. This is very ugly looking, and has always concerned me from a security perspective.
So you have three options (that I can think of off the top of my head):
1. Require cookies. This is not a bad thing, especially if your site is one that would have requiring cookies as normal.
2. Use ViewState.
3. Pass information from page to page within the URL. This, again worries me from a security perspective.

What is the difference between a Session and a Cookie in ASP.net?

What is the difference between a Session and a Cookie?
What circumstances should each be used?
Sessions
Sessions are stored per-user in memory(or an alternative Session-State) on the server. Sessions use a cookie(session key) to tie the user to the session. This means no "sensitive" data is stored in the cookie on the users machine.
Sessions are generally used to maintain state when you navigate through a website. However, they can also be used to hold commonly accessed objects. Only if the Session-state is set to InProc, if set to another Session-State mode the object must also serializable.
Session["userName"] = "EvilBoy";
if(Session["userName"] != null)
lblUserName.Text = Session["userName"].ToString();
Cookies
Cookies are stored per-user on the users machine. A cookie is usually just a bit of information. Cookies are usually used for simple user settings colours preferences ect. No sensitive information should ever be stored in a cookie.
You can never fully trust that a cookie has not been tampered with by a user or outside source however if security is a big concern and you must use cookies then you can either encrypt your cookies or set them to only be transmitted over SSL. A user can clear his cookies at any time or not allow cookies altogether so you cannot count on them being there just because a user has visited your site in the past.
//add a username Cookie
Response.Cookies["userName"].Value = "EvilBoy";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(10);
//Can Limit a cookie to a certain Domain
Response.Cookies["userName"].Domain = "Stackoverflow.com";
//request a username cookie
if(Request.Cookies["userName"] != null)
lblUserName.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
sidenote
It is worth mentioning that ASP.NET also supports cookieless state-management
Cookie is a client side storage of your variables. It stored on client machine by browser physically. It's scope is machine wide. Different users at same machine can read same cookie.
Because of this :
You should not store sensitive data on cookie.
You should not store data that belongs to one user account.
Cookie has no effect on server resources.
Cookie expires at specified date by you.
Session is a server side storage of your variables. Default, it stored on server's memory. But you can configure it to store at SqlServer. It's scope is browser wide. Same user can run two or more browsers and each browser has it's own session.
Because of this :
You can save sensitive data in session.
You should not save everything in session. it's waste of server resources.
After user closes browser, session timeout clears all information. (default is 20 minutes)
A cookie is an identifaction string stored by a server (who has a domain) in the browser of the user who visits the server/domain.
A session is a unit of maybe variables, state, settings while a certain user is accessing a server/domain in a specific time frame. All the session information is in the traditional model stored on the server (!)
Because many concurrent users can visit a server/domain at the same time the server needs to be able to distinguish many different concurrent sessions and always assign the right session to the right user. (And no user may "steal" another uses's session)
This is done through the cookie. The cookie which is stored in the browser and which should in this case be a random combination like s73jsd74df4fdf (so it cannot be guessed) is sent on each request from the browser to the server, and the server can assign and use the correct session for its answers (page views)
The cookie allows the server to recognize the browser/user. The session allows the server to remember information between different page views.
Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit.
Its possible to have both: a database primary key is hashed and stored in a lookup table: then the hash is stored on the client as a cookie. Once the hash cookie (hahhahaha :) is submitted, its corresponding primary key is looked up, and the rest of the details are associated with it in another table on the server database.
The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not. This difference determines what each is best used for.
A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie.
Session is a server side object,
which transfer or access data between page call.
Cookies is a object which is client side/client machine which store some text information of browser and server.
There appears to be some confusion regarding what a session cookie is.
Firstly, when we are talking session cookies - it has nothing to do with ASP.Net sessions. Likewise, session cookies have nothing to do with server side processes or caching.
A session cookie is nothing more than a cookie that expires when the browser session expires. To create a session cookie - don't put an expiration date on it. Doing this stores the cookie in memory and is disposed of when the browser is disposed.

Image caching, HTTPHandler and FormsAuthentication

The Setup:
I'm working on a website that uses Formsauthentication using cookies to store the login ticket. The site also has an HTTPHandler that manages images stored in the database. The handler caches the images to be public and expire in 20 minutes. We have noticed that since the images have the same lifecycle as a page the images also include the Formsauthentication cookie. The configuration is IIS 6, Win2k server, Content Expiration is not enabled.
The Problem:
What we are experiencing is Person A logs in and hits a couple of pages. Then Person B hits the default page not logging in and get's the cookie for Person A and is able to see all of Person's A data. We have reproduced the problem once by turning on Content Expiration in IIS but have not reproduced consistently so we are not sure if Content Expiration helped us reproduce it. We are assuming since the images are being cached as public and they also contain the cookie with the FormsAuthentication, it's somehow possible for Person B to unintentionally get Person A's cookie. We know this isn't a attack on the website.
Has anyone experienced anything similar to this behavior? If so, can you provide any advice on how to reproduce this issue consistently?
We are assuming the cookie is in the Response Header and is writing out the same cookie that exist on Person A's machine to Person B. Its important to note that this issue occured with Person A in IE 7 and Person B in FireFox. Also when Person A logged out it logged out Person B was logged out as well since the Formsauthentication ticket was no longer valid on the server. So yes they did have differnet cookies but the same formsauthentication ticket within each of thier cookies. One was however generated without logging in.
We also found this article but haven't been able to confirm if this is the cause. http://support.microsoft.com/default.aspx?scid=kb;EN-US;917072
I'll see what LiveHTTP tells me and will report back. Thanks.
Why does Person B get Person A's cookie? I'm assuming you mean Person B's session cookie is being associated with A's login ID. That's the nub of the problem.
It sounds to me that A's login ID is being stored in a place that could cross requests -- such as a temp file or in the DB -- without associating it with a session cookie. (Related issue: Page output is being cached, but not properly associated with or retrieved via the session cookie.) When session information is stored or cached, it must be associated with the cookie. Think in terms of session data belonging to a brower, not a login.
I would install the Firefox extension LiveHTTP and examine the request/response headers. My bet is, you'll see A and B have different cookies, but on the server they're both associated with the same login ID.
Sure, if those images (and CSS and static JS files, etc...) aren't being served as HTTPS, they'll be subject to caching by ISPs or other proxies (well, caches actually), along with their cookies.
There's a caching directive something like this:
Cache-control: no-cache="set-cookie,set-cookie2"
...which is supposed to instruct caches not to cache the "set-cookie" response headers, but I'm not sure how widely supported this is (despite it being standard).
Avoid set-cookie response headers when serving images if you can (might not be easy if you're not in complete control of session management). If a user must be authenticated to see certain images, then those images shouldn't be publicly cached anyway.
Sorry I forgot to mention that all traffic was going through port 443 as SSL. We are planning on removing the set cookie for images. However, we are little confused how this could happen when all traffic is processed through SSL.
All traffic was SSL... reviewing the IIS logs everything was going through port 443. The only caching that was being set was on the images to public as mentioned earlier. Our assumption is this is in result output caching causing the issue.
Are you sure you don't have something like output caching enabled on the page?
It may help to install Fiddler to investigate your http requests as specified above. Also, confirm the cookies are the same. Does your handler, or forms authentication system use a static object reference? You may have a race condition in your code. and aren't properly locking your resources.

Categories

Resources