session aware applications - session

I intentionally wrote 'session aware' instead of 'session shared' applications. Following is a scenario:
I have a webapp (WA1) deployed in one instance of Tomcat.. Assume that all apps are deployed on root and we are not dealing with contexts. This application allows users to login, do their thing on site and logout.
There is another webapp (WA2) on another tomcat instance. This application handles a service, lets say, it reads some files and streams to the browser.
WA1 serves a page which has a link that links to WA2.
Now I have a valid session in WA1 which identifies who the user is and if the session is a valid session. I would like WA2 to know it before honoring the request from the page served by WA1.
What is the best way to handle this?
I have ruled out sharing sessions (unless that is the better way, please explain), due to the reason that WA1 could be itself load balanced and WA2 could be load balanced, and to keep shared sessions over two load balanced instances of the app may get overwhelming.
I am leaning towards a 'token' mechanism.. where WA1 creates a token associated with every session and makes it available to every url to WA2 from any page served from WA1. WA2 would first inspect the token, and see if it is a valid token (many ways to do this: A: make a web-service call to WA1 to ask if token is a valid session token.. B: WA1 persists to DB or file system and WA2 seeks from there.. ), and if it is valid, then honor the request. The issue here would be to make sure that the token is invalidated when a session in WA1 expires.
I would like to know if this approach is good enough, or are there better ways to do this?
Thanks
M. Rather

By default, the servlet API uses a cookie, typically named jsessionid, to store a session ID in each browser. Then, the browser passes the cookie to the server with each request. As long as both instances of tomcat are within the same domain, they should both have access to that cookie. Unless I'm missing something, it's just a matter of testing for that cookie in the second application.
Update: Even if each instance of tomcat runs in a different domain, they can still share these cookies by calling the setDomain(String domainPattern) method of the Cookie class.

Related

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

How do I properly secure a REST-like service using Spring Security based on cookies?

I read this article on using Spring Security to "secure" (password-protect) a REST-like service: http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/.
This solution is what I seem to want, however, I noticed that at the bottom of the article, the authentication process is based on a cookie. If you notice, after a user logs in, a cookie is sent back to the user, and the user keeps using this cookie on subsequent request to access the REST endpoints (see the curl commands).
My concern about this approach centers on security; meaning, what's to stop the user from sending this cookie to someone else for use or someone from copying this cookie and using the REST service without proper authentication?
Is there a way to set the cookie (or cookies) such that it is valid for only one user? For example, for only the IP that authenticated correctly? But even this is problematic, as multiple users may share one external IP address.
It looks like the code is just demonstrating how to maintain a session between requests, exactly as your browser would do, by storing the JSESSIONID cookie. So I think your question is really the same as "what's to stop a user from copying the session cookie from their browser and giving it to someone else?". Of course there is nothing to stop them doing that but why would they want to? The same argument applies to any kind of security token. There's nothing to stop them giving away their username and password either which would have the same effect.
In most cases a web service would be stateless, so it wouldn't use session cookies. But OAuth tokens and so on are just as sensitive, often more so since they usually have a longer life span.

What exactly is meant by session in the context of a Web Application

I did a little bit of Web Programming here and there but I never quite understood what's meant by the word Session.
I've googled a bit here and there, read the Wikipedia article, but could never quite grasp the meaning of it.
So, what's a Session?
Session is a way of persisting your information across multiple pages and requests. When you visit the login page of any site and you provide your username and password, you won't need to provide them again on subsequent pages.
This is done by attaching a session id, unique to your request, and is sent back and forth as you navigate pages.
Session Id could be stored in cookies (file on your system), in the URL as part of query string or in the database
A session is a place for storing data for a particular visitor of your site.
You can store data there that is also available on the next page request from that visitor. If some data is stored 'in the session', it means that the data is stored somewhere (possibly in the database of the server or in files) which the server can then use to construct the web page.
The visitor will receive a temporary cookie which contains a session id, an identifier which is used to associate that visitor with the session data that is stored on the web server.
The session id is sent to the server with each request and the server can lookup the stored session data (which can then be used to construct the web page).
It's the concept of keeping state around over an inherently stateless protocol like HTTP.
If you want to keep track of a logged-in user, for example, and maybe some data associated with that user, you could send that data between the server and the client each time, which of course would be terribly insecure. Or you could keep it in a session store on the server, for example a file or a database, and just exchange an identifier for the storage location between client and server. That's usually done via cookies these days, but could also be a parameter in the URL.
To make it simple:
If you first visit the site, the server gives the client an identifier. With this the server can identify a client across several request from the client to the server. The identifier is deleted after a preset time.
The combination of this identifier and the timeframe the identifier is valid, is called session.
Hope that helps. :-)
Session: An interaction between user & server, which has an ID associated with it. So that server can pin-point & serve the users according to their requests. Cookies are basically used for storing the session information because by default HTTP is state-less.

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.

Codeigniter session security

How can I increase the security of my sessions?
$this->session->userdata('userid')
I've been throwing this little bad boy around for my ajax calls. Some cases I haven't. Then I was like, is this really secure using id from the DOM? what if the DOM is changed to hack user accounts data? So then I was like I guess anytime a user is doing something relating to their id, only sessions should be referenced. Am I right?
Referenced like so:
$this->some_model->do_data_stuff($dataId, $this->session->userdata('userid'));
Then I read this:
While the session data array stored in the user's cookie contains a
Session ID, unless you store session data in a database there is no
way to validate it. For some applications that require little or no
security, session ID validation may not be needed, but if your
application requires security, validation is mandatory. Otherwise, an
old session could be restored by a user modifying their cookies.
http://codeigniter.com/user_guide/libraries/sessions.html
I'm not going to be storing financial data but I don't want any data on my site corrupted ever. Does SO use session validation? How much overhead will this validation cost? How would a session be hacked? What are some things to look out for with session security?
Using CodeIgniter sessions with database is going to be fairly secure. You just don't have to trust the input that the user gives. Even if you are using AJAX, the CodeIgniter session will work just like any standard call, so the same security goes on.
What happens with the CodeIgniter session is that the server stores the cookie, and every time the user does an action that would change the content of the cookie, it is first compared to the previous cookie.
If the user changes the content of the session cookie in the browser, CodeIgniter will notice on the next server call, and create a new session for the user, basically logging him out.
CodeIgniter doesn't really need the data stored in the cookie in the user's browser, and as long as you're using
$this->session->userdata('userid');
you're going to get trusted server-side data. The user can't change that. Furthermore, the cookie can be encrypted, and you should have it encrypted. Just look in config.php of CodeIgniter.
There are several other protections around the session data: the short refresh timeout (usually 300 seconds), it checks if the IP changed, and if the browser changed. In other words, in the worst case scenario, the only way to spoof the session data is by having the same version of the browser, having the same IP, getting direct access to the computer to copy/paste the cookie, and getting this done within 5 minutes.
So, watch out for the guy sitting beside you!

Resources