Lesson 6 of 11
Broken Authentication & Session Management
Authentication failures - weak passwords, missing MFA, insecure session handling - allow attackers to compromise accounts without exploiting any technical vulnerability. This is OWASP A07 and responsible for a massive proportion of real-world breaches.
Authentication Attack Vectors
- Brute force: Systematically trying all password combinations - targeted when no rate limiting exists. Online attack assumes ~1 req/sec; with no lockout, automated tools try thousands per second
- Credential stuffing: Using username/password pairs from previous breaches (billions available on dark web). Works because ~65% of users reuse passwords across sites. HaveIBeenPwned API detects known-compromised passwords
- Password spraying: Try a few common passwords (Password1!, Summer2024!) across many accounts - avoids lockout, effective against Microsoft 365 and corporate accounts
- Session hijacking: Steal session token via XSS, network sniffing (HTTP), or physical access - then impersonate user without knowing their password
- Session fixation: Attacker sets a known session ID before login - if server doesn't regenerate session ID on authentication, attacker's known ID becomes the authenticated session
Secure Authentication Implementation
# Secure authentication system - Python example
import secrets
import time
from datetime import datetime, timedelta
import bcrypt
# In-memory rate limiter (use Redis in production)
failed_attempts = {}
def check_rate_limit(ip_address: str) -> bool:
"""Return True if request should be blocked."""
now = time.time()
attempts = failed_attempts.get(ip_address, [])
# Clean up attempts older than 15 minutes
attempts = [t for t in attempts if now - t < 900]
failed_attempts[ip_address] = attempts
return len(attempts) >= 5 # Block after 5 failures in 15 minutes
def secure_login(username: str, password: str, ip: str) -> dict:
if check_rate_limit(ip):
return {"error": "Too many attempts. Try again later."}
# Constant-time user lookup (prevent username enumeration via timing)
user = db.get_user(username)
if user is None:
# Hash a dummy value - same time as real hash check
bcrypt.checkpw(password.encode(), b"$2b$12$" + b"x" * 53)
failed_attempts.setdefault(ip, []).append(time.time())
return {"error": "Invalid credentials"} # Generic message!
if not bcrypt.checkpw(password.encode(), user['password_hash']):
failed_attempts.setdefault(ip, []).append(time.time())
return {"error": "Invalid credentials"} # Same message as above!
# Successful login - generate secure session
session_token = secrets.token_urlsafe(32)
# Store session with expiry
session = {
'token': session_token,
'user_id': user['id'],
'created_at': datetime.utcnow(),
'expires_at': datetime.utcnow() + timedelta(hours=24),
'ip': ip
}
db.store_session(session)
return {"session_token": session_token}Secure Session Management
- Session token generation: Use cryptographically secure random generator - Python: secrets.token_urlsafe(32), Node.js: crypto.randomBytes(32).toString('hex')
- Session token storage: Never store meaningful data in the token itself - store a random ID that maps to session data in the server-side database/Redis
- Session expiry: Implement both absolute timeout (24h) and idle timeout (30 min inactivity). Invalidate server-side - not just clear the cookie
- Session regeneration: Generate a new session token on privilege change (login, MFA completion, role change) - prevents session fixation
- Logout: Invalidate session server-side, not just delete the cookie - an attacker who captured the token can still use it if only the cookie is cleared
Common Mistakes
- Different error messages for 'user not found' vs 'wrong password' - enables username enumeration; always return identical messages
- Not regenerating session token after login - session fixation attack; generate a new token after successful authentication
- JWT with 'alg: none' vulnerability - JWT libraries that accept 'alg: none' allow attackers to forge tokens without a signature; always enforce expected algorithm server-side
Tip
Tip
Practice Broken Authentication Session Management in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Broken Authentication Session Management from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Broken Authentication Session Management is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- Authentication failures - weak passwords, missing MFA, insecure session handling - allow attackers to compromise accounts without exploiting any technical vulnerability.
- Brute force: Systematically trying all password combinations - targeted when no rate limiting exists. Online attack assumes ~1 req/sec; with no lockout, automated tools try thousands per second
- Credential stuffing: Using username/password pairs from previous breaches (billions available on dark web). Works because ~65% of users reuse passwords across sites. HaveIBeenPwned API detects known-compromised passwords
- Password spraying: Try a few common passwords (Password1!, Summer2024!) across many accounts - avoids lockout, effective against Microsoft 365 and corporate accounts
Finished this lesson?