Opening Framing: Maintaining State in a Stateless Protocol
HTTP is stateless—each request is independent. Yet applications need to remember who you are. Session management bridges this gap by assigning a unique identifier that links requests to authenticated users.
This creates a valuable target. Whoever possesses the session identifier becomes that user. Session tokens are the keys to the kingdom—steal them, predict them, or forge them, and you gain unauthorized access.
This week covers session management mechanisms, token analysis, session hijacking techniques, and Cross-Site Request Forgery— tricking users into making requests they didn't intend.
Key insight: Authentication happens once; session management happens with every request. Weaknesses multiply.
1) Session Management Fundamentals
How applications track authenticated users:
Session Management Flow:
1. User authenticates
POST /login → credentials valid
2. Server creates session
- Generate unique session ID
- Store session data server-side
- Associate with user identity
3. Server sends session identifier
Set-Cookie: SESSIONID=abc123xyz
4. Browser stores and sends cookie
Cookie: SESSIONID=abc123xyz
5. Server validates session
- Look up session ID
- Retrieve user context
- Process request as that user
6. Session terminates
- User logs out
- Session expires
- Server invalidation
Session Storage Methods:
Server-Side Sessions:
- Session ID in cookie
- Data stored on server
- Most secure approach
- Session ID is only reference
Client-Side Sessions (JWT):
- All data in token
- Signed but readable
- Server doesn't store state
- Can't be invalidated easily
Cookie Attributes:
Set-Cookie: session=abc123;
Secure; ← Only over HTTPS
HttpOnly; ← No JavaScript access
SameSite=Strict; ← CSRF protection
Path=/; ← Cookie scope
Domain=.example.com;
Max-Age=3600; ← Expiration
Missing attributes = vulnerabilities!
Session Token Requirements:
Secure Session IDs must be:
1. Unpredictable
- Cryptographically random
- No patterns
- No sequential values
2. Sufficient length
- Minimum 128 bits of entropy
- Typically 32+ characters
3. Unique
- No collisions
- Not reused
Bad session IDs:
- session=1, session=2 (sequential)
- session=admin (username-based)
- session=1703123456 (timestamp)
- session=abc123 (short, guessable)
Good session IDs:
- session=a7f3b2c9d4e5f6a7b8c9d0e1f2a3b4c5
- 256-bit random hex string
Key insight: Session security depends on token randomness and proper cookie configuration. Weakness in either is exploitable.
2) Session Token Analysis
Analyzing tokens for weaknesses:
Token Analysis Goals:
1. Identify token format
- Hex, Base64, JWT
- Custom encoding
2. Check for patterns
- Sequential values
- Timestamps
- User data embedded
3. Assess randomness
- Statistical analysis
- Prediction attempts
4. Test manipulation
- Decode and modify
- Check signature validation
Burp Sequencer:
# Analyze session token randomness
1. Capture request that returns session token
- Login response with Set-Cookie
- Any response with new token
2. Send to Sequencer
Right-click → Send to Sequencer
3. Configure token location
- Select the session token value
- Define start and end markers
4. Start live capture
- Collects many tokens
- Minimum 100, ideally 1000+
5. Analyze results
- Character-level analysis
- Bit-level analysis
- Overall randomness score
Interpretation:
- Effective entropy > 100 bits = good
- Predictable patterns = vulnerable
- Low entropy = can be brute forced
Manual Token Analysis:
# Collect multiple tokens
Token 1: YWRtaW46MTcwMzEyMzQ1Ng==
Token 2: YWRtaW46MTcwMzEyMzQ1Nw==
Token 3: YWRtaW46MTcwMzEyMzQ1OA==
# Decode (Base64)
admin:1703123456
admin:1703123457
admin:1703123458
# Pattern identified: username:timestamp
# Completely predictable!
# Analysis steps:
1. Is it encoded? Try Base64, URL decode, hex
2. Are there patterns? Compare multiple tokens
3. Is user data embedded? Look for username, email
4. Is there a timestamp? Look for epoch times
5. Is there a signature? JWT has three parts
JWT Token Analysis:
# JWT structure
header.payload.signature
# Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4ifQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
# Decode header:
{"alg":"HS256","typ":"JWT"}
# Decode payload:
{"user":"admin","role":"admin"}
# Signature (verify integrity)
# JWT vulnerabilities to test:
1. Algorithm confusion (alg:none)
2. Weak secret (brute force)
3. Key confusion (RS256 → HS256)
4. Missing signature validation
5. Sensitive data in payload
# Tools:
# jwt.io - decode and edit
# jwt_tool - comprehensive testing
Key insight: Weak tokens can be predicted or forged. Analysis reveals the attack approach.
3) Session Hijacking
Stealing or capturing session tokens:
Session Hijacking Methods:
1. Network Interception (MITM)
- Unencrypted HTTP
- ARP spoofing
- WiFi sniffing
2. Cross-Site Scripting (XSS)
- Steal cookie via JavaScript
- If HttpOnly not set
3. Session Fixation
- Force victim to use known session
- Attacker already knows the ID
4. Session Prediction
- Weak token generation
- Guess valid sessions
5. Physical Access
- Browser left open
- Session in URL history
Session Fixation Attack:
# Session Fixation Flow
1. Attacker obtains session ID
- Visit target site
- Get assigned: session=abc123
2. Attacker tricks victim into using that session
- Send link: https://target.com/?session=abc123
- Some apps accept session ID in URL
3. Victim authenticates
- Logs in with session=abc123
- Session now associated with victim's account
4. Attacker hijacks session
- Uses same session=abc123
- Now authenticated as victim
# Testing for session fixation:
1. Get session before login
2. Login
3. Check if session ID changed
# Vulnerable: Same session ID after login
# Secure: New session ID generated
Cookie Theft via XSS:
# If HttpOnly is NOT set:
# Attacker receives:
GET /steal?c=session=abc123xyz
# Attacker uses cookie:
Cookie: session=abc123xyz
# Now authenticated as victim!
# Prevention:
Set-Cookie: session=abc123; HttpOnly
# HttpOnly prevents JavaScript access
# XSS can't steal HttpOnly cookies
Session Token Prediction:
# If tokens are predictable:
Observed tokens:
user1: session=100001
user2: session=100002
user3: session=100003
# Predict next user:
session=100004, 100005, 100006...
# Or timestamp-based:
session=1703123456
session=1703123457
# Brute force with Burp Intruder:
1. Capture authenticated request
2. Send to Intruder
3. Payload: Numbers 100000-100999
4. Look for 200 responses with content
# Sequential sessions allow mass account takeover
Key insight: Session hijacking gives full account access without knowing the password. Protect tokens accordingly.
4) Cross-Site Request Forgery (CSRF)
Tricking users into making unintended requests:
CSRF Attack Concept:
Victim is logged into bank.com
Victim visits malicious site
Malicious site triggers:
POST bank.com/transfer
to=attacker&amount=10000
Browser sends victim's bank.com cookies
Bank sees valid session
Transfer executes!
Key requirements:
1. Victim authenticated to target
2. Target doesn't validate request origin
3. Attacker knows required parameters
CSRF Attack Examples:
# GET-based CSRF (easy)
# Change email:
# Hidden in image tag, loads automatically
# POST-based CSRF
# Auto-submits when page loads
# JSON-based CSRF (harder)
# Creates: {"email":"attacker@evil.com","ignore":"="}
CSRF Protections:
# Anti-CSRF Tokens
Server includes token in form:
Server validates token on submission
Attacker can't guess the token
# Token bypass attempts:
1. Remove token entirely
2. Use empty token
3. Use token from different session
4. Use token from different user
5. Reuse old token
# SameSite Cookie Attribute
Set-Cookie: session=abc; SameSite=Strict
Strict: Cookie never sent cross-site
Lax: Sent on top-level GET only
None: Always sent (requires Secure)
# Testing SameSite:
1. Check cookie attributes
2. If None or missing, CSRF possible
3. If Lax, GET-based CSRF possible
# Referer/Origin Validation
Server checks:
Origin: https://target.com
Referer: https://target.com/page
# Bypass attempts:
- Remove header
- Spoof header (not in browser)
- Use data: or javascript: URLs
Testing for CSRF:
# CSRF testing methodology
1. Identify state-changing requests
- Password change
- Email change
- Money transfer
- Settings update
2. Check for protections
- CSRF token present?
- SameSite cookie?
- Referer validation?
3. Test token validation
- Remove token
- Change token value
- Use different session's token
4. Create PoC
# Burp: Right-click → Engagement tools → Generate CSRF PoC
5. Test PoC
- Open in different browser
- While logged in as victim
- Does action execute?
# Burp extension: CSRF Scanner
Key insight: CSRF exploits the trust a site has in the user's browser. Any action the user can take, CSRF can trigger.
5) Session Management Best Practices Testing
Comprehensive session security assessment:
Session Security Checklist:
Token Generation:
□ Cryptographically random?
□ Sufficient length (128+ bits)?
□ No predictable patterns?
□ No embedded user data?
Cookie Configuration:
□ HttpOnly flag set?
□ Secure flag set?
□ SameSite attribute?
□ Appropriate scope (Path, Domain)?
□ Reasonable expiration?
Session Lifecycle:
□ New session on login?
□ Session invalidated on logout?
□ Session timeout implemented?
□ Concurrent session handling?
CSRF Protection:
□ Anti-CSRF tokens used?
□ Tokens properly validated?
□ SameSite cookies?
□ Referer validation?
Testing Session Timeout:
# Session timeout tests
1. Idle timeout
- Login, wait (30min, 1hr)
- Try to access protected page
- Should require re-authentication
2. Absolute timeout
- Session should expire regardless of activity
- Prevents infinite sessions
3. Timeout on sensitive actions
- Password change should require recent auth
- Not rely on old session
# Test methodology:
1. Login and note session token
2. Wait beyond expected timeout
3. Use old token
4. Should receive 401/403 or redirect to login
Testing Logout:
# Logout security tests
1. Is session invalidated server-side?
- Logout
- Try using old session token
- Should be rejected
2. Is cookie cleared client-side?
- Check Set-Cookie after logout
- Should clear/expire session cookie
3. Are all sessions terminated?
- Login on device A and B
- Logout on A
- Is B still valid?
4. "Logout everywhere" function?
- Should invalidate all sessions
- Test if it works
# Common issues:
- Session not invalidated (can reuse token)
- Only clears cookie (token still valid)
- Doesn't handle concurrent sessions
Testing Concurrent Sessions:
# Multiple session tests
1. Are concurrent sessions allowed?
- Login from browser A
- Login from browser B
- Both should work? Or one invalidated?
2. Session limit enforcement
- Login from many browsers
- Is there a maximum?
- What happens when exceeded?
3. Session visibility
- Can user see active sessions?
- Can user terminate other sessions?
# Security implications:
- No limit = attacker maintains access
- Old sessions survive password change?
- Password change should invalidate all sessions
Key insight: Session security is holistic. Weak links in generation, storage, or lifecycle all create vulnerabilities.
Real-World Context: Session Attacks in Practice
Session vulnerabilities in the wild:
OAuth Session Issues: Modern applications use OAuth extensively. Token theft, improper validation, and scope escalation are common. OAuth adds complexity that creates new attack surfaces.
Mobile Session Security: Mobile apps often store tokens insecurely—in shared preferences, plain files, or logs. Tokens may not expire, enabling persistent access if device is compromised.
API Token Management: API keys and tokens often lack proper lifecycle management. Keys that should be temporary become permanent. Rotation is rare. Leaked keys remain valid indefinitely.
MITRE ATT&CK Mapping:
- T1539 - Steal Web Session Cookie: Session hijacking
- T1550.001 - Use Alternate Auth Material: Token reuse
- T1185 - Browser Session Hijacking: MITM attacks
Key insight: Session management vulnerabilities provide persistent access. Once you have a valid token, you're in until it expires or is revoked.
Guided Lab: Session Management Testing
Test session management on vulnerable applications.