# Vulnerability Patterns

## Overview

Common vulnerability patterns and how to identify them in code review.

---

## 1. Authentication Vulnerabilities

### Weak Password Storage

**Pattern**:

```typescript
// ❌ BAD: Plain text or weak hashing
const passwordHash = md5(password);
const passwordHash = sha1(password);
```

**Fix**:

```typescript
// ✅ GOOD: Strong adaptive hashing
const passwordHash = await bcrypt.hash(password, 12);
```

### Missing Rate Limiting

**Pattern**:

```typescript
// ❌ BAD: No rate limiting on login
app.post('/login', async (req, res) => {
  const user = await authenticate(req.body);
  // Allows unlimited attempts
});
```

**Fix**:

```typescript
// ✅ GOOD: Rate limited
app.post('/login', rateLimiter({ max: 5, windowMs: 60000 }), ...);
```

---

## 2. Injection Vulnerabilities

### SQL Injection

**Pattern**:

```typescript
// ❌ BAD: String concatenation
const query = `SELECT * FROM users WHERE id = '${userId}'`;
```

**Fix**:

```typescript
// ✅ GOOD: Parameterized query
const result = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
```

### Command Injection

**Pattern**:

```typescript
// ❌ BAD: User input in shell command
exec(`convert ${userFilename} output.png`);
```

**Fix**:

```typescript
// ✅ GOOD: Validate and escape
const sanitizedName = sanitize(userFilename);
execFile('convert', [sanitizedName, 'output.png']);
```

### NoSQL Injection

**Pattern**:

```typescript
// ❌ BAD: Object injection in MongoDB
const user = await User.findOne({
  username: req.body.username,
  password: req.body.password, // Could be { $gt: '' }
});
```

**Fix**:

```typescript
// ✅ GOOD: Type validation
const username = String(req.body.username);
const password = String(req.body.password);
```

---

## 3. XSS Vulnerabilities

### Reflected XSS

**Pattern**:

```typescript
// ❌ BAD: User input in response
res.send(`<h1>Search: ${req.query.q}</h1>`);
```

**Fix**:

```typescript
// ✅ GOOD: Escape output
res.send(`<h1>Search: ${escapeHtml(req.query.q)}</h1>`);
```

### Stored XSS

**Pattern**:

```typescript
// ❌ BAD: Unescaped database content
<div dangerouslySetInnerHTML={{ __html: user.bio }} />
```

**Fix**:

```typescript
// ✅ GOOD: Sanitize HTML
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(user.bio) }} />
```

---

## 4. Access Control Vulnerabilities

### IDOR (Insecure Direct Object Reference)

**Pattern**:

```typescript
// ❌ BAD: No ownership check
app.get('/documents/:id', async (req, res) => {
  const doc = await Document.findById(req.params.id);
  res.json(doc); // Anyone can access any document
});
```

**Fix**:

```typescript
// ✅ GOOD: Verify ownership
app.get('/documents/:id', async (req, res) => {
  const doc = await Document.findOne({
    _id: req.params.id,
    owner: req.user.id, // Only owner can access
  });
  if (!doc) return res.status(404).end();
  res.json(doc);
});
```

### Privilege Escalation

**Pattern**:

```typescript
// ❌ BAD: Client-controlled role
const user = await User.create({
  ...req.body,
  role: req.body.role, // User can set admin role!
});
```

**Fix**:

```typescript
// ✅ GOOD: Server-controlled role
const user = await User.create({
  name: req.body.name,
  email: req.body.email,
  role: 'user', // Default role, not from request
});
```

---

## 5. Sensitive Data Exposure

### Hardcoded Secrets

**Pattern**:

```typescript
// ❌ BAD: Secrets in code
const API_KEY = 'sk_live_abc123xyz';
const dbPassword = 'admin123';
```

**Fix**:

```typescript
// ✅ GOOD: Environment variables
const API_KEY = process.env.API_KEY;
const dbPassword = process.env.DB_PASSWORD;
```

### Verbose Error Messages

**Pattern**:

```typescript
// ❌ BAD: Stack trace to client
app.use((err, req, res, next) => {
  res.status(500).json({ error: err.stack });
});
```

**Fix**:

```typescript
// ✅ GOOD: Generic error to client
app.use((err, req, res, next) => {
  logger.error(err); // Log full error
  res.status(500).json({ error: 'Internal server error' });
});
```

---

## 6. CSRF Vulnerabilities

### Missing CSRF Token

**Pattern**:

```html
<!-- ❌ BAD: No CSRF protection -->
<form action="/transfer" method="POST">
  <input name="amount" value="1000" />
  <input name="to" value="attacker" />
</form>
```

**Fix**:

```html
<!-- ✅ GOOD: CSRF token included -->
<form action="/transfer" method="POST">
  <input type="hidden" name="_csrf" value="{{csrfToken}}" />
  <input name="amount" value="1000" />
</form>
```

---

## 7. Insecure Dependencies

### Outdated Packages

**Detection**:

```bash
npm audit
snyk test
pip-audit
```

**Prevention**:

```json
// package.json
{
  "scripts": {
    "security-check": "npm audit --audit-level=high"
  }
}
```

---

## Code Review Security Checklist

### Input Handling

- [ ] All user input validated
- [ ] Type checking enforced
- [ ] Length limits applied
- [ ] Special characters escaped

### Authentication

- [ ] Strong password hashing (bcrypt/Argon2)
- [ ] Rate limiting on auth endpoints
- [ ] Secure session management
- [ ] MFA where appropriate

### Authorization

- [ ] Ownership verified for resources
- [ ] Roles checked on server side
- [ ] Deny by default policy

### Output

- [ ] HTML escaped for display
- [ ] JSON properly encoded
- [ ] Error messages sanitized

### Data Protection

- [ ] Secrets in environment variables
- [ ] Sensitive data encrypted
- [ ] TLS for all connections

### Dependencies

- [ ] No known vulnerabilities
- [ ] From trusted sources
- [ ] Minimal and necessary
