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.

53 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
  10. the best services about www.unitedcheckcashing.com within a short period. In USA you may find us everywhere, every city and 24/7. We actually love to oblige you the best things with 100% agreements and faster ever.
    check cashing

    ReplyDelete
  11. OPSC has announced a government job recruitment for 2173 posts. opsc 2173 medical officer posts job,

    ReplyDelete
  12. d 2018 recruitment

    Wow!! this is a very helpful article.
    Thank you for sharing this.

    ReplyDelete
  13. We have devised solutions for MS Paint related errors and bugs. If you are not able to fix these problems, do not worry we are here to make things easier and smoother for you. MS Paint Customer Service

    ReplyDelete
  14. Nice post. Thank u so much for sharing with us.
    Kerala HSE +2 Date Sheet 2018 PDF Download

    ReplyDelete
  15. Bring in a present service bill to demonstrate your habitation. In many cases a permit won't have the most current address. Since service bills are paid every month, you should give the latest one.
    Check Cashing
    Cash Advance Chicago
    Auto Title Loans Chicago

    ReplyDelete
  16. CIITN is the Best Php training institute in Noida and delhi Ncr. You will get Live Project Training on PHP by our PHP expert who have 5+ year industrial experience.Focus on practical and live project training. In our PHP training, we you will learn core PHP, advance PHP, HTML, CSS, JavaScript, jQuery, Bootstrap, Cake PHP and Wordpress.CIITN provides 100% job assistance in PHP training. CIITN is well known PHP coaching center because our 100% PHP students are placed now.


    Ciitnoida provides Core and java training institute in noida. We have a team of experienced Java professionals who help our students learn Java with the help of Live Base Projects. The object-oriented, class-based build of Java has made it one of most popular programming languages and the demand of professionals with certification in Advance Java training is at an all-time high not just in India but foreign countries too.

    By helping our students understand the fundamentals and Advance concepts of Java, we prepare them for a successful programming career. With over 13 years of sound experience, we have successfully trained hundreds of students in Noida and have been able to turn ourselves into an institute for best Java training in Noida.


    php training in noida
    java training institute in noida
    javascript training in noida
    linux training in noida
    linux institute in noida
    red hat linux training in noida

    ReplyDelete
  17. The levels of obligation have been ascending as the measure of cash found in bank accounts has been contracting. Could the ascent in online loan credit applications be an impact of individual funds spiraling descending? personal cash advance san diego

    ReplyDelete
  18. Thanks for such important information.keep up the good work.Ethical Hacking training is based on current industry standards that helps attendees to secure placements in their dream jobs at MNCs. Indian Cyber Army Provides Best Ethical Hacking Training in India.Indian Cyber Army credibility in Ethical hacking training & Cybercrime investigation training is acknowledged across nation as we offer hands on practical knowledge and full assistance with basic as well as advanced level ethical hacking & cybercrime investigation courses

    ReplyDelete
  19. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

    ReplyDelete
  20. All Brokers in any case, endeavor to be the most minimal generally speaking expense of the tickets available. In this way, they consistently look into their opposition and alter appropriately. Boston red sox tickets

    ReplyDelete