# Secure Coding Practices

Based on OWASP Secure Coding Practices, Top 10 Proactive Controls, and Developer Guide.

---

## Authentication & Password Management

### Core Requirements
- Require authentication for **all** pages/resources except explicitly public
- All auth controls enforced on **trusted system** (server-side)
- Use **standard, tested auth services** (OAuth, OIDC, identity providers)
- Centralize auth implementation — single component for all auth controls
- Segregate auth logic from resource; use redirection to centralized control
- All auth controls **fail securely** (deny by default)

### Password Handling
- Use **cryptographically strong, salted, one-way hashes** (bcrypt, scrypt, Argon2, PBKDF2)
- **Never MD5, SHA-1, SHA-256** for passwords — too fast
- Hashing on **trusted system (server-side)** only
- Validate auth data only after **complete input** (prevents timing attacks)
- Generic failure messages: "Invalid username and/or password" (not which part failed)

### Account Protection
- Enforce **password complexity + length** (min 16 chars or passphrases)
- Obscure password entry (`type="password"`)
- **Account lockout** after failed attempts (5 attempts, lock for deterring brute-force but not DoS)
- **Multi-Factor Authentication (MFA)** for high-value/sensitive accounts
- Re-authenticate before critical operations
- Password reset = same controls as account creation
- Reset links: pre-registered email only, short expiry, one-time use
- Notify users on password reset

### Session Management
- Secure token generation (≥128 bits entropy)
- **HttpOnly, Secure, SameSite=Strict/Lax** cookies
- Proper invalidation on logout/timeout
- Concurrent session limits + monitoring
- Rotate tokens periodically

---

## Access Control (Authorization)

### Principles
- **Single site-wide component** for authorization decisions
- Use **trusted system objects** (server-side sessions) for decisions
- Access controls **fail securely** (deny by default)
- Deny all if security config unavailable
- Enforce on **every request**, including server-side scripts
- Segregate privileged logic from application code

### Implementation
- **Server-side enforcement** — never trust client-side checks
- **Default deny** — explicit allow only
- **Prevent IDOR** (Insecure Direct Object References) — authorize every resource access
- Function-level controls for admin functions
- Role assignments cannot be manipulated by users
- Prevent privilege escalation (horizontal + vertical)
- Centralize access control logic
- Post-authentication authorization checks

### Least Privilege
- Each module/process gets minimum access needed
- Minimum time necessary
- Service accounts = least privilege possible

---

## Cryptographic Practices

### General Rules
- **Never implement your own crypto** — use vetted libraries (libsodium, Bouncy Castle, Web Crypto API)
- All crypto on **trusted system**
- Crypto modules **fail securely**
- Use **CSPRNG** for all randomness (numbers, filenames, UUIDs, strings)
- FIPS 140-2 compliant modules (or equivalent)
- Plan for **algorithm agility** — support changing algorithms

### Encryption
| Use Case | Algorithm |
|---|---|
| Symmetric (data at rest) | AES-256-GCM (preferred), AES-256-CBC + HMAC |
| Asymmetric (key exchange) | RSA-2048+, ECDSA P-256+, X25519 |
| Password hashing | Argon2id, bcrypt, scrypt, PBKDF2 (100k+ iterations) |
| TLS | TLS 1.2+ (prefer 1.3) |

### Key Management
- Store keys in **secrets vault** (HashiCorp Vault, AWS KMS, Azure Key Vault, GCP KMS)
- **Never in code, config files, or environment variables**
- Independent keys for different purposes
- Support **key rotation** (build features to handle it)
- Log all authorized key access for forensics
- Scan repos for accidentally committed secrets

### Data Protection
- **Classify data** by sensitivity level
- Avoid storing sensitive data when possible
- Encrypt sensitive data **at rest** and **in transit**
- No sensitive info in URLs/query strings (API keys, tokens)
- `Cache-Control: no-store` for sensitive pages
- `Referrer-Policy` to prevent leakage via Referer header

---

## Communication Security

- **TLS for all sensitive transmission** (including internal services)
- TLS certs: valid, correct domain, not expired, full chain
- **No fallback to insecure** on TLS failure
- TLS for all authenticated content + external systems with sensitive data
- Single standard TLS implementation, properly configured
- Specify character encodings for all connections
- Filter sensitive params from Referer when linking externally

---

## Input Validation & Output Encoding

### Validation
- Validate **all inputs** (client and server-side)
- **Allowlist** validation preferred over denylist
- Validate on **trusted system**
- Centralized validation routines
- Validate **after** decoding/normalization
- Reject invalid input (don't sanitize/mutate)

### Output Encoding
- Context-aware encoding (HTML, JS, CSS, URL, SQL)
- Use template engines with auto-escaping
- Never concatenate untrusted data into queries/commands

---

## Error Handling & Logging

### Error Handling
- **Fail securely** — errors don't leak stack traces, DB schema, config
- Generic error messages to users; detailed logs for debugging
- Don't expose which validation failed (e.g., "invalid field" not "email invalid")

### Logging
- **No sensitive data in logs** (passwords, tokens, PII, keys)
- Log security events: auth failures, access violations, input validation failures
- Structured logging (JSON) for SIEM integration
- Audit trail for privileged operations

---

## API Security (REST/gRPC)

### REST
- **HTTPS only** — no HTTP endpoints
- Access control at **each endpoint**
- Local authorization decisions (minimize latency/coupling)
- Centralized auth via Identity Provider (IdP) issuing access tokens
- Prevent IDOR — authorize every resource access
- Rate limiting per client/IP

### General
- Validate Content-Type
- Implement CORS properly (restrict origins)
- Security headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options
- API versioning in URL or header

---

## OWASP Top 10 (2021) — Quick Reference

| # | Category | Key Mitigations |
|---|---|---|
| **A01** | Broken Access Control | Deny by default, server-side enforcement, test authorization |
| **A02** | Cryptographic Failures | Encrypt in transit/at rest, strong algorithms, key management |
| **A03** | Injection | Parameterized queries, input validation, ORMs, least privilege DB |
| **A04** | Insecure Design | Threat modeling, secure design patterns, security requirements |
| **A05** | Security Misconfiguration | Hardening, patching, least privilege, automated config scans |
| **A06** | Vulnerable/Outdated Components | Dependency scanning, SBOM, automated updates, vetted libraries |
| **A07** | Identification/Auth Failures | MFA, strong passwords, secure session mgmt, breach monitoring |
| **A08** | Software/Data Integrity Failures | CI/CD integrity, signed artifacts, provenance, review dependencies |
| **A09** | Security Logging/Monitoring Failures | Structured logs, alerting on anomalies, audit trails |
| **A10** | Server-Side Request Forgery (SSRF) | Allowlist URLs, deny by default, network segmentation, no raw user URLs |

---

## Secure Code Review Checklist

### Authentication & Session
- [ ] Strong hashing + salt
- [ ] Account lockout with thresholds
- [ ] Secure token generation (≥128 bits)
- [ ] Session invalidation on logout/timeout
- [ ] Re-auth for sensitive ops
- [ ] MFA for high-risk accounts
- [ ] Secure password reset (time-limited)
- [ ] HttpOnly, Secure, SameSite cookies
- [ ] Concurrent session limits

### Authorization
- [ ] Server-side enforcement
- [ ] Default deny
- [ ] IDOR prevention
- [ ] Admin functions protected
- [ ] Roles non-manipulable
- [ ] Privilege escalation prevented
- [ ] Centralized decisions

### Cryptography
- [ ] Modern algorithms (AES-256, RSA-2048+, ECDSA P-256+)
- [ ] Proper key gen/storage/rotation
- [ ] Cert validation + hostname verification
- [ ] CSPRNG for randomness
- [ ] Encryption at rest + in transit
- [ ] Proper IV/nonce handling
- [ ] Up-to-date crypto libraries

---

## Supply Chain Security

- **SBOM** (Software Bill of Materials) for every build
- **Dependency scanning** in CI (OWASP Dependency Check, Snyk, Dependabot)
- **Signed artifacts** — verify provenance (SLSA, Sigstore/cosign)
- **Pin dependencies** — lockfiles committed, no floating versions
- **Vet dependencies** — popularity, maintenance, license, security history
- **Private registry** — proxy/mirror public registries

---

## Related Notes

- [[Security/Authentication-Authorization]] — Deep dive on auth patterns
- [[Security/Cryptography]] — Encryption, hashing, key management details
- [[Security/API-Security]] — REST/gRPC, rate limiting, OAuth/OIDC
- [[Security/Supply-Chain-Security]] — SBOM, signing, dependency management
- [[DevOps/CI-CD-Best-Practices]] — Security in pipeline
- [[Patterns/Resilience-Patterns]] — Fail securely, circuit breakers

---

*Sources: OWASP Secure Coding Practices Quick Reference, OWASP Top 10 Proactive Controls, OWASP Developer Guide, OWASP Cheat Sheet Series (REST Security, Secure Code Review), NIST SSDF*