Platform Engineering · Lesson 155

Threat Modeling & Security Practice

A system is not secure because nobody has attacked it yet. It is secure because someone wrote down how it could be attacked, and then closed those doors one by one. That list is a threat model. This lesson is the practice of writing one. I take one request, a user asking for a record that belongs to someone else, and I walk it through nine hops. At each hop I ask what an attacker could do there, and what check stops them. By the end you will have run a STRIDE checklist, caught a broken access check with curl, scanned your own machine, and read a capture the way a defender reads it.

Difficulty: Advanced · Know this first: Lesson 113, Lesson 154, Lesson 52

What you will build

By the end of this lesson you will have written a threat model for a small service and proved it against a running system. First, a STRIDE checklist script that grades eight components and names the open findings. Second, a record service you can break on purpose: with the authorization check off, one curl leaks another customer's invoice; with it on, the same curl gets a 403. Third, a port scan of your own machine, run for real, with one open port and five closed ones. You will also know how a defender reads a Wireshark capture, and what Burp Suite is for, even though those two labs run on your own machine, not in this page.

What you need: Python 3 for the checklist, the record service, and the scanner. All three run on this machine and their outputs are shown exactly as they ran. The nmap, Wireshark, and Burp Suite steps run on your own machine, and they are marked that way. Nothing in this lesson runs against a live system that is not yours.

The story: one request, nine chances to break it

The request is simple. Alice is logged in. She asks for record 2. Record 2 belongs to Bob. The token is valid. The URL is well formed. The app is up. Every check that most teams write would pass this request, because most teams write checks for the wrong question. They check whether Alice is logged in. They do not check whether the record is hers. That missing check has a name. It is BOLA, broken object level authorization, and it is number one on the OWASP API Top 10. This lesson follows that request through nine hops and asks, at each hop, what an attacker could do and what check stops them.

The six questions have a name too. STRIDE. One letter per question. Learn the letters first. They are what you remember at 2 AM.

LetterThe questionWhere it bites in this lesson
S · SpoofingCan someone pretend to be someone else?A stolen session token logs in as Alice. The auth hop checks the signature, the expiry, and the deny list.
T · TamperingCan someone change data on the way?A record ID of "2 OR 1=1" in the URL. The app hop validates the input before it reaches the query.
R · RepudiationCan someone do it and deny it later?A denied read that is never logged. The audit hop writes the user, the record, the decision, and the time.
I · Information disclosureCan someone read what is not theirs?Alice reading Bob's invoice. The authorization hop is the check that stops it.
D · Denial of serviceCan someone stop the system working?A scanner sending 4,800 probes in an hour. The edge hop rate limits the source.
E · Elevation of privilegeCan someone get more access than they should have?A normal user reading a record that belongs to someone else. That is BOLA, and it is elevation, not theft.

Three more ideas carry the whole lesson. The first is the CIA triad. Confidentiality means data stays private. Integrity means data stays unaltered. Availability means the system stays reachable. Every fix in this lesson has to pass all three. A fix that locks the data away so nobody can use it has failed availability. A fix that keeps the system up by letting anyone read anything has failed confidentiality.

The second is Zero Trust. Never trust the network. Verify every request, every time, no matter where it came from. The request in this lesson comes from inside the system, from a logged in user, through the gateway, and it is still checked at every hop. The mesh lesson, Lesson 96, has the machinery for this, mTLS and workload identity, but it never names the idea. This lesson names it. The idea is the point. The machinery is how you build it.

The third is the OWASP Top 10. It is the checklist for the app hop. It names the ten most common web weaknesses, and it changes every few years as the web changes. Lesson 59 teaches the attacks themselves, SQL injection and cross site scripting, without naming the list. This lesson names the list and puts it to work. The full list is in Go deeper. The LLM version of the list lives in Lesson 196, the guardrails lesson, and this lesson does not repeat it.

Here are the nine hops, each with its one job. The request enters at the client and the answer is born at the database. Everything after the database is the answer coming back and the system writing down what happened.

HopIts one jobThe check that runs there
1 · Client sendsThe request enters the modelNothing. The client is never trusted.
2 · Edge and WAFThe first filterKnown bad patterns are dropped. One loud source is rate limited.
3 · API gatewayRouting and countingThe route is checked. The request is logged.
4 · Auth checkWho are youThe token signature, expiry, and deny list.
5 · App serverWhere OWASP livesInput is validated before it reaches the query.
6 · AuthorizationMay you see this recordThe record owner is compared to the logged in user.
7 · DatabaseThe data hopThe app login can read the records table and nothing else.
8 · Audit logThe memory of the systemEvery read writes a line, with the decision in it.
9 · VerdictThe threat model answersEvery STRIDE row has a check, or a finding with a date.

Do this now, before you read on

Write down the three assets of the lab service. The records, the session tokens, and the audit log. Three assets, three things an attacker wants. If you cannot name the assets, you cannot model the threats. The checklist script in the lab starts from exactly this list, and it finds two open findings. See if you can guess which two before you run it.

Run it as:

When it breaks, I check

One thing to remember

Four paths, one family

The diagram above follows one request through nine hops. These four paths are the same idea drawn four ways. One request, clean. One request, asking for someone else's record. One threat model, counted in risk points. One scanner, filtered hop by hop. Run each path. One run takes 7.2 seconds across the path, so you can watch each hop light up in turn.

The return rule: the green dot only starts moving after the orange dot reaches the data hop. A return with no request is a lie. The diagram never draws one. The failure replay at the end of Run all four shows the other side of the rule. Run the BOLA attempt again, and the orange dot stops at the authorization hop and never comes back.

Path 1: the clean request

Risk trail: skipped

Alice asks for her own record. Client, edge, gateway, auth, app, authorization, database. Every hop runs its check, and the database answers the request.

Client0 ms
Edge and WAF3 ms
API gateway4 ms
Auth check6 ms
App server8 ms
Authorization5 ms
Database10 ms

Not run yet.

Path 2: the BOLA attempt

Database: skipped

Same request, one change. Alice asks for record 2, which belongs to Bob. Authentication passes, because Alice is Alice. The authorization hop denies the read. The database never sees the question.

Client0 ms
Edge and WAF3 ms
API gateway4 ms
Auth check6 ms
App server8 ms
Authorizationdenied

Not run yet.

Path 3: the risk trail

Scanner: skipped

The same request, counted in risk points instead of milliseconds. Each hop shows how many STRIDE threats the threat model counts there. The trail adds up to 23 risk points. The app hop counts the most, because that is where input meets the query.

Client2 pts
Edge and WAF3 pts
API gateway2 pts
Auth check4 pts
App server5 pts
Authorization4 pts
Database3 pts

Not run yet.

Path 4: the scanner storm

Database: skipped

A scanner sends 4,800 probes in an hour. Each hop shows how many probes reach it. The edge drops most of them. The gateway throttles what is left. Auth rejects the bad tokens. The app sees 620 probes that got through the filters. The verdict blocks the source. The database sees none of it.

Client1 probe
Edge and WAF4,800
API gateway4,300
Auth check1,900
App server620
Verdictblocked

Not run yet.

Where the time goes

Every hop charges rent in milliseconds. The bar below is a worked example for one request through the threat model, not a measurement from a live system, but the shape is honest. The clean request costs 42 ms. The BOLA attempt costs 79 ms, and the extra time is the deny and the alert. The scanner storm costs 161 ms, and most of it is the edge saying no. Move a simulator slider and watch the edge, auth, and app hops move with it. Switch the scenario and watch the authorization hop or the edge hop change instead.

Risk or speed: move the sliders and watch the trade

The budget bar above shows three fixed stories. This simulator lets you write your own. It answers the trade-off at the heart of this lesson: every check costs milliseconds, and every missing check costs risk. You set how many endpoints the internet can reach, how many auth checks run, how hard a scanner is hitting the edge, and how much of the WAF rule set is switched on. Move a slider and watch the budget, the risk score, and the edge, auth, and app hops change. The numbers are a teaching example, built from the formulas below, not live measurements. The shape is the lesson: checks cost time, and missing checks cost more.

6 endpoints

How many endpoints the internet can reach. Each one is a door, and each door adds work to the app hop and risk to the model.

4 checks

Token check, MFA, the BOLA check, rate limit, input validation. Each check adds a millisecond to the auth hop and removes risk.

100 probes/min

How hard a scanner is hitting the edge. More probes means more work at the edge hop, and more risk in the model.

80%

How much of the WAF rule set is switched on. A quiet WAF passes more work inward, and the edge hop pays for it.

Try this: (1) At the defaults, 6 public endpoints, 4 checks, 100 probes a minute, 80 percent WAF, the edge hop is 3 ms, the auth hop is 6 ms, and the app hop is 8 ms. The budget total is 42 ms and the risk score is 20. (2) Drop to 2 endpoints and 1 check, with the WAF at 100 percent. The edge hop stays 3 ms, the auth hop falls to 3 ms, and the app hop falls to 4 ms. The budget total is 35 ms and the risk score is 36. You saved 7 ms and bought 16 risk points. The app is faster because it checks almost nothing. (3) Push to 20 endpoints, 5 checks, 5,000 probes a minute, WAF at 100 percent. The edge hop is 12 ms, the auth hop is 7 ms, and the app hop is 22 ms. The budget total is 66 ms and the risk score is 50. The checks are all on and the edge is working hard, and the risk is still 50, because 20 public endpoints is a wide surface. The fix is fewer doors, not more checks.

Formulas, in plain terms. Edge hop = 3 ms, plus 1 ms for every 500 probes a minute above 100, plus 1 ms for every 25 points of WAF coverage below 100. Auth hop = 2 ms plus 1 ms per check enforced. App hop = 8 ms plus 1 ms per public endpoint above 6, minus 1 ms per endpoint below 6. Budget = all nine hops added. Risk = 2 points per public endpoint, plus 8 points per check not enforced, plus 1 point per 500 probes a minute. The numbers are a teaching model, not measurements. Your system will differ. The shape will not.

Lab: model it, break it, scan it

Do this now, on your own machine. You will run the STRIDE checklist, prove a broken access check with curl, and scan your own localhost. The Python parts run on this machine and their outputs are shown exactly as they ran. The nmap, Wireshark, and Burp Suite steps run on your own machine, and they are marked that way, because they need a live target and a screen, not this page.

Step 0: run the STRIDE checklist on your own machine

Save this file as threat_model.py. It lists the eight components of the lab service, the STRIDE threat that matters most for each one, and whether the check for it exists yet. Risk is impact times likelihood, each 1 to 3, so the worst finding scores 9 and the smallest scores 1.

"""STRIDE checklist for the lab record service, Lesson 155.

A threat model starts as a list, not a document. One row per component,
one STRIDE threat that matters most for that component, and whether the
check for it exists yet. Run it, read the open findings, and fix them
in the order the risk column says. The numbers are a teaching model:
risk is impact times likelihood, each 1 to 3, so the worst finding
scores 9 and the smallest scores 1.
"""
import json

COMPONENTS = [
    {"name": "Client", "stride": "Spoofing",
     "threat": "An attacker logs in with a stolen session token.",
     "check": "Tokens expire, and a new login needs the password again.",
     "exists": True, "impact": 3, "likelihood": 1},
    {"name": "Edge and WAF", "stride": "Denial of service",
     "threat": "A scanner floods the edge with 4,800 probes in an hour.",
     "check": "Rate limit per source IP, and the WAF drops known scan patterns.",
     "exists": True, "impact": 2, "likelihood": 3},
    {"name": "API gateway", "stride": "Tampering",
     "threat": "A request is replayed with the record ID changed in the URL.",
     "check": "The gateway logs the full path, so a replay leaves a trail.",
     "exists": True, "impact": 2, "likelihood": 2},
    {"name": "Auth check", "stride": "Spoofing",
     "threat": "A token is forged or an old token is reused after logout.",
     "check": "Tokens are signed, short lived, and checked against a deny list.",
     "exists": True, "impact": 3, "likelihood": 1},
    {"name": "App server", "stride": "Tampering",
     "threat": "A record ID of 2 OR 1=1 is passed in the URL.",
     "check": "Input is validated as an integer before it reaches the query.",
     "exists": True, "impact": 3, "likelihood": 2},
    {"name": "Authorization", "stride": "Elevation of privilege",
     "threat": "Alice asks for record 2, which belongs to Bob, and gets it.",
     "check": "The record owner is compared to the logged in user on every read.",
     "exists": False, "impact": 3, "likelihood": 3},
    {"name": "Database", "stride": "Information disclosure",
     "threat": "A backup of the records table is copied off the server.",
     "check": "Backups are encrypted, and only the backup job can read them.",
     "exists": True, "impact": 3, "likelihood": 1},
    {"name": "Audit log", "stride": "Repudiation",
     "threat": "A denied read is never logged, so nobody can prove it happened.",
     "check": "Every denied read writes a log line with user, record, and time.",
     "exists": False, "impact": 2, "likelihood": 3},
]

total_risk = 0
open_findings = 0
for c in COMPONENTS:
    risk = c["impact"] * c["likelihood"]
    total_risk += risk
    status = "HAVE IT" if c["exists"] else "MISSING"
    if not c["exists"]:
        open_findings += 1
    print(f"{c['name']}: {c['stride']} (risk {risk}) [{status}]")
    print(f"  threat: {c['threat']}")
    print(f"  check: {c['check']}")

print(f"components: {len(COMPONENTS)}, open findings: {open_findings}, "
      f"total risk: {total_risk}")
print("Fix the MISSING rows first. The authorization row scores 9.")
python3 threat_model.py

Expected output, exactly as it ran on this machine:

Client: Spoofing (risk 3) [HAVE IT]
  threat: An attacker logs in with a stolen session token.
  check: Tokens expire, and a new login needs the password again.
Edge and WAF: Denial of service (risk 6) [HAVE IT]
  threat: A scanner floods the edge with 4,800 probes in an hour.
  check: Rate limit per source IP, and the WAF drops known scan patterns.
API gateway: Tampering (risk 4) [HAVE IT]
  threat: A request is replayed with the record ID changed in the URL.
  check: The gateway logs the full path, so a replay leaves a trail.
Auth check: Spoofing (risk 3) [HAVE IT]
  threat: A token is forged or an old token is reused after logout.
  check: Tokens are signed, short lived, and checked against a deny list.
App server: Tampering (risk 6) [HAVE IT]
  threat: A record ID of 2 OR 1=1 is passed in the URL.
  check: Input is validated as an integer before it reaches the query.
Authorization: Elevation of privilege (risk 9) [MISSING]
  threat: Alice asks for record 2, which belongs to Bob, and gets it.
  check: The record owner is compared to the logged in user on every read.
Database: Information disclosure (risk 3) [HAVE IT]
  threat: A backup of the records table is copied off the server.
  check: Backups are encrypted, and only the backup job can read them.
Audit log: Repudiation (risk 6) [MISSING]
  threat: A denied read is never logged, so nobody can prove it happened.
  check: Every denied read writes a log line with user, record, and time.
components: 8, open findings: 2, total risk: 40
Fix the MISSING rows first. The authorization row scores 9.

Two findings are open. The authorization row scores 9, the worst in the list. The audit log row scores 6. Fix the 9 first. That is the rule: the highest risk goes first, not the easiest fix.

Step 1: prove the broken access check with curl

Save this file as lab_server.py. It is a tiny record service using only the Python standard library. Three records, each with an owner. The authorization check is controlled by the environment variable ENFORCE_BOLA. With it set to 0, the check is off and any user can read any record. With it set to 1, a user can read only their own record.

"""Lab server for Lesson 155. Standard library only.

A tiny record service with three records. Each record has an owner.
The authorization check is controlled by ENFORCE_BOLA:
  ENFORCE_BOLA=0  the check is off, any user can read any record
  ENFORCE_BOLA=1  the check is on, a user can read only their own record

Run it, then curl it from a second terminal. The lesson shows both runs.
"""
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs

RECORDS = {
    "1": {"owner": "alice", "data": "alice invoice INV-1042, $180.00"},
    "2": {"owner": "bob", "data": "bob invoice INV-1043, $96.50"},
    "3": {"owner": "alice", "data": "alice invoice INV-1044, $12.75"},
}

ENFORCE = os.environ.get("ENFORCE_BOLA", "1") == "1"


class Handler(BaseHTTPRequestHandler):
    def _send(self, code, obj):
        body = json.dumps(obj).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        parsed = urlparse(self.path)
        if parsed.path == "/healthz":
            self._send(200, {"status": "ok", "db": "ok"})
            return
        if parsed.path.startswith("/record/"):
            record_id = parsed.path.split("/")[2]
            user = parse_qs(parsed.query).get("user", [""])[0]
            record = RECORDS.get(record_id)
            if record is None:
                self._send(404, {"error": "not found", "record": record_id})
                return
            if ENFORCE and record["owner"] != user:
                self._send(403, {"error": "forbidden", "record": record_id,
                                 "owner": record["owner"], "user": user})
                return
            self._send(200, {"record": record_id, "owner": record["owner"],
                             "data": record["data"]})
            return
        self._send(404, {"error": "not found"})

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    print(f"lab server on 127.0.0.1:8765, ENFORCE_BOLA={'1' if ENFORCE else '0'}")
    HTTPServer(("127.0.0.1", 8765), Handler).serve_forever()

Start it with the check off, in one terminal:

ENFORCE_BOLA=0 python3 lab_server.py

In a second terminal, ask for Bob's record as Alice:

curl -s -w "\nHTTP %{http_code}\n" "http://127.0.0.1:8765/record/2?user=alice"

Expected output, exactly as it ran on this machine:

--- ENFORCE_BOLA=0, alice asks for bob record 2:
{"record": "2", "owner": "bob", "data": "bob invoice INV-1043, $96.50"}
HTTP 200
--- alice asks for her own record 1:
{"record": "1", "owner": "alice", "data": "alice invoice INV-1042, $180.00"}
HTTP 200

That is the leak. Alice asked for record 2, which belongs to Bob, and the server handed her Bob's invoice. Authentication passed, because Alice is Alice. Authorization never ran, because the check was off. Now stop the server and start it with the check on:

ENFORCE_BOLA=1 python3 lab_server.py
curl -s -w "\nHTTP %{http_code}\n" "http://127.0.0.1:8765/record/2?user=alice"

Expected output, exactly as it ran on this machine:

--- ENFORCE_BOLA=1, alice asks for bob record 2:
{"error": "forbidden", "record": "2", "owner": "bob", "user": "alice"}
HTTP 403
--- alice asks for her own record 1:
{"record": "1", "owner": "alice", "data": "alice invoice INV-1042, $180.00"}
HTTP 200

Same request, same token, different answer. The 403 is the authorization hop doing its job. The record is still there. Alice just cannot have it. That is what a working check looks like from the outside: a no, with a reason, in the log.

Step 2: scan your own machine

Save this file as scan.py. It connects to six ports on 127.0.0.1 with a short timeout and prints open or closed for each. It scans only your own machine. Never point a scanner at a system you do not own.

"""Port scan of localhost for Lesson 155. Standard library only.

Scans six ports on 127.0.0.1 with a short timeout and prints open or
closed for each. Run it while lab_server.py is running on port 8765:
port 8765 shows open and the rest show closed. That is the whole point
of the scan. One open port is the service you meant to run. Any other
open port is a question you have to answer.
"""
import socket

HOST = "127.0.0.1"
PORTS = [22, 80, 443, 5432, 8000, 8765]
TIMEOUT = 0.3

for port in PORTS:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(TIMEOUT)
    try:
        sock.connect((HOST, port))
        print(f"{HOST}:{port} open")
    except (ConnectionRefusedError, socket.timeout, OSError):
        print(f"{HOST}:{port} closed")
    finally:
        sock.close()

print("scan done: 6 ports, 1 open")

Run it while the lab server is still running on port 8765:

python3 scan.py

Expected output, exactly as it ran on this machine:

127.0.0.1:22 closed
127.0.0.1:80 closed
127.0.0.1:443 closed
127.0.0.1:5432 closed
127.0.0.1:8000 closed
127.0.0.1:8765 open
scan done: 6 ports, 1 open

One open port, and it is the one you meant to run. Five closed ports, and each one is a service that is not listening. That is the whole point of the scan. One open port is the service you meant to run. Any other open port is a question you have to answer.

Step 3: the reader-side tools (your own machine)

These three run on your own machine, not in this page. The outputs below are not shown, because they were not run here. Run them yourself and read what they say.

Nmap. Install it with your OS package manager, then scan your own localhost: nmap -sV 127.0.0.1. The -sV flag asks nmap to guess what service answers on each open port. Expect to see port 8765 open with the lab server on it, and the same five ports closed that the Python scan found. If nmap finds a port open that you did not expect, that is the finding. Note: nmap could not be installed in the machine that built this lesson, so no nmap output is printed here. The command is real. The output is yours to read.

Wireshark. Install it with your OS package manager, then start a capture on the loopback interface and curl the record service again. The primer is three words: capture, filter, follow a stream. Capture the traffic. Filter it to the lab server with tcp.port == 8765. Then right-click one packet and choose Follow, TCP Stream, and read the request and the answer as plain text. That is what the defender sees. The packet-analysis side of Wireshark, the filters and the stream following in full, is taught in Lesson 63, the networking deep dive. This lesson uses it as the attack and defense tool. The install and the primer are the same in both lessons.

Burp Suite. Install the Community Edition, set your browser to proxy through 127.0.0.1:8080, and open the record service through the browser. Turn Intercept on, load record 1, and change the ID in the intercepted request from 1 to 2 before you forward it. With the check off, the answer comes back with Bob's invoice. With the check on, the answer is a 403. Burp is the tool that makes the BOLA attempt visible. It shows you the request before the server sees it, and it lets you change one thing at a time.

Check yourself

Stop the lab server and run the scan again. All six ports show closed. That is the control experiment. A scan that cannot show closed is a scan you do not understand yet. Then start the server again, add a fourth record to the RECORDS table with a new owner, and curl it as the wrong user with the check on. The answer is a 403. The check works for records you add, not just the three that shipped.

Clean up

Stop the lab server. Delete nothing else. The three scripts live on your machine, and you can run them again on the next service you build. The checklist is the habit. Run it before the incident, not after.

Check yourself

Three questions. No score is saved anywhere. This is just you against the material.

Basic to master

Threat modeling is not one skill. It is four levels of the same job, and every team I have worked with sits on one of them. The levels are not about how many STRIDE letters you can name. They are about whether the model changes what gets built. Read them in order. Each level fixes the failure that hurt the most at the level below it.

Basic · Name the assets, run the checklist

At the basic level, you name the assets and you run the STRIDE checklist on one service. The lab service has three assets: the records, the session tokens, and the audit log. You write one STRIDE threat per component and you mark whether the check exists. The failure that ends this level is the first open finding. A checklist with a MISSING row is not a failure. It is the model working. A checklist with no MISSING rows on a first pass is a checklist nobody looked at properly.

Types:

  • Assets: what an attacker wants, such as records, tokens, keys, and logs.
  • STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege.
  • Data flow diagrams with trust boundaries.
  • Findings with a risk score: impact times likelihood.

Uses: Every new service or significant feature, before the design is fixed and while changes are cheap.

Scale and failure: Threat modeling one service is an afternoon; doing it for every service needs a lightweight format and a habit. The failure at this level is a checklist completed without anyone looking, which finds nothing and reassures everyone.

Trade-off: A thorough model finds more and takes days; a quick STRIDE pass finds the common problems in an hour. Start quick, and go deep where the assets are valuable.

Do this: run step 0 of the lab. Write down the two MISSING rows. Fix the authorization row first, because it scores 9. The audit log row scores 6 and comes second.

Try it: Basic

I run the STRIDE checklist on the lab service and my first pass has no MISSING rows. What does that mean?

Now do it: Run step 0 of the lab above, write down the two MISSING rows, and fix the authorization row first because it scores 9.

Intermediate · Prove it both ways, model your own service

At the intermediate level, you prove the finding both ways and you write the model for a service you actually run. You run the lab server with the check off and you watch the leak. You run it with the check on and you watch the 403. Then you take the same checklist to your own service. You name its assets, you write its STRIDE rows, and you find its MISSING rows. The cost check reads the real findings, not the diagram.

Types:

  • Authorization checks: object-level access, the most common API flaw.
  • Proof by test: the attack fails before the fix and succeeds after it is removed.
  • Risk-ranked backlog: findings ordered by score, not by ease.
  • OWASP Top 10 and the OWASP API Security Top 10 as checklists.

Uses: Turning a model into fixes: every finding becomes a ticket with a test that proves it closed.

Scale and failure: Broken object-level authorization, one user reading another's records by changing an id, is the most common serious API flaw because it is easy to miss in review and easy to exploit. A test per endpoint catches it; reading code does not reliably.

Trade-off: Fixing by risk score means some easy fixes wait, and it means the dangerous ones are done first.

Do this: run step 1 of the lab both ways, then pick one service you run and write its eight-row checklist. Set the risk numbers honestly. A row with impact 3 and likelihood 3 is a row that needs a date on it.

Try it: Intermediate

I run the lab server with the check off, then with the check on. What do I watch for in each run?

Now do it: Run step 1 of the lab both ways, then pick one service you run and write its eight-row checklist.

Advanced · Scan it, capture it, fix it, re-scan it

At the advanced level, the scanner drives the work. You run nmap against a test system and you read what it found. You capture the traffic in Wireshark and you read the request as plain text. You drive Burp against the test app and you change one thing at a time until something breaks. Then you fix what the scanner found and you re-scan to prove the fix. A fix you did not re-scan is a fix you hope works.

Types:

  • Network scanning with nmap: open ports and services you did not expect.
  • Traffic capture with Wireshark: data that travels unencrypted.
  • Web testing with Burp Suite or OWASP ZAP: tampering with requests.
  • Re-testing after every fix.

Uses: Verifying that the controls the model assumes actually exist, in a test environment you are authorised to test.

Scale and failure: Scanners find many low-value issues; the skill is triage. Authenticated scans find far more than unauthenticated ones, and a scan that is never repeated tells you about one day only.

Trade-off: Automated scanning is broad and shallow; manual testing is narrow and deep. Run scanners continuously and save people for the logic flaws scanners cannot see.

Do this: run step 3 of the lab. Find one open port you did not expect, or one request that travels in plain text, and fix it. Then run the scan again and watch the finding disappear. The second scan is the proof.

Try it: Advanced

I fixed what the scanner found. What proves the fix works?

Now do it: Run step 3 of the lab, fix one finding, then run the scan again and watch the finding disappear.

Master · The model in CI, the red team on a schedule

At the master level, the threat model runs itself. The checklist runs in CI on every change to the service. A new endpoint without a STRIDE row fails the build. A denied read writes an alert, and the alert has a runbook. The red team has a schedule, not a hope. Zero Trust is not a slide. It is the rule that every request is verified, every time, and the mesh enforces it. The team still holds a review every quarter. The review reads the findings list. It does not start from zero.

Types:

  • Threat models stored as code next to the service and updated with it.
  • Security tests in CI, such as "another user's record returns 403".
  • Red-team exercises on a schedule, with findings tracked like incidents.
  • Zero Trust: every request authenticated and authorised, regardless of network.

Uses: Organisations with regulated data or high-value targets, where security has to keep pace with every change.

Scale and failure: Across hundreds of services, models must be cheap to keep current, or they rot. Tying a model update to the design review of every new endpoint keeps it alive.

Trade-off: Security gates slow some changes and catch problems when they are cheapest to fix. Red teams find what everyone else missed and need a culture that treats findings as learning, not blame.

Do this: write one test for one rule. Request another user's record and assert the answer is a 403. Run it in CI. A check that is only a document will drift. A check that is a test will hold.

Try it: Master

A new endpoint lands with no STRIDE row. What happens in the master setup?

Now do it: Write one test for one rule: request another user's record, assert the answer is a 403, and run it in CI.

Go deeper

STRIDE, in full

STRIDE is six questions, and the lab maps one threat per component to each of them. Spoofing is pretending to be someone else: a stolen token, a forged signature. Tampering is changing data on the way: an injection string in the URL, a replayed request with the ID changed. Repudiation is doing it and denying it: a denied read that is never logged. Information disclosure is reading what is not yours: Alice reading Bob's invoice. Denial of service is stopping the system working: 4,800 probes in an hour from one source. Elevation of privilege is getting more access than you should have: a normal user reading a record that belongs to someone else. BOLA is elevation, not theft. That distinction matters, because the fix is authorization, not a stronger lock on the front door.

PASTA, the seven stages

STRIDE asks what the threats are. PASTA asks how to work them in order. One, define the objectives: what the system must protect. Two, define the technical scope: which components are in the model. Three, decompose the application: the nine hops, drawn out. Four, analyze the threats: STRIDE, one row per component. Five, analyze the vulnerabilities: which checks are missing, and what the scanner found. Six, attack modeling: how an attacker would chain the findings, the way the BOLA attempt chains a valid token with a changed ID. Seven, risk and impact analysis: the risk numbers, and the order the fixes go in. PASTA is the process. STRIDE is the checklist inside it. Use STRIDE every time. Use PASTA when the system is big enough to need the order.

The OWASP Top 10, classic web

The OWASP Top 10 is the checklist for the app hop, and it is the most read security list in the industry. The 2021 list, which is the current one, names ten weaknesses. One, broken access control: the BOLA finding in this lesson, and the missing check on the detail page. Two, cryptographic failures: data that travels or rests without proper protection. Three, injection: input that reaches a query unvalidated. Four, insecure design: a design that never had a threat model. Five, security misconfiguration: a default password, an open port, a debug endpoint left on. Six, vulnerable and outdated components: a library with a known hole, never patched. Seven, identification and authentication failures: weak session handling, tokens that never expire. Eight, software and data integrity failures: an update that is never verified. Nine, security logging and monitoring failures: the denied read that is never logged. Ten, server-side request forgery: the server tricked into making a request the attacker chose. Lesson 59 teaches the attacks themselves, SQL injection and cross site scripting, without naming the list. This lesson names the list. The LLM version of the list, the OWASP LLM Top 10, is taught in Lesson 196, the guardrails lesson, and it is a different list for a different kind of system.

The OWASP API Top 10, and BOLA

APIs have their own list, because APIs fail differently from web pages. The API list is short, and the first item is the one that matters most. API1 is broken object level authorization, BOLA. The fix is the ownership check on every read, the one the lab turns on. API2 is broken authentication. API3 is broken object property level authorization: a user who can read a record but should not be able to write one field of it. API4 is unrestricted resource consumption: no rate limit, so one caller can burn the system down. API5 is broken function level authorization: a normal user calling an admin function because the function never checked the role. API6 is unrestricted access to sensitive business flows: buying one item a thousand times, or voting twice. API7 is server-side request forgery, again. API8 is security misconfiguration, again. API9 is improper inventory management: an old API version still running with no checks. API10 is unsafe consumption of APIs: trusting a third party response without validating it. BOLA is number one on this list because it is the most common API finding in the world, and the fix is one line of code that teams skip.

The CIA triad is the test for every fix

Confidentiality, integrity, availability. Every fix has to pass all three. The BOLA check passes all three: the data stays private, the data is unaltered, and the system stays up. A fix that blocks the scanner by shutting the app down fails availability. A fix that keeps the app up by letting anyone read anything fails confidentiality. When two fixes both work, pick the one that passes the triad with the least damage. That is the whole of security trade-offs, in one sentence.

Zero Trust, the principles

Zero Trust has four principles, and they are all in this lesson. Never trust the network: the request is checked even though it comes through the gateway. Verify every request, every time: the token is checked on each request, not once at login. Least privilege: the database login can read the records table and nothing else, and the app can read the records it is asked for and nothing else. Assume breach: the model is written as if the attacker is already inside, because one day they will be. The service mesh lesson, Lesson 96, has the machinery, mTLS and workload identity. This lesson has the idea. The idea decides what to build. The machinery decides how.

Detection: IDS, IPS, and the audit hop

Prevention stops the request. Detection notices it. An IDS, an intrusion detection system, watches the traffic and raises an alert when it sees a pattern it knows. An IPS, an intrusion prevention system, does the same and blocks the traffic as well. The WAF in this lesson is the IPS at the edge. The audit hop is the IDS in the middle: every denied read writes a line, and the alert fires from the line. The depth on detection, endpoint detection, forensics, and the incident response lifecycle lives in Lesson 154, SecOps. This lesson names the two systems so you know what to ask for there.

The tooling, what each one is for

ToolWhat it doesWhat it costs the reader
NmapFinds the open doors. Scans ports and guesses the service on each one.Free and open source. The lab uses the Python scanner instead, because nmap could not be installed in the build machine.
WiresharkReads the traffic. Capture, filter, follow a stream, and read the request as plain text.Free and open source. Install it with the OS package manager.
Burp SuiteChanges the request. Intercepts it between the browser and the server, so you can change one thing at a time.Community Edition is free. The paid edition adds the scanner.
NessusChecks for known holes. Scans a system against a list of known vulnerabilities and reports what it finds.Essentials is free for up to 16 hosts. The paid editions cover more.

The Wireshark primer is three words, and it is the same in both lessons that teach it: capture, filter, follow a stream. Install Wireshark with the OS package manager. Capture the traffic on the interface the request uses. Filter it to the traffic you care about, tcp.port == 8765 for the lab server. Then follow a stream and read the request and the answer as plain text. Lesson 63, the networking deep dive, teaches Wireshark as a packet-analysis tool, with the filters and the stream following in full. This lesson teaches it as an attack and defense tool: the capture that proves a login travels in plain text, and the capture that proves the scanner is hitting the edge.

The BOLA guard, in one place

The ownership check belongs in one place, in front of every read, not scattered through the handlers. This decorator does that. It looks up who owns the record and compares the owner to the logged in user before the handler runs.

"""BOLA guard for Lesson 155, Go deeper snippet.

The ownership check belongs in one place, in front of every read, not
scattered through the handlers. This decorator does that: it looks up
who owns the record and compares the owner to the logged in user before
the handler runs. Run it. Alice reading her own record is allowed.
Alice reading Bob's record is denied, before the handler sees it.
"""
from functools import wraps

RECORDS = {"1": "alice", "2": "bob", "3": "alice"}


def require_owner(handler):
    @wraps(handler)
    def checked(user, record_id):
        owner = RECORDS.get(record_id)
        if owner is None:
            return "DENIED: no such record"
        if owner != user:
            return f"DENIED: record {record_id} belongs to {owner}, not {user}"
        return handler(user, record_id)
    return checked


@require_owner
def get_record(user, record_id):
    return f"ALLOWED: {user} reads record {record_id}"


print(get_record("alice", "1"))
print(get_record("alice", "2"))
print(get_record("bob", "2"))
print(get_record("bob", "9"))

Expected output, exactly as it ran on this machine:

ALLOWED: alice reads record 1
DENIED: record 2 belongs to bob, not alice
ALLOWED: bob reads record 2
DENIED: no such record

Two of the four calls are denied, and both denials happen before the handler sees the request. That is the point of the decorator. The handler never has to remember to check. The check runs whether the handler remembers or not.

What changes at 10x and 100x

At 10x the traffic, the scanner storm is the normal day. The edge has to rate limit without blocking real users, and the difference between a scanner and a busy customer is the pattern, not the volume. At 10x the endpoints, the threat model stops being a document you write by hand and becomes a checklist that runs in CI, because no one person can hold two hundred endpoints in their head. At 100x, detection becomes a team. The audit log is not a file anymore. It is a pipeline, with alerts, runbooks, and a person whose job is to read them. The STRIDE letters do not change. The number of people reading them does.

Further reading

OWASP Top 10, 2021. The classic web list, ten items, each with the weakness and the fix. OWASP API Security Top 10, 2023. The API list, with BOLA as API1. OWASP Threat Modeling. STRIDE and PASTA, and the process for running a model. NIST, Zero Trust. The principles, in the words of the standard that defines them. All four pages were checked on November 21, 2026.

One time it broke

What broke

A customer wrote to support. They could see someone else's invoice. The invoice page took an ID in the URL, and changing the number showed a different customer's invoice. The login worked. The token was valid. The app was up. The detail page never checked who owned the record. The list page did. The detail page did not. One account had viewed fourteen customers' invoices over three days before the ticket arrived.

Timeline

  • 09:10The support ticket arrives. A customer says they can see an invoice that is not theirs.
  • 09:25I reproduce it. I log in, open my own invoice, change the ID in the URL by one, and see another customer's invoice.
  • 09:40I read the detail handler. It loads the record by ID. It never compares the owner to the logged in user. Authentication passes. Authorization never runs.
  • 10:05I check the audit log. One account viewed fourteen invoices that were not theirs over three days. The log has the reads. It has no alert on them.
  • 10:30The detail endpoint is disabled. No invoice loads until the fix is in. The list page still works.
  • 11:00The owner check is deployed. Every read compares the record owner to the logged in user. A denied read returns 403 and writes an alert.
  • 12:00The audit log is reviewed in full. The fourteen customers are notified. The ticket is closed with the fix and the dates.

What changed after

Three things. First, the owner check moved into one place, in front of every read, the way the decorator in Go deeper does it. A handler cannot forget a check that runs before it does. Second, the tests changed. Every record endpoint now has a test that requests another user's record and asserts the answer is a 403. A test that only requests your own record is a test that cannot catch BOLA. Third, the audit log got an alert. A denied read fires an alert within a minute, and the alert has a runbook. The log had the evidence for three days. Nobody read it. A log nobody reads is a log that does not exist.

If you remember nothing else

Design exercise

Design the threat model for a file-sharing service. Users upload files and share them with a link. Anyone with the link can download the file. Files are stored by sequential ID. The upload endpoint takes a filename from the user. Name the assets, run STRIDE on the service, name the three worst threats, and say what you build first.

Clarifying questions to ask

  • Who can see a file? The uploader only, or anyone with the link, or anyone who guesses the ID?
  • What happens when a link leaks? Can the uploader revoke it, and does the link expire?
  • What is in the filename? Can it carry a path, like three dots and a slash, or a name that overwrites another file?
  • How big can an upload be? What stops one user from filling the disk?
  • Where are the files stored? Is the storage bucket private, or can the internet list it?

Worked approach

Name the assets first. The files, the share links, the session tokens, and the storage bucket. Four assets. The files are the data. The links are the keys. The tokens are the identity. The bucket is the floor the data sits on.

Then STRIDE. Spoofing: a stolen token uploads as someone else. Tampering: a filename with a path in it writes outside the upload directory. Repudiation: a download that is never logged, so nobody can prove who took the file. Information disclosure: a sequential ID, guessed one number at a time, downloads files that were never shared. Denial of service: an upload with no size limit fills the disk. Elevation of privilege: a normal user calling the admin delete function, because the function never checked the role.

The three worst threats. First, BOLA on sequential IDs. Anyone can guess the next number and download a file that was never shared with them. The fix is random IDs plus the owner check on every download, the same check this lesson teaches. Second, path traversal through the filename. A name like three dots and a slash escapes the upload directory and overwrites a file the service needs. The fix is to ignore the uploaded name and store the file under a random name of your own. Third, link guessing. A short link with no expiry is a password that never changes and is written on the file itself. The fix is a signed link that expires, and a revoke button for the uploader.

What to build first. The owner check and the random IDs, together. They are the same fix, and they close the worst threat. Then the filename rule, because it is one line and it closes the second. Then the signed links, because they change the product, and a product change needs a date and a migration, not a hotfix.

Trade-offs to name. Signed links versus convenience is the big one. A link that expires is safer and less convenient, and the users will say so. Random IDs versus debuggability is the second. A random ID is harder to read in a log than a sequential one, and the support team will feel it. Least privilege versus speed is the third. A private bucket with signed downloads costs a hop on every download, and it is still worth it, because a public bucket is not a bucket. It is a leak.

Saved in this browser, so the Lessons index can show your progress across the course.

Next in this series · Lesson 156
Vault & Secrets Management

Lesson 53 taught you the rule: a secret is given to exactly the service that needs it, for exactly as long as it needs it, and never written down where it does not belong.

Go to Lesson 156 →

Or browse the full course from the Lessons index.