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.

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

VulnerabilityAttack MethodTypical ImpactCommon Location
Broken AuthenticationExploiting flawed authentication mechanismsAccount takeover, data accessLogin systems, session management
Session HijackingStealing or predicting session tokensSession compromiseSession cookies, tokens
Session FixationForcing users to use known session IDsSession compromiseSession initialization
Credential StuffingUsing leaked credentials from other breachesAccount takeoverLogin forms
Password SprayingTrying common passwords across accountsAccount takeoverLogin forms
Brute Force AttackTrying all possible password combinationsAccount takeoverLogin forms
Weak Password PoliciesExploiting weak password requirementsCredential compromiseRegistration, 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

  1. Weak password policies: Exploiting insufficient password requirements
  2. Insecure credential storage: Accessing poorly stored passwords
  3. Session fixation: Forcing users to use known session IDs
  4. Session hijacking: Stealing or predicting session tokens
  5. Insecure session management: Exploiting session timeout flaws
  6. Credential stuffing: Using leaked credentials from other breaches
  7. Password spraying: Trying common passwords across accounts
  8. Brute force attacks: Trying all possible password combinations
  9. Insecure password reset: Exploiting flawed password recovery
  10. 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:

  1. Attacker identifies login endpoint
  2. Uses automated tool to try different password combinations
  3. Application processes each attempt without rate limiting
  4. Eventually finds correct password
  5. 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:

  1. Attacker generates a session ID and sends link to victim
  2. Victim clicks link and logs in using attacker's session ID
  3. Application doesn't regenerate session ID after login
  4. Attacker uses the known session ID to access victim's account
  5. 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:

  1. Attacker obtains leaked credentials from previous breaches
  2. Uses automated tool to try credentials on target site
  3. Application processes each attempt without detection
  4. Finds accounts where users reused credentials
  5. 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:

  1. Attacker identifies common passwords
  2. Uses automated tool to try passwords across multiple accounts
  3. Application processes attempts without detection
  4. Finds accounts using common passwords
  5. 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:

  1. Attacker identifies XSS vulnerability
  2. Injects malicious script that accesses session token
  3. Script sends session token to attacker's server
  4. Attacker uses stolen session token to hijack session
  5. 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:

  1. Minimum length: Require 12+ character passwords
  2. Complexity requirements: Uppercase, lowercase, numbers, symbols
  3. Password blacklists: Ban common passwords
  4. Password expiration: Regular password changes
  5. 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:

  1. Strong hashing: Use bcrypt, Argon2, or PBKDF2
  2. Unique salts: Generate unique salt for each password
  3. Secure parameters: Appropriate work factors
  4. Key management: Secure encryption keys
  5. 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:

  1. Session ID generation: Use cryptographically secure random IDs
  2. Session expiration: Implement proper session timeout
  3. Session invalidation: Invalidate sessions after logout
  4. Secure cookies: Use HttpOnly, Secure, SameSite flags
  5. 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:

  1. Multiple factors: Combine something you know, have, and are
  2. Time-based tokens: TOTP (Time-based One-Time Password)
  3. SMS/email codes: One-time codes sent to user
  4. Hardware tokens: Physical security keys
  5. 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