Lesson 02 · 45 minutes
Map what the target offers and what it can reach
- List the endpoints that the target answers, inside the scope only
- Find the tools, documents and files that the target reaches by reading its own files
- Scan a folder for secrets and write the data flows with their trust boundaries
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 test starts. You have the address of the chat endpoint and the source of the program, and nothing else. Your lead wants a map before any attack: what the system answers, what it can reach, and where a secret may lie. "If a tester cannot draw the system, they are guessing." You build the map from outside, by asking, and from inside, by reading. Every request goes through the rules of lesson 1.
Recall
Lesson 1: a draft request uses the host "localhost". What does the checker do, and why?
It refuses with the reason host. It matches the written text exactly, and scope.json names 127.0.0.1 only. A wider match needs a change of the scope, made by the owner.
Lesson 1: which function sends requests, and what does it ask first?
call in rules.py. It asks refusal (is the request in the scope?) and stop_reason (must the test stop?), and it refuses before anything is sent.
The idea
A map of a system is the list of everything that an attacker can reach, and everything that the system can reach on its own. You need both: the first list shows where an attacker can enter, the second what an attacker can do after entering. A chat assistant with a tool that reads files can read every file that the tool can read.
| Question | Outside view | Inside view |
|---|---|---|
| Which endpoints exist? | Ask for paths and read the status codes. | Search the source for routes. |
| Which tools does the model have? | Ask the assistant, read errors. | Search the source for the tool list. |
| Which documents does it use? | Read the sources of the answers. | Read the folders that it opens. |
| Where are the secrets? | Look at replies, pages, logs. | Scan the files for key shapes. |
An outside probe is a request, so the scope applies. A path outside it is not requested: you ask the owner to add it. Reading the source needs no request, and it finds more. The two views together become a data-flow list: who sends what to whom, and which flows cross a trust boundary, a line where the level of trust changes. Here code checks the list against the real files.
- Customer → Chat endpoint: the message crosses a boundary
- Chat endpoint → Retrieval: words of the question
- Retrieval → docs folder: finds passages, some from customers
- Retrieval → Model: the passages and the question
- Model → order_status: tool call with an order id
- Model → read_doc: tool call with a file name
- order_status → orders: lookup
- read_doc → .env: reads the file that the name points to
Worked example
1. Start the target and probe it
Open a second terminal in the lab folder and start the target. KR_STUB=1 before the command sets that setting for this one command. The terminal stays busy: that is right.
KR_STUB=1 python3 target.pyBack in the first terminal, save the paths that a tester would try, one on each line.
cat > paths.txt <<'EOT'
/
/health
/chat
/debug
/admin
/metrics
/docs
/openapi.json
/.env
/api/tags
/status
/login
EOTmapper.py asks for each path with GET, but only if the scope allows it, and writes the result to map.json. A status code is the number that a web server answers with: 200 means ok, 404 no such path, 405 that the path exists but not for this method.
mapper.py
"""mapper.py: find out what the target offers, inside the scope only.
python3 mapper.py probe paths.txt ask for each path with GET, write map.json (exit code 2 if nothing answered)
python3 mapper.py flows flows.txt check a list of data flows against what the target holds
"""
import json
import sys
from rules import call, load_scope, refusal
BASE = "http://127.0.0.1:8410"
def probe(scope, paths):
"""Return {"found": {path: status}, "skipped": {path: reason}}. A path outside the scope is not requested."""
found, skipped = {}, {}
for path in paths:
why = refusal(scope, "GET", BASE + path)
if why:
skipped[path] = why
else:
found[path] = call(scope, "GET", BASE + path)[0]
return {"found": found, "skipped": skipped}
def flows(lines, must_appear=("order_status", "read_doc", ".env", "target.log")):
"""Count the flows 'source | destination | data | crosses a boundary (yes or no)' and list what no flow mentions."""
rows = [[part.strip() for part in line.split("|")] for line in lines if line.strip()]
crossing = sum(row[3] == "yes" for row in rows)
missing = [name for name in must_appear if not any(name in " ".join(row) for row in rows)]
return len(rows), crossing, missing
if __name__ == "__main__":
lines = open(sys.argv[2]).read().splitlines()
if sys.argv[1] == "probe":
result = probe(load_scope(), [line.strip() for line in lines if line.strip()])
json.dump(result, open("map.json", "w"), indent=2)
for path, status in result["found"].items():
print(f"{status or 'no answer'} {path}")
for path, why in result["skipped"].items():
print(f"-- {path} not requested: outside the scope ({why})")
if not any(result["found"].values()):
print("nothing answered: the target may be down")
sys.exit(2)
else:
total, crossing, missing = flows(lines)
print(f"flows {total}, crossing a trust boundary {crossing}, not in any flow: {missing or 'none'}")python3 mapper.py probe paths.txt200 /health
405 /chat
200 /debug
-- / not requested: outside the scope (path)
-- /admin not requested: outside the scope (path)
-- /metrics not requested: outside the scope (path)
-- /docs not requested: outside the scope (path)
-- /openapi.json not requested: outside the scope (path)
-- /.env not requested: outside the scope (path)
-- /api/tags not requested: outside the scope (path)
-- /status not requested: outside the scope (path)
-- /login not requested: outside the scope (path)Three paths were asked, and nine were not. /health and /debug answer, and /chat answers 405 (it exists, but it wants POST). /api/tags is allowed on the model server only. If /metrics matters, ask the owner to put it in the scope. A path that gets no answer at all (status 0) prints no answer, and when no path answers, mapper.py ends with exit code 2: a map of nothing is not a clean map.
2. Read the target from inside
The source is yours to read. grep -n prints the lines that match a pattern, with their line numbers. Search for the routes, the tools, and everything that the program reads or writes.
grep -n "self.path\|def do_" target.py
grep -n "^TOOLS\|os.environ\|open(\|read_text\|write_text" target.py124: def do_GET(self):
125: if self.path == "/health":
127: elif self.path == "/debug" and "debug" not in FIX:
130: self.send(405 if self.path == "/chat" else 404, {"error": "not available"})
132: def do_POST(self):
133: if self.path != "/chat":
20:FIX = set(filter(None, os.environ.get("KR_FIX", "").split(",")))
21:STUB = os.environ.get("KR_STUB") == "1"
22:ENV = dict(line.split("=", 1) for line in (HOME / ".env").read_text().split() if "=" in line)
38: (DOCDIR / (name + ".txt")).write_text(text)
88: return path.read_text()[:300]
93:TOOLS = {"order_status": order_status, "read_doc": read_doc}
104: with open(HOME / "target.log", "a") as f:
154: port = int(os.environ.get("KR_PORT", "8410"))Four facts that no probe showed. A setting called debug switches /debug off. The tools are order_status and read_doc. The program reads .env and writes docs/ and target.log. And read_doc opens a file whose name comes from the model (line 88): lesson 3 turns that into the cases info-1 and agency-2, and lesson 4 runs them.
3. Scan for secrets
A secret is a value that gives access: a key, a token, a password, a private key. The most common finding of any review is one of them, left in a file. First make a small project to practise on: make_repo.py writes repo-sample/ with fake secrets in it, each built from two pieces so that the scanner does not flag the generator.
make_repo.py
"""make_repo.py: make repo-sample/, a small project with FAKE secrets planted in it, for the scanner.
The fake values are built from two pieces, so that the scanner does not flag this generator itself.
"""
from pathlib import Path
FILES = {
"app/main.py": 'import os\n\ntoken = os.environ["API_TOKEN"]\nprint("start", len(token))\n',
"app/settings.py": 'DEBUG = True\nPAYMENT_KEY = "pk-' + 'live-3c9d5e7f1a2b4c6d"\nDB_PASS' + 'WORD = "winter2024!"\n',
"deploy/notes.txt": "Deploy on Friday.\nLogin as admin, pass" + "word: Tr0ub4dor&3\n",
"deploy/id_demo": "-----BEGIN " + "PRIVATE KEY-----\nbm90IGEgcmVhbCBrZXk=\n-----END " + "PRIVATE KEY-----\n",
"data/backup.json": '{"owner": "ops", "key_id": "AK' + 'IAABCDEFGHIJKLMNOP"}\n',
".env.example": "API_TOKEN=changeme\n",
"README.md": "# Sample project\nSettings come from the environment.\n",
"tests/test_main.py": 'password = "test"\n',
}
for name, text in FILES.items():
path = Path("repo-sample") / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
print("made", len(FILES), "files in repo-sample")python3 make_repo.pymade 8 files in repo-samplesecretscan.py looks for the shapes of secrets. A regular expression (a pattern for text, written with the re module) describes each shape. rglob("*") lists every file below a folder. enumerate counts lines from 1. PLACEHOLDERS are words such as changeme that mark a value as not real. It prints only the first four characters of a value, because a tool that prints findings in full creates a new leak. It also takes one file, and mask replaces every secret in a text (lesson 7 uses it).
secretscan.py
"""secretscan.py: look for secrets in the files of a folder (or in one file). Values are masked in the output.
python3 secretscan.py [folder or file] exit code 1 when it finds something
"""
import re
import sys
from pathlib import Path
PATTERNS = {
"api key": r"pk-(?:live|test)-[A-Za-z0-9]{8,}",
"key id": r"AKIA[0-9A-Z]{16}",
"private key": r"-----BEGIN [A-Z ]*PRIVATE KEY-----",
"assigned secret": r"(?i)(?:password|passwd|secret|token)\s*[=:]\s*['\"]?(?!os\.)([^\s'\"]{6,})",
}
PLACEHOLDERS = ("changeme", "example", "xxxx", "<")
SKIP = {".git", "__pycache__", "node_modules"}
def mask(text):
"""Replace every secret that a pattern finds in `text`. Use it before a value goes into a report."""
for pattern in PATTERNS.values():
text = re.sub(pattern, "[secret removed]", text)
return text
def scan(folder):
"""Return a list of (file, line number, kind, masked value)."""
found = []
root = Path(folder)
for path in [root] if root.is_file() else sorted(root.rglob("*")):
if not path.is_file() or SKIP & set(path.parts):
continue
try:
lines = path.read_text().splitlines()
except (UnicodeDecodeError, OSError):
continue
for number, line in enumerate(lines, 1):
for kind, pattern in PATTERNS.items():
match = re.search(pattern, line)
if match and not any(p in line.lower() for p in PLACEHOLDERS):
found.append((str(path), number, kind, match.group(match.lastindex or 0)[:4] + "***"))
break
return found
if __name__ == "__main__":
results = scan(sys.argv[1] if len(sys.argv) > 1 else ".")
for file, number, kind, value in results:
print(f"{file}:{number} {kind} {value}")
print(f"findings: {len(results)} in {len({r[0] for r in results})} files")
sys.exit(1 if results else 0)python3 secretscan.py repo-samplerepo-sample/app/settings.py:2 api key pk-l***
repo-sample/app/settings.py:3 assigned secret wint***
repo-sample/data/backup.json:1 key id AKIA***
repo-sample/deploy/id_demo:1 private key ----***
repo-sample/deploy/notes.txt:2 assigned secret Tr0u***
findings: 5 in 4 filesFive findings in four files: app/main.py reads its token from the environment, .env.example holds a placeholder, and the test password is too short to match. Now scan your own lab folder.
python3 secretscan.py ..env:1 api key pk-t***
.env:2 assigned secret lab-***
repo-sample/app/settings.py:2 api key pk-l***
repo-sample/app/settings.py:3 assigned secret wint***
repo-sample/data/backup.json:1 key id AKIA***
repo-sample/deploy/id_demo:1 private key ----***
repo-sample/deploy/notes.txt:2 assigned secret Tr0u***
findings: 7 in 5 filesThe two lines for .env are the keys of your own target. The rest is the sample.
4. Write the data flows
Each line of flows.txt has four fields: source, destination, data, and whether it crosses a trust boundary. mapper.py flows counts them and lists what no flow mentions: the tools, the .env file and the log.
cat > flows.txt <<'EOT'
customer | chat endpoint | the message | yes
chat endpoint | retrieval | words of the question | no
retrieval | docs | search | no
docs | model | passages, some written by customers | yes
chat endpoint | model | system prompt, passages, message | yes
model | order_status | tool call with an order id | yes
model | read_doc | tool call with a file name | yes
read_doc | .env | file read through the name | yes
order_status | orders | lookup | no
chat endpoint | target.log | one line for each tool call | no
chat endpoint | customer | the reply | yes
EOT
python3 mapper.py flows flows.txtflows 11, crossing a trust boundary 7, not in any flow: noneSeven flows cross a boundary, and each is a place for a test case in lesson 3. The flow read_doc | .env should surprise you: the model, which a customer can steer, can reach a file with keys in it.
Your turn
A colleague drew a map of the same system and saved it as flows-draft.txt. It is a copy of the first eight lines of your flows.txt.
flows-draft.txt
customer | chat endpoint | the message | yes
chat endpoint | retrieval | words of the question | no
retrieval | docs | search | no
docs | model | passages, some written by customers | yes
chat endpoint | model | system prompt, passages, message | yes
model | order_status | tool call with an order id | yes
model | read_doc | tool call with a file name | yes
read_doc | .env | file read through the name | yes- Run
mapper.py flowson the draft and say what is missing. Then add the line that closes the gap. - The CI server of the sample project runs a job that holds a bearer token (a token that a client sends in a header). Create the file below, then add a pattern named
bearertoPATTERNSinsecretscan.pythat findsBearerfollowed by at least 12 letters, digits, dots, dashes or underscores. Scanrepo-sampleagain.
mkdir -p repo-sample/ci
cat > repo-sample/ci/job.sh <<'EOT'
#!/bin/bash
# start a build on the CI server
curl -H "Authorization: Bearer abc123def456ghi789" https://ci.internal/api/run
EOTCheck yourself
Why does reading the source find more than probing from outside?
A probe sees only what the system answers. The source shows every route, tool, file and setting, including those that no request reaches today.
The scanner prints "pk-l***" and not the whole key. Why?
The output is saved, mailed and pasted into reports. Four characters are enough to find the line.
A flow "docs to model" crosses a trust boundary, but the docs belong to the shop. Why?
Some documents hold text that customers wrote, such as reviews. The model cannot tell data from an instruction, so you mark the flow by its least trusted writer.
Field notes
- Make the map before the test and keep it with the report, so that the reader can rank findings by what the system touches.
- A scanner finds shapes, not truth: expect false positives (example values) and false negatives (a secret with no known shape). Add a pattern for each secret type of your client.
- A secret that was ever committed is leaked, even if the file is deleted later. The fix is a new secret and a clean history.
- MITRE ATLAS has a tactic called Reconnaissance for AI systems. It tells you which parts of this map an attacker can build from outside.