Skip to content

Security Fundamentals for System Design

Intermediate 60 min read Part 13 of 18

Keep data safe: encryption, hashing vs tokenization, password storage, secrets, certificates, WAF and DDoS, OWASP risks, least privilege and GDPR.

Summary#

Security in system design means protecting the confidentiality, integrity and availability of data and services against mistakes and attackers. Those three properties are called the CIA triad. You get them through layers, not through one wall. The main tools:

  • Encryption. Encrypt data in transit (TLS everywhere, including inside the data centre) and at rest (disk, database and field-level, with keys managed by a KMS through envelope encryption).
  • The right transformation for the job. Encoding is for format, encryption is for confidentiality, hashing is for integrity and passwords, and tokenization replaces sensitive values with stand-ins.
  • Password storage with slow, salted hashes: Argon2id, scrypt or bcrypt.
  • Secrets management. Keep secrets out of code, in Vault, a KMS or a cloud secrets manager, rotate them, and prefer short-lived credentials.
  • Digital signatures and certificates to prove who sent something, and that it wasn't changed.
  • Network defences: firewalls, security groups, a WAF, and DDoS protection at the edge.
  • Defences against the common application flaws (OWASP): injection, XSS, CSRF and SSRF.
  • Least privilege for people, services and networks.
  • An API security checklist applied to every endpoint.
  • Privacy and compliance basics: minimise personal data (PII), know where it lives, and honour rights such as erasure under the GDPR.

Why It Exists#

Breaches are rarely the result of exotic cryptographic attacks. They come from unpatched software, leaked credentials, misconfigured storage, injection bugs, over-privileged accounts, and missing authorization checks. Each of those is a design failure as much as a coding one. For example:

  • the bucket was public by default;
  • the service account could read every table;
  • the internal API trusted anything on the network;
  • the logs contained card numbers.

Security also has a cost asymmetry. The defender must protect every path, while the attacker needs only one. That's why the core idea is defence in depth: independent layers, each assuming the others might fail. A SQL injection bug should hit a database user that can only read one schema. A stolen laptop should hold only encrypted disks and short-lived tokens. A compromised container should find mTLS, network policies and no standing credentials.

A useful habit is threat modelling: for each component, ask what could go wrong. STRIDE, a mnemonic from Microsoft, lists the classes of threat, and the property each one breaks.

ThreatProperty brokenTypical defence
SpoofingAuthenticationStrong authentication
TamperingIntegritySignatures, MACs, TLS
RepudiationNon-repudiationAudit logs, signatures
Information disclosureConfidentialityEncryption, access control
Denial of serviceAvailabilityRate limits, DDoS protection
Elevation of privilegeAuthorizationLeast privilege, input validation

Walking a data-flow diagram with STRIDE takes an hour, and it finds most design-level gaps before they ship.

How It Works#

Encryption in transit#

Encryption in transit protects data as it moves between machines: browser to load balancer, service to service, application to database, region to region. Without it, anyone on the path can read and modify traffic: a coffee-shop Wi-Fi operator, a compromised router, a cloud neighbour on a misconfigured network, an internet service provider.

The standard tool is TLS (Transport Layer Security; "SSL" is its obsolete predecessor). TLS gives three guarantees.

  • Confidentiality: the traffic is encrypted.
  • Integrity: tampering is detected.
  • Server authentication: the client verifies a certificate proving the server owns the domain name.

HTTPS is HTTP over TLS. HTTP and HTTPS covers the protocol side.

TLS combines two kinds of cryptography.

  • Asymmetric (public-key) cryptography: a key pair, where what one key does only the other can undo. Examples are ECDHE for key exchange, and RSA or ECDSA for signatures. It is slow, so it's used only during the handshake, to authenticate the server and agree a shared secret.
  • Symmetric cryptography: one shared key encrypts and decrypts. Examples are AES-GCM and ChaCha20-Poly1305. It is fast (gigabytes per second per core, with AES hardware instructions), and it encrypts the actual data.

Where TLS should run:

  • At the edge: HTTPS for every public endpoint, and HTTP redirected to HTTPS. Send HSTS (HTTP Strict Transport Security), so browsers refuse plain HTTP to your domain in future.
  • Inside the system: service-to-service traffic should be encrypted too. Usually this is mTLS through a service mesh, which also authenticates each service (Authentication and Authorization). "The internal network is trusted" is the assumption most lateral-movement attacks exploit.
  • To databases, caches and brokers: enable TLS on PostgreSQL, MySQL, Redis, Kafka and the rest, and verify server certificates. Don't just turn encryption on without verification, because an unverified TLS connection can still be intercepted.
  • Between regions and to partners: TLS, or VPN tunnels and private interconnects. Cloud providers encrypt some backbone traffic themselves, but don't depend on what you can't verify.

TLS termination points matter. A load balancer or CDN that terminates TLS sees plaintext. You can re-encrypt from there to the backends (end-to-end TLS), or pass TCP through to the backends (TLS passthrough) when the edge must not see the content. Each termination point is a place where keys live, and where data is briefly in the clear.

Encryption in transit, in depth: the TLS 1.3 handshake, forward secrecy and pitfalls#

TLS 1.3 (RFC 8446, 2018) cut the handshake to one round trip, and removed weak options. The flow:

  1. ClientHello: the client sends supported cipher suites, and a key share: an ephemeral elliptic-curve Diffie-Hellman public value, such as X25519. It names the server it wants with SNI.
  2. ServerHello: the server picks a suite, and sends its own ephemeral key share. Both sides can now compute the same shared secret through Diffie-Hellman, without ever sending it. From here on, everything is encrypted.
  3. The server sends its certificate, plus a CertificateVerify signature over the handshake transcript, made with its private key. That proves it holds the key in the certificate. It then sends Finished.
  4. The client validates the certificate chain against trusted root CAs, checks the hostname, verifies the signature, and sends Finished. Application data then flows.

Forward secrecy. Key exchange uses ephemeral keys, new for every connection, and the server's long-term key only signs. So recording traffic today and stealing the server's private key tomorrow doesn't let an attacker decrypt the recorded sessions. TLS 1.2 with RSA key exchange lacked this property, and TLS 1.3 makes forward secrecy mandatory.

Resumption and 0-RTT. Returning clients can resume with a pre-shared key, and even send 0-RTT early data with their first flight. Early data can be replayed by an attacker, though, so allow it only for idempotent requests, such as GETs without side effects.

Costs. A full handshake costs one round trip, plus a little CPU: an ECDHE computation and one signature, about a millisecond or less on modern servers. Bulk encryption with AES-GCM is nearly free on CPUs with AES-NI. In practice, TLS's cost is the round trip on new connections. That is why connection reuse, keep-alive and HTTP/2 or HTTP/3 multiplexing matter more than cipher choices.

Ways TLS is undermined:

  • Skipped certificate verification in clients (verify=False, InsecureSkipVerify: true), which makes TLS trivially interceptable;
  • expired certificates taking down services. Automate renewal, and alert 30 days ahead;
  • downgrade or legacy protocols. Disable SSL 3.0, TLS 1.0 and TLS 1.1, and use TLS 1.2 with modern suites, or 1.3;
  • TLS-intercepting middleboxes, such as corporate proxies, which install their own root certificate on employee devices and decrypt traffic. HTTPS is "safe" only relative to the set of roots the client trusts;
  • private keys in plaintext on many servers. Centralise termination, or use HSMs or managed certificate services, such as AWS Certificate Manager, so keys aren't exportable.

Other secure channels. SSH authenticates servers by host keys, and users by keys or certificates. It uses the same building blocks: ephemeral key exchange, then symmetric encryption. VPNs (IPsec, WireGuard, TLS-based VPNs) encrypt whole network paths. Site-to-site VPNs connect networks, and remote-access VPNs connect users. Zero-trust access proxies increasingly replace user VPNs with per-application access.

Encryption at rest#

Encryption at rest protects stored data: disks, database files, backups, object storage, laptops. It defends against stolen or improperly disposed-of disks, leaked backups or snapshots, and someone with access to the storage layer who isn't supposed to read the data. It does not protect against an attacker who compromises the running application, or its credentials. The application decrypts data for legitimate use, so it decrypts it for the attacker too. Know which threat each layer addresses.

The layers, from broad to narrow:

  • Full-disk or volume encryption: cloud block storage (EBS, Persistent Disk), and LUKS or BitLocker. Data is encrypted transparently below the file system. It protects physical media, and it's free to turn on, often on by default.
  • Storage-service encryption: S3, GCS and managed databases encrypt objects and tables with keys managed by the provider, or by you through a KMS. It protects against storage-layer access. With customer-managed keys, revoking the key access makes the data unreadable.
  • Database transparent data encryption (TDE): the database encrypts its files and pages. It's similar in protection to volume encryption, but it's controlled by the database.
  • Application-level or field-level encryption: the application encrypts specific fields before storing them (government ID numbers, bank details, health data), using keys the database never sees. Database administrators, backups and SQL injection then see only ciphertext. The cost is that you can't easily query or index encrypted fields. Use deterministic encryption or blind indexes (an HMAC of the value) for equality lookups.
  • Client-side or end-to-end encryption: data is encrypted on the user's device, and the service never holds the keys. Messaging apps using the Signal protocol work this way, as do password managers and some backup products. This is the strongest option, but it limits server-side features: search, recovery, moderation.

Envelope encryption is how keys are managed at scale.

  1. Each object or record is encrypted with its own data encryption key (DEK), a random AES-256 key.
  2. The DEK itself is encrypted (wrapped) by a key encryption key (KEK) that lives in a KMS (AWS KMS, Google Cloud KMS, Azure Key Vault) or an HSM, and never leaves it.
  3. You store the wrapped DEK next to the ciphertext. To decrypt, you ask the KMS to unwrap the DEK, which is checked against IAM and audited. You decrypt locally, and discard the plaintext DEK.

Encryption at rest, in depth: envelope encryption, rotation and crypto-shredding#

Why envelopes? A KMS can't encrypt terabytes of data itself. Requests are rate-limited, typically to thousands or tens of thousands per second per account, and each costs a network call. Envelope encryption sends only the 32-byte DEK to the KMS. Bulk encryption happens locally at memory speed. DEKs can also be cached for a short time, minutes, and for a bounded number of uses, which cuts KMS calls further.

Key hierarchy and blast radius. Use separate KEKs per environment, per service, and per tenant for B2B. Then IAM policies on the KMS key limit who can decrypt what. A compromised analytics service with no kms:Decrypt permission on the payments key can't read payment data even if it reads the database.

Rotation.

  • Rotating the KEK is cheap. The KMS keeps old key versions for decryption, and wraps new DEKs with the new version. Old wrapped DEKs can be rewrapped lazily.
  • Rotating DEKs means re-encrypting data. Do it on a schedule for high-value data, or whenever compromise is suspected.

Record the key ID and version with every ciphertext, so decryption knows which key to use.

Crypto-shredding. To delete data you can't easily reach, such as copies in backups, logs and replicas, encrypt each user's or tenant's data with its own key, and destroy the key. Every copy becomes unreadable at once. This is a practical way to honour erasure requests across immutable backups.

Authenticated encryption. Always use AEAD modes (AES-GCM, ChaCha20-Poly1305), which detect tampering, and never ECB or unauthenticated CBC. Never reuse a nonce with the same key in GCM, because reuse can reveal the authentication key, and the XOR of the plaintexts. Use the associated data field to bind ciphertext to its context, such as the record ID or tenant ID. Then an attacker can't move encrypted values between rows.

HSMs. Hardware security modules are tamper-resistant devices that generate and use keys without exposing them. Cloud KMS services are backed by HSMs, and dedicated cloud HSMs (AWS CloudHSM, Azure Dedicated HSM) exist when regulations require single-tenant control. Payment card processing and certificate authorities commonly require HSMs.

Encoding vs encryption vs hashing vs tokenization#

These four get confused constantly, and confusing them causes real breaches. The tell is usually Base64 called "encryption", or passwords encrypted when they should be hashed. They solve different problems.

TransformationPurposeReversible?Needs a key?ExamplesUse for
EncodingRepresent data in a different formatYes, by anyoneNoBase64, URL encoding, UTF-8, hexTransport and storage format, never secrecy
EncryptionConfidentialityYes, with the keyYesAES-GCM, ChaCha20, RSA-OAEPData that must be read back by authorised parties
HashingIntegrity, fingerprinting, password verificationNo (one-way)No; keyed variants (HMAC) use oneSHA-256, BLAKE3; Argon2 and bcrypt for passwordsChecksums, deduplication, passwords, content addressing
TokenizationRemove sensitive data from systemsOnly through the token vaultVault accessPayment card tokens, SSN tokensShrink compliance scope (PCI DSS), limit exposure
  • Encoding is about format. Base64 turns bytes into printable characters, so they survive JSON or email. Anyone can decode it. A JWT payload is Base64url-encoded, not encrypted. That's why you never put secrets in a JWT.
  • Encryption is reversible with a key. The security rests entirely on the key: who holds it, where it's stored, how it's rotated. Use encryption when the system must get the original value back, for example to show the last four digits of a bank account, to call a partner API with a stored credential, or to decrypt a document for its owner.
  • Hashing maps any input to a fixed-size digest, and you can't feasibly reverse it, or find two inputs with the same digest. Use it to detect changes (file checksums, Merkle trees, Git object IDs), to deduplicate, and to verify passwords, using a slow password hash, as explained below. A plain hash of a guessable value isn't private, though. A SHA-256 of a phone number can be brute-forced in seconds, because there are only about 10¹⁰ possible numbers. Use a keyed HMAC, with the key held in a KMS, when you need a stable pseudonymous identifier.
  • Tokenization replaces a sensitive value with a random token that has no mathematical relationship to it. The mapping lives in a heavily protected token vault. Downstream systems (orders, analytics, customer support) store and pass around tokens, and only the vault can turn a token back into the card number. Card tokenization by payment processors is why most merchants never touch raw card numbers, and stay out of most of PCI DSS scope.

Encoding, hashing and tokenization, in depth: properties and design choices#

Hash function properties. A cryptographic hash must have three:

  • preimage resistance: given a digest, you can't find an input that produces it;
  • second-preimage resistance: given an input, you can't find another with the same digest;
  • collision resistance: you can't find any two inputs with the same digest.

The birthday bound means collisions for an n-bit hash take about 2^(n/2) work. So SHA-256 gives 128-bit collision resistance. MD5 and SHA-1 are broken for collision resistance. The 2017 "SHAttered" attack by Google and CWI Amsterdam produced two different PDFs with the same SHA-1 hash. Never use either for signatures or certificates. They survive only in non-adversarial checksums.

Length extension. SHA-256 and SHA-512 use the Merkle-Damgård construction. Given H(secret || message), an attacker can compute H(secret || message || padding || extra) without knowing the secret. So hash(key + data) is not a safe MAC. Use HMAC (RFC 2104, by Bellare, Canetti and Krawczyk, 1996), or a hash designed to be keyed, such as SHA-3 or BLAKE3 in keyed mode.

Constant-time comparison. When you compare a provided MAC, token or API-key hash with the expected value, use a constant-time comparison (crypto.timingSafeEqual, hmac.compare_digest). A normal == that exits at the first differing byte leaks how many leading bytes matched, through timing.

Tokenization design.

  • Vault-based tokens are random IDs stored in a mapping table. They are simple, and revocable per token, but the vault is a high-value, latency-critical service, so replicate it and isolate it.
  • Vaultless tokenization uses format-preserving encryption (NIST FF1), so the token has the same shape as the input, for example 16 digits that pass the Luhn check. That avoids a lookup table, but it reintroduces a key that must be protected.
  • Single-use tokens are minted per transaction. Multi-use tokens are stable per card, so analytics can count repeat customers.
  • Network tokens, from Visa and Mastercard, are bound to a merchant and device, so a stolen token is useless elsewhere.

Pseudonymization vs anonymization. Replacing names with tokens or HMACs is pseudonymization. The data is still personal data under the GDPR, because it can be re-linked. True anonymization (aggregation, k-anonymity, differential privacy) means individuals can't reasonably be re-identified. Rare attribute combinations re-identify people surprisingly often, which is why releasing "anonymised" datasets is risky.

Password storage#

Passwords must be stored so that a database leak doesn't reveal them. Leaks happen, and users reuse passwords across sites. The rule is simple: store a slow, salted, one-way hash, never the password and never a reversible encryption of it. At login, hash the submitted password with the stored parameters, and compare.

  • Why not encryption? Whoever gets the key gets every password. The application needs only to verify a password, never to recover it. "Email me my password" features are a red flag.
  • Why not SHA-256? General-purpose hashes are designed to be fast. A single modern GPU computes billions of SHA-256 hashes per second. An 8-character lowercase-plus-digit password, 36⁸ ≈ 2.8 × 10¹² possibilities, falls in minutes.
  • Salt: a random value, 16 bytes, unique per user and stored with the hash. Salting makes identical passwords hash differently, and it defeats precomputed rainbow tables: an attacker must attack each hash separately.
  • Pepper (optional): a secret added to every hash, or an HMAC applied over it, and stored outside the database, in a KMS or HSM. A database-only leak then can't be cracked at all without the pepper.
  • Slow, memory-hard functions make each guess expensive.
    • Argon2id won the Password Hashing Competition in 2015 (Biryukov, Dinu and Khovratovich), and is the current first choice. It is memory-hard: each guess needs, say, 19–64 MiB of RAM, which cripples GPU and ASIC parallelism.
    • scrypt (Colin Percival, 2009) is also memory-hard.
    • bcrypt (Provos and Mazières, 1999) is not memory-hard, but it is still solid, with a cost factor of 10–12 or more. It truncates input at 72 bytes.
    • PBKDF2 with a high iteration count, such as 600,000 for HMAC-SHA-256 (OWASP's guidance), is acceptable where FIPS compliance requires it.

Store the algorithm, parameters and salt together. The standard PHC string format looks like $argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>. Then you can raise the cost later, and rehash on next login when a user's stored parameters are older than current policy.

Password storage, in depth: tuning cost, breach maths and beyond passwords#

Tuning. Pick parameters so that one hash takes about 100–500 ms, or less if login volume is huge, on your login servers, within your memory budget. The OWASP Password Storage Cheat Sheet suggests Argon2id with m = 19 MiB, t = 2, p = 1 as a minimum, or bcrypt cost 10 or more. Capacity matters too. At 250 ms and 64 MiB per hash, a 16-core login server handles about 64 logins per second, using about 1 GiB of RAM in flight. Size the login fleet for peak, and rate-limit attempts (Rate Limiting). Otherwise password hashing becomes a self-inflicted DoS vector: an attacker sends floods of login attempts, just to burn your CPU.

Breach maths. Say an attacker steals 10 million Argon2id hashes, each costing 250 ms and 64 MiB on a CPU. A GPU farm gains little, because of memory hardness. Even at an optimistic 10,000 guesses per second across their whole cluster, trying the 1,000 most common passwords against every account takes 10⁷ × 10³ / 10⁴ = 10⁶ seconds, about 12 days. Against unsalted MD5, the same attack takes well under a second, because one pass of a precomputed table cracks every matching account. That difference is why algorithm choice is a design decision.

Upgrading legacy hashes. If old hashes are MD5 or SHA-1, you don't need users' passwords to protect them now. Wrap each one: store argon2id(md5_hash), and mark the record as wrapped. At the user's next login, verify through the wrapper, then replace it with a direct Argon2id of the password.

Policy. NIST SP 800-63B (Digital Identity Guidelines) recommends:

  • minimum length, rather than composition rules;
  • checking new passwords against lists of breached passwords, such as the Have I Been Pwned k-anonymity API, which reveals only a 5-character hash prefix;
  • no forced periodic rotation, unless compromise is suspected;
  • allowing long passphrases and paste, so password managers work.

Beyond passwords. The strongest password storage is not storing passwords. Passkeys (WebAuthn) store only a public key on the server, so a database leak reveals nothing that can be used to log in. Federated login (OIDC) moves the problem to an identity provider. See Authentication and Authorization.

Related secrets. The same principle applies to anything the server only needs to verify:

  • API keys: store a SHA-256 of a high-entropy key. Fast hashing is fine here, because the key has 128 or more bits of entropy, so brute force is hopeless.
  • Password-reset tokens and session IDs: store a hash, so a database read can't replay them.

Secrets management#

A secret is any credential that grants access: database passwords, API keys, OAuth client secrets, TLS private keys, signing keys, encryption keys, cloud access keys, webhook secrets. Secrets management is about where secrets live, who can read them, how they're rotated, and how their use is audited.

The anti-patterns, all common sources of breaches:

  • secrets in source code or Git history. Bots scan public repos for leaked cloud keys within minutes of a push, and deleting a commit doesn't remove it from forks or clones;
  • secrets in container images, or in plain environment files committed alongside the code;
  • secrets in logs, error messages, crash dumps, or CI output;
  • long-lived shared credentials used by many services, never rotated, and known to ex-employees;
  • secrets passed through chat or tickets.

The pattern that works:

  1. A central store. Use HashiCorp Vault or OpenBao, a cloud secrets manager (AWS Secrets Manager, GCP Secret Manager, Azure Key Vault), or Kubernetes Secrets backed by a KMS. Secrets are encrypted at rest, every read is authenticated and audited, and access is set per service.
  2. Workload identity to fetch secrets. The service proves who it is through its platform identity: an IAM role, a Kubernetes service-account token, or a SPIFFE ID. So there's no "secret zero" baked into the image.
  3. Inject at runtime. A sidecar or agent writes the secret to a memory-backed file, the app fetches it through an SDK at startup, or a CSI driver mounts it. Environment variables are convenient, but they leak into child processes, crash dumps and /proc. Files or direct SDK fetches are safer.
  4. Short-lived and dynamic credentials. Vault can mint a unique database user per service instance, with a TTL of 1 hour, and revoke it at lease expiry. Cloud IAM roles issue temporary credentials that expire in 15 minutes to 12 hours. A leaked credential then expires on its own, and every credential traces back to one workload.
  5. Rotation. Automate rotation of static secrets, such as third-party API keys, every 30–90 days, and immediately on suspected leak. Support two valid versions at once during rotation, so there's no downtime. Add the new one, deploy consumers, then remove the old one.
  6. Detection. Run secret scanning in CI and on repositories (GitHub secret scanning, gitleaks, trufflehog), with pre-commit hooks. Alert on unusual secret-access patterns.

Secrets management, in depth: secret zero, KMS vs secrets manager, and break-glass#

The secret-zero problem. To fetch secrets, a service must authenticate to the secrets store, and that needs a credential. Where does that live? Platform identity is the answer. Examples include cloud instance metadata credentials, Kubernetes projected service-account tokens (audience-bound and short-lived), and SPIFFE SVIDs issued after node and workload attestation. The platform vouches for the workload, so nothing is baked into the image. Protect the instance metadata endpoint: require IMDSv2's session tokens on AWS, and block metadata access from containers that don't need it. SSRF attacks against the metadata endpoint have leaked cloud credentials in real breaches, as covered below.

KMS vs secrets manager vs Vault.

  • A KMS holds keys that never leave it. You send data, or a DEK, in to be encrypted or decrypted, or signed. Use it for envelope encryption and signing.
  • A secrets manager stores and returns secret values, such as passwords and API keys, with versioning and rotation hooks.
  • Vault does both, and more: dynamic secrets for databases, clouds and PKI, encryption-as-a-service through its transit engine, and short-lived SSH certificates.

Many organisations use the cloud KMS and secrets manager for cloud-native workloads, and Vault for multi-cloud setups or dynamic credentials.

Availability. The secrets store sits on the critical path of every deploy and restart. If Vault is down and pods can't fetch credentials, nothing starts. Run it highly available (Vault uses Raft integrated storage, with 3–5 nodes), cache secrets in agents with sensible TTLs, and decide what happens at lease expiry during an outage. Usually that means renewing early, and not killing working connections.

Sealing and unsealing. Vault encrypts its storage with a master key that is split with Shamir's secret sharing, for example 3 of 5 key holders, or auto-unsealed by a cloud KMS. A restarted node is "sealed" and useless to anyone who steals its disk.

Break-glass access. Humans sometimes need emergency production access. Make it explicit:

  • time-boxed elevation (just-in-time access), approved by a second person;
  • full session recording;
  • automatic alerts to the security team;
  • credentials rotated afterwards.

Break-glass that is easy, quiet and permanent becomes the normal path.

Digital signatures and certificates#

A digital signature proves that a message was produced by the holder of a private key, and hasn't been changed since. The signer computes sign(private_key, hash(message)). Anyone with the public key can verify it. Signatures give:

  • integrity: any change breaks the signature;
  • authenticity: it came from the key holder;
  • non-repudiation: the signer can't plausibly deny it, unlike a shared-key MAC, where either party could have produced it.

Where signatures appear in system design:

  • TLS handshakes, where the server signs the transcript;
  • JWT and OIDC tokens (RS256, ES256, EdDSA);
  • software supply chain: signed container images (Sigstore cosign), signed packages and commits, and signed OS updates;
  • webhooks and API requests: HMAC signatures are the symmetric cousin;
  • documents and financial messages;
  • code signing for mobile and desktop apps.

The algorithms:

  • RSA-PSS or RSA PKCS#1 v1.5, with 2048–3072-bit keys;
  • ECDSA on P-256, which has small keys and signatures, but needs a good random nonce per signature, or must use deterministic RFC 6979;
  • Ed25519 (EdDSA, by Bernstein et al., 2011), which is fast and deterministic, with a 64-byte signature and fewer pitfalls.

Post-quantum signatures, such as NIST's ML-DSA standardised in FIPS 204 (2024), are starting to appear for long-lived keys.

A certificate (X.509) binds a public key to an identity, such as a domain name, a service ID or an organisation. It is signed by a certificate authority (CA). Browsers and operating systems ship with about 100–150 trusted root CAs. Roots sign intermediate CAs, and intermediates sign leaf certificates. When a client connects, it checks:

  • the chain up to a trusted root;
  • the validity dates;
  • that the hostname matches the certificate's Subject Alternative Names;
  • key usage;
  • revocation status.

Digital signatures and certificates, in depth: PKI operations, revocation, transparency and internal CAs#

Automation. ACME (RFC 8555), the protocol behind Let's Encrypt, proves domain control through an HTTP-01, DNS-01 or TLS-ALPN-01 challenge, and issues certificates automatically. Let's Encrypt certificates last 90 days, and the industry is moving toward shorter lifetimes still. The CA/Browser Forum approved a phased reduction of maximum public TLS certificate lifetimes, reaching 47 days by 2029. Short lifetimes are only workable with automation: cert-manager in Kubernetes, managed certificates on load balancers and CDNs, and Caddy-style servers with built-in ACME. Expired certificates still cause high-profile outages, so monitor expiry independently of the renewal system.

Revocation is weak.

  • CRLs (certificate revocation lists) grow large.
  • OCSP (online status checks) adds latency and leaks browsing to the CA, and browsers mostly "soft-fail" if OCSP is unreachable, so an attacker who blocks OCSP defeats it. OCSP stapling, where the server attaches a fresh signed OCSP response, helps, but the industry has largely given up on online revocation for the public web. Let's Encrypt ended its OCSP service in 2025, in favour of CRLs.

The practical answer is short-lived certificates: a compromised key is useful for days, not years.

Certificate Transparency (CT). CAs must log every publicly trusted certificate to public append-only Merkle-tree logs (RFC 6962, by Laurie, Langley and Käsper, 2013), and browsers require proof of logging. Domain owners can monitor the CT logs, through services like crt.sh or cloud CT monitors, to detect certificates misissued for their domains. CT has exposed real CA misissuance.

Internal PKI. For mTLS between services, run a private CA: Vault PKI, AWS Private CA, cert-manager with an issuer, or SPIRE for SPIFFE identities. It issues certificates that last hours to days. The root key stays offline or in an HSM, and online intermediates do the signing. Name services by a SPIFFE ID (spiffe://prod.example.com/ns/payments/sa/checkout) rather than by hostnames that change.

Key compromise response. Have a runbook ready:

  1. revoke or stop trusting the affected certificate or key;
  2. issue new keys;
  3. rotate any tokens signed with them (publish a new kid in the JWKS, and stop accepting the old one);
  4. review CT and access logs for misuse.

Signing in the supply chain. Sigstore, from the Linux Foundation, provides keyless signing. A developer or CI job gets a short-lived certificate tied to an OIDC identity, signs the artefact, and the event is recorded in a public transparency log (Rekor). Kubernetes admission controllers can then refuse to run images that aren't signed by your CI identity. SLSA levels describe how strongly a build's provenance is attested. These defences answer supply-chain attacks such as the 2020 SolarWinds compromise, where attackers inserted malicious code into a signed software update.

Firewalls, WAF and DDoS protection#

Network defences filter traffic before it reaches your code. Each layer looks at different information.

  • Network firewalls filter by IP address, port and protocol (layers 3 and 4). In the cloud they appear as security groups, which are stateful and attached to instances or network interfaces, and network ACLs, which are stateless and attached to subnets. The rule of thumb is to deny by default and allow only what's needed. For example:
    • the load balancer accepts 443 from the internet;
    • application servers accept only from the load balancer's security group;
    • the database accepts 5432 only from the application servers;
    • nothing accepts SSH from 0.0.0.0/0.
  • Private subnets and egress control. Databases and internal services get no public IP. Outbound internet goes through a NAT gateway or an egress proxy with an allowlist of domains. Egress control is underrated. It stops malware from phoning home, and it limits where a data thief can send data.
  • Next-generation firewalls and cloud firewall services (AWS Network Firewall, Azure Firewall, Cloud NGFW) add deep packet inspection, domain filtering and intrusion prevention.
  • Kubernetes NetworkPolicies and service-mesh authorization policies give the same deny-by-default control between pods. Use them for microsegmentation: the checkout service may call payments, and nothing else may.
  • A web application firewall (WAF) inspects HTTP requests (layer 7): paths, headers, bodies. It blocks known attack patterns, such as SQL injection strings, XSS payloads, path traversal, bad bots, and exploits for known CVEs. Examples are AWS WAF, Cloudflare WAF, Akamai, Azure Front Door WAF, Google Cloud Armor, and ModSecurity with the OWASP Core Rule Set. A WAF is a compensating layer that buys time when a new CVE drops (virtual patching). It doesn't replace fixing the code, because it can be bypassed by encoding tricks, and it produces false positives. Roll out new rules in count or log-only mode first.
  • DDoS protection absorbs floods meant to exhaust your bandwidth, connection tables or servers.

DDoS attacks come in three kinds:

Attack layerExamplesDefence
Volumetric (L3/L4)UDP floods, DNS/NTP/memcached reflection and amplification, measured in TbpsAnycast networks with huge capacity (Cloudflare, AWS Shield, Akamai Prolexic, Google Cloud Armor), upstream scrubbing
Protocol (L4)SYN floods, ACK floods, fragmented packetsSYN cookies, stateless edge proxies, connection limits
Application (L7)HTTP floods, expensive search or login requests, slowlorisWAF rate rules, bot detection, challenges, caching, per-client rate limits, autoscaling with caps

Firewalls, WAF and DDoS, in depth: amplification, L7 floods and origin protection#

Amplification maths. Reflection attacks spoof the victim's IP address, and send small requests to open servers that reply with large responses. DNS amplification can reach about 50×. NTP's monlist reached around 500×. Memcached over UDP reached roughly 50,000× in the 2018 attacks, including one of about 1.35 Tbps against GitHub, which its DDoS provider absorbed within about 10 minutes. No single data centre link survives multi-terabit floods. Only globally distributed anycast capacity does. That's why DDoS protection is bought as a service, not built.

Origin protection. Edge protection is useless if attackers can reach the origin directly. So:

  • allow inbound traffic to the origin only from the CDN's or WAF's IP ranges, or through private connectivity (Cloudflare Tunnel, AWS CloudFront with VPC origins);
  • or require a secret header or mTLS from the edge;
  • never leak origin IPs through DNS history, email headers or subdomains that bypass the CDN.

L7 floods are the hard ones. They look like real users. HTTP/2 "Rapid Reset" (CVE-2023-44487, disclosed in 2023 by Google, Cloudflare and AWS) used stream cancellation to generate attacks of hundreds of millions of requests per second, against tiny botnets. Defences:

  • cache aggressively, so floods hit the CDN rather than the origin;
  • make expensive endpoints, such as search, login and export, cost-aware in rate limiting;
  • use bot scores and challenges for anonymous traffic;
  • shed load by priority, keeping logged-in checkout alive and dropping anonymous browse (Resilience Patterns);
  • cap autoscaling, so an attack can't turn into a giant cloud bill. This kind of "economic denial of sustainability" is a real risk with serverless and auto-scaled infrastructure.

WAF tuning. Run managed rule sets in log-only mode first. Review false positives, add exclusions per path (for example, a rich-text field that legitimately contains HTML), then switch to block. Keep custom rules for your own known-bad patterns. WAF logs are excellent threat intelligence. Feed them into your SIEM.

OWASP risks: injection, XSS, CSRF, SSRF and friends#

The OWASP Top 10 is a regularly updated list of the most critical web application security risks, compiled from industry data. The 2021 edition leads with Broken Access Control, followed by Cryptographic Failures, Injection, Insecure Design, Security Misconfiguration, Vulnerable and Outdated Components, Identification and Authentication Failures, Software and Data Integrity Failures, Security Logging and Monitoring Failures, and Server-Side Request Forgery (SSRF). OWASP published a further revision in 2025. A separate OWASP API Security Top 10 (2023) focuses on API-specific risks, led by Broken Object Level Authorization (BOLA), also known as IDOR. That means changing /orders/123 to /orders/124, and getting someone else's order. The four the phase asks for are each explained here, with their system-level fixes.

Injection. This happens when untrusted input is interpreted as code or commands: SQL, NoSQL queries, OS shell commands, LDAP, template engines. The classic case is "SELECT * FROM users WHERE name = '" + input + "'" with the input ' OR '1'='1. Fix: never build queries by string concatenation.

  • Use parameterised queries or prepared statements, so the database treats input strictly as data.
  • Use ORMs safely, and watch for their raw-query escape hatches.
  • For shell commands, avoid the shell entirely: pass argument arrays to execFile, never a string to sh -c.
  • Add defence in depth: least-privilege database users (the app user can't DROP TABLE or read other schemas), allowlist validation of identifiers such as sort columns, and WAF signatures.
-- Vulnerable: input becomes part of the SQL text
-- query = "SELECT id, email FROM users WHERE email = '" + input + "'";
 
-- Safe: placeholder, value sent separately as data
PREPARE find_user (text) AS
  SELECT id, email FROM users WHERE email = $1;
EXECUTE find_user('alice@example.com');
 
-- Identifiers cannot be parameters: allowlist them in code
-- sort = {"created": "created_at", "name": "name"}[userSort] or reject

Cross-site scripting (XSS). An attacker gets their JavaScript to run in another user's browser, on your origin. It can then read the page, act as the user, and steal non-HttpOnly tokens. The kinds:

  • Stored XSS: a comment containing a <script> tag, saved and shown to everyone.
  • Reflected XSS: a URL parameter echoed into the page.
  • DOM-based XSS: client-side code writes untrusted data into innerHTML.

Fix:

  • Context-aware output encoding. Modern frameworks such as React, Angular and Vue escape by default, so avoid dangerouslySetInnerHTML and v-html with untrusted data.
  • Sanitise HTML that you must allow, with a vetted library such as DOMPurify.
  • A Content Security Policy (CSP) header that forbids inline scripts, and allows scripts only from your origins or with nonces. That stops most injected scripts even when a bug slips through.
  • HttpOnly cookies, so scripts can't read session cookies.
  • Trusted Types, in browsers that support them, which lock down dangerous DOM sinks.

Cross-site request forgery (CSRF). A malicious site makes the victim's browser send a request to your site. The browser automatically attaches the victim's cookies, so the request is authenticated. An example is a hidden form that POSTs to /transfer. Fix:

  • SameSite=Lax or Strict cookies. Modern browsers default to Lax, which blocks most cross-site POSTs carrying cookies.
  • Anti-CSRF tokens: a per-session random token in a form field or header, checked by the server, often as a double-submit cookie.
  • Check the Origin or Sec-Fetch-Site headers on state-changing requests.
  • Never change state on GET.

APIs authenticated with Authorization: Bearer headers rather than cookies aren't vulnerable to classic CSRF, because browsers don't attach those headers automatically. They do have to protect tokens from XSS instead. More detail is in Authentication and Authorization.

Server-side request forgery (SSRF). Your server fetches a URL that the attacker controls: webhooks, "import from URL", image previews, PDF renderers. The attacker points it at internal addresses, such as http://169.254.169.254/ (the cloud metadata endpoint, which holds instance credentials), http://localhost:6379 (Redis) or an internal admin API. The server is inside your network, so firewalls don't help. The 2019 Capital One breach involved SSRF against a misconfigured WAF, which reached instance metadata credentials with broad S3 access. That is the case study for why IMDSv2 and least-privilege roles matter. Fix:

  • Resolve the hostname, and block private, loopback and link-local ranges, including IPv6 and alternative encodings such as decimal IPs.
  • Pin the resolved IP for the actual connection, to defeat DNS rebinding.
  • Don't follow redirects blindly.
  • Better still, run URL fetching in an isolated egress proxy or sandbox with no route to internal networks.
  • Require IMDSv2, and give the fetching service's role minimal permissions.

The others, briefly but importantly:

  • Broken access control and IDOR. Check authorization on every object access against the caller, not just "is logged in". Use unguessable IDs as defence in depth only, never as the control itself.
  • Insecure deserialisation. Never deserialise untrusted data with formats that can instantiate arbitrary types, such as Java native serialisation, Python pickle, or some YAML loaders.
  • Security misconfiguration. Watch for default credentials, verbose error pages showing stack traces, open admin consoles, public buckets, and permissive CORS (Access-Control-Allow-Origin: * with credentials).
  • Vulnerable components. Log4Shell (CVE-2021-44228) showed one logging library could expose a vast share of Java services. You need a software bill of materials (SBOM), dependency scanning, and the ability to patch fleet-wide within hours.
  • Path traversal. Input like ../../etc/passwd in file paths. Normalise the path, and check it stays within the allowed directory.
  • Mass assignment. Binding request JSON straight onto models lets a user set isAdmin: true. Use explicit allowlisted DTOs.

OWASP risks, in depth: SSRF defence, CSP design and injection beyond SQL#

SSRF filtering is subtle. Blocklists fail against many tricks:

  • http://2130706433/, which is 127.0.0.1 in decimal;
  • http://[::ffff:127.0.0.1]/;
  • http://localtest.me/, a public DNS name that resolves to 127.0.0.1;
  • redirects from an allowed host to an internal one;
  • DNS rebinding, where the first resolution is public and the second is internal.

A robust design has four parts.

  1. Parse with the same library the HTTP client uses.
  2. Resolve once, and check every resulting IP against the deny ranges: RFC 1918, loopback, link-local 169.254/16, carrier-grade NAT 100.64/10, IPv6 ULA and link-local, and the metadata IPs.
  3. Connect to that exact IP, with the original Host header and SNI.
  4. Re-validate on every redirect, or disable redirects.

Simplest of all, route these fetches through a dedicated egress proxy, such as Smokescreen from Stripe, that enforces the policy centrally and has no network path inward.

CSP that works. A strict policy looks like Content-Security-Policy: script-src 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'self', with a fresh random nonce on every response, and nonce attributes on legitimate script tags. It blocks injected inline scripts and javascript: URLs. Domain allowlists, such as script-src cdn.example.com, are weaker, because allowlisted CDNs often host JSONP endpoints or libraries that can be abused. Google's research on CSP (Weichselbaum et al., "CSP Is Dead, Long Live CSP!", ACM CCS 2016) found most allowlist-based policies bypassable, and recommended nonce-based strict policies. Deploy with Content-Security-Policy-Report-Only first, and collect violation reports. frame-ancestors also blocks clickjacking, where your page is framed invisibly by an attacker.

Injection beyond SQL.

  • NoSQL injection: MongoDB queries where {"password": {"$ne": null}} arrives as JSON. Validate types, so a string must be a string.
  • Template injection (SSTI): rendering user input as a template.
  • Log injection: newlines that forge log lines, or Log4Shell's JNDI lookups.
  • Header injection: CRLF characters that split responses.
  • Prompt injection in LLM-backed features: untrusted content instructs the model to ignore its rules, or to call tools. Treat model output as untrusted input to downstream tools, and give agents least-privilege tool access.

The unifying principle is the same each time: keep code and data separate, and validate input against a strict schema at the boundary.

CORS is not a security boundary for your server. CORS controls which browser origins may read responses. It doesn't stop curl, servers or attackers from calling your API. Misconfigured CORS can let a malicious site read authenticated responses. The worst case is reflecting any Origin header with Access-Control-Allow-Credentials: true. Allowlist specific origins.

Least privilege#

Least privilege means every identity gets only the permissions it needs, for only as long as it needs them. Identities here are users, services, CI jobs and admins. It limits blast radius: when, not if, something is compromised, the damage is bounded. It applies at every layer.

  • Cloud IAM: one role per service, with specific actions on specific resources. For example, s3:GetObject on arn:aws:s3:::invoices-prod/*, not s3:* on *. Avoid long-lived access keys for humans; use SSO with short sessions. Use separate accounts or projects per environment, so a dev compromise can't touch production.
  • Databases: separate users for migrations (DDL) and the application (DML only, on its own schema). Give read-only users to analytics, and use row-level security for multi-tenant tables.
  • Network: deny-by-default security groups and NetworkPolicies; services talk only to declared dependencies.
  • Kubernetes: namespace-scoped RBAC; no cluster-admin for apps. Pods run as non-root, with a read-only root filesystem and dropped Linux capabilities, under Pod Security Standards set to "restricted". Don't mount service-account tokens into pods that don't need them.
  • Humans:
    • just-in-time access: request, approve and expire;
    • separation of duties: the engineer who writes code can't approve and deploy it alone, and payment approvers can't create payees;
    • regular access reviews, and immediate de-provisioning on departure through SCIM.
  • Code and dependencies: sandboxing, capability-limited runtimes, minimal base images (distroless).

Least privilege, in depth: getting there in practice, and zero trust#

Start broad, then tighten with data. Nobody writes a perfect policy up front. Use access analysis, such as AWS IAM Access Analyzer's policy generation from CloudTrail, GCP's IAM Recommender, or audit logs. They show which permissions a role actually used in the past 90 days, so you can remove the rest. Enforce guardrails above the individual policies:

  • AWS Service Control Policies, or GCP organisation policies, that forbid disabling CloudTrail, making buckets public, or using unapproved regions, whatever an account admin does;
  • permission boundaries, which cap what delegated admins can grant.

Protect the backups from the production identity. Ransomware and destructive attackers go for the backups first. Keep backups in a separate account, with immutable or object-lock retention, and with deletion requiring a different identity. Then a fully compromised production account can't destroy recovery (Disaster Recovery).

Zero trust is least privilege applied to the network. No implicit trust comes from network location: every request is authenticated, authorised and encrypted, based on identity and device posture. Google's BeyondCorp papers (Ward and Beyer, 2014, plus later papers) describe moving employee access off the VPN to identity-aware proxies. For services, zero trust means mTLS identities, policy-checked calls, and no "inside is safe" flat networks. It is a direction rather than a product: the practical steps are workload identity, mTLS, authorization per call, and microsegmentation.

Privilege also has a time dimension. Standing privileges, such as permanent admin rights, are risky even if they're rarely used. Convert them to time-bound grants. Short-lived credentials (STS tokens, Vault leases, short certificates) are least privilege over time. A credential that expires in 15 minutes is worth far less to a thief than one that lasts until someone notices.

API security checklist#

Every API endpoint, public or internal, should pass this checklist. It condenses the practices above into what reviewers actually check.

  1. HTTPS only, with HSTS on public domains, TLS 1.2 or later, and TLS or mTLS for internal calls. Never accept credentials over plain HTTP.
  2. Authenticate every request, with OAuth 2.0 access tokens, session cookies, or API keys for server-to-server calls. Validate the token's signature, issuer, audience and expiry on every call (Authentication and Authorization).
  3. Authorise every object. Check that this caller may perform this action on this resource (BOLA/IDOR). Also check function-level access, so a normal user can't reach admin routes, and property-level access, so users can't read or write fields they shouldn't.
  4. Validate input against a schema: types, lengths, ranges, formats and allowed values, with OpenAPI or JSON Schema enforced at the gateway or the framework. Reject unknown fields, which also prevents mass assignment.
  5. Use parameterised queries, and encode output for its context.
  6. Rate-limit and set quotas per user, key and IP, with cost weighting for expensive operations. Cap payload sizes, pagination limits and query complexity, such as GraphQL depth and cost (Rate Limiting).
  7. Return minimal data. Don't send whole database rows to the client, and trust it to hide fields. Choose response fields explicitly.
  8. Send safe errors. Use generic messages and correlation IDs, with no stack traces, SQL errors or internal hostnames. Use the same response for "user not found" and "wrong password", to prevent account enumeration.
  9. Keep secrets out of URLs. Query strings end up in logs, browser history and Referer headers. Put tokens in headers.
  10. Set security headers: Strict-Transport-Security, Content-Security-Policy, X-Content-Type-Options: nosniff, Referrer-Policy, frame-ancestors (or X-Frame-Options), and strict CORS allowlists.
  11. Make writes idempotent, and sign webhooks. Use Idempotency-Key headers (Idempotency), HMAC-signed webhook payloads with timestamps to block replay, and verified signatures on inbound webhooks.
  12. Keep an inventory and version your APIs. Know every API you expose, including old versions and "shadow" internal APIs, and retire them. Forgotten endpoints are a top API risk (OWASP API9, Improper Inventory Management).
  13. Log and monitor: authentication failures, authorization denials, rate-limit hits and unusual access patterns, with alerts, and without logging secrets or full PII.
  14. Protect business flows. Defend sensitive flows (signup, checkout, ticket purchase, coupon redemption) against automation abuse, with bot detection and per-account limits (OWASP API6, Unrestricted Access to Sensitive Business Flows).
  15. Handle third-party APIs with care. Validate the data you receive from them too (OWASP API10, Unsafe Consumption of APIs), with timeouts and size limits.

PII and compliance basics (GDPR)#

PII (personally identifiable information), called "personal data" in the GDPR, is any information relating to an identifiable person. That includes names, emails, phone numbers, addresses, IP addresses, device IDs, location, and cookie identifiers. Special categories (health, biometrics, religion, sexual orientation, and similar) need stronger protection. Payment card data falls under PCI DSS, US health data under HIPAA, and many US states have their own privacy laws, such as the CCPA/CPRA in California.

The GDPR (EU General Data Protection Regulation, in force since 2018) applies to anyone processing EU residents' personal data, wherever the company is based. Fines reach the higher of €20 million or 4% of global annual turnover. Its principles translate into design requirements.

GDPR principle or rightWhat it means for the design
Lawful basis and purpose limitationRecord why each data field is collected; don't reuse it for unrelated purposes without a basis, such as consent
Data minimisationCollect only what you need; don't log full request bodies containing PII
Storage limitationRetention policies with TTLs; delete or anonymise automatically after the purpose ends
Integrity and confidentialityEncryption, access control, pseudonymisation
Right of access and portabilityBe able to find and export everything about a user, in a machine-readable form
Right to erasure ("right to be forgotten")Be able to delete a user's data across services, caches, search indexes, analytics and backups
Right to rectification and objectionUpdate data everywhere it's copied; honour opt-outs
Privacy by design and by defaultPrivacy-protective defaults; data protection impact assessments (DPIAs) for risky processing
Breach notificationNotify the supervisory authority within 72 hours of becoming aware of a qualifying breach
International transfersTransfers out of the EU need a legal mechanism, such as adequacy decisions or standard contractual clauses; this drives data-residency designs

The system-design consequences:

  • A data inventory and classification. Tag fields as public, internal, confidential or restricted, and know which services and stores hold PII. This is the lineage you need for access and erasure requests. Without it, you can't answer "where is this user's data?"
  • Isolate PII. Keep it in a few well-protected services, such as a user-profile service. Give everything else opaque user IDs. That shrinks both the blast radius and compliance scope.
  • Erasure pipelines. A deletion request publishes a UserDeleted event. Every service that holds user data consumes it, deletes or anonymises, and reports completion. Crypto-shredding handles the copies in backups and logs. Erasure usually has to complete within a month.
  • Data residency. Keep EU users' data in EU regions, through a user's "home region" in routing, with per-region storage and keys. Some sectors and countries require in-country storage.
  • Logs and analytics. Redact PII at the logging library, with masking by field, and hash or tokenise identifiers for analytics. Logs are the most common uncontrolled copy of personal data.
  • Consent management. Record consents, with timestamps and versions, and propagate opt-outs to marketing and analytics systems.

Security operations: DevSecOps, logging and incident response#

Security has to be continuous, not a gate at the end. DevSecOps builds it into the delivery pipeline (CI/CD and Deployment).

  • On commit: secret scanning, SAST (static analysis such as CodeQL or Semgrep), dependency scanning (SCA, through Dependabot, Snyk or OSV-Scanner), and infrastructure-as-code scanning (tfsec/Trivy, Checkov) for public buckets and open security groups.
  • On build: minimal base images, container image scanning, signed images, and an SBOM.
  • Before release: DAST (dynamic scanning of the running app, such as OWASP ZAP), and threat-model review for new designs.
  • At runtime: admission policies (Kyverno, OPA Gatekeeper) that reject privileged or unsigned pods; runtime detection (Falco, cloud threat detection such as GuardDuty); patching SLAs, for example critical CVEs within 7 days or faster when they're actively exploited.

Security logging records the events an investigator needs: logins (success and failure), MFA changes, permission changes, admin actions, secret access, data exports and API key creation. Every entry carries who, what, when, from where, and the outcome. Ship these to a SIEM (Splunk, Elastic Security, Microsoft Sentinel, Google SecOps), protected from tampering in an append-only store, or in a separate account. Retain them long enough to investigate, often 1 year or more. Attackers often dwell for weeks before detection. More on pipelines and alerting is in Observability.

Incident response is a plan written before the incident: detection, triage, containment (revoke credentials, isolate hosts), eradication, recovery, notification (the 72-hour GDPR clock, contracts, customers), and a blameless post-incident review. Practise with tabletop exercises.

Security operations, in depth: password managers, bastions and admin access#

Human credentials are the soft target. Phishing and credential reuse dominate breach statistics. The system-design answers:

  • SSO for every internal tool, with phishing-resistant MFA: FIDO2 security keys or passkeys, rather than SMS or push approvals. Push approvals have been defeated by "MFA fatigue" spamming in real breaches.
  • Password managers for the secrets humans still handle. A good password manager encrypts the vault on the client with a key derived from the master password, using PBKDF2 or Argon2 with high cost, plus a device secret in some designs. The provider stores only ciphertext. Its security therefore depends on the KDF cost and on endpoint security. Password managers also defeat phishing, because they autofill only on the exact domain.

Admin access paths. Replace SSH bastions with long-lived keys by:

  • short-lived SSH certificates, signed by a CA (Vault SSH, Teleport, or Smallstep) after SSO, valid for hours;
  • or cloud session managers (AWS SSM Session Manager, GCP IAP TCP forwarding) with no inbound ports open.

Record sessions, and require a ticket or approval for production. Production databases should never be directly reachable from laptops.

Device trust. Zero-trust access also checks the device: managed, encrypted, patched, with EDR running. That's done through device certificates or posture checks at the access proxy.

When to Use It#

Security fundamentals aren't optional features. Every system needs them. The question is how much of each layer, and that depends on the data and threat model. Concrete signals that push you to the stronger end:

  • You store regulated or high-value data: payment cards (PCI DSS needs tokenization or a vault, network segmentation and quarterly scans), health data (HIPAA), government IDs, credentials, or children's data. Use field-level encryption, tokenization, HSM-backed keys, and strict access logging.
  • You're multi-tenant B2B. Customers will ask for SOC 2 or ISO 27001 reports, SSO, audit logs, per-tenant keys (bring-your-own-key), data residency, and pen-test results. Design tenant isolation and per-tenant encryption keys early. Retrofitting is painful.
  • You expose public APIs or user-generated content. Prioritise a WAF, rate limits, bot management, input validation, CSP, and SSRF defences for any URL fetching.
  • You have many services and engineers. Central secrets management, workload identity, mTLS, IaC scanning and least-privilege IAM pay off quickly, once you have more than a handful of services. Manual credential handling doesn't scale past then.
  • You're a target: finance, crypto, elections, healthcare, critical infrastructure, or popular consumer brands. Assume determined attackers. Invest in DDoS protection, detection and response, insider-threat controls, and red teams.
  • You process EU (or other regulated-jurisdiction) personal data. GDPR design obligations apply: an inventory, minimisation, erasure, residency and breach response.

When NOT to Use It#

"Not using" security means right-sizing, not skipping it. Over-engineering has real costs: complexity, outages, and slower delivery.

  • Don't build your own cryptography or crypto protocols. Use vetted libraries (libsodium, Tink, the platform's TLS) and managed services. Hand-rolled crypto is where subtle, catastrophic bugs live.
  • Don't add field-level encryption to data that isn't sensitive. It breaks querying and indexing, and adds key-management load. Disk and storage encryption is enough for most fields.
  • Don't run your own HSM fleet, PKI or DDoS scrubbing at small scale. Cloud KMS, managed certificates and a CDN's DDoS protection cost little, and are better operated than what a small team can build.
  • Don't make security controls single points of failure without availability engineering. A Vault outage, an expired internal CA, or an over-eager WAF rule can take everything down. Plan for them like any critical dependency.
  • Don't collect data "just in case" and then protect it. Not storing it at all is the cheapest and strongest control.
  • Don't add friction that users route around. Forced 30-day password changes produce Summer2026!. Overly strict internal access makes engineers share credentials. Security that blocks work gets bypassed.
  • Prototypes and internal demos with fake data don't need production-grade controls. They still need no real secrets in code, and no real customer data.

How to Implement It#

A practical order for building a new system, or hardening an existing one:

  1. Threat-model the design. Draw the data-flow diagram, mark trust boundaries, run STRIDE, and list your top risks. Classify the data.
  2. Lock down identity. Use SSO with phishing-resistant MFA for humans, workload identity for services, separate cloud accounts per environment, and least-privilege roles. Never use root or owner credentials day to day.
  3. Encrypt everything in transit and at rest by default. Use managed certificates and ACME, TLS to all datastores, KMS-backed storage encryption, and field-level or tokenized handling for restricted data.
  4. Centralise secrets. Adopt Vault or a cloud secrets manager, prefer dynamic or short-lived credentials, inject them at runtime, and scan repos and CI.
  5. Build the network perimeter and segmentation. Use private subnets, deny-by-default security groups and NetworkPolicies, egress allowlists, and only the load balancer public. Put a CDN, WAF and DDoS protection in front.
  6. Harden the application. Apply the API checklist, parameterised queries, CSP and secure cookies, SSRF-safe fetchers, schema validation and safe errors.
  7. Build the pipeline. Run SAST, SCA, IaC scanning and image scanning, sign images, enforce admission policies, and set patch SLAs.
  8. Add logging, detection and response. Send audit logs to a SIEM, set alerts on high-risk events, and keep an incident runbook with tested credential revocation.
  9. Handle privacy. Keep a data inventory, retention TTLs, erasure pipelines, consent records and residency routing.
  10. Verify continuously. Run pen tests, bug bounties, red-team exercises, access reviews and DR/IR drills.

A Node/TypeScript sketch of envelope encryption for a sensitive field, using AWS KMS for the data key and AES-256-GCM locally. The record ID is bound as associated data.

import { KMSClient, GenerateDataKeyCommand, DecryptCommand } from "@aws-sdk/client-kms";
import { randomBytes, createCipheriv, createDecipheriv } from "node:crypto";
 
const kms = new KMSClient({});
const KEY_ID = "alias/payments-pii"; // KEK lives in KMS, never leaves it
 
export async function encryptField(plain: string, recordId: string) {
  const dk = await kms.send(new GenerateDataKeyCommand({ KeyId: KEY_ID, KeySpec: "AES_256" }));
  const iv = randomBytes(12);                        // unique per encryption
  const c = createCipheriv("aes-256-gcm", dk.Plaintext!, iv);
  c.setAAD(Buffer.from(recordId));                   // bind ciphertext to its row
  const ct = Buffer.concat([c.update(plain, "utf8"), c.final()]);
  dk.Plaintext!.fill(0);                             // drop plaintext DEK
  return { v: 1, iv: iv.toString("base64"), tag: c.getAuthTag().toString("base64"),
           ct: ct.toString("base64"), wrappedKey: Buffer.from(dk.CiphertextBlob!).toString("base64") };
}
 
export async function decryptField(e: any, recordId: string) {
  const { Plaintext } = await kms.send(new DecryptCommand({   // IAM-checked, audited
    CiphertextBlob: Buffer.from(e.wrappedKey, "base64") }));
  const d = createDecipheriv("aes-256-gcm", Plaintext!, Buffer.from(e.iv, "base64"));
  d.setAAD(Buffer.from(recordId));
  d.setAuthTag(Buffer.from(e.tag, "base64"));                 // tampering fails here
  return Buffer.concat([d.update(Buffer.from(e.ct, "base64")), d.final()]).toString("utf8");
}

In production you would cache data keys for a short time, with a bounded number of uses, to cut KMS calls. You would also store the key ID with the record, and use a library such as the AWS Encryption SDK or Google Tink, which packages these details safely.

A least-privilege IAM policy, in YAML form for readability, for the checkout service:

Version: "2012-10-17"
Statement:
  - Effect: Allow
    Action: ["s3:GetObject", "s3:PutObject"]
    Resource: "arn:aws:s3:::invoices-prod/checkout/*"
  - Effect: Allow
    Action: ["kms:Decrypt", "kms:GenerateDataKey"]
    Resource: "arn:aws:kms:eu-west-1:111122223333:key/payments-pii-key-id"
    Condition:
      StringEquals: { "kms:EncryptionContext:service": "checkout" }
  - Effect: Allow
    Action: ["secretsmanager:GetSecretValue"]
    Resource: "arn:aws:secretsmanager:eu-west-1:111122223333:secret:checkout/*"
TechnologyFits when
AWS KMS / Google Cloud KMS / Azure Key VaultEnvelope encryption and signing keys for cloud workloads, with IAM-controlled, audited use
Cloud HSM / dedicated HSMsRegulations require single-tenant, FIPS 140-3 Level 3 key custody: payments, CAs
HashiCorp Vault / OpenBaoMulti-cloud or on-prem secrets, dynamic database or cloud credentials, internal PKI, SSH certificates, encryption-as-a-service
AWS Secrets Manager / GCP Secret ManagerCloud-native static secrets with versioning and managed rotation
Let's Encrypt + cert-manager / ACMAutomated public TLS certificates; ACM for AWS load balancers and CloudFront
SPIFFE/SPIRE, Istio or LinkerdWorkload identity and automatic mTLS between services
Cloudflare / AWS Shield + WAF / Akamai / Cloud ArmorEdge DDoS absorption, WAF managed rules, bot management
OWASP ModSecurity CRS / CorazaSelf-hosted WAF in front of NGINX or Envoy
Argon2id (libsodium, argon2 libraries) / bcryptPassword hashing
Google Tink / libsodium / AWS Encryption SDKApplication-level encryption without hand-rolled crypto
Payment processor tokenization (Stripe, Adyen) / Vault transformKeep card data out of your systems, shrink PCI scope
Semgrep / CodeQL, Dependabot / Snyk, Trivy, gitleaksSAST, dependency and container scanning, and secret scanning in CI
Sigstore cosign + Kyverno / GatekeeperSigning images and enforcing signed-only, non-privileged deployments
Splunk / Elastic Security / Sentinel / GuardDutySIEM and threat detection on audit logs

Trade-offs#

OptionProsConsPick when
Storage or disk encryption onlyFree, transparent, no app changesDoesn't protect against app or credential compromiseDefault for all data
Field-level encryptionDBAs, backups and SQLi see only ciphertext; per-field key controlNo range queries, no easy indexing; key-management load; slowerRestricted fields: national IDs, bank details, health data
Tokenization (vault)Most systems never hold the real value; shrinks PCI scopeVault is a critical, latency-sensitive dependencyCard numbers, SSNs, data that needs a narrow access path
End-to-end or client-side encryptionProvider can't read data even if breached or compelledNo server-side search, ML or moderation; key recovery is hardMessaging, password managers, private backups
TLS terminated at the edge onlySimple; edge does WAF and cachingPlaintext inside the networkNever for sensitive data; acceptable only in tiny trusted setups
mTLS everywhere through a meshEncryption plus service identity, zero-trust readyMesh complexity, certificate operations, some latencyMany services, regulated data, multi-tenant clusters
Static secrets in a managerSimple, works with any softwareLong-lived; leaks stay valid until rotatedThird-party API keys that can't be dynamic
Dynamic short-lived credentialsLeaks expire; per-instance attributionSecrets store becomes critical; more moving partsDatabases and cloud access at scale
Managed WAF and DDoSHuge capacity, maintained rulesCost; false positives; vendor dependence; TLS terminates at the vendorAny public internet-facing system
Self-hosted WAFControl, no vendor in the data pathNo volumetric DDoS capacity; you tune and patch itInternal apps, compliance that forbids third-party termination

Common Pitfalls#

  • Calling Base64 "encryption", or putting secrets in JWT payloads. Encoding hides nothing.
  • Fast hashes for passwords (MD5, SHA-1, or SHA-256 without a KDF), or unsalted hashes.
  • Disabling TLS certificate verification "temporarily" in a client, and shipping it.
  • Secrets in Git, images, logs or URLs, and assuming deleting a commit removes them. Rotate immediately on any leak.
  • One shared, all-powerful service account or database user across services.
  • Trusting the internal network: no TLS and no authentication between services, flat networks, metadata endpoints reachable from every container.
  • Authenticated but not authorised: checking the login, but not that the user owns /orders/124.
  • A WAF instead of fixes, or a WAF in blocking mode without tuning, which then blocks real customers.
  • Origin IP exposed, so attackers bypass the CDN and WAF entirely.
  • Certificates expiring because renewal was manual, or monitoring was missing.
  • PII in logs, analytics and test databases. Production data copied to staging without masking.
  • Backups deletable by the production identity, which ransomware then wipes.
  • No inventory: forgotten APIs, old versions, unmanaged subdomains (subdomain takeover through dangling DNS records), and orphaned cloud resources.
  • Encryption keys stored next to the data they protect, such as the AES key in the same database or config repo.
  • Nonce reuse in AES-GCM, or ECB mode. Use high-level libraries that manage nonces.

Real-World Examples#

  • Capital One (2019). SSRF through a misconfigured WAF reached EC2 instance metadata, and obtained role credentials with broad S3 read access. About 100 million customers' data was exposed. Lessons: IMDSv2, least-privilege roles, egress controls, and SSRF-safe fetchers.
  • Equifax (2017). An unpatched Apache Struts vulnerability (CVE-2017-5638) in an internet-facing application led to exposure of data on roughly 147 million people. The lessons are patch management, a component inventory, and segmentation.
  • Log4Shell (December 2021). A JNDI lookup in Log4j's message formatting enabled remote code execution from logged strings, across a huge share of Java software. Organisations with SBOMs and fast fleet-wide patching responded in hours. Others took weeks.
  • GitHub (2018). It absorbed a memcached amplification attack of about 1.35 Tbps, by routing traffic to its DDoS mitigation provider.
  • HTTP/2 Rapid Reset (2023). Google reported a peak of about 398 million requests per second. It was mitigated by edge providers' protocol-level changes, showing L7 attacks evolve with protocols.
  • Let's Encrypt has made free, automated, 90-day certificates the norm since 2015. It now issues certificates for hundreds of millions of sites, which shows automation makes short lifetimes practical.
  • Google BeyondCorp moved employee access from VPNs to identity- and device-aware proxies, which shaped the industry's zero-trust model.
  • Password-hash breaches. LinkedIn's 2012 breach exposed unsalted SHA-1 password hashes, most of which were cracked. It is a standard cautionary tale for why salted, slow hashing matters.
  • Stripe and other payment processors offer client-side tokenization (hosted fields and elements), so merchants' servers never see card numbers, and merchants qualify for the simplest PCI self-assessment.

Case studies that use this pattern#

  • Payment System: tokenization, PCI scope, HSM-backed keys, idempotent and signed webhooks, audit trails.
  • Chat System: TLS on long-lived connections, end-to-end encryption trade-offs, abuse and rate limiting.
  • File Sync: encryption at rest per user, signed URLs, sharing permissions, malware scanning.
  • URL Shortener: abuse, phishing and malware link detection, enumeration resistance, rate limits.
  • Web Crawler: SSRF-safe fetching, politeness, sandboxed parsing of hostile content.
  • Ticket Booking: bot and scalper defence, protecting a sensitive business flow under flash-crowd load.

In the Interview#

Deep Dive: Key management at scale and the cryptographic toolboxShow

Choosing primitives (a decision table you can defend):

  • Symmetric AEAD: AES-256-GCM, with hardware acceleration, or ChaCha20-Poly1305 on devices without AES-NI. GCM's 96-bit random nonces are safe up to about 2³² messages per key. Beyond that, collision risk grows, so rotate DEKs, or use AES-GCM-SIV or XChaCha20, which are nonce-misuse-resistant or have extended nonces.
  • Key exchange: X25519 or P-256 ECDHE; hybrid post-quantum (X25519 with ML-KEM-768) is now deployed in major browsers and CDNs. It defends against "harvest now, decrypt later" attackers, who record traffic today hoping for future quantum computers.
  • Signatures: Ed25519 for new systems; ECDSA P-256 where FIPS or ecosystem support demands it; RSA-3072 for legacy compatibility. ML-DSA is for long-term post-quantum readiness.
  • Hashing: SHA-256 or SHA-512, BLAKE3 for speed, HMAC-SHA-256 for MACs. Use a KDF (HKDF, RFC 5869) to derive sub-keys from a master secret, never ad-hoc concatenation.
  • Passwords: Argon2id, scrypt or bcrypt.

Envelope maths. A service writing 20,000 encrypted records per second, with one KMS call per record, would need 20,000 KMS requests per second. That exceeds typical default quotas, and adds a 5–20 ms network round trip to every write. With data-key caching (reuse one DEK for 5 minutes, or 10,000 messages, whichever comes first), it needs about 2 KMS calls per second per instance. The cost is a wider blast radius per DEK: one key now protects 10,000 records instead of 1. That is acceptable, because the DEK exists only in memory, and the KEK stays in the HSM. Tune the cache limits by data sensitivity.

Key rotation versus re-encryption. Rotating a KEK (new version for new wraps) takes seconds. Re-encrypting 50 TB under new DEKs at 500 MB/s per worker takes 50 × 10¹² / 5 × 10⁸ = 10⁵ seconds, about 28 hours, for one worker, so it's parallelised and throttled. That's why systems separate the two, and re-encrypt only when a DEK may be compromised, or when policy demands it.

Multi-region keys. Encrypted data replicated across regions needs keys there too. Either use multi-region keys, where the same key material is replicated by the KMS, or rewrap DEKs per region. The trade-off is availability (a regional KMS outage shouldn't block other regions) against sovereignty (EU keys never leaving the EU).

Customer-managed keys (BYOK/HYOK). B2B SaaS customers increasingly demand control over their tenant's KEK, held in their own cloud KMS account. The service calls the customer's KMS to unwrap tenant DEKs. If the customer revokes access, their data becomes unreadable: a crypto-shred under customer control. The design challenges are caching (the customer's KMS adds latency and is outside your SLO), clear failure behaviour when a key is disabled, and audit visibility for the customer.

Deep Dive: Threat-modelling a real design, step by stepShow

Take a typical SaaS design: a web app, an API gateway, about 10 microservices, PostgreSQL, Redis, S3, Kafka, a webhook-delivery service, and an admin console.

1. Assets and data classification. Identify the assets: user credentials (handled by the IdP), customer documents in S3 (restricted), billing details (tokenized at the processor), audit logs (integrity-critical), signing keys (critical), and analytics (internal, pseudonymised).

2. Trust boundaries. Internet → edge; edge → services; services → datastores; services → third parties (webhooks out, payment processor in); admins → console; CI → production.

3. STRIDE per boundary (selected findings):

BoundaryThreatMitigation
Internet → APISpoofing via stolen tokensShort-lived tokens, refresh rotation, device-bound tokens (DPoP) for high-risk clients
Internet → APIDoS through expensive export endpointAsync export jobs, per-tenant concurrency caps, cost-weighted rate limits
Webhook service → customer URLsSSRF into the VPCEgress proxy with deny ranges, no metadata access, separate subnet
Service → S3Information disclosure through public bucketBlock Public Access at account level, SCP guardrail, presigned URLs with 5-minute expiry
Admin → consoleElevation through compromised admin laptopSSO + FIDO2, device posture, JIT elevation, session recording
CI → prodTampering through poisoned dependencyPinned dependencies, SCA, signed images, admission policy, separate deploy identity
Services → KafkaRepudiation, no record of who wrote eventsmTLS client identities, ACLs per topic, producer identity in headers

4. Rank by likelihood × impact, and fix the top items first. Here that's object-level authorization tests, the SSRF egress proxy, and S3 guardrails. Accept low risks explicitly, and record the decisions.

5. Re-run on every significant design change. Threat models go stale. Attach a lightweight one to design-review templates, with ten questions rather than fifty pages, so it actually happens.

Attack-path thinking. Real attackers chain small weaknesses. A typical chain: phishing gets a developer's password; there's no MFA on the CI system; the CI system holds a long-lived cloud key with admin rights; the attacker deletes backups and exfiltrates S3. Each link is mundane. Breaking any one (phishing-resistant MFA, OIDC-federated short-lived CI credentials, least-privilege deploy roles, immutable backups in a separate account) stops the chain. Defence in depth means making sure every likely chain has at least two breaks.

Deep Dive: Privacy engineering beyond the checklistShow

Data-subject request (DSR) architecture at scale. With 50 services and petabytes of data, "find everything about user X" needs three pieces.

  1. A data catalogue: each dataset declares its PII fields and the user-ID column, through schema annotations checked in CI.
  2. A DSR orchestrator that fans out access and erasure tasks, through events or a workflow engine, and tracks completion per system, with deadlines and retries.
  3. Per-store handlers:
    • OLTP: delete or anonymise rows.
    • Search: delete documents.
    • Caches: evict, or let TTLs expire.
    • Data lake: rewrite partitions with table formats that support row-level deletes, such as Delta Lake, Apache Iceberg or Hudi, through merge-on-read delete files followed by compaction.
    • ML features: remove the rows; retraining policies decide model impact.
    • Backups: crypto-shred, or document the retention window after which backups expire.

Legal holds and conflicting obligations. Tax and anti-money-laundering laws require keeping some records, such as invoices, for 5–10 years, even after an erasure request. The design answer is to minimise and separate. Keep only the legally required fields, in a restricted store, with restricted access and a scheduled deletion at the end of the retention period. Anonymise everything else.

Pseudonymisation that holds up. Replace user IDs in analytics with HMAC(k_analytics, user_id), keeping the key in the KMS. Analysts can join datasets and count unique users, but can't reverse the IDs without the key, and rotating the key per dataset prevents cross-dataset linking. Remember that the output is still personal data under the GDPR, because the key holder can re-identify.

Differential privacy (Dwork, McSherry, Nissim and Smith, "Calibrating Noise to Sensitivity in Private Data Analysis", 2006) gives a mathematical guarantee. Adding calibrated noise means any one person's presence changes published statistics by at most a factor of e^ε. It is used, for example, by the US Census Bureau for its 2020 census data products, and in some telemetry collection by Apple and Google. Use it when you publish aggregates from sensitive data. The ε budget is a real trade-off between accuracy and privacy.

Data residency patterns.

  • Region pinning: each user's or tenant's data lives in their home region; a global directory maps user to region (holding only minimal, non-sensitive routing data); requests are routed or proxied there.
  • Split storage: PII stays in-region; non-personal aggregates replicate globally.

Watch for leaks: logs, traces, support tools, backups and analytics pipelines that replicate globally by default. Residency failures usually happen in these side channels, not the primary database.

Key Takeaways#

  • Security is layers that assume the others fail: edge, network, application, data, keys, with least privilege and logging everywhere. Threat-model with STRIDE to find gaps early.
  • Encrypt in transit everywhere (TLS 1.3, mTLS inside, verified certificates) and at rest (storage encryption by default, envelope encryption with KMS-held KEKs, field-level for restricted data).
  • Encoding ≠ encryption ≠ hashing ≠ tokenization. Pick by need: format, reversible confidentiality, one-way verification, or removing the value from most systems.
  • Passwords: a unique salt plus a slow, memory-hard hash (Argon2id, scrypt, bcrypt), tunable and rehashed over time. Better still, passkeys or federation.
  • Secrets belong in Vault, a KMS or a secrets manager, fetched by workload identity. Prefer short-lived, dynamic credentials; scan for leaks; rotate with overlap.
  • Signatures and certificates prove origin and integrity. Automate certificates (ACME, short lifetimes), watch Certificate Transparency, run an internal CA for mTLS, and sign your software supply chain.
  • Firewalls, a WAF and edge DDoS protection filter at L3/4/7. Hide the origin, cache aggressively, and cap autoscaling against L7 floods.
  • OWASP risks are design problems. Parameterise queries, encode output and use CSP, use SameSite cookies and tokens against CSRF, sandbox URL fetching against SSRF, and authorise every object.
  • Least privilege across IAM, databases, networks, Kubernetes and humans, over time too (just-in-time access and short credentials), limits the blast radius.
  • Privacy is architecture. Keep a data inventory, minimise collection, isolate PII, set retention TTLs, build erasure pipelines (with crypto-shredding for backups), route for residency, and be ready for the 72-hour breach clock.