Threat Modeling and Risk Control
1) Principles
1. Architectural First. We start with contexts, trust boundaries and data flows.
2. Risk ≈ Likelihood × Impact. We measure, not feel.
3. Defense in Depth. Controls on each layer: code → protocol → platform → people.
4. Shift Left/Right. Early gates in PR + monitoring and reaction in prod.
5. Privacy by Design. We simulate not only security threats, but also privacy risks.
6. Automate Where Possible. Policies as code, auto-checks, "red lines."
2) Inventory: assets, entities, boundaries of trust
Assets: data (PII, finance, secrets), computing resources, keys, accesses, business processes.
Subjects: users, services, admins, partners, external providers.
Trust boundaries: users ↔ front, front ↔ API gateway, services ↔ databases/caches/queues, regions/clouds.
Attack surface: input points (API, webhooks, UI, networks, CI/CD, supply chain).
mermaid flowchart LR
U[Пользователь] -- TLS --> WAF[WAF/CDN]
WAF --> GW[API Gateway]
GW --> Svc[Service A]
Svc --> DB[(Postgres)]
Svc --> MQ[[Kafka]]
MQ --> SvcB[Service B]
subgraph Trust Boundary
GW; Svc; SvcB end
3) Threat frameworks
STRIDE (безопасность): Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege.
LINDDUN (приватность): Linkability, Identifiability, Non-repudiation, Detectability, Disclosure, Unawareness, Non-compliance.
PASTA (process): from business goals and threat actors → technical details → test scenarios.
4) Risk assessment
DREAD/OWASP Risk Rating or CVSS for vulnerabilities.
Probability (L): attacker's motive/capabilities, complexity, surface exposure.
Impact (I): finance, legal risks, downtime, PD leaks.
Risk (R = L × I) → prioritization and tritment: Avoid/Reduce/Transfer/Accept.
Impact
Low Med High Critical
Lik Low L L M H
Med L M H H
High M H High Crit
Risk register (minimum fields): 'id, scenario, STRIDE, asset, L, I, R, owners, controls, status, revision date'.
5) Controls: Prevent/Detect/Respond
Prevent:- Authentication/authorization: OIDC/OAuth2, PoLP, RBAC/ABAC, short-term service credits.
- Secrets/keys: KMS/HSM, rotation, do not know, FPE/field encryption.
- Secure protocols: TLS1. 2 +, mTLS, webhook signatures, idempotency, and anti-replay.
- Validation/sanitation: schemes (JSON Schema/Proto), limits, normalization.
- Isolation: network policies, segmentation, sandbox, namespaces, bulkheads.
- Audit logs (unrecognizable), correlation in SIEM, alerts to anomalies.
- Monitoring signature and integrity (export of artifact hashes, attestation).
- Honeytokens/canaries for early key leak detection.
- Runbook IR: classification, isolation, key recall, alerts, forensics.
- Automatic kill-switch/feature-flag, "black lists" of tokens.
- Notifications of users/regulators in case of PD incidents.
6) SDL and security gates
In idea/design: threat model (RFC/ADR), checklist of controls.
In development: SAST/secret-scan, dependency scans (SCA), dependency policy.
In assembly: SBOM, artifact signature, vulnerability policy (CVSS thresholds).
In the field: OPA/Kyverno - IaC/manifest policy (securityContext, network policies, secret forwarding).
In sales: IDS/WAF, anomaly detection, canary checks, chaos security (for example, expired certificate).
rego package policy.cicd deny[msg] {
some v input.sbom.vulns[v].cvss >= 7.0 msg:= sprintf("High vuln blocked: %s %s", [v.package, v.id])
}
deny[msg] {
input.k8s.pod.spec.securityContext.runAsRoot == true msg:= "RunAsRoot forbidden"
}
7) Supply Chain and Trust in Artifacts
SBOM per image/package; dependency updates - via bot/policy.
SLSA/Provenance: reproducible assemblies, signatures, attestations.
Containers: minimal images, rootless, drop capabilities, read-only FS.
IaC scans: Terraform/Helm - encryption policy, open ports, network rules.
8) Privacy and compliance
LINDDUN-map of privacy threats, data minimization, pseudonymization/anonymization.
Retention policies: TTL/retention, "right to delete," audit of access to PD.
Localization: geo-limitations, "data remains in the region."
Transparency: processing, notification and consent logs.
9) Clouds and perimeters
Zero Trust: authentication of each request, mTLS/OPA between services.
Segmentation: VPC/subnets/SG, private endpoints, egress control.
Keys/secrets: KMS, rotation, short credits in CI (OIDC federation).
Reserve/DR: encrypted backups, keys separately, recovery rehearsals.
10) Red/purple teams and tabletop exercises
Red Team: threat hypothesis testing, social engineering, chain exploitation.
Purple Team: joint debugging of detections/alerts, improving playbooks IR.
Tabletop: scripts "expired certificate," "leaked keys," "supply-chain compromise." The result is updated controls and metrics.
11) Maturity metrics and management
Coverage:% of services with current threat model and DFD.
Safety MTTD/MTTR, proportion of incidents caught by controls.
Policy pass-rate in CI, time to close vulnerabilities by criticality.
Privacy:% of datasets with TTL/ILM, share of access with justification.
Audit: regularity of risk register revision (quarterly).
12) Artifact patterns
12. 1 Risk card (example)
Risk ID: SEC-API-012
Сценарий: SSRF через изображение в профиле
STRIDE: Tampering/Info Disclosure
Актив: API / файловый прокси
Likelihood: High Impact: High Risk: Critical
Контроли: denylist схем, egress-прокси, URL-fetcher в изолированном рантайме,
DNS-resolv только через прокси, время/размер-лимиты, allowlist.
Владелец: team-accounts Статус: Reduce (в работе)
Дата пересмотра: 2025-12-01
12. 2 Design checklist
Assets and PII identified? Trust boundaries marked?
Are DFDs/data loops composed and mapped to ADRs?
STRIDE/LINDDUN traversed each DFD arrow?
Risk tritment selected; have owners/deadlines/DoD?
Policies as code added (OPA/Kyverno/CI gates)?
Monitoring plan/alerts and IR-runbook updated?
Privacy: minimization, encryption, TTL/retention, localization?
12. 3 Webhook Policy (Pseudocode)
python def verify_webhook(req, keys):
ts = int(req.h["X-Timestamp"])
if abs(now_utc()-ts) > 300: return 401 if not hmac_ok(req.body, ts, keys.active_or_prev(), req.h["X-Signature"]):
return 401 if replay_cache.seen(req.h["X-Event-ID"]): return 200
PoLP: в обработчике — только нужные скоупы handle(json.loads(req.body))
replay_cache.mark(req.h["X-Event-ID"])
return 200
13) Anti-patterns
Policies not embedded as code → manual "forgotten."
Threat model "for show" without DFD/invariants.
"Super-perimeter" without internal service-to-service authentication.
Long-lived secrets in environment/repo variables.
Logs with PD without camouflage and without retention/TTL.
Ignoring supply chain (no SBOM/signatures/scans).
Accept without owner and revision date.
14) Integration into processes
RFC/ADR - Each meaningful solution contains a Threats and Controls section.
Docs-as-Code: threat model, DFD, risk register in the version next to the code.
Release gates: the release is blocked when SAST/SCA/SBOM policies fail or high-severity controls are missing.
Training: playbooks for developers (secrets, signatures, PoLP), regular tabletop.
Conclusion
Threat Modeling is an engineering practice of risk management, not a one-time document. Define assets and trust boundaries, apply STRIDE/LINDDUN, measure risk, register it, and implement controls as code by embedding them in CI/CD and operation. With maturity metrics and regular revision, you will turn safety into a predictable architectural ability - with understandable price, effect and speed.