Threat modelling for .NET teams: the four questions, data flow diagrams and trust boundaries, STRIDE per element, ranking and tracking threats, and a 60-minute in-sprint version.
Threat modelling is a structured way to find design-level security flaws before you write the code. I answer four questions: what are we building, what can go wrong, what will we do about it, and did we do a good job? I draw a data flow diagram (processes, data stores, external entities and flows) and mark the trust boundaries, because that is where most threats live. Then I walk each element with STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. Each threat becomes a decision (mitigate, accept, transfer or eliminate) and mitigations become backlog items with acceptance criteria. I do it at design time and whenever a change adds or crosses a trust boundary. The trade-off is depth against cadence: a 60-minute session every feature beats a two-day workshop nobody repeats.
"Threat modelling is how I find security flaws in the design rather than waiting for a pen tester to find them in the build. I use the four questions from the Threat Modeling Manifesto: what are we building, what can go wrong, what are we going to do about it, and did we do a good job. For the first one I draw a data flow diagram: external entities like the browser or a payment provider, our processes like the API and a background worker, data stores like Azure SQL and Blob Storage, and the flows between them. The important part is the trust boundaries: the internet edge, the line between our API and the database, the line to a third party. Almost every interesting threat sits on a flow that crosses one.
For 'what can go wrong' I walk each element and flow with STRIDE. Spoofing breaks authentication, tampering breaks integrity, repudiation breaks non-repudiation, information disclosure breaks confidentiality, denial of service breaks availability, and elevation of privilege breaks authorisation. For a new 'upload a receipt' feature that gives me questions like: can someone upload as another user, can they tamper with the stored file, can they make the API fetch a URL, can a 2 GB upload take the service down? Each threat gets a decision and an owner, and the mitigations go into the backlog as acceptance criteria, not into a document nobody reads.
The mistake I see is treating it as an annual compliance workshop that produces a 40-page PDF. I run a lightweight version in refinement for any story that adds or crosses a trust boundary: 45 to 60 minutes, a whiteboard diagram, STRIDE on the new flows only, and tickets out the other side. The model lives as a markdown file next to the ADR and gets updated when the design changes. A threat model is a living artefact, not a gate you pass once."
| Question | Activity | Output |
|---|---|---|
| What are we building? | Draw the DFD, mark trust boundaries, list assets (PII, tokens, money) | Diagram plus asset list |
| What can go wrong? | STRIDE per element or per boundary-crossing flow | Threat list |
| What are we going to do about it? | Mitigate, accept, transfer or eliminate; rank by risk | Backlog items with acceptance criteria, accepted risks recorded |
| Did we do a good job? | Review coverage, test the mitigations, revisit after change | Security tests, pen-test scope, updated model |
| Threat | Property violated | Typical .NET / Azure mitigation |
|---|---|---|
| Spoofing | Authentication | Entra ID / OIDC, JWT validation, managed identity between services, mTLS |
| Tampering | Integrity | HTTPS, HMAC on webhooks, EF Core concurrency tokens, signed tokens, immutable Blob storage |
| Repudiation | Non-repudiation | Audit log with user id and correlation id, append-only storage, clock-synced timestamps |
| Information disclosure | Confidentiality | Resource-based authorisation, encryption at rest, redaction in logs, ProblemDetails without stack traces |
| Denial of service | Availability | Rate limiting middleware, request size limits, timeouts, queue-based load levelling, Azure Front Door WAF |
| Elevation of privilege | Authorisation | Policy-based authorisation, least-privilege RBAC, no [AllowAnonymous] drift, input validation |
| Trigger | Depth |
|---|---|
| New system or service | Full session (2-3 hours) with architect, devs, security, product |
| Story adds a new external integration, data store, public endpoint or new kind of PII | Lightweight (45-60 min) in refinement |
| Change to authentication, authorisation or tenancy | Lightweight, plus security reviewer on the PR |
| Pure UI or internal refactor with no new flows | Skip; note "no new trust boundaries" on the story |
For [a customer document-upload feature], a 50-minute session found three issues before any code was written: the API would have fetched user-supplied URLs (SSRF), uploads had no size limit, and the background virus scan wrote results back with a connection string that had db_owner. All three became acceptance criteria. The later external pen test found [0 high findings] on that feature, against [3 highs] on the previous release that had no threat model.
Checks whether the candidate can find security problems at design time in a way a delivery team will actually sustain.
Green flags
Red flags
Static analysis and code review catch implementation bugs: a concatenated SQL string, a missing [Authorize]. They don't catch design bugs: "the worker trusts any message on the queue", "support staff can impersonate any customer with no audit". Those come from how components trust each other, so you find them by looking at the components and the trust between them, which is what a DFD is for.
Five building blocks:
[External entity] a person or system you don't control (browser, Stripe)
( Process ) code you run (API, Function, worker)
=Data store= where data rests (Azure SQL, Blob, Redis, Service Bus)
----> data flow, labelled with what moves
- - - - - - - - trust boundary: where the level of trust changes
A receipt-upload feature:
[Customer browser]
| HTTPS: JWT + multipart file
- - - -|- - - - - - - - - - - - - - - - - - - internet boundary
v
( Receipts API )----SQL (managed identity)---->=Azure SQL=
| ^
| put blob (managed identity) | scan result
v |
=Blob: quarantine=----event---->( Scan worker )-+
- - - - - - - - - - - - - - - - - - - - - - - - - - third-party boundary
|
v
[Malware scanning service]
Every arrow that crosses a dashed line gets STRIDE first.
Other lenses: LINDDUN for privacy threats (linkability, identifiability, non-repudiation, detectability, disclosure, unawareness, non-compliance), which pairs well with APP obligations; attack trees for one high-value goal ("steal another tenant's invoices"); PASTA for risk-centric, business-driven models.
DREAD has fallen out of favour because its scores are subjective. Practical options:
| Method | How | Fits |
|---|---|---|
| Likelihood x impact (1-3 each) | Quick 3x3 grid | In-sprint sessions |
| CVSS-style | Exploitability and impact metrics | Aligning with pen-test findings |
| Organisation risk matrix | The risk team's own scale | Regulated environments that need sign-off of accepted risks |
What matters more than the score is that every threat has a decision and that accepted risks have a named owner and a review date.
A threat is only useful if it changes the backlog:
Threat: T-07 Tampering - scan worker trusts any blob event
Decision: Mitigate
Story AC: worker verifies the blob is in the quarantine container and the
event comes from our storage account's Event Grid system topic;
integration test sends a forged event and expects rejection.
Owner: [name] Review: when the scanning provider changes
People: one developer who will build it, one who won't (fresh eyes), the tester, and a security champion. A security specialist is a bonus, not a requirement.
| Tool | Strength | Weakness |
|---|---|---|
| Whiteboard + markdown in repo | Zero friction, versioned with the code | No automatic threat generation |
| Microsoft Threat Modeling Tool | STRIDE threats generated from Azure-aware templates | Windows-only, binary files are hard to diff |
| OWASP Threat Dragon | Cross-platform, JSON files in the repo | Smaller template library |
| Diagrams-as-code (Mermaid) | Diffs nicely in PRs | You still have to do the thinking |
The ISM expects systems to be designed with security controls identified from risk assessment, and IRAP assessors ask for evidence of threat modelling on government systems. For anything handling personal information, a privacy impact assessment (PIA) is the privacy counterpart; APP 1 requires practices that ensure compliance, and the OAIC treats a PIA as the expected way to show it for high-risk projects. Running LINDDUN alongside STRIDE gives you most of the PIA's technical input.
threat-model.md next to an ADR and a PR template checkbox: "Does this change add or cross a trust boundary?"A threat model kept as a versioned file next to the ADR, with a Mermaid DFD so it diffs in pull requests:
# Threat model: receipt upload (ADR-0042)
```mermaid
flowchart LR
B[Customer browser] -- "HTTPS JWT + file" --> API(Receipts API)
subgraph Azure [Trust boundary: our subscription]
API -- "managed identity" --> SQL[(Azure SQL)]
API -- "put blob" --> Q[(Blob: quarantine)]
Q -- "Event Grid" --> W(Scan worker)
end
W -- "HTTPS API key" --> S[Scanning service]
| Id | Flow / element | STRIDE | Threat | Decision | Mitigation / AC | Owner |
|---|---|---|---|---|---|---|
| T-01 | Browser -> API | S | Upload as another user | Mitigate | Owner taken from token sub, never from the form |
[dev] |
| T-02 | Browser -> API | D | 2 GB upload exhausts memory | Mitigate | 10 MB limit, streamed to Blob | [dev] |
| T-03 | API -> Blob | I | Public blob URL leaks receipts | Mitigate | Private container, short-lived user-delegation SAS | [dev] |
| T-04 | Q -> Worker | T | Forged event marks file clean | Mitigate | Validate event source and container | [dev] |
| T-05 | Worker -> SQL | E | Worker has db_owner | Mitigate | Dedicated user, UPDATE on one table only | [dev] |
| T-06 | Audit | R | User denies uploading a receipt | Accept | Upload audit row with user id; review 2027-06 | [PO] |
An integration test that proves one mitigation (T-01), so the threat model is backed by an automated check:
```csharp
namespace Receipts.Api.Tests;
public sealed class UploadOwnershipTests(ApiFactory factory) : IClassFixture<ApiFactory>
{
[Fact]
public async Task Upload_ignores_owner_supplied_in_form()
{
// Threat T-01: spoofing the owner through a form field.
var client = factory.CreateClientFor(userId: "alice");
using var form = new MultipartFormDataContent
{
{ new StringContent("bob"), "ownerId" },
{ new ByteArrayContent("%PDF-1.7"u8.ToArray()), "file", "r.pdf" }
};
var response = await client.PostAsync("/receipts", form, TestContext.Current.CancellationToken);
response.EnsureSuccessStatusCode();
var saved = await factory.GetLatestReceiptAsync(TestContext.Current.CancellationToken);
Assert.Equal("alice", saved.OwnerId);
}
}
The value of threat modelling is not the diagram, it is the conversation it forces about trust between components, and the backlog items that come out of it. In a DevSecOps team it sits at the design end of the same continuous loop as SAST, dependency scanning and DAST: threat modelling decides which controls should exist, the pipeline proves they still do. A senior engineer makes it cheap enough to do often: a standing question in refinement ("does this add or cross a trust boundary?"), a 60-minute session when the answer is yes, and a markdown file that lives with the code. They also know when not to: a pure UI tweak or an internal refactor with no new flows doesn't need a session.
What goes wrong without decisions and owners is concrete: a team lists "queue messages are not authenticated" as a threat, nobody owns it, and a year later a misconfigured partner integration with send rights on the same Service Bus namespace posts forged "payment approved" messages that the worker trusts. The threat was found; it was never decided. Likewise, a team that skipped modelling a "just add a webhook" story shipped an endpoint that fetched arbitrary URLs from inside the VNet, exposing internal admin endpoints (SSRF). Privacy threats need their own lens: running LINDDUN on the same DFD for a feature that adds date of birth and address catches linkability (joining analytics events to identities) and unawareness (no notice under APP 5) that STRIDE never asks about.
Measure it by outcomes: high-severity pen-test findings per release, the share of security bugs found in design versus production, and how many threat-model mitigations have tests.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Lightweight in-sprint (STRIDE per interaction) | Features that add a flow, store or integration | 45-60 min, 3-5 people | Large new systems with many unknowns |
| Full workshop (STRIDE per element + LINDDUN) | New system, new tenancy model, regulated data | 0.5-2 days | Small incremental features |
| Attack tree | One high-value goal, e.g. cross-tenant data access | A few hours | Broad coverage of a whole system |
| Tool-generated (MS Threat Modeling Tool) | Azure-heavy designs, teams new to STRIDE | Setup time, noisy output | As a substitute for thinking |
SSRF is when your server makes a request to a destination the attacker chooses, using your network position and identity. Features like webhooks, URL previews and image fetches are classic entry points. The prize is usually internal: the cloud metadata endpoint (169.254.169.254) or a managed identity endpoint that hands out tokens, internal admin APIs, or services on localhost.
Defend in layers: allow only https and standard ports, resolve and check the IP at connect time (with SocketsHttpHandler.ConnectCallback) so private, loopback and link-local ranges are refused even after DNS rebinding, disable auto-redirects or re-check each hop, cap time and size, and never echo the response. Then add network egress controls so the fetcher can't reach internal ranges at all. The trade-off: strict egress isolation is the strongest control but needs infrastructure work.
Broken object-level authorisation (BOLA, also called IDOR) is API1:2023 in the OWASP API Security Top 10: the API checks who you are but not whether this object is yours.
callerId read from the token's claims, never from the request (Where(o => o.Id == id && o.CustomerId == callerId)), or load and call IAuthorizationService.AuthorizeAsync when roles or teams are involved; return 404, not 403.The trade-off: random ids slow attackers down, but they are not authorisation; only a server-side ownership check is.
A privacy impact assessment (PIA) examines what personal information a project collects, why, who sees it, where it goes and how long it's kept, tested against the APPs; the OAIC expects one for high-privacy-risk projects and it's mandatory for those projects in Australian Government agencies under the Privacy (Australian Government Agencies - Governance) APP Code. LINDDUN (Linkability, Identifiability, Non-repudiation, Detectability, Disclosure of information, Unawareness, Non-compliance) is to privacy what STRIDE is to security: you walk the same data flow diagram and ask privacy questions. In an agile team I run both in one refinement session for any story that adds personal information, iterate the PIA as the design changes rather than writing it once, and turn the outputs into backlog items (minimisation, retention jobs, collection notices) and PIA updates.
How to tell it (STAR)
**S:** We were adding receipt upload to [our customer portal], with a third-party malware scanner and a background worker, and the pen test was [two sprints] away. **T:** I wanted to find design problems before we built them, without slowing the sprint. **A:** I ran a 50-minute threat model in refinement: we drew the data flows, marked the trust boundaries, and used STRIDE on each flow that crossed one. We found an SSRF risk, no upload size limit, and a worker with db_owner. Each became an acceptance criterion with a test, and the model went into the repo next to the ADR. **R:** The external pen test found [zero high findings] on the feature, compared with [three] on the previous release, and the team now runs the session whenever a story crosses a trust boundary.
Last updated 23 Nov 2026.