I have a small spring MVC-app with session, with also some small amount of REST methods.
If I copy the JSESSIONID and use it with a 'curl'-command I'm able to access the rest methods from a different computer with a different IP, and thus 'faking' a session.
Is there a way to "bind" a session to one IP-address?
You can bind a session to IP address using a custom filter:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
boolean chainCompleted = implementEnforcement(request, response);
if (!chainCompleted) {
filterChain.doFilter(request, response);
}
}
private boolean implementEnforcement(HttpServletRequest request, HttpServletResponse response) throws IOException {
final String key = "enforcement.ip";
HttpSession session = request.getSession(false);
if (session != null) {
// we have a session
String ip = request.getRemoteAddr();
String ipInSession = session.getAttribute(key);
if (ipInSession == null) {
session.setAttribute(key, ip);
} else {
if (!ipInSession.equals(ip)) {
// JSESSIONID is the same, but IP has changed
// invalidate the session because there is a probability that it is
// a session hijack
session.invalidate();
return true;
}
}
}
return false;
}
It remembers user's IP address and then compares current IP with the remembered one: if it differs, the session is destroyed.
you can use Spring security hasIpAddress() check spring security refrence
You should read through Session Fixation Attack Protection in the Spring documentation, where it is written, that you can configure that inside the session-management tag
<session-mangagement session-fixation-protection="migrateSession|none|newSession">
migrateSession - creates a new session and copies the existing session attributes to the new session. This is the default.
none - Don't do anything. The original session will be retained.
newSession - Create a new "clean" session, without copying the existing session data.
a session will be fixed to a set of variables like browser agent, IP. So in your case the browser agent of curl will not match and the provided sessionid will be of no use
Related
Recently I started using Spark Java Framework (2.7.2) to create a lightweight web application. One of its requirements is that the application must be deployed to an Apache Tomcat Server 8.5.
I've managed to set things going, but I have not been able to set any custom cookie.
I have used the following method but none worked.
response.cookie("my_cookie", "value");
response.cookie("/path", "my_cookie", "value", -1, false, true);
It seems like tomcat is setting correctly the JSESSIONID cookie but I have no control over this cookie generation and I would like to generate a random and unique cookie, in order to be used for user authorization.
EDIT:
The control flow for setting the cookie is this
// In the main application
before("/*", AccessController.setSession);
// Method for setting an existing session
public static Filter setSession = (Request request, Response response) -> {
// If the user is not set in the session
if (!SessionUtil.hasSession(request)) {
// Obtain the cookie session ID
String sessionId = SessionUtil.getCookie(request);
System.out.println(sessionId);
// Obtain the user according to the session ID
User user = app.getUserFromSession(sessionId);
System.out.println(user != null);
// if does exists we set the session
if (user != null)
SessionUtil.setSession(request, user);
}
};
// Methods for the session
public static boolean hasSession(Request request) {
if (request.session().attribute("user") == null)
return false;
return true;
}
public static String getCookie(Request request) {
return request.cookie(COOKIE_NAME);
}
public static void setSession(Request request, User user) {
request.session().attribute("user", user);
}
This is called when a login is succesfull. Cookie is stored in the user database persisting sessions
public static void setSession(Response response, String cookie) {
response.cookie(COOKIE_NAME, cookie);
}
We have the following:
Java 8 web app developed with Spring Boot and embedded Jetty.
The UI for the app is built using react.
The backend exposes multiple REST APIs via Jersey.
The authentication is done using SAML with Okta as the IDP. We use spring-security-saml-core for SAML authentication.
The Java app is fronted by Nginx for SSL termination but this issue is reproducible without Nginx too.
The issue we have been noticing is that the user session times-out after the session timeout time despite user activity. Following is an excerpt of the application.properties related to session and JSESSIONID cookie:
# Session #
server.session.cookie.domain=domain.example.com
server.session.cookie.http-only=true
server.session.cookie.max-age=-1
server.session.cookie.name=JSESSIONID
server.session.cookie.path=/
server.session.cookie.secure=true
server.session.persistent=false
server.session.timeout=900
server.session.tracking-modes=cookie
# Custom #
auth.cookie-max-age=900
The cookie-mag-age above dictates the lifespan of other cookies we create to store other user details, e.g user id. Following code gets called when Okta sends back the assertion on valid auth. This is a custom class extended from SavedRequestAwareAuthenticationSuccessHandler
#Override
public void onAuthenticationSuccess(
final HttpServletRequest request,
final HttpServletResponse response,
final Authentication authentication)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
Object credentials = authentication.getCredentials();
if (credentials instanceof SAMLCredential) {
SAMLCredential samlCredential = (SAMLCredential) credentials;
NameID nameId = samlCredential.getNameID();
if (nameId != null) {
String nameIdValue = nameId.getValue();
UserDetail userDetail = userManager.getUserByName(nameIdValue, false);
if(userDetail != null) {
session.setAttribute(Constants.SESSION_USERID_FIELD, userDetail.getId());
String token = csrfTokenManager.getTokenFromSession(request);
if(token == null) {
token = csrfTokenManager.generateAndSaveToken(request, response);
response.addHeader(CsrfTokenManager.TOKEN_HEADER_NAME, token);
}
Cookie idCookie = AuthUtil.createCookie(
Constants.SESSION_USERID_FIELD,
userDetail.getId(),
appConfig.getCookieMaxAge(), true);
response.addCookie(idCookie);
}
}
}
getRedirectStrategy().sendRedirect(request, response,
appConfig.getAuthSuccessRedirectUrl());
}
We call the REST APIs from Javascript using isomorphic fetch as follows:
export const fetchAllProjects = () => {
return dispatch => {
dispatch(requestAllProjects())
return fetch(`/rest/private/v1/projects`, {
credentials: 'same-origin'
})
.then(errorMessageUtil.handleErrors)
.then(response => response.json())
.then(json => dispatch(receiveAllProjects(json)))
.catch(error => errorMessageUtil.dispatchError(error, dispatch, appActions.displayBadRequestMessage))
}
}
The credentials: 'same-origin', sends all the cookies to the backend including the JESESSIONID and the other cookies set above. We have an authentication filter that checks for valid session and not sends 401
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession(false);
if(session == null) {
this.sendUnauthorizedResponse(httpServletResponse);
} else {
String userIdFromCookie = null;
Cookie[] cookies = httpServletRequest.getCookies();
for(Cookie cookie : cookies) {
if(Constants.SESSION_USERID_FIELD.equals(cookie.getName())) {
userIdFromCookie = cookie.getValue();
break;
}
}
String userId = (String)session.getAttribute(Constants.SESSION_USERID_FIELD);
if(userIdFromCookie != null && userId != null
&& userId.equals(userIdFromCookie)) {
HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(httpServletRequest);
requestWrapper.addHeader(Constants.USERID_HEADER_NAME, userId);
chain.doFilter(requestWrapper, httpServletResponse);
} else {
this.sendUnauthorizedResponse(httpServletResponse);
}
}
}
I am sure, we are not doing something right because the timeout time for the session is for the inactivity.
One other question is, do calls to the REST APIs qualify as valid activity for session time-out to extend?
Found the problem with my logic. The code above tries to get the userId from the cookie and the userId from the session and then compare and if not matched, redirect the user to login.
The issue was the timeout time for the session and the cookie expiry time, auth.cookie-max-age=900, were same so even though the session was active because of activity, the cookie was getting expired and userId values didn't match.
My approach is to increase the max age of the cookie to a bigger value, so UI can keep sending the cookies with valid values and if the session really expires due to inactivity, its the userId value from the session that will be null and the user will need to re-login.
I have been trying to find the reason as to why my session would be lost when I do a POST.
I am checking my session all throughout my app but the session will drop when I call a particular servlet and it only drops on this particular one. The issue is intermittent so it is very frustrating. I'm not sure what is needed so I'll put as much info as I can up.
The page is accessed through a servlet. I can verify that the session is still the same.
As the user is routing through the app, I can see that the session is still the same.
Checking Session:HTTP Session CEHKIIMEKHMH
Calling Get Details
Checking Session:HTTP Session CEHKIIMEKHMH
Calling Project Details
Checking Session:HTTP Session CEHKIIMEKHMH
Calling Attachment Controller
Checking Session:HTTP Session CEHKIIMEKHMH
public class Attachments extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Calling Attachment Controller");
HttpSession session = request.getSession(false);
System.out.println("Checking Session:"+session);
if(session != null){
Object projectId = session.getAttribute("projectId");
request.getRequestDispatcher(response.encodeURL("views/attachments.jsp")).forward(request, response);
}else{
System.err.println("Invalid session");
response.sendRedirect("/");
}
}
}
Here is my form posting. The form is actually submitted via javascript after I perform validation, I just merely call $('#files).submit(); not sure if that really matters or not.
<form id="files" name="files" method="POST" action="FileUpload" enctype="multipart/form-data">
The moment they post, the session is lost
Calling File Upload
Checking Session:null
null
Here is the start of the servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Calling File Upload");
HttpSession session = request.getSession(false);
System.out.println("Checking Session:"+session);
if(session != null){
Object projectId = session.getAttribute("projectId");
System.out.println("Accessing File Upload: Session is valid");
It's the same method all across the board. I have no idea what the problem is.
I've narrowed down the issue but I still have not resolved it yet. It happens during my redirect. I also was not encoding the URL correctly. I have modified all my redirects to have the folowing:
request.getRequestDispatcher(response.encodeRedirectURL("views/attachments.jsp")).forward(request, response);
This only resolves it on the server side though and does not provide a solution when I am handling redirects from the client.
I am very new to java servlet programming. I have been writing a simple program for practicing java session. There are two .jsp file. first one called index.jsp, and another one is selection.jsp. And there is a servlet called controller. At first the index.jsp will be called, and user will be submit a input. That will be redirect in servlet controller. In that servlet will check whether it is new request or not. If new then it redirect to other page, else will do some other work.
I am checking whether it is new request or not by session.isNew() method. But it always says it is not new session. But, if I disable the browser cookies option then it is working fine. Now what is my observation is that when in the first I request the index.jsp to the container it assign a session along with that request. So when it comes to servlet it treat as a old session. I got this idea from Head first book Servlet and JSP.
Here is my servlet code -
public class Controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user;
HttpSession session = request.getSession(false);
if (session == null) {
user = request.getParameter("user");
if (user == null) {
response.sendRedirect("index.jsp");
}
session.setAttribute("username", user);
SelectItem selectItem = new SelectItem();
selectItem.setUser(user);
response.sendRedirect("selection.jsp");
session.setAttribute("selectItem", selectItem);
} else {
String selectionItem = request.getParameter("selection");
SelectItem selectItem = (SelectItem) session.getAttribute("selectItem");
if (selectItem != null) {
selectItem.add(selectionItem);
session.setAttribute("selectItem", selectItem);
}
response.sendRedirect("selection.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
So, how to determine whether it is a new session or old one? Thank you.
HttpSession.isNew API:
Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.
So, you're getting true because the client has cookies disabled. The "new session" check in done in the else block of this check:
HttpSession session = request.getSession(false);
if (session == null) {
// create new session
session = request.getSession();
} else {
// existing session so don't create
}
In your code, you don't appear to be creating a new session when a new session is detected. Perhaps that's where you're stumbling.
Note: learning the basic Servlet API is a good thing. However, for my professional work I use frameworks which simplify my programming, like Spring Boot and Spring Security.
Suppose a person is logged in with user id and password in an app. Now with same user id and password he is trying to log without logging out from first session. I want to make it that it willlog out from and first session and continue with new one automatically.
Struts2, JSP , Java are technologies , i m using for my apps.
Problems facing
IE 8 giving same session id in same machine if we open in new tab or window. Not able to differentiate between different login from same machine.
How to set own session id?
Banking application like SBI sites and all works like that only , how does it work real time?
I want to replicate same thing like SBI bank sites work on online transaction. Send message session out in first window if you open again in new window
Please let me know how does this logging part in details.
Thanks.
This is my filter
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("FirstFilter : In filter doFilter before doFilter...");
HttpServletRequest req = (HttpServletRequest) request ;
HttpServletResponse res = (HttpServletResponse) response ;
HttpSession session = req.getSession(false);
String userId=req.getParameter("username");
String password=req.getParameter("password");
System.out.println(" : : " + req.getParameter("username")) ;
System.out.println(" : " + req.getServletPath());
LoggedInUserVO userProfVOSession = null ;
if(session != null) {
String sessionId=session.getId();
userProfVOSession = (LoggedInUserVO)session.getAttribute("LoggedInUser") ;
//check for login id password and session for single user sign in
if(null!=userProfVOSession){
if(userProfVOSession.getUserName().equalsIgnoreCase(userId) && userProfVOSession.getUserPassword().equals(password) && userProfVOSession.getSessionId().equals(sessionId)){
//do nothing
}
else{
System.out.println("in duplicate");
}
}
}
if(userProfVOSession == null) {
if("/populatelogin.action".equals(req.getServletPath()) || "/login.action".equals(req.getServletPath())||"/images/Twalk-Logo-4-green.png".equals (req.getServletPath())||"css/twalk.css".equals( req.getServletPath() )) {
chain.doFilter(req, res) ;
} else {
req.getRequestDispatcher("Entryindex.jsp").forward(req, res) ;
}
} else {
chain.doFilter(req, res) ;
}
Basically your requirement leads to web security vulnerability.If a person is already logged in, then his session must be active.Now the scenario is like this:
If you tries to login again with the same credentials, he wll be automatically logged in.
If you want to kill the old session for every login, then what you need to do is , you need to get a new session every time when you login, so your old session will be expired.You can achieve this by just writing a filter.In this filter check whether the user is already associated with a session or not, if yes, then invalidate his current session and start new one.This will solve the issue of multiple login attempts.
Remember that when a session is initiated, then the server is sending a cookie back to the user.Henceforth for every subsequent request made, this cookie will be transmitted to the server. Even if that if you open multiple tabs in browsers, this same cookie only is sent back to the server.
Hope I understood this.