How to maintain session in java - java

I know following are the ways to maintain or session tracking in java but looking for a good one
URL rewritting
Hidden form fields
cookies
Session object like setAttribitute() and session.getAttribute()
If the client browser has blocked accepting and storing cookies then last 2 ways are not valid.In hidden form fields I need to pass the hidden values in each and every page inside form.So suppose If I am just using response.sendRedirect() Then hidden form field is of not use.The remaining is URL rewriting in which I will pass JsessionID in the URl.So My question by knowing the sessionID isnt the unauthorized persons can able to access the pages.
For example There are 3 pages login,register,send.So after login user can register and/or send.So if any one knows the sessionID cant he/she go direct to register/send page.If yes Please tell me how to prohibit this

As of Servlet 3.0 (Apache Tomcat 7 onwards) if you use SSL then you can configure your application to track sessions based on the SSL session ID. The downside is that everything has to be over SSL. The advantages are that the session is strongly tied to the SSL connection. Only the user that created the connection to the server that has the correct SSL session has access to the session. Even if an attacker knows the session ID, they can't access the session.
One word of caution, this form of session tracking is the least widely used so it may not have been as heavily tested as the more usual cookie and URL re-writing mechanisms.

Have a look at this link which outlines Best practices for using HTTP sessions
Including
javax.servlet.http.HttpSession.invalidate()
Use HTTPS

With standard solutions you can't.
You can add some measure of security by adding request originator IP address verification, but that's also fooled easily. (to clarify some here means very tiny itsy bitsy little bit of)
So the secure route is to not use URL Rewriting to maintain session in secure application.
However you may be able to get some security by keeping the JSessionID as a separate encrypted attribute that which will be decrypted by a middle-ware or a load balancing server sitting between the client and your application servers. This of course is just a thought, I haven't, fortunately ever had to try something like that out :-)

Session tracking & authentication are two diff things don't club them.
Understanding your requirement I see you want to secure the sessionid of the user.
Evasdroping: If someone is listing to the request & response in the middle he can take the sessionid and use it. The best way would be to use a SSL. This ensures no one is listening in the middle.
Sessionid stolen from Client side: Normally this should be taken care by the browser and OS. So your user is as secure as the system he has.

Related

Logout in token-based authentication and Single page application

I'm using JWT authentication for my Spring Boot application. The front-end is going to be a single-page-application.
Should I handle logout functionality on the server side? As far as I understand, there's no way to invalidate a JWT token unless we have a stateful server (storing logged out tokens for the maximum lifetime of a token).
The SPA passes the JWT token every time making a request in its header, and it can delete it from the localStorage when the user visits /logout without making a call to the server.
What are the potential issues? Is this idea used anywhere else? What is the best practice?
First of all you must decide wether you want a statefull server, or not.
statefull server
this is easy. Just send a logout request to the server and throw the session away. That's it. That's the safest way.
stateless server
I like stateless servers because you don't have to manage the state. But of course you have a tradeoff. In this case the securety. There is no way to logout because you don't have a session that you can invalidate on the server side.
So an attacker which steels your JWT-token can use the session until it ends and there's nothing to do to prevent this.
But you can do something to avoid that the atacker can get the JWT Token. Here are some things that you can do and that you have done already right
Don't use cookies to send the token. The way you do it is perfect. Use the header. This is encryptet by SSL and Single-page-app must send it on purpose.
Put a timestamp into the JWT-Token so that it invalidates itselve after some time. But be aware of effects like Timezones and Clocks wich are out of sync.
Put some browser fingerprinting information into the Token like the OS or the Browser version. In that way the atacker has also to fake that.
But these mechanisms are all there to make it harder for an atacker. A real logout is not possible.
Note
If you use JWT correctly your server will have a "state". You have to define a secret that is the same on all servers. That's something you must be aware of, if you use multiple servers.

Workaround to share session cookie between two domains in Apache Tomcat

I have a website under a domain called www.example.com.br. And my server is set to work with cookie session tracking mode.
getServletContext().getSessionCookieConfig().setDomain(".example.com.br");
getServletContext().getSessionCookieConfig().setPath("/");
But now I'm introducing an english version of the website under www.example.com, because for Google and SEO techniques it's better to have different domains instead of a subdomain.
I found a lot of questions in Stack Overflow about this, and I know it's impossible for a lot of security reasons.
But isn't there anyway to tell Tomcat to work with a cookie domain .example.com.br if the URL has .com.br and .example.com if the URL has .com? I don't need to share session information... ie: the user may have to login again if he changes the domain. I'm not worried about it. The problem is that no information on the .com version is been stored at all, because the cookie is set to .com.br version.
Isn't there any workaround for that?
It is user's browser that decides whether to send the cookie with the request or not. Web server (Tomcat, in your case) does not have any say in that decision. What you are asking for explicitly forbidden. For example, RFC2109 says:
A user agent should make every attempt to prevent the sharing of
session information between hosts that are in different domains.
The best recommendation I can make is to make your session management (login, logout, ...) work off a single domain, regardless of what domain user originally accessed.

Securing every request of a session by challenge/response?

We need to design a secure web application. I would like to propose a session handling mechanism which does a challenge-response on every request, not only during login using a CRAM method.
The reason is to harden the web application against session hijacking (eg by CSRF) and replay or man-in-the-middle attacks.
Using a nonce is suggested in some places, but in our webapp it seems impractical, as asynchronous requests can go on, or the user could open new windows, hit the back button etc.
Idea: The client and the server have a shared secret (a previously established user password), every subsequent request does again a challenge/response based on that secret, e.g 'response = hash(challenge + hashedPassword)'. The server executes the request only if the response to the challenge matches. Much like during CRAM, but ongoing for every request.
The question: Is this a feasible idea? If so, it surely has been implemented or is even some standard? How would we use this in a java or php based webapp?
The question really comes down to what you want to achieve. If you want to fight CSRF-Attacks, a secret token in addition to the session key is your way to go. However, changing the token in every request will cause problems - not only will the back-button kill the session, but as one webpage usually contains a lot of asynchronously and parallel loaded data (images, css, javascript, etc.), your approach will not enable any additional data to be loaded afterwards, as each additional request will change the required token, thus killing the session.
You may get around this by embedding all resources into the page via BASE64 and other tricks, but that will seriously hinder your possibilities and may have compatibility issues with some browsers.
So, in the end, your approach will not add much security, but will most likely create a whole set of potential problems for your customers. I'd stick to one secret token per session in the URL to fight CSRF and concentrate on securing against other attacks like XSS and user-friendly security measures like two-factor authentication with a smartphone or something similar. After all, the user is the #1 attack vector nowadays.
Update (2012-06-14)
The token will not fight XSS-attacks, but it will defend against basic CSRF-attacks (e.g. by implanting a bogus url call in an image). I've actually had a situation at work today, where I needed to secure a get-request against user modification and worked up some code. The code may be also usable to secure static, session-timeout form- and link-tokens (right your problem).
The idea is to have a server-secret, which is used to generate a hash/AuthToken over data to secure. If a rogue javascript would try to change any of the given data, the AuthToken would not match. In my specific problem, I have one server authenticating a user and have to send his information over to a third party (username, mailaddress, name, etc.). This GET-Request might be easily changed by any user after authentication, so I have to authenticate the GET-Request-Parameters. By rerunning the AuthenticationToken-Process, the third party can compare the resulting AuthTokens, thus validating the incoming data. Without the shared secret, it is (near-to) impossible to forge the data.
On your problem: Having a static token on GET and POST-requests (or a dynamic one like the project of mine) will protect you against simple CSRF-attacks via e.g. links in forums, which a user has to click to get attacked. As the link will never contain the correct token, your webpage is secure. However, if an attacker manages to load a javascript into the webpage via XSS, you're screwed and no technique in the world will help against it, as the javascript can scan the whole DOM-tree of the page to find an capture any tokens whatsoever.
So, it comes down to this:
use tokens on GET and POST-requests to fight CSRF
secure your page against XSS-injections
I find the OWASP cheat sheets are a good resource for such design decisions:
CSRF Prevention Cheat Sheet
XSS Prevention Cheat Sheet
Your scheme sounds similar to the HTTP digest authentication without establishing any kind of session post authentication. Which is probably an improvement over HTTP Basic. And that is assuming both are over TLS!
I am not sure how feasible your scheme might be or how vulnerable to replay attacks or MITM it might be.
If it is an option you might consider the new <keygen> html5 tag which can help establish a two way TLS session. This would be the most secure option..

Good alternative for user session in high traffic web application?

What would be good/scalable user session alternative in following scenario:
users don't have to have cookies enabled
URL query string restriction of 255 characters is imposed
lot of GET requests (no hidden form fields)
application runs on several servers (web farm)
some users connect over proxy (same IP)
users connect over HTTPS
50 000 concurrent users
If you can guarantee that the client always connects to the same web server, you can use the SSL ID as a simple session tracking mechanism. Some web servers expose this capability and automatically use it for session tracking when cookies aren't supported.
The only solution that will work no matter what is to include a session ID in the URL itself. Adding a parameter to the URL is the simplest way to do this, but the ID can be embedded anywhere in the URL, i.e. as part of the path. You would use this ID to fish information about the user out of a database.
You will run into the usual problems, of course, with ID spoofing and having the session database be a bottleneck.
First, IMHO, there is no good alternative to session. The question is how do you obtain it when cookies are disabled. The answer is using URL parameter. So, you have to append session id to each request (including links and forms). All other requirements are not really relevant. Make your logic stateless, so you do not have scalability problems: all requests should arrive to your logic via load ballancer, so you can add as many servers as you want.
Maybe URL Rewriting or some URI shortening mechanism like http://tinyurl.com or http://goo.gl so you can pass your session details well under 255 chars.
Note: Not recommending to use these services but the mechanism.
First of all, your requirements are very tight.
The only option I see is using an approach like this: http://code.google.com/p/seaside/
In short: your system will generate statless urls like
http://host/app/#123445568978
Then you will go on the db to get the session object.
50000 users doing what? Continuous drag-and-drop with position updates to the server or clicking a text link every 15 minutes? In the last case: move everything onto a single server with a lot of ram.

Securing a REST API

I am in the middle of developing a PHP social media web application which will be supported by various web services each operating a REST API. Web services will probably be implemented in Java with MySQL data layer but the whole point of what I am trying to do is make it really easy to implement modules in different languages/data stores depending on what is approriate.
So for example when the user logs into the application via a login form the PHP code connects to a web service and POSTs the username and password to check if they should be authenticated. I would normally at this point start a session and store it in a session data store.
Another example could be if a user sends a private message to another user. The message would be POSTed to the private messaging web service which would take care of all the storage. Similarly the web service could be contacted to retrieve messages for a user.
Although I understand how to implement the REST web service in Java and make the connection to it in PHP I am totally unsure as to how to secure the data being passed and make sure that it is the users data being returned. If for example I want to get all of user As private messages how does the web service know to return that users. I could pass that users identifier as part of the GET url but then surely any old user could just figure out the GET url and use it to look up other peoples messages. I thought maybe I could pass over the session identifier and IP address which would allow me to check the session data store and make sure it is the correct user?
To secure the data that is important - like the username/password I thought I would just pass it over SSL.
Hope this explains my problem better.
Thanks
Take a look at HTTP Digest authentication. Most clients should support it, and it means the auth details can be passed securely with each request as part of the headers without interfering with the payload of the request itself.
I think requiring OAuth is a good choice. Your end users should appreciate that other websites don't need to ask usernames and passwords to access their data. As far as SSL, it's clearly worth doing if you can. You'll have to see if the performance trade-off is acceptable.
Keep in mind that your api must mimic the HTTP protocol.
Http is stateless, and by adding any Sessions or so, you're trying to fake an "Alwaysconnected" method.
With a LoginForm, it's like I'll have to send two requests for each calls ;)
These are basically 2 questions.
When privacy is a concern I'd go for the safest option: Serve data over SSL (via HTTPS).
As far as authentication is concerned, there are several possibilities. Basic over SSL is one of them, but a simple login form with a cookie can be another one. (ASP.Net Forms Authentication for example.) This all depends on how you want to implement your authentication mechanism.

Categories