Security — Basics
Security — Basics
Section titled “Security — Basics”OWASP Top 10 (2021 → still authoritative for backend, refreshed 2024-2025)
Section titled “OWASP Top 10 (2021 → still authoritative for backend, refreshed 2024-2025)”- Broken Access Control — IDOR, missing authz checks, path traversal.
- Cryptographic Failures — sensitive data in plaintext, weak/wrong crypto, no TLS.
- Injection — SQL, NoSQL, LDAP, command, server-side template, log.
- Insecure Design — flawed model not patchable in code (e.g., insecure password reset flow).
- Security Misconfiguration — defaults left on, verbose errors, open S3 bucket, exposed admin.
- Vulnerable & Outdated Components — known CVEs in deps.
- Identification & Authentication Failures — weak passwords, broken session mgmt.
- Software & Data Integrity Failures — unsigned packages, insecure deserialization, supply chain.
- Logging & Monitoring Failures — no detection of breach.
- Server-Side Request Forgery (SSRF) — server fetches attacker URL (e.g., metadata endpoint).
OWASP API Security Top 10 (more relevant for backend):
- BOLA (Broken Object Level Auth — IDOR), Broken Auth, BOPLA (Property-Level Auth), Resource consumption, BFLA (Function-Level Auth), Server-Side Forgeries, Misconfig, Inventory mgmt, Unsafe consumption of APIs.
Authentication
Section titled “Authentication”Verify who the user is. Methods:
- Password + storage rules (bcrypt/argon2id with strong cost; salt is automatic).
- MFA (TOTP, WebAuthn, SMS — SMS weakest).
- OAuth 2.0 / OIDC — delegate to IdP (Google, Auth0, Cognito).
- API keys — long, opaque; rotated; per-tenant; logged.
- mTLS — for service-to-service.
- WebAuthn / passkeys — phishing-resistant.
Authorization
Section titled “Authorization”Decide what the authenticated user can do.
Models:
- RBAC (Role-Based) — user has roles, role has permissions.
- ABAC (Attribute-Based) — policy considers attrs of user + resource + env.
- ReBAC (Relationship-Based) — Zanzibar/SpiceDB style for “Alice can edit Bob’s doc shared with team X”.
- Scopes (OAuth) — coarse capabilities tokens carry.
Always verify on the server side at the access point, not via client checks.
OAuth 2.0 essentials
Section titled “OAuth 2.0 essentials”- Resource Owner (user), Client (app), Authorization Server (issues tokens), Resource Server (API).
- Grants (flows):
- Authorization Code + PKCE — use this for almost everything (web, mobile, SPA).
- Client Credentials — service-to-service.
- Refresh Token — get new access token.
- Implicit, Password — deprecated.
- OIDC is OAuth + identity (
id_tokenJWT,userinfoendpoint).
JSON Web Token — signed, base64url-encoded header.payload.signature.
Pros: stateless verification, embeds claims (sub, iss, aud, exp, iat).
Cons: can’t revoke without extra mechanism (denylist or short TTL + refresh), bloats every request.
Critical:
- Use short-lived access tokens (5-15 min) + rotating refresh tokens.
- Validate
alg(rejectnone!),iss,aud,exp. Don’t trust unverified. - Don’t put PII or secrets in payload — anyone with the token reads it.
- Sign with RS256/ES256 (asymmetric) for distributed verification, or HS256 (symmetric) within a single trust boundary.
Cookies / sessions
Section titled “Cookies / sessions”- Server-side session store (DB/Redis) → cookie holds session id. Easier to revoke than JWT.
- Cookie flags:
HttpOnly— JS can’t read.Secure— HTTPS only.SameSite=Lax(default) /Strict/None.Path,Domain,Max-Age/Expires.
- Rotate session id on login (prevent fixation).
Common attacks & mitigations
Section titled “Common attacks & mitigations”- SQL injection — parameterized queries, never string concat.
- NoSQL injection — same idea, validate types in queries.
- XSS — escape on output, CSP,
HttpOnlycookies, framework escaping. - CSRF —
SameSitecookies, anti-CSRF token, double-submit cookie. - SSRF — block private IP ranges, deny redirects to internal, allowlist domains.
- XXE (XML) — disable external entities.
- Open redirect — validate redirect targets against allowlist.
- Mass assignment — explicit allow-list of update fields.
- IDOR — check authz on every resource access by id.
- Brute force — rate limit + account lockout / exponential delay + CAPTCHA.
- Replay — nonces, timestamps, short-lived tokens.
Crypto
Section titled “Crypto”- Don’t roll your own.
- At rest: AES-GCM 256, with KMS-managed keys (AWS KMS, GCP KMS, Vault Transit).
- In transit: TLS 1.2+ (1.3 preferred). HSTS. Modern ciphers only.
- Passwords: argon2id (preferred), bcrypt (acceptable). Never SHA/MD5.
- Hashing for integrity: SHA-256+. HMAC for keyed hashing.
- Random:
crypto.randomBytes,secrets(Python),crypto/rand(Go). NeverMath.random. - Key rotation: routine, with backwards compatibility window.
Secrets management
Section titled “Secrets management”- Never in code, env files committed, logs, or error reports.
- Stores: HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager, Doppler, 1Password Secrets.
- Inject via env at runtime; tools to scan repos: gitleaks, trufflehog.
- Rotate periodically; on suspicion, immediately.
Defense in depth
Section titled “Defense in depth”Multiple layers — assume any single layer fails:
- Network: VPC, security groups, firewall, WAF.
- Auth: MFA, short tokens, rate-limit, anomaly detection.
- App: input validation, output encoding, prepared statements.
- Data: encrypt at rest, least privilege DB user, audit logs.
- Build: SBOM, signed artifacts, image scanning.
- Runtime: limited container caps, read-only fs, non-root user.
Compliance & standards
Section titled “Compliance & standards”- PCI-DSS — payments.
- HIPAA — US healthcare.
- GDPR — EU privacy.
- SOC 2 — controls audit.
- ISO 27001 — ISMS.
Security testing
Section titled “Security testing”- SAST — code scan (Semgrep, SonarQube, CodeQL).
- DAST — running app scan (OWASP ZAP, Burp).
- SCA — dependency CVE scan (Snyk, Dependabot, Trivy).
- Container scan — Trivy, Grype, Clair.
- Pen test — periodic external.
- Bug bounty — incentivize responsible disclosure.