logo

Database

Java Weak Random Cookie

Description

This detector identifies Java web applications that create HTTP cookies using weak or insecure random values as the cookie secret/value. When a `javax.servlet.http.HttpServletResponse` (or equivalent servlet response) calls `addCookie()` with a `Cookie` object whose value is derived from a weak random number generator (e.g., `java.util.Random` instead of `java.security.SecureRandom`), attackers can potentially predict or brute-force the cookie value, leading to session hijacking or authentication bypass.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    • Identify all method calls named `addCookie` in the source code.

    • Verify that the object invoking `addCookie` is a servlet HTTP response object (i.e., an instance of `HttpServletResponse` or a compatible servlet response type).

    • Confirm that exactly one argument is passed to `addCookie`, representing the Cookie being added.

    • Trace the definition of the Cookie argument back to its construction and check whether its value/secret was generated using a weak random source (e.g., `java.util.Random`, `Math.random()`) rather than a cryptographically secure random generator like `java.security.SecureRandom`.

    • Report the `addCookie` call site as vulnerable only when all of the above conditions are satisfied: the caller is a servlet response, and the cookie's value originates from a weak random number generator.

Vulnerable code example

import java.util.Random;
import javax.servlet.http.*;

public class Example extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        long l = new java.util.Random().nextLong();
        Cookie cookie = new Cookie("sessionId", Long.toString(l)); // Weak PRNG: predictable session token
        res.addCookie(cookie);...

✅ Secure code example

import java.security.SecureRandom;
import java.util.Base64;
import javax.servlet.http.*;

public class Example extends HttpServlet {
    // Use SecureRandom once and reuse it (it's thread-safe and expensive to initialize)
    private static final SecureRandom secureRandom = new SecureRandom();
...