# OWASP A07:2021 - Credential and Authentication Security

**Source:** [OWASP Top 10:2021 - A07:2021 – Identification and Authentication Failures](https://owasp.org/Top10/2021/A07_2021-Identification_and_Authentication_Failures/)

**Authority Tier:** 1 (Clinical - Security/compliance standards from OWASP)

## Overview

**Risk Category:** A07:2021 – Identification and Authentication Failures

Previously known as "Broken Authentication," this category covers security failures related to user identity confirmation, authentication mechanisms, and session management. Authentication and credential management failures can lead to account takeover, identity theft, and unauthorized access to sensitive data.

## Credential Storage & Password Handling

### Plaintext and Weak Encryption

**Prohibited:** "Uses plain text, encrypted, or weakly hashed passwords data stores"

Applications must implement strong hashing mechanisms rather than storing credentials in plaintext or weak encryption. This includes:

- Connection strings with plaintext passwords
- Configuration files with unencrypted credentials
- Database tables storing unhashed passwords
- Log files containing credentials

### Hard-coded Credentials

**Requirement:** Eliminate all default credentials before deployment, especially administrative accounts.

**Prohibition:** Remove any embedded passwords or secrets from:
- Application source code
- Configuration files committed to version control
- Build artifacts and container images
- Infrastructure-as-code templates

### Best Practice: Environment Variables

Credentials should be:
- Stored in environment variables or secure credential stores
- Loaded at runtime from secure vaults (e.g., HashiCorp Vault, AWS Secrets Manager)
- Never hardcoded in connection strings
- Rotated regularly through automated processes

## Password Policy Standards

### Password Strength Requirements

**Requirement:** Test new or changed passwords "against the top 10,000 worst passwords list"

**Standards Alignment:** Align policies with NIST 800-63b guidelines emphasizing memorized secrets standards.

### Deprecated Policies

**Avoid:** Password rotation and complexity requirements that encourage weak reuse patterns

Modern password policy focuses on:
- Length over complexity
- Passphrase support
- Eliminating forced periodic changes
- Preventing credential stuffing through breach detection

## Authentication Security Practices

### Multi-factor Authentication (MFA)

**Requirement:** Implement MFA to prevent:
- Credential stuffing attacks
- Brute force attacks
- Stolen credential reuse

MFA should be enforced for:
- Administrative accounts (mandatory)
- High-value user accounts
- Access from untrusted networks

### Session Management

**Requirements for secure session handling:**

1. **Session ID Generation:** Generate new random session IDs with high entropy after successful login
2. **URL Safety:** Session identifiers should never appear in URLs
3. **Session Invalidation:** Invalidate sessions after:
   - Logout (user-initiated)
   - Idle timeout (inactivity period)
   - Absolute timeout (maximum session duration)
4. **Session Fixation Prevention:** Regenerate session identifiers upon authentication

## Attack Prevention

### Rate Limiting

**Requirement:** Implement rate limiting on failed login attempts without creating denial-of-service exposure

Best practices:
- Limit failed attempts per account (e.g., 5-10 attempts before temporary lockout)
- Implement progressive delays (exponential backoff)
- Use CAPTCHA after threshold violations
- Avoid permanent account lockout (DoS risk)

### Account Enumeration Prevention

**Requirement:** Use identical error messages for all authentication outcomes to prevent account enumeration

**Implementation:**
- Same response time for valid/invalid usernames
- Generic error messages ("Invalid credentials" vs "Invalid username")
- No differentiation in password reset flows

### Logging and Monitoring

**Requirement:** Log all authentication failures and alert administrators to potential attacks

**Essential logs:**
- Failed login attempts with username, IP, timestamp
- Successful logins from new locations/devices
- Password reset requests
- Account lockouts
- MFA failures

## Connection String Security

### PostgreSQL Connection Strings

**Insecure (Prohibited):**
```
postgresql://username:password123@localhost:5432/mydb
```

**Secure (Required):**
```rust
// Load from environment
let password = env::var("DB_PASSWORD").expect("DB_PASSWORD not set");
let connection_string = format!("postgresql://{}:{}@{}/{}",
    username, password, host, database);
```

### Best Practices

1. **NEVER commit credentials to version control**
2. **Use environment variables for all credentials**
3. **Implement credential rotation** (e.g., 90-day password rotation)
4. **Use connection pooling with encrypted connections** (SSL/TLS)
5. **Encrypt credentials at rest** in configuration management systems
6. **Audit credential access** through logging and monitoring

## Prescriptive Statements for Claims

1. **MUST NOT store plaintext passwords:** Connection strings, configuration files, and data stores must not contain plaintext passwords
2. **MUST use strong hashing:** Passwords must be hashed using strong algorithms (bcrypt, Argon2, scrypt)
3. **MUST NOT hardcode credentials:** Application code must not contain hardcoded passwords or API keys
4. **MUST load credentials from environment:** Credentials must be loaded from environment variables or secure vaults at runtime
5. **MUST implement MFA:** Administrative and high-value accounts must require multi-factor authentication
6. **MUST regenerate session IDs:** Session identifiers must be regenerated after successful authentication
7. **MUST implement rate limiting:** Authentication endpoints must implement rate limiting to prevent brute force attacks
8. **MUST use identical error messages:** Authentication failures must not reveal whether username or password was incorrect
9. **MUST log authentication events:** All authentication failures and security events must be logged
10. **MUST validate password strength:** New passwords must be checked against common password lists
11. **MUST invalidate sessions:** Sessions must be invalidated on logout, idle timeout, and absolute timeout
12. **MUST NOT expose session IDs in URLs:** Session identifiers must never appear in URLs or GET parameters
13. **MUST use secure connection encryption:** Database connections must use SSL/TLS encryption
14. **SHOULD rotate credentials regularly:** Database credentials should be rotated on a regular schedule (e.g., 90 days)

## Consequences of Violations

### Plaintext Password Exposure

**Impact:** Credential theft through:
- Source code leaks
- Log file exposure
- Configuration file disclosure
- Memory dumps

**Severity:** Critical - enables complete account takeover

### Hardcoded Credentials

**Impact:**
- Credentials exposed in version control history
- Cannot rotate without code changes
- Spreads across multiple deployments
- Discoverable through static analysis

**Severity:** High - enables persistent unauthorized access

### Missing Rate Limiting

**Impact:**
- Brute force attacks succeed
- Credential stuffing attacks at scale
- Account enumeration
- Denial of service through lockouts

**Severity:** High - enables automated credential compromise

### Session Fixation

**Impact:**
- Attacker can hijack authenticated sessions
- Bypasses authentication entirely
- Enables privilege escalation

**Severity:** High - complete authentication bypass
