Data AccessCore JavaApp FrameworksViewTestingBuildingDeploymentDev ToolsSecurityOpinions

Monday, December 5, 2011

Changing the Session Identifier (JSESSIONID) on Authentication. Protecting against Session Fixation attacks in Java Web Environments

It is a standard security practice to change the session identifier (JSESSIONID) after a successful login or authentication.

The attack scenario with this vulnerability is that a user can open a browser on a shared terminal and record the session identifier set by the application. Later when any other user of the system logs into the application without closing instances of that browser the same cookie will be used to track the victim's session.

Alternatively, if the application is susceptible to cross-site scripting on a publicly accessible page (most damagingly the home page), an attacker can use this vulnerability to learn the value of the session identifier, because the cookie does not change since it was first set. The attacker now knows the value of the session token can hijack the victim's session. This is a limited session fixation attack where the attacker does not have control over the value of the session identifier, but is able to know its value through various means before and after a user authenticates.

Most times, invalidating the session and creating a new one may suffice. However, if you are storing variables or objects, you may need to carry these variables or objects from the old session into the new session.

Below is a javax.servlet.Filter. This filter protects against the Session Fixation attacks described above. The filter looks for a specific session attribute, the (NEW_SESSION_INDICATOR) attribute. If one is found, the filter copies out relevant session data to a map, invalidates the session, creates a new session and loads the new session with the old session data.

The filter is simply mapped in your web.xml. Any place you successfully authenticate, an attribute is added to the session (NEW_SESSION_INDICATOR).

The code below follows:

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class NewSessionFilter implements Filter {
  
  private static Logger logger = Logger.getLogger(NewSessionFilter.class.getName());
 
  public static final String NEW_SESSION_INDICATOR = "filter.NewSessionFilter";
  
  public void destroy() {}
  
  @SuppressWarnings("unchecked")
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest){
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      if (httpRequest.getSession(false) != null && 
          httpRequest.getSession(false).getAttribute(NEW_SESSION_INDICATOR) != null
      ){
        //copy session attributes from new session to a map. 
        HttpSession session = httpRequest.getSession();
        HashMap old = new HashMap();
        Enumeration keys = (Enumeration) session.getAttributeNames();
        while (keys.hasMoreElements()) {
          String key = keys.nextElement();
          if (!NEW_SESSION_INDICATOR.equals(key)) {
            old.put(key, session.getAttribute(key));
            session.removeAttribute(key);
          }
        }
        logger.info("session invalidated on " + httpRequest.getRequestURI());
  
        //invalidation session and create new session.
        session.invalidate();
        session = httpRequest.getSession(true);
 
        //copy key value pairs from map to new session.
        for (Map.Entry entry : old.entrySet()) {
          session.setAttribute(entry.getKey(), entry.getValue());
        }
 
        logger.info((new StringBuffer()).append("new Session for URI '")
             .append(httpRequest.getRequestURI()).append("':")
             .append( session.getId()).toString());
      }
    }
    chain.doFilter(request, response);
  }
  
  public void init(FilterConfig filterconfig) {}
}

Any questions about this posting or filter, comment below and I'll be sure to answer.

28 comments:

  1. Hi,

    Where do we place this class file & what entry do we do in web.xml?

    ReplyDelete
  2. pls add NEW_SESSION_INDICATOR configuration details as well.

    ReplyDelete
  3. Where do we place this class file & what entry do we do in web.xml? please let me know its urget

    ReplyDelete
  4. This is great do you have a catologue if so I would love one to share with friends and family.
    T20 cricket world cup 2016 Groups List
    ICC World Cup 2016 WC Live

    ReplyDelete
  5. Indian Premiere League (IPL)Starting from April 9 to 29 May 2016.Check out latest IPL 2016 Schedule
    IPL 2016
    IPL LIVE STREAM
    IPL Points Table
    IPL Live
    IPL Live Score Board

    ReplyDelete
  6. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai

    Online Java Training Java Online Training | Java J2EE Online Training | JavaEE Training Institute in Chennai

    ReplyDelete
  7. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me.I actually appreciate your own position and I will be sure to come back here.
    temple run 2 l download temple run 2 l temple run 2 game l temple run 2 download l temple run 2 app

    ReplyDelete
  8. Wazifa Husband Love Istikhara Online
    Wazifa Husband Love Istikhara Online , ” English:- Sometimes we have been noticed In some familiest husband and wife often quarrel on a small matter with each other.
    Man Pasand Shadi ka Wazifa
    Man Pasand Shadi ka Wazifa , ” Man Pasand Shadi Love Marriage Aaj key es nafsa nafsi k daor main jis taraf dekhen har shukhs musibatun aur Muskhkalun main ghira howa hai muskhilen aur azmaishen kabhi tou batoor imtihan hoti hai aur kabhi batoor-e-saza e amaal.
    Wazifa For Job Interview
    Wazifa For Job Interview , ” It is the very tough time for the person who is going for job interview when he or she goes for job interview different paranoid comes to mind that i will qualify or not what will be the interviewer
    Wazifa For husband and wife love
    Wazifa For husband and wife love , ” The relation of Husband and wife want extra care because it is very strong and also sensitive relation.Keep in mind that give most respect to each other don’t quarrel with each other if husband or wife don’t give attention,time then take extra
    Wazifa to Stop Job Transfer
    Wazifa to Stop Job Transfer , ” You will know better if you are doing job with multinational or governament organization that sometimes your transfer are make when you are unwilling by that transfer which are done by company for their benefit or sometime to punish you however the issue

    ReplyDelete
  9. Thanks for sharing this quality information with us. I really enjoyed reading.

    http://word-cookies-answers.com

    ReplyDelete