| Tiago Coimbra
11. Broken Authentication and Session Management

Broken Authentication and Session Management
Category: #Authentication-and-Session-Attack
Attack: Broken authentication occurs when session management mechanisms (such as session tokens, cookies, and login functions) are improperly implemented, allowing attackers to hijack sessions or bypass authentication mechanisms.
Attack Example (Session Hijacking):
An attacker steals a valid session ID from a victim’s session and uses it to gain unauthorized access to their account.
Vulnerable Code (Session without Secure Flags):
@app.route('/login', methods=['POST'])
def login():
session['user'] = request.form['username'] # Session cookie is not secure
return "Login successful"
In this example, the session cookie is vulnerable because it is not marked as secure and can be stolen over unencrypted connections.
Remediation Steps:
- Use Secure Cookies: Ensure cookies are flagged as
HttpOnly
,Secure
, andSameSite
. - Regenerate Session IDs: After a successful login, regenerate session tokens to prevent session fixation attacks.
- Session Timeout: Implement session expiration after a period of inactivity or maximum session lifetime.
- Use Strong Session Management Libraries: Use well-established authentication and session management libraries (e.g., OAuth2) to avoid custom insecure implementations.
Safe Code (Using secure session cookies in Python Flask):
app.config['SESSION_COOKIE_HTTPONLY'] = True # Prevent access from JavaScript
app.config['SESSION_COOKIE_SECURE'] = True # Send cookies only over HTTPS
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # Prevent cross-site request sharing
@app.route('/login', methods=['POST'])
def login():
session['user'] = request.form['username']
return "Login successful"
Reference: OWASP Session Management Cheat Sheet