How does Spring Security sessions work? - spring

How do Spring sessions work when you login to a form on Spring security as described in this tutorial? http://static.springsource.org/spring-security/site/tutorial.html
Is it cookie based? Im not sure what exactly is going on that allows the user to log in and have it remember and keep you logged in for the remainder of the browsing session.

It is cookie based similar to how the servlet maintains sessions . If cookies are disabled, you would have to resort to URL rewriting .According to the FAQ here.
"All it sees are HTTP requests and it ties those to a particular session according to the value of the the JSESSIONID cookie that they contain. When a user authenticates during a session, Spring Security's concurrent session control checks the number of other authenticated sessions that they have. If they are already authenticated with the same session, then re-authenticating will have no effect. "
also
"If clients have cookies disabled, and you are not rewriting URLs to include the jsessionid, then the session will be lost. Note that the use of cookies is preferred for security reasons, as it does not expose the session information in the URL. "
See here for the Single sign on feature

Related

Tomcat disable session not working

I have several apps deployed in Tomcat 7, and use Keycloak to manage user login and logout of these apps. Logout does not work i.e., does not log the user out and redirect to Keycloak's login page. Then I found the JSESSIONID cookie is still present, once I deleted the JSESSIONID cookie, the logout link works as expected. So I tried to disable Tomcat's session by putting
<%# page session="false" %>
in the header of my apps' JSP pages. Unfortunately, this still does not seem to disable Tomcat's session, I still see JSESSIONID cookie present. I am wondering if anyone has a solution to this problem? I believe the presence of the Tomcat session interferes with the Keycloak's SSO session, and causes Keycloak logout to not work. This has to be a common problem Keycloak users encounter, Tomcat is so widely used for web apps.
Would appreciate any tips on how we should handle this!
I don't have specific experience with Keycloak, however, there's a principle that applies to most if not all Single-Sign-On (or external authentication) solutions:
SSO identifies a user and removes the burden of knowing passwords from typical applications. When a user signs in, an application server is often detached from the actual SSO system, thus it will need to cache the user once they're identified, just as if the user identified itself with a classic login.
On the logout side, you can either log out of the application itself (tomcat in this case) or you can log out of the SSO system (which seems to be what you're doing here). With the later approach, you're running into the problem of "Single Sign Out": Logging out of the SSO system should invalidate all sessions that once were initiated with the associated login. As I know it, the SSO system needs to keep track of all of the systems that have signed on through it and trigger an explicit logout there.
I can't tell you how to implement this in Keycloak, but hope that the general principle helps guiding you towards the solution:
The use or non-use of a session on Tomcat's side has nothing to do with the problem: You might have applications that legitimately store information in a session in addition to the signed in user - those applications should continue to work even if you're not comparing passwords in tomcat itself.
Edit, after your comment:
If this one page doesn't trigger the use of a session, any other code (e.g. the code that processes your login) still might trigger a session and then later delegate to the page that doesn't want to use a session.
I'd expect that you'll have to disable sessions in Tomcat's configuration e.g. through providing a custom "Manager" implementation. It looks like the default ones do not expect you to completely ignore sessions. As I've outlined above, I'd also expect sessions to be required even if you're not logging in through Tomcat itself.
Another way to avoid sessions (this is the indicator why I don't expect "no session" config to work) is to avoid calling any method on request/response that would trigger the automatic creation of a session. And it seems that you have such a method somewhere in your app.
(someone correct me if I'm wrong. This is mostly my educated expectation as I've never looked at this requirement)

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

Spring Security : restrict other web application access

I am running spring web application in broswer. I logged in to my account and update some value using a url say localhost:80/update/name. On the controller side I check principal==null if not redirect to login page.
Now while login to this application. I open other web application page in the same browser and execute the same update url localhost:80/update/name through ajax call and it is updating the value. How can i avoid this security threat.
How can i make sure that Application1 update url will be executed by application1 request only? Application2 should not be allowed to execute app1's update request no matter whether it is in same browser ?
Why are you surprised ? You are logged, thus the browser has a valid session cookie. You ask the browser to send a request to the host (be it in first window or any other window, it is the same) : it sends the request with all relevant cookies, including session cookie and if appropriate any other security cookie. The server receives a request containing a valid session cookie for a valid logged user and even if it controls IP addressed coming from same address : all is valid and it proceeds with the request.
If you have a different browser on your client machine and if you open the connection from this unrelated browser, the server should reject your request, because the browser would not present a valid cookie.
You are describing a variant of cross-site request forgery, you should enable Spring Security CSRF protection. You can read about it in the reference manual.
Even if the two applications are on the same server, they will get different CSRF tokens, which will protect your case.
You described Cross-Site request forgery attack. Typically when POST method is used hidden token is added to prevent it. I assume You are using GET method - It is good practice to not change any state using GET method.

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.

Grails: CookieTheftException with anonymous access

I have a grails server and an iOS client that communicate over HTTPS via POST messages. I'm using PersistentTokenBasedRememberMeServices to ensure that the user doesn't have to enter his password all the time. This doesn't seem to work as the session is lost continuously and the user has to login again. The server logs show that a CookieTheftException has occurred with message "Invalid remember-me token (Series/token) mismatch".
Not all server actions require a logged in user. Some can be accessed anonymously and this may be the root of the problem. When the user accesses restricted server actions, the session is maintained, but not when accessing unrestricted actions.
Here's my config in Config.groovy:
grails.plugins.springsecurity.rememberMe.cookieName = 'SomeRememberMeName'
grails.plugins.springsecurity.rememberMe.persistent = true
grails.plugins.springsecurity.rememberMe.alwaysRemember = true
grails.plugins.springsecurity.rememberMe.persistentToken.domainClassName = 'com.myapp.PersistentLogin'
grails.plugins.springsecurity.rememberMe.tokenValiditySeconds=31*24*60*60
I added some traces in the iOS client and noticed a couple of things. First of all the JSESSIONID cookie doesn't have an expiration time, which means it isn't saved in the client like the rememberMe cookie. Can I force it to have an expiration time or is that even a good idea? Secondly I noticed that sometimes the rememberMe cookie that I receive from the server is empty. That may be just because a CookieTheftException was thrown.
Since all of the post message bodies are encrypted with 256-bit AES, I'm not really worried about cookie theft at this time. I just need to get this to work.
I tried adding the following to my config to ensure that the session would be always updated even when accessing unrestricted actions:
grails.plugins.springsecurity.useSessionFixationPrevention = true
grails.plugins.springsecurity.SessionFixationPrevention.migrate = true
grails.plugins.springsecurity.SessionFixationPrevention.alwaysCreateSession = true
I don't even know what these all mean. I just liked the "alwaysCreateSession" part and figured that I need to enable session fixation prevention in order for that setting to have any effect. Will it still always create a session if I set useSessionFixationPrevention to false?
Any help is appreciated.
If you are using PersistentTokenBasedRememberMeServices, your "remember me" token will change after every HTTP request.
Unfortunately that means that requests will only authenticate if your browser makes exactly one request at a time, and browsers often don't do that. If there are 4 few images on a page, the browser will send out 4 simultaneous requests, each with the same "remember me" token. Only the first request will authenticate, because after Spring Security processes the first request, it changes the token. When Spring Security tries to process the next request, it throws a CookieTheftException.
That's the typical scenerio for the CookieTheftException when using PersistentTokenBasedRememberMeServices.
Here's a link that explains some things you can do about it: Grails Cookie Theft Exceptions
There's also an open issue with the Grails Spring Security Core plugin that discusses this problem: Remember me functionality fails intermittently with CookieTheftException: Invalid remember-me token
The JSESSIONID stuff is probably a red herring. If you're using PersistentTokenBasedRememberMeServices, your authentication won't need a session.

Resources