Web Security 20 🛡️ Threat Modeling, Testing & Incident Response — Running STRIDE, SAST/DAST automation, audit logging, and breach playbooks
Every chapter before this one described a control. This one describes how you decide which controls to build, how you verify they work, how you record what happened, and what you do on the day one of them fails. It is the chapter that makes the other nineteen operational rather than aspirational, and it is the one most often skipped because none of its outputs are visible in a demo.
Threat modeling is the design-time activity. It is a structured conversation held before the code exists, in which the team draws what it is building, marks where trust changes hands, and asks what an attacker would do at each of those boundaries. STRIDE is the checklist that makes the conversation exhaustive rather than anecdotal — six categories of threat, each corresponding to a security property, each applicable to specific elements of a data flow diagram. Its output is not a document that gets filed; it is a prioritized list of mitigations that becomes the backlog for everything else in this series.
Security testing is the verification layer. Static analysis reads the code without running it, dynamic analysis attacks the running application, and neither replaces the other because they find different classes of defect. The engineering problem with both is not running them — the tools are free and the CI integration is a few lines — it is that an unprioritized scanner output is noise, and a team that ignores two thousand findings will ignore the one that matters. The chapter treats triage and the SARIF interchange format as first-class concerns because that is where the value lives.
Audit logging is the evidence layer. An application log tells you the service was healthy; an audit log tells you who did what, to which object, at what time, from where, and whether it succeeded. The distinction only becomes obvious during an incident, when the question is “which accounts accessed this customer’s records in the last ninety days” and the answer needs to be a query rather than an apology.
Incident response is the day the rest of it fails. It is a process with named roles, defined severities, containment options that were chosen in advance, and — the part that catches teams out — legal deadlines that begin at awareness rather than at confirmation. GDPR gives 72 hours to notify a supervisory authority. The SEC gives four business days once an incident is determined material. NIS2 gives 24 hours for an early warning. None of those clocks start when the investigation concludes.
This chapter works through the four in sequence, because that is the order of the calendar: model the threat at design, test the code at build, log the activity in production, and respond when the log shows something wrong.
Key point: Threat modeling decides what to build, security testing proves it was built, audit logging records what the built system actually did, and incident response is the plan for the day the first three were not enough — the four are a loop, not a list, and each one feeds the next.
Why it exists
The unbounded-threat-space problem. “Make it secure” is not an actionable requirement because there is no finite list of things that could go wrong. A threat model bounds the problem: it names the assets worth protecting, the actors who want them, the boundaries an attacker must cross, and the categories of attack available at each boundary. That bound is what turns security from an anxiety into a backlog, and a backlog is what a team can actually work through.
The design-time economics problem. A missing authorization check found during design costs a conversation. The same defect found in code review costs a day. Found in a penetration test it costs a sprint, and found in production by a customer it costs a disclosure, a notification, and a legal review. OWASP’s own framing of the cost curve is steep enough that a two-hour threat modeling session pays for itself the first time it prevents one architectural mistake — and it usually prevents several.
The scanner-noise problem. Static analysis tools report false positives at rates that make untriaged output actively harmful: a developer who dismisses fifty findings to reach the one real one learns to dismiss findings. The tooling problem is therefore not detection but prioritization — severity weighting, reachability analysis, a baseline that suppresses pre-existing findings so new ones stand out, and a format (SARIF) that lets the platform annotate the diff rather than dump a report.
The evidence problem. When a breach is discovered, the first three questions are always the same: what data was accessed, which accounts were involved, and when did it start. Answering them requires that the access was logged — with an actor, an object, a timestamp, an outcome, and a source — before anyone knew the question would be asked. Logs added after an incident can only describe the future.
The clock problem. Breach notification is a legal obligation with a statutory deadline, and the deadline is measured from awareness rather than from certainty. An organisation that spends a week investigating before telling its lawyer has already missed the GDPR window in most interpretations. The only defence is a playbook that names the decision-maker, defines “awareness,” and routes to legal counsel on a parallel track rather than sequentially after the technical investigation.
The rehearsal problem. An incident is the worst possible time to discover that nobody has the pager, that the credential rotation process is undocumented, that the on-call engineer has never used the SIEM, or that the communications team does not have a template. A tabletop exercise — a ninety-minute conversation in which the team walks through a hypothetical breach — surfaces all four at a cost of ninety minutes instead of four hours of production downtime.
The trade-off. Each of these activities competes directly with feature work, and each one can be done badly in a way that produces the artifact without the benefit: a threat model written by one person and never read, a scanner enabled and ignored, a log pipeline that captures everything and answers nothing, a playbook that names roles nobody holds. The design principle throughout is that the artifact must be used — the threat model drives the test plan, the test findings close threats, the logs answer the incident’s questions, and the post-mortem feeds the next threat model.
a. STRIDE — categories, diagrams, and the boundary worksheet
STRIDE is a checklist attributed to Loren Kohnfelder and Praerit Garg at Microsoft in 1999, and it remains the most widely used threat-listing framework because it is mnemonic, exhaustive at the category level, and maps cleanly to a property that a control can restore.
S Spoofing → Authentication (is the actor who they claim?)
T Tampering → Integrity (can the data be changed in transit or at rest?)
R Repudiation → Non-repudiation (can an action be denied afterwards?)
I Information discl. → Confidentiality (can data reach someone not entitled?)
D Denial of service → Availability (can the service be made useless?)
E Elevation of priv. → Authorization (can a limited actor gain powers?)
The framework is applied to a data flow diagram rather than to a feature list, because threats live at the boundaries the diagram makes visible. A DFD has four element types — external entity, process, data store, and data flow — and one annotation, the trust boundary, which is where data or control crosses from one privilege level to another. The boundary is the whole point of the diagram; a DFD without boundaries is a screenshot.
TRUST BOUNDARY MAP FOR A CHECKOUT FLOW
[customer]
│ ← boundary 1: internet → edge
════╪════════════════════════════════════════════
▼
(api-gateway) ──► (auth-service)
│ │
│ ▼
│ ╔══════════════╗
│ ║ auth tokens ║ ← boundary 2: service → secret store
│ ╚══════════════╝
▼ ← boundary 3: api → payment processor
(checkout) ──► [payment-api]
│
▼
╔═════════════╗
║ orders DB ║ ← boundary 4: service → persistent store
╚═════════════╝
Each element type admits a specific subset of STRIDE, which is what makes the exercise tractable rather than a free-association session. An external entity can be spoofed or repudiated. A process can be subjected to all six. A data store can be tampered with, disclosed, or made unavailable, and repudiation applies if it has no write log. A data flow can be tampered with, eavesdropped on, or interrupted.
STRIDE PER ELEMENT
Element S T R I D E
─────────────────────────────────────────────
External entity ✓ · ✓ · · ·
Process ✓ ✓ ✓ ✓ ✓ ✓
Data store · ✓ ✓ ✓ ✓ ·
Data flow · ✓ · ✓ ✓ ·
The worksheet is the deliverable. Each row is a threat, and each threat has a likelihood, an impact, a mitigation, and a state. The value of writing it down is that the mitigation becomes a ticket with an owner rather than a concern in someone’s head, and the state is what lets the next review see whether the model was acted on.
| Threat | Element | Category | Mitigation | State |
|---|---|---|---|---|
| Stolen session token replayed | Data flow | Spoofing | Bind session to device, rotate on privilege change | Done |
| Order total modified in flight | Data flow | Tampering | TLS plus server-side price recalculation | Done |
| Refund denied by an admin | Process | Repudiation | Immutable audit log with actor and reason | Open |
| Invoice IDs enumerate other tenants | Data store | Info disclosure | Scope query by tenant, return 404 | Done |
| Bulk export saturates the DB | Process | Denial of service | Per-account export limit, async job | Open |
| Support role can refund | Process | Elevation | Split invoice:read and invoice:refund | Done |
Adam Shostack’s four-question framing is the guide for running the session itself: what are we building, what can go wrong, what are we going to do about it, and did we do a good job. The first question is answered by the diagram, the second by STRIDE, the third by the worksheet, and the fourth by reviewing the model against the incidents and findings that have occurred since — which is where the loop closes and the model stops being a one-off artifact.
The cadence matters as much as the content. A threat model is a design activity, so it runs when the design changes: a new trust boundary, a new external integration, a new class of data, a new actor. It does not run per commit, and it does not need to cover the whole system every time. The working pattern is a lightweight model per significant change — thirty to sixty minutes, three to six people, one diagram, one worksheet — plus a full-system review once a year.
b. Security testing automation — SAST, DAST, and where each belongs
Static analysis reads source or bytecode without executing it. Its strength is coverage of code paths that tests never reach, its weakness is that it cannot know runtime state, and its characteristic failure mode is a high false-positive rate on taint flows that are in fact sanitized. The two tools that matter most in practice are Semgrep and CodeQL, and they differ in a way that determines where each fits.
Semgrep matches syntactic patterns you write yourself, which makes it fast, language-agnostic, and immediately useful for enforcing a team’s own conventions — “no innerHTML assignment without a sanitizer”, “no exec with a template literal”. CodeQL compiles the code into a relational database and runs declarative queries over it, which makes it slower and far better at interprocedural dataflow — following a tainted value across ten function calls and three files.
# .github/workflows/sast.yml
name: sast
on: [pull_request]
permissions:
contents: read
security-events: write # required to upload SARIF results
jobs:
semgrep:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# Registry rulesets cover OWASP Top 10 and common languages
- run: |
pip install semgrep
semgrep ci --sarif --output=semgrep.sarif
env:
SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }}
# SARIF is what puts findings inline on the pull request diff
- uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: semgrep.sarif
The security-events: write permission and the SARIF upload are the two lines that decide whether the tool changes behaviour. A scan whose output lands in a build log is a scan nobody reads; a scan whose findings annotate the exact line of the diff is a scan the author addresses before merging.
# CodeQL runs on a schedule and on main, not on every PR, because it is slow
codeql:
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v3
with:
queries: security-extended # broader than the default suite
- uses: github/codeql-action/analyze@v3
Dynamic analysis attacks a running application over HTTP the way an external attacker would. OWASP ZAP is the open-source standard, and it ships two scripts that map directly onto the CI problem: zap-baseline.py runs a passive scan in a couple of minutes and is safe against any environment, while zap-full-scan.py runs an active scan that sends attack payloads and must only ever be pointed at a disposable environment.
# Baseline scan against an ephemeral preview deployment
dast:
needs: deploy-preview
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# Passive only: spiders the app and analyses responses, no attacks sent
- run: |
docker run --rm -v "$PWD:/zap/wrk" \
-t ghcr.io/zaproxy/zaproxy:stable \
zap-baseline.py -t "${{ needs.deploy-preview.outputs.url }}" \
-J report.json -w report.md -r report.html
# -w writes markdown; the exit code is 1 if any alert is found
An unauthenticated DAST scan finds what an anonymous visitor can reach, which for most applications is a small fraction of the surface. Getting real coverage requires supplying ZAP with a session — a cookie, an authorization header, or a scripted login — and running it with at least two roles so that it can also test horizontal privilege escalation, which is precisely the BOLA class from the previous chapter and the one most likely to be found this way.
# Authenticated scan: supply both a header and a low-privilege session
zap-full-scan.py -t https://staging.example.com \
-z "-config replacer.full_list(0).description=auth \
-config replacer.full_list(0).enabled=true \
-config replacer.full_list(0).matchtype=REQ_HEADER \
-config replacer.full_list(0).matchstr=Authorization \
-config replacer.full_list(0).replacement='Bearer $SCAN_TOKEN'"
Fuzzing is the technique that finds the defects neither of the above can reach: parser bugs, memory-safety issues in native code, and logic errors triggered by malformed input. Coverage-guided fuzzers — libFuzzer, AFL++, and the language-native harnesses in Go, Rust, and Python’s Atheris — mutate an input toward new code paths and are devastatingly effective on any code that parses untrusted bytes. The candidates worth the effort are the obvious ones: the file-format parser, the image resizer, the URL router, the deserializer, the query parser.
// A Go fuzz target: the input is arbitrary bytes, the assertion is "no panic"
func FuzzParseQuery(f *testing.F) {
// Seed with a valid example so the fuzzer starts near real input
f.Add("filter=status:open&sort=-created")
f.Fuzz(func(t *testing.T, raw string) {
q, err := ParseQuery(raw)
if err != nil {
return // malformed input is an acceptable outcome
}
// The property: any successfully parsed query must round-trip
if got := q.String(); got == "" {
t.Fatalf("parsed query serialized empty: %q", raw)
}
})
}
The tests form a pyramid, and the ordering is by cost and frequency rather than by sophistication. Unit tests and type checks run per commit and must be fast. SAST runs per pull request on the diff and full-suite on main. DAST runs per preview deployment. Fuzzing runs continuously in the background against a corpus that grows over time. Penetration testing and bug bounty sit at the top: expensive, episodic, and irreplaceable for finding the logical and business-flow flaws that no automated tool models.
Triage is where the pyramid succeeds or fails. The rules worth committing to are: a new critical finding blocks the merge, a new high finding requires an owner within the working day, and a baseline file records the pre-existing findings so that “the tool reports 412 issues” never becomes the reason nothing is fixed. A suppression without an expiry date and an owner is a decision to accept the risk indefinitely, and it should be recorded as such.
c. Audit logging — the evidence layer
There are three kinds of logs and they answer different questions. Application logs describe the service’s own health — a request arrived, a database call was slow, an exception was thrown. Access logs describe the HTTP transaction — method, path, status, duration, bytes. Audit logs describe what a principal did to a resource, and their defining property is that they are designed to be evidence rather than to be debugged.
The taxonomy worth logging is small and stable. Authentication events — success, failure, MFA challenge issued and passed, session created and destroyed. Authorization decisions — grants and, more importantly, denials, because a burst of denials is the signature of an enumeration or privilege-escalation attempt. Account and privilege changes — role granted, role revoked, password changed, email changed, MFA disabled. Access to sensitive records — who read which customer, which invoice, which export. Administrative actions against configuration. And the security-relevant failures — input validation rejections, rate-limit trips, WAF blocks.
{
"ts": "2025-03-14T09:21:44.812Z",
"event": "invoice.read",
"outcome": "success",
"actor": {
"id": "usr_8f2a",
"type": "user",
"ip": "203.0.113.44",
"user_agent": "Mozilla/5.0 …",
"session_id": "ses_1c9d"
},
"target": {
"type": "invoice",
"id": "inv_5521",
"owner_id": "org_77b1"
},
"request": {
"id": "req_2f8e91c4",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
},
"service": "billing-api",
"env": "production"
}
The schema matters because it determines what can be queried later. The actor block is required for attribution, the target block for impact assessment, the outcome field for distinguishing attempted from successful, and the request.id / trace_id for joining an audit record to the application logs and traces of the same request.
The field that is most often missing is the correlation identifier. Without it, an audit record saying “user 8f2a read invoice 5521” cannot be joined to the application log entry that shows the SQL it ran, the cache hit, or the error that followed. Propagating one identifier — the W3C traceparent header or a plain request ID — through every layer is what makes the evidence usable.
What must never be logged is equally specific: passwords, whether hashed or not; session tokens and API keys; full payment card numbers (PCI DSS is explicit, and truncation to the last four plus the brand is the permitted representation); and personal data that is not necessary for the audit purpose, because the audit log is itself a store of personal data subject to the same retention and access rules as the primary database.
// The redaction helper runs before the record is serialized
const REDACT = new Set(["password", "token", "authorization", "cookie", "pan", "cvv", "secret"]);
function redact(obj) {
if (Array.isArray(obj)) return obj.map(redact);
if (obj === null || typeof obj !== "object") return obj;
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [
k,
// Case-insensitive match against the deny list
REDACT.has(k.toLowerCase()) ? "[REDACTED]" : redact(v),
]),
);
}
// Emit one structured line per event; never interpolate into a message string
audit.info(JSON.stringify(redact({ event: "invoice.read", actor, target })));
Tamper evidence is the difference between a log and a record. An attacker who achieves code execution will often try to erase their trail, and an append-only store they cannot write to removes the opportunity. Three layers achieve this: ship the records off the host immediately so the application never holds the only copy; write to storage that is append-only or WORM (write once, read many) with a separate credential; and chain the records cryptographically so that a deletion is detectable even if the store is compromised.
import { createHash } from "node:crypto";
// Each record carries the hash of its predecessor: removing one breaks the chain
async function appendAudit(record) {
const prev = await lastHash(); // hash of the previous record
const body = JSON.stringify({ ...record, prev_hash: prev });
const hash = createHash("sha256").update(body).digest("hex");
// Write to the append-only sink and return the chained hash
await auditSink.append({ ...record, prev_hash: prev, hash });
return hash;
}
// Verification walks the chain; a missing or altered record fails at its link
async function verifyChain(from, to) {
let expected = null;
for await (const rec of auditSink.range(from, to)) {
if (expected !== null && rec.prev_hash !== expected) return { ok: false, at: rec };
expected = rec.hash;
}
return { ok: true };
}
Retention is driven by compliance rather than by preference. The commonly cited floors are six months for PCI DSS 4.0 (Requirement 10.5.1, which also requires a year of availability with three months immediately available online), six years for HIPAA under the Security Rule’s documentation requirement, and one year for the SEC’s record-keeping in a financial context. GDPR cuts the other way and requires that personal data be kept no longer than necessary, so the working configuration is a short hot window with fast queries, a longer cold window with slow queries, and a documented deletion policy that legal counsel has seen.
d. Incident response — playbooks, severities, and the legal clock
The reference process is NIST SP 800-61. Its third revision, published in April 2025, restructures the guidance around the CSF 2.0 functions — Govern, Identify, Protect, Detect, Respond, Recover — while the earlier revision’s four-phase lifecycle remains the operational model most teams implement: preparation; detection and analysis; containment, eradication, and recovery; and post-incident activity.
Preparation is everything that makes the other phases possible, and it is done in advance or not at all. A named on-call rotation. A communication channel that is not the affected system — if the incident is a Slack compromise, the war room cannot be a Slack channel. Out-of-band contact details for legal, communications, and executive leadership. Pre-authorized credentials or a documented break-glass procedure for revoking access, because the person who needs to revoke a token at 3 a.m. may be the person whose token is compromised. And evidence-preservation instructions, because the first instinct — rebuild the host — destroys the forensic image that would have answered what was accessed.
Severity is defined before the incident so that classification is not a negotiation during one. The useful definition is in terms of impact and scope rather than in terms of the attack technique, because classification drives response time, escalation, and who gets woken up.
| Severity | Definition | Response |
|---|---|---|
| SEV1 | Confirmed or suspected breach of customer data, or full outage | Page immediately, IC assigned, exec notified within 30 min |
| SEV2 | Vulnerability exploitable in production, no evidence of use | Page immediately, IC assigned, fix within 24 h |
| SEV3 | Degraded security control, no direct exposure | Ticket, fix within the sprint |
| SEV4 | Finding in a non-production or defence-in-depth control | Backlog with owner |
Detection and analysis is where audit logging from the previous section earns its cost. The sources are the SIEM, the WAF, the cloud provider’s control-plane logs, the EDR agent, the application’s own audit stream, and — routinely and importantly — a report from a third party, since a large share of real-world breaches are first reported by an external researcher, a customer, or the payment processor. The analysis phase answers the same three questions every time: what is the scope, what is the initial access vector, and is the attacker still present. The first answer drives notification, the second drives eradication, and the third drives urgency.
Containment has four standard options, and the playbook should say which one applies to which scenario in advance. Revoke credentials and invalidate sessions — the correct first move for almost any confirmed compromise, because it costs users a re-login and nothing else. Block at the edge — an IP, an ASN, a user agent — which is fast and easily evaded. Disable the feature with a flag — the least disruptive containment for the common case where the vulnerability is in one code path rather than the whole service. And take the service offline, which is the last resort and should be treated as an executive decision rather than an engineering one.
Eradication and recovery is where the clock pressure is highest and the temptation to skip steps is strongest. Preserve the evidence before rebuilding — snapshot the disk, export the relevant audit range, record the container image digests that were running. Patch the vector rather than the symptom; the attacker who returns through the same hole because only the credential was rotated is a familiar failure. Rotate every credential that was reachable from the compromised host, not only the one that was used. Verify recovery against the detection that caught the incident in the first place, then watch for recurrence for a defined period rather than assuming the absence of an alert means the absence of an attacker.
The legal clock runs on a different schedule from the technical investigation, and it is the part teams are least prepared for.
| Regime | Deadline | Starts From | To Whom |
|---|---|---|---|
| GDPR Art. 33 | 72 hours | Awareness | Supervisory authority |
| GDPR Art. 34 | Without undue delay | Confirmation of high risk | Data subjects |
| NIS2 | 24 h early warning, 72 h notification | Awareness | CSIRT / authority |
| SEC Item 1.05 | 4 business days | Determination of materiality | SEC via Form 8-K |
| HIPAA | 60 days | Discovery | Individuals, then HHS |
| PCI DSS | Promptly | Discovery | Acquirer and card brands |
The GDPR clock is the one that governs most web application incidents in the EU, and its 72 hours start at awareness — the point at which a controller has a reasonable degree of certainty that a security incident has occurred and led to personal data being compromised. Waiting for the investigation to complete before involving counsel is how the window is missed. The operational consequence is that legal counsel is engaged in parallel from the moment a SEV1 is declared, not after the root cause is found.
Post-incident activity is the phase that determines whether the incident repeats. The output is a blameless review — the term is deliberate, because a review that assigns blame produces a report that omits the details that would explain the failure. The structure is a factual timeline reconstructed from logs rather than memory, a contributing-factors analysis built from asking why repeatedly rather than stopping at “human error”, a set of action items each with a named owner and a date, and a scheduled check-in on whether those action items were completed.
Tabletop exercises are the rehearsal that makes the playbook real. A ninety-minute session, a scenario drawn from the threat model — “an attacker used a leaked credential to export the customer table” — and a walk through each phase with the people who would actually be involved. The value is not the scenario; it is discovering that the on-call engineer does not have the SIEM login, that the legal contact list is three years old, and that nobody knows who is authorized to take the service down.
Complete Example Session
# ============================================
# PART 1: THE THREAT MODEL WORKSHEET
# ============================================
Threat L I Mitigation State
─────────────────────────────────────────────────────────────────────────────────────────────
Session token replayed from a new device M H Bind to device, rotate on change Done
Order total tampered in the request body M H Recalculate server-side Done
Admin deletes a record with no trace L M Append-only audit log Open
Invoice ID enumerates another tenant H H Scope query by tenant, 404 Done
Export job saturates the database M M Per-account limit, async queue Open
Support role can issue refunds M H Split read and refund scopes Done
# ============================================
# PART 2: THE SAST GATE
# ============================================
# .github/workflows/sast.yml
- name: Semgrep
run: semgrep ci --sarif --output=semgrep.sarif
- uses: github/codeql-action/upload-sarif@v3
with:
# Findings annotate the pull request diff rather than a build log
sarif_file: semgrep.sarif
# ============================================
# PART 3: THE CUSTOM RULE
# ============================================
# .semgrep/no-innerhtml.yml
rules:
- id: no-innerhtml-without-sanitizer
pattern: $EL.innerHTML = $X
# Exempt the sanitiser's own output
pattern-not: $EL.innerHTML = DOMPurify.sanitize(...)
message: Sanitise before assigning to innerHTML
severity: ERROR
languages: [javascript, typescript]
# ============================================
# PART 4: THE DAST SCAN
# ============================================
- name: ZAP baseline
# Passive only: safe against the ephemeral preview environment
run: |
docker run --rm -v "$PWD:/zap/wrk" -t ghcr.io/zaproxy/zaproxy:stable \
zap-baseline.py -t "$PREVIEW_URL" -J report.json -w report.md
# ============================================
# PART 5: THE FUZZ TARGET
# ============================================
# go test -fuzz=FuzzParseQuery -fuzztime=60s ./internal/query
func FuzzParseQuery(f *testing.F) {
f.Add("filter=status:open") // seed with real-shaped input
f.Fuzz(func(t *testing.T, raw string) {
q, err := ParseQuery(raw)
if err != nil { return } // malformed input is fine
_ = q.String() // any panic is a failure
})
}
// ============================================
// PART 6: THE AUDIT RECORD
// ============================================
audit.info(JSON.stringify({
ts: new Date().toISOString(),
event: "invoice.read",
outcome: "success",
actor: { id: user.id, ip: req.ip, session_id: req.sessionID },
target: { type: "invoice", id: invoice.id, owner_id: invoice.orgId },
request: { id: req.id, trace_id: req.traceparent },
}));
// ============================================
// PART 7: THE HASH CHAIN
// ============================================
async function appendAudit(record) {
const prev = await lastHash(); // predecessor's hash
const body = JSON.stringify({ ...record, prev_hash: prev });
const hash = createHash("sha256").update(body).digest("hex");
await auditSink.append({ ...record, prev_hash: prev, hash });
return hash;
}
# ============================================
# PART 8: THE DETECTION QUERY
# ============================================
-- A burst of denials from one actor is the enumeration signature
SELECT actor->>'id' AS actor_id,
count(*) AS denials,
min(ts) AS first_seen,
max(ts) AS last_seen
FROM audit_events
WHERE event = 'invoice.read'
AND outcome = 'denied'
AND ts > now() - interval '15 minutes'
GROUP BY 1
HAVING count(*) > 20
ORDER BY denials DESC;
# ============================================
# PART 9: THE INCIDENT RECORD
# ============================================
# incident 2025-03-14-billing
severity: SEV1
declared_at: 2025-03-14T09:41:00Z
incident_commander: oncall-billing
aware_at: 2025-03-14T09:38:00Z # legal clock starts here
vector: leaked credential, no MFA
containment:
- revoke all sessions for org_77b1
- rotate the service account key
- disable the export endpoint via flag
evidence:
- disk snapshot i-0abc123
- audit range 2025-03-01..2025-03-14
notification:
gdpr_deadline: 2025-03-17T09:38:00Z # awareness + 72h
counsel_engaged_at: 2025-03-14T09:52:00Z
# ============================================
# PART 10: THE POST-MORTEM ACTION ITEMS
# ============================================
actions:
- id: A1
fix: enforce MFA on all service accounts
owner: platform
due: 2025-03-28
- id: A2
fix: alert when a single credential exports > 1k rows/hour
owner: detection
due: 2025-04-04
- id: A3
fix: add export abuse to the threat model worksheet
owner: security
due: 2025-04-11
The ten parts traced the loop: a threat model that produced a prioritized worksheet, the SAST gate and a custom rule from that worksheet, the DAST scan and the fuzz target, the audit record and its hash chain, the detection query that would have caught the incident, the incident record with the legal clock, and the post-mortem actions that return to the threat model.
Quick Reference
STRIDE to Property
| Letter | Threat | Property | Control |
|---|---|---|---|
| S | Spoofing | Authentication | MFA, tokens, mTLS |
| T | Tampering | Integrity | Signatures, TLS, checks |
| R | Repudiation | Non-repudiation | Audit log, hash chain |
| I | Information disclosure | Confidentiality | Authz, encryption |
| D | Denial of service | Availability | Rate limits, quotas |
| E | Elevation of privilege | Authorization | Scope checks |
Testing Placement
| Technique | Runs On | Finds |
|---|---|---|
| Unit / type checks | Every commit | Logic errors |
| SAST (Semgrep, CodeQL) | Pull request diff | Tainted flows, patterns |
| SCA (Dependabot, Trivy) | Pull request | Known CVEs |
| DAST (ZAP baseline) | Preview deploy | Runtime misconfig |
| Fuzzing | Continuous | Parser and memory bugs |
| Pen test / bounty | Quarterly | Business logic |
Audit Event Taxonomy
| Event | Outcome Values |
|---|---|
auth.login | success, failure, mfa_required |
authz.denied | denied |
invoice.read | success, denied |
export.create | success |
role.grant / role.revoke | success |
session.create / session.destroy | success |
Notification Deadlines
| Regime | Deadline | Trigger |
|---|---|---|
| GDPR Art. 33 | 72 hours | Awareness |
| NIS2 | 24 h / 72 h / 1 month | Awareness |
| SEC Item 1.05 | 4 business days | Materiality |
| HIPAA | 60 days | Discovery |
| PCI DSS | Promptly | Discovery |
Best Practices
✅ Do This:
# Draw the boundary before the box
threat model → DFD with trust boundaries → worksheet # ✅
# Tier the count so the noise is bounded
severity: ERROR / WARNING: 1 candidate found? No. # ✅
# Upload SARIF so findings annotate the diff
uses: github/codeql-action/upload-sarif@v3 # ✅
# Run the passive scan on every preview
zap-baseline.py -t "$PREVIEW_URL" # ✅
# Run the active scan only on disposable environments
zap-full-scan.py -t "$STAGING_URL" # ✅
// Log the actor, the target, and the outcome
{ event: "invoice.read", actor: {...}, target: {...}, outcome } # ✅
// Chain each record to its predecessor
hash = sha256(JSON.stringify({ ...rec, prev_hash: prev })) # ✅
# Engage counsel on the awareness clock, not after the RCA
aware_at → counsel within 15 min → 72h deadline tracked # ✅
# Preserve before rebuilding
snapshot disk → export audit range → then terminate # ✅
❌ Don’t Do This:
# A DFD with no trust boundaries
boxes and arrows, no privilege changes marked # ❌
# Scanner output nobody reads
run: semgrep ci # no SARIF upload ❌
# Active attack traffic against production
zap-full-scan.py -t https://app.example.com # ❌
// Log the credential
audit.info(JSON.stringify({ email, password, token })) # ❌
// A log the attacker can edit
fs.appendFileSync("/var/log/audit.log", line) # ❌
# Wipe the host before imaging it
kubectl delete pod → investigation begins # ❌
# Wait for the root cause before calling legal
rca_complete: day 5 → counsel notified: day 5 # ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Threat model never read | Written by one person, filed once | Worksheet becomes tickets |
| SAST ignored | 2,000 findings, no baseline | Baseline file, diff-only gate |
| DAST finds only public pages | No session supplied | Authenticated scan, two roles |
| Audit log misses the act | Actor or target omitted | Fixed schema, required fields |
| Records unjoinable | No correlation ID | Propagate traceparent |
| Logs erased by the attacker | Application holds the only copy | Ship off-host, append-only |
| Legal clock missed | Counsel engaged after the RCA | Parallel track from SEV1 |
| Evidence destroyed | Host rebuilt first | Snapshot before remediation |
| Post-mortem assigns blame | “Human error” as root cause | Blameless, ask why again |
Real-World Examples
1. Threat model session
4 people, 60 min, one DFD, one worksheet, 12 threats, 3 accepted
2. CodeQL query suite
queries: security-extended
3. Semgrep custom rule
pattern: $EL.innerHTML = $X
pattern-not: $EL.innerHTML = DOMPurify.sanitize(...)
4. ZAP baseline in CI
zap-baseline.py -t "$PREVIEW_URL" -J report.json
5. Go fuzz target
f.Fuzz(func(t *testing.T, raw string) { ParseQuery(raw) })
6. Audit record
{ event: "invoice.read", actor, target, outcome, request }
7. Hash chain append
const hash = sha256(JSON.stringify({ ...rec, prev_hash: prev }));
8. Enumeration detection
HAVING count(*) > 20 -- denials per actor in 15 minutes
9. Severity ladder
SEV1 breach → page + IC + exec 30 min
10. Post-mortem owner
actions: [{ fix: enforce MFA, owner: platform, due: 2025-03-28 }]
Visual
The Security Loop
┌────────────────────────────────────────────────────┐
│ MODEL ──► TEST ──► LOG ──► RESPOND │
│ ▲ │ │
│ └──────────────────────────────────┘ │
│ │
│ model decides which controls to build │
│ test proves the controls were built │
│ log records what the built system did │
│ respond handles what the first three missed │
│ │
│ post-mortem actions re-enter the model │
└────────────────────────────────────────────────────┘
Trust Boundaries on a DFD
┌────────────────────────────────────────────────────┐
│ [user] │
│ │ boundary 1: internet → edge │
│ ════╪═══════════════════════════════════ │
│ ▼ │
│ (api-gateway) ──► (auth) │
│ │ │ boundary 2: svc → vault │
│ │ ▼ │
│ │ ╔══════════╗ │
│ │ ║ vault ║ │
│ │ ╚══════════╝ │
│ ▼ boundary 3: api → payment │
│ (checkout) ──► [payment-api] │
│ │ boundary 4: svc → store │
│ ▼ │
│ ╔════════════╗ │
│ ║ orders ║ │
│ ╚════════════╝ │
└────────────────────────────────────────────────────┘
The Testing Pyramid
┌────────────────────────────────────────────────────┐
│ cost ▲ │
│ │ pen test / bug bounty episodic │
│ │ fuzzing continuous │
│ │ DAST per preview │
│ │ SAST / SCA per commit │
│ │ unit / type checks per save │
│ └──────────────────────────────────► freq │
│ │
│ finds: the higher the layer, the more logic │
│ and the less syntax │
└────────────────────────────────────────────────────┘
The Incident Timeline
┌────────────────────────────────────────────────────┐
│ T+0 aware of the anomaly │
│ T+3m SEV1 declared, IC assigned │
│ T+14m counsel engaged ← 72h clock running │
│ T+22m containment: revoke sessions, rotate key │
│ T+1h evidence preserved before rebuild │
│ T+6h vector patched, service restored │
│ T+72h supervisory-authority deadline │
│ T+7d blameless post-mortem, actions assigned │
└────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Threat framework | STRIDE, Kohnfelder and Garg, 1999 |
| DFD elements | External entity, process, data store, data flow |
| DFD annotation | Trust boundary |
| Four questions | Building / wrong / doing / good job (Shostack) |
| SAST tools | Semgrep, CodeQL, SonarQube |
| DAST tools | OWASP ZAP, Burp Suite |
| Interchange format | SARIF |
| Fuzzers | libFuzzer, AFL++, Atherton/Atheris, Go native |
| Audit schema | actor, target, outcome, request ID |
| Tamper evidence | Off-host append-only plus hash chain |
| IR reference | NIST SP 800-61, revision 3 April 2025 |
| GDPR deadline | 72 hours from awareness |
Key takeaways:
- STRIDE bounds an unbounded problem. It is mnemonic, exhaustive at the category level, and maps each category to a property a control can restore. Applied per DFD element rather than to a feature list, it produces a worksheet rather than a worry.
- A threat model’s value is in the tickets it creates. A document that lives in a wiki and drives nothing is worse than no model, because it creates the impression of coverage. Every open row becomes an owned, dated task.
- SAST and DAST find different things and neither replaces the other. SAST reaches code paths tests never execute; DAST sees the runtime configuration and the header that the code review never inspects. A DAST scan without an authenticated session sees almost nothing of a modern application.
- The SARIF upload is the line that makes a scanner matter. Findings that annotate the pull request diff get fixed; findings in a build log get ignored.
- An audit log is evidence and must be engineered as such. Actor, target, outcome, correlation ID, shipped off-host, append-only, hash-chained, and with a retention window that legal counsel has approved.
- The legal clock starts at awareness, parallel to the technical investigation. Counsel is engaged when a SEV1 is declared, not when the root cause is found, because GDPR’s 72 hours do not wait for the analysis to complete.
- Tabletop exercises are the cheapest way to find the gaps. Ninety minutes reveals the missing SIEM login, the stale contact list, and the missing authority to take the service down — before they cost four hours of production downtime.
Remember: These four activities are a loop and the loop is the point. Threat modeling names what could go wrong; testing proves the mitigation works; logging records what the system actually did; response handles what got through — and the post-mortem returns to the threat model with an answer the model did not have. A team that runs the loop twice has a materially better security posture than a team that ran a penetration test once, because the loop compounds and the one-off does not. The artifact is never the deliverable. The conversation, the ticket, the query, and the rehearsal are.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!