Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 06 · 45 minutes

Threat-model an AI system

After this lesson you can
  • Describe an AI system as data flows with trust boundaries
  • Write a threat table in which every boundary flow has a threat and a control
  • Check the table for gaps with a script
Lab files of this lesson (25)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The KR Books assistant goes live in three weeks. On Friday the team holds a design review, and the lead asks you: "Tell us what can go wrong before we write more code." There is no diagram and no test yet, only the asset map from lesson 1. You turn the map into data flows and a threat table that a script can check. Then the clinic team gives you their first table and asks you to find what it lacks.

Recall

Lesson 1: what is the trust question, and which three groups does it sort the writers into?

The question is: who can write to this asset? The groups are trusted, untrusted and third-party.

Lesson 4: what must every step of an attack path name besides the tactic and the technique?

The asset that the step touches and the control that stops it or limits it. A step with no control is the next piece of work.

The idea

The four questions are the same as in the course "Security fundamentals" (lesson 7), and each has an AI addition.

QuestionIn an AI system
1. What are we building?The asset map (lesson 1), the data flows between the assets and the trust boundaries
2. What can go wrong?Prompts for threats: STRIDE, the public lists of lessons 4 and 9, the attack path, the NIST AI 100-2 families
3. What will we do about it?One control, at least, for each threat (lesson 7 builds the full matrix)
4. Did we do a good job?A check that finds gaps, and tests (lesson 10)

A data flow is a movement of data from one asset or actor to another. A trust boundary is a line where the level of trust changes. In an AI system four kinds of text are untrusted, even when they come from your own database or your own model:

  • user input;
  • retrieved documents;
  • tool results;
  • model output.

The reason is the way a model works. It cannot tell data from instruction: any text in its prompt can steer it. A retrieved document and a tool result are data to you, and instructions to the model. Model output is shaped by all the text that went in, so it is as trustworthy as the least trusted part of its input.

For the KR Books assistant, put three boundaries on the map.

BoundaryBetween
B1The internet (customers) and your chat API
B2Your application and the provider's model
B3Text from a source that you do not control, and the component that reads it or acts on it (the model, a tool or the page)
One chat, and where the text is untrusted
InternetYour companyProviderOrder serviceCustomerAttackerApplicationRetrievalLanguage modelOrder tool12345678InternetYour companyProviderOrder serviceCustomerAttackerApplicationRetrievalLanguage modelOrder tool12345678
  1. Customer → Application: chat message, crosses B1
  2. Attacker → Retrieval: a review that others can read
  3. Retrieval → Application: passages that others wrote, B3
  4. Application → Language model: system text, passages, message, B2
  5. Language model → Order tool: a tool call, B3
  6. Order tool → Language model: a result with customer text, B3
  7. Language model → Application: an answer, B3
  8. Application → Customer: the answer on the page, B1

The rule for the file: every flow that crosses a boundary has at least one threat, and every threat has at least one control. A flow with no threat is not safe. It is a flow that nobody has examined.

Worked example

1. Write the data flows

Work in the folder of lesson 1. Create flows.csv. Each flow has an id, two ends (asset ids from assets.json, or an actor), the data and the boundary that it crosses (- for none). Read it as the life of one chat: F1 to F4 build the prompt, F5 to F7 are the tool call, F8 and F9 return the answer.

cd ~/krlab/ai-security-fundamentals/kr-books
cat > flows.csv <<'EOF'
id,from,to,data,boundary
F1,customer,A5,chat message,B1
F2,A5,A3,message to the chat code,-
F3,A1,A3,retrieved passages,B3
F4,A3,A2,prompt: system text + passages + message,B2
F5,A2,A4,tool call with an order number,B3
F6,A4,A6,order lookup and result,-
F7,A4,A2,tool result with delivery notes,B3
F8,A2,A5,answer from the model,B3
F9,A5,customer,answer shown on the page,B1
EOF
One row of flows.csv (F4)
F4flow idA3from: the chat codeA2to: the modelprompt: system text + passages + messagethe dataB2boundary it crossesF4flow idA3from: the chat codeA2to: the modelprompt: system text + passages +messagethe dataB2boundary it crosses

Seven of the nine flows cross a boundary. F3 and F7 carry text that customers wrote. F5 and F8 carry model output.

2. Write the first threat table

Create threats.csv. Each row has an id, the flow, the threat and the main control. The control names come from lesson 7. In row T12 the author did not know the control, so the field is empty.

cat > threats.csv <<'EOF'
id,flow,threat,control
T1,F1,A customer message tells the assistant to ignore its rules,untrusted-delimit
T2,F1,A flood of long chats runs up the model bill,rate-limit
T3,F3,A review in the index hides an instruction for the model,doc-review
T4,F4,The system prompt leaks a staff discount code,no-secrets-in-prompt
T5,F4,The provider keeps prompts that hold customer data,privacy-minimise
T6,F4,The provider changes the model and the behaviour changes,model-pin
T7,F5,Injected text makes the tool read another customer's order,tool-auth
T8,F7,A delivery note in a tool result carries an instruction,untrusted-delimit
T9,F8,Model output holds HTML or a link that leaks data in the browser,output-filter
T10,F1,A caller without an account uses the API,api-auth
T11,F5,A write tool added later acts on injected text,read-only-tools
T12,F7,The tool returns more personal data than the answer needs,
EOF
One row of threats.csv (T7)
T7threat idF5the flow it sits onInjected text makes the tool read another...what can go wrongtool-auththe main controlT7threat idF5the flow it sits onInjected text makes the tool readanother...what can go wrongtool-auththe main control

3. Write the checker

Create check_threats.py. It reports threats that point to a flow that does not exist, threats with no control, and, for each boundary flow, the number of threats. As in lesson 4, the folder is an optional word after the script name, and the script ends with status 1 when it finds any problem. continue skips the rest of the loop for the current flow.

kr-books/check_threats.py

import csv
import sys

folder = sys.argv[1] if len(sys.argv) > 1 else "."
flows = list(csv.DictReader(open(f"{folder}/flows.csv")))
threats = list(csv.DictReader(open(f"{folder}/threats.csv")))

known = {f["id"] for f in flows}
lost = [t["id"] for t in threats if t["flow"] not in known]
bare = [t["id"] for t in threats if not t["control"].strip()]
print("threats on a flow that does not exist:", lost or "none")
print("threats with no control:", bare or "none")

print()
gaps = 0
for flow in flows:
    if flow["boundary"] == "-":
        continue
    mine = [t for t in threats if t["flow"] == flow["id"]]
    controls = [t for t in mine if t["control"].strip()]
    ok = bool(mine) and bool(controls)
    gaps += not ok
    print(f'{flow["id"]} crosses {flow["boundary"]}: threats {len(mine)}, with a control {len(controls)}  {"ok" if ok else "GAP"}')
print(f"\nflows with a gap: {gaps}")
sys.exit(1 if gaps or lost or bare else 0)

4. Run it and read the gaps

python3 check_threats.py
threats on a flow that does not exist: none
threats with no control: ['T12']

F1 crosses B1: threats 3, with a control 3  ok
F3 crosses B3: threats 1, with a control 1  ok
F4 crosses B2: threats 3, with a control 3  ok
F5 crosses B3: threats 2, with a control 2  ok
F7 crosses B3: threats 2, with a control 1  ok
F8 crosses B3: threats 1, with a control 1  ok
F9 crosses B1: threats 0, with a control 0  GAP

flows with a gap: 1

Two findings. T12 has no control, and flow F9, the page that shows the answer to the customer, has no threat at all. F9 is where the answer is put in HTML. Lesson 5 showed what can happen there.

5. Close the gaps

Give T12 its control, and add a threat for F9. In the sed pattern, \(.*\) keeps the middle of the line, and \1 writes it back. > writes the result into a new file, and mv moves that file over the old one. (sed -i would edit in place, but it differs between Linux and macOS.) >> adds a line to the end of a file.

sed 's/^T12,F7,\(.*\),$/T12,F7,\1,privacy-minimise/' threats.csv > threats.new
mv threats.new threats.csv
echo 'T13,F9,The page puts the answer in HTML without escaping and a script runs,output-filter' >> threats.csv
python3 check_threats.py | tail -4
F8 crosses B3: threats 1, with a control 1  ok
F9 crosses B1: threats 1, with a control 1  ok

flows with a gap: 0

The check passes. It does not tell you that the table is complete. It tells you that you have looked at every boundary. Keep flows.csv and threats.csv: lessons 7, 9 and 10 use them.

6. The finished file

This is the whole threats.csv as it stands after the steps above (the table of step 2, with the control of T12 and the new row T13). The lab files of the course hold it.

The finished file: threats.csv

kr-books/threats.csv

id,flow,threat,control
T1,F1,A customer message tells the assistant to ignore its rules,untrusted-delimit
T2,F1,A flood of long chats runs up the model bill,rate-limit
T3,F3,A review in the index hides an instruction for the model,doc-review
T4,F4,The system prompt leaks a staff discount code,no-secrets-in-prompt
T5,F4,The provider keeps prompts that hold customer data,privacy-minimise
T6,F4,The provider changes the model and the behaviour changes,model-pin
T7,F5,Injected text makes the tool read another customer's order,tool-auth
T8,F7,A delivery note in a tool result carries an instruction,untrusted-delimit
T9,F8,Model output holds HTML or a link that leaks data in the browser,output-filter
T10,F1,A caller without an account uses the API,api-auth
T11,F5,A write tool added later acts on injected text,read-only-tools
T12,F7,The tool returns more personal data than the answer needs,privacy-minimise
T13,F9,The page puts the answer in HTML without escaping and a script runs,output-filter

Your turn

The clinic team sends the data flows of the KR Clinic assistant and the table that they wrote alone. The boundaries are the same as above: B1 between the internet and the chat API, B2 between your application and the provider's model, B3 between a source that you do not control and what reads it. In the clinic folder, save these two files.

clinic/flows.csv

id,from,to,data,boundary
F1,patient,C7,chat message and reason for visit,B1
F2,C7,C5,message to the chat code,-
F3,C1,C5,help pages and leaflets,-
F4,C2,C5,doctor profiles from the partner,B3
F5,C5,C4,prompt: system text + passages + message,B2
F6,C4,C6,tool call with a patient number,B3
F7,C6,C3,booking lookup and result,-
F8,C6,C4,tool result with the reason for visit,B3
F9,C4,C7,answer from the model,B3
F10,C7,patient,answer shown on the page,B1

clinic/threats.csv

id,flow,threat,control
T1,F1,A patient message tells the assistant to ignore its rules,untrusted-delimit
T2,F1,A flood of chats runs up the model bill,rate-limit
T3,F4,A doctor profile in the partner file hides an instruction,feed-review
T4,F5,The provider keeps prompts that hold patient data,privacy-minimise
T5,F6,Injected text makes the tool read the booking of another patient,tool-auth
T6,F8,The reason for visit in a tool result carries an instruction,untrusted-delimit
T7,F9,Model output holds a link that leaks data in the browser,
T8,F11,A script flood hits the booking tool,rate-limit

Run the checker on the clinic folder. Then repair the table. A flow with no threat needs a new row that you write. A threat with no control needs a control. A threat on a flow that does not exist belongs to a flow that does: decide which one, and correct the row.

Last, read your repaired table once more, one boundary at a time. Which threat did the script not ask for, and that you would still add?

Check yourself

Why is the output of the model untrusted when you wrote the model's system prompt?

The model's answer depends on all of its input, including documents and messages that other people wrote. An attacker who controls part of the input can control part of the output. Check output as you would check input from a stranger.

Flow F6 (the order lookup) crosses no boundary in the file. Is that a mistake?

It is a choice, and you can defend it: both ends are your own components, and the query is built by your code. The delivery notes that come back are customer text, so that risk is counted on flow F7, where the text reaches the model. Write down choices like this one.

Which STRIDE kind is T4, the leak of the staff discount code? Why does STRIDE not replace the four questions?

In STRIDE (course "Security fundamentals", lesson 7) the kinds are Spoofing, Tampering, Repudiation, Information disclosure, Denial of service and Elevation of privilege. T4 is Information disclosure. STRIDE is a list of kinds of threat that prompts question 2. It does not give the asset map, the controls or the checks, and it says little about the parts that are new in AI systems, so use it with the public lists of lessons 4 and 9.

A colleague wants to skip the model of a feature that "only summarises text". What do you say?

A summary tool reads untrusted text and writes text that a person or a program uses. Both ends are flows that cross a boundary. Its threat model is short, so it costs little to write.

Field notes

  • Keep the model in the repository of the system and change it in the same pull request as the design. A threat model in a slide deck goes out of date in a month.
  • Rate each threat with the likelihood and impact method of the course "Security fundamentals" and sort the table. A table of 80 equal rows is not a plan. Review the top ten each quarter.
  • Add the flows that people forget: the training and fine-tuning pipeline, evaluation data, logs that hold prompts, and the memory of an agent between sessions. In agent systems, add a column for the identity under which each tool call runs.
  • For retrieval, ask whose documents sit in the same index. If more than one customer shares an index, access control must work at retrieval time, not only at the page.
  • The NIST AI Risk Management Framework calls this work Map: you set the context, find the harms and name who is affected. A threat model is one concrete way to do the Map function.