Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 2

Attack Trees for the Threats That Matter

Expand one high-impact BookSwap threat into an attack tree with AND and OR nodes, score it with a short script, and use the results to see which control removes a whole attack path, which only raises the cost, and which only looks like it helps.

Contentsand lesson path

What you will learn

  • Enumerate threats with STRIDE per element and expand the highest-impact ones into attack trees.

01. The problem

A STRIDE pass on BookSwap's loans pages produced one threat everyone agreed was serious: a member can read another member's loan history. Loan history is personal data; it can reveal health conditions, religion or politics through the books people borrow. The team has time for one or two fixes this sprint and wants to know which control buys the most.

A one-line threat cannot answer that, because there are several ways to reach the same goal and they need different fixes. An attack tree breaks the goal down. Bruce Schneier described the idea in 1999: the attacker's goal is the root, the ways to reach it are child nodes, and you keep breaking nodes down until you reach concrete steps, the leaves.

In this worked example you will write the tree as data, score it with a short Python script, and test four candidate controls. You need Python 3.10 or later and a folder called tree-lab.

02. Step 1: Decide how nodes combine

Every inner node is one of two kinds:

  • An OR node offers alternatives: the attacker needs only one child to succeed. "Get the data from storage" is an OR node, because downloading a leaked backup or bribing a support agent both work.
  • An AND node lists steps that must all succeed. "Abuse the loans API" needs both a victim's member id and an API that returns loans for any id it is given.

To compare paths, give each leaf a value. Here it is a rough estimate of attacker effort in days for a moderately skilled outsider. Other trees use money, required skill or chance of detection. The values then roll up the tree, in the way Schneier's paper describes for costs: an OR node is worth its cheapest child, because the attacker picks the easiest option, and an AND node is worth the sum of its children, because the attacker must do all of them. A blocked leaf (one a control makes impossible) is worth infinity.

Estimates are rough, and that is fine. The tree is for comparing options, not for predicting exact numbers. If two people disagree whether a leaf costs one day or three, the disagreement itself is worth discussing.

03. Step 2: Write the tree

The tree has three branches under the root. The second branch is the interesting one: a stored cross-site scripting (XSS) bug, where a script saved in a cover caption runs in other members' browsers. Once it runs, the attacker can either read the session cookie or simply call the loans API from the victim's own page, using the victim's session. Each leaf carries the name of the control that would block it, or None if no planned control does. Save this as tree-lab/tree.py.

Python · tree-lab/tree.py
"""Score an attack tree: OR takes the cheapest child, AND adds its children."""
import sys

INF = float("inf")
TREE = ("OR", "Read another member's loan history", [
    ("AND", "Abuse the loans API", [
        ("leaf", "Learn the victim's member id", 1, "ids"),
        ("leaf", "API returns loans for any member id", 1, "owner-check"),
    ]),
    ("AND", "Act as the victim through stored XSS", [
        ("leaf", "Make a stored caption run as script", 3, "escaping"),
        ("OR", "Use the victim's session", [
            ("leaf", "Read the session cookie from script", 1, "httponly"),
            ("leaf", "Call the loans API from the victim's page", 2, None),
        ]),
    ]),
    ("OR", "Get the data from storage", [
        ("leaf", "Find and download a public DB backup", 6, "backup-acl"),
        ("leaf", "Bribe a support agent for an export", 8, None),
    ]),
])


def cost(node, blocked):
    if node[0] == "leaf":
        return INF if node[3] in blocked else node[2]
    costs = [cost(child, blocked) for child in node[2]]
    return min(costs) if node[0] == "OR" else sum(costs)


def show(node, blocked, depth=0):
    c = cost(node, blocked)
    label = "blocked" if c == INF else f"{c:g} day{'' if c == 1 else 's'}"
    kind = "" if node[0] == "leaf" else f"[{node[0]}] "
    print(f"{'  ' * depth}{kind}{node[1]}: {label}")
    for child in node[2] if node[0] != "leaf" else []:
        show(child, blocked, depth + 1)


def cheapest(node, blocked):
    if node[0] == "leaf":
        return [node[1]]
    if node[0] == "AND":
        return [step for child in node[2] for step in cheapest(child, blocked)]
    return cheapest(min(node[2], key=lambda child: cost(child, blocked)), blocked)


if __name__ == "__main__":
    blocked = set(sys.argv[1:])
    print("Mitigations:", ", ".join(sorted(blocked)) or "none")
    show(TREE, blocked)
    if cost(TREE, blocked) < INF:
        print("Cheapest path:")
        for step in cheapest(TREE, blocked):
            print(f"  - {step}")

04. Step 3: Score the tree with no controls

Terminal
python3 tree.py
Expected output
Mitigations: none
[OR] Read another member's loan history: 2 days
  [AND] Abuse the loans API: 2 days
    Learn the victim's member id: 1 day
    API returns loans for any member id: 1 day
  [AND] Act as the victim through stored XSS: 4 days
    Make a stored caption run as script: 3 days
    [OR] Use the victim's session: 1 day
      Read the session cookie from script: 1 day
      Call the loans API from the victim's page: 2 days
  [OR] Get the data from storage: 6 days
    Find and download a public DB backup: 6 days
    Bribe a support agent for an export: 8 days
Cheapest path:
  - Learn the victim's member id
  - API returns loans for any member id

The cheapest attack costs two days: find a member id, which BookSwap shows in profile URLs, and ask the API for that member's loans. This is an insecure direct object reference (IDOR): the API trusts an id from the request instead of checking that the record belongs to the caller. It is the path to close first.

05. Step 4: Try controls one at a time

Pass control names to the script to block their leaves. Start with an ownership check in the API: the loans query filters by the signed-in member, not by a value from the request.

Terminal
python3 tree.py owner-check
Expected output
Mitigations: owner-check
[OR] Read another member's loan history: 4 days
  [AND] Abuse the loans API: blocked
    Learn the victim's member id: 1 day
    API returns loans for any member id: blocked
  [AND] Act as the victim through stored XSS: 4 days
    Make a stored caption run as script: 3 days
    [OR] Use the victim's session: 1 day
      Read the session cookie from script: 1 day
      Call the loans API from the victim's page: 2 days
  [OR] Get the data from storage: 6 days
    Find and download a public DB backup: 6 days
    Bribe a support agent for an export: 8 days
Cheapest path:
  - Make a stored caption run as script
  - Read the session cookie from script

Blocking one leaf of the AND node blocks the whole branch: the attacker still knows member ids, but they are useless. The cheapest attack is now the XSS branch at four days. A common first idea is to set the HttpOnly flag on the session cookie, which stops scripts from reading it. Try it.

Terminal
python3 tree.py owner-check httponly
Expected output
Mitigations: httponly, owner-check
[OR] Read another member's loan history: 5 days
  [AND] Abuse the loans API: blocked
    Learn the victim's member id: 1 day
    API returns loans for any member id: blocked
  [AND] Act as the victim through stored XSS: 5 days
    Make a stored caption run as script: 3 days
    [OR] Use the victim's session: 2 days
      Read the session cookie from script: blocked
      Call the loans API from the victim's page: 2 days
  [OR] Get the data from storage: 6 days
    Find and download a public DB backup: 6 days
    Bribe a support agent for an export: 8 days
Cheapest path:
  - Make a stored caption run as script
  - Call the loans API from the victim's page

The root only moves from four to five days. HttpOnly blocks one child of an OR node, so the attacker switches to the other child: the injected script makes API calls from the victim's page, and the browser attaches the cookie anyway. HttpOnly is still worth having, but it does not fix XSS. Now block the leaf that every XSS path shares: getting the stored caption to run as script in the reader's browser, which context-aware output escaping prevents. Escaping does not stop anyone saving the text; it makes the browser show it as text instead of running it.

Terminal
python3 tree.py owner-check escaping
Expected output
Mitigations: escaping, owner-check
[OR] Read another member's loan history: 6 days
  [AND] Abuse the loans API: blocked
    Learn the victim's member id: 1 day
    API returns loans for any member id: blocked
  [AND] Act as the victim through stored XSS: blocked
    Make a stored caption run as script: blocked
    [OR] Use the victim's session: 1 day
      Read the session cookie from script: 1 day
      Call the loans API from the victim's page: 2 days
  [OR] Get the data from storage: 6 days
    Find and download a public DB backup: 6 days
    Bribe a support agent for an export: 8 days
Cheapest path:
  - Find and download a public DB backup

With two controls, both cheap paths are gone and the cheapest attack is a six-day hunt for a public database backup. That is the general pattern: a control on a leaf directly under an AND node removes the whole branch, while a control on one child of an OR node only pushes the attacker to the next child.

06. Step 5: Spot a control that only looks good

Someone suggests replacing numeric member ids with random ones instead of adding the ownership check. The script seems to agree:

Terminal
python3 tree.py ids | head -2
Expected output
Mitigations: ids
[OR] Read another member's loan history: 4 days

The root moves to four days, the same as with the ownership check, but the model is now wrong. Random ids are harder to guess, yet they still leak: in shared links, browser history, logs and referrer headers. The OWASP IDOR Prevention Cheat Sheet recommends random identifiers only as defence in depth and says access control checks are still essential. In the tree, random ids should raise the cost of the "learn the id" leaf, not block it. A tree is only as honest as the values on its leaves, so challenge every "blocked".

07. Check your understanding

Practice check · 3 questions

Reading attack trees

Use tree.py from this lesson.

Q1. You run `python3 tree.py httponly` with no other control. What does the root line show?
Q2. With no other controls, the team makes the database backup private (`backup-acl`). What happens to "Get the data from storage"?
Q3. Both `owner-check` and `ids` move the root from 2 to 4 days in tree.py. Why does the lesson still recommend the ownership check?
Practice only: not graded, not saved, not evidence.

08. Apply it

For the skill project, pick the threat you rated most serious in the payment flow, for example "an attacker marks an unpaid order as paid". Write its attack tree in the same format as tree.py, with at least one AND node and one non-technical leaf. Run it with no controls and with each candidate control, and write down which single control raises the cheapest attack the most and why.

09. Review prompt

From memory, explain how OR and AND nodes combine leaf costs, and why blocking a leaf under an AND node can remove a whole branch while blocking one under an OR node often does not. Then give one example of a control that only raises a leaf's cost.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check