Quantcast
Viewing latest article 3
Browse Latest Browse All 15

Answer by Jzf for What is the best way to prevent session hijacking?

AFAIK the session object is not accessible at the client, as it is stored at the web server. However, the session id is stored as a Cookie and it lets the web server track the user's session.

To prevent session hijacking using the session id, you can store a hashed string inside the session object, made using a combination of two attributes, remote addr and remote port, that can be accessed at the web server inside the request object. These attributes tie the user session to the browser where the user logged in.

If the user logs in from another browser or an incognito mode on the same system, the IP addr would remain the same, but the port will be different. Therefore, when the application is accessed, the user would be assigned a different session id by the web server.

Below is the code I have implemented and tested by copying the session id from one session into another. It works quite well. If there is a loophole, let me know how you simulated it.

@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    HttpSession session = request.getSession();    String sessionKey = (String) session.getAttribute("sessionkey");    String remoteAddr = request.getRemoteAddr();    int remotePort = request.getRemotePort();    String sha256Hex = DigestUtils.sha256Hex(remoteAddr + remotePort);    if (sessionKey == null || sessionKey.isEmpty()) {        session.setAttribute("sessionkey", sha256Hex);        // save mapping to memory to track which user attempted        Application.userSessionMap.put(sha256Hex, remoteAddr + remotePort);    } else if (!sha256Hex.equals(sessionKey)) {        session.invalidate();        response.getWriter().append(Application.userSessionMap.get(sessionKey));        response.getWriter().append(" attempted to hijack session id ").append(request.getRequestedSessionId());         response.getWriter().append("of user ").append(Application.userSessionMap.get(sha256Hex));        return;    }    response.getWriter().append("Valid Session\n");}

I used the SHA-2 algorithm to hash the value using the example given at SHA-256 Hashing at baeldung

Looking forward to your comments.


Viewing latest article 3
Browse Latest Browse All 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>