Broken Authentication
What is Broken Authentication?
Broken Authentication is a web security vulnerability that occurs when authentication mechanisms are implemented incorrectly, allowing attackers to compromise user accounts, passwords, session tokens, or keys. This vulnerability enables attackers to assume other users' identities, gain unauthorized access to sensitive data, and perform actions on behalf of legitimate users.
Key Characteristics
- Account takeover: Attackers gain control of user accounts
- Session compromise: Attackers hijack active user sessions
- Credential theft: Attackers obtain user credentials
- Identity impersonation: Attackers act as legitimate users
- Access control bypass: Attackers bypass authentication mechanisms
- Information disclosure: Attackers access sensitive user data
- Common in authentication flows: Frequently found in login, registration, and password reset functionality
Broken Authentication vs Other Authentication Vulnerabilities
| Vulnerability | Attack Method | Typical Impact | Common Location |
|---|---|---|---|
| Broken Authentication | Exploiting flawed authentication mechanisms | Account takeover, data access | Login systems, session management |
| Session Hijacking | Stealing or predicting session tokens | Session compromise | Session cookies, tokens |
| Session Fixation | Forcing users to use known session IDs | Session compromise | Session initialization |
| Credential Stuffing | Using leaked credentials from other breaches | Account takeover | Login forms |
| Password Spraying | Trying common passwords across accounts | Account takeover | Login forms |
| Brute Force Attack | Trying all possible password combinations | Account takeover | Login forms |
| Weak Password Policies | Exploiting weak password requirements | Credential compromise | Registration, password change |
How Broken Authentication Works
Technical Mechanism
graph TD
A[Attacker] -->|1. Identifies authentication flaw| B[Vulnerable Authentication System]
B -->|2. Processes malicious input| C[Authentication Mechanism]
C -->|3. Fails to validate properly| B
B -->|4. Grants unauthorized access| A
Common Exploitation Paths
- Weak password policies: Exploiting insufficient password requirements
- Insecure credential storage: Accessing poorly stored passwords
- Session fixation: Forcing users to use known session IDs
- Session hijacking: Stealing or predicting session tokens
- Insecure session management: Exploiting session timeout flaws
- Credential stuffing: Using leaked credentials from other breaches
- Password spraying: Trying common passwords across accounts
- Brute force attacks: Trying all possible password combinations
- Insecure password reset: Exploiting flawed password recovery
- Authentication bypass: Bypassing authentication entirely
Common Broken Authentication Vulnerabilities
1. Weak Password Policies
Description: Insufficient password complexity requirements that allow users to create easily guessable passwords.
Examples:
- No minimum length requirements
- No complexity requirements (uppercase, lowercase, numbers, symbols)
- Common password allowances (e.g., "password123")
- No password expiration policies
- No account lockout after failed attempts
Impact:
- Increased susceptibility to brute force attacks
- Higher success rate for credential stuffing
- Easier password guessing
Prevention:
- Enforce minimum password length (12+ characters)
- Require complexity (uppercase, lowercase, numbers, symbols)
- Ban common passwords
- Implement password expiration policies
- Enforce account lockout after failed attempts
2. Insecure Credential Storage
Description: Storing user credentials in insecure formats that can be easily compromised.
Examples:
- Plaintext password storage
- Weak hashing algorithms (MD5, SHA-1)
- Unsalted hashes
- Insecure encryption
- Hardcoded credentials
Impact:
- Mass credential compromise if database is breached
- Credential reuse across services
- Easy password recovery for attackers
Prevention:
- Use strong hashing algorithms (bcrypt, Argon2, PBKDF2)
- Always use unique salts for each password
- Never store passwords in plaintext
- Use secure key management for encryption
- Regularly audit credential storage practices
3. Session Fixation
Description: Forcing a user to use a known session ID that the attacker can later use to hijack the session.
Examples:
- Session ID not regenerated after login
- Session ID passed in URL parameters
- Session ID not invalidated after logout
- Predictable session ID generation
Impact:
- Session hijacking
- Account takeover
- Unauthorized access to user data
Prevention:
- Regenerate session ID after login
- Use secure, random session ID generation
- Invalidate session IDs after logout
- Use HttpOnly and Secure cookie flags
- Implement session timeout
4. Session Hijacking
Description: Stealing or predicting session tokens to gain unauthorized access to user accounts.
Examples:
- Session token theft via XSS
- Session token prediction
- Session token interception (MITM)
- Session token leakage in logs
- Session token reuse
Impact:
- Unauthorized account access
- Data theft
- Identity impersonation
- Fraudulent transactions
Prevention:
- Use secure, random session tokens
- Implement proper session expiration
- Use HttpOnly and Secure cookie flags
- Encrypt session data
- Implement session validation
5. Insecure Session Management
Description: Flaws in session management that allow attackers to maintain or extend unauthorized access.
Examples:
- No session timeout
- Long session expiration
- No session invalidation after logout
- Session token leakage
- Insecure session storage
Impact:
- Prolonged unauthorized access
- Increased window for session hijacking
- Persistent account compromise
Prevention:
- Implement proper session timeout
- Invalidate sessions after logout
- Use secure session storage
- Encrypt session data
- Monitor for suspicious session activity
6. Credential Stuffing
Description: Using leaked credentials from other breaches to gain unauthorized access to accounts.
Examples:
- Using credentials from previous data breaches
- Automated login attempts with leaked credentials
- Credential reuse across multiple services
- Password spraying with common passwords
Impact:
- Account takeover
- Data breach amplification
- Credential reuse attacks
- Mass account compromise
Prevention:
- Implement multi-factor authentication
- Monitor for credential stuffing attempts
- Enforce password uniqueness
- Implement rate limiting
- Use breach detection services
7. Insecure Password Reset
Description: Flaws in password reset functionality that allow attackers to reset passwords for other users.
Examples:
- Password reset tokens sent in plaintext
- Predictable password reset tokens
- No validation of password reset requests
- Password reset tokens not expiring
- Password reset tokens not invalidated after use
Impact:
- Account takeover
- Unauthorized password changes
- Identity theft
- Data access
Prevention:
- Use secure, random password reset tokens
- Implement token expiration
- Invalidate tokens after use
- Require additional verification
- Use secure channels for token delivery
8. Authentication Bypass
Description: Flaws that allow attackers to bypass authentication mechanisms entirely.
Examples:
- Direct object reference to authenticated content
- Missing authentication checks
- Insecure direct object references
- Parameter manipulation
- Header manipulation
Impact:
- Unauthorized access to sensitive data
- Administrative access
- Complete system compromise
- Data theft
Prevention:
- Implement proper access controls
- Validate all authentication requirements
- Use indirect object references
- Implement comprehensive authorization checks
- Regular security testing
Broken Authentication Exploitation Techniques
1. Brute Force Attack
Attack Scenario: Trying all possible password combinations to gain access.
Vulnerable Code (Python Flask):
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
# No rate limiting or account lockout
user = db.get_user(username)
if user and user['password'] == password: # Plaintext comparison
session['user_id'] = user['id']
return redirect('/dashboard')
else:
return "Invalid credentials", 401
Attack Process:
- Attacker identifies login endpoint
- Uses automated tool to try different password combinations
- Application processes each attempt without rate limiting
- Eventually finds correct password
- Gains access to user account
Prevention:
- Implement rate limiting
- Enforce account lockout after failed attempts
- Use strong password policies
- Implement CAPTCHA
- Use secure password storage
2. Session Fixation Attack
Attack Scenario: Forcing a user to use a known session ID.
Vulnerable Code (PHP):
<?php
// Session ID not regenerated after login
session_start();
if ($_POST['username'] && $_POST['password']) {
$user = authenticate($_POST['username'], $_POST['password']);
if ($user) {
$_SESSION['user_id'] = $user['id'];
header('Location: /dashboard.php');
exit;
}
}
?>
Attack Process:
- Attacker generates a session ID and sends link to victim
- Victim clicks link and logs in using attacker's session ID
- Application doesn't regenerate session ID after login
- Attacker uses the known session ID to access victim's account
- Gains unauthorized access
Prevention:
- Regenerate session ID after login
- Use secure session ID generation
- Invalidate old session IDs
- Use HttpOnly and Secure cookie flags
3. Credential Stuffing Attack
Attack Scenario: Using leaked credentials from other breaches.
Attack Process:
- Attacker obtains leaked credentials from previous breaches
- Uses automated tool to try credentials on target site
- Application processes each attempt without detection
- Finds accounts where users reused credentials
- Gains access to multiple accounts
Prevention:
- Implement multi-factor authentication
- Monitor for credential stuffing patterns
- Enforce password uniqueness
- Implement rate limiting
- Use breach detection services
4. Password Spraying Attack
Attack Scenario: Trying common passwords across multiple accounts.
Attack Process:
- Attacker identifies common passwords
- Uses automated tool to try passwords across multiple accounts
- Application processes attempts without detection
- Finds accounts using common passwords
- Gains access to multiple accounts
Prevention:
- Implement multi-factor authentication
- Enforce strong password policies
- Implement account lockout
- Monitor for password spraying patterns
- Use CAPTCHA
5. Session Hijacking via XSS
Attack Scenario: Stealing session tokens using cross-site scripting.
Vulnerable Code (JavaScript):
// Session token stored in localStorage without protection
const sessionToken = localStorage.getItem('sessionToken');
// Vulnerable to XSS that can access localStorage
document.write(userInput);
Attack Process:
- Attacker identifies XSS vulnerability
- Injects malicious script that accesses session token
- Script sends session token to attacker's server
- Attacker uses stolen session token to hijack session
- Gains unauthorized access to user account
Prevention:
- Use HttpOnly cookies for session tokens
- Implement proper XSS protections
- Use Content Security Policy
- Sanitize all user input
- Use secure storage mechanisms
Broken Authentication Prevention Methods
1. Secure Password Policies
Implementation Strategies:
- Minimum length: Require 12+ character passwords
- Complexity requirements: Uppercase, lowercase, numbers, symbols
- Password blacklists: Ban common passwords
- Password expiration: Regular password changes
- Account lockout: Lock after failed attempts
Example (Password Policy in Node.js):
function validatePassword(password) {
// Minimum 12 characters
if (password.length < 12) {
return { valid: false, reason: 'Password must be at least 12 characters' };
}
// Require complexity
const hasUpper = /[A-Z]/.test(password);
const hasLower = /[a-z]/.test(password);
const hasNumber = /[0-9]/.test(password);
const hasSymbol = /[!@#$%^&*(),.?":{}|<>]/.test(password);
if (!hasUpper || !hasLower || !hasNumber || !hasSymbol) {
return { valid: false, reason: 'Password must contain uppercase, lowercase, number, and symbol' };
}
// Check against common passwords
const commonPasswords = ['password', '12345678', 'qwertyuiop', 'letmein'];
if (commonPasswords.includes(password.toLowerCase())) {
return { valid: false, reason: 'Password is too common' };
}
return { valid: true };
}
2. Secure Credential Storage
Implementation Strategies:
- Strong hashing: Use bcrypt, Argon2, or PBKDF2
- Unique salts: Generate unique salt for each password
- Secure parameters: Appropriate work factors
- Key management: Secure encryption keys
- Regular audits: Audit credential storage practices
Example (Secure Password Storage in Python):
import bcrypt
import secrets
def hash_password(password):
# Generate a unique salt
salt = bcrypt.gensalt(rounds=12)
# Hash the password with the salt
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8')
def verify_password(password, hashed):
# Verify the password against the stored hash
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
# Example usage
password = "SecurePassword123!"
hashed = hash_password(password)
# Verify
is_valid = verify_password(password, hashed) # True
3. Secure Session Management
Implementation Strategies:
- Session ID generation: Use cryptographically secure random IDs
- Session expiration: Implement proper session timeout
- Session invalidation: Invalidate sessions after logout
- Secure cookies: Use HttpOnly, Secure, SameSite flags
- Session storage: Use secure session storage
Example (Secure Session in Express):
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const { v4: uuidv4 } = require('uuid');
// Configure secure session
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
name: 'secure_session_id',
genid: () => uuidv4(), // Generate secure session ID
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 30 * 60 * 1000 // 30 minutes
},
resave: false,
saveUninitialized: false
}));
// Middleware to validate session
app.use((req, res, next) => {
if (!req.session.userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Check session expiration
if (req.session.cookie.expires < new Date()) {
req.session.destroy();
return res.status(401).json({ error: 'Session expired' });
}
next();
});
// Logout endpoint
app.post('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.status(500).json({ error: 'Logout failed' });
}
res.clearCookie('secure_session_id');
res.json({ success: true });
});
});
4. Multi-Factor Authentication (MFA)
Implementation Strategies:
- Multiple factors: Combine something you know, have, and are
- Time-based tokens: TOTP (Time-based One-Time Password)
- SMS/email codes: One-time codes sent to user
- Hardware tokens: Physical security keys
- Biometric verification: Fingerprint, face recognition
Example (MFA Implementation in Node.js):
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
// Generate MFA secret
function generateMFASecret(userId) {
const secret = speakeasy.generateSecret({
length: 20,
name: 'MyApp',
issuer: 'MyCompany'
});
// Store secret with user
db.storeMFASecret(userId, secret.base32);
return secret;
}
// Generate QR code for MFA setup
async function generateQRCode(userId) {
const secret = await db.getMFASecret(userId);
const otpauthUrl = speakeasy.otpauth
Blind SQL Injection
Blind SQL Injection is a type of SQL Injection attack where attackers infer data from application behavior rather than direct error messages or output.
Brute Force Attack
A trial-and-error method used by attackers to guess passwords, encryption keys, or other credentials through exhaustive enumeration.
