Claude
Skills
Sign in
Back

authentication-authorization-vulnerabilities-ai-code

Included with Lifetime
$97 forever

Understand authentication and authorization defects in AI-generated code including insecure password storage, broken session management, and access control bypasses. Use this skill when you need to learn about auth vulnerabilities in AI code, understand why AI suggests MD5/plaintext passwords, recognize broken session patterns, or identify access control gaps. Triggers include "auth vulnerabilities AI", "password storage AI", "session management", "broken access control", "authentication defects", "MD5 passwords", "session hijacking", "authorization bypass".

General

What this skill does


# Authentication and Authorization Defects in AI-Generated Code

## The Systemic Nature of Auth Vulnerabilities

A 2025 study by Databricks revealed:

> "AI-generated authentication systems frequently incorporate outdated patterns and fail to implement modern security practices, creating what we call 'authentication debt' in codebases."

### The Statistics

The research found that:
- **73% of AI-generated authentication code** lacked proper session management
- **81% stored passwords insecurely** (MD5, SHA1, or plaintext)

These aren't edge cases—they're the norm in AI-generated authentication code.

## 1.2.1 Insecure Password Storage

### The Problem

The most alarming finding from multiple studies is the prevalence of **plaintext or weakly hashed password storage** in AI-generated code.

As noted by Infisical's security team:

> "AI models trained on older codebases often suggest MD5 or SHA1 for password hashing, algorithms that have been cryptographically broken for over a decade."

### AI-Generated Vulnerable Code

```python
# Prompt: "Implement user registration with password"
import hashlib
import mysql.connector

def register_user(username, password, email):
    conn = mysql.connector.connect(host='localhost', database='app')
    cursor = conn.cursor()

    # ❌ VULNERABLE: MD5 is cryptographically broken
    password_hash = hashlib.md5(password.encode()).hexdigest()

    # ❌ VULNERABLE: No salt means identical passwords have identical hashes
    query = "INSERT INTO users (username, password, email) VALUES (%s, %s, %s)"
    cursor.execute(query, (username, password_hash, email))

    conn.commit()
    return {"status": "success", "user_id": cursor.lastrowid}

# Even worse: Some AI models generate this
def register_user_worse(username, password, email):
    # ❌ CRITICAL: Storing plaintext passwords
    user_data = {
        "username": username,
        "password": password,  # Never do this!
        "email": email
    }
    database.save(user_data)
```

### Secure Implementation

```python
import bcrypt
import secrets
from datetime import datetime, timedelta

def register_user_secure(username, password, email):
    # ✅ SECURE: Validate password strength
    if len(password) < 12:
        raise ValueError("Password must be at least 12 characters")

    # ✅ SECURE: Use bcrypt with cost factor 12
    salt = bcrypt.gensalt(rounds=12)
    password_hash = bcrypt.hashpw(password.encode('utf-8'), salt)

    # ✅ SECURE: Generate secure activation token
    activation_token = secrets.token_urlsafe(32)
    token_expiry = datetime.utcnow() + timedelta(hours=24)

    user_data = {
        "username": username,
        "password_hash": password_hash,
        "email": email,
        "activation_token": activation_token,
        "token_expiry": token_expiry,
        "is_active": False,
        "created_at": datetime.utcnow(),
        "failed_login_attempts": 0,
        "last_failed_login": None
    }

    # Store with proper error handling
    try:
        user_id = database.create_user(user_data)
        send_activation_email(email, activation_token)
        return {"status": "success", "message": "Check email for activation"}
    except IntegrityError:
        return {"status": "error", "message": "Username or email already exists"}
```

### Why AI Generates Insecure Password Storage

**1. Training Data from Older Code:**
- Millions of examples from 2000s-2010s use MD5/SHA1
- AI learns these as "standard" approaches
- Doesn't know they're cryptographically broken

**2. Simplicity Bias:**
- `hashlib.md5()` is simpler than `bcrypt.gensalt()`
- Fewer lines of code
- No external dependencies in simple example

**3. Missing Security Knowledge:**
- AI doesn't understand rainbow tables
- Can't reason about hash collision attacks
- Doesn't know MD5 is broken

### Why MD5/SHA1 Are Broken

**MD5 Problems:**
- Can be computed **billions of times per second** on modern GPUs
- 8-character password: cracked in **minutes**
- Rainbow tables exist for common passwords
- Collision attacks demonstrated since 2004

**SHA1 Problems:**
- Also too fast to compute
- Google demonstrated practical collision attack (2017)
- NIST deprecated for cryptographic use (2011)

**What "Cryptographically Broken" Means:**
Not that hashes can be "decrypted" (they can't), but that:
- Brute force is too fast
- Collision attacks are practical
- No computational cost for attackers

### What Secure Hashing Requires

**bcrypt (Recommended):**
- **Adaptive cost factor:** Can be increased as hardware improves
- **Built-in salt:** Unique per password
- **Slow by design:** Makes brute force impractical
- **Industry standard:** Widely audited and trusted

**Cost Factor:**
```python
# Cost factor = 12 (recommended)
# 2^12 = 4,096 iterations
# Makes each hash computation slower
# Attacker must do 4,096 iterations per attempt
```

### Real-World Password Storage Breaches

**Ashley Madison (2015):**
- Custom authentication with **weak password hashing**
- **32 million accounts** compromised
- Passwords cracked within days
- Company nearly destroyed

**Dropbox (2012):**
- Custom authentication led to **password hash database theft**
- **68 million accounts** affected
- Many passwords cracked from hashes
- Years of credential stuffing attacks followed

**LinkedIn (2012):**
- Used **unsalted SHA-1** for passwords
- **117 million password hashes** stolen
- 90% of passwords cracked within days
- Used in credential stuffing attacks for years

### The Secure Alternative: Use Clerk

According to Veracode's 2024 report:

> Applications using managed authentication services (like Clerk, Auth0) had **73% fewer authentication-related vulnerabilities** than those with custom authentication.

**Why Clerk is Secure:**
- ✅ Uses bcrypt/Argon2 (modern, secure algorithms)
- ✅ Proper salt generation
- ✅ SOC 2 certified (audited security controls)
- ✅ Regular security updates
- ✅ Professional security team maintaining code

---

## 1.2.2 Broken Session Management

### The Problem

Research from The Hacker News found:

> "AI-generated session management code often lacks proper timeout mechanisms, secure cookie flags, and session fixation protection."

This creates multiple attack vectors for session hijacking.

### AI-Generated Vulnerable Code

```javascript
// Prompt: "Implement user sessions"
const sessions = {};

app.post('/login', async (req, res) => {
    const { username, password } = req.body;

    if (await validateCredentials(username, password)) {
        // ❌ VULNERABLE: Predictable session ID
        const sessionId = Buffer.from(username + Date.now()).toString('base64');

        // ❌ VULNERABLE: No expiration
        sessions[sessionId] = {
            username: username,
            loginTime: Date.now()
        };

        // ❌ VULNERABLE: Missing security flags
        res.cookie('sessionId', sessionId);
        res.json({ success: true });
    }
});

app.get('/profile', (req, res) => {
    const sessionId = req.cookies.sessionId;

    // ❌ VULNERABLE: No session validation or renewal
    if (sessions[sessionId]) {
        const userData = getUserData(sessions[sessionId].username);
        res.json(userData);
    }
});
```

### Multiple Vulnerabilities in This Code

**1. Predictable Session IDs:**
```javascript
const sessionId = Buffer.from(username + Date.now()).toString('base64');
```

**Problem:**
- Attacker knows username (public)
- Can guess timestamp (Date.now() when login occurred)
- Can recreate session ID and hijack session

**2. No Session Expiration:**
```javascript
sessions[sessionId] = { username, loginTime }
```

**Problem:**
- Session never expires
- Stolen session valid forever
- No automatic logout

**3. Missing Cookie Security Flags:**
```javascript
res.cookie('sessionId', sessionId);
```

**Problem:**
- No `httpOnly`: JavaScript can access (XSS steals session)
- No `secure`: Sent over HTTP (man-in-the-middle)
- No `sameSite`: Vulnerable to CSRF

**4. In-Memory Storage:**
```javascript
const se

Related in General