authentication-authorization-vulnerabilities-ai-code
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".
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 seRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.