Predictable session tokens

Predictable session tokens

Description

Generating session or authentication tokens from incrementing values, uniqid, rand or mt_rand may allow attackers to predict them.

Potential impact

This may enable session hijacking, authentication bypass or account impersonation.

Remediation

Generate tokens with random_bytes or the secure randomness provided by PHP session management.

Examples

These excerpts show cookie-value generation for an HTTPS environment. Separately implement server-side storage and verification that bind tokens to authenticated users, as well as expiry and revocation.

Before

php
<?php
$_SESSION['last_session_id']++;
setcookie('session', $_SESSION['last_session_id']);

After

php
<?php
setcookie('session', bin2hex(random_bytes(32)), [
    'httponly' => true,
    'secure' => true,
    'samesite' => 'Lax',
]);

Explanation:

  • Before: Generates a session or authentication token from a predictable value.
  • After: Generates a token with random_bytes. PHP session management with secure randomness is another option.

References