Attack Trees for Defenders: Model “Steal the Payment Data” Before the Attackers Do

Attack Trees for Defenders: Model “Steal the Payment Data” Before the Attackers Do

📋 Key Takeaways
  • Attack trees were introduced by Bruce Schneier in 1999 and remain one of the simplest, most underused threat-modeling tools on the defensive side.
  • You'll need Python 3 on your own machine.
  • Create tree.yaml. The root goal splits into four OR branches: compromise the client, compromise the server, compromise the transport, or compromise the backend storage.
  • Take the top five leaves and map each one to an existing control or detection.
10 min read · 1,833 words
Educational & Ethical Use Only — This article is provided for educational and ethical cybersecurity research purposes only. The techniques described should only be used on systems you own or have explicit permission to test. Always follow responsible disclosure and the laws applicable to you. Mitigations are included so engineers can harden real systems.
Concept flowThe Attack Tree Modeling Flow
  1. 🎯Root GoalDefine the adversary's single objective: steal payment data at c
  2. 🌳OR / AND BranchesDecompose into client, server, transport, storage attack paths
  3. 🍃Scored LeavesAttach cost and detectability to every concrete attacker action
  4. 🐍Risk RankingPython script computes risk; cheapest, quietest paths rise to th
  5. 🛡️Sigma ControlsMap each high-risk leaf to a detection or preventive hardening c

Think like an attacker, then fix the cheapest, quietest paths before someone else finds them.

Security

🔎 Last updated · Editorial policy · Report an error

TL;DR: Attack trees let defenders think like attackers: you decompose a single adversary goal — here, “steal payment data at checkout” — into concrete sub-goals connected by OR and AND gates, then score the leaves so the cheapest, least-detectable paths rise to the top. In this lab you’ll build the tree in a YAML file, compute the riskiest paths with a short Python script, and map each high-risk leaf to a Sigma detection or a preventive control, producing a prioritized hardening list you can defend to management.

Authorization note: Everything in this tutorial is analysis work — modeling, scripting, and writing detections — performed on your own lab machine against your own synthetic data. We do not attack any system, ours or anyone else’s. Attack-tree modeling is purely defensive: it’s how you enumerate what an attacker could do so you can close the gaps first. Still, never point any tooling at infrastructure you don’t own or have written permission to test.

Why Defenders Should Build Attack Trees

Attack trees were introduced by Bruce Schneier in 1999 and remain one of the simplest, most underused threat-modeling tools on the defensive side. The root node is the attacker’s goal. Children are ways to achieve that goal (OR gates — any one suffices) or required steps (AND gates — all must succeed). Leaf nodes are the concrete actions, and once you attach attributes like cost (how hard/expensive for the attacker) and detectability (how likely you notice), the tree stops being a diagram and becomes a prioritization engine.

The key insight: attackers behave like rational cost-minimizers. They probe for the cheapest quiet path. If your tree shows that “scrape payment fields via a malicious browser extension” costs $200 and is nearly invisible to your monitoring, that’s your next project — regardless of what a compliance checklist says.

Lab Setup

You’ll need Python 3 on your own machine. Create a working directory:

mkdir attack-tree-lab && cd attack-tree-lab
python3 --version
# Python 3.11.4
pip install pyyaml

We’ll store the tree as YAML so it’s diffable in git and reviewable by non-engineers. The scoring model is deliberately simple: each leaf gets cost (attacker effort, 1 = trivial to 10 = infeasible) and detectability (1 = silently achievable to 10 = you’ll definitely notice). A leaf’s risk score is (11 - cost) + (11 - detectability); the highest scores are the leaves you fix first.

Building the Tree: “Steal Payment Data at Checkout”

Create tree.yaml. The root goal splits into four OR branches: compromise the client, compromise the server, compromise the transport, or compromise the backend storage.

goal: Steal payment data at checkout
children:
  - gate: OR
    name: Compromise the client
    children:
      - gate: OR
        name: Inject skimming script (Magecart-style)
        children:
          - leaf: Exploit vulnerable 3rd-party JS dependency on checkout page
            cost: 3
            detectability: 4
          - leaf: Compromise S3 bucket / CDN serving checkout JS
            cost: 4
            detectability: 5
          - leaf: Hijack analytics/marketing tag via misconfigured tag manager
            cost: 2
            detectability: 3
      - gate: OR
        name: Malicious browser extension reads form fields
        children:
          - leaf: Publish trojanized extension to official web store
            cost: 3
            detectability: 9
  - gate: OR
    name: Compromise the server
    children:
      - gate: AND
        name: Exfiltrate from web application memory
        children:
          - leaf: Exploit RCE / deserialization flaw in checkout service
            cost: 5
            detectability: 6
          - leaf: Dump process memory to harvest card data pre-tokenization
            cost: 6
            detectability: 7
      - gate: OR
        name: Abuse legitimate access
        children:
          - leaf: Phish developer with prod checkout-service access
            cost: 2
            detectability: 3
          - leaf: Abuse over-permissive service account / over-scoped token
            cost: 3
            detectability: 4
  - gate: OR
    name: Compromise the transport
    children:
      - leaf: Downgrade TLS / strip HSTS on victim network
        cost: 6
        detectability: 6
      - leaf: Terminate TLS at compromised middlebox / corporate proxy
        cost: 5
        detectability: 7
  - gate: OR
    name: Compromise backend storage
    children:
      - leaf: Dump tokenized PAN vault via stolen cloud credentials
        cost: 4
        detectability: 5
      - leaf: Read payment logs that accidentally contain full PANs
        cost: 2
        detectability: 4

Notice the structure doing real work: the “exfiltrate from memory” branch is an AND gate — an attacker needs both the RCE and the memory dump, so its difficulty compounds. Everything else is OR: any single leaf is enough. The scariest leaves on paper are the low-cost, low-detectability ones like the tag-manager abuse and the PANs-in-logs issue.

Scoring the Tree with a Script

Create score.py:

import yaml, sys

WORST = 11  # scores are 1..10, so (11 - x) gives "badness"

def risk(node):
    """Risk of a node: leaves get a score; gates aggregate children."""
    if "leaf" in node:
        return (WORST - node["cost"]) + (WORST - node["detectability"])
    child_risks = [risk(c) for c in node["children"]]
    if node["gate"] == "OR":
        return max(child_risks)      # attacker picks the easiest child
    return sum(child_risks)          # AND: all steps required

def leaves(node, path=()):
    if "leaf" in node:
        yield path + (node["leaf"],), node, risk(node)
    for c in node.get("children", []):
        yield from leaves(c, path + (node.get("name", "GOAL"),))

tree = yaml.safe_load(open(sys.argv[1]))
rows = sorted(leaves(tree), key=lambda x: -x[2])
print(f"{'RISK':>5}  {'COST':>4}  {'DET':>3}  PATH")
print("-" * 100)
for path, leaf, r in rows:
    print(f"{r:>5}  {leaf['cost']:>4}  {leaf['detectability']:>3}  {' > '.join(path)} > {leaf['leaf']}")

Run it:

python3 score.py tree.yaml

Expected output:

 RISK  COST  DET  PATH
----------------------------------------------------------------------------------------------------
   16     2    3  GOAL > Compromise the client > Inject skimming script (Magecart-style) > Hijack analytics/marketing tag via misconfigured tag manager
   15     2    4  GOAL > Compromise backend storage > Read payment logs that accidentally contain full PANs
   15     2    3  GOAL > Compromise the server > Abuse legitimate access > Phish developer with prod checkout-service access
   14     3    4  GOAL > Compromise the server > Abuse legitimate access > Abuse over-permissive service account / over-scoped token
   13     3    4  GOAL > Compromise the client > Inject skimming script (Magecart-style) > Exploit vulnerable 3rd-party JS dependency on checkout page
   11     4    5  GOAL > Compromise backend storage > Dump tokenized PAN vault via stolen cloud credentials
   ...

The script sorts every leaf globally by risk, regardless of branch. That’s your backlog order. Note the AND-gated memory-dump path doesn’t even appear at the top even though its leaves score moderately — the aggregation correctly penalizes paths requiring multiple steps.

Turning Scores into a Prioritized Control List

Take the top five leaves and map each one to an existing control or detection. Be honest about what you actually have — a control you “have on paper” scores differently from one you’ve tested. A simple mapping table in markdown or a spreadsheet is enough:

# Leaf (attack path) Risk Existing control? Detection? Action
1 Hijack tag via misconfigured tag manager 16 Tag manager locked to allowlist? Untested None Lock container publish rights; CSP with nonces; monitor script hashes
2 Full PANs in payment logs 15 Tokenization at edge — but logging unreviewed None Log-scrubbing filter; scan logs with PAN regex + Luhn check
3 Phish developer with prod access 15 MFA on prod — SMS-based Impossible-travel alert only FIDO2 hardware keys for prod roles; JIT access elevation
4 Over-scoped service-account token 14 Partial — annual access review only None Scope tokens to read-only; short TTL; alert on anomalous vault reads
5 Vulnerable 3rd-party JS dependency 13 SBOM for backend only None Subresource Integrity (SRI) hashes; CSP; frontend dependency SBOM

The last column is your prioritized control list. Notice what’s absent from the top five: exotic 0-days and TLS attacks. The cheapest attacker paths are almost always identity, configuration, and data-hygiene problems.

Mapping High-Risk Leaves to Sigma Detections

For each high-risk leaf, ask: “If this happened tomorrow, would anything fire?” Write the Sigma rule even if you can only detect the noisy precursor. Here’s one for leaf #4, anomalous token-vault access:

title: Anomalous Payment Vault Read by Service Account
id: 7c1f4e2a-9b3d-4e88-a6f1-2d5c0b8e4a11
status: experimental
description: Detects a service account reading the tokenized PAN vault
  outside its normal access window — possible stolen-credential abuse.
logsource:
  product: cloud
  service: cloudtrail
detection:
  selection:
    eventSource: secretsmanager.amazonaws.com
    eventName: GetSecretValue
    resourceName|contains: 'payment-vault'
  filter_known:
    userAccountId|endswith: '-vault-sync-svc'
  timeframe: 5m
  condition: selection and not filter_known | count() by userIdentity.arn > 3
tags:
  - attack.t1555        # Credentials from Password Stores
  - attack.t1530        # Data from Cloud Storage Object
  - attack.credential_access
level: high

And one for leaf #1’s precursor — an unexpected script source appearing on checkout:

title: New Third-Party Script Source on Checkout Page
id: 3e9a02cc-4f71-4b2e-9d50-8a1c6f7b3d22
status: experimental
description: Alert on any script origin not in the approved allowlist,
  catching tag-manager abuse and compromised CDN dependencies.
logsource:
  category: proxy
detection:
  selection:
    csHost|endswith: '.example-checkout.com'
    destHost|contains: 'js'
  filter_allowlist:
    destHost|endswith:
      - 'cdn.jsdelivr.net'
      - 'js.stripe.com'
  condition: selection and not filter_allowlist
falsepositives:
  - Approved marketing tags not yet in allowlist
tags:
  - attack.t1189        # Drive-by Compromise
  - attack.t1195.002    # Supply Chain Compromise: Compromise Software
level: high

Validate the YAML parses before committing:

python3 -c "import yaml; yaml.safe_load(open('pan-vault-access.yml')); print('OK')"
# OK

Then convert to your SIEM’s query language with sigmac:

pip install sigma-cli
sigma convert -t splunk pan-vault-access.yml
# index=cloud_trail eventSource="secretsmanager.amazonaws.com" ...

For leaves that prevention handles better than detection — like the PANs-in-logs issue — write a verification command instead. Scan a rotated log file for card numbers (run this only against your own lab logs):

grep -rEo 'b[0-9]{13,16}b' app.log 
  | while IFS=: read -r line num; do
      # Luhn check to cut false positives
      sum=0; rev=$(echo "$num" | rev)
      for i in $(seq 0 $((${#rev}-1))); do
        d=${rev:$i:1}
        if [ $((i % 2)) -eq 1 ]; then d=$((d*2)); [ $d -gt 9 ] && d=$((d-9)); fi
        sum=$((sum+d))
      done
      [ $((sum % 10)) -eq 0 ] && echo "PAN in log: $line"
    done
# PAN in log: app.log:4721  (then: fix the logger, rotate the log store)

Exercise: Extend the Tree Yourself

Scale the exercise by adding a branch. Some prompts:

  1. Add an insider-threat branch: “Abuse employee console access to read one card at a time from the support tool.” Score it. Where does it land?
  2. Add a mobile-checkout branch with a malicious SDK dependency leaf. Does it outrank the web paths?
  3. Add a detectability attribute to gates and see how a well-instrumented AND path changes the aggregate.

Keep the tree in version control. When a real incident happens in your industry, add the attacker’s actual path as a new leaf and re-score — over time the tree becomes an organizational memory of what adversaries actually try, not just what you imagined.

Defender Takeaways

  • Attack the cheapest paths first, not the scariest ones. Scoring leaves by attacker cost and detectability consistently surfaces identity abuse, misconfigured third-party scripts, and data leakage into logs — fix those before chasing APT fantasies.
  • Every high-risk leaf needs either a working detection or a tested control — never “we have MFA” on paper. Map each top-scoring leaf to a Sigma rule you’ve actually fired in a test, or a preventive control you’ve actually verified (SRI hashes, log scrubbing, scoped short-TTL tokens).
  • Keep the tree alive in version control. Re-score after incidents, architecture changes, and new control rollouts; the delta between old and new scores is your measurable risk reduction, and it’s the artifact that justifies the security budget.
HMMNM Security
Published by HMMNM Security

Hands-on cybersecurity tutorials, CVE breakdowns, and guided learning paths — written and lab-tested by the HMMNM Security team.

Keep going — the structured way
This post is one step. The learning paths chain the next ones for you, with progress tracking and no account needed.
Follow a learning path →

Check your understanding

1. How does an AND gate differ from an OR gate in an attack tree?

2. According to the risk formula, which leaves should be fixed first?

3. What assumption about attackers underlies scoring leaves by cost and detectability?

4. Why is the attack tree stored as a YAML file rather than a diagram?

Your answers stay in this browser only.

Prabhu Kalyan Samal

Application Security Consultant and founder of Hmmnm. Certified Red Team Operator, Burp Suite Certified Practitioner, eWPTX, CompTIA SecurityX and Azure Security Engineer. Writes hands-on labs and threat analysis on web, cloud and AI-agent security.