Core / Securing LLM applications
Securing LLM applications cheat sheet
Set up (lesson 0)
| Task | Command or code |
|---|---|
| List the models of the local server | curl -s http://127.0.0.1:11434/api/tags |
| Prove that the lab works | python3 labcheck.py |
Build the bot and break it (lesson 1)
| Task | Command or code |
|---|---|
| Ask the bot with a seed and sampling | bot.ask(prompt, seed=0, temperature=0.7, max_tokens=60) |
| Run each attack N times and count successes | run(ask, TESTS) |
| Print an answer with its quotes and line ends | repr(answer) |
| Measure the baseline | python3 attack.py |
Indirect injection (lesson 2)
| Task | Command or code |
|---|---|
| Summarise a review | bot.summarise(review, seed=0) |
| Measure the hidden-line tests | python3 attack2.py |
| Add a sentence to the summary prompt and measure | python3 try_fix2.py |
Secrets (lesson 3)
| Task | Command or code |
|---|---|
| Measure the leak of a code in the prompt | python3 leak.py |
| Hash a code with SHA-256 | hashlib.sha256(code.encode()).hexdigest() |
| Compare two hashes without a timing leak | hmac.compare_digest(given, stored) |
| Measure the bot with the code kept in the application | python3 fixed.py |
Sensitive data (lesson 4)
| Task | Command or code |
|---|---|
| Put only one customer record in the prompt | system_one(user) |
| Remove e-mails and card-like numbers | pii.redact(text) |
| Keep only letters and digits, in lower case | squash(text): re.sub(r"[^a-z0-9]", "", text.lower()) |
| Measure one set-up of the bot | python3 pii.py all |
| Measure the set-ups that you name | python3 pii.py all-filter one one-filter |
| Mark a test of an honest request (a fourth item) | ("my-order", prompt, check, True) |
Model output (lesson 5)
| Task | Command or code |
|---|---|
| Escape an answer for HTML | html.escape(text) |
| List the inline Markdown images of an answer from other hosts (it misses other forms) | foreign_images(answer) |
| Measure the page | python3 unsafe.py |
| Sign an answer record with a secret key | sign(record): hmac.new(KEY, json.dumps(record, sort_keys=True).encode(), hashlib.sha256).hexdigest() |
| Check a record before use | verified(record, signature) |
| Count the pairs whose outcome differs when one group word differs | sum(offered(a) != offered(b) for a, b in pairs) |
Database queries (lesson 6)
| Task | Command or code |
|---|---|
| Run a query with a value that cannot become SQL | db.execute("SELECT id FROM orders WHERE customer = ? AND item LIKE ?", (user, f"%{word}%")) |
| Accept a word only if the whole text fits | re.fullmatch(r"[A-Za-z0-9]{1,30}", word) |
| Measure the weak and the safe query | python3 sql_unsafe.py and python3 sql_safe.py |
Tools and approval (lesson 7)
| Task | Command or code |
|---|---|
| Let the bot only ask for a refund | request_refund(order_id, amount) |
Refuse True as an amount | type(amount) in (int, float) |
| Measure one tool set-up | python3 agent.py approval |
Cost and abuse (lesson 8)
| Task | Command or code |
|---|---|
| Read the tokens and the time of one request | chat(messages, full=True) |
| Limit requests for each user | RateLimit(5, 60).allow(user, now=t) |
| Stop waiting for a slow answer | future.result(timeout=120) |
| Measure the four limits | python3 cost.py |
| Refuse a wrong key, type, size or number of parts before the model | admit(key, [("text/plain", data)]) |
Guardrails (lesson 9)
| Task | Command or code |
|---|---|
| Refuse a known attack phrase | input_blocked(text) |
| Refuse an answer with no shop topic | on_topic(answer) |
| Measure the guardrails and the false refusals | python3 guardrail.py |
Secure design patterns (lesson 10)
| Task | Command or code |
|---|---|
| Put outside text in a labelled block | wrap(text) |
| Parse a JSON answer | json.loads(raw) |
| Find the words of 4 letters or more | set(re.findall(r"[a-z]{4,}", text.lower())) |
| Compare the weak and the pattern app | python3 compare.py |
Test suite (lesson 11)
| Task | Command or code |
|---|---|
| Run the suite on a module and judge it | python3 suite.py vulnerable 0.2 |
| Judge a saved results file with no model calls | python3 suite.py --from results-patterns.json 0.3 |
| Run a command only when the gate passes | python3 suite.py --from results-patterns.json 0.5 && echo "gate passed" |
| Read the exit code of the last command | echo "exit code $?" |
Jailbreak cases (lesson 12)
| Task | Command or code |
|---|---|
| Judge a reply for the planted code, spaced, backwards or in halves | leaked(text) |
| Replay the replies written for the lab (not recorded from a model), with no model | python3 jailbreak.py replay rule-in-prompt |
| Run the cases on your local model | python3 jailbreak.py live rule-in-prompt |
| Read the saved replies of a run | json.load(open('replies-jb-rule-in-prompt-live.json')) |
| Write a text backwards | text[::-1] |
Hardened bot and report (lesson 13)
| Task | Command or code |
|---|---|
| Run the suite on the hardened bot | python3 suite.py safe_bot 0.2 |
| Write the before-and-after report | python3 report.py results-vulnerable.json results-safe_bot.json |
Close the last gap (lesson 14)
| Task | Command or code |
|---|---|
| Refuse an answer that repeats a code of the user | echoed(prompt, answer) |
| Run the suite with that check | python3 suite.py safe_bot2 0.2 |
| Compare the before and after files | python3 report.py results-vulnerable.json results-safe_bot2.json |
Review a chatbot (lesson 15)
| Task | Command or code |
|---|---|
| Show what the app sends to the model | python3 scenario_tests.py audit |
| Run fixed model answers through the app | python3 scenario_tests.py recorded |
| Run the real model, 5 seeds for each test | python3 scenario_tests.py live 5 |
Safety habits
- Attack only your own lab bot, with a made-up canary word and invented data.
- Never put a secret in a prompt, a tool description or a chat history. A rule in a prompt is a request, not a control.
- Put each limit in code: the identity of the user, the amount, the length, the rate, the tool list.
- Keep only the data of the logged-in user in the context.
- Escape or validate every model answer at the place where you use it. Sign a stored answer and verify it before use. Let the model pick a value, not write code. Drop images from a model answer, or show plain text: a pattern list misses forms.
- Let a person approve every action that moves money or data.
- Judge the output of a jailbreak case, not the wording of the input. A phrase blocklist is a first filter, not the control.
- Allow only the kinds of input that the job needs, and refuse the rest at the gateway.
- Report a rate with the number of runs and the model. A count of 0 of 5 is not a rate of 0.
- Keep a control sample of normal questions, and report the honest users that your defences refuse.
- Read a sample of the answers next to the counts.
- Re-run the suite after every change of the model, the prompt or the code.