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.
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();
...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' pentesting team, fill out this contact form.