Security Foundations: Why Systems Get Hacked, CIA Triad, Defense in Depth, STRIDE
"Every access to every object must be checked for authority." — Jerome H. Saltzer and Michael D. Schroeder, The Protection of Information in Computer Systems, Proceedings of the IEEE (1975), principle c) Complete mediation
Summary: Security in system design is the discipline of deciding, before the code exists, what must stay secret, correct and available, who might try to break that, where they can reach in, and which layered controls stop, detect and repair each attempt. Focus: Why systems really get hacked (attacker economics, attack surface, misconfiguration, stolen credentials, unpatched and zero-day vulnerabilities, supply chain, social engineering, with Verizon DBIR numbers), the CIA triad plus authenticity, non-repudiation and accountability (and the Parkerian hexad), threat modelling (assets, trust boundaries, data flow diagrams, STRIDE per element with a worked web app + API + queue + database table, DREAD, CVSS v4, attack trees, abuse cases, MITRE ATT&CK), defense in depth, the Saltzer and Schroeder principles with zero trust, secure by default and shift left, preventive/detective/corrective controls, secrets and supply chain hygiene (SBOM, pinning, Sigstore, SLSA), the security design review, and compliance frameworks (SOC 2, ISO 27001, PCI DSS, GDPR) as design constraints. Learning goal: Draw a data flow diagram of any system with its trust boundaries, generate and triage its STRIDE checklist, place layered controls with a reason for each, apply the design principles to a concrete API, and run a security design review that ends with owners, residual risk and tests instead of a feeling.
This chapter is the map of the SD 07 Security group. It owns the vocabulary, the threat model and the layering; each sibling owns one mechanism in depth: Authentication (passwords, MFA, sessions), JWT, OAuth 2.0 and OIDC, Authorization models and zero trust, Cryptography, TLS, PKI and secrets, OWASP Top 10, DDoS and network segmentation, mTLS between services and Secure SDLC and incident response. Primitives (AES-GCM, signatures, KDFs) live in Cryptography Fundamentals; database hardening (roles, RLS, pgAudit) lives in Database Security; code-level secure design lives in Security by Design.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why attackers succeed, with numbers | Why it exists, How systems really get hacked |
| Saltzer and Schroeder, STRIDE, ATT&CK, CVSS history | Where it comes from |
| Attack surface and threat actors | Attack surface |
| Confidentiality, integrity, availability | CIA triad |
| Authenticity, non-repudiation, accountability, Parkerian hexad | Beyond CIA |
| Assets, trust boundaries, DFDs, the four questions | Threat modelling |
| Spoofing, Tampering, Repudiation, Information disclosure, DoS, Elevation | STRIDE per element |
| The worked table for web app + API + queue + DB | Worked STRIDE table |
| DREAD, CVSS v4, likelihood times impact | Scoring risk |
| Attack trees, abuse cases | Attack trees and abuse cases |
| Tactics and techniques | MITRE ATT&CK |
| Layers from edge to data | Defense in depth |
| Least privilege, fail-safe defaults, complete mediation and friends | Design principles |
| Zero trust in one block | Zero trust |
| Secure by default, shift left | Secure by default and shift left |
| Preventive, detective, corrective | Controls catalogue |
| Secrets in code and config | Secrets hygiene |
| SBOM, pinning, Sigstore, SLSA | Supply chain |
| SOC 2, ISO 27001, PCI DSS, GDPR | Compliance as constraints |
| The design review checklist | Security design review |
| What to do when it happens anyway | Incident basics |
| Exact knobs, status codes, vector strings | Mechanics |
| Code | Go, Laravel |
| Classic holes and their fixes | Solving the classic problems |
| Which control for which situation | Choosing |
| Monolith to distributed system | In architecture |
| Run the threat-model tool and the server | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The properties you protect, and the STRIDE threat that attacks each.
| Property | Plain words | STRIDE threat against it | Typical control |
|---|---|---|---|
| Confidentiality | Only the right people can read it | Information disclosure | Authorization, encryption, minimisation |
| Integrity | Nobody can change it unnoticed | Tampering | Validation, MACs and signatures, least privilege |
| Availability | It works when it is needed | Denial of service | Limits, timeouts, redundancy, backups |
| Authenticity | It is really who or what it claims to be | Spoofing | MFA, mTLS, signed tokens |
| Non-repudiation / accountability | An actor cannot deny an action, and every action traces to an actor | Repudiation | Audit logs, signatures, synchronised clocks |
| Authorization | Each actor does only what it is allowed to | Elevation of privilege | Policy check on every request, least privilege |
How breaches start (Verizon DBIR 2025, 12,195 confirmed breaches).
| Initial vector or factor | What the DBIR 2025 press release says | Design answer on this page |
|---|---|---|
| Credential abuse | Leading vector, 22% | MFA, rate limits against credential stuffing, short-lived tokens |
| Exploitation of vulnerabilities | 20%, up 34%, "zero-day exploits targeting perimeter devices and VPNs" | Patch cadence, small attack surface, zero trust instead of VPN-equals-trusted |
| Third-party involvement | "doubled to 30%" | Supply chain controls, vendor least privilege |
| Ransomware | Present in 44% of breaches | Tested offline backups, segmentation, detective controls |
| Human element | "significant overlap between social engineering and credential abuse" | Phishing-resistant MFA (passkeys), least privilege |
The threat-modelling loop (Threat Modeling Manifesto via OWASP).
| Question | Output | Tool on this page |
|---|---|---|
| What are we working on? | Data flow diagram with trust boundaries and assets | DFD, model.json |
| What can go wrong? | Threat list | STRIDE per element, attack trees, ATT&CK |
| What are we going to do about it? | Mitigate, eliminate, transfer or accept each threat | Controls catalogue, principles |
| Did we do a good enough job? | Reviewed model, tests for each mitigation | Design review, CI gate in Go |
Layers and principles worth reciting.
| Layer (outside in) | Example controls | Principle it leans on |
|---|---|---|
| Edge | CDN, WAF, DDoS protection, TLS | Economy of mechanism (one hardened entry) |
| Network | VPC segmentation, security groups, mTLS | Least privilege for packets |
| Identity | MFA, SSO, workload identity | Separation of privilege |
| Application | Authorization per request, validation, limits | Complete mediation, fail-safe defaults |
| Data | Least-privilege roles, encryption at rest, backups | Least privilege, defense in depth |
| Monitoring | Audit logs, alerts, incident response | Compromise recording, accountability |
The picture is the shape of the whole chapter: the attacker is assumed to get through some layers, so every layer is designed as if the one above it has already failed.
Why it exists
A system is attacked because someone gains more from breaking it than it costs them. That is the whole economics: an attacker with a list of a billion leaked passwords pays almost nothing per login attempt, a ransomware crew pays nothing for a misconfigured backup server it finds by scanning, and a nation-state pays a lot for a zero-day because the prize justifies it. Defenders do not need to be unbreakable; they need to make every path more expensive than its prize, and to notice quickly when someone pays the price anyway.
Security is a design property, not a feature you add later, because the expensive mistakes are architectural: a database reachable from the internet, a single shared admin account, an API that trusts a tenant_id from the request body, a network where everything inside the VPN trusts everything else. None of these is a bug a scanner finds in a line of code; each is a decision on a diagram.
| Security as an afterthought | Security as a design input |
|---|---|
| Pen test finds the IDOR two weeks before launch | The DFD shows the trust boundary and the per-object check is a requirement |
| One perimeter (VPN, firewall), flat inside | Layers; each assumes the outer one failed |
| Shared admin account, long-lived keys | Named identities, short-lived credentials, least privilege |
| Errors print stack traces | Generic errors outside, details in an access-controlled log |
| "We will add logging later" | Audit events are part of the API contract |
| Compliance is a yearly scramble | SOC 2 / PCI DSS / GDPR controls are traced to components |
The analogy reused on this page: a bank branch. The vault holds the asset (confidentiality, integrity). The door, the guard, the teller window and the vault door are layers (defense in depth). The teller checks your ID for every withdrawal, not only the first one (complete mediation). The vault needs two keys held by two people (separation of privilege and duties). The cameras do not stop a robbery but make it provable and traceable (detective controls, non-repudiation). Insurance and the cash reserve let the branch reopen tomorrow (corrective controls, availability). A threat model is the walk-through the manager does with a floor plan, asking at every door "who could pretend to be someone else here, what could they change, what could they take, how could they stop us working?"
Three common misunderstandings, up front
- "Attackers mostly use clever zero-days." The DBIR 2025 press release puts credential abuse (22%) ahead of exploitation of vulnerabilities (20%) as initial vectors, and most exploited vulnerabilities are known ones. The 2026 DBIR landing page says software vulnerabilities now beat stolen passwords as the top way in, which is still mostly about patching speed and exposure, not genius.
- "We use HTTPS, so we are secure." TLS protects a data flow against tampering and disclosure in transit. It does nothing against a forged identity, a missing authorization check, a leaked database dump or a flood of requests. It is one control for three of eighteen cells in the STRIDE grid.
- "Threat modelling needs a security team and a week." The OWASP cheat sheet describes four questions; for one feature they take an hour around a whiteboard, and the model can live in the repository as data (the Go tool on this page does exactly that).
Where it comes from
Saltzer and Schroeder, 1975. The Protection of Information in Computer Systems placed potential violations in three categories: "Unauthorized information release", "Unauthorized information modification" and "Unauthorized denial of use". Those are confidentiality, integrity and availability under older names. The same paper lists eight design principles ("Economy of mechanism, fail-safe defaults, complete mediation, open design, separation of privilege, least privilege, least common mechanism, and psychological acceptability") plus two borrowed from physical security, work factor and compromise recording. Fifty years later they are still the vocabulary of every design review.
The CIA triad and the Parkerian hexad. The triad became the standard teaching frame; Donn B. Parker proposed in 1998 to add possession or control, authenticity and utility (secondary source: Wikipedia's Parkerian Hexad article). Regulation adopted the triad's words: GDPR Article 32 asks for "the ability to ensure the ongoing confidentiality, integrity, availability and resilience of processing systems and services".
STRIDE at Microsoft. OWASP's cheat sheet: "STRIDE is a mature and popular threat modeling technique and mnemonic originally developed by Microsoft employees." Microsoft's Security Development Lifecycle and the Microsoft Threat Modeling Tool built the per-element approach on data flow diagrams; Adam Shostack's Threat Modeling: Designing for Security (Wiley, 2014; a second edition, Designing for Security in an AI World, is announced by his site for February 2027) made it a teachable method. (The Microsoft Learn pages could not be fetched from this machine; the per-element chart below is the widely published SDL chart, reproduced from our knowledge and implemented in code, not quoted.)
DREAD, then CVSS. DREAD (Damage, Reproducibility, Exploitability, Affected users, Discoverability) rated each category 1 to 10 and summed them (secondary source: Wikipedia). It fell out of favour for being subjective; the OWASP threat modelling process page notes that qualitative values "help avoid the ranking becoming overly subjective". FIRST's CVSS became the industry score for vulnerabilities; version 4.0 "consists of four metric groups: Base, Threat, Environmental, and Supplemental".
Attack trees, ATT&CK, zero trust, supply chain. Bruce Schneier's Attack Trees (Dr. Dobb's Journal, December 1999) gave goal-rooted trees with AND and OR nodes. MITRE ATT&CK became "a globally-accessible knowledge base of adversary tactics and techniques based on real-world observations". NIST SP 800-207 (August 2020) defined zero trust architecture. After SolarWinds-style compromises, SBOMs (CISA), SLSA build levels and Sigstore keyless signing made the supply chain a first-class design topic, and OWASP Top 10:2025 lists "A03 Software Supply Chain Failures".
Year Idea What changed in practice
1 1975 Saltzer & Schroeder Three violation categories (CIA) and eight design principles
2 1998 Parkerian hexad (Parker) Possession, authenticity, utility added to CIA
3 1999 Schneier, Attack Trees Goal-rooted AND/OR trees with priced leaves
4 - STRIDE and DREAD at Microsoft (SDL) Per-element threat checklists on DFDs
5 2014 Shostack, Threat Modeling (Wiley) The method taught outside Microsoft
6 - MITRE ATT&CK Shared names for real adversary techniques
7 - GDPR (Articles 25 and 32) "Data protection by design and by default" becomes law
8 2020 NIST SP 800-207 (August 2020) No implicit trust from network location
9 2023 FIRST CVSS v4.0 Base, Threat, Environmental, Supplemental groups
10 2024 NIST CSF 2.0 (26 Feb 2024) GOVERN added to Identify/Protect/Detect/Respond/Recover
11 2025 OWASP Top 10:2025 Supply chain failures enter at A03The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline or request flow, real scenarios, how products provide it, and the fix.
Attack surface and threat actors Must-know
In plain words: the attack surface is every place an attacker can send input or reach in: every URL, port, queue, upload form, admin panel, CI token, third-party SDK and person with access. A threat actor is whoever might use it, with a motive and a budget.
Common misunderstanding: "Our attack surface is the public API." It also includes the staging environment with production data, the forgotten /debug endpoint, the S3 bucket with public ACLs, the CI runner that holds deploy keys, the support staff who can reset passwords, and every dependency you install.
Definition: attack surface = the set of entry points (and exit points) across trust boundaries, plus the assets reachable from each. Threat actor = an adversary class characterised by motive (money, espionage, activism, revenge, curiosity), capability (script, crew, nation-state) and access (outsider, customer, insider, partner).
Attacker path through a typical web stack (attack surface enumerated)
1 scan: *.example.com -> finds staging.example.com (forgotten, no WAF)
2 staging /actuator/env -> leaks DB_PASSWORD (misconfiguration, information disclosure)
3 DB port 5432 open to 0.0.0.0/0 on the staging security group (misconfiguration)
4 staging DB is a nightly copy of production (asset outside its boundary)
5 exfiltrate customers table -> breach notification under GDPR Art. 33/34
Every step used an entry point nobody listed in the design.Real scenarios: a marketing subdomain on an old CMS; a mobile app that ships an API key; a partner SFTP drop that runs a parser on uploaded files; a support tool that impersonates users with no audit trail; a GitHub Actions workflow triggered by pull requests from forks that can read secrets.
| Threat actor | Motive | Typical capability | What it usually goes for |
|---|---|---|---|
| Opportunistic criminal | Money at scale | Automated scanning, leaked credential lists | Exposed services, credential stuffing, ransomware |
| Organised crew | Money, extortion | Custom tooling, initial-access brokers | VPN and edge-device exploits, backups, domain admin |
| Nation-state | Espionage | Zero-days, supply chain operations | Long-term access, source code, identity providers |
| Insider (malicious or careless) | Money, revenge, mistake | Legitimate access | Bulk exports, misconfigured sharing |
| Customer or partner | Fraud, competitive data | Valid accounts | IDOR, business-logic abuse, scraping |
Fix / how to use it: keep an inventory (DNS, cloud accounts, endpoints, queues, CI), delete what you do not need (Shostack's "eliminate"), put every remaining entry behind the same edge and identity layers, and list actors explicitly in the threat model so "who would bother?" becomes a written assumption.
How systems really get hacked: the initial access vectors Must-know
In plain words: most break-ins use one of five doors: a password someone else already has, a known hole nobody patched, a setting left open, a trusted supplier that was itself compromised, or a person who was tricked.
Common misunderstanding: "Phishing is a user-training problem, not an architecture problem." Phishing-resistant authentication (passkeys, FIDO2, mTLS for services), least privilege and short-lived sessions are architecture; they make the phished credential worth less.
Definition: an initial access vector is the first technique that gives an attacker a foothold. The ones every design must answer:
| Vector | What happens | Evidence | Design control |
|---|---|---|---|
| Credential stuffing | Leaked username/password pairs tried against your login | ATT&CK T1110.004: "Adversaries may use credentials obtained from breach dumps of unrelated accounts to gain access to target accounts through credential overlap." | MFA, per-account and per-IP throttling, breached-password checks, bot detection |
| Phishing | A message tricks a person into giving credentials or running code | ATT&CK T1566: "All forms of phishing are electronically delivered social engineering." | Passkeys/FIDO2, least privilege, attachment sandboxing, reporting button |
| Misconfiguration | A setting exposes data or control (public bucket, default password, debug mode) | OWASP Top 10:2025 "A02 Security Misconfiguration" | Secure-by-default templates, policy as code, config scanning |
| Unpatched or zero-day vulnerability | Code flaw exploited before or after a fix exists | DBIR 2025: exploitation up 34%, focus on "perimeter devices and VPNs" | Patch SLAs, small surface, WAF virtual patching, segmentation |
| Supply chain attack | A dependency, build tool or vendor is compromised | ATT&CK T1195: "Adversaries may manipulate products or product delivery mechanisms prior to receipt by a final consumer" | Pinning, SBOM, signature verification, vendor least privilege |
| Social engineering beyond email | Help-desk password resets, SIM swaps, fake vendors | DBIR 2025: overlap of social engineering and credential abuse | Out-of-band verification, step-up auth for resets |
Credential stuffing against /login, no throttling (timeline)
1 t=0 attacker loads 1,000,000 leaked pairs from an unrelated breach
2 t=0-60m 280 req/s from a residential proxy pool, ~1 attempt per IP per minute
3 t=60m 0.1% reuse rate (illustrative) -> 1,000 valid accounts
4 t=61m logins succeed; nothing alerts because no single IP looks noisy
5 t=2d stored cards used, loyalty points drained, support flooded
Controls that break it: MFA (step 4), per-account limit + breached-password check (step 3),
anomaly alert on failed-login ratio across IPs (step 2).Real scenarios: a loyalty programme drained by credential stuffing; a ransomware crew entering through an unpatched VPN appliance; a typosquatted npm package stealing CI secrets; a contractor's laptop with a saved production kubeconfig.
Fix / how to use it: in the design review, ask for each entry point which of the five doors it offers, and require one preventive and one detective control per door. Credential and session mechanics are in Authentication; vulnerability classes in OWASP Top 10.
The CIA triad Must-know
In plain words: confidentiality means only the right people can read it, integrity means nobody can change it without being noticed or authorised, availability means it is there when it is needed.
Common misunderstanding: "Integrity means the data is encrypted." Encryption alone (for example AES-CBC without a MAC) gives confidentiality; integrity needs a MAC, a signature, an authenticated cipher (AES-GCM) or access control on writes. Laravel's encrypter makes this explicit: values are encrypted with AES-256-CBC and "signed using a message authentication code (MAC)".
Definition: the three security objectives of information and systems. Saltzer and Schroeder defined their violations: unauthorized information release (confidentiality), unauthorized information modification (integrity, which "does not require that the intruder see the information he has changed"), and unauthorized denial of use (availability).
One order, three properties (request flow)
1 Browser -> POST /orders {card, address} C: TLS in transit, card tokenised at the PSP
2 API validates, writes orders row I: validation, DB role cannot UPDATE amount after capture
3 API -> queue "order.placed" -> worker I: message signed or broker ACL; C: no card in the message
4 Worker -> PSP capture A: timeout + retry with idempotency key
5 Black Friday: 20x traffic A: rate limits, autoscaling, load sheddingReal scenarios: confidentiality, a leaked customer export; integrity, a price changed in transit or an attacker editing their own invoice amount; availability, ransomware encrypting the database or a regex that spins one CPU per request. The three conflict: more replicas and backups (availability) create more copies to protect (confidentiality); strict input rejection (integrity) can lock users out (availability).
| Property | Measured as | Typical design control | Product example |
|---|---|---|---|
| Confidentiality | Who can read what; data classification | Authorization, encryption at rest and in transit, minimisation | AWS KMS, PostgreSQL RLS, Laravel encrypted cast |
| Integrity | Unauthorised changes detected or prevented | Validation, MACs/signatures, write permissions, audit | Signed URLs (Laravel), Sigstore signatures, PostgreSQL grants |
| Availability | SLO, RTO/RPO | Redundancy, limits, timeouts, backups | Cloudflare/AWS Shield, Go http.Server timeouts, throttle middleware |
Fix / how to use it: classify data (public, internal, confidential, restricted), write the three properties per asset in the threat model, and pick controls per property; one control rarely serves all three. The cryptographic tools are in Cryptography in Practice.
Beyond CIA: authenticity, non-repudiation, accountability, Parkerian hexad Important
In plain words: authenticity is "this really came from who it says"; non-repudiation is "they cannot later deny they did it"; accountability is "every action traces back to one actor".
Common misunderstanding: "Our logs give us non-repudiation." Ordinary application logs that admins can edit, with a shared service account as the actor, give neither accountability nor non-repudiation. You need a named identity per actor, tamper-evident storage, and synchronised clocks; for legal-grade non-repudiation, a signature only the actor could have produced.
Definition: authenticity: the property that an entity or data is genuine (verified by authentication and integrity checks). Non-repudiation: assurance that the sender or actor cannot deny the action (signatures, append-only signed logs). Accountability: actions of an entity can be traced uniquely to it. OWASP's STRIDE table lists "Accounting" as what Repudiation violates. The Parkerian hexad (Parker, 1998; secondary source) has six attributes: confidentiality, possession or control, integrity, authenticity, availability, utility. Possession covers "they have our encrypted backup tape even if they cannot read it"; utility covers "we have the data, but the key is lost so it is useless".
Repudiation dispute (two actors)
1 10:02 support agent A uses shared account "support" to refund order 42
2 10:05 refund of 9,000 EUR lands on an attacker card
3 +3d finance asks who did it; log says actor=support, ip=office NAT
4 A and B both deny it; no evidence distinguishes them
With named accounts + audit row {actor: A, action: refund, order: 42, request_id}
in an append-only table, step 4 has an answer (accountability), and a
step-up confirmation signed with A's passkey gives non-repudiation.Real scenarios: payment approvals (two-person rule plus signed approval), contract signing, admin impersonation tools, data exports, configuration changes in production, API calls between companies (signed webhooks).
| Need | Weak version | Strong version |
|---|---|---|
| Authenticity of a user | Password only | Phishing-resistant MFA, device binding |
| Authenticity of a service | Shared API key | mTLS or workload identity with short-lived certificates |
| Authenticity of a message | Plain JSON over HTTPS | HMAC or signature over the body plus timestamp (webhooks) |
| Accountability | Shared accounts, mutable logs | Named identities, append-only audit table, central log store |
| Non-repudiation | "It is in our logs" | Actor's private-key signature, transparency log (Rekor for artifacts) |
Fix / how to use it: add an "actor" to every write path, write audit events to a store the application role cannot modify (the SQL in Mechanics), and use signatures where a third party must be convinced.
Threat modelling: assets, trust boundaries and data flow diagrams Must-know
In plain words: draw what you are building, mark where trust changes, list what is valuable, then ask what can go wrong at each place.
Common misunderstanding: "A threat model is a document you write once for the auditors." OWASP: "A threat model is something that should be maintained, updated and refined alongside the system." If it is not in the repository next to the code, it is out of date by the next sprint.
Definition: OWASP: threat modelling is "a structured, repeatable process used to gain actionable insights into the security characteristics of a particular system". Its four questions (Threat Modeling Manifesto) are "What are we working on?", "What can go wrong?", "What are we going to do about it?", "Did we do a good enough job?". The model has:
| DFD element | Shape | Meaning | Examples |
|---|---|---|---|
| External entity | Rectangle | Outside your control, interacts through an entry point | Browser user, payment provider, partner API |
| Process | Circle | Code you run that transforms data | Web app, API, worker, Lambda function |
| Data store | Two parallel lines | Data at rest; OWASP: "Data stores do not modify the data, they only store data." | PostgreSQL, S3 bucket, Redis, queue backlog |
| Data flow | Arrow | Data moving between elements | HTTPS request, SQL connection, AMQP message |
| Trust boundary | Dashed line | OWASP: "Boundaries show any location where the level of trust changes." | Internet/DMZ, app zone/data zone, tenant A/tenant B, CI/prod |
An asset is anything worth protecting: data (PII, card data, credentials, audit logs), capabilities (issuing refunds, deploying code), and reputation or availability itself.
One-hour threat-modelling session for a new "share invoice by link" feature
1 0-10m draw the DFD: user -> web -> API -> invoice store; new flow: anonymous -> download URL
2 10-15m mark boundaries: the anonymous flow crosses internet -> app with NO session
3 15-40m STRIDE the new elements: S (who is the downloader?), T (can the id be changed?),
I (can links be guessed or leak via Referer?), D (bulk download?), R (who shared?)
4 40-55m responses: signed + expiring URL (S, T), Referrer-Policy (I), throttle (D), audit row (R)
5 55-60m owners and tests: each mitigation becomes a ticket with an acceptance testReal scenarios: a new public endpoint; a new third-party integration; moving a component to another network zone; adding a queue between services (new store and two new flows); introducing an LLM tool that can call internal APIs.
Fix / how to use it: keep the DFD as data (the model.json in Go), re-run the checklist when the diagram changes, and record responses as Shostack's four options quoted by OWASP: mitigate, eliminate, transfer, accept. Other methods exist for other questions: LINDDUN for privacy, PASTA for business impact, OCTAVE for organisational risk, VAST for many teams (OWASP lists all of them); STRIDE is the default for a technical design.
STRIDE per element Must-know
In plain words: six questions, each the opposite of a property you want: can someone pretend (Spoofing), change (Tampering), deny (Repudiation), read (Information disclosure), stop (Denial of service), or gain powers (Elevation of privilege)?
Common misunderstanding: "Apply all six letters to every box." The per-element approach applies only the letters that make sense for the element type, which keeps the list honest and short. A data flow cannot repudiate anything; an external entity is outside your code so you do not ask whether its memory can be tampered with.
Definition: STRIDE groups threats into six categories, each "a violation of a desirable security attribute" (OWASP):
| Letter | Threat | Violates (OWASP wording) | OWASP example | First controls |
|---|---|---|---|---|
| S | Spoofing | Authentication | "An attacker steals the authentication token of a legitimate user and uses it to impersonate the user." | MFA, mTLS, token binding, short TTLs |
| T | Tampering | Integrity | "An attacker abuses the application to perform unintended updates to a database." | Validation, MAC/signature, least privilege on writes |
| R | Repudiation | Accounting | "An attacker manipulates logs to cover their actions." | Append-only audit, central log store, signatures |
| I | Information disclosure | Confidentiality | "An attacker extracts data from a database containing user account info." | Authorization, encryption, generic errors, minimisation |
| D | Denial of service | Availability | "An attacker locks a legitimate user out of their account by performing many failed authentication attempts." | Rate limits, timeouts, body limits, quotas, autoscaling |
| E | Elevation of privileges | Authorization | "An attacker tampers with a JWT to change their role." | Policy check per request, signed tokens validated, least privilege |
The per-element chart (the convention from Microsoft's SDL and Shostack's book, implemented in threatmodel.Applicable): external entities get S and R; processes get all six; data stores get T, I, D, and R when they hold logs; data flows get T, I, D.
STRIDE walk over one flow: "web app -> Orders API" crossing DMZ -> app zone
1 S can a non-web caller reach the API and claim to be the web app? -> mTLS / workload identity
2 T can the body be changed between them? -> TLS (mTLS), signed internal tokens
3 I can someone on the path read it? -> TLS
4 D can the web tier flood the API? -> per-caller limit, timeouts
5 (R and E are asked on the two processes at each end, not on the flow)Real scenarios: S, a forged X-User-Id header trusted behind a proxy; T, a client-side price field; R, a support refund with no actor; I, a stack trace with the DB DSN; D, a /search endpoint with an unbounded regex; E, a role field accepted by mass assignment.
Fix / how to use it: generate the checklist from the DFD (the Go tool prints it as a Markdown table), answer each row with a control id or an explicit acceptance, and fail CI on open high-severity rows.
The worked STRIDE table: web app + API + queue + database Must-know
In plain words: the same shop as the diagram, one row per element and letter that matters, each with a concrete threat and the control that answers it.
Common misunderstanding: "The queue is internal, so it needs nothing." A queue is a data store (backlog at rest) plus two flows. A worker that trusts any message on the queue turns "can publish to the queue" into "can ship orders for free".
Definition: the threat register for the system in the DFD figure. Element types follow the per-element chart; severity follows the triage rule in generate.go (sensitive asset and boundary crossing gives high).
| Element (type) | STRIDE | Concrete threat | Control | Control type |
|---|---|---|---|---|
| Customer (entity) | S | Credential stuffing takes over accounts | MFA, per-account throttle, breached-password check | Preventive |
| Customer (entity) | R | "I never placed that order" | Audit row with session id, device, IP; email receipt | Detective |
| Browser to web (flow) | T, I | Session cookie stolen on hostile Wi-Fi | TLS, HSTS, Secure + HttpOnly + SameSite cookies | Preventive |
| Browser to web (flow) | D | Request flood, Slowloris | CDN/WAF rate rules, ReadHeaderTimeout, body limits | Preventive |
| Web app (process) | T | CSRF makes the browser post a change | Laravel PreventRequestForgery (Sec-Fetch-Site, then token) | Preventive |
| Web app (process) | I | Stack trace with secrets on error | APP_DEBUG=false, generic error page, recover middleware | Preventive |
| Web app (process) | E | Mass assignment sets role=admin | $fillable, validated input only | Preventive |
| Web to API (flow) | S | Something else inside the VPC calls the API | mTLS or signed service token (workload identity) | Preventive |
| Orders API (process) | E | IDOR: GET /invoices/43 returns another tenant's invoice | Policy check per object (complete mediation), 404 for foreign ids | Preventive |
| Orders API (process) | D | One customer's export starves everyone | Per-user quotas, separate limiter for exports, timeouts | Preventive |
| Orders API (process) | R | Admin deletes an invoice silently | Audit event with actor, append-only store | Detective |
| API to queue (flow) | T | Forged "order.paid" message published by a compromised service | Broker ACL per producer, signed message envelope | Preventive |
| Order queue (store) | I | Messages carry full card data and sit for days | Only token ids in messages, encryption at rest, retention limit | Preventive |
| Order queue (store) | D | Queue filled by a poison loop | Max length, DLQ, alert on depth | Detective / corrective |
| Worker (process) | E | Worker's DB role can drop tables | Least-privilege role: INSERT/UPDATE on two tables only | Preventive |
| API to DB (flow) | I | Plaintext DB connection inside the VPC | TLS with sslmode=verify-full | Preventive |
| Orders DB (store) | I | Snapshot shared publicly or stolen backup | Encryption at rest (KMS), private snapshots, least privilege | Preventive |
| Orders DB (store) | T, D | Ransomware encrypts the database | Point-in-time recovery, immutable off-account backups, restore drills | Corrective |
| Audit log (store) | R, T | Attacker deletes their trail | Append-only grants + trigger, hash chain, ship to separate account | Preventive / detective |
| Worker to PSP (flow) | S | Webhook from a fake "payment provider" marks orders paid | Verify the provider's webhook signature and timestamp | Preventive |
Real scenarios: this is the table you bring to the design review for any CRUD + async system; swap the PSP for a shipping partner or an email provider and most rows stay.
Fix / how to use it: run go run ./cmd/stride in the Lab and compare its output with this hand-written table; the tool finds the rows, humans write the concrete threat and decide.
Scoring risk: likelihood times impact, DREAD, CVSS v4 Important
In plain words: after listing threats you need an order to fix them; score how likely and how bad each one is.
Common misunderstanding: "A CVSS 9.8 in a library means we are at 9.8." CVSS Base describes the vulnerability in general; your risk depends on whether the vulnerable function is reachable, the asset behind it and existing controls. CVSS v4 has Threat and Environmental groups exactly for that, and Go's govulncheck reports only vulnerabilities in functions your code actually calls.
Definition: OWASP: "ranking should be based on the mathematical product of an identified threat's likelihood and its impact", while noting both are hard to estimate and ignore the cost of the fix. DREAD rates five factors 1 to 10 and sums them (Wikipedia). CVSS v4.0 (FIRST) scores vulnerabilities from metric groups Base, Threat, Environmental and Supplemental, and names scores by what was used: CVSS-B, CVSS-BT, CVSS-BE, CVSS-BTE.
| CVSS v4 rating | Score range |
|---|---|
| None | 0.0 |
| Low | 0.1 - 3.9 |
| Medium | 4.0 - 6.9 |
| High | 7.0 - 8.9 |
| Critical | 9.0 - 10.0 |
Reading a CVSS v4 vector from the spec (example vector, ours annotated)
1 CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N/E:A
2 AV:N attack vector network AC:L low complexity AT:N no attack requirements
3 PR:H high privileges required UI:N no user interaction
4 VC/VI/VA impact on the vulnerable system (L, L, None); SC/SI/SA impact on subsequent systems (None)
5 E:A Threat metric Exploit Maturity = Attacked (exploitation reported) -> CVSS-BT score| Method | Good for | Weakness |
|---|---|---|
| Likelihood x impact (High/Medium/Low) | Design-time threats | Coarse, but honest about uncertainty |
| DREAD | Historical; quick team discussion | Subjective; Discoverability rewards obscurity |
| CVSS v4 Base | Comparing vulnerabilities across vendors | Not your risk until Threat and Environmental are applied |
| CVSS-BTE + reachability | Patch prioritisation | Needs asset inventory and exploit intelligence |
| Attack-tree cost | Which path is cheapest for the attacker | Only as good as the leaf estimates |
Real scenarios: a Critical CVE in an XML parser that your service never invokes (low priority after reachability); a Medium IDOR on the invoices API that exposes every customer (high business impact); a Low-scored info leak that reveals internal hostnames used in a later attack chain.
Fix / how to use it: use High/Medium/Low at design time, CVSS-BTE plus reachability for patching, and write the residual risk and its owner next to every accepted threat.
Attack trees and abuse cases Important
In plain words: an attack tree starts from what the attacker wants and branches into every way to get it; an abuse case is a user story written by the attacker ("as a customer I want to see other customers' invoices").
Common misunderstanding: "STRIDE already covers business-logic abuse." STRIDE asks about properties of elements; it rarely finds "apply the same coupon 50 times in parallel" or "refund to a different card". OWASP's method table recommends "Misuse or abuse cases" to "Explore actions performed out of order, repeatedly, concurrently, or for an unintended outcome."
Definition: Schneier (1999): "you represent attacks against a system in a tree structure, with the goal as the root node and different ways of achieving that goal as leaf nodes", with OR nodes as alternatives and AND nodes as required steps; leaves can carry costs that propagate up. Abuse case: a negative requirement describing an interaction that must fail, with an acceptance test.
Abuse case -> test (coupon race)
1 Story: as a customer I apply coupon SAVE50 in 20 parallel requests
2 Expect: exactly one order gets the discount; 19 get 409 Conflict
3 Control: unique (coupon_id, customer_id) constraint + transaction (see /database/isolation-levels)
4 Test: integration test fires 20 goroutines / Laravel parallel HTTP calls and counts 201sReal scenarios: gift-card balance races, refund to a different instrument, account recovery via email takeover, scraping through pagination, invite-link reuse, quantity set to a negative number.
| Technique | Starts from | Finds best |
|---|---|---|
| STRIDE per element | The diagram | Missing technical controls at elements and flows |
| Attack tree | An attacker goal | Cheapest multi-step path; where one control cuts a branch |
| Abuse case | A user story | Business-logic flaws, races, workflow order |
| ATT&CK mapping | Known adversary behaviour | Detection gaps after initial access |
Fix / how to use it: one attack tree per top asset ("read another tenant's data", "move money", "deploy code"), and one abuse case per money- or permission-changing endpoint, each turned into an automated test.
MITRE ATT&CK mapping Good to know
In plain words: a shared dictionary of what real attackers do after they get in, organised by goal (tactic) and method (technique), so you can ask "would we notice this?".
Common misunderstanding: "ATT&CK is a checklist to make us secure." It describes adversary behaviour; it is most useful for detection engineering and red/blue exercises, after the design-time threat model.
Definition: "a globally-accessible knowledge base of adversary tactics and techniques based on real-world observations". The Enterprise matrix, as shown on the ATT&CK site when we fetched it, lists the tactics Reconnaissance, Resource Development, Initial Access, Execution, Persistence, Privilege Escalation, Stealth, Defense Impairment, Credential Access, Discovery, Lateral Movement, Collection, Command and Control, Exfiltration and Impact. Techniques have ids such as T1110.004 (Credential Stuffing), T1566 (Phishing), T1195 (Supply Chain Compromise).
Mapping one breach story to ATT&CK and to our layers
1 Initial Access T1566 Phishing -> developer laptop layer: identity (passkeys), endpoint
2 Credential Access steals cloud CLI token layer: short-lived creds, device-bound
3 Discovery lists S3 buckets detect: unusual API calls alert
4 Collection/Exfil downloads backups layer: data (KMS key policy), egress limits
5 Impact deletes snapshots, ransom note corrective: immutable cross-account backups| STRIDE (design time) | ATT&CK tactic it relates to (operations) |
|---|---|
| Spoofing | Initial Access, Credential Access |
| Tampering | Persistence, Impact |
| Repudiation | Stealth, Defense Impairment |
| Information disclosure | Collection, Exfiltration |
| Denial of service | Impact |
| Elevation of privilege | Privilege Escalation, Lateral Movement |
Real scenarios: writing detection rules for the SIEM; choosing which logs to keep; planning a tabletop exercise; reading a vendor's incident report.
Fix / how to use it: for each high-severity threat, name the ATT&CK technique and the log line that would show it; if no log would, that is a detective-control gap. Operations detail is in Secure SDLC and incident response.
Defense in depth Must-know
In plain words: several independent locks, so one broken lock is not a breach.
Common misunderstanding: "Defense in depth means buying more products." Two WAFs in a row are one layer. Layers must fail independently: different mechanism, different credentials, different team or account.
Definition: OWASP's Secure Product Design cheat sheet: a strategy "that involves multiple layers of security controls to protect an organization’s assets", based on the idea "that if one layer of security fails, the other layers will still be able to protect the asset."
| Layer | Preventive | Detective | Corrective | Sibling chapter |
|---|---|---|---|---|
| Edge | WAF (Cloudflare, AWS WAF), DDoS protection, TLS, bot rules | WAF logs, rate anomalies | Under-attack mode, block lists | DDoS & network security, CDN |
| Network | VPC private subnets, security groups, Kubernetes NetworkPolicy, mTLS (Istio, Linkerd) | Flow logs | Isolate a subnet | mTLS, Firewalls |
| Identity | MFA, SSO (OIDC), workload identity, short-lived tokens | Failed-login and impossible-travel alerts | Revoke sessions, rotate keys | OAuth/OIDC, Authentication |
| Application | Authorization per request, validation, CSRF, rate limits, headers, timeouts | Audit events, error-rate alerts | Feature flags, kill switches | OWASP Top 10, Rate limiting |
| Data | Least-privilege roles, RLS, encryption at rest (KMS), tokenisation | pgAudit, access anomaly alerts | PITR, immutable backups | Database Security, Encryption |
| Monitoring | (none on its own) | Central logs, SIEM, alerting | Incident response, runbooks | Observability |
Stolen password, with and without depth
1 attacker logs in with a phished password edge: passes; network: passes
2 without MFA: logged in with MFA (passkey): stopped here (identity)
3 GET /invoices/43 (another tenant) policy check -> 404 (application)
4 tries SQL injection on /search parameterised query; DB role read-only on 2 tables (data)
5 every step emits an audit event alert "403/404 burst for one account" fires (monitoring)Real scenarios: an SSRF that reaches the cloud metadata service is stopped by IMDSv2 and a role without S3 access; an SQL injection in a reporting page limited by a read-only replica role; a leaked API key blunted by IP allow-listing and per-key quotas.
Fix / how to use it: for each top threat, require controls in at least two different layers, one of them detective, and write down which layer you rely on if the first fails.
Design principles: Saltzer and Schroeder, applied Must-know
In plain words: a short list of habits that make whole classes of bugs impossible or cheap: give the least power, deny by default, check every time, keep it simple, assume the design is public, split critical powers.
Common misunderstanding: "Open design means open source." It means the protection must not depend on the attacker not knowing how it works: "The design should not be secret". Security rests on keys and credentials, which are easy to change, not on obscure endpoints, which are not.
Definition: the eight principles of the 1975 paper, with the modern names and practices:
| Principle | Saltzer and Schroeder wording | Modern practice | Example in this chapter's code |
|---|---|---|---|
| Economy of mechanism | "Keep the design as simple and small as possible." | One auth library, one policy engine, small trusted base | One middleware chain in secureserver.New |
| Fail-safe defaults | "Base access decisions on permission rather than exclusion." | Deny by default; zero config means safe config | Config.withDefaults never leaves a timeout at zero; policies deny unless allowed |
| Complete mediation | "Every access to every object must be checked for authority." | Authorization per request and per object; no cached "is admin" | Gate::authorize('view', $invoice) on every call |
| Open design | "The design should not be secret" | Kerckhoffs; public algorithms; secrets only in keys | Signed URLs rely on APP_KEY, not on hidden paths |
| Separation of privilege | "a protection mechanism that requires two keys to unlock it is more robust" | MFA, two-person approval, split KMS key policies | password.confirm step-up before delete |
| Least privilege | "Every program and every user of the system should operate using the least set of privileges necessary to complete the job." | Scoped IAM roles, DB roles per service, short-lived tokens | app_writer role has INSERT/SELECT on audit only |
| Least common mechanism | "Minimize the amount of mechanism common to more than one user" | Tenant isolation, per-tenant keys, no shared admin accounts | Per-user rate-limit keys |
| Psychological acceptability | "the human interface be designed for ease of use" | Passkeys over complex password rules; safe path is the easy path | Secure defaults instead of a hardening guide |
Separation of duties is the organisational form of separation of privilege: the person who creates a payment cannot approve it, the developer who writes the code cannot deploy it alone. The InvoicePolicy::delete rule (the issuer cannot delete their own invoice) is a tiny example.
Fail-safe defaults vs fail-open (authorization service timeout)
1 T0 request arrives, API asks the policy service "may user 7 view invoice 43?"
2 T1 policy service times out after 200 ms
3 fail-open code: catch (Timeout) { allow } -> every invoice readable during the outage
4 fail-safe code: catch (Timeout) { deny 503 } -> users see an error, no data leaks
5 availability vs confidentiality trade-off decided in the design, not in a catch blockReal scenarios: an IAM policy with "Action": "*" for a Lambda that reads one bucket; a feature flag that defaults to "enabled" when the flag service is down; an admin panel protected only by an unlisted URL; a single person able to change bank details and approve the payment run.
Fix / how to use it: in review, ask for each new permission "what is the smallest set?", for each error path "does it fail closed?", and for each critical action "how many people or factors are needed?". Code-level application of the principles is in Security by Design.
Zero trust, in one block Important
In plain words: being inside the network proves nothing; every request is authenticated and authorised as if it came from the internet.
Common misunderstanding: "Zero trust is a product you buy." NIST SP 800-207 calls it "an evolving set of cybersecurity paradigms"; products implement parts (identity-aware proxies, mTLS meshes, device posture), but the decision is architectural.
Definition: NIST SP 800-207: "Zero trust assumes there is no implicit trust granted to assets or user accounts based solely on their physical or network location (i.e., local area networks versus the internet) or based on asset ownership (enterprise or personally owned)." Authentication and authorization "are discrete functions performed before a session to an enterprise resource is established."
Perimeter model vs zero trust for an internal admin tool
1 perimeter: VPN login -> 10.0.0.0/8 reachable -> admin tool trusts source IP
2 attacker phishes one VPN credential -> every internal tool is open (lateral movement)
3 zero trust: identity-aware proxy -> SSO + MFA + device check -> per-app authorization
4 the same phished password fails at MFA; even with a session, only one app is reachableReal scenarios: replacing a VPN with an identity-aware proxy; service-to-service mTLS with per-service authorization policies (Istio AuthorizationPolicy); short-lived database credentials issued per workload.
| Perimeter assumption | Zero trust replacement |
|---|---|
| Inside the VPC means trusted | Every call carries a verified identity |
| VPN grants network access | Proxy grants access per application |
| Static service passwords | Short-lived certificates or tokens per workload |
| Check once at login | Continuous evaluation (device, risk, session age) |
Fix / how to use it: start with the highest-value internal paths (admin tools, service-to-service calls to the payment service). The models and policy engines are in Authorization Models: RBAC, ABAC, ReBAC & Zero Trust.
Secure by default and shift left Must-know
In plain words: secure by default means the out-of-the-box configuration is the safe one; shift left means finding security problems earlier (design, code review, CI) where they are cheap.
Common misunderstanding: "Shift left means developers now do the security team's job." It means the security team builds paved roads (templates, libraries, CI checks) so the safe path is the default path; it does not remove the review or the operations side.
Definition: CISA's Secure by Design page: products should prioritise "the security of customers as a core business requirement", and "Out-of-the-box, products should be secure". GDPR Article 25 makes "Data protection by design and by default" a legal duty for personal data. Shift left: move threat modelling to design, SAST/SCA/secret scanning to the pull request, and policy as code to CI; OWASP: threat modelling "is ideally performed early in the SDLC, such as during the design phase."
Cost of the same flaw found at different stages (qualitative)
1 design review "tenant_id comes from the body" -> change one line in the spec
2 pull request reviewer spots it -> change one handler, add a test
3 staging pen test -> fix handler, audit every similar endpoint
4 production -> fix, investigate access logs, notify customers, regulators (GDPR Art. 33)Real scenarios: a service template where new HTTP servers already have timeouts and headers (the secureserver package); a Terraform module where buckets are private and encrypted unless a reviewed exception says otherwise; a Laravel app where CSRF, hashing, encrypted cookies and APP_DEBUG=false in production are defaults.
| Default | Insecure default | Secure default |
|---|---|---|
| Go HTTP server | http.ListenAndServe (zero-value Server, no timeouts) | secureserver.New with all timeouts set |
| Laravel web routes | (none; CSRF is on in the web group) | PreventRequestForgery in the web group by default |
| Passwords | Fast hashes | Laravel Hash uses bcrypt by default; Argon2 available |
| Storage buckets | Public ACLs allowed | Block public access on, encryption on |
| Debug output | Detailed errors everywhere | Generic errors in production |
Fix / how to use it: make the secure configuration the only one the template offers, and require a reviewed, expiring exception to deviate. The pipeline side is in Secure SDLC.
Security controls catalogue: preventive, detective, corrective Must-know
In plain words: some controls stop the attack (lock), some notice it (alarm), some repair the damage (insurance and spare key).
Common misunderstanding: "If our preventive controls are good, we do not need detection." Every preventive control has gaps (zero-days, insiders, phished MFA). The DBIR's ransomware share (44% of breaches in the 2025 release) is largely a story of attacks that were not noticed until the impact.
Definition: a preventive control reduces the likelihood of a threat succeeding; a detective control identifies an attempt or a compromise; a corrective control limits damage and restores the system. Deterrent, compensating and recovery controls are sometimes added as separate types. NIST SP 800-53 Rev. 5 groups controls by family (Access Control, Audit and Accountability, Contingency Planning, Identification and Authentication, Incident Response, and others) rather than by type.
| Control | Type | STRIDE it answers | Product example |
|---|---|---|---|
| MFA / passkeys | Preventive | S | Okta, Entra ID, WebAuthn |
| Authorization policy per object | Preventive | E, I | Laravel policies, OPA, Cedar |
| Input validation, parameterised queries | Preventive | T, E | Laravel validation, database/sql placeholders |
| TLS / mTLS | Preventive | T, I, S | Let's Encrypt, Istio |
| Rate limits, timeouts, body limits | Preventive | D | Laravel throttle, Go http.Server, Cloudflare rules |
| Encryption at rest | Preventive | I | AWS KMS, PostgreSQL TDE (products vary), Laravel encrypted cast |
| Audit log | Detective | R | pgAudit, CloudTrail, Laravel log channel |
| Alerting and SIEM | Detective | all | Datadog, Elastic, Splunk |
| File integrity / signature verification | Detective (or preventive at admission) | T | Sigstore cosign verify, Kubernetes admission policies |
| Backups and PITR | Corrective | D, T | PostgreSQL PITR, AWS Backup |
| Key and credential rotation | Corrective | S, I | Laravel APP_PREVIOUS_KEYS, Vault |
| Incident response runbook | Corrective | all | PagerDuty, runbooks |
One threat, three control types (ransomware on the orders DB)
1 preventive no public DB, least-privilege roles, MFA for admins, patched hosts
2 detective alert on mass UPDATE/DELETE rate, snapshot deletion events, new admin user
3 corrective immutable backups in a separate account, restore drill RTO 2 h, runbook
4 if 1 fails and 2 is missing, 3 is the only thing between you and payingReal scenarios: a payment API with fraud scoring (preventive), chargeback monitoring (detective) and refunds plus card reissue (corrective); a CI system with signed commits (preventive), audit of workflow changes (detective) and secret rotation (corrective).
Fix / how to use it: in the threat register, every high-severity threat gets at least one preventive and one detective control, and the asset gets a corrective plan. The Go tool tags each missing control with its type.
Secrets hygiene, overview Important
In plain words: passwords, API keys, signing keys and tokens must never be in code, never be shared between environments, live as short as possible, and be rotatable without a deploy.
Common misunderstanding: "The repository is private, so a key in .env committed once is fine." Git history keeps it, forks and CI caches copy it, and laptops get stolen. Treat any committed secret as leaked and rotate it.
Definition: secrets management is the lifecycle of credentials: generation, storage (a secrets manager or KMS), distribution to workloads (environment injection, workload identity), use, rotation, revocation and audit.
Leaked key, the usual timeline
1 commit adds config with AWS key "for testing"
2 pushed to a public fork / package by mistake
3 automated scanners find the key (minutes, per public reports; not measured here)
4 crypto-mining instances launched in every region
5 fix: revoke key, rotate, purge history, add secret scanning + pre-commit hook, use workload identityReal scenarios: Laravel APP_KEY (encrypts cookies, signs URLs; rotate with APP_PREVIOUS_KEYS so old values still decrypt); database passwords in Kubernetes Secrets; webhook signing secrets; CI deploy keys.
| Practice | Weak | Strong |
|---|---|---|
| Storage | .env in the repo | Secrets manager (Vault, AWS Secrets Manager), KMS |
| Lifetime | Years | Short-lived (minutes to hours) via workload identity |
| Scope | One key for everything | One key per service and environment |
| Rotation | Manual, needs downtime | Overlap window (APP_PREVIOUS_KEYS, dual keys) |
| Detection | None | Secret scanning in CI and on the git host |
Fix / how to use it: the full design (envelope encryption, PKI, rotation) is in Cryptography in Practice.
Supply chain: SBOM, dependency pinning, signing with Sigstore, SLSA Must-know
In plain words: most of your production code was written by someone else; know what it is (SBOM), make sure you get exactly the version you reviewed (pinning and checksums), and that it was built by who you think (signatures and provenance).
Common misunderstanding: "Pinning versions in composer.json is enough." A version range resolves differently tomorrow; a lockfile (composer.lock, go.sum) pins exact versions and hashes, and Go's checksum database makes the hash for a module version the same for everyone. Pinning stops silent drift; it does not stop a malicious version you deliberately upgrade to.
Definition: CISA: "An SBOM is a nested inventory, a list of ingredients that make up software components." Dependency pinning: resolving every direct and transitive dependency to an exact version and content hash. Code signing: a signature binding an artifact to an identity. Sigstore: "Signatures are generated with ephemeral signing keys so there’s no need to manage keys. Signing events are recorded in a tamper-resistant public log". Its client Cosign gets a short-lived certificate from Fulcio bound to an OIDC identity, and records the signature in "an immutable, append-only ledger known as Rekor". SLSA defines build levels: "Build L0: No guarantees", "Build L1: Provenance exists", "Build L2: Hosted build platform", "Build L3: Hardened builds".
A dependency attack and where each control cuts it
1 attacker publishes "left-padx" (typosquat) or hijacks a maintainer account
2 developer runs composer require / go get cut: allow-list, review new deps
3 CI resolves a range to the new malicious version cut: lockfile + go.sum, no floating ranges
4 build embeds it; image pushed cut: SBOM shows the new component in the diff
5 cluster pulls the image cut: admission policy requires cosign signature from our CI identity
6 runtime calls home cut: egress allow-list, alert on new destinationsReal scenarios: an npm/PyPI typosquat; a compromised GitHub Action tag; a build server that injects code (SolarWinds-style; we cite only the category here); a base image with a known CVE.
| Control | Go | PHP / Laravel | Containers |
|---|---|---|---|
| Pin exact versions and hashes | go.mod + go.sum, checksum database | composer.lock | Image digest @sha256: |
| Known vulnerabilities | govulncheck (call-graph aware) | composer audit | Image scanners |
| SBOM | cyclonedx-gomod, Syft | CycloneDX Composer plugin, Syft | Syft, BuildKit SBOM attestations |
| Signing and verification | Cosign for binaries (sign-blob) | Cosign for release archives | cosign sign / cosign verify, Kubernetes admission policy |
| Provenance | SLSA generator in CI | SLSA generator in CI | Build attestations |
Fix / how to use it: lockfiles committed and verified in CI, SBOM generated per build and stored with the artifact, images signed by the CI identity and verified at deploy, and a short list of who may add dependencies. OWASP Top 10:2025 now ranks this risk third.
Compliance frameworks as design constraints Important
In plain words: some customers, card networks and laws require specific controls; treat them as non-functional requirements on the design, not as paperwork after it.
Common misunderstanding: "Being compliant means being secure." Compliance is a minimum baseline audited at a point in time; attackers do not check certificates. The reverse also holds: a secure design with no evidence (logs, tickets, reviews) fails an audit.
Definition: the four frameworks a system designer meets most:
| Framework | What it is (from the source) | What it forces on the design | Evidence an auditor asks for |
|---|---|---|---|
| SOC 2 (AICPA) | Reports on controls "Relevant to Security, Availability, Processing Integrity, Confidentiality, or Privacy" | Access reviews, change management, logging, incident process | Tickets, approvals, log retention, access review records |
| ISO/IEC 27001:2022 | Information security management system standard (NIST publishes an SP 800-53 crosswalk to it) | Risk register, asset inventory, policies, Annex A controls | Statement of Applicability, risk treatment plan |
| PCI DSS v4.x | "a baseline of technical and operational requirements designed to protect payment account data" | Shrink the cardholder data environment: tokenise, segment, never log PANs | Network diagrams, scans, segmentation tests |
| GDPR | EU regulation; Art. 25 "Data protection by design and by default", Art. 32 security of processing including "the pseudonymisation and encryption of personal data" | Data minimisation, purpose limits, erasure, breach notification | Records of processing, DPIAs, breach logs |
PCI DSS scope reduction by design (request flow)
1 browser loads the PSP's hosted card field (iframe/JS from the PSP)
2 card number goes browser -> PSP directly; our servers never see the PAN
3 PSP returns a token; our API stores token + last4 only
4 our cardholder data environment shrinks to the page that embeds the field
A design decision removed most of the PCI scope; no control had to be bought.Real scenarios: an enterprise customer requiring a SOC 2 Type II report before signing; a payments feature that would put the whole Kubernetes cluster in PCI scope; GDPR erasure requests against an append-only event log (see Messaging Security for erasure in immutable logs).
Fix / how to use it: map each framework control to a component and a test in the threat model; design to shrink scope (tokenisation, separate accounts). Audit evidence and breach handling are in Secure SDLC, Incident Response, Compliance & Breaches; payment-specific design in Payment Processing Architecture.
Security in the design review: the checklist Must-know
In plain words: a short list of questions every design document answers before it is approved, so security is a gate with criteria, not an opinion.
Common misunderstanding: "The security reviewer will find the problems." The reviewer checks the answers; the authors must bring the DFD, the threat list and the decisions. A review without a model reviews prose.
Definition: a security review checklist is a fixed set of questions with required artefacts, applied at design time and re-applied when the DFD changes.
| # | Question | Required artefact | Fails if |
|---|---|---|---|
| 1 | What assets does this touch and how are they classified? | Asset list with classification | PII or secrets not listed |
| 2 | Where are the trust boundaries and new entry points? | DFD with boundaries | Any arrow crosses a boundary unlabelled |
| 3 | How is every caller authenticated (people and services)? | Auth method per flow | Any "internal, so trusted" flow |
| 4 | Where is authorization checked, per object? | Policy names per endpoint | Tenant or owner id taken from input |
| 5 | What do the STRIDE rows say, and who owns each open one? | Generated checklist with owners | Open high rows without owner or acceptance |
| 6 | What are the limits (rate, size, time) on each entry point? | Numbers per endpoint | Any unbounded input |
| 7 | What is logged for audit, and what is never logged? | Audit event list, redaction rules | Secrets or full PANs in logs |
| 8 | Which secrets are needed, where do they live, how are they rotated? | Secret inventory | Long-lived keys in config |
| 9 | Which new dependencies or vendors, and what can they reach? | SBOM diff, vendor scopes | Unpinned or unreviewed dependency |
| 10 | What fails closed, what fails open, and why? | Failure-mode table | Authorization that fails open |
| 11 | How would we detect abuse and recover? | Alerts, runbook, backup/restore plan | No detective control on a high threat |
| 12 | Which compliance controls apply? | Mapping to SOC 2 / PCI DSS / GDPR items | In-scope data with no mapped control |
Review flow
1 author: design doc + DFD (model.json) + generated STRIDE table
2 CI: go run ./cmd/stride -> exit 1 while an open high-severity threat exists
3 review meeting: walk the 12 questions, record decisions (mitigate/eliminate/transfer/accept)
4 accepted risks: owner + expiry date in the risk register
5 tickets: each mitigation with an acceptance test; review re-opens if the DFD changesReal scenarios: adding SSO, adding a public webhook, moving files to object storage with presigned URLs, adding an LLM agent with tool access, opening an API to partners.
Fix / how to use it: copy the table into your design-doc template and make question 5 machine-checked. The four-step design method this plugs into is in The 4-Step Approach.
Incident basics Good to know
In plain words: assume something will get through; decide now who is called, what logs exist, how to contain it and how to tell customers.
Common misunderstanding: "Incident response is the security team's problem." The first responder is usually the on-call engineer who sees odd traffic; the design decides whether the logs, kill switches and restore paths they need exist.
Definition: NIST CSF 2.0 organises outcomes into six functions: GOVERN, IDENTIFY, PROTECT, DETECT, "RESPOND (RS) — Actions regarding a detected cybersecurity incident are taken" and "RECOVER (RC) — Assets and operations affected by a cybersecurity incident are restored." An incident runbook covers detection, triage, containment, eradication, recovery and lessons learned.
First hour after "unusual export volume" alert
1 00m alert: one API key exported 50,000 invoices in 10 minutes
2 05m triage: audit log shows key belongs to partner X, IPs new
3 10m contain: revoke key (corrective), block IPs at the WAF
4 30m scope: which records? (audit rows by request_id) -> GDPR 72-hour clock starts on awareness
5 60m eradicate/recover: rotate partner secrets, add per-key export quota, post-incident review| Design decision | Why it matters in an incident |
|---|---|
| Audit events with request ids | Scope "what was taken" in minutes, not days |
| Per-key and per-tenant credentials | Revoke one without taking everyone down |
| Kill switches and feature flags | Contain without a deploy |
| Immutable, separate-account backups | Recover after ransomware |
| Synchronised clocks (NTP) | Correlate events across services |
Real scenarios: a leaked partner key, a compromised developer laptop, ransomware on a file server, a vulnerable dependency announced on a Friday.
Fix / how to use it: write the runbook alongside the threat model and drill it. The full lifecycle (logging, SIEM, breach notification) is in Secure SDLC & Incident Response.
Mechanics
The threat-model-as-code loop
The model is a JSON list of DFD elements; each has a kind, a boundary (trust zone), the holds assets and the controls already in place. The generator applies the per-element chart, marks a row mitigated when all its required controls are present, and computes a triage severity.
| Element kind | Letters generated | Required controls per letter (from rules in generate.go) |
|---|---|---|
external_entity | S, R | S: authn; R: audit-log |
process | S, T, R, I, D, E | S: authn; T: validation; R: audit-log; I: authz; D: rate-limit; E: authz + least-priv |
data_store | T, I, D (+ R if it holds audit_log) | T: least-priv; I: least-priv + enc-rest; D: backups; R: integrity + least-priv |
data_flow | T, I, D | T: tls; I: tls; D: rate-limit |
Severity rule (a triage hint, not a CVSS score): high when the element touches a sensitive asset (pii, card, secrets, credentials, audit_log) and a trust boundary is crossed; medium when only one holds; low otherwise. The command exits 1 while an open high row exists, so CI can block the merge.
HTTP server knobs and status codes
| Knob | Go net/http | Zero value means | This chapter's default |
|---|---|---|---|
ReadHeaderTimeout | "the amount of time allowed to read request headers" | Falls back to ReadTimeout; if that is zero, no timeout | 5 s |
ReadTimeout | "the maximum duration for reading the entire request, including the body" | No timeout | 15 s |
WriteTimeout | "the maximum duration before timing out writes of the response" | No timeout | 30 s |
IdleTimeout | Wait for the next keep-alive request | Falls back to ReadTimeout | 60 s |
MaxHeaderBytes | Header size limit, "does not limit the size of the request body" | DefaultMaxHeaderBytes (1 MB) | 16 KiB |
| Body limit | http.MaxBytesReader returns *http.MaxBytesError | Unlimited | 1 MiB |
| CSRF (Go 1.25+) | http.CrossOriginProtection ("added in go1.25.0", uses Sec-Fetch-Site) | Not applied | Not used here: the module targets go 1.24 |
| Status | Who emits it | Meaning in this chapter |
|---|---|---|
| 401 | Laravel auth, hasValidSignature() example in the docs uses abort(401) | Not authenticated |
| 403 | Laravel signed middleware on an invalid signature; PreventRequestForgery in origin-only mode | Authenticated or not, not allowed |
| 404 | Response::denyAsNotFound() | Hide that a foreign object exists |
| 413 | Our LimitBody | Body over the cap |
| 419 | Laravel CSRF token mismatch | "the 419 response typically associated with CSRF token mismatches" |
| 429 | Laravel throttle, rate limiters | Too many requests, with Retry-After |
The audit table in SQL
The repudiation control in the database: the application role can insert and read but not change history, a trigger blocks updates even if a grant is added by mistake, and a hash chain lets a nightly job detect edits by a superuser.
-- Repudiation control in the database: an append-only audit table.
-- The application role may INSERT and SELECT, never UPDATE or DELETE;
-- a hash chain makes silent edits by a superuser detectable.
CREATE TABLE audit_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
actor text NOT NULL, -- user id or service identity
action text NOT NULL, -- 'invoice.deleted'
object_ref text NOT NULL, -- 'invoice:42'
source_ip inet,
request_id text,
prev_hash bytea,
row_hash bytea NOT NULL
);
CREATE ROLE app_writer NOLOGIN;
GRANT INSERT, SELECT ON audit_events TO app_writer;
REVOKE UPDATE, DELETE, TRUNCATE ON audit_events FROM app_writer;
-- Defence in depth: even a role that was granted UPDATE by mistake is stopped.
CREATE FUNCTION audit_events_immutable() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'audit_events is append-only' USING ERRCODE = 'insufficient_privilege';
END $$;
CREATE TRIGGER audit_events_no_update
BEFORE UPDATE OR DELETE ON audit_events
FOR EACH ROW EXECUTE FUNCTION audit_events_immutable();
-- Insert with a hash chain (computed in the application or here with pgcrypto):
-- row_hash = sha256(prev_hash || occurred_at || actor || action || object_ref)
-- Verification job (detective control): recompute the chain nightly and alert on a break.-- Quick check that the control works (expected, not run)
SET ROLE app_writer;
UPDATE audit_events SET actor = 'someone-else' WHERE id = 1;
-- ERROR: permission denied for table audit_events
RESET ROLE;Go
Before
The tutorial server: a zero-value http.Server through http.ListenAndServe, no body limit, error details reflected to the caller, no authorization, the whole payload in the log. Every comment names the STRIDE letter it opens.
// Before: the server most tutorials start with. Nothing here is a syntax or
// logic bug; every line is an insecure default that an attacker can use.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type order struct {
ID string `json:"id"`
Amount float64 `json:"amount"`
Role string `json:"role"` // mass assignment: the client can send "admin"
}
func main() {
http.HandleFunc("/orders", func(w http.ResponseWriter, r *http.Request) {
var o order
// No body limit: a 10 GB body is read until memory runs out (D).
if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
// Internal detail reflected to the caller (I).
http.Error(w, fmt.Sprintf("decode failed: %v", err), http.StatusBadRequest)
return
}
// No authentication, no authorization check (S, E), no audit record (R).
log.Printf("order %+v", o) // the whole payload, PII included, goes to logs (I)
w.WriteHeader(http.StatusCreated)
})
// http.ListenAndServe uses a zero-value Server: no ReadHeaderTimeout,
// no ReadTimeout, no WriteTimeout, no IdleTimeout. One slow client per
// connection holds a goroutine and a socket forever (Slowloris, D).
log.Fatal(http.ListenAndServe(":8080", nil))
}After
Two packages. threatmodel is the threat-model-as-code tool: DFD types, validation (unique ids, known kinds, flows that point at existing nodes and never at another flow), the STRIDE-per-element generator with a small control catalogue tagged preventive/detective/corrective, a triage severity, Markdown output and a per-category summary.
// Package threatmodel turns a data flow diagram (DFD) written as data into a
// STRIDE-per-element checklist. It is threat modelling as code: the model
// lives in the repository, is reviewed like code and is re-run in CI.
package threatmodel
import (
"errors"
"fmt"
"sort"
"strings"
)
// Kind is one of the four DFD element types used by Microsoft's SDL and Shostack.
type Kind string
const (
ExternalEntity Kind = "external_entity" // a user, a partner, a third-party API
Process Kind = "process" // code you run: web app, API, worker
DataStore Kind = "data_store" // database, bucket, cache, queue at rest
DataFlow Kind = "data_flow" // a connection between two elements
)
// Category is one STRIDE letter.
type Category string
const (
Spoofing Category = "S"
Tampering Category = "T"
Repudiation Category = "R"
InformationDisclosure Category = "I"
DenialOfService Category = "D"
ElevationOfPrivilege Category = "E"
)
// Property is the security property each STRIDE category violates.
var Property = map[Category]string{
Spoofing: "authenticity",
Tampering: "integrity",
Repudiation: "non-repudiation",
InformationDisclosure: "confidentiality",
DenialOfService: "availability",
ElevationOfPrivilege: "authorization",
}
// Applicable is the STRIDE-per-element chart: which categories apply to which
// element type. Data stores get Repudiation only when they hold audit logs.
var Applicable = map[Kind][]Category{
ExternalEntity: {Spoofing, Repudiation},
Process: {Spoofing, Tampering, Repudiation, InformationDisclosure, DenialOfService, ElevationOfPrivilege},
DataStore: {Tampering, InformationDisclosure, DenialOfService},
DataFlow: {Tampering, InformationDisclosure, DenialOfService},
}
// Element is one node or flow of the DFD.
type Element struct {
ID string `json:"id"`
Name string `json:"name"`
Kind Kind `json:"kind"`
Boundary string `json:"boundary,omitempty"` // trust zone the node sits in
From string `json:"from,omitempty"` // data flows only
To string `json:"to,omitempty"` // data flows only
Holds []string `json:"holds,omitempty"` // assets: "pii", "card", "secrets", "audit_log"
Controls []string `json:"controls,omitempty"` // control ids already in place
}
// Model is a whole system.
type Model struct {
Name string `json:"name"`
Elements []Element `json:"elements"`
}
// Validate checks the model is a real graph: unique ids, known kinds, flows
// that point at existing nodes and never at another flow.
func (m Model) Validate() error {
var errs []error
byID := map[string]Element{}
for _, e := range m.Elements {
if e.ID == "" {
errs = append(errs, fmt.Errorf("element %q has no id", e.Name))
continue
}
if _, dup := byID[e.ID]; dup {
errs = append(errs, fmt.Errorf("duplicate id %q", e.ID))
}
if _, ok := Applicable[e.Kind]; !ok {
errs = append(errs, fmt.Errorf("%s: unknown kind %q", e.ID, e.Kind))
}
byID[e.ID] = e
}
for _, e := range m.Elements {
if e.Kind != DataFlow {
continue
}
for _, end := range []string{e.From, e.To} {
n, ok := byID[end]
switch {
case !ok:
errs = append(errs, fmt.Errorf("%s: endpoint %q does not exist", e.ID, end))
case n.Kind == DataFlow:
errs = append(errs, fmt.Errorf("%s: endpoint %q is a flow", e.ID, end))
}
}
}
return errors.Join(errs...)
}
// CrossesBoundary reports whether a flow connects two different trust zones.
func (m Model) CrossesBoundary(flow Element) bool {
from, to := m.find(flow.From), m.find(flow.To)
return from.Boundary != to.Boundary
}
func (m Model) find(id string) Element {
for _, e := range m.Elements {
if e.ID == id {
return e
}
}
return Element{}
}
func has(list []string, v string) bool {
for _, x := range list {
if strings.EqualFold(x, v) {
return true
}
}
return false
}
// sortedIDs is used to make output deterministic for golden tests and diffs.
func sortedIDs(m Model) []string {
ids := make([]string, 0, len(m.Elements))
for _, e := range m.Elements {
ids = append(ids, e.ID)
}
sort.Strings(ids)
return ids
}package threatmodel
import (
"fmt"
"io"
"sort"
"strings"
)
// ControlType is the conventional preventive / detective / corrective split.
type ControlType string
const (
Preventive ControlType = "preventive"
Detective ControlType = "detective"
Corrective ControlType = "corrective"
)
// Control is one entry of the control catalogue.
type Control struct {
ID string
Name string
Type ControlType
}
// Catalogue is the small control catalogue the generator suggests from.
var Catalogue = map[string]Control{
"authn": {"authn", "Strong authentication (MFA for people, mTLS or signed tokens for services)", Preventive},
"authz": {"authz", "Authorization check on every request (complete mediation)", Preventive},
"least-priv": {"least-priv", "Least-privilege identity for the process and its credentials", Preventive},
"tls": {"tls", "TLS 1.2+ on the connection", Preventive},
"integrity": {"integrity", "Integrity protection (HMAC, signatures, signed URLs, checksums)", Preventive},
"validation": {"validation", "Input validation and output encoding", Preventive},
"enc-rest": {"enc-rest", "Encryption at rest with managed keys", Preventive},
"rate-limit": {"rate-limit", "Rate limits, quotas, body and timeout limits", Preventive},
"audit-log": {"audit-log", "Append-only audit log with actor, action, time", Detective},
"alerting": {"alerting", "Alerting on anomalies and failed authentication", Detective},
"backups": {"backups", "Tested backups and restore (corrective)", Corrective},
"redundancy": {"redundancy", "Redundancy, autoscaling and failover", Corrective},
}
type rule struct {
question string
required []string // controls that, all present, mark the threat mitigated
suggest []string // extra controls worth considering
}
// rules is the STRIDE question bank per element kind.
var rules = map[Kind]map[Category]rule{
ExternalEntity: {
Spoofing: {"Can someone pretend to be this user or partner?", []string{"authn"}, []string{"alerting"}},
Repudiation: {"Can this actor deny an action they performed?", []string{"audit-log"}, []string{"integrity"}},
},
Process: {
Spoofing: {"Can a caller or a fake instance impersonate this process?", []string{"authn"}, []string{"tls"}},
Tampering: {"Can inputs, code or memory of this process be modified?", []string{"validation"}, []string{"integrity"}},
Repudiation: {"Are security-relevant actions recorded so they cannot be denied?", []string{"audit-log"}, []string{"alerting"}},
InformationDisclosure: {"Can it leak data through errors, logs or responses?", []string{"authz"}, []string{"validation"}},
DenialOfService: {"Can a caller exhaust its CPU, memory, connections or threads?", []string{"rate-limit"}, []string{"redundancy"}},
ElevationOfPrivilege: {"Can a caller make it do something the caller is not allowed to do?", []string{"authz", "least-priv"}, []string{"validation"}},
},
DataStore: {
Tampering: {"Can stored data be modified outside the intended path?", []string{"least-priv"}, []string{"integrity", "backups"}},
Repudiation: {"Can audit records be altered or deleted?", []string{"integrity", "least-priv"}, []string{"backups"}},
InformationDisclosure: {"Can stored data be read by someone who should not?", []string{"least-priv", "enc-rest"}, []string{"audit-log"}},
DenialOfService: {"Can the store be filled, locked or deleted?", []string{"backups"}, []string{"redundancy", "rate-limit"}},
},
DataFlow: {
Tampering: {"Can data be modified in transit?", []string{"tls"}, []string{"integrity"}},
InformationDisclosure: {"Can data be read in transit?", []string{"tls"}, nil},
DenialOfService: {"Can the channel be flooded or cut?", []string{"rate-limit"}, []string{"redundancy"}},
},
}
// Threat is one generated checklist row.
type Threat struct {
ElementID string
Element string
Kind Kind
Category Category
Property string
Question string
Missing []string // required controls not present
Suggested []string
Severity string // high, medium, low (a triage hint, not a CVSS score)
Mitigated bool
}
var sensitive = []string{"pii", "card", "secrets", "credentials", "audit_log"}
// Generate returns the STRIDE-per-element checklist for a valid model,
// ordered by severity, then element id, then STRIDE order.
func Generate(m Model) ([]Threat, error) {
if err := m.Validate(); err != nil {
return nil, err
}
var out []Threat
for _, id := range sortedIDs(m) {
e := m.find(id)
cats := append([]Category(nil), Applicable[e.Kind]...)
if e.Kind == DataStore && has(e.Holds, "audit_log") {
cats = append(cats, Repudiation)
}
for _, c := range cats {
r := rules[e.Kind][c]
t := Threat{
ElementID: e.ID, Element: e.Name, Kind: e.Kind, Category: c,
Property: Property[c], Question: r.question, Suggested: r.suggest,
}
for _, need := range r.required {
if !has(e.Controls, need) {
t.Missing = append(t.Missing, need)
}
}
t.Mitigated = len(t.Missing) == 0
t.Severity = m.severity(e, c)
out = append(out, t)
}
}
rank := map[string]int{"high": 0, "medium": 1, "low": 2}
order := "STRIDE"
sort.SliceStable(out, func(i, j int) bool {
a, b := out[i], out[j]
if a.Mitigated != b.Mitigated {
return !a.Mitigated
}
if rank[a.Severity] != rank[b.Severity] {
return rank[a.Severity] < rank[b.Severity]
}
if a.ElementID != b.ElementID {
return a.ElementID < b.ElementID
}
return strings.Index(order, string(a.Category)) < strings.Index(order, string(b.Category))
})
return out, nil
}
// severity is a deliberately simple triage rule: sensitive assets plus a
// trust-boundary crossing is high; one of the two is medium; neither is low.
// A node "crosses" when any flow touching it crosses a boundary; a process is
// "sensitive" when it reads or writes a node that holds a sensitive asset.
func (m Model) severity(e Element, c Category) string {
assets := append([]string(nil), e.Holds...)
crosses := e.Kind == ExternalEntity
for _, f := range m.Elements {
if f.Kind != DataFlow {
continue
}
switch {
case f.ID == e.ID:
assets = append(assets, m.find(f.From).Holds...)
assets = append(assets, m.find(f.To).Holds...)
crosses = crosses || m.CrossesBoundary(f)
case f.From == e.ID || f.To == e.ID:
crosses = crosses || m.CrossesBoundary(f)
if e.Kind == Process {
assets = append(assets, m.find(f.From).Holds...)
assets = append(assets, m.find(f.To).Holds...)
}
}
}
sens := false
for _, a := range sensitive {
if has(assets, a) {
sens = true
}
}
switch {
case sens && crosses:
return "high"
case sens || crosses:
return "medium"
default:
return "low"
}
}
// WriteMarkdown prints the checklist as a Markdown table for the design review.
func WriteMarkdown(w io.Writer, threats []Threat) error {
if _, err := fmt.Fprintln(w, "| Element | STRIDE | Violates | Question | Severity | Status | Missing controls |"); err != nil {
return err
}
if _, err := fmt.Fprintln(w, "| --- | --- | --- | --- | --- | --- | --- |"); err != nil {
return err
}
for _, t := range threats {
status := "OPEN"
if t.Mitigated {
status = "mitigated"
}
missing := make([]string, 0, len(t.Missing))
for _, id := range t.Missing {
missing = append(missing, fmt.Sprintf("%s (%s)", id, Catalogue[id].Type))
}
if _, err := fmt.Fprintf(w, "| %s | %s | %s | %s | %s | %s | %s |\n",
t.Element, t.Category, t.Property, t.Question, t.Severity, status, strings.Join(missing, ", ")); err != nil {
return err
}
}
return nil
}
// Summary counts open threats per STRIDE category.
func Summary(threats []Threat) map[Category]int {
s := map[Category]int{}
for _, t := range threats {
if !t.Mitigated {
s[t.Category]++
}
}
return s
}The tests check the per-element counts (1 entity x 2 + 2 processes x 6 + 3 stores x 3 + 1 + 4 flows x 3), that only the audit store gets Repudiation, that "mitigated" needs every required control, the severity rule and ordering, validation errors, and the Markdown output.
package threatmodel
import (
"bytes"
"strings"
"testing"
)
func shop() Model {
return Model{Name: "shop", Elements: []Element{
{ID: "user", Name: "Customer browser", Kind: ExternalEntity, Boundary: "internet"},
{ID: "web", Name: "Web app", Kind: Process, Boundary: "dmz", Controls: []string{"authn", "validation", "rate-limit"}},
{ID: "api", Name: "Orders API", Kind: Process, Boundary: "app", Controls: []string{"authn", "authz", "least-priv"}},
{ID: "queue", Name: "Order queue", Kind: DataStore, Boundary: "app"},
{ID: "db", Name: "Orders DB", Kind: DataStore, Boundary: "data", Holds: []string{"pii", "card"}, Controls: []string{"least-priv", "enc-rest", "backups"}},
{ID: "audit", Name: "Audit log", Kind: DataStore, Boundary: "data", Holds: []string{"audit_log"}},
{ID: "f1", Name: "HTTPS browser to web", Kind: DataFlow, From: "user", To: "web", Controls: []string{"tls", "rate-limit"}},
{ID: "f2", Name: "web to API", Kind: DataFlow, From: "web", To: "api", Controls: []string{"tls"}},
{ID: "f3", Name: "API to queue", Kind: DataFlow, From: "api", To: "queue"},
{ID: "f4", Name: "API to DB", Kind: DataFlow, From: "api", To: "db", Controls: []string{"tls"}},
}}
}
func TestPerElementCounts(t *testing.T) {
threats, err := Generate(shop())
if err != nil {
t.Fatal(err)
}
per := map[Kind]int{}
for _, th := range threats {
per[th.Kind]++
}
// 1 entity x 2, 2 processes x 6, 3 stores x 3 + 1 (audit store gets R), 4 flows x 3
want := map[Kind]int{ExternalEntity: 2, Process: 12, DataStore: 10, DataFlow: 12}
for k, n := range want {
if per[k] != n {
t.Errorf("%s: got %d threats, want %d", k, per[k], n)
}
}
}
func TestAuditStoreGetsRepudiation(t *testing.T) {
threats, _ := Generate(shop())
found := false
for _, th := range threats {
if th.ElementID == "audit" && th.Category == Repudiation {
found = true
}
if th.ElementID == "queue" && th.Category == Repudiation {
t.Fatal("queue holds no audit log, R should not apply")
}
}
if !found {
t.Fatal("audit store must get a repudiation threat")
}
}
func TestMitigatedNeedsEveryRequiredControl(t *testing.T) {
threats, _ := Generate(shop())
for _, th := range threats {
switch {
case th.ElementID == "api" && th.Category == ElevationOfPrivilege && !th.Mitigated:
t.Error("api has authz and least-priv: EoP should be mitigated")
case th.ElementID == "web" && th.Category == ElevationOfPrivilege && th.Mitigated:
t.Error("web has no authz: EoP must stay open")
case th.ElementID == "f3" && th.Category == InformationDisclosure && !(len(th.Missing) == 1 && th.Missing[0] == "tls"):
t.Errorf("f3 should miss tls, got %v", th.Missing)
}
}
}
func TestSeverityAndOrdering(t *testing.T) {
m := shop()
threats, _ := Generate(m)
if !m.CrossesBoundary(m.find("f4")) || m.CrossesBoundary(m.find("f3")) {
t.Fatal("f4 crosses app->data, f3 stays inside app")
}
for _, th := range threats {
if th.ElementID == "f4" && th.Severity != "high" {
t.Errorf("flow into card store across a boundary should be high, got %s", th.Severity)
}
if th.ElementID == "f3" && th.Severity != "low" {
t.Errorf("internal flow without assets should be low, got %s", th.Severity)
}
}
seenMitigated := false
for _, th := range threats {
if th.Mitigated {
seenMitigated = true
} else if seenMitigated {
t.Fatal("open threats must come before mitigated ones")
}
}
}
func TestValidate(t *testing.T) {
m := shop()
m.Elements = append(m.Elements,
Element{ID: "f9", Kind: DataFlow, From: "api", To: "ghost"},
Element{ID: "f10", Kind: DataFlow, From: "f1", To: "api"},
Element{ID: "web", Kind: Process},
Element{ID: "x", Kind: "router"},
)
err := m.Validate()
if err == nil {
t.Fatal("expected validation errors")
}
for _, want := range []string{`"ghost" does not exist`, `"f1" is a flow`, `duplicate id "web"`, `unknown kind "router"`} {
if !strings.Contains(err.Error(), want) {
t.Errorf("missing %q in %v", want, err)
}
}
if _, err := Generate(m); err == nil {
t.Fatal("Generate must refuse an invalid model")
}
}
func TestMarkdownAndSummary(t *testing.T) {
threats, _ := Generate(shop())
var buf bytes.Buffer
if err := WriteMarkdown(&buf, threats); err != nil {
t.Fatal(err)
}
out := buf.String()
if !strings.HasPrefix(out, "| Element | STRIDE |") || !strings.Contains(out, "audit-log (detective)") {
t.Fatalf("unexpected markdown:\n%s", out)
}
s := Summary(threats)
if s[Repudiation] == 0 || s[DenialOfService] == 0 {
t.Fatalf("summary should count open R and D threats: %v", s)
}
if lines := strings.Count(out, "\n"); lines != len(threats)+2 {
t.Fatalf("got %d lines for %d threats", lines, len(threats))
}
}The command reads model.json (embedded by default) and exits 1 while an open high-severity threat exists.
// Command stride reads a DFD as JSON and prints the STRIDE-per-element
// checklist as Markdown. Usage: go run ./cmd/stride [model.json]
// Exit status 1 when an open high-severity threat exists, so CI can gate on it.
package main
import (
_ "embed"
"encoding/json"
"fmt"
"os"
"academy/security-foundations-cia-stride/threatmodel"
)
//go:embed model.json
var sample []byte
func main() {
data := sample
if len(os.Args) > 1 {
b, err := os.ReadFile(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
data = b
}
var m threatmodel.Model
if err := json.Unmarshal(data, &m); err != nil {
fmt.Fprintln(os.Stderr, "parse model:", err)
os.Exit(2)
}
threats, err := threatmodel.Generate(m)
if err != nil {
fmt.Fprintln(os.Stderr, "invalid model:\n", err)
os.Exit(2)
}
fmt.Printf("# Threat checklist: %s\n\n", m.Name)
if err := threatmodel.WriteMarkdown(os.Stdout, threats); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
s := threatmodel.Summary(threats)
fmt.Printf("\nOpen per category: S=%d T=%d R=%d I=%d D=%d E=%d (total threats %d)\n",
s["S"], s["T"], s["R"], s["I"], s["D"], s["E"], len(threats))
for _, t := range threats {
if !t.Mitigated && t.Severity == "high" {
os.Exit(1)
}
}
}{
"name": "shop: web app + API + queue + DB",
"elements": [
{"id": "user", "name": "Customer browser", "kind": "external_entity", "boundary": "internet"},
{"id": "psp", "name": "Payment provider", "kind": "external_entity", "boundary": "partner", "controls": ["authn"]},
{"id": "web", "name": "Web app (Laravel)", "kind": "process", "boundary": "dmz", "controls": ["authn", "validation", "rate-limit", "audit-log"]},
{"id": "api", "name": "Orders API (Go)", "kind": "process", "boundary": "app", "controls": ["authn", "authz", "least-priv", "validation"]},
{"id": "worker", "name": "Fulfilment worker", "kind": "process", "boundary": "app", "controls": ["least-priv"]},
{"id": "queue", "name": "Order queue (RabbitMQ)", "kind": "data_store", "boundary": "app"},
{"id": "db", "name": "Orders DB (PostgreSQL)", "kind": "data_store", "boundary": "data", "holds": ["pii"], "controls": ["least-priv", "enc-rest", "backups"]},
{"id": "audit", "name": "Audit log", "kind": "data_store", "boundary": "data", "holds": ["audit_log"], "controls": ["least-priv"]},
{"id": "f1", "name": "browser -> web (HTTPS)", "kind": "data_flow", "from": "user", "to": "web", "controls": ["tls", "rate-limit"]},
{"id": "f2", "name": "web -> API", "kind": "data_flow", "from": "web", "to": "api", "controls": ["tls"]},
{"id": "f3", "name": "API -> queue", "kind": "data_flow", "from": "api", "to": "queue"},
{"id": "f4", "name": "queue -> worker", "kind": "data_flow", "from": "queue", "to": "worker"},
{"id": "f5", "name": "API -> DB", "kind": "data_flow", "from": "api", "to": "db", "controls": ["tls"]},
{"id": "f6", "name": "worker -> payment provider", "kind": "data_flow", "from": "worker", "to": "psp", "controls": ["tls"]},
{"id": "f7", "name": "web -> audit log", "kind": "data_flow", "from": "web", "to": "audit"}
]
}secureserver is the secure-by-default HTTP server: timeouts that can never be zero, a 16 KiB header cap, a 1 MiB body cap with a 413, OWASP-recommended headers, a panic handler that keeps details out of the response, and one structured audit line per request that drops any client-supplied identity header and never logs bodies or credentials.
// Package secureserver builds an *http.Server whose defaults are safe:
// bounded time, bounded size, safe headers, no internal detail in errors,
// and one audit line per request. It is "secure by default" in code form.
package secureserver
import (
"crypto/rand"
"encoding/hex"
"errors"
"log/slog"
"net/http"
"time"
)
// Config holds the limits. Zero values are replaced by the defaults below,
// so forgetting a field never turns a limit off (fail-safe default).
type Config struct {
Addr string
ReadHeaderTimeout time.Duration // Slowloris: time to send the headers
ReadTimeout time.Duration // whole request including body
WriteTimeout time.Duration // whole response
IdleTimeout time.Duration // keep-alive connections
MaxHeaderBytes int
MaxBodyBytes int64
CSP string
Logger *slog.Logger
}
func (c Config) withDefaults() Config {
def := func(d *time.Duration, v time.Duration) {
if *d <= 0 {
*d = v
}
}
def(&c.ReadHeaderTimeout, 5*time.Second)
def(&c.ReadTimeout, 15*time.Second)
def(&c.WriteTimeout, 30*time.Second)
def(&c.IdleTimeout, 60*time.Second)
if c.MaxHeaderBytes <= 0 {
c.MaxHeaderBytes = 16 << 10 // 16 KiB instead of the 1 MiB DefaultMaxHeaderBytes
}
if c.MaxBodyBytes <= 0 {
c.MaxBodyBytes = 1 << 20 // 1 MiB
}
if c.CSP == "" {
c.CSP = "default-src 'none'; frame-ancestors 'none'"
}
if c.Logger == nil {
c.Logger = slog.Default()
}
if c.Addr == "" {
c.Addr = ":8443"
}
return c
}
// New wraps h with the middleware chain and returns a configured server.
// Order, outside to inside: audit log, panic recovery, headers, body limit.
func New(h http.Handler, cfg Config) *http.Server {
cfg = cfg.withDefaults()
chain := Audit(cfg.Logger, Recover(cfg.Logger, Headers(cfg.CSP, LimitBody(cfg.MaxBodyBytes, h))))
return &http.Server{
Addr: cfg.Addr,
Handler: chain,
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
IdleTimeout: cfg.IdleTimeout,
MaxHeaderBytes: cfg.MaxHeaderBytes,
ErrorLog: slog.NewLogLogger(cfg.Logger.Handler(), slog.LevelWarn),
}
}
// Headers sets the response headers recommended by the OWASP HTTP Headers
// Cheat Sheet for an API. HSTS is only meaningful over HTTPS; it is set
// unconditionally because this server is meant to sit behind TLS.
func Headers(csp string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
h.Set("Content-Security-Policy", csp)
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Cross-Origin-Opener-Policy", "same-origin")
h.Set("Permissions-Policy", "geolocation=(), camera=(), microphone=()")
h.Set("Cache-Control", "no-store")
h.Del("Server")
next.ServeHTTP(w, r)
})
}
// LimitBody caps every request body. A handler that reads past the cap
// gets an *http.MaxBytesError; IsTooLarge lets it answer 413.
func LimitBody(n int64, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength > n {
http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
return
}
r.Body = http.MaxBytesReader(w, r.Body, n)
next.ServeHTTP(w, r)
})
}
// IsTooLarge reports whether err came from the body limit.
func IsTooLarge(err error) bool {
var mbe *http.MaxBytesError
return errors.As(err, &mbe)
}
// Recover turns a panic into a generic 500. The detail goes to the log with
// the request id, never to the client (information disclosure).
func Recover(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
if v == http.ErrAbortHandler {
panic(v)
}
log.Error("panic", "request_id", r.Header.Get("X-Request-Id"), "panic", v)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (s *statusWriter) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
// Audit assigns a request id and writes one structured line per request:
// who (remote address and, when present, the authenticated subject), what,
// when, outcome. It never logs bodies, cookies or Authorization headers.
func Audit(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := newID()
// Never trust identity headers from the client: an inner authn
// layer sets the subject after verifying a credential (spoofing).
r.Header.Del("X-Authenticated-Subject")
r.Header.Set("X-Request-Id", id)
w.Header().Set("X-Request-Id", id)
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
start := time.Now()
next.ServeHTTP(sw, r)
log.Info("request",
"request_id", id,
"remote", r.RemoteAddr,
"subject", r.Header.Get("X-Authenticated-Subject"),
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration_ms", time.Since(start).Milliseconds(),
)
})
}
func newID() string {
var b [8]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}package secureserver
import (
"bytes"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func echo() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := io.ReadAll(r.Body); err != nil {
if IsTooLarge(err) {
http.Error(w, "too large", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if r.URL.Path == "/panic" {
panic("db password is hunter2")
}
w.WriteHeader(http.StatusNoContent)
})
}
func TestDefaultsAreNeverZero(t *testing.T) {
srv := New(echo(), Config{})
if srv.ReadHeaderTimeout != 5*time.Second || srv.ReadTimeout == 0 || srv.WriteTimeout == 0 || srv.IdleTimeout == 0 {
t.Fatalf("timeouts must default to non-zero: %+v", srv)
}
if srv.MaxHeaderBytes != 16<<10 {
t.Fatalf("MaxHeaderBytes = %d", srv.MaxHeaderBytes)
}
}
func TestSecurityHeaders(t *testing.T) {
srv := New(echo(), Config{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
rec := httptest.NewRecorder()
srv.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
for _, h := range []string{"Strict-Transport-Security", "Content-Security-Policy", "X-Content-Type-Options", "X-Frame-Options", "Referrer-Policy", "X-Request-Id"} {
if rec.Header().Get(h) == "" {
t.Errorf("missing header %s", h)
}
}
}
func TestBodyLimit(t *testing.T) {
srv := New(echo(), Config{MaxBodyBytes: 10, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
// Declared length over the cap: rejected before the handler runs.
rec := httptest.NewRecorder()
srv.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(strings.Repeat("a", 11))))
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("declared length: got %d", rec.Code)
}
// Unknown length (chunked): stopped by MaxBytesReader while reading.
req := httptest.NewRequest(http.MethodPost, "/", io.MultiReader(strings.NewReader(strings.Repeat("a", 64))))
req.ContentLength = -1
rec = httptest.NewRecorder()
srv.Handler.ServeHTTP(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("streamed body: got %d", rec.Code)
}
}
func TestPanicDoesNotLeak(t *testing.T) {
var logs bytes.Buffer
srv := New(echo(), Config{Logger: slog.New(slog.NewJSONHandler(&logs, nil))})
rec := httptest.NewRecorder()
srv.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/panic", nil))
if rec.Code != http.StatusInternalServerError {
t.Fatalf("got %d", rec.Code)
}
if strings.Contains(rec.Body.String(), "hunter2") {
t.Fatal("panic detail leaked to the client")
}
if !strings.Contains(logs.String(), "hunter2") {
t.Fatal("panic detail should be in the server log for responders")
}
}
func TestAuditLine(t *testing.T) {
var logs bytes.Buffer
srv := New(echo(), Config{Logger: slog.New(slog.NewJSONHandler(&logs, nil))})
req := httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(`{"card":"4111111111111111"}`))
req.Header.Set("Authorization", "Bearer secret-token")
req.Header.Set("X-Authenticated-Subject", "admin") // forged by the client
srv.Handler.ServeHTTP(httptest.NewRecorder(), req)
var line map[string]any
if err := json.Unmarshal(bytes.TrimSpace(logs.Bytes()), &line); err != nil {
t.Fatalf("audit line is not one JSON object: %v\n%s", err, logs.String())
}
if line["path"] != "/orders" || line["status"].(float64) != 204 || line["request_id"] == "" {
t.Fatalf("unexpected audit line: %v", line)
}
if line["subject"] != "" {
t.Fatalf("client-supplied subject must be dropped, got %v", line["subject"])
}
if strings.Contains(logs.String(), "4111") || strings.Contains(logs.String(), "secret-token") {
t.Fatal("audit log must not contain bodies or credentials")
}
}| Threat (STRIDE) | Before | After |
|---|---|---|
| D: Slowloris | No timeouts | ReadHeaderTimeout 5 s and friends |
| D: huge body | Unlimited | MaxBytesReader, 413 |
| I: error details | decode failed: ... to the client | Generic 500/400; details only in the log |
| I: PII in logs | Whole payload logged | Method, path, status, ids only |
| S: forged identity header | (no identity at all) | Client X-Authenticated-Subject deleted before handlers |
| R: no record | Nothing | One audit line with request id per request |
| T/E: mass assignment | Role decoded from input | Handlers decode into request-specific types (not shown; see Laravel $fillable) |
The Go angle
Go's standard library gives you most controls but few defaults: http.ListenAndServe builds a zero-value Server, and its documentation says a zero ReadTimeout means "there will be no timeout", so production code always constructs http.Server explicitly. http.MaxBytesReader and the typed *http.MaxBytesError make body limits testable. log/slog gives structured audit lines; keep a separate handler for audit events if they go to a different store. crypto/rand (not math/rand) for ids and tokens. Since Go 1.25, http.CrossOriginProtection offers Sec-Fetch-Site based CSRF protection for cookie-authenticated handlers; our module stays on go 1.24 and therefore does not use it. For the supply chain, go.sum plus the checksum database pins module content, and govulncheck reports only vulnerabilities reachable from your call graph. Embedding the model with //go:embed keeps the tool a single binary for CI.
Laravel
Before
A controller that works in a demo and fails the threat model: no authorization (IDOR), forceCreate($request->all()) (mass assignment), the full payload in the default log, a guessable "share" URL, and a silent delete.
<?php
namespace App\Http\Controllers;
use App\Models\Invoice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
// Before: works in a demo, fails a threat model. Every method maps to a STRIDE letter.
class InvoiceController extends Controller
{
// E: no authorization. Any logged-in user can read any invoice by changing the id (IDOR).
public function show(Invoice $invoice)
{
return $invoice;
}
// T + E: mass assignment of the whole request, including "status" and "tenant_id".
public function store(Request $request)
{
$invoice = Invoice::forceCreate($request->all());
// I: the full payload (bank account included) is written to the default log.
Log::info('invoice created', $request->all());
return $invoice;
}
// S + T: a "secret" link that is only a guessable id; anyone can change it or share it forever.
public function shareLink(Invoice $invoice)
{
return url('/invoices/'.$invoice->id.'/download');
}
// R: an admin deletes an invoice and nothing records who did it.
public function destroy(Invoice $invoice)
{
$invoice->delete();
return response()->noContent();
}
}After
The same features, each method naming the STRIDE letter its control answers. Laravel 13 provides every control as a framework default or a one-liner; the code below uses only APIs from the 13.x documentation.
The model limits mass assignment and encrypts the bank account with the encrypted cast; #[UsePolicy] binds the policy.
<?php
namespace App\Models;
use App\Policies\InvoicePolicy;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Model;
#[UsePolicy(InvoicePolicy::class)]
class Invoice extends Model
{
// Tampering: only these fields can ever be mass assigned.
protected $fillable = ['customer_id', 'amount_cents', 'currency', 'bank_account'];
protected function casts(): array
{
return [
// Information disclosure: encrypted with APP_KEY (AES-256-CBC + MAC) before it reaches the database.
'bank_account' => 'encrypted',
'amount_cents' => 'integer',
];
}
}The policy is deny-by-default, answers a foreign invoice with denyAsNotFound(), and enforces separation of duties on delete.
<?php
namespace App\Policies;
use App\Models\Invoice;
use App\Models\User;
use Illuminate\Auth\Access\Response;
// Elevation of privilege: one place answers "may this user do this to this invoice?".
// Fail-safe default: anything not explicitly allowed is denied.
class InvoicePolicy
{
public function view(User $user, Invoice $invoice): Response
{
// Information disclosure: a foreign invoice is answered with 404, not 403,
// so the caller cannot even learn that the id exists.
return $user->tenant_id === $invoice->tenant_id
? Response::allow()
: Response::denyAsNotFound();
}
public function create(User $user): bool
{
return $user->hasVerifiedEmail();
}
public function delete(User $user, Invoice $invoice): bool
{
// Separation of duties: the person who issued an invoice cannot also delete it.
return $user->tenant_id === $invoice->tenant_id
&& $user->is_finance_admin
&& $user->id !== $invoice->created_by;
}
}The controller authorises every action (complete mediation), validates input, takes tenant and author from the session, writes audit events without payloads, and issues a temporary signed URL.
<?php
namespace App\Http\Controllers;
use App\Models\Invoice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
// After: each method names the STRIDE letter its control answers.
class InvoiceController extends Controller
{
// E + I: complete mediation, the policy runs on every request.
public function show(Invoice $invoice)
{
Gate::authorize('view', $invoice);
return $invoice->only(['id', 'amount_cents', 'currency', 'status']);
}
// T: validated fields only; tenant and author come from the session, never from input.
public function store(Request $request)
{
Gate::authorize('create', Invoice::class);
$data = $request->validate([
'customer_id' => ['required', 'integer'],
'amount_cents' => ['required', 'integer', 'min:1', 'max:100000000'],
'currency' => ['required', 'in:EUR,USD,GBP'],
'bank_account' => ['required', 'string', 'max:34'],
]);
$invoice = new Invoice($data);
$invoice->tenant_id = $request->user()->tenant_id;
$invoice->created_by = $request->user()->id;
$invoice->save();
// R: an audit record with actor, action, object; no payload, no secrets.
Log::channel('audit')->info('invoice.created', [
'actor' => $request->user()->id,
'invoice' => $invoice->id,
'ip' => $request->ip(),
]);
return response()->json(['id' => $invoice->id], 201);
}
// S + T: an HMAC-signed link that expires; changing the id or the expiry breaks the signature.
public function shareLink(Invoice $invoice)
{
Gate::authorize('view', $invoice);
return ['url' => URL::temporarySignedRoute(
'invoices.download', now()->plus(minutes: 30), ['invoice' => $invoice->id]
)];
}
// R + separation of duties: the policy forbids self-deletion, the log records who did it.
public function destroy(Request $request, Invoice $invoice)
{
Gate::authorize('delete', $invoice);
$invoice->delete();
Log::channel('audit')->warning('invoice.deleted', [
'actor' => $request->user()->id,
'invoice' => $invoice->id,
]);
return response()->noContent();
}
}Login: Hash::check, Hash::needsRehash, a per-email-and-IP limiter against credential stuffing, one generic message (no user enumeration), session regeneration and audit events.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
// Spoofing controls at the front door: slow password hashing, rehash on login,
// a per-account-and-IP limit against credential stuffing, one generic error.
class LoginController extends Controller
{
public function store(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required', 'string'],
]);
$key = 'login:'.Str::lower($credentials['email']).'|'.$request->ip();
if (RateLimiter::tooManyAttempts($key, 5)) {
// D + S: the attacker's guess rate is capped; the account is not locked for its owner forever.
throw ValidationException::withMessages([
'email' => 'Too many attempts. Try again in '.RateLimiter::availableIn($key).' seconds.',
]);
}
$user = User::where('email', $credentials['email'])->first();
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
RateLimiter::increment($key);
// R + detective control: failed logins are evidence for credential-stuffing alerts.
Log::channel('audit')->notice('auth.failed', ['email_hash' => hash('sha256', Str::lower($credentials['email'])), 'ip' => $request->ip()]);
// I: the same message whether the email exists or not (no user enumeration).
throw ValidationException::withMessages(['email' => 'These credentials do not match our records.']);
}
if (Hash::needsRehash($user->password)) {
// Corrective: old hashes are upgraded to the current work factor on the next login.
$user->forceFill(['password' => Hash::make($credentials['password'])])->save();
}
RateLimiter::clear($key);
Auth::login($user);
$request->session()->regenerate(); // session fixation
Log::channel('audit')->info('auth.login', ['actor' => $user->id, 'ip' => $request->ip()]);
return redirect()->intended('/dashboard');
}
}Named rate limiters (one for the API, a much smaller one for exports) and the routes that use them, with password.confirm as step-up and signed on the anonymous download.
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// D: per-user (or per-IP for guests) API quota; 429 with Retry-After when exceeded.
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
// D: expensive exports get their own, much smaller budget (bulkhead for a hot endpoint).
RateLimiter::for('exports', function (Request $request) {
return [
Limit::perMinute(2)->by($request->user()?->id),
Limit::perDay(20)->by($request->user()?->id),
];
});
}
}<?php
use App\Http\Controllers\InvoiceController;
use App\Http\Controllers\LoginController;
use App\Models\Invoice;
use Illuminate\Support\Facades\Route;
// Every route states its controls: who may call it (auth), how often (throttle),
// what proves the link was ours (signed). CSRF comes from the web group itself.
Route::post('/login', [LoginController::class, 'store']);
Route::middleware(['auth', 'verified', 'throttle:api'])->group(function () {
Route::get('/invoices/{invoice}', [InvoiceController::class, 'show']);
Route::post('/invoices', [InvoiceController::class, 'store']);
Route::post('/invoices/{invoice}/share', [InvoiceController::class, 'shareLink']);
Route::delete('/invoices/{invoice}', [InvoiceController::class, 'destroy'])
->middleware('password.confirm'); // step-up for a destructive action
Route::get('/exports/invoices', fn () => response()->streamDownload(fn () => print ('...'), 'invoices.csv'))
->middleware('throttle:exports');
});
// No session needed: the HMAC signature and the expiry are the authorization (403 if tampered).
Route::get('/invoices/{invoice}/download', function (Invoice $invoice) {
return response()->download(storage_path('invoices/'.$invoice->id.'.pdf'));
})->name('invoices.download')->middleware('signed');Application wiring: preventRequestForgery(except: [...]) for the one webhook that is authenticated by signature instead, trustProxies restricted to the load balancers (documentation range), and the security headers middleware.
<?php
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// T + S: PreventRequestForgery checks Sec-Fetch-Site, then falls back to the CSRF token.
// Only the payment webhook is exempt; it is authenticated by the provider's signature instead.
$middleware->preventRequestForgery(except: [
'webhooks/psp',
]);
// S: only our load balancers may set X-Forwarded-For (documentation range used here).
$middleware->trustProxies(at: [
'192.0.2.0/24',
]);
$middleware->append(SecurityHeaders::class);
})
->withExceptions(function (Exceptions $exceptions): void {
// I: with APP_DEBUG=false (production) users see a generic error page; details stay in the log.
})
->create();<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
// Secure by default at the response layer: the same headers as the Go server.
class SecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
$response->headers->set('Content-Security-Policy', "default-src 'self'; frame-ancestors 'none'; object-src 'none'");
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set('Permissions-Policy', 'geolocation=(), camera=(), microphone=()');
$response->headers->remove('X-Powered-By');
return $response;
}
}| STRIDE | Laravel 13 control | Where |
|---|---|---|
| S | Hash (bcrypt default), RateLimiter::tooManyAttempts, session()->regenerate(), signed middleware | LoginController, routes |
| T | PreventRequestForgery (Sec-Fetch-Site then CSRF token), $fillable, validation, signed URLs | bootstrap/app.php, model, controller |
| R | Log::channel('audit') with actor and object ids | Controllers |
| I | encrypted cast (AES-256-CBC + MAC), denyAsNotFound(), only([...]) responses, generic errors with APP_DEBUG=false | Model, policy, controller |
| D | RateLimiter::for + throttle: middleware, separate export limiter | Provider, routes |
| E | Policies via #[UsePolicy], Gate::authorize, password.confirm step-up | Policy, controller, routes |
The Laravel angle
Laravel 13's defaults already cover a large part of the STRIDE grid: the web middleware group includes PreventRequestForgery, which "checks the browser's Sec-Fetch-Site header" and "falls back to traditional CSRF token validation" (419 on mismatch; 403 in originOnly mode); the Hash facade uses bcrypt by default with Argon2 available; Crypt and the encrypted cast use "the AES-256-CBC cipher" with a MAC, and APP_PREVIOUS_KEYS lets you rotate APP_KEY; URL::temporarySignedRoute plus the signed middleware turn a link into a capability that cannot be edited. What Laravel cannot decide for you: which policy method runs on which route (complete mediation is your job), what goes into the audit channel and where that channel ships (a store the app cannot edit), the numbers in your rate limiters, and whether trustProxies lists only your real proxies. PHP-FPM workers are per request, so rate limiter state must live in a shared cache (Redis), which is the default for production deployments.
Solving the classic problems
IDOR: changing an id returns someone else's data
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Policy check per object | Gate::authorize('view', $invoice) on every action | Complete mediation; one place to audit | Must be applied to every route; test it |
| Scope queries by tenant | Global scope or where tenant_id = ? from the session | Defence in depth below the policy | Forgotten in raw queries and reports |
| Row-level security in PostgreSQL | RLS policy on tenant_id with a per-request setting | Holds even if the app forgets | Connection-pool and migration care (Database Security) |
| Unguessable ids (UUIDv4/ULID) | Random identifiers | Slows enumeration | Not an access control; never alone (open design) |
Credential stuffing on login
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| MFA / passkeys | WebAuthn, TOTP | Stolen passwords stop working | Enrolment UX, recovery flows |
| Per-account + per-IP throttling | Laravel RateLimiter keyed on email plus IP | Caps guesses per account | Distributed botnets rotate IPs; combine with account-level limits |
| Breached-password check | Compare hash prefixes against a breach corpus at sign-up and login | Removes reused passwords | External dependency or local dataset |
| Detection | Alert on failed-login ratio across all IPs | Sees low-and-slow attacks | Needs a baseline |
Secrets committed to git
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Rotate immediately | Revoke and reissue the key | Only real fix once leaked | Requires rotatable design |
| Secret scanning | Pre-commit hook and host-side scanning | Catches before push | False positives |
| Workload identity | IAM roles for service accounts, OIDC to cloud from CI | No long-lived secret exists | Cloud-specific setup |
| Secrets manager | Vault, AWS Secrets Manager, Kubernetes External Secrets | Central rotation and audit | Another critical dependency |
Slowloris and oversized requests
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Server timeouts | ReadHeaderTimeout, ReadTimeout, IdleTimeout | Frees goroutines and sockets | Long uploads need a per-route design |
| Body and header limits | MaxBytesReader, MaxHeaderBytes, NGINX client_max_body_size | Bounded memory | Upload endpoints need their own limit |
| Reverse proxy buffering | NGINX/Envoy/CDN in front | Slow clients handled at the edge | Another layer to configure |
| Rate limiting and shedding | Per-client limits, load shedding | Protects shared capacity | Tuning |
A malicious or vulnerable dependency
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Lockfiles and checksums | go.sum, composer.lock, image digests | No silent drift | Upgrades become explicit work |
| Reachability-aware scanning | govulncheck, composer audit | Fewer false alarms | Coverage differs per ecosystem |
| SBOM per build | Syft / CycloneDX stored with the artifact | Answer "are we affected?" in minutes | Storage and tooling |
| Signature verification at deploy | Cosign + admission policy | Only CI-built artifacts run | Key/identity policy to maintain |
Attackers erasing their tracks
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Append-only grants + trigger | SQL in Mechanics | App role cannot rewrite history | Superuser still can, hence the next rows |
| Hash chain | Each row hashes the previous | Edits become detectable | Verification job needed |
| Ship to a separate account | Log pipeline to a different cloud account / WORM bucket | Survives a full app compromise | Cost, retention policy |
| Alert on gaps | Missing sequence or silence alerts | Detects disabled logging | Noise |
Verbose errors leak internals
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Generic errors outside | Go Recover middleware; Laravel APP_DEBUG=false | No stack traces or DSNs to clients | Support needs request ids to debug |
| Request ids | X-Request-Id in response and log | Correlate a user report to the log | None worth mentioning |
| Redaction rules | Never log bodies, cookies, Authorization | Logs safe to share with responders | Discipline; test it (TestAuditLine) |
Choosing
Which threat-modelling technique
| Situation | Technique | Extra | Reason |
|---|---|---|---|
| New service or feature with a diagram | STRIDE per element | Generated checklist in CI | Systematic, covers technical controls |
| One high-value goal (move money, read all tenants) | Attack tree | Cost per leaf | Finds the cheapest path |
| Money- or permission-changing workflows | Abuse cases | Automated tests | Finds business-logic and race flaws |
| Personal data processing | LINDDUN | DPIA under GDPR | Privacy harms STRIDE does not name |
| Detection and SOC planning | MITRE ATT&CK | Log-source mapping | Real adversary behaviour after access |
| Prioritising vulnerability patches | CVSS v4 BTE + reachability | govulncheck | Base score alone overstates or understates |
Which control first, by situation
| Situation | First control | Second layer | Reason |
|---|---|---|---|
| Public login | MFA or passkeys | Per-account throttle + breached-password check | Credential abuse is the leading vector |
| Multi-tenant API | Policy per object | Tenant-scoped queries or RLS | IDOR is the most common access-control failure |
| Internal service calls | mTLS / workload identity | Per-service authorization policy | No implicit trust from network location |
| File downloads for anonymous users | Temporary signed URL | Short expiry, throttle | Capability without a session |
| Webhooks from providers | Signature + timestamp check | IP allow-list, idempotency | Spoofed callbacks mark orders paid |
| Card payments | Tokenise at the PSP (hosted fields) | Segment what remains | Removes most PCI DSS scope |
| Admin and support tools | SSO + MFA + named accounts | Audit every action, step-up for destructive ones | Insider and phishing risk, accountability |
| Build and deploy pipeline | Lockfiles + signature verification | SBOM + SLSA provenance | Supply chain failures |
How much depth for how much risk
| Asset sensitivity | Minimum layers | Detective requirement | Review |
|---|---|---|---|
| Public content | Edge + application limits | Error-rate alerts | Lightweight checklist |
| Internal business data | Identity + application authz + data roles | Audit of writes | Full checklist |
| PII | Above + encryption at rest + minimisation | Audit of reads and exports | Checklist + DPIA |
| Card data, credentials, signing keys | Above + isolation (separate account/cluster) + HSM/KMS | Real-time alerts, separate log account | Checklist + external review |
In architecture: from a single process to a distributed system
Monolith: one process, one database
The trust boundaries are few: internet to app, app to database. The threat model fits on one page and most controls are framework defaults: Laravel's CSRF, hashing, encrypted cookies, policies and throttling. The dangerous simplicity is a single database role with full rights and an admin panel inside the same app; give the app a least-privilege role, put admin routes behind SSO with MFA, and keep the audit table append-only. Concrete example: a Laravel shop with one PostgreSQL; the worked STRIDE table collapses to about ten rows, the most important being per-object policies and the DB role.
Modular monolith: boundaries without the network
Modules introduce internal trust boundaries that are not network boundaries: the billing module should not read the identity module's password hashes even though they share a process and maybe a database. Enforce it with separate schemas and database roles per module, module-level authorization at the public module interface, and no shared "god" service that every module calls with elevated rights (least common mechanism). Example: billing gets SELECT on a view of customers, not the users table.
Microservices: every arrow is a decision
Each service adds a process, a store and several flows, and every flow crosses a trust boundary. Without zero trust, compromising one service means reaching all of them. The flow for "place order" shows what must survive:
Order placement across services
1 browser -> API gateway: OIDC session, WAF, rate limit (S, D at the edge)
2 gateway -> orders: JWT with user + tenant, validated by orders (S, E; never trust a header set by the client)
3 orders -> payments: mTLS (service identity) + per-service authz (S, T, I between services)
4 orders -> broker "order.placed": producer ACL, no card data (T, I on the queue)
5 fulfilment consumes: verifies envelope, idempotent processing (T, D)
6 each service: own DB role, own secrets, audit events with trace id (E, R)Gateways and meshes carry part of this (see API Gateway, BFF & Service Mesh and mTLS), but authorization of business objects stays in each service. Broker-side controls (TLS, SASL, ACLs, payload encryption) are in Messaging Security.
Distributed data: replicas, caches, regions
Every copy of the data is another asset to protect: read replicas need the same access controls as the primary, caches (Redis) need authentication and must not hold data the requester could not read (cache keys per tenant), analytics copies and backups need encryption and their own access policies, and multi-region deployments raise data-residency questions under GDPR. Integrity across copies needs authenticated replication channels; availability gains from replicas also widen the confidentiality surface. Example: a Redis cache keyed only by invoice:43 served tenant A's invoice to tenant B after a policy check was skipped on cache hits; the fix is checking authorization before the cache lookup and including the tenant in the key.
Scaling path: 1x, 10x, 100x
| Scale | What changes in security design |
|---|---|
| 1x (one team, one app) | Framework defaults, one threat model, least-privilege DB role, MFA for admins, backups tested |
| 10x (several teams and services) | Paved-road templates (secure server, CI checks), threat model per service in the repo, mTLS, central logging, SOC 2 evidence |
| 100x (many teams, regions, regulated data) | Zero trust access, policy as code (OPA, Cedar), signed artifacts with admission control, SBOM per build, dedicated detection engineering mapped to ATT&CK, per-region data controls, incident drills |
Lab: threat-model a system and harden a server
Experiment 1: generate the STRIDE checklist (run)
cd docs/snippets/system-design/security-foundations-cia-stride/go
go run ./cmd/stride | head -8# Threat checklist: shop: web app + API + queue + DB
| Element | STRIDE | Violates | Question | Severity | Status | Missing controls |
| --- | --- | --- | --- | --- | --- | --- |
| Orders API (Go) | R | non-repudiation | Are security-relevant actions recorded so they cannot be denied? | high | OPEN | audit-log (detective) |
| Orders API (Go) | D | availability | Can a caller exhaust its CPU, memory, connections or threads? | high | OPEN | rate-limit (preventive) |
| Audit log | R | non-repudiation | Can audit records be altered or deleted? | high | OPEN | integrity (preventive) |
| Audit log | I | confidentiality | Can stored data be read by someone who should not? | high | OPEN | enc-rest (preventive) |The last line (run on this machine) is Open per category: S=2 T=5 R=5 I=7 D=10 E=2 (total threats 53) and the exit status is 1 because open high rows exist.
Experiment 2: close a threat and watch the gate (run, then edit)
Add "audit-log", "rate-limit" to the api element's controls in a copy of model.json and run go run ./cmd/stride my-model.json. Expected: the two Orders API rows move to "mitigated" at the bottom of the table, and the R and D counts drop by one each. The exit status stays 1 until every high row is closed or the model records the control.
Experiment 3: break the model on purpose (expected, not run)
Add {"id": "f9", "kind": "data_flow", "from": "api", "to": "ghost"}. Expected output on stderr and exit status 2:
invalid model:
f9: endpoint "ghost" does not existExperiment 4: the secure server tests (run)
go test -race ./...ok academy/security-foundations-cia-stride/secureserver
ok academy/security-foundations-cia-stride/threatmodelThe tests prove: timeouts default to non-zero, five security headers and the request id are present, a declared 11-byte body over a 10-byte cap and a streamed 64-byte body both get 413, a panic containing a password returns a generic 500 while the detail stays in the log, and the audit line contains neither the card number, the bearer token nor the forged subject header.
Experiment 5: Slowloris against Before and After (expected, not run)
Run before/main.go, open a TCP connection and send one header byte every 10 seconds (nc localhost 8080, type POST /orders HTTP/1.1 and wait). Expected: the Before server keeps the connection open indefinitely. Against a server built with secureserver.New the connection is closed after the 5-second ReadHeaderTimeout.
Experiment 6: Laravel controls (expected, not run)
| Request | Expected response |
|---|---|
GET /invoices/43 as a user of another tenant | 404 (policy denyAsNotFound) |
POST /invoices without CSRF token from an old browser without Sec-Fetch-Site | 419 |
Download URL with the invoice parameter changed | 403 (signed middleware) |
| Download URL after 30 minutes | 403 (expired temporary signature) |
| 6th failed login for the same email and IP within the window | Validation error "Too many attempts. Try again in N seconds." |
| 61st API request in one minute | 429 with Retry-After |
DELETE /invoices/42 by the invoice's creator | 403 (separation of duties in the policy) |
Common misconceptions
| Belief | Reality |
|---|---|
| "Hackers mostly use zero-days" | Credential abuse (22%) and exploitation of known vulnerabilities lead in the DBIR 2025 press release; zero-days are concentrated on edge devices and VPNs |
| "HTTPS makes us secure" | TLS covers T and I on flows; it does nothing for S, R, D or E at processes |
| "Internal services can trust each other" | NIST SP 800-207: no implicit trust from network location |
| "Encryption gives integrity" | Only authenticated encryption or a MAC does; plain CBC does not |
| "Our logs give non-repudiation" | Not with shared accounts and logs the app can edit |
| "Obscure URLs are access control" | Open design: protection must rest on keys, not secrecy of the design |
| "A threat model is a one-time document" | OWASP: it should be maintained alongside the system |
| "CVSS Base is our risk" | Apply Threat and Environmental metrics and reachability |
| "Compliance equals security" | Compliance is an audited baseline, not protection against a motivated attacker |
| "Defense in depth means more tools" | Layers must fail independently; two of the same is one layer |
| "Pinning in composer.json is enough" | Ranges drift; lockfiles and checksums pin content |
| "Detection can wait until we are bigger" | Without detective controls, prevention failures are discovered by customers |
Cheat sheet
| Topic | Remember |
|---|---|
| Why hacked | Credentials, known vulns, misconfiguration, supply chain, people; cheapest path wins |
| CIA | Confidentiality (read), integrity (change), availability (use); Saltzer & Schroeder 1975 |
| Beyond CIA | Authenticity, non-repudiation, accountability; Parkerian hexad adds possession, authenticity, utility |
| Four questions | What are we working on, what can go wrong, what will we do, did we do enough |
| DFD | Entities, processes, stores, flows, trust boundaries |
| STRIDE per element | Entity S,R; process all six; store T,I,D (+R for logs); flow T,I,D |
| Responses | Mitigate, eliminate, transfer, accept (with owner and expiry) |
| Scoring | Likelihood x impact at design; CVSS v4 BTE + reachability for patching |
| Attack trees | Goal at root, OR = alternatives, AND = all required, price the leaves |
| Defense in depth | Edge, network, identity, application, data, monitoring; each assumes the previous failed |
| Principles | Least privilege, fail-safe defaults, complete mediation, economy of mechanism, open design, separation of privilege |
| Zero trust | No implicit trust from network location; authenticate and authorise every request |
| Controls | Every high threat: one preventive and one detective; every asset: a corrective plan |
| Supply chain | Lockfiles, SBOM, signature verification (Sigstore), SLSA provenance |
| Compliance | SOC 2, ISO 27001, PCI DSS, GDPR as non-functional requirements; design to shrink scope |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Which three violation categories did Saltzer and Schroeder name, and which CIA property is each? Good to know
Answer
Answer: Unauthorized information release (confidentiality), unauthorized information modification (integrity), unauthorized denial of use (availability).
2 — Which STRIDE letters apply to a data flow, and why not R or E? Good to know
Answer
Answer: T, I and D. A flow does not act, so it cannot deny an action or gain privileges; those are asked of the processes at each end.
3 — A queue sits between the API and a worker. What new DFD elements does it add and which threats matter most? Important
Answer
Answer: A data store (the backlog) and two data flows. Tampering (forged messages from a compromised producer), information disclosure (sensitive data at rest in messages) and denial of service (queue flooding or poison loops). Controls: producer ACLs, signed envelopes, no sensitive payloads, max length and DLQ.
4 — Why is a CVSS 9.8 in a dependency not automatically a 9.8 risk for you? Must-know
Answer
Answer: Base describes the vulnerability in general. Your risk depends on reachability (govulncheck), exploit maturity (Threat metrics) and your environment and controls (Environmental metrics).
5 — Give two principles violated by an admin panel protected only by an unlisted URL. Must-know
Answer
Answer: Open design (protection depends on secrecy of the design) and complete mediation (no authorization check on access); also fail-safe defaults.
6 — What separates defense in depth from simply buying more security products? Must-know
Answer
Answer: Independence: each layer uses a different mechanism and credentials so one failure does not defeat the others, and each is designed assuming the outer layer already failed.
7 — Name a preventive, a detective and a corrective control against ransomware on the database. Must-know
Answer
Answer: Preventive: no public endpoint, least-privilege roles, MFA for admins. Detective: alerts on mass writes and snapshot deletion. Corrective: immutable backups in a separate account with tested restores.
8 — Why does the Go audit middleware delete X-Authenticated-Subject from incoming requests? Important
Answer
Answer: To prevent spoofing: only the inner authentication layer may set the subject after verifying a credential; a client-supplied value would be logged as if it were a verified identity.
9 — What does Laravel's PreventRequestForgery check first, and what status do token and origin failures return? Important
Answer
Answer: It checks the Sec-Fetch-Site header first, then falls back to the CSRF token. A token mismatch returns 419; in originOnly mode a failed origin check returns 403.
10 — How does tokenising card numbers at the payment provider change PCI DSS? Important
Answer
Answer: Card numbers never reach your servers, so most of your systems leave the cardholder data environment and PCI DSS scope shrinks to the page that embeds the provider's field.
11 — What does Sigstore record in Rekor, and why does that remove key management? Good to know
Answer
Answer: The artifact digest, signature and short-lived certificate. Signing uses an ephemeral key bound by Fulcio to an OIDC identity; verifiers check the identity and the log inclusion instead of a long-lived public key.
12 — Which design decisions make the first hour of an incident shorter? Must-know
Answer
Answer: Audit events with request ids, per-key and per-tenant credentials that can be revoked individually, kill switches, immutable separate-account backups and synchronised clocks.
Glossary
| Term | Meaning |
|---|---|
| Attack surface | All entry and exit points an attacker can reach, plus the assets behind them |
| Threat actor | An adversary class defined by motive, capability and access |
| Asset | Anything worth protecting: data, capabilities, availability |
| Misconfiguration | An unsafe setting (public bucket, default password, debug mode) |
| Credential stuffing | Trying leaked username/password pairs from other breaches (ATT&CK T1110.004) |
| Phishing | Electronically delivered social engineering (ATT&CK T1566) |
| Social engineering | Manipulating people into giving access or information |
| Zero-day | A vulnerability exploited before a fix is available |
| Supply chain attack | Compromise through a dependency, build system or vendor (ATT&CK T1195) |
| Ransomware | Malware that encrypts or steals data for extortion |
| CIA triad | Confidentiality, integrity, availability |
| Confidentiality | Only authorised parties can read information |
| Integrity | Information cannot be changed without authorisation or detection |
| Availability | Information and services are usable when needed |
| Authenticity | An entity or data is genuine |
| Non-repudiation | An actor cannot deny an action they performed |
| Accountability | Actions trace uniquely to an actor |
| Parkerian hexad | CIA plus possession or control, authenticity, utility (Parker, 1998) |
| Threat modelling | Structured analysis of what can go wrong and what to do about it |
| Data flow diagram (DFD) | Model of entities, processes, stores and flows |
| Trust boundary | A line where the level of trust changes |
| STRIDE | Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege |
| Spoofing | Pretending to be another user or system |
| Tampering | Unauthorised modification of data or code |
| Repudiation | Denying an action with no evidence to the contrary |
| Information disclosure | Exposing data to unauthorised parties |
| Denial of service | Making a system unavailable to legitimate users |
| Elevation of privilege | Gaining rights beyond those granted |
| STRIDE per element | Applying only the letters relevant to each DFD element type |
| DREAD | Damage, Reproducibility, Exploitability, Affected users, Discoverability scoring (historical) |
| CVSS | FIRST's Common Vulnerability Scoring System; v4.0 has Base, Threat, Environmental, Supplemental groups |
| Attack tree | Goal-rooted tree of attack paths with AND/OR nodes (Schneier 1999) |
| Abuse case | A story an attacker wants to succeed, turned into a test that must fail |
| LINDDUN | Privacy threat-modelling method |
| PASTA | Risk-centric threat-modelling method linking business impact |
| MITRE ATT&CK | Knowledge base of adversary tactics and techniques |
| Defense in depth | Multiple independent layers of controls |
| Least privilege | Every program and user has only the privileges needed |
| Fail-safe defaults | Deny unless explicitly permitted |
| Separation of duties | Critical tasks split between people or roles |
| Separation of privilege | Requiring two keys or factors to unlock |
| Complete mediation | Every access to every object checked for authority |
| Economy of mechanism | Keep protection mechanisms small and simple |
| Open design | Security must not depend on secrecy of the design |
| Least common mechanism | Minimise mechanisms shared between users |
| Psychological acceptability | The secure path must be easy to use |
| Zero trust | No implicit trust based on network location or ownership (NIST SP 800-207) |
| Secure by default | The out-of-the-box configuration is the safe one |
| Shift left | Moving security activities earlier in the lifecycle |
| Preventive control | Reduces the likelihood of a successful attack |
| Detective control | Identifies an attempt or compromise |
| Corrective control | Limits damage and restores the system |
| Residual risk | Risk remaining after controls, owned and accepted explicitly |
| Secrets management | Lifecycle of credentials: store, distribute, rotate, revoke, audit |
| SBOM | Software bill of materials: a nested inventory of components |
| Dependency pinning | Resolving dependencies to exact versions and hashes |
| Code signing | Binding an artifact to the identity that produced it |
| Sigstore | Keyless signing with Fulcio certificates and the Rekor transparency log; client Cosign |
| SLSA | Supply-chain Levels for Software Artifacts, build levels L0 to L3 |
| Security review checklist | Fixed questions and artefacts required before a design is approved |
| SOC 2 | AICPA report on controls for security, availability, processing integrity, confidentiality, privacy |
| ISO 27001 | International standard for an information security management system |
| PCI DSS | Payment card industry baseline for protecting account data |
| GDPR | EU data protection regulation; Art. 25 by design and default, Art. 32 security |
| Verizon DBIR | Verizon's annual Data Breach Investigations Report |
| OWASP | Open Worldwide Application Security Project: Top 10, cheat sheets, threat modelling guidance |
| NIST CSF | NIST Cybersecurity Framework 2.0: Govern, Identify, Protect, Detect, Respond, Recover |
| IDOR | Insecure direct object reference: access by changing an identifier |
| Slowloris | Holding connections open by sending headers very slowly |
References
- Saltzer and Schroeder, The Protection of Information in Computer Systems (1975), Section I: https://web.mit.edu/Saltzer/www/publications/protection/Basic.html
- Saltzer and Schroeder paper index: https://web.mit.edu/Saltzer/www/publications/protection/
- OWASP Threat Modeling Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Threat_Modeling_Cheat_Sheet.html
- OWASP Threat Modeling Process: https://owasp.org/www-community/Threat_Modeling_Process
- OWASP Secure Product Design Cheat Sheet (defense in depth): https://cheatsheetseries.owasp.org/cheatsheets/Secure_Product_Design_Cheat_Sheet.html
- OWASP HTTP Headers Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html
- OWASP Top 10:2025: https://owasp.org/Top10/2025/
- Shostack, Threat Modeling book page: https://shostack.org/books/threat-modeling-book
- Verizon 2025 DBIR press release: https://www.verizon.com/about/news/2025-data-breach-investigations-report
- Verizon DBIR landing page (2026 edition): https://www.verizon.com/business/resources/reports/dbir/
- MITRE ATT&CK: https://attack.mitre.org/
- MITRE ATT&CK T1110.004 Credential Stuffing: https://attack.mitre.org/techniques/T1110/004/
- MITRE ATT&CK T1566 Phishing: https://attack.mitre.org/techniques/T1566/
- MITRE ATT&CK T1195 Supply Chain Compromise: https://attack.mitre.org/techniques/T1195/
- FIRST CVSS v4.0 Specification: https://www.first.org/cvss/v4.0/specification-document
- Schneier, Attack Trees (1999): https://www.schneier.com/academic/archives/1999/12/attack_trees.html
- NIST SP 800-53 Rev. 5: https://csrc.nist.gov/pubs/sp/800/53/r5/upd1/final
- NIST Cybersecurity Framework 2.0 (CSWP 29): https://nvlpubs.nist.gov/nistpubs/CSWP/NIST.CSWP.29.pdf
- NIST CSF 2.0 publication page: https://csrc.nist.gov/pubs/cswp/29/the-nist-cybersecurity-framework-csf-20/final
- NIST SP 800-207 Zero Trust Architecture: https://csrc.nist.gov/pubs/sp/800/207/final
- CISA SBOM: https://www.cisa.gov/sbom
- CISA Secure by Design: https://www.cisa.gov/securebydesign
- Sigstore overview: https://docs.sigstore.dev/about/overview/
- SLSA v1.0 levels: https://slsa.dev/spec/v1.0/levels
- PCI DSS (PCI SSC): https://www.pcisecuritystandards.org/standards/pci-dss/
- AICPA SOC 2: https://www.aicpa-cima.com/topic/audit-assurance/audit-and-assurance-greater-than-soc-2
- GDPR Article 25: https://gdpr-info.eu/art-25-gdpr/
- GDPR Article 32: https://gdpr-info.eu/art-32-gdpr/
- Wikipedia, Parkerian Hexad (secondary source): https://en.wikipedia.org/wiki/Parkerian_Hexad
- Wikipedia, DREAD (secondary source): https://en.wikipedia.org/wiki/DREAD_(risk_assessment_model)
- Go
net/http: https://pkg.go.dev/net/http - Go vulnerability management (govulncheck): https://go.dev/doc/security/vuln/
- Go modules reference (go.sum, checksum database): https://go.dev/ref/mod
- Laravel 13 CSRF protection: https://laravel.com/docs/13.x/csrf
- Laravel 13 Hashing: https://laravel.com/docs/13.x/hashing
- Laravel 13 Encryption: https://laravel.com/docs/13.x/encryption
- Laravel 13 URL generation (signed URLs): https://laravel.com/docs/13.x/urls
- Laravel 13 Rate limiting: https://laravel.com/docs/13.x/rate-limiting
- Laravel 13 Routing (named rate limiters): https://laravel.com/docs/13.x/routing
- Laravel 13 Authorization: https://laravel.com/docs/13.x/authorization
- Laravel 13 Authentication (password confirmation, session regeneration): https://laravel.com/docs/13.x/authentication
- Laravel 13 Eloquent mutators and casts (encrypted cast): https://laravel.com/docs/13.x/eloquent-mutators
- Laravel 13 Requests (trusted proxies): https://laravel.com/docs/13.x/requests
- Laravel 13 Logging: https://laravel.com/docs/13.x/logging