# Common Vulnerability Patterns

## Injection Vulnerabilities

### SQL Injection
**Pattern**: User input directly concatenated into SQL queries

**Vulnerable Code**:
```python
query = f"SELECT * FROM users WHERE username = '{username}'"
```

**Secure Code**:
```python
query = "SELECT * FROM users WHERE username = ?"
cursor.execute(query, (username,))
```

**Prevention**:
- Use parameterized queries (prepared statements)
- Use ORM frameworks
- Validate and sanitize input
- Use least privilege database accounts

### Command Injection
**Pattern**: User input used in system commands

**Vulnerable Code**:
```python
os.system(f"ping {hostname}")
```

**Secure Code**:
```python
subprocess.run(["ping", hostname], check=True)
```

**Prevention**:
- Avoid shell execution
- Use parameterized system calls
- Validate input against whitelist
- Use safe APIs

### LDAP Injection
**Pattern**: User input in LDAP queries without sanitization

**Prevention**:
- Use parameterized LDAP APIs
- Escape special characters
- Validate input format

## Cross-Site Scripting (XSS)

### Stored XSS
**Pattern**: Malicious script stored in database and executed when displayed

**Vulnerable Code**:
```html
<div>{{ user_input }}</div>
```

**Secure Code**:
```html
<div>{{ user_input | escape }}</div>
```

**Prevention**:
- Encode all output
- Use Content Security Policy (CSP)
- Validate and sanitize input
- Use templating engines with auto-escaping

### Reflected XSS
**Pattern**: Malicious script reflected in response

**Prevention**:
- Encode all output
- Validate input
- Use CSP headers

### DOM-based XSS
**Pattern**: Client-side JavaScript manipulating DOM with untrusted data

**Prevention**:
- Avoid `innerHTML` with user data
- Use `textContent` instead
- Validate and sanitize client-side input

## Cross-Site Request Forgery (CSRF)

**Pattern**: Forcing authenticated users to perform unwanted actions

**Vulnerable Code**:
```html
<form action="/transfer" method="POST">
  <input name="amount" value="1000">
  <input name="to" value="attacker">
</form>
```

**Secure Code**:
```html
<form action="/transfer" method="POST">
  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
  <!-- ... -->
</form>
```

**Prevention**:
- Use CSRF tokens
- Verify origin/referer headers
- Use SameSite cookie attribute
- Require re-authentication for sensitive operations

## Insecure Direct Object References (IDOR)

**Pattern**: Accessing resources by manipulating identifiers

**Vulnerable Code**:
```python
def get_file(file_id):
    return open(f"/files/{file_id}")  # No access check
```

**Secure Code**:
```python
def get_file(file_id, user_id):
    file = File.query.filter_by(id=file_id, owner_id=user_id).first()
    if not file:
        raise PermissionDenied
    return file
```

**Prevention**:
- Verify authorization on every request
- Use indirect references (maps to real IDs)
- Check ownership/access rights
- Don't expose internal identifiers

## Security Misconfiguration

### Default Credentials
**Pattern**: Using default usernames/passwords

**Prevention**:
- Change all default credentials
- Use strong, unique passwords
- Implement password policies
- Disable default accounts

### Verbose Error Messages
**Pattern**: Exposing sensitive information in errors

**Vulnerable Code**:
```python
except Exception as e:
    return {"error": str(e)}  # Exposes stack trace
```

**Secure Code**:
```python
except Exception as e:
    logger.error(f"Error: {e}", exc_info=True)
    return {"error": "An error occurred"}  # Generic message
```

**Prevention**:
- Use generic error messages
- Log detailed errors server-side
- Don't expose stack traces
- Don't reveal system internals

### Missing Security Headers
**Pattern**: Not setting security headers

**Prevention**:
- Set Content-Security-Policy
- Set X-Frame-Options
- Set X-Content-Type-Options
- Set Strict-Transport-Security
- Set Referrer-Policy

## Broken Authentication

### Weak Password Requirements
**Pattern**: Allowing weak passwords

**Prevention**:
- Require minimum length (12+ characters)
- Require complexity (mixed case, numbers, symbols)
- Check against common password lists
- Implement password history

### Session Fixation
**Pattern**: Not regenerating session ID after login

**Vulnerable Code**:
```python
session['user_id'] = user.id  # Same session ID
```

**Secure Code**:
```python
session.regenerate()
session['user_id'] = user.id  # New session ID
```

**Prevention**:
- Regenerate session ID after login
- Regenerate after privilege changes
- Use secure session management
- Set appropriate timeouts

### Insecure Password Storage
**Pattern**: Storing passwords in plain text or weak hashing

**Vulnerable Code**:
```python
password_hash = md5(password)  # Weak and deprecated
```

**Secure Code**:
```python
password_hash = bcrypt.hashpw(password, bcrypt.gensalt())
```

**Prevention**:
- Use strong hashing (bcrypt, Argon2, PBKDF2)
- Never store plain text passwords
- Use salt for all hashes
- Use appropriate work factors

## Sensitive Data Exposure

### Insecure Transmission
**Pattern**: Sending sensitive data over HTTP

**Prevention**:
- Use HTTPS for all sensitive data
- Enforce HTTPS (HSTS)
- Use secure protocols (TLS 1.2+)
- Validate certificates

### Insecure Storage
**Pattern**: Storing sensitive data without encryption

**Prevention**:
- Encrypt sensitive data at rest
- Use strong encryption (AES-256)
- Secure key management
- Don't store unnecessary sensitive data

### Insecure Logging
**Pattern**: Logging sensitive information

**Vulnerable Code**:
```python
logger.info(f"User login: {username}, password: {password}")
```

**Secure Code**:
```python
logger.info(f"User login: {username}")  # Never log passwords
```

**Prevention**:
- Don't log passwords, tokens, or secrets
- Mask sensitive data in logs
- Use data classification
- Implement log access controls

## XML External Entity (XXE)

**Pattern**: Processing XML with external entity references

**Vulnerable Code**:
```python
tree = ET.parse(xml_string)  # Processes external entities
```

**Secure Code**:
```python
parser = ET.XMLParser()
parser.entity = {}  # Disable external entities
tree = ET.parse(xml_string, parser=parser)
```

**Prevention**:
- Disable external entity processing
- Use simpler data formats (JSON)
- Validate XML schemas
- Use whitelist for XML parsers

## Insecure Deserialization

**Pattern**: Deserializing untrusted data

**Vulnerable Code**:
```python
data = pickle.loads(user_input)  # Dangerous!
```

**Secure Code**:
```python
data = json.loads(user_input)  # Safer format
# Or use signed serialization
```

**Prevention**:
- Avoid deserializing untrusted data
- Use safe serialization formats (JSON)
- Implement integrity checks
- Use digital signatures

## Using Components with Known Vulnerabilities

**Pattern**: Using outdated or vulnerable libraries

**Prevention**:
- Keep dependencies up to date
- Monitor for vulnerabilities
- Use dependency scanning tools
- Remove unused dependencies
- Use only trusted sources

## Insufficient Logging and Monitoring

**Pattern**: Not logging security events

**Prevention**:
- Log all authentication attempts
- Log all authorization failures
- Log all input validation failures
- Implement real-time monitoring
- Set up alerts for suspicious activity

## References

- [OWASP Top 10](https://owasp.org/Top10/)
- [CWE Top 25](https://cwe.mitre.org/top25/)
- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/)

