Description
If a session keeps its pre-login ID after authentication, someone who already knows that ID may gain access to the signed-in session.
Potential impact
With an ID fixed through a shared browser or a link, another person may be able to read the user’s private data or act with their permissions.
Remediation
- Regenerate the session ID immediately after authentication succeeds. Stop the login flow if regeneration fails. Only on success should you write the user ID, roles, and authentication state to
$_SESSION. - The example’s
session_regenerate_id(true)deletes the old session data. For concurrent requests or unstable connections, plan how to restrict the old ID while clients transition to the new one. - On logout, delete the session data and expire the session cookie.
Examples
These excerpts run after a session has started and user authentication has succeeded. $user represents the authenticated user.
Before
php
<?php
class AuthController {
public function login($user) {
$_SESSION['user_id'] = $user['id'];
}
}
After
php
<?php
class AuthController {
public function login($user) {
if (!session_regenerate_id(true)) {
throw new RuntimeException('Session ID regeneration failed');
}
$_SESSION['user_id'] = $user['id'];
}
}
Explanation:
- Before: Retains the existing ID after authentication, potentially promoting an attacker-fixed ID to the victim’s authenticated session.
- After: Stores the authenticated user ID only after session ID regeneration succeeds.