Threat modelling

Decide what you defend, and from whom, before building defences

User’s browsernot under your controlYour serverDatabasetrust boundarytrust boundarymost security bugs live at these linesWhat are you protecting?card dataFrom whom?outside criminalsWhat do they want?to sell itWhat will you spend?5% of engineering timeSTRIDE: six kinds of harm to ask about at every componentSpoofingTamperingRepudiationInfo disclosureDenial of servicePrivilege elevationDecide what you defend, from whom, and at what cost before writing code. Then look hardest where trust changes.A useful threat model is concrete: “we protect card data from outside attackers who want to sell it, with up to 5% ofengineering capacity.” It expires whenever the architecture changes, so it is redone at every design review.

A threat model names the asset, the attacker and the budget. Bugs cluster at trust boundaries.

Threat modelling · Going deeper

STRIDE — six categories of harm to brainstorm against Spoofing Tampering Repudiation Information disclosure Denial of service Elevation of privilege claim to be someone you're not session-token replay, credential stuffing change data in transit or at rest modified DB record, man-in-the-middle deny having done something missing audit log, no signed receipt read what shouldn't be read leaked secrets, plaintext backups, side channels make the system unavailable flood, algorithmic DoS, resource exhaustion do more than you should broken access control, container escape walk every trust boundary; ask whether each category applies; record the ones that do defenses map back: authentication · integrity · non-repudiation · confidentiality · availability · authorization

STRIDE

Spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege. The categories say what to look for, not what to do. Other frameworks exist (PASTA, LINDDUN, OCTAVE); pick one and use it consistently. A two-year-old threat model is fiction.

Cryptographic primitives

All of cryptography is three operations

Symmetric: one shared keyhellox9$f…hellokey Kkey Kthe same key locks and unlocksfast: gigabytes a second per corebut how do strangers share K?Asymmetric: a key pairpublic keyprivate keyanyone: lock, checkowner: unlock, signstrangers can agree a key, and provewho they areabout 1,000× slower than symmetricHash: a fingerprintinput, any size32 bytesone changed bit changes all of itone-way: cannot be run backwardsno key at alldetects any changeOne HTTPS connection uses all threeasymmetric, once: agree a keysymmetric, for all the data: fasthash on every message: catch tamperingAll of cryptography is three operations, and every protocol is a combination of them.Never write these yourself: a correct algorithm becomes broken code when its timing leaks the key. Use a vetted library.MD5 and SHA-1 are broken. AES, ChaCha20, SHA-256, Ed25519 and X25519 are the current defaults.

Symmetric encryption hides data, asymmetric keys handle identity and key agreement, a hash fingerprints.

Cryptographic primitives · Going deeper · 1 of 2

The three crypto primitives — symmetric, asymmetric, hash Symmetric Asymmetric Hash one shared key · fast key pair · slow · identity no key · one-way fingerprint plaintext "hi" ciphertext 0xa9... key key key key encrypt decrypt "hi" AES · ChaCha20 message m signature σ private public sign verify valid / invalid RSA · ECDSA · Ed25519 · X25519 any input m digest H(m) one-way cannot recover m from H(m) SHA-256: 32 bytes SHA-256 · SHA-3 · BLAKE3

What each primitive does and does not do

Symmetric: AES, or ChaCha20 where AES hardware is absent. Asymmetric: Ed25519 for signatures and X25519 for key exchange are the modern defaults; ML-KEM and ML-DSA (2024) resist future quantum computers. A cryptographic hash resists finding an input for a digest, a second input with the same digest, or any colliding pair.

Cryptographic primitives · Going deeper · 2 of 2

AEAD — encrypt and authenticate together; tampering breaks the tag plaintext key nonce AAD m unencrypted, authenticated AEAD encrypt AES-GCM · ChaCha20-Poly1305 cipher + MAC in one pass ciphertext auth tag same length as m 16 bytes decrypt fails fast: any flipped bit in ciphertext, AAD, or tag breaks tag verification — receiver discards the message

Encrypt and authenticate together

Encryption alone hides data but lets an attacker flip bits undetected. AEAD constructions (AES-GCM, ChaCha20-Poly1305) add a tag so any change is rejected on decryption. The same key and nonce must never encrypt two messages: reuse leaks the plaintexts’ XOR and allows forgeries.

Digital signatures

A signature proves who sent it and that nothing changed

Alice signsmessage“transfer $100 to Bob”hashSHA-256 → 4f8c…a91dsignwith Alice’s private keysignature64 bytesmessage + signature travel together, over any channelBob checksreceived messagehash againfrom the bytes he receivedverifywith Alice’s public keytruefrom Alice, unchangedOne byte changed on the way → Bob’s hash differs → verify returns falseSigned by anyone without Alice’s private key → verify returns falseOnly the private key can sign; anyone with the public key can check. It proves who, and that nothing changed.The signature is bound to these exact bytes. This is how software updates, certificates and login tokens are trusted.It is not encryption: the message itself stays readable.

A digital signature: signed with a private key, verifiable by anyone holding the public key.

Digital signatures · Going deeper

Merkle tree — leaf hashes combine pairwise into a single root root = H(H12 || H34) H12 = H(H1 || H2) H34 = H(H3 || H4) H1 = H(d1) H2 = H(d2) H3 = H(d3) H4 = H(d4) d1 d2 d3 d4 data data data data inclusion proof for d3: send H4 and H12; verifier recomputes H34 then root, compares to known root

Hashes that prove membership

A Merkle tree combines leaf hashes pairwise up to a single root. Proving one leaf belongs takes about log₂(N) sibling hashes: twenty for a million leaves. Git, Certificate Transparency logs and BitTorrent use it. A hash chain is the linear case; it only detects tampering, so real chains add a signature or other witness.

Check yourself

pay Bob $100signed by Alicepay Bob $900same signatureverify?

Someone changes one character of a signed message on its way to Bob. What happens when Bob verifies?

Key exchange

Two strangers can agree on a secret in public

AliceSent in the open: an eavesdropper sees all of itBobagreed numbers: p = 23, g = 5picks a secret: a = 6picks a secret: b = 155⁶ mod 23 = 8A = 85¹⁵ mod 23 = 19B = 1919⁶ mod 23 = 28¹⁵ mod 23 = 2the shared secretthe same secreteavesdropper has 23, 5, 8, 19. Not 2.real numbers are hundreds of digits longTwo strangers can agree on a secret while everyone listens: mixing the numbers is easy, un-mixing them is not.This is Diffie–Hellman, run at the start of every HTTPS connection. Its one gap: it does not say who is at the other end.An attacker in the middle could run it with each side separately. Closing that gap is the job of certificates.

Diffie–Hellman key exchange: both sides derive the same secret from values an eavesdropper can see.

Key exchange · Going deeper

Diffie-Hellman key exchange — public transmissions, private secret Alice Bob Eve (eavesdropper) public channel private a (secret) private b (secret) A = g^a mod p visible to Eve B = g^b mod p also visible to Eve computes B^a mod p computes A^b mod p B^a = A^b = g^(ab) shared secret Eve has g^a and g^b but not g^(ab) discrete log is hard: recovering a from g^a takes exponential time at sufficient key sizes

Key exchange and its gap

Reversing the computation is the discrete-logarithm problem, which is computationally hard at real sizes. Plain Diffie–Hellman does not authenticate: an active attacker can run it separately with each side and sit in the middle. TLS closes this by having the server sign the exchange with a certificate key.

Certificates and PKI

A certificate ties a public key to a name you can check

bank.comits public keysigned by: Intermediate CAIntermediate CAits public keysigned by: Root CAsignssent by the server at the start of the connectionRoot CAalready on your device:one of about 100signsshipped with your OS or browserThe browser checks four things, and any failure aborts the connectionSignaturesevery link, up to a rootNameit really says bank.comDatesnot expiredRevocationnot withdrawnThe weak point: any root can sign for any name. So every certificate must be published in a public, append-only logthat site owners watch. DigiNotar was breached in 2011 and its certificates used to spy on Gmail users in Iran.A certificate is a signed statement that “this public key belongs to bank.com”, traceable to a key you already trust.Without it, key exchange agrees a secret with whoever answered. With it, the server signs the handshake with the matchingprivate key. Session keys are fresh every time, so a certificate key that leaks later exposes no past traffic.

A certificate is a signed claim “this key belongs to this name”, chained to a root your device already trusts.

Certificates and PKI · Going deeper · 1 of 2

A certificate chain from leaf to trust anchor Leaf certificate CN = bank.com + server's public key signed by Intermediate CA Let's Encrypt R3 issuing key, online signed by Root CA ISRG Root X1 offline · in trust store OS / browser trust store CT log (audit trail) validate: leaf signature → intermediate signature → root in trust store · check expiry, hostname, revocation

The chain and its weak point

Certificates follow X.509: subject, public key, issuer, validity, extensions. Any root can sign for any domain, so the model is as weak as its weakest authority. Certificate Transparency requires every certificate to be logged publicly; CAA DNS records declare which authority may issue for a domain.

Certificates and PKI · Going deeper · 2 of 2

TLS 1.3 1-RTT handshake — three primitives composed Client Server ClientHello + key_share (X25519 pubkey) supported ciphers, ALPN, SNI, random nonce ServerHello + key_share + {cert, sig, finished} chosen cipher · server's X25519 pubkey · cert chain server signs handshake transcript with cert's private key Both derive shared secret from ECDHE HKDF → traffic keys for AES-GCM / ChaCha20-Poly1305 Finished + encrypted application data first payload byte arrives in 1 RTT encrypted application data primitives used: X25519 (exchange) · Ed25519/RSA (cert sig) · AES-GCM (bulk) · HKDF (derive)

TLS 1.3: the three primitives composed

Client and server run an authenticated Diffie–Hellman exchange, derive symmetric session keys, then switch to AEAD. TLS 1.3 needs one round trip and removed the legacy weaknesses. Forward secrecy comes from the throwaway exchange keys: the certificate key only signs, so its later leak exposes no past sessions.

Password storage

Store passwords so that every guess is expensive

passwordsaltrandom, per userargon2idhalf a second and 64 MBper attempt, on purposestoredsalt + resultthe password is discardedLogin repeats the samefunction with the same saltand compares the results.The table is stolen. How fast can the attacker guess?plain SHA-25610 billion guesses a second on one GPU, against every user at once: a dictionary falls in secondsargon2id + salta few hundred a second, one user at a time: the same dictionary takes weeks, per userStore passwords with a hash that is slow and memory-hungry on purpose, salted per user.Half a second costs a real user nothing at login and costs an attacker everything across billions of guesses. Needingmemory is what defeats GPUs, and the per-user salt means no work is shared between users. Never use a plain fast hash.

A password hash must be slow, memory-hard and salted: argon2id, never a plain fast hash.

Password storage · Going deeper

Password hashing — same input, three very different cost profiles password = "correct horse battery staple" SHA-256 bcrypt argon2id fast hash high cost factor memory-hard ≈ 1 µs per hash ≈ 10 billion / sec on GPU ≈ 250 ms per hash ≈ 4 / sec per core ≈ 500 ms + lots of RAM GPU-resistant offline crack of leaked DB: hours offline crack of leaked DB: centuries per password offline crack of leaked DB: centuries + RAM-bound always salt per-user; raise the cost factor over time as hardware improves

Three cost profiles

argon2id and scrypt are memory-hard: every guess must allocate megabytes, and GPU memory bandwidth becomes the bottleneck. bcrypt is iteration-hard only, acceptable at a high cost factor for legacy systems. The per-user salt prevents precomputed tables. Compare results in constant time.

Check yourself

ASHA-256 of the passwordBSHA-256 of the password + a per-user saltCargon2id of the password + a per-user salt

A user table leaks. Which way of storing passwords slows the attacker the most?

Passkeys and phishing

A passkey cannot be phished; a typed code can

Password + 6-digit codeYoulook-alike sitebank-login.examplereal bankattacker is logged inthe code is valid for 30 syou type both into the fake site, which passes them straight on to the real onePasskeyYour devicea private key per sitelook-alike sitebank-login.examplereal bankthe device signs the bank’s challenge together with the address of the site that asked: “bank-login.example”rejectedsigned for the wrong siteA passkey signs the address of the site that asked, so a fake site gets a signature that is useless anywhere else.Codes from an app stop leaked passwords but not phishing, because a person can be tricked into typing them anywhere.Passkeys (WebAuthn) resist phishing by construction, not by vigilance. SMS codes are weaker still: SIM swaps hijack them.

A passkey signs the requesting site’s address along with the challenge, so a look-alike site gets nothing usable.

OAuth

Let an app act for you without giving it your password

YouThe appSign-in serviceYour data (API)1 sends you to the sign-in service2 you log in there and approve “read my calendar”3 a one-time code4 code + the app’s own proofshort-lived access token5 each request carries the tokenThe app never sees your password. It receives a short-lived token that allows only what you approved.This is OAuth 2.0. An access token says what its holder may do, not who they are: identity is a separate signed ID token(OpenID Connect). Authentication asks who you are; authorisation asks what you may do. Confusing them is the classic bug.

OAuth hands an app a limited, short-lived token. Authentication and authorisation are different questions.

OAuth · Going deeper · 1 of 2

OAuth 2.0 authorization code flow with PKCE User Client app Authorization server Resource server click "log in" /authorize?...&code_challenge=S256(verifier) login + consent screen enter password / passkey, approve redirect ?code=xyz POST /token code=xyz, code_verifier access_token (+ refresh_token) GET /api/data, Authorization: Bearer ... user's resource PKCE binds the code to the client that started the flow — without it, a stolen code can be redeemed by anyone

Authorisation code flow with PKCE

PKCE binds the code to the app that requested it, so an intercepted code is useless. OIDC adds an id_token, a signed statement about the user, alongside the access token. Authorisation models: roles (RBAC), attributes (ABAC), or capabilities where holding the token is the permission. Policy increasingly lives in code (OPA, Cedar).

OAuth · Going deeper · 2 of 2

JWT structure — three base64url segments separated by dots eyJhbGciOi...XVCJ9 . eyJzdWIiOi...MzkwMjJ9 . SflKxw...sw5c Header Payload (claims) Signature base64url JSON base64url JSON base64url bytes { "alg": "RS256", "typ": "JWT", "kid": "2026-q2" } { "iss": "auth.example", "sub": "user-1234", "aud": "api.example", "iat": 1714000000, "exp": 1714003600, "scope": "read:orders" } sign( base64url(header) + "." + base64url(payload), private_key ) Footguns accepting alg=none · verifying HS256 with the RSA public key · skipping aud / iss / exp checks letting the token's own header pick the algorithm — pin the algorithm at the verifier instead

Inside a JWT

Three base64url parts: a header naming the algorithm, a payload of claims, and a signature over both. Anyone can read the claims, so no secrets go in. Pitfalls: accepting alg none, letting the token choose its own algorithm, skipping the audience, issuer or expiry checks. Pin the algorithm and issuer at the verifier.

Zero trust

Being inside the network proves nothing: check every request

Castle and moatinside the network = trustedphished laptopfilespayrollwikibuilddatabaseone stolen login, and the attacker walks everywherea VPN that checks once at the door is this modelZero trustphished laptopfileschecks every callpayrollchecks every callwikichecks every callbuildchecks every calldatabasechecks every call✕✕each request is checked: who, which device, what contexta stolen login reaches only what that one user may reachBeing inside the network proves nothing. Verify identity, device and context on every single request.The perimeter stopped being real with cloud services, remote work and personal devices, and moving sideways after onebreak-in drove most large breaches of the 2010s. Zero trust is a design, built from strong identity and per-service policy.

Zero trust replaces the trusted internal network with identity and policy checked on every call.

Zero trust · Going deeper

Castle-and-moat vs zero trust Castle-and-moat Zero trust perimeter = trust boundary "corporate network" app db app app app app implicit trust between services one breached host → lateral movement VPN trust = "you are inside" no perimeter; identity is the boundary app db app app app app mTLS mTLS mTLS mTLS every request: authn + authz + encrypted device posture · context · least privilege trust = "you proved it, again, just now" Google's BeyondCorp was the canonical implementation; SASE / SSE products package the controls

What zero trust is built from

It is not a product. The pieces are identity-aware proxies, workload identity (SPIFFE, cloud IAM roles), mutual TLS between services, usually via a service mesh, and a policy decision point at every service.

Injection

Injection: data that gets read as code

The attacker types this into the “name” field:x' OR '1'='1Query built by gluing strings"… WHERE name = '" + input + "'"… WHERE name = 'x' OR '1'='1'the input became part of the command: every row matchesQuery with a placeholder… WHERE name = ?name must equal the text x' OR '1'='1the command was fixed first; the input can only be a valueThe same shape everywhere: untrusted input reaches something that reads it as instructionsSQL injectionread as a queryCross-site scriptingread as page scriptShell injectionread as a commandPrompt injectionread as instructions (lesson 11)Injection is data being parsed as code. The fix is structural: keep command and data in separate channels.No escaping rule is as reliable as a placeholder. In the browser the equivalent is a template engine that encodes outputfor its context, backed by a Content Security Policy that tells the browser which scripts may run at all.

Injection is untrusted input interpreted as instructions. Placeholders keep data and command apart.

Injection · Going deeper

SQL injection — string concatenation vs parameterized query Vulnerable: string concat Safe: parameterized query "SELECT * FROM users WHERE name='" + n + "'" n = "x' OR '1'='1" attacker-supplied input SELECT * FROM users WHERE name='x' OR '1'='1' parser sees code, not data → returns every row "SELECT * FROM users WHERE name = ?" params = ["x' OR '1'='1"] same attacker input SELECT ... WHERE name = ? [? bound to literal "x' OR '1'='1"] parser fixed at prepare time → matches no rows; data is data same shape applies to shell (argv arrays not strings), HTML (auto-escaping templates), LDAP, XPath

The OWASP Top 10, and the structural fix

The Top 10 lists the categories behind most real breaches, led by broken access control, cryptographic failures and injection. It is a map for design review, not a checklist. Cross-site scripting comes in reflected, stored and DOM-based forms; context-aware output encoding catches all three, and Content Security Policy is the browser-side backstop.

Check yourself

code"SELECT * FROM users WHERE name = '" + input + "'"inputx' OR '1'='1

This code runs with the input shown. What does the database do?

CSRF and cookies

Your browser sends your cookies even when an attacker asks

attacker.coma page you happen to openhidden formYour browserstill logged in to bank.combank.comsees a logged-in requestPOST /transferOrigin: https://attacker.comto=attacker_account&amount=10000Cookie: session=abc123← attached by the browser, automaticallyDefencesSameSite cookies, now the default:the browser leaves the cookie offrequests that start on another siteCSRF token:a value only bank.com’s own pages can readThe browser attaches your cookies to any request for that site, whoever caused it. No password is needed.The attacker never sees the reply; the harm is the side effect, money already moved. The server-side mirror image is SSRF:a URL your server is tricked into fetching from inside your network. Capital One lost 100 million records that way in 2019.

CSRF rides the cookies a browser attaches automatically. SameSite cookies and tokens close it.

CSRF and cookies · Going deeper · 1 of 2

CSRF — browser auto-attaches bank.com cookies to a request from attacker.com User attacker.com bank.com 1. user logs in to bank.com (session cookie set) 2. user visits attacker.com (different tab) <form action="bank.com/transfer" method="POST" hidden> <script>form.submit()</script> 3. browser sends POST + bank.com session cookie (automatic) cookie valid → transfer succeeds defenses: SameSite cookies · CSRF token · Origin/Referer check · re-auth on sensitive ops SameSite=Lax is the modern browser default — neutralizes most cross-site POSTs

The forged request in detail

The attacker never reads the response, since the same-origin policy hides it, but the side effect has already happened. A third defence is checking the Origin header on the server. Other header-level defaults worth shipping: HSTS to lock the browser to TLS, Subresource Integrity for third-party scripts, frame-ancestors against clickjacking.

CSRF and cookies · Going deeper · 2 of 2

SSRF — attacker pivots through a server-side fetcher into the internal network Attacker on the public internet App server URL preview / webhook / avatar fetcher / PDF render internal network (VPC) 169.254.169.254 cloud metadata · IAM creds 10.0.0.5:5432 internal Postgres redis.internal:6379 no auth on private net file:///etc/passwd local-file fetch url=… server fetches whatever URL it's told defense: deny private IP ranges · DNS pinning · egress proxy · IMDSv2 Capital One 2019: SSRF → cloud metadata → IAM creds → 100M records

SSRF: pivoting through your server

The attacker controls a URL the server fetches (a preview, a webhook, an avatar) and points it at internal addresses, such as the cloud metadata service at 169.254.169.254 that hands out credentials. The fix is an egress proxy that resolves DNS once, blocks private ranges and enforces an allow-list. Hiding endpoints is not a defence.

Summary

Security is built in layers, starting from a threat model

In practicecheck every request · separate data from commands · safe cookie defaultsProtocolsTLS and certificates · OAuth and ID tokens · passkeysPrimitivessymmetric encryption · key pairs · hashesFoundationa threat model, and the trust boundaries it revealsSecurity is a property of every layer, not a step at the end. The primitives are few; the bugs live in how they are combined.Written down in NIST FIPS 197 (AES) and 180-4 (SHA-2), TLS 1.3, OAuth 2.0, WebAuthn and the OWASP Top 10.

Threat model, three primitives, a few protocols, daily practice. Next: standards, how systems agree.

Summary · Going deeper

The security stack — foundations, primitives, protocols Foundations Primitives Protocols what to defend, from whom three building blocks composed defenses on the wire Threat model STRIDE Risk budget assets · adversary · goals six categories of harm cost of defense vs cost of loss Symmetric Asymmetric Hash AES-GCM · ChaCha20 Ed25519 · X25519 · RSA SHA-256 · BLAKE3 TLS 1.3 PKI / X.509 OAuth · OIDC Zero trust channel secrecy + integrity strangers prove identity delegated access · SSO verify every request Failure surfaces — where attacks actually land OWASP Top 10 supply chain (SLSA, SBOM) human / phishing web app vulnerabilities code you didn't write credentials, social engineering three primitives compose into every protocol; protocols compose into the defenses that meet the threat model

The security stack

Foundations come first: without a threat model the rest is busywork. Primitives are few. Protocols are where most engineering effort goes and where most bugs live. Algorithm standards come from NIST (FIPS 197, 180-4, 186-5, and 203 to 205 for post-quantum schemes).

Lesson complete

You finished “Security and Cryptography”

Answer the questions along the way to see your score here.

Open in a new tab