RecapsKayavak

Kayavak / Recaps / Security

Recaps · Volume 10

Security

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

106

Security Foundations

Key ideas

  • CIA triad: confidentiality, integrity, availability (+ authenticity, non-repudiation).
  • AAA: authentication (who), authorisation (what you may do), accounting/audit (what happened).
  • Risk = likelihood × impact; treat by reduce / accept / transfer / avoid.
  • Saltzer–Schroeder principles: economy of mechanism, fail-safe defaults, complete mediation, open design (no security by obscurity), least privilege, least common mechanism, psychological acceptability, separation of privilege.
  • Defence in depth: independent layers; blast-radius reduction.
  • Zero trust: no implicit trust from network location; authenticate and authorise every request on identity and device posture.
  • Secure by design: threat model early, eliminate bug classes (memory-safe languages, safe APIs), shift security left.

Numbers to remember

  • Lab: root could read a 640 root file and bind port 80; nobody could do neither; nobody + CAP_NET_BIND_SERVICE could bind only.
  • Five independent layers at 70/95/60/50/40% leave 0.18% through; the product rule needs independence.

Pitfalls

  • Running services as root "to make it work".
  • Security by obscurity instead of open, reviewed design.
  • Defence-in-depth layers that share a dependency, secret or assumption.
  • Treating modelled control percentages as measured assurance.
  • Authenticating but not authorising (or the reverse).

Glossary

  • Capability: a divisible piece of root's power (Linux CAP_*).
  • Trust boundary: where data or control crosses between parties of different privilege.
  • Blast radius: how much a single compromise can reach.
  • Complete mediation: every access is checked, every time.
  • Fail-safe default: deny unless explicitly allowed.

107

Cryptography Foundations

Key ideas

  • Don't invent crypto; use vetted libraries and high-level APIs (libsodium, Tink, cryptography, JCA with care).
  • Pick the tool by the question: hash (integrity), MAC (shared-key authenticity), signature (public verifiability, non-repudiation), AEAD (confidentiality + integrity), key exchange (agreeing keys), slow password hash (storing passwords).
  • Passwords: Argon2id (or bcrypt/scrypt), salted, parameters stored in the hash, rehash on login when you raise cost.
  • AEAD only for new code: AES-GCM or ChaCha20-Poly1305; bind context with associated data; never reuse a nonce under one key.
  • Randomness from the OS CSPRNG for every key, token, nonce and salt.
  • Hybrid: public-key crypto sets up keys; symmetric crypto moves data. Ephemeral ECDH gives forward secrecy.
  • TLS 1.3: ECDHE key exchange, certificate signature, AEAD record protection; verify the chain and the hostname.
  • Key management is the hard part: generate, store (KMS/HSM), rotate, revoke, and use envelope encryption.
  • Post-quantum: ML-KEM (FIPS 203) and ML-DSA (FIPS 204) are standardised; hybrid X25519+ML-KEM key exchange is deployed in browsers; plan crypto-agility now ("harvest now, decrypt later").

Numbers to remember

  • Lab: bcrypt cost 12 ≈ 278 ms; each cost step doubles; MD5 ≈ 448 ns per hash in Python, about 600,000× faster.
  • AES-GCM: 12-byte nonce, 16-byte tag; rotate keys well before 2³² random-nonce messages.
  • X25519 public key 32 bytes; Ed25519 signature 64 bytes; ECDSA P-256 ≈ 70–72 bytes DER.
  • RSA-2048 ≈ 112-bit security, RSA-3072 / P-256 ≈ 128-bit; AES-128 is 128-bit, AES-256 is the post-quantum-comfortable choice.
  • Lab: RSA-4096 sign 2.38 ms vs ECDSA P-256 0.05 ms.

Pitfalls

  • Fast hashes (MD5, SHA-256 alone) for passwords; unsalted hashes.
  • ECB or CBC without a MAC; "encrypt then forget to authenticate".
  • Reusing nonces or IVs; hard-coded keys in source or images.
  • random/Math.random for tokens.
  • Disabling TLS verification "temporarily"; checking the chain but not the hostname.
  • Comparing MACs with == (timing leak); use constant-time compare.
  • Using one key for several purposes instead of deriving separate keys with HKDF.

Glossary

  • AEAD: authenticated encryption with associated data.
  • Nonce: number used once per key.
  • KDF: key derivation function (HKDF for keys, Argon2id for passwords).
  • Forward secrecy: a stolen long-term key doesn't decrypt past sessions.
  • Envelope encryption: data encrypted with a data key, data key encrypted with a master key in a KMS.
  • PKI: the CAs, certificates and revocation that bind public keys to names.

108

Web Application Security

Key ideas

  • Root cause: untrusted data interpreted as code; fix by separating channels or encoding for context.
  • Injection (SQL, NoSQL, OS command, LDAP, template): parameterise; never build commands by string; pass argument lists.
  • XSS: auto-escaping templates by context; sanitise HTML only with a vetted library; CSP with nonces as a second layer; HttpOnly cookies.
  • CSRF: SameSite cookies plus anti-CSRF tokens on state-changing requests; never change state on GET.
  • SSRF: allow-list destinations, resolve and block private/link-local ranges, disable redirects, use IMDSv2 in the cloud.
  • Path traversal: canonicalise then check, or look files up by ID.
  • Deserialisation/XXE: never deserialise untrusted native objects; disable external entities in XML parsers.
  • Access control (Top 10's #1 category): check authorisation on every request, server-side, per object.
  • Headers: CSP, HSTS, nosniff, Referrer-Policy, frame-ancestors; strict CORS.

Numbers to remember

  • OWASP Top 10:2025 lists Broken Access Control first.
  • HSTS commonly max-age=31536000 (one year); preload requires includeSubDomains and preload.
  • Lab: one CSP header turned "inline script RAN" into "did not run" with a console violation.

Pitfalls

  • Blacklist filters ("strip <script>") instead of encoding.
  • Escaping for the wrong context (HTML-escaping inside a JavaScript string or URL).
  • CSP with 'unsafe-inline'; CORS reflecting any Origin with credentials.
  • Checking .. in the raw string instead of the resolved path.
  • nginx add_header in a location silently dropping inherited headers.
  • Trusting client-side validation.

Glossary

  • XSS: script injected into a page another user views.
  • CSRF: a forged cross-site request riding the victim's cookies.
  • SSRF: making the server fetch a URL of the attacker's choice.
  • CSP: browser policy restricting where scripts and other resources load from.
  • Canonicalisation: reducing a path or input to its single standard form before checking it.

109

Identity and Access

Key ideas

  • Authentication ≠ authorisation; check both, server-side, on every request.
  • Factors: something you know, have, are; passkeys (WebAuthn) are phishing-resistant because the credential is bound to the origin.
  • Sessions: random server-side IDs in HttpOnly, Secure, SameSite cookies; rotate on login; expire idle and absolute.
  • OAuth 2: authorisation code + PKCE for users, client credentials for services, device flow for TVs/CLIs, token exchange for delegation. OIDC adds the ID token and user identity.
  • JWT validation: signature, fixed algorithms, exp/nbf, iss, aud; keys from JWKS by kid.
  • Tokens: short-lived access tokens, rotating refresh tokens, sender-constrained (DPoP, mTLS) where theft matters.
  • Models: RBAC (roles), ABAC (attributes and conditions), ReBAC (relationships); policy engines OPA, Cedar, OpenFGA.
  • Workload identity: short-lived credentials from the platform (SPIFFE, cloud IAM roles), no long-lived secrets.

Numbers to remember

  • Lab: 7-row validation matrix, 1 accept and 6 rejects, each with a distinct error.
  • PKCE verifier 43–128 characters; challenge = BASE64URL(SHA-256(verifier)).
  • Access-token lifetimes are typically minutes (5–60), refresh tokens hours to days with rotation.
  • OWASP API Security Top 10 (2023): API1 is Broken Object Level Authorisation.

Pitfalls

  • Decoding a JWT without verifying it, or trusting its alg header.
  • Skipping aud, so tokens for one service open another.
  • Storing tokens in localStorage where any XSS can read them.
  • Authorising by role but never by object ownership (BOLA).
  • Long-lived API keys and service-account keys in repos.
  • Revocation assumed for JWTs that are valid until exp.

Glossary

  • IdP: identity provider issuing tokens.
  • Scope: what a token permits (e.g. orders:read).
  • PKCE: proof key binding an authorisation code to the client that requested it.
  • JWKS: the issuer's published set of public keys.
  • BOLA / IDOR: accessing another user's object by changing its identifier.
  • DPoP: proof-of-possession binding a token to a client key.

110

API Security

Key ideas

  • OWASP API Top 10 (2023): BOLA, broken authentication, broken object property level authorisation, unrestricted resource consumption, broken function level authorisation, unrestricted access to sensitive business flows, SSRF, misconfiguration, improper inventory, unsafe consumption of third-party APIs.
  • Authenticate with OAuth tokens or mTLS; API keys identify clients but are weak secrets on their own. Sign requests (SigV4, RFC 9421) where integrity matters.
  • Authorise every object and every property (what a caller may read and write).
  • Validate strictly: explicit input models, unknown fields rejected, types and ranges enforced, size limits.
  • Limit consumption: per-identity rate limits, quotas, pagination caps, timeouts, query cost limits for GraphQL.
  • Integrity and freshness: HMAC or signatures over timestamp + nonce + raw body; idempotency keys for retries.
  • Gateways centralise authentication, limits and logging, but services still authorise objects themselves.
  • Inventory: know every API and version you expose; retire old ones.

Numbers to remember

  • Lab: 5 r/s with burst 10 let 21 of 40 requests through over 2.1 s; the second key was untouched.
  • Typical webhook freshness window: 5 minutes; idempotency keys kept around 24 hours.
  • 429 Too Many Requests with Retry-After; 422 for validation failures.

Pitfalls

  • Rate-limit config that never runs (nginx return before limit_req); always test that a control fires.
  • Keying limits on a client-chosen header.
  • Binding request bodies onto entities (mass assignment); returning whole entities (excessive data exposure).
  • Verifying webhook signatures on re-serialised JSON instead of the raw body.
  • GraphQL without depth/cost limits; introspection open in production.
  • Forgotten old API versions with weaker checks.

Glossary

  • BOPLA: broken object property level authorisation (reading or writing fields you shouldn't).
  • Token bucket: rate limiter that refills at a fixed rate up to a burst capacity.
  • Replay attack: resending a captured valid request.
  • Idempotency key: client-chosen ID making a request safe to retry.
  • mTLS: both client and server present certificates.

111

Container, Kubernetes and Cloud Security

Key ideas

  • 4C model: cloud, cluster, container, code; each layer relies on the one below.
  • Images: minimal or distroless, pinned by digest, scanned, rebuilt often, signed, verified at admission.
  • Runtime hardening: non-root (with runAsGroup), drop ALL capabilities, read-only root, no privilege escalation, seccomp RuntimeDefault, resource limits; user namespaces where available.
  • Pod Security Standards: privileged, baseline, restricted; enforced per namespace by Pod Security Admission; policy engines (Kyverno, Gatekeeper, ValidatingAdmissionPolicy) for custom rules.
  • RBAC: least-privilege Roles, no wildcards, watch secrets/exec/create-pods/escalate/bind/impersonate; disable token automount where unused.
  • Network: default-deny ingress and egress, explicit allows, mTLS via a mesh for identity between services.
  • Secrets: external secret stores or encrypted-at-rest etcd; never in images or env dumps; short-lived workload identity instead of static cloud keys.
  • Runtime detection: Falco, Tetragon (eBPF) for unexpected shells, network calls, file writes.
  • Cloud posture: guardrails (SCPs, org policies), CSPM, central audit logs, block public storage by default.

Numbers to remember

  • Docker default: 14 capabilities (CapEff a80425fb); hardened: 0.
  • Lab: one privileged pod spec produced six Pod Security violations.
  • Lab: default-deny + one allow left exactly one client able to reach web.

Pitfalls

  • Treating containers as a hard security boundary; root in a container is root on the kernel.
  • runAsUser without runAsGroup; privileged: true "for debugging" left in.
  • NetworkPolicies on a CNI that doesn't enforce them.
  • Wildcard RBAC and cluster-admin for CI.
  • Static cloud keys in Kubernetes Secrets instead of workload identity.
  • Mounting the Docker socket or host paths into pods.

Glossary

  • Capability: a slice of root's power.
  • seccomp: system-call filter for a process.
  • Admission controller: API-server hook that can reject or modify objects on create.
  • CSPM: cloud security posture management.
  • Workload identity: short-lived cloud credentials bound to a pod's service account.

112

Software Supply Chain Security

Key ideas

  • Attack types: compromised build (SolarWinds), compromised CI secret (Codecov), long-con maintainer takeover (xz-utils, 2024), hijacked package (event-stream), typosquatting, dependency confusion, malicious CI actions.
  • Know what you run: SBOMs (SPDX, CycloneDX) generated at build time, with purls.
  • Know what's vulnerable: continuous scanning (pip-audit, npm audit, govulncheck, Grype, Trivy, OSV-Scanner), triage by reachability, VEX for decisions, automated upgrades.
  • Get exactly what you meant: lockfiles with hashes; scoped/private registries to stop dependency confusion; pin CI actions by commit SHA.
  • Know who built it: signatures (Sigstore keyless: Fulcio, Rekor, cosign), provenance attestations (in-toto), SLSA build levels, admission-time verification.
  • Trust the build: hardened, ephemeral, isolated builders; least-privilege CI tokens; reproducible builds for independent verification.

Numbers to remember

  • Lab: 3 old pins → 22 advisories across 4 packages; all fixed by upgrading.
  • Lab: one changed hex digit stopped the install; one changed byte failed signature verification.
  • SLSA v1.0 build track levels: L1 provenance exists, L2 signed provenance from a hosted builder, L3 hardened, isolated builder.

Pitfalls

  • Version pins without hashes; floating tags (latest, v1) for images and actions.
  • Scanning once and never again; ignoring transitive dependencies.
  • Treating a signature as proof of safety rather than of origin.
  • Long-lived signing keys and publish tokens on developer laptops.
  • Internal package names that also resolve on public registries.
  • Builds that can't be reproduced, so a tampered builder goes unnoticed.

Glossary

  • purl: package URL identifying a component across ecosystems.
  • VEX: statement of whether a product is actually affected by a vulnerability.
  • Provenance: a signed record of how, where and from what an artefact was built.
  • SLSA: Supply-chain Levels for Software Artifacts.
  • Transparency log: append-only public log of signatures (Rekor).
  • Dependency confusion: a public package shadowing a private one with the same name.

113

Threat Modelling

Key ideas

  • Four questions (Shostack): what are we working on, what can go wrong, what will we do about it, did we do a good job.
  • DFD: external entities, processes, data stores, data flows, trust boundaries.
  • STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege; apply per element and per boundary-crossing flow.
  • Other lenses: attack trees (attacker goals decomposed), abuse/misuse cases, LINDDUN for privacy, PASTA for risk-centric analysis, kill chains for operations.
  • Responses: mitigate, eliminate, transfer, accept (owner, reason, review date).
  • Rating: likelihood × impact, or DREAD/CVSS-style scores; consistency matters more than precision.
  • LLM and agent systems: prompt injection through any text the model reads, excessive agency (tools), data exfiltration through outputs, insecure output handling.
  • Lightweight practice: small models per feature, in the design review, kept in the repo as code or diagrams, revisited when the design changes.

Numbers to remember

  • Lab: pytm produced 119 candidate threats with no controls declared and 50 with controls declared.
  • STRIDE has 6 categories; a DFD has 4 element types plus trust boundaries.

Pitfalls

  • A one-off document for an audit, never updated.
  • Modelling the whole company at once instead of one feature.
  • Treating tool output as the model; or ignoring it entirely.
  • Listing threats without responses, owners or tests.
  • Forgetting external systems (payment providers, LLM APIs) and the data they return.

Glossary

  • Trust boundary: where privilege or ownership changes along a flow.
  • Attack tree: a goal decomposed into AND/OR sub-goals.
  • Abuse case: a user story written from the attacker's side.
  • LINDDUN: linking, identifying, non-repudiation, detecting, data disclosure, unawareness, non-compliance (privacy threats).
  • Residual risk: what remains after mitigations.