Maintaining session after browser is closed - session

How does one implement maintaining sessions securely. Suppose just the login page uses SSL. So the user enters his usernamepassword and the http server verifies it is in the database and now what?
Does it set some cookie? If so then what should the cookie be set to so that security is maintained (encrypted, what kind of encryption)? Looking for a low level detailed answer. I hear there are various cookie hijacking concerns. If I only use SSL for the login but thereafter don't use SSL will the cookie be vulnerable?
Then after the browser is closed and the user comes back how does the cookie identify the username. How is this done securely without the cookie being stolen?

You definitely expose your clients to session theft if your connection is not encrypted at all times.
HTTP is a stateless protocol, so the only way to fake a stateful interaction is for client and server to send a session identifier with every transaction. If this isn't protected, it can trivially be stolen. Since the session identifier is the only authentication token during the open session, this is catastrophic.
The usual way to make a "remember me" feature would be to set a cookie whose lifetime is not limited to the browser's program lifetime (i.e. by setting an explicit expiration date), and storing some unique data in the cookie which you match against some remembering data (including the IP perhaps) in your database. But that does not absolve you from the need to encrypt all communication!

Related

Why do we need session , when we already have cookies?

I am new to web application , I am learning cookies and session, I understand HTTP is stateless protocol to make it stateful we use cookies at client side and session at server side.
When user requests a webpage it sends all the cookies available for that
browser on the PC.
If any one of the cookie matches with server side database , the server
shows the data , else sends set cookie with a session iD(optional to send
create session and send the session ID).
a. If server sends set cookie the client sends cookie in all respective
requests with the session id , only if the domain name matches with the
server to which the client sent .
Now my doubt is suppose I am working on an e-commerce site. And the server sends the number of items added to the cart till the user is not logging out , now it can be done using cookie alone why do we need session at all?
Is there something I am not understanding ?
These are separate concepts:
Cookie - Browser sends this with every request automatically
Header - Part of a HTTP request, the browser will only send data here if instructed.
Access token - Contains secret which may be a JWT (and identify the user) or a random set of characters
Session - a token bound to a user + device that authenticates the user. If the user doesn't have an access token, they can use the session to get a new token.
You can see that Cookie/Header are the where and access token/session token are the what.
The user needs to authenticate in your service. That means you need to be able to identify the user. That may be done with a JWT, session token, IP address, a signature, etc... And that is separate from how this data is transmitted to the service from the user.
So when you say why do you I need session when the user has cookies, these are totally unrelated. The session id may be saved in a cookie, that's just one option.
Whether or not the session id in a cookie corresponds to actual data on the server side is another completely separate question. Should the session token be a encrypted (or signed) object, like a JWT which contains user identifying information, or should that data be saved in a server side DB, and only transmit a random-string identifier. Who knows?
The answer is going to be based on what's critical for your application. Generally speaking, session tracking on the server side is a legacy concept, and the new hotness (which is old now), is to make the sessionId a JWT saved a HTTP Only cookie for security. And then passed on every request.
Lot's of services have sessions and access token management baked in, and for a working example and more about tokens, check out any one of many knowledge bases.
Because:
There may be, and probably is, sensitive data in that session, e.g. the user's id, identifying who the user is. If you just stored the user's id in a cookie, the user could manipulate it and easily pose as anyone else. There are of course ways to mitigate that, but simply not allowing the user to futz with the cookie contents (because it's just a meaningless session id) is the simplest.
It allows the server to manage session state; e.g. if a user suspects somebody is logged in as them on another device, they can invalidate all other sessions ("log me out everywhere" functionality).
You may be storing a lot of data, and sending it back and forth in a cookie on every request can become rather wasteful.
You may want to associate something like a shopping basket with the user's account, not just the user's browser, so when they log in on another device their shopping cart is following them around.
Yes, there are also perfectly fine cases were storing information just in a cookie is fine and preferable, especially since that allows you to scale your server more easily to a cluster of servers without having to worry about where the session information is stored. It depends on what information exactly you are storing.
The usual pattern is
the cookie contains only a unique session identifier (but no useful information itself)
the session storage (server-side) contains the associated data for this session. This can be a) very big and b) hidden from the user/browser and c) trustworthy (because the user cannot just modify it in the browser)
It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.

Prevent session from being replicated when JSESSIONID cookie copied

Background: I have a javaee webapp deployed on tomcat which uses form based authentication. When the web server receives a login request, it sends the request to a dedicated authentication service which validates user login (User id and password). After successful authentication user's session is maintained in the web server.
Problem: I have written a simple webpp source code here, to simulate the scenario. On successful login the current HttpSession instance is invalidated and new instance is created. For each request for a post login page, the session is validated. A new JSESSIONID cookie is set which is used to identify the user during the session until session is expired or user logs out. This cookie can easily viewed in browser's dev tools. If I copy the cookie and set this in a different browser via JavaScript (document.cookie="JSESSIONID=xyzz") and then try to access a post login page, the server identifies it as a valid request and session is validated successfully. The post login page is served without user being challenged for user Id and password.
POC: User opens chrome and enter the URL http://localhost:8080/mywebapp/ and logs in with admin and pass1234. On successful log in the home page http://localhost:8080/mywebapp/home is shown. Now the JSESSIONID cookie is copied and set in FireFox. User enters http://localhost:8080/mywebapp/home in Firefox and is shown the home page without being challenged for userId and password.
Question: How can this be prevented wherein same session is getting replicated over multiple browsers?
You can't prevent this specific case of simply copying the cookie from your own browser (or by copying the cookie value from a HTTP payload copypaste/screenshot posted by an ignorant somewhere on the Internet). You can at most prevent the cookie getting hijacked by XSS or man-in-middle attacks.
This all is elaborated in Wikipedia page on the subject Session Hijacking of which I snipped away irrelevant parts (either already enforced by Servlet API, or are simply not applicable here).
Prevention
Methods to prevent session hijacking include:
Encryption of the data traffic passed between the parties by using SSL/TLS; in particular the session key (though ideally all traffic for the entire session[11]). This technique is widely relied-upon by web-based banks and other e-commerce services, because it completely prevents sniffing-style attacks. However, it could still be possible to perform some other kind of session hijack. In response, scientists from the Radboud University Nijmegen proposed in 2013 a way to prevent session hijacking by correlating the application session with the SSL/TLS credentials[12]
(snip, not relevant)
(snip, not relevant)
Some services make secondary checks against the identity of the user. For example, a web server could check with each request made that the IP address of the user matched the one last used during that session. This does not prevent attacks by somebody who shares the same IP address, however, and could be frustrating for users whose IP address is liable to change during a browsing session.
Alternatively, some services will change the value of the cookie with each and every request. This dramatically reduces the window in which an attacker can operate and makes it easy to identify whether an attack has taken place, but can cause other technical problems (for example, two legitimate, closely timed requests from the same client can lead to a token check error on the server).
(snip, not relevant)
In other words:
Use HTTPS instead of HTTP to prevent man-in-middle attacks.
Add a checkbox "Lock my IP" to login form and reject requests from different IP associated with same session in a servlet filter. This only works on users who know themselves they have a fixed IP.
Change session cookie on every request. Interesting at first sight, but breaks when user has same website open in multiple browser tabs/windows in same "session".
Not mentioned, but make sure you don't have a XSS hole anywhere, else it's very easy stealing cookies.
Last but not least, I'd like to make clear that this problem is absolutely not specifically related to Servlet API and the JSESSIONID cookie. All other stateful server side languages/frameworks such as PHP (PHPSESSID) and ASP (ASPSESSIONID) also expose exactly the same security problem. The JSESSIONID was previously (decade ago orso) only a bit more in news because by default it was possible to pass the session identifier along in the URL (which was done to support HTTP session in clients who have cookies disabled). Trouble started when ignorant endusers copypasted the full URL with JSESSIONID inside to share links with others. Since Servlet 3.0 you can turn off JSESSIONID in URLs by enforcing a cookie-only policy.
<session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
How to prevent adding jsessionid at the end of redirected url
remove jsessionid in url rewrite in spring mvc
What you have stated is called session hijacking. There are many good answers on how to prevent it.
Using same Jsession ID to login into other machine
we can use Encryption or hide JSESSIONID using Browser control.
Thanks

OAUTH2 - Using refresh tokens to implement sliding expiration

I have a single-page web application that uses OAuth bearer tokens to authenticate users. We do not use cookies, and there is no support for sessions. It simply makes calls to an ASP.NET Web API to access protected resources with an access token. We also support refresh tokens to obtain a new access token.
How would I implement a sliding expiration? I only see three options:
Issue a new access token on every request using the refresh token. This defeats the whole purpose of refresh tokens.
Track when the last request was in the client app. Each request would see when the last one was, and if it was after a set period, log them out and bring up the login screen. If not and their access token has expired, issue a new one and let them continue. This seems kind of messy and insecure to me.
Forget refresh tokens. Store access tokens in a database with the expiration date and update it on every request. I prefer to not do a DB operation on every request.
Is there another option or do one of these actually sound acceptable?
You said there is no session support. But this is pretty much what sessions are for, and ASP.NET and IIS support them with quite a few options for how they are managed, with or without cookies and with or without a database if I recall right. If sessions are not available in your case...
There is also the option of using an encrypted token, which contains session identity and timeout info. Then the server merely needs to know the key for decrypting the token. The server decrypts the token on each request, updates the time and sends a new encrypted token back with the new response. You can send the token as a header, cookie, part of url, take your pick. But cookies and headers are designed for this use pattern and take less work in my experience.
A token that does not decrypt is treated as an unauthorized request. Timeout is handled as you normally would, e.g. using the refresh token to get a new authentication.
If you have a server farm, only the key for decryption has to be shared between the servers. No need for a session in a database or shared cache.
You can elaborate this to expire keys over time. Then servers only have to infrequently check with a directory service, shared cache, or database, message or queue to get the most recent keys. If you generate them properly and expire them faster than someone can brute force hack them, you win! (joke) Windows has apis to support you on the encryption and key management.
I did this for a project years ago with success. It is, in effect implementing sessions without server side state. And as with all session methods and all authentication methods it has vulnerabilities.
But without some special reason to the contrary, I would just use sessions for their intended purpose. If I want each browser tab to have separate authentication I would use header based session tokens. If I want browser tabs in a browser session to share authentication I would use session cookies.
Or I would use your option three, maybe with a shared cache instead of a database, depending on performance requirements and infrastructure. I suspect that IIS+ASP.Net may even do that for you, but I have been away from them too long to know.

Cookies vs Sessions for a secure "Remember me" functionality

I am using a computer in the place as work as a web dedicate server for the application. (so sessions won't be shared)
I want to develop a secure remember me functionality and i was wondering which is the best way to do it:
Sessions
Cookies
With cookies I would have to encrypt the user password, create some salts and add some fields in the database. (as detailed here or here)
Wouldn't it be more simple using sessions in this case configuring them to last longer?
Thanks.
Cookies.
You need to store some state on the client. The idea of "remember me" is that coming back to the same site without a session will still get you logged back in, without having a valid session established.
Cookies allow you to store state. There can be other ways to do it, but definitely not sessions.
Cookies vs. Sessions
PROS for Sessions:
Sessions might be easier to configure.
Sessions would work well for a limited number of extremely TRUSTED users
Cookies and Sessions have same threat model. If a hacker can decrypt a cookie he can decrypt a session
CONS
If your server is attacked, the attacker gains a context. i.e. a whole bunch of tokens via which he can decrypt the data
Sessions hold memory on the server side. Also session cookies expire when the browser closes. Though this could be re-configured (if you try really hard). You basically end up re-creating the cookie in a slightly new avatar.
All in all Cookies VS Sessions for "remember me" its cookies without a doubt.

What's the best way to use HTTP Authentication in an Ajax Application that's not 100% AJAX

I have a standard HTML login page, which I would much rather use than the standard HTTP authentication pop-up provided by browsers. Today, I am using session cookies to keep track of the session after logging in, but I'd like to be stateless and pass the HTTP authentication every time. The web services I am hitting already support this, so this is a browser-only issue.
Adding authentication credentials is trivial in jQuery, but I don't know how to keep them around. If you go from the login page (a jsp) to the Home page (another jsp) you clearly don't keep the username and password fields from the login page. I know some browsers will store your HTTP authentication credentials if you enter them from the pop-up, but I don't know if they get stored when using an XHRRequest. If they do, is there much consistency among browsers?
Also, the user needs to be able to "sign out" of the application, too. If the browser stores the authentication credentials, is there a way to clear them using JavaScript.
I feel like I can't be the first person to try to solve this. Is there some jQuery plugin or something that already handles this? Or is it simply not possible to do what I'm trying to do?
You have 2 options:
1) Client-side storage of credentials -- not a good idea. For obvious reasons you don't want to store the username/password on the client. If you had a hashed version of the password, it might not be so bad, but still not recommended. In any case, if you're going to store on the client side, you either have to use a cookie, or HTML5 local storage (which is not widely supported, yet)
2) Server-side storage of credentials -- typically done with sessions. Then the resultant Session ID can be passed back to the client and persisted in either a cookie or in the URL of each subsequent AJAX call (?SESSID=xyz for example)
The server-side approach would be the most secure, reliable, and easiest to implement
Okay, I'll take a stab at helping ...
Firstly, understand how HTTP authentication works. There are two versions - Basic and Digest. Basic transmits in plaintext, digest is encrypted. With these types of authentication, the username/password are passed in the HTTP header with every single request. The browser captures these at login and they are stored in an inaccessible browser session cookie which is deleted when the browser session is closed. So, in answer to one of your questions, you can't access these from javascript.
You could create your own session cookie variables for username and password. The jQuery functions for this are really simple. See jquery-cookie module as one example of how to set session cookies. These could be retrieved from the session cookie and sent with each ajax request and validated in the server. However, this is not a particulary good way to do authentication since sniffing the network will allow anybody to easily grab your auth details. But, it would work.
Using session cookie based authentication where the session ID is sent sent with each request is the best way to do this. At the server side, you need to have a function called for every HTTP request. This function should do the following:
check to see if the session has been authenticated
if no:
redirect to login screen
if yes:
do authorization and allow the user access to the page
Most web frameworks support session cookie authentication and the management of session ids at the server. This is definately the way to go.
This is interesting one.
Manage user sessions on server by use of cookies. Create a session when user first accesses the login page and pass the session id/key as value to one of the cookie via response. When the user is authenticated put user "key" info in cookie and "values" in application context at server. Once user is logged, any subsequent request will be authenticated based on session cookie value at server. Authorization will be done based on user "key" passed as cookie value.
On logout clear the session based cookies from server and refresh the site to default page.
Cookies are bizarre with different browsers - just a note ;)
Hope this helps.
Update
The answer below was posted in 2012 and the links are mostly dead. However, since then, a more elegant standards-based approach to the same solution appeared using JSON Web Tokens. Here is a good blog post explaining how to use them.
Most answers miss the point, which is to avoid having any server-side session. I don't want any application state in the server. I'll award the bounty to answer that came closest, but the real credit goes to the rest-discuss group and Jon Moore for the correct answer and to Mike Amundsen for helping me to actually understand it.
The best answer I've gotten is to use a cookie, but not the typical automatic session id cookie given to you by most application servers. The cookie (which will automatically be sent with each subsequent request) is a user identifier and time signed by the server. You can include an expiration time with the cookie so it simulates the typical 30 minute session on a server (which means you have to push it forward with subsequent requests) as well as keeps the same cookie from being valid forever.
The XHR/AJAX part is a red herring. This will work whether you are doing XHR requests or an old-fashioned page-by-page web application. The main points are:
The cookie is automatically sent on subsequent requests so there's no
special scripting required - it's just how browsers work already.
The server does not need to store any session for the user, so the user
can hit any server in a cluster and not have to re-authenticate.
Slightly interesting in that you consider pushing some of the authent to the client. If you want a conventional solution, KOGI's server-side suggestion is the way to go.
But you also seem to be asking questions about memory leaks involving your user supplied secrets. Good questions. But to take a general stab at answering that I'd say it would have to be browser specific. It's browser internals, javascript engine internals -dependent where a client side application (i.e., the browser, or js in the browser) is storing the values the user inputs.
Most likely those values are not replicated needlessly throughout memory, but there's no way to guarantee that. Apart from responsible javascript coding practices, there's nothing you can do to guarantee the limit of locations of user inputs.
Slight digression
The basic point is if you store it on the client it is not really secure -- unless, the serve stores encrypted information on the client with a key that only the server (or the user via their correct credentials), has. So you could conceivably code a JS application to do some authent on the client -- much the same as how bank card (used to?) do POS authent by checking the PIN to the PIN on the card, and not back at the DB. It's based on the (somewhat flimsy) assumption the user has no direct read/write access of the "dark area" cookie/local storage on client / mag strip on bank card. So I would only advise this as disqualifier for false authents and not as a sole qualifier for the credentials.
Main point
If you do want to be stateless, just store user credentials in localstorage, or as a cookie but encrypt them with a server key. When you need them send an XHR with the encrypted / use stored credentials to the server over HTTPS, let your server decrypt them and send them to the callback. Then pass those cleartext of HTTPS to do your authent.

Resources