🔐 OWASP API Security

Broken Authentication (A2) - Security Analysis & Mitigation

📋 Overview

Broken Authentication is ranked as A2 in the OWASP API Security Top 10. This vulnerability occurs when authentication mechanisms are improperly implemented, allowing attackers to compromise passwords, keys, session tokens, or exploit other implementation flaws to assume users' identities temporarily or permanently.

What is Broken Authentication?

Broken Authentication refers to weaknesses in the authentication process that allow attackers to gain unauthorized access to user accounts or systems. Common issues include missing CAPTCHA, lack of rate limiting, weak password policies, and insecure session management.

🎯 Key Vulnerability: Missing CAPTCHA

One of the most common examples of Broken Authentication is the absence of CAPTCHA on login pages. This allows automated bots to perform various attacks including credential stuffing, brute force attacks, and automated login attempts.

⚠️ Risk Assessment

Severity Level: HIGH

Impact: Unauthorized access, account takeover, data breach

Likelihood: High - easily exploitable with automated tools

Real-World Scenario

Imagine a login page without CAPTCHA protection. An attacker can use automated tools to attempt thousands of login combinations per minute, testing stolen credentials from previous data breaches (credential stuffing) or systematically guessing passwords (brute force).

🔍 Common Broken Authentication Vulnerabilities

1. No CAPTCHA Protection

Allows bots to perform automated login attempts without human verification.

2. Missing Rate Limiting

No restrictions on the number of login attempts, enabling brute force attacks.

3. Weak Password Policy

Allows simple passwords that are easily guessable or crackable.

4. Credential Stuffing

Using stolen username/password pairs from other breaches.

5. Session Fixation

Attacker sets a user's session ID before they log in.

6. Insecure Token Storage

Authentication tokens stored in insecure locations or transmitted insecurely.

🎬 Attack Flow Diagram

How Broken Authentication Attacks Work

1. Reconnaissance
Attacker identifies login page
2. Vulnerability Check
Tests for CAPTCHA/rate limiting
3. Attack Execution
Launches automated bot attacks
4. Access Gained
Successful account compromise

Detailed Attack Process

1
Target Identification: Attacker discovers a login page without visible CAPTCHA protection.
2
Tool Setup: Attacker configures automated tools (e.g., Hydra, Burp Suite, custom scripts) with credential lists.
3
Automated Testing: Bot sends thousands of login requests with different credential combinations.
4
Success Identification: Valid credentials are identified through different HTTP response codes or page content.
5
Account Takeover: Attacker gains unauthorized access and can perform malicious actions.

🛠️ Testing for Broken Authentication

Manual Testing Commands

1. Test for CAPTCHA presence:

curl -X POST https://target-site.com/login -d "username=test&password=test" -v

2. Test for rate limiting by sending multiple requests:

for i in {1..100}; do curl -X POST https://target-site.com/login -d "username=admin&password=test$i"; done

3. Using Hydra for brute force testing:

hydra -l admin -P /path/to/passwords.txt target-site.com http-post-form "/login:username=^USER^&password=^PASS^:F=incorrect"

4. Using Burp Suite Intruder:

Configure Burp Suite Intruder > Set payload positions > Load password list > Start attack

5. Testing with Python script:

import requests url = "https://target-site.com/login" passwords = ["password123", "admin123", "test123"] for password in passwords: data = {"username": "admin", "password": password} response = requests.post(url, data=data) if response.status_code == 200: print(f"Success with password: {password}")

6. Check for account lockout mechanism:

curl -X POST https://target-site.com/login -d "username=testuser&password=wrong" --cookie-jar cookies.txt

7. Test session token security:

curl -X GET https://target-site.com/api/user -H "Authorization: Bearer TOKEN" -v

8. Analyze response time for user enumeration:

time curl -X POST https://target-site.com/login -d "username=validuser&password=test"

🔬 Example Vulnerable vs Secure Implementation

❌ Vulnerable Login Page (No CAPTCHA, No Rate Limiting)

<form action="/login" method="POST"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button type="submit">Login</button> </form> // Backend (vulnerable) app.post('/login', (req, res) => { const { username, password } = req.body; if (validateCredentials(username, password)) { res.send('Login successful'); } else { res.send('Login failed'); } });

✅ Secure Login Page (With CAPTCHA and Rate Limiting)

<form action="/login" method="POST"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <div class="g-recaptcha" data-sitekey="your_site_key"></div> <button type="submit">Login</button> </form> // Backend (secure with rate limiting) const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 5 // limit each IP to 5 requests per windowMs }); app.post('/login', limiter, async (req, res) => { const { username, password, captchaToken } = req.body; // Verify CAPTCHA const captchaValid = await verifyCaptcha(captchaToken); if (!captchaValid) { return res.status(400).send('Invalid CAPTCHA'); } // Validate credentials with account lockout if (validateCredentials(username, password)) { resetLoginAttempts(username); res.send('Login successful'); } else { incrementLoginAttempts(username); res.status(401).send('Login failed'); } });

🛡️ Mitigation Strategies

Essential Security Controls

  1. Implement CAPTCHA: Use reCAPTCHA or similar solutions to prevent automated bot attacks
  2. Rate Limiting: Limit the number of login attempts per IP address or user account
  3. Account Lockout: Temporarily lock accounts after multiple failed login attempts
  4. Strong Password Policy: Enforce minimum length, complexity requirements, and password strength meters
  5. Multi-Factor Authentication (MFA): Add an additional layer of security beyond passwords
  6. Secure Session Management: Use secure, httpOnly cookies and implement proper session timeout
  7. Monitor and Log: Track failed login attempts and alert on suspicious patterns
  8. Use HTTPS: Always encrypt authentication traffic with TLS/SSL

Implementation Examples

Rate Limiting with Express.js:

npm install express-rate-limit

CAPTCHA Integration (Google reCAPTCHA):

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Account Lockout Logic:

if (failedAttempts >= 5) { lockAccount(username, 15 * 60 * 1000); }

Password Hashing with bcrypt:

const hashedPassword = await bcrypt.hash(password, 10);

📊 Comparison Table: Vulnerable vs Secure

Feature Vulnerable Implementation Secure Implementation
CAPTCHA ❌ Not implemented ✅ reCAPTCHA v3 or hCaptcha
Rate Limiting ❌ Unlimited attempts allowed ✅ 5 attempts per 15 minutes
Account Lockout ❌ No lockout mechanism ✅ Lock after 5 failed attempts
Password Policy ❌ Accepts weak passwords ✅ Minimum 12 characters, complexity required
MFA ❌ Not available ✅ TOTP or SMS-based 2FA
Session Management ❌ Insecure cookies ✅ HttpOnly, Secure, SameSite flags
Logging ❌ No monitoring ✅ Comprehensive audit logs
Transport Security ❌ HTTP allowed ✅ HTTPS enforced with HSTS

🔧 Tools for Testing and Protection

Penetration Testing Tools:

  • Burp Suite: Comprehensive web application security testing
  • OWASP ZAP: Free, open-source security scanner
  • Hydra: Fast network logon cracker
  • Medusa: Parallel, modular brute-force login auditor
  • Nikto: Web server scanner
  • Custom Python Scripts: For automated testing

Protection Solutions:

  • Google reCAPTCHA: Free CAPTCHA service
  • hCaptcha: Privacy-focused CAPTCHA alternative
  • Cloudflare: DDoS protection and rate limiting
  • AWS WAF: Web Application Firewall
  • Fail2Ban: Intrusion prevention software
  • Auth0: Authentication and authorization platform

📚 Additional Resources

Further Learning

  • OWASP API Security Project: Complete guide to API security best practices
  • OWASP Testing Guide: Comprehensive testing methodology
  • NIST Digital Identity Guidelines: Authentication and lifecycle management standards
  • CWE-287: Improper Authentication common weakness enumeration

🎓 Key Takeaways

  1. Never deploy login pages without bot protection: Always implement CAPTCHA or similar mechanisms
  2. Implement multiple layers of defense: Combine rate limiting, account lockout, and MFA
  3. Monitor and respond: Set up alerts for suspicious login patterns
  4. Regular security audits: Test your authentication mechanisms periodically
  5. Stay updated: Keep abreast of new attack vectors and mitigation techniques
  6. Educate users: Promote strong password practices and MFA adoption

⚠️ Final Warning

Ethical Considerations

The techniques and tools described in this document are for educational and authorized testing purposes only. Unauthorized access to computer systems is illegal and punishable by law. Always obtain proper authorization before conducting security assessments. Use this knowledge to build more secure systems and protect users.