Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

Threat modelling with STRIDE

Build a STRIDE threat model of Harbourline's Payments API: draw the data-flow diagram, mark trust boundaries, find threats per element, rank them, map each one to an AWS or .NET mitigation, and keep the model current as code.

intermediate⏱ 2 h 🟢 FreeSCS-C03SAA-C03

Assumes: .NET 10 LTS (file-based apps with dotnet run) · AWS SDK for .NET v4 · AWS CLI v2 · Threat Composer (AWS Labs, open source) · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain what a threat model is, when a bank needs one, and the four questions every threat model answers.
  • Draw a data-flow diagram (DFD) of a payment API with external entities, processes, data stores, data flows and trust boundaries.
  • Apply STRIDE (Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege) systematically with the STRIDE-per-element method.
  • Write threats as clear statements, rank them by likelihood and impact, and record a decision for each: mitigate, transfer, avoid or accept.
  • Map each threat to concrete controls on AWS (IAM, KMS, WAF, CloudTrail, VPC endpoints, idempotency) and in your .NET code.
  • Keep a threat model alive as a versioned file in the repository, checked by a small C# tool in the pipeline.

Prerequisites

Why this matters in banking

In 2024 Harbourline's fictional competitor launched an "instant payments to new payees" feature. The code passed review, the penetration test found nothing critical, and the feature went live. Three weeks later fraud analysts noticed that a single compromised mobile session could add a payee and send the maximum payment within seconds, with no step-up authentication, because nobody had asked "what happens if the session token is stolen?" during design. The fix took two sprints. The losses, customer refunds and regulator conversations took far longer.

That is the gap a threat model closes. Code review and scanning find bugs in what you built. Threat modelling finds flaws in what you designed, before anyone writes code, when changes are cheapest. Regulators and auditors increasingly expect to see it, too:

  • PCI DSS v4.0.1 expects software to be developed securely, with attention to common attacks and an inventory of risks to bespoke code (requirement 6) and a targeted risk analysis for some controls. ⚠ VERIFY exact requirement numbers with your QSA.
  • UK operational resilience rules expect you to understand how an important business service (such as making payments) could be disrupted.
  • DORA (for Harbourline's EU subsidiary) expects an ICT risk-management framework that identifies threats to ICT systems.

None of these regulations prescribes STRIDE. They expect a documented, repeatable way of finding and treating risk. STRIDE is the most widely used method for doing that at the level of a single system, and it is the one this platform teaches.

The idea in plain language

A threat model is a structured conversation about a system, written down. It answers four questions, popularised by Adam Shostack and the Threat Modeling Manifesto:

  1. What are we working on? A diagram of the system and how data moves through it.
  2. What can go wrong? A list of threats.
  3. What are we going to do about it? A decision and a control for each threat.
  4. Did we do a good enough job? A review, plus tests and monitoring that prove the controls work.

STRIDE is a checklist for question 2. Each letter is a category of threat, and each category is the opposite of a security property you want:

LetterThreatProperty violatedPlain questionBanking example
SSpoofingAuthenticationCan someone pretend to be someone or something else?A stolen mobile session token is used to initiate payments
TTamperingIntegrityCan someone change data or code they shouldn't?The amount in a queued payment message is changed from 50.00 to 5,000.00
RRepudiationNon-repudiationCan someone deny doing something, and can we prove otherwise?An operator approves a CHAPS payment and later claims they never did
IInformation disclosureConfidentialityCan data leak to someone who shouldn't see it?IBANs and names appear in application logs shipped to a third-party tool
DDenial of serviceAvailabilityCan someone stop the service working for others?A bot floods the payment-status endpoint and starves database connections
EElevation of privilegeAuthorisationCan someone do more than they are allowed to?A customer changes accountId in the URL and reads another customer's account

Analogy: a threat model is the walk-through a bank's physical-security team does before opening a new branch. They look at the floor plan (the DFD), mark where the public area ends and the staff area begins (trust boundaries), then go room by room asking "could someone get in here pretending to be staff? Could they change the till float? Could they deny they opened the safe?" (STRIDE per element). Every answer becomes a lock, a camera, a procedure, or a signed acceptance of the risk.

The data-flow diagram in five shapes

STRIDE works on a data-flow diagram, not on a class diagram or a network diagram. A DFD has only five element types:

ElementDrawn asExamples at Harbourline
External entityRectangleCustomer's mobile app, the Faster Payments scheme, an operator
ProcessCircle or rounded boxPayments API (ASP.NET Core), sanctions-screening Lambda
Data storeTwo parallel lines or a cylinderPayments table (DynamoDB), audit log bucket (S3), Secrets Manager
Data flowArrowHTTPS request, SQS message, SQL query
Trust boundaryDashed lineInternet → AWS edge, public subnet → private subnet, Harbourline account → scheme network

A trust boundary is anywhere data or control passes between parts of the system that have different levels of trust or different owners. Threats cluster at trust boundaries, so that is where you look hardest.

STRIDE per element

Not every STRIDE category applies to every element. The classic STRIDE-per-element table (from Microsoft's Security Development Lifecycle) tells you which questions to ask:

ElementSTRIDE
External entity✓✓
Process✓✓✓✓✓✓
Data store✓✓*✓✓
Data flow✓✓✓

* Repudiation applies to data stores that hold logs or audit trails, because attacking the log is how someone hides what they did.

This turns "think of everything that could go wrong" into a finite checklist: for each element on the diagram, ask the questions ticked in its row.

What problem threat modelling solves

Threat modelling is a practice, not an AWS service. It solves three problems:

  1. Design flaws are invisible to scanners. No SAST tool can tell you that "add payee" should require step-up authentication. A threat model can.
  2. Security work needs a reason. Each control in the module project (WAF, KMS keys, VPC endpoints, idempotency keys) should trace back to a threat. When an architect asks "why do we pay for this?", the threat model answers.
  3. Auditors want evidence of risk-based thinking. A dated, reviewed, versioned threat model is that evidence.

AWS supports the practice in a few places:

  • The AWS Well-Architected Framework security pillar includes a best practice to identify and prioritise risks using a threat model.
  • Threat Composer is an open-source tool from AWS Labs. It helps you write threats in a consistent grammar, attach mitigations and export the result as JSON or Markdown. It runs in a browser with data stored locally, and AWS has also made it available inside the AWS Toolkit for VS Code. ⚠ VERIFY the current VS Code integration status.
  • AWS publishes threat-modelling guidance and workshops for builders.

Limitations to be honest about:

  • A threat model is only as good as the diagram. If the diagram omits the batch job that exports data to a partner over SFTP, the model omits its threats.
  • STRIDE finds technical threats well. It is weaker on business-logic abuse (for example, "authorised push payment" fraud where a genuine customer is tricked into paying a fraudster). Add abuse cases for those.
  • It goes stale. A threat model written once and never updated is worse than none, because it gives false comfort.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Microsoft Threat Modeling Tool (.tm7 files, STRIDE templates for Azure)Threat Composer (open source, JSON export) or any diagram tool + a threat registerThreat Composer is threat-statement first rather than diagram-first; you draw the DFD separately (Mermaid in this lesson)
Microsoft SDL "STRIDE per element"Same method — STRIDE is vendor-neutralNothing changes; only the mitigations map to AWS services instead of Azure ones
Azure Well-Architected security pillarAWS Well-Architected security pillarBoth recommend threat modelling; AWS frames it as identifying and prioritising risks
Entra ID Conditional Access as a spoofing mitigationCognito / IAM Identity Center MFA, WAF ATP, step-up authentication in your appAWS has no single Conditional Access engine; mitigations are spread across services
Defender for Cloud attack-path analysisSecurity Hub exposure findings, IAM Access Analyzer external-access findingsThese complement a threat model by finding deployed misconfigurations, not design flaws

If you have used the Microsoft tool, your STRIDE knowledge transfers completely. The difference is that the Microsoft tool generates threats from an Azure stencil library; on AWS you generate them yourself with the per-element table, which is better practice anyway because you have to think.

Architecture

This is the system we will model: the Payments API that lets a Harbourline customer send a Faster Payment from the mobile app.

The numbered arrows are the data flows we will analyse. The subgraphs are trust zones; every arrow that crosses a subgraph edge crosses a trust boundary.

Security-boundary view

BoundaryCrossing flowsWhat changes across itPrimary controls
Internet → AWS edge1Anonymous → authenticated customerTLS 1.2+, WAF, Cognito JWT, rate limits
Edge → private app2Gateway → workloadPrivate integration (VPC link), no public IPs
App → data3, 4, read credsCode → durable stateIAM task role, KMS key policy, VPC endpoints
App → log archive account7Workload → evidenceCross-account bucket policy, Object Lock, write-only role
AWS → scheme6Harbourline → external partymTLS, message signing, egress filtering

Step-by-step implementation

Scope the model and gather inputs

Decide what is in scope: here, "customer-initiated Faster Payment from the mobile app, from request to submission to the scheme". Collect the architecture diagram, the OpenAPI specification, the IAM roles and the data classification of each field (see Data classification, masking and tokenisation). Invite the right people for one 90-minute session: the developer who owns the API, an architect, a security engineer, someone from fraud operations, and a product owner who can accept risk. A threat model done by security alone misses how the system really works; one done by developers alone misses how attackers think.

Draw the data-flow diagram

Draw only the five DFD shapes. Number every data flow. Draw trust boundaries as dashed lines. Then check the diagram against reality: list the deployed resources (the CLI section shows how) and make sure nothing is missing. Common omissions are admin paths (an operator's console access), batch exports, and third-party monitoring agents.

Apply STRIDE per element

Walk the diagram element by element. For each one, ask the questions from the per-element table and write each threat as a threat statement in this grammar (the same one Threat Composer uses):

A [threat source] with [prerequisites] can [threat action], which leads to [threat impact], negatively impacting [assets].

For example: "An external attacker with a stolen customer access token can initiate payments to a new payee, which leads to fraudulent loss of customer funds, negatively impacting customer balances and Harbourline's reputation."

Writing in this grammar forces you to state the prerequisite, which is often where the cheapest mitigation lives.

Rate each threat

Use a simple, defensible scale rather than a precise-looking formula. Harbourline uses likelihood (1–3) × impact (1–3), giving 1–9, with High ≥ 6, Medium 3–4, Low 1–2. Agree definitions in advance, for example impact 3 = "customer funds lost, or personal data of more than 1,000 customers exposed, or a reportable incident". Older methods such as DREAD produce numbers that look scientific but vary wildly between assessors; most teams have moved away from them.

Decide and map to controls

For each threat choose:

  • Mitigate — add a control (most threats).
  • Eliminate/avoid — remove the feature or data (for example, don't store full PAN at all).
  • Transfer — move the risk to someone else, contractually or technically (for example, a payment-card tokenisation provider).
  • Accept — a named risk owner signs it, with a review date. Developers cannot accept risk on the bank's behalf.

Map each mitigation to a specific AWS feature or code change, and to a verification: a test, a Config rule, a WAF metric, a CloudTrail query. A mitigation without verification is a hope.

Store the model as code and review it on change

Save the threat register as a JSON file next to the code (threat-model/payments-api.json). The C# checker in this lesson fails the pipeline if any High threat lacks a mitigation, if an accepted risk has passed its review date, or if a mitigation is missing a verification. Add a pull-request template question: "Does this change add a data flow, data store, external entity or trust boundary? If yes, update the threat model." That is the trigger for re-review.

The worked model: Payments API

Here is the output of the session for the diagram above. It is deliberately not exhaustive; the exercises ask you to extend it.

IDElementSTRIDEThreat statement (short)L×IDecisionMitigationVerification
T01Customer (external entity)SAttacker with a stolen access token initiates payments2×3=6 HighMitigateShort-lived Cognito tokens; step-up MFA when adding a payee or paying a new payee; device bindingIntegration test: new-payee payment without step-up returns 403
T02Flow 1T, IAttacker on hostile Wi-Fi intercepts or modifies the request1×3=3 MedMitigateTLS 1.2+ only (API Gateway security policy), certificate pinning in the appSecurity Hub CSPM / Config check on TLS policy; app pen test
T03Flow 1 / APIDBot floods POST /payments and GET /payments/{id}2×2=4 MedMitigateWAF rate-based rules, API Gateway usage plans and throttling, Fargate auto scaling with a ceilingWAF BlockedRequests metric alarm; load test
T04Payments API (process)ECustomer changes debtorAccountId to an account they don't own (IDOR / broken object-level authorisation)3×3=9 HighMitigateOwnership check on every request using the sub claim, never the request body; deny by defaultUnit + integration test "customer B cannot pay from customer A's account"
T05Payments APITClient retries a timed-out request and the payment is made twice3×2=6 HighMitigateMandatory Idempotency-Key header; DynamoDB conditional put on the keyTest: two identical POSTs produce one payment and the same response
T06Payments APIRCustomer disputes that they initiated a payment2×2=4 MedMitigateaudit_events record with actor, device, correlation ID, before/after state; written to the log-archive accountQuery a sample payment end to end during audit evidence collection
T07Payments APIIException details, IBANs or tokens leak in error responses or logs2×3=6 HighMitigateProblemDetails without stack traces; structured logging with redaction; CloudWatch Logs data protection policyLog review in code review; Macie or data protection findings
T08Payments table (data store)TA developer with console access edits a payment's amount or status directly1×3=3 MedMitigateNo human write access in production (SCP + permission sets); break-glass role with alertingAccess Analyzer / IAM review; EventBridge alert on break-glass use
T09Payments tableISnapshot or export of the table is shared or copied outside the account1×3=3 MedMitigateKMS CMK with key policy restricted to the account; RCP/SCP on sharingConfig rule; key policy review
T10Flow 4 / SQSTA compromised component injects a forged payment message onto the queue1×3=3 MedMitigateQueue policy allows sqs:SendMessage only from the API's task role; screening Lambda verifies a signature over the payment (see Transaction integrity and non-repudiation)Policy test with the IAM policy simulator; signature verification unit tests
T11Screening LambdaEOver-broad execution role lets a bug in the Lambda read all secrets2×2=4 MedMitigateLeast-privilege role; resource-scoped secretsmanager:GetSecretValueAccess Analyzer unused-access findings
T12Audit storeR, TAn attacker who compromised the workload account deletes logs to hide activity1×3=3 MedMitigateSeparate log-archive account, S3 Object Lock, CloudTrail log file validationMonthly validation run (aws cloudtrail validate-logs)
T13Flow 6 / schemeSAttacker impersonates the FPS gateway (DNS hijack) to capture payments1×3=3 MedMitigatemTLS with pinned scheme CA; egress allow-list in Network FirewallCertificate validation test; firewall rule review
T14Secrets ManagerIScheme client certificate private key exfiltrated1×3=3 MedMitigateKey stored in Secrets Manager with CMK, or non-exportable in Private CA/CloudHSM; rotationSecrets Manager rotation status; CloudTrail GetSecretValue anomaly alarm
T15CustomerS (business)Customer is socially engineered into paying a fraudster (APP fraud)3×3=9 HighMitigate (partly) / TransferConfirmation of Payee check, risk-based warnings, delayed first payment to new payeeFraud KPIs — outside STRIDE's technical scope, tracked by fraud ops

Notice what the model produced:

  • Two High threats (T04, T15) are not about AWS at all. Broken object-level authorisation is the most common API vulnerability in the OWASP API Security Top 10, and APP fraud is a business threat. A threat model that only lists AWS services would miss both.
  • T05 is a correctness threat that STRIDE calls tampering. Duplicate payments are an integrity failure. The idempotency key in CONVENTIONS.md exists because of it.
  • Every mitigation has a verification. That last column is what turns a workshop into evidence.

AWS Console instructions

Threat modelling is mostly offline, but the console helps you check the diagram matches what is deployed (read-only):

  1. Console → API Gateway → APIs → (your API) → Resources — list every route. Each route is part of a process in your DFD; unexpected routes (for example a forgotten /debug) are new threats.
  2. Console → API Gateway → (API) → Authorizers — confirm which routes have an authoriser. A route with Authorization: NONE is a spoofing threat.
  3. Console → VPC → Endpoints — confirm which AWS services the workload reaches privately. Anything not listed goes via NAT and crosses an extra trust boundary.
  4. Console → IAM → Roles → (task role) → Permissions — list what the process can actually do. Compare with the least privilege you assumed in the model.
  5. Console → Resource Groups & Tag Editor → Tag Editor — search for resources tagged Project=cea-lab (or your production tag) to find stores and queues missing from the diagram.

If you use Threat Composer, open it from the AWS Labs GitHub Pages site (linked under Further reading) or the VS Code toolkit, create a workspace "Harbourline Payments API", add the application description, paste your Mermaid diagram as an image or description, then add threats using the statement builder and link mitigations. Export as JSON and commit it.

AWS CLI

These read-only commands help you build and verify the DFD. They need the learn-sandbox profile and only work if you deployed the Module 4 or module-project resources; otherwise read them as a checklist.

# 1. Who am I? Confirms which account you are inventorying.
aws sts get-caller-identity --profile learn-sandbox

# 2. Every resource tagged for this platform: the raw material for data stores and processes.
aws resourcegroupstaggingapi get-resources \
  --tag-filters Key=Project,Values=cea-lab \
  --query "ResourceTagMappingList[].ResourceARN" --output table --profile learn-sandbox

# 3. REST API routes and their authorisation type: any NONE is a spoofing candidate.
aws apigateway get-resources --rest-api-id <api-id> \
  --query "items[].{path:path,methods:resourceMethods}" --profile learn-sandbox
aws apigateway get-method --rest-api-id <api-id> --resource-id <resource-id> \
  --http-method POST --query "{auth:authorizationType,apiKey:apiKeyRequired}" --profile learn-sandbox

# 4. VPC endpoints: data flows that stay on the AWS network.
aws ec2 describe-vpc-endpoints \
  --query "VpcEndpoints[].{service:ServiceName,type:VpcEndpointType}" --output table --profile learn-sandbox

# 5. Who can send to the payment queue? (Threat T10)
aws sqs get-queue-attributes --queue-url <queue-url> \
  --attribute-names Policy KmsMasterKeyId --profile learn-sandbox

# 6. Simulate whether the screening Lambda's role can read a secret it should not (Threat T11).
aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::<account-id>:role/hl-m05-screening-role \
  --action-names secretsmanager:GetSecretValue \
  --resource-arns arn:aws:secretsmanager:us-east-1:<account-id>:secret:hl-m05-unrelated-secret \
  --query "EvaluationResults[].EvalDecision" --profile learn-sandbox

Placeholders in angle brackets are values from your own deployment. Every command is read-only.

Infrastructure as Code

Threat models are most useful when mitigations are visible in the code that creates the resources. A simple convention is to tag each resource with the threat IDs it mitigates, so a reviewer (or a Config rule) can trace controls back to threats. Below, the payments table carries the mitigations for T08 and T09, and the queue policy implements T10.

PaymentsDataStack.cs
using System.Collections.Generic;
using Amazon.CDK;
using Amazon.CDK.AWS.DynamoDB;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.SQS;
using Constructs;

namespace Harbourline.Payments.Infra;

public sealed class PaymentsDataStack : Stack
{
    public PaymentsDataStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
    {
        // Mitigates T09: a customer managed key whose policy we control, with rotation on.
        var key = new Key(this, "PaymentsKey", new KeyProps
        {
            Alias = "alias/hl-m05-payments",
            EnableKeyRotation = true,
            RemovalPolicy = RemovalPolicy.DESTROY, // learning shortcut: production uses RETAIN
        });

        // Mitigates T05 (idempotency key is the partition key of a separate table, see the lesson code)
        // and T08 (deletion protection, point-in-time recovery for forensic restore).
        var payments = new TableV2(this, "Payments", new TablePropsV2
        {
            TableName = "hl-m05-payments",
            PartitionKey = new Amazon.CDK.AWS.DynamoDB.Attribute { Name = "paymentId", Type = AttributeType.STRING },
            Encryption = TableEncryptionV2.CustomerManagedKey(key),
            PointInTimeRecoverySpecification = new PointInTimeRecoverySpecification { PointInTimeRecoveryEnabled = true },
            DeletionProtection = true,
            RemovalPolicy = RemovalPolicy.DESTROY, // learning shortcut
        });
        Amazon.CDK.Tags.Of(payments).Add("ThreatMitigates", "T05 T08 T09");

        // Mitigates T10: only the API task role may send messages to the queue.
        var queue = new Queue(this, "PaymentQueue", new QueueProps
        {
            QueueName = "hl-m05-payment-queue",
            Encryption = QueueEncryption.KMS,
            EncryptionMasterKey = key,
            EnforceSSL = true,
        });
        var apiTaskRole = Role.FromRoleName(this, "ApiTaskRole", "hl-m05-payments-api-task");
        queue.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps
        {
            Sid = "DenySendExceptPaymentsApi",
            Effect = Effect.DENY,
            Principals = new IPrincipal[] { new AnyPrincipal() },
            Actions = new[] { "sqs:SendMessage" },
            Resources = new[] { queue.QueueArn },
            Conditions = new Dictionary<string, object>
            {
                ["ArnNotEquals"] = new Dictionary<string, object> { ["aws:PrincipalArn"] = apiTaskRole.RoleArn },
            },
        }));
        Amazon.CDK.Tags.Of(queue).Add("ThreatMitigates", "T10");

        foreach (var (k, v) in new[] { ("Project", "cea-lab"), ("Lab", "m05-stride"), ("Environment", "learn"), ("Owner", "you") })
        {
            Amazon.CDK.Tags.Of(this).Add(k, v);
        }
    }
}

You do not need to deploy this to complete the lesson. If you do, it costs about USD 1 per month for the KMS key (prorated hourly) plus negligible request charges; destroy it in the same session.

Complete code

The threat register lives as JSON next to the service. A small checker, written as a .NET 10 file-based app (a single .cs file you run with dotnet run), enforces the rules a reviewer would otherwise check by hand.

threat-model/payments-api.json
{
  "system": "Harbourline Payments API",
  "version": "2026-11-18",
  "owner": "payments-platform-team",
  "elements": [
    { "id": "E1", "name": "Customer mobile app", "kind": "ExternalEntity" },
    { "id": "P1", "name": "Payments API", "kind": "Process" },
    { "id": "D1", "name": "Payments table", "kind": "DataStore" },
    { "id": "D2", "name": "Audit store", "kind": "DataStore", "holdsLogs": true },
    { "id": "F1", "name": "POST /payments over HTTPS", "kind": "DataFlow", "crossesTrustBoundary": true }
  ],
  "threats": [
    {
      "id": "T01", "elementId": "E1", "category": "Spoofing",
      "statement": "An external attacker with a stolen access token can initiate payments to a new payee, leading to fraudulent loss of customer funds.",
      "likelihood": 2, "impact": 3, "decision": "Mitigate",
      "mitigations": [ { "control": "Step-up MFA for new payees", "verification": "IntegrationTests.NewPayeeRequiresStepUp" } ]
    },
    {
      "id": "T04", "elementId": "P1", "category": "ElevationOfPrivilege",
      "statement": "An authenticated customer can change debtorAccountId to another customer's account, leading to unauthorised payments.",
      "likelihood": 3, "impact": 3, "decision": "Mitigate",
      "mitigations": [ { "control": "Ownership check from sub claim", "verification": "IntegrationTests.CannotPayFromOthersAccount" } ]
    },
    {
      "id": "T15", "elementId": "E1", "category": "Spoofing",
      "statement": "A fraudster can socially engineer a customer into paying them, leading to customer loss and reimbursement cost.",
      "likelihood": 3, "impact": 3, "decision": "Accept",
      "riskOwner": "Head of Fraud Operations", "reviewBy": "2027-05-18",
      "mitigations": [ { "control": "Confirmation of Payee and risk warnings", "verification": "Fraud KPI dashboard" } ]
    }
  ]
}
threat-model/check.cs
// Run with:  dotnet run threat-model/check.cs -- threat-model/payments-api.json
// A .NET 10 file-based app: no .csproj needed. Exit code 0 = pass, 1 = rule failures, 2 = bad input.
using System.Text.Json;
using System.Text.Json.Serialization;

var path = args.Length > 0 ? args[0] : "threat-model/payments-api.json";
if (!File.Exists(path))
{
    Console.Error.WriteLine($"Threat model not found: {path}");
    return 2;
}

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    Converters = { new JsonStringEnumConverter() },
};

ThreatModel? model;
try
{
    model = JsonSerializer.Deserialize<ThreatModel>(File.ReadAllText(path), options);
}
catch (JsonException ex)
{
    Console.Error.WriteLine($"Invalid JSON: {ex.Message}");
    return 2;
}
if (model is null)
{
    Console.Error.WriteLine("Empty threat model.");
    return 2;
}

var today = DateOnly.FromDateTime(DateTime.UtcNow);
var problems = ThreatModelRules.Check(model, today).ToList();
var coverage = ThreatModelRules.MissingStrideCoverage(model).ToList();

Console.WriteLine($"# Threat model check — {model.System} (version {model.Version})");
Console.WriteLine();
Console.WriteLine("| ID | Category | Risk | Decision |");
Console.WriteLine("|---|---|---|---|");
foreach (var t in model.Threats.OrderByDescending(t => t.Likelihood * t.Impact))
{
    Console.WriteLine($"| {t.Id} | {t.Category} | {ThreatModelRules.Rating(t)} ({t.Likelihood * t.Impact}) | {t.Decision} |");
}

Console.WriteLine();
foreach (var gap in coverage)
{
    Console.WriteLine($"INFO  {gap}");
}
foreach (var p in problems)
{
    Console.WriteLine($"FAIL  {p}");
}
Console.WriteLine(problems.Count == 0 ? "PASS  all rules satisfied" : $"{problems.Count} rule failure(s)");
return problems.Count == 0 ? 0 : 1;

enum ElementKind { ExternalEntity, Process, DataStore, DataFlow }
enum Stride { Spoofing, Tampering, Repudiation, InformationDisclosure, DenialOfService, ElevationOfPrivilege }
enum Decision { Mitigate, Avoid, Transfer, Accept }

sealed record Element(string Id, string Name, ElementKind Kind, bool HoldsLogs = false, bool CrossesTrustBoundary = false);
sealed record Mitigation(string Control, string? Verification);
sealed record Threat(
    string Id, string ElementId, Stride Category, string Statement,
    int Likelihood, int Impact, Decision Decision,
    List<Mitigation> Mitigations, string? RiskOwner = null, DateOnly? ReviewBy = null);
sealed record ThreatModel(string System, string Version, string Owner, List<Element> Elements, List<Threat> Threats);

static class ThreatModelRules
{
    // STRIDE-per-element: which categories are expected for each DFD element kind.
    private static readonly Dictionary<ElementKind, Stride[]> Expected = new()
    {
        [ElementKind.ExternalEntity] = [Stride.Spoofing, Stride.Repudiation],
        [ElementKind.Process] = Enum.GetValues<Stride>(),
        [ElementKind.DataStore] = [Stride.Tampering, Stride.InformationDisclosure, Stride.DenialOfService],
        [ElementKind.DataFlow] = [Stride.Tampering, Stride.InformationDisclosure, Stride.DenialOfService],
    };

    public static string Rating(Threat t) => (t.Likelihood * t.Impact) switch
    {
        >= 6 => "High",
        >= 3 => "Medium",
        _ => "Low",
    };

    public static IEnumerable<string> Check(ThreatModel model, DateOnly today)
    {
        var elementIds = model.Elements.Select(e => e.Id).ToHashSet(StringComparer.Ordinal);
        var seen = new HashSet<string>(StringComparer.Ordinal);

        foreach (var t in model.Threats)
        {
            if (!seen.Add(t.Id))
                yield return $"{t.Id}: duplicate threat ID";
            if (!elementIds.Contains(t.ElementId))
                yield return $"{t.Id}: refers to unknown element '{t.ElementId}'";
            if (t.Likelihood is < 1 or > 3 || t.Impact is < 1 or > 3)
                yield return $"{t.Id}: likelihood and impact must be 1-3";
            if (string.IsNullOrWhiteSpace(t.Statement) || t.Statement.Length < 40)
                yield return $"{t.Id}: threat statement is missing or too vague";

            if (t.Decision == Decision.Mitigate && t.Mitigations.Count == 0)
                yield return $"{t.Id}: decision is Mitigate but no mitigation is listed";
            foreach (var m in t.Mitigations.Where(m => string.IsNullOrWhiteSpace(m.Verification)))
                yield return $"{t.Id}: mitigation '{m.Control}' has no verification";

            if (t.Decision == Decision.Accept)
            {
                if (string.IsNullOrWhiteSpace(t.RiskOwner))
                    yield return $"{t.Id}: accepted risk needs a named risk owner";
                if (t.ReviewBy is null)
                    yield return $"{t.Id}: accepted risk needs a review date";
                else if (t.ReviewBy < today)
                    yield return $"{t.Id}: risk acceptance expired on {t.ReviewBy:yyyy-MM-dd}";
            }
        }
    }

    // Informational: which expected STRIDE categories have no threat recorded yet.
    public static IEnumerable<string> MissingStrideCoverage(ThreatModel model)
    {
        foreach (var e in model.Elements)
        {
            var expected = Expected[e.Kind].ToList();
            if (e.Kind == ElementKind.DataStore && e.HoldsLogs)
                expected.Add(Stride.Repudiation);
            var covered = model.Threats.Where(t => t.ElementId == e.Id).Select(t => t.Category).ToHashSet();
            var missing = expected.Where(c => !covered.Contains(c)).ToList();
            if (missing.Count > 0)
                yield return $"{e.Id} ({e.Name}): no threats recorded for {string.Join(", ", missing)} — considered and not applicable?";
        }
    }
}

Run it:

dotnet run threat-model/check.cs -- threat-model/payments-api.json

Expected output (abridged): a Markdown table of the three threats ordered by risk, a set of INFO lines listing STRIDE categories you have not yet considered for each element (for example INFO D1 (Payments table): no threats recorded for Tampering, InformationDisclosure, DenialOfService — considered and not applicable?), and PASS all rules satisfied. Change T15's reviewBy to a past date and the run ends with FAIL T15: risk acceptance expired … and exit code 1, which fails a pipeline step.

Code explained line by line

  1. // Run with: dotnet run threat-model/check.cs … — .NET 10 can run a single C# file directly (a file-based app), so the checker needs no project file. In a pipeline, the same command runs after actions/setup-dotnet.
  2. JsonStringEnumConverter — lets the JSON say "Spoofing" instead of 0. Human-readable enums matter because security and risk people will edit this file too.
  3. PropertyNameCaseInsensitive = true — the JSON uses camelCase; the C# records use PascalCase (the platform convention).
  4. return 2 for missing or invalid input, 1 for rule failures, 0 for pass — distinct exit codes let the pipeline tell "the model is broken" apart from "the model reveals a gap".
  5. enum Stride { … } — the six categories. Encoding them as an enum means a typo such as Spoffing fails deserialisation instead of silently creating a seventh category.
  6. sealed record Threat(…) — immutable records are a natural fit for register entries; ReviewBy is a DateOnly? because only accepted risks need it.
  7. Expected — the STRIDE-per-element table as data. Data stores get Repudiation only when HoldsLogs is true, exactly as the table's footnote says.
  8. Rating — the agreed 1–9 scale with thresholds. Keeping the formula in code means everyone rates the same way.
  9. Check — the review rules: unique IDs, valid element references, a statement long enough to be specific, a mitigation for every Mitigate decision, a verification for every mitigation, and a named owner plus an unexpired review date for every accepted risk.
  10. t.ReviewBy < today — risk acceptance must expire. Banks commonly re-review accepted risks at least annually; Harbourline uses six months for High risks.
  11. MissingStrideCoverage — prints INFO, not FAIL, because "not applicable" is a legitimate answer. The point is to make the team say so consciously.
  12. The output is Markdown so the pipeline can post it as a pull-request comment or a job summary.

Security considerations

⚠ Learning shortcut — not for production

In this lesson the threat model has fifteen threats, one session and no independent review. In production, a payment system's threat model is reviewed by the security architecture function, accepted risks are signed by a named business owner within the bank's risk-management framework, and the model is re-reviewed on every significant change and at least annually. The JSON file in Git gives version history, but the formal risk acceptance must also be recorded in the bank's risk register (GRC tool), because that is what the second line of defence and auditors look at.

  • Treat the threat model as sensitive. It is a map of your weaknesses. Store it in a private repository, restrict access, and don't paste it into public tools or unapproved AI services.
  • Threat Composer stores data in the browser's local storage when used from the web; clearing browser data loses unsaved work, and shared machines expose it. Export to JSON and commit to the private repository.
  • Don't let the model replace testing. A mitigation recorded as "done" with no test is the most dangerous line in the register.
  • Include the AWS shared responsibility boundary. AWS mitigates threats to its infrastructure (physical access, hypervisor isolation). Everything in the worked model above is Harbourline's responsibility, including how AWS services are configured.

Banking use case

Harbourline's change process requires a threat model for any change that touches money movement, customer personal data or authentication. The Payments Platform team keeps threat-model/payments-api.json in the service repository. The pipeline (see Pipeline security scanning) runs the checker on every pull request and posts the table as a job summary. When the team added "request to pay", a new external entity (the payee's bank) and a new data flow appeared, the PR template question triggered a 45-minute review, and three new threats were added — including one (spoofed request-to-pay messages used for phishing) that led to a product change: requests from unknown payees are shown with a warning.

The security architecture team samples threat models quarterly. Internal audit asks for evidence that High threats have tested mitigations; the team answers by linking each verification to a passing test run and a Config rule result, which is exactly the evidence pattern in Audit logging and evidence collection.

Common mistakes

  • Modelling the network diagram instead of the data flows → you end up listing subnets, not threats. Draw DFD shapes only; network controls appear as mitigations.
  • Boiling the ocean → a single model for "the bank" never finishes. Scope one business capability per model, and link models where they meet.
  • Generic threats ("hackers could hack the API") → nobody can act on them. Use the threat grammar with a prerequisite and an impact.
  • Mitigations that are products, not controls ("we have GuardDuty") → say what the control does against this threat and how you'd know it worked.
  • Developers accepting risk → acceptance belongs to an accountable business owner within the bank's risk framework.
  • Never updating the model → wire the update trigger into the PR template and the pipeline.
  • Ignoring business-logic abuse → add abuse cases (APP fraud, limit abuse, promotional-offer abuse) next to STRIDE.

Troubleshooting

SymptomLikely causeFix
Workshop produces 200 threats and no decisionsScope too wide, no rating scale agreedNarrow the scope; agree likelihood/impact definitions before the session; time-box per element
Everyone rates everything HighImpact definitions missingWrite concrete impact levels tied to money, customers affected and regulatory reporting
dotnet run check.cs fails with "Couldn't find a project to run"SDK older than .NET 10, or path typoRun dotnet --version (must be 10.x); check the path
Checker exits 2: Invalid JSON … could not be converted to StrideTypo in a category, or using "Information disclosure" with a spaceUse the exact enum names, e.g. InformationDisclosure
Lots of INFO lines for data flowsFlows not yet analysedFor each, either add a threat or note "not applicable" in your review minutes
Model and reality differResources added outside the designRe-run the CLI inventory; add a Config rule or tag check for untagged resources

Cost and cleanup

This lesson is free: threat modelling is a workshop, Threat Composer is open source, and the checker runs locally. The CLI commands are read-only.

If you deployed the optional IaC:

# CDK
cdk destroy --profile learn-sandbox
# or Terraform
terraform destroy

# DynamoDB deletion protection blocks deletion: switch it off first if destroy fails
aws dynamodb update-table --table-name hl-m05-payments --no-deletion-protection-enabled --profile learn-sandbox

# The KMS key enters a waiting period (7–30 days) and costs nothing more once pending deletion
aws kms list-aliases --query "Aliases[?AliasName=='alias/hl-m05-payments']" --profile learn-sandbox

# Confirm nothing tagged for this lab remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m05-stride --profile learn-sandbox

Exercises

  • 🟢 Guided: Add threats for the Payments table (D1) for each category the checker reports as missing (Tampering, Information disclosure, Denial of service). Write each with the threat grammar, rate it, and map it to an AWS control with a verification. Re-run the checker until D1 has no INFO line.
  • 🟡 Challenge: Extend the DFD with an operator approval step for CHAPS payments over GBP 250,000: an operator in a back-office web app approves the payment before submission. Identify the new elements and trust boundaries, and write at least six new threats, including a segregation-of-duties threat (the same person initiates and approves).
  • 🔴 Live problem: A product manager messages you: "Marketing wants to send payment confirmations through a new third-party messaging SaaS by Friday. It just needs the payee name, amount and the customer's phone number. Can you sign it off?" Decide what you need to model, what threats you expect, which of them you can't decide on alone, and write your reply.

Assignment

Create threat-model/accounts-api.json for the Account API from Module 4 (or the module project), with at least one element of each DFD kind, at least twelve threats covering all six STRIDE categories, and a Mermaid DFD in a README.md. Add the checker to your repository and a GitHub Actions step that runs it. Commit both to your portfolio repository.

Solutions

Knowledge check

Interview questions

  • "Walk me through how you'd threat-model a new API." — Scope one capability; draw a DFD with the five element types and trust boundaries; apply STRIDE per element with the team; write threats in a source–prerequisite–action–impact grammar; rate with agreed definitions; decide mitigate/avoid/transfer/accept; map each mitigation to a control with a verification; store it in the repo and re-review when a PR adds flows, stores or boundaries.
  • "What's the most common High threat you find in banking APIs?" — Broken object-level authorisation (IDOR): a customer accessing another customer's account by changing an ID. It is mitigated in code, by deriving ownership from the authenticated identity, and verified with negative tests. No AWS service fixes it for you.
  • "How is STRIDE different from an OWASP Top 10 review?" — STRIDE is a method for generating threats from the design of your system; the OWASP lists are catalogues of common weaknesses. Use STRIDE to find design threats and OWASP lists as a checklist during code review.
  • "Who should accept risk?" — An accountable business owner under the bank's risk-management framework, with security's advice. Engineers recommend; they don't accept on the bank's behalf.
  • "How do you keep a threat model from going stale?" — Version it with the code, trigger re-review from the PR template when the DFD changes, check it automatically in the pipeline, expire risk acceptances, and sample models in quarterly security reviews.

Certification practice

Completion checklist

  • I can name the six STRIDE categories and the security property each one violates
  • I drew a DFD of the Payments API with numbered flows and trust boundaries
  • I applied STRIDE per element and wrote threats with the statement grammar
  • I ran the C# checker and understood every INFO and FAIL line
  • I can explain who may accept a risk and why it must expire
  • If I deployed the optional IaC, I destroyed it and confirmed nothing tagged Lab=m05-stride remains

Key takeaways

  • A threat model answers four questions: what are we building, what can go wrong, what will we do about it, and did we do a good job.
  • STRIDE per element turns "think like an attacker" into a checklist over a data-flow diagram; look hardest at trust boundaries.
  • The highest-risk threats in banking APIs are often in your code and business logic (IDOR, duplicate payments, APP fraud), not in AWS configuration.
  • Every mitigation needs a verification, and every accepted risk needs an accountable owner and an expiry date.
  • Keep the model in the repository, check it in the pipeline, and re-review when the design changes. AWS secures its infrastructure; the threats in your design are yours.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page