Tuesday, November 18, 2014

How to change Session ID after a successful login

In many web application it required to change the sessionid after user is successfully login to the system. In this case, the session ID exists in two different contexts which is vulnerable for attackes. Those contexts are authenticated state and a non-authenticated one. An attacker could start a session, continued through login by a legitimate user, and then re-use the same session to access the user’s account. So using that session id, attacker can obtain the access users' resources as a legitimate user.
In java appplication, JSESSIONID use as the session id. JSESSIONID is a cookie generated by Servlet container like Tomcat or Jetty and used for session management in J2EE web application for http protocol. So below code segment shows how to generate a new session out of old session.
private void regenrateSession(HttpServletRequest request) {
  
  HttpSession oldSession = request.getSession();
  
  Enumeration attrNames = oldSession.getAttributeNames();
  Properties props = new Properties();
  
  while (attrNames != null && attrNames.hasMoreElements()) {
   String key = (String) attrNames.nextElement();
   props.put(key, oldSession.getAttribute(key));
  }
  
  oldSession.invalidate();
  HttpSession newSession = request.getSession(true);
  attrNames = props.keys();
  
  while (attrNames != null && attrNames.hasMoreElements()) {
   String key = (String) attrNames.nextElement();
   newSession.setAttribute(key, props.get(key));
  }
 }


References
http://javarevisited.blogspot.com/2012/08/what-is-jsessionid-in-j2ee-web.html#ixzz3JRxDttxm
http://blog.credera.com/technology-insights/java/broken-authentication-session-management/

No comments:

Post a Comment