AI Threat Modeling and Supply Chain Security

Updated · 8 min read
hardPython 3.13aisecuritythreat-modelingsupply-chainsafetensorsred-teaming

Threat modeling is a structured way to find security problems before attackers do. You draw how data flows through the system, mark each trust boundary (where data passes from something you don't control to something you do), list what could go wrong at each one, and decide on a control and a test for every threat. Supply chain security covers the parts you didn't build: models, datasets and packages, which can be tampered with before they ever reach you.

"Threats to AI Applications" listed the risks. This lesson turns them into a plan for a specific system.

The Steps

StepDescription
1. Draw the systemIt is used to show users, app, retrieval, model, tools, logs and suppliers, and the data between them
2. Mark trust boundariesEvery place untrusted input enters: users, documents, web pages, tool results, downloads
3. List threatsFor each boundary: injection, leakage, abuse, tampering, overload
4. Score riskIt is used to rank threats by likelihood × impact
5. Choose controlsPrevent, detect and limit damage; never rely on the system prompt alone
6. Write testsIt is used to prove each control works, and to rerun after every change (red-team regression tests)

Example: A Threat Model for Campus Helper

Every boundary gets a threat, a control and a test
Python
# A threat model for Campus Helper: what crosses each trust boundary, what could go wrong, and the control.
# Likelihood and impact are scored 1 (low) to 3 (high) by the team; risk = likelihood x impact.
THREATS = [
    # (boundary, threat, likelihood, impact, control, test)
    ("parent -> app", "direct prompt injection", 3, 2, "input screening + output check", "attack set in CI"),
    ("documents -> model", "uploaded document with hidden instructions", 2, 3, "screen documents; treat as data", "poisoned-document test"),
    ("app -> retrieval", "one family sees another's records", 2, 3, "permission filter before search", "cross-user access test"),
    ("model -> tools", "agent sends messages or refunds", 1, 3, "allowlist, approval, budgets", "tool-abuse test"),
    ("app -> logs", "personal data and secrets in logs", 2, 2, "redact before logging; 90-day retention", "log scan for emails and cards"),
    ("internet -> app", "oversized or flood requests (cost attack)", 2, 2, "size limits, rate limits, cost alert", "load test with limits"),
    ("supplier -> app", "tampered model or package", 1, 3, "safetensors, pinned versions, hash checks", "verify hashes on deploy"),
    ("app -> parent", "model output with HTML or script", 1, 2, "escape all output", "XSS test strings"),
]
print(f"{'risk':>4}  {'boundary':20} {'threat':44} control")
for b, t, l, i, c, test in sorted(THREATS, key=lambda x: -x[2] * x[3]):
    print(f"{l * i:4}  {b:20} {t:44} {c}")
print(f"\n{len(THREATS)} threats; every one has a control and a test. Highest risk first.")
Output
risk  boundary             threat                                       control
   6  parent -> app        direct prompt injection                      input screening + output check
   6  documents -> model   uploaded document with hidden instructions   screen documents; treat as data
   6  app -> retrieval     one family sees another's records            permission filter before search
   4  app -> logs          personal data and secrets in logs            redact before logging; 90-day retention
   4  internet -> app      oversized or flood requests (cost attack)    size limits, rate limits, cost alert
   3  model -> tools       agent sends messages or refunds              allowlist, approval, budgets
   3  supplier -> app      tampered model or package                    safetensors, pinned versions, hash checks
   2  app -> parent        model output with HTML or script             escape all output
 
8 threats; every one has a control and a test. Highest risk first.

Explanation:

  • Each row is a trust boundary, written as "from -> to": untrusted data crosses it, so something can go wrong there.
  • Risk = likelihood × impact, each scored 1 to 3 by the team. The three highest (score 6) are prompt injection, poisoned documents and cross-user data access: one family seeing another's records would be a serious privacy breach.
  • Every threat has a control and a test. The tests become a red-team regression suite: the attacks from "Prompt Injection and Jailbreaks", a cross-user query, a tool-abuse attempt, a log scan and an oversized request, run on every release.
  • Scores are judgments, not measurements; revisit them when the system or the attacks change.

Example: Supply Chain, Pickle and Hashes

Many older model files use Python's pickle format, and loading a pickle file can run any code its author chose. This program shows that safely (the "attack" only prints a message), compares it with safetensors, and pins a file with a SHA-256 hash. It needs pip install torch safetensors.

Python
import hashlib
import pickle
 
import torch
from safetensors.torch import load_file, save_file
 
# 1. Why pickle model files are dangerous: loading one can run any code the author chose.
class NotAModel:
    def __reduce__(self):                      # pickle calls this to rebuild the object...
        return (print, ("!!! code ran while loading the file: it could have stolen your keys",))
 
with open("model.pkl", "wb") as f:
    pickle.dump(NotAModel(), f)
print("Loading model.pkl with pickle:")
pickle.load(open("model.pkl", "rb"))           # ...so "loading" runs the attacker's function
 
# 2. safetensors stores only tensors: loading reads numbers and can't run code.
save_file({"weight": torch.ones(2, 3)}, "model.safetensors")
print("\nLoading model.safetensors:", {k: tuple(v.shape) for k, v in load_file("model.safetensors").items()})
 
# 3. Pin the file you tested: compare its hash before loading it in production
expected = hashlib.sha256(open("model.safetensors", "rb").read()).hexdigest()
print("Pinned SHA-256:", expected[:16], "...")
with open("model.safetensors", "r+b") as f:    # simulate tampering: change one byte at the end
    f.seek(-1, 2)
    last = f.read(1)
    f.seek(-1, 2)
    f.write(bytes([last[0] ^ 1]))
actual = hashlib.sha256(open("model.safetensors", "rb").read()).hexdigest()
print("Hash matches the pinned value:", actual == expected, "-> refuse to load" if actual != expected else "")
Output
Loading model.pkl with pickle:
!!! code ran while loading the file: it could have stolen your keys
 
Loading model.safetensors: {'weight': (2, 3)}
Pinned SHA-256: 45b4625ad991419c ...
Hash matches the pinned value: False -> refuse to load

Explanation:

  • __reduce__ tells pickle how to rebuild an object, and an attacker can make it call any function. Simply loading model.pkl ran the planted code. A real attack would steal keys or install malware instead of printing.
  • safetensors stores only tensors and metadata, so loading reads numbers and can't run code. That's why this course loads models with use_safetensors=True and chose an image model that ships safetensors files (see "Diffusion Models").
  • Hash pinning: record the SHA-256 of the exact file you tested, and refuse to load anything else. After one byte changed, the hash no longer matched, so the file would be refused.

Other Controls Worth Knowing

AreaControl
SecretsKeep keys in a secret store, scope each key narrowly, rotate them; see "API Keys and Secrets"
Code executionRun model-written code only in a sandbox with no network or secrets
AuthorizationCheck the user's permissions in code for every data access and tool call
Abuse and overloadRate limits, size limits, cost alerts
IncidentsPreserve logs and traces as evidence; follow "Tracing, SLOs and Incident Response"

Common Mistakes

Relying on the system prompt for security. It's a request, not a control.

Threat models that are never tested. Turn each threat into a test.

Loading whatever file a tutorial links to. Check the source, the format and the hash.

Forgetting outbound data. Logs, analytics and providers are boundaries too.

Interview Corner

How would you threat-model an LLM application?

Draw the data flows, mark every trust boundary (users, documents, tools, logs, suppliers), list threats at each, score likelihood and impact, choose layered controls, and write a test for each, run on every release.

Why are pickle model files a security risk?

Loading a pickle can execute arbitrary code chosen by whoever made the file. Use formats that store only data, such as safetensors, and verify file hashes against pinned values.

Practice

Exercise: add two threats. Add rows for "a malicious MCP server tool description" and "a model provider changes the model without notice", with likelihood, impact, control and test. Where do they rank?

Check your understanding:

  1. What is a trust boundary? Give two from Campus Helper.
  2. Why did loading model.pkl run code?
  3. What does hash pinning protect against?

Quick check: threat modeling

4 questions
1Which threats scored highest for Campus Helper?
2What happened when model.pkl was loaded?
3What does safetensors store?
4What should every threat in a threat model have?

Key Takeaways

Quick reference

NeedPractice
Find risksBoundaries × threats, scored by likelihood × impact
Prove controlsA test per threat, run in CI
Safe model filesuse_safetensors=True; avoid untrusted pickle
Integrityhashlib.sha256(file).hexdigest() against a pinned value
SecretsSecret store, narrow scope, rotation

Was this tutorial helpful?

Lesson 168 of 186