Lesson 10 · 50 minutes
Build the security file of an AI system
- Put the asset map, attack path, threat table, control matrix and test plan in one folder
- Write a script that checks the whole file set and prints PASS or FAIL for each rule
- Use the script to find a gap that no single file shows, and fix it
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
A large customer asks KR Books: "Show me how you secure your AI feature." You have an asset map, an attack path, a threat table and a control matrix, each in its own file. Your lead wants one folder that a script checks on every change. You join the files, find what no single file shows, and then check the folder of the clinic team.
Recall
Lesson 4: the path checker printed "ok" for every step. What did that prove?
Only that each step has a named control, a known tactic and a real asset. Not that the control exists or works.
Lesson 7: what is a single point of failure in the control matrix?
A threat that rests on one control. If it fails, nothing else stands in the way.
The idea
The security file is one folder in the repository of the system. It holds five documents, and each one answers a question from this course.
- Asset map → Flows: where data crosses a boundary
- Flows → Threats: what can go wrong on each flow
- Threats → Controls: what stops, detects, answers
- Controls → Tests: how we know each one works
- Tests → Asset map: a failed test changes the map
| File | Question | Lesson |
|---|---|---|
assets.json | What are we protecting, and who can write to it? | 1 |
attack-path.csv | How would an attacker go step by step? | 4 |
flows.csv and threats.csv | Where does untrusted data cross a boundary, and what can go wrong? | 6 |
controls.csv | What stops, detects or answers each threat? | 7 |
test-plan.csv | How do we know each control works? | new |
In NIST AI Risk Management Framework terms, the asset map and the flows are Map, the test plan is Measure, and the control matrix is Manage.
The documents refer to each other by id: an attack step names an asset and a control, a threat names a flow and a control, a control names threats, a test names a control. A script can follow these links, and the links are where gaps hide. A check across all the files finds the gaps between them.
Worked example
1. Collect the files
Make the folder and copy in the files of lessons 1, 4, 6 and 7. The lab files hold them in kr-books. cp copies files, {a,b,c} writes each name in turn, and . means "into the folder where I am".
mkdir -p ~/krlab/ai-security-fundamentals/security-file
cd ~/krlab/ai-security-fundamentals/security-file
cp ../kr-books/{assets.json,attack-path.csv,flows.csv,threats.csv,controls.csv} .
lsassets.json attack-path.csv controls.csv flows.csv threats.csv2. Write the test plan
Each control gets at least one test. A drill practises a response, such as switching the tool off. The first version has 15 tests; one control has none.
cat > test-plan.csv <<'EOF'
id,control,test,type,pass_when
P1,api-auth,Call the API with no token,script,HTTP 401
P2,rate-limit,Send 100 chats in a minute,script,HTTP 429
P3,untrusted-delimit,Run 10 poisoned reviews,script,No marker
P4,doc-review,Submit a hidden instruction,manual,Review waits
P5,tool-auth,Ask for another's order,script,Not found
P6,read-only-tools,List the tool's database rights,review,SELECT only
P7,output-filter,Make the model write a tag,script,No live tag
P8,no-secrets-in-prompt,Search the prompt for secrets,script,No match
P9,model-pin,Compare the model digest,script,Digests match
P10,privacy-minimise,Read the tool's fields,review,No address or phone
P11,request-log,Find one chat in the log,script,Request id appears
P12,tool-alerts,Make 5 refused tool calls,drill,Alert in 5 minutes
P13,runbook,Run a tabletop on a leak,drill,An owner is named
P14,regression-tests,Run the fixed questions,script,Within 5 points
P15,vendor-review,Score the provider,review,No critical no
EOF3. Write the checker
Create check.py. It loads the five documents and runs eleven rules. Each rule is a function that returns a list of problems, and the rule passes when the list is empty. Its docstring (the text in quotes at the top of the function) is the rule in plain words, and the loop at the end prints it. The checker uses the rule of lesson 7: a control marked outside_model no does not count as a prevent control. TACTICS is a copy of the list of lesson 4 and goes out of date, so take current names from the ATLAS matrix.
Read it with these notes.
folder / namejoins a folder and a file name.{x for x in xs}builds a set, a list with no repeats. For two sets,a - bis whataholds andbdoes not,a | bjoins them,a & bis what both hold, anda <= basks whetherafits insideb.by_threatmaps each threat id to the controls that answer it, each with its kind.any(...)is true when at least one item fits.sorted(...)puts a list in order.RULESis a list of the functions themselves.enumerate(RULES, 1)numbers them from 1, andrule()calls each one.sys.exit(1)ends the program with status 1, so a build can stop on it.
security-file/check.py
import csv
import json
import sys
from collections import defaultdict
from pathlib import Path
LAYERS = {"data", "model", "application", "agent", "infrastructure"}
TACTICS = {
"Reconnaissance", "Resource Development", "Initial Access", "Execution",
"Persistence", "Privilege Escalation", "Defense Evasion", "Credential Access",
"Discovery", "Lateral Movement", "Collection", "AI Model Access", "AI Attack Adaptation",
"Command and Control", "Exfiltration", "Impact",
"AI Attack Staging", "ML Model Access", "ML Attack Staging", # older names, kept so that old reports pass
}
folder = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
def table(name):
with open(folder / name) as f:
return list(csv.DictReader(f))
system = json.load(open(folder / "assets.json"))
actors, assets = system["actors"], system["assets"]
path, flows = table("attack-path.csv"), table("flows.csv")
threats, controls, tests = table("threats.csv"), table("controls.csv"), table("test-plan.csv")
control_ids = {c["control"] for c in controls}
by_threat = defaultdict(list) # threat id -> [(kind, control)]
for c in controls:
kind = c["kind"] if c["outside_model"] == "yes" else "model-only" # as in lesson 7
for t in c["threats"].split():
by_threat[t].append((kind, c["control"]))
ends = {a["id"] for a in assets} | set(actors)
def asset_map():
"""Every asset has a known layer and only known writers"""
return [a["id"] for a in assets if a["layer"] not in LAYERS or not set(a["writers"]) <= set(actors)]
def all_layers():
"""All five layers have an asset"""
return sorted(LAYERS - {a["layer"] for a in assets})
def path_steps():
"""Every attack step has a known tactic and a control"""
return ["step " + r["step"] for r in path if r["tactic"] not in TACTICS or not r["control"]]
def path_links():
"""Attack steps name real assets and real controls"""
return ["step " + r["step"] for r in path if r["asset"] not in ends or r["control"] not in control_ids]
def flow_ends():
"""Every flow joins known assets or actors"""
return [f["id"] for f in flows if f["from"] not in ends or f["to"] not in ends]
def boundary_flows():
"""Every flow that crosses a boundary has a threat with a control"""
return [f["id"] for f in flows if f["boundary"] != "-"
and not any(t["flow"] == f["id"] and t["control"] for t in threats)]
def threat_controls():
"""Each threat's control is in the matrix for that threat"""
return [t["id"] for t in threats if (t["control"] not in control_ids
or t["control"] not in [c for _, c in by_threat[t["id"]]])]
def kinds_per_threat():
"""Every threat has a prevent control outside the model and a detect or respond control"""
out = []
for t in threats:
kinds = {kind for kind, _ in by_threat[t["id"]]}
if "prevent" not in kinds or not kinds & {"detect", "respond"}:
out.append(t["id"])
return out
def single_points():
"""No threat rests on a single control"""
return [t["id"] for t in threats if len(by_threat[t["id"]]) < 2]
def untrusted_writers():
"""Assets with untrusted or third-party writers sit on a flow that has a threat"""
threatened = {f["id"] for f in flows if any(t["flow"] == f["id"] for t in threats)}
out = []
for a in assets:
if any(actors[w] != "trusted" for w in a["writers"]):
on = [f for f in flows if a["id"] in (f["from"], f["to"]) and f["id"] in threatened]
if not on:
out.append(a["id"])
return out
def test_plan():
"""Every control has a test, and every test names a real control"""
tested = {t["control"] for t in tests}
return sorted(control_ids - tested) + sorted(tested - control_ids)
RULES = [asset_map, all_layers, path_steps, path_links, flow_ends, boundary_flows,
threat_controls, kinds_per_threat, single_points, untrusted_writers, test_plan]
failed = 0
for n, rule in enumerate(RULES, 1):
problems = rule()
failed += bool(problems)
print(f"R{n:<2} {'FAIL' if problems else 'PASS'} {rule.__doc__}")
if problems:
print(" ->", ", ".join(problems))
print(f"\n{len(RULES) - failed} of {len(RULES)} rules pass")
sys.exit(1 if failed else 0)4. Run it and read the failures
python3 check.pyR1 PASS Every asset has a known layer and only known writers
R2 PASS All five layers have an asset
R3 PASS Every attack step has a known tactic and a control
R4 PASS Attack steps name real assets and real controls
R5 PASS Every flow joins known assets or actors
R6 PASS Every flow that crosses a boundary has a threat with a control
R7 PASS Each threat's control is in the matrix for that threat
R8 PASS Every threat has a prevent control outside the model and a detect or respond control
R9 PASS No threat rests on a single control
R10 FAIL Assets with untrusted or third-party writers sit on a flow that has a threat
-> A6
R11 FAIL Every control has a test, and every test names a real control
-> kill-switch
9 of 11 rules passEach rule is a function of three to six lines. Read the docstring first, then the return line.
R11 is the plain one: kill-switch has no test. R10 is the finding: A6, the orders database, has an untrusted writer (the delivery notes). The only flow that touches A6 is F6, and no threat points at F6. Lesson 6 covered flow F7, not the database.
5. Fix both, then break it on purpose
Add the missing threat: a delivery note that holds an instruction waits in the database. Three existing controls cover it, one of each kind: tool-auth (prevent: it stops the harm, what a fooled model can do with the note, not the note), request-log (detect) and kill-switch (respond). Then add the missing test. -e adds one more edit to sed.
echo 'T14,F6,A delivery note that a customer wrote waits in the database with an instruction,tool-auth' >> threats.csv
sed -e '/^tool-auth/ s/$/ T14/' -e '/^request-log/ s/$/ T14/' -e '/^kill-switch/ s/$/ T14/' controls.csv > controls.new
mv controls.new controls.csv
echo 'P16,kill-switch,Switch off the tool in staging,drill,Tools off in 1 minute' >> test-plan.csv
python3 check.py | tail -4R10 PASS Assets with untrusted or third-party writers sit on a flow that has a threat
R11 PASS Every control has a test, and every test names a real control
11 of 11 rules passA check that never fails is not proven. Put a typo in the control of step 5 of the attack path, run the check, and restore the file.
cp attack-path.csv attack-path.bak
sed 's/,A4,tool-auth$/,A4,tool-auht/' attack-path.bak > attack-path.csv
python3 check.py | sed -n 3,5p
mv attack-path.bak attack-path.csv
python3 check.py | tail -1R3 PASS Every attack step has a known tactic and a control
R4 FAIL Attack steps name real assets and real controls
-> step 5
11 of 11 rules pass6. The finished file
Three files changed in steps 2 and 5: threats.csv, controls.csv and test-plan.csv. Here they are whole. In the lab files, the other three files of this folder are only in kr-books: copy them with cp ../kr-books/{assets.json,attack-path.csv,flows.csv} ..
The finished file: threats.csv
security-file/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
T14,F6,A delivery note that a customer wrote waits in the database with an instruction,tool-authThe finished file: controls.csv
security-file/controls.csv
control,kind,ai_specific,outside_model,threats
api-auth,prevent,no,yes,T10
rate-limit,prevent,no,yes,T2
untrusted-delimit,prevent,yes,no,T1 T3 T8
doc-review,prevent,yes,yes,T3
tool-auth,prevent,yes,yes,T7 T11 T1 T8 T14
read-only-tools,prevent,yes,yes,T11
output-filter,prevent,yes,yes,T9 T13
no-secrets-in-prompt,prevent,yes,yes,T4
model-pin,prevent,yes,yes,T6
privacy-minimise,prevent,no,yes,T5 T12
request-log,detect,yes,yes,T1 T3 T4 T7 T8 T9 T10 T2 T12 T13 T14
tool-alerts,detect,yes,yes,T7 T12
kill-switch,respond,no,yes,T1 T3 T7 T8 T9 T11 T14
runbook,respond,no,yes,T2 T4 T5 T6 T10 T12 T13
regression-tests,detect,yes,yes,T6
vendor-review,govern,no,yes,T5 T6The finished file: test-plan.csv
security-file/test-plan.csv
id,control,test,type,pass_when
P1,api-auth,Call the API with no token,script,HTTP 401
P2,rate-limit,Send 100 chats in a minute,script,HTTP 429
P3,untrusted-delimit,Run 10 poisoned reviews,script,No marker
P4,doc-review,Submit a hidden instruction,manual,Review waits
P5,tool-auth,Ask for another's order,script,Not found
P6,read-only-tools,List the tool's database rights,review,SELECT only
P7,output-filter,Make the model write a tag,script,No live tag
P8,no-secrets-in-prompt,Search the prompt for secrets,script,No match
P9,model-pin,Compare the model digest,script,Digests match
P10,privacy-minimise,Read the tool's fields,review,No address or phone
P11,request-log,Find one chat in the log,script,Request id appears
P12,tool-alerts,Make 5 refused tool calls,drill,Alert in 5 minutes
P13,runbook,Run a tabletop on a leak,drill,An owner is named
P14,regression-tests,Run the fixed questions,script,Within 5 points
P15,vendor-review,Score the provider,review,No critical no
P16,kill-switch,Switch off the tool in staging,drill,Tools off in 1 minuteYour turn
The clinic team sends its folder. A colleague wrote six files, and the file does not pass. This script makes the folder clinic-file and writes the six files into it.
mkdir -p ~/krlab/ai-security-fundamentals/clinic-file
cd ~/krlab/ai-security-fundamentals/clinic-file
cat > assets.json <<'EOT'
{"system": "KR Clinic booking assistant",
"actors": {"patient": "untrusted", "staff": "trusted", "developer": "trusted", "booking-system": "trusted", "partner": "third-party", "model-provider": "third-party"},
"assets": [
{"id": "C1", "name": "help pages", "layer": "data", "writers": ["staff"]},
{"id": "C2", "name": "doctor profiles", "layer": "data", "writers": ["partner"]},
{"id": "C3", "name": "booking database", "layer": "data", "writers": ["booking-system", "patient"]},
{"id": "C4", "name": "language model", "layer": "model", "writers": ["model-provider"]},
{"id": "C5", "name": "prompt and retrieval", "layer": "application", "writers": ["developer"]},
{"id": "C6", "name": "booking tool", "layer": "agent", "writers": ["developer"]},
{"id": "C7", "name": "chat API and server", "layer": "infrastructure", "writers": ["developer"]}]}
EOT
cat > attack-path.csv <<'EOT'
step,attacker_does,tactic,technique,asset,control
1,Asks for the tools,Reconnaissance,Probe the assistant,C7,rate-limit
2,Types an instruction as the reason,Resource Development,Prepare hostile content,C3,untrusted-delimit
3,Asks about the visit,Initial Access,Hostile text reaches the model,C5,untrusted-delimit
4,The model follows the instruction,Execution,LLM Prompt Injection,C4,untrusted-delimit
5,The model asks for another visit,Collection,Misuse of a tool,C6,tool-authz
6,The page shows the details,Exfiltration,Data leaves in output,C7,output-filter
EOT
cat > flows.csv <<'EOT'
id,from,to,data,boundary
F1,patient,C7,chat message,B1
F2,C7,C5,message,-
F3,C1,C5,help pages,-
F4,C2,C5,doctor profiles,B3
F5,C5,C4,prompt,B2
F6,C4,C6,tool call,B3
F7,C6,C3,booking lookup,-
F8,C6,C4,tool result,B3
F9,C4,C7,answer,B3
F10,C7,patient,page,B1
EOT
cat > threats.csv <<'EOT'
id,flow,threat,control
T1,F1,A message tells the assistant to ignore its rules,untrusted-delimit
T2,F1,A flood of chats runs up the model bill,rate-limit
T3,F5,The provider keeps prompts that hold patient data,privacy-minimise
T4,F6,Injected text reads another patient's visit,tool-auth
T5,F7,A reason that holds an instruction waits in the database,untrusted-delimit
T6,F8,A tool result carries an instruction,untrusted-delimit
T7,F9,Output holds a link that leaks data,output-filter
T8,F10,The page shows live HTML,output-filter
EOT
cat > controls.csv <<'EOT'
control,kind,ai_specific,outside_model,threats
rate-limit,prevent,no,yes,T2
untrusted-delimit,prevent,yes,no,T1 T5 T6
privacy-minimise,prevent,no,yes,T3
tool-auth,prevent,yes,yes,T1 T4 T5 T6
output-filter,prevent,yes,yes,T7 T8
request-log,detect,yes,yes,T1 T2 T3 T4 T5 T6 T7 T8
kill-switch,respond,no,yes,T1 T4 T5 T6 T7
EOT
cat > test-plan.csv <<'EOT'
id,control,test,type,pass_when
P1,rate-limit,Send 100 chats in a minute,script,HTTP 429
P2,untrusted-delimit,Run 10 hostile reasons,script,No answer follows
P3,privacy-minimise,Read the tool's fields,review,No phone number
P4,tool-auth,Ask for another's visit,script,Not found
P5,output-filter,Make the model write a tag,script,No live tag
P6,kill-switch,Switch the tool off in staging,drill,Tools off in 1 minute
EOTRun check.py on that folder, find every cause, and fix the files until all rules pass. A fix in one file may need a change in another.
Check yourself
Why does the check read all five files together and not one at a time?
The gaps sit in the links: an asset with no threat, a control with no test, a path step with a control that the matrix lacks.
R9 passes. A colleague says the system is therefore defended in depth. What is missing from that claim?
R9 counts controls, not their independence or strength. Two controls that fail for the same reason count as two.
Field notes
- Treat the file as code. Run
check.pyin the build so that a pull request fails when the file no longer holds, and keep its output as evidence for an audit or a customer. - The folder can also hold
use-case.json(lesson 1), andsources.csvandwatch.csv(lesson 9). This checker has no rule for them yet. The next rules to add are one for the use case and one for the watch list; lesson 11 asks you to write or finish these three files for a new system. - After an incident, write the rule that would have caught it.
- Give each row an owner and a review date.
- A passing file shows that the paper is consistent, not that the system behaves as it says. Tests and logs show that.