Zulia Shavaeva← Back to Zulia

Learn / LLM security: prompt injection, jailbreaks, output handling

LLM security: prompt injection, jailbreaks, output handling

Understanding how attackers manipulate LLM inputs and outputs, and how to design applications that resist prompt injection, jailbreaks, and unsafe output handling.

Before the exercises: Start with Step 0 AI and security vocabulary. Coding exercises need Python and an authorised local or API-based model. Start with Step 0 if needed.

Researched on 2026-09-26 with AI assistance. Links and summaries can change; verify details with the original source. Not yet reviewed by a person.

What it is

LLM security is the practice of treating a language model as a component that does not reliably separate instructions from data. Prompt injection exploits exactly that: attacker text placed anywhere in the model's context can override the developer's intent. Role markers such as system, user and tool give the model a hint about provenance, and training can make it weight them, but the preference is behavioural rather than enforced, so it can be argued away by the content itself.21

The field splits into two related problems. Input-side attacks (direct prompt injection, indirect injection through retrieved content, jailbreaks that defeat safety training) and output-side failures, where the application trusts model output and passes it unvalidated into a browser, a shell, a database or a tool call.23

OWASP codifies this as the Top 10 for LLM Applications, whose first entry is prompt injection and which also covers Sensitive Information Disclosure, Improper Output Handling, Excessive Agency and System Prompt Leakage. The 2026 edition maps its risks to NIST, MITRE ATLAS, CWE and the OWASP Top 10 for Agentic Applications.34

Because the model is non-deterministic and the space of malicious phrasings is unbounded, defence is an architecture problem rather than a filtering problem: recent work proposes design patterns that constrain what an agent is allowed to do, accepting less generality in exchange for resistance that does not depend on the model refusing correctly.17

In the job-posting sample

Counts describe 48 postings collected on 24 September 2026. Small role samples do not establish market-wide requirements or explain employer decisions.

44 of 48 postings (92%) ask for it, including all 7 AI Security Architect and all 7 AI Governance / GRC postings in this sample. Cluster denominators are small, so read them as direction, not as a hiring rule.P

The AI/Agent Security Engineer cluster carries the most postings (16 postings, 94%). What those postings describe as the work is application design: separating trusted instructions from untrusted content, scoping tool permissions and validating model output before it reaches a renderer or interpreter.P23

Red team postings ask at a lower rate in this sample (9 postings, 78%). Independently of the counts, the deliverable that gets paid for is judging whether a deployment combines private data, untrusted content and an exfiltration path, and saying what to change.P1

Key terms and concepts

Start with the meaning, then connect it to an example. Use these notes while learning or revising; explaining a term is one part of applying it.

Tokens and tokenisation

Tokens are the units a model processes. For text, a token might be a whole word, part of a word or punctuation. Tokenisation splits input into these units; token counts vary by model and language.10

Example: Two sentences with the same number of words can use different numbers of tokens. Count with the chosen model rather than assuming one word equals one token.

Security connection: Limit input size and output length to control cost and resource use. A token limit does not decide whether the content is safe.

Context window and saved memory

The context window is the model's capacity for the input and output of a request. Instructions, conversation history and tool results share this space. An application may store history elsewhere and select what to include.1112

Example: A saved conversation can contain 200 messages, while the next request includes only recent messages and a summary. Saving a message does not mean the model sees it every turn.

Security connection: Review what enters the context, including retrieved text. Removing text from a request does not delete stored history or logs.

Instruction/data confusion

Chat APIs distinguish system, user and tool messages, and models can be trained to follow an instruction hierarchy. Attackers can still induce a model to follow instructions embedded in untrusted content. Role labels and delimiters do not enforce application access control; validate tool actions outside the model.21

Direct versus indirect prompt injection

Direct injection is a malicious end user typing at the model. Indirect injection plants instructions in data the application will retrieve: web pages, emails, documents, code comments, commit messages, issue descriptions, hidden text. Greshake et al. showed this allows remote exploitation with no direct interface, demonstrated against Bing's GPT-4 powered chat and code completion engines.52

The lethal trifecta

Simon Willison uses the lethal trifecta to describe a risky combination: private data access, untrusted content and an external communication channel. Trace the actual data path and permissions before claiming exploitability. Removing a capability can block that path, but other channels or harmful actions may remain.1

Improper output handling

Model output is untrusted input to whatever consumes it. OWASP lists Improper Output Handling as insufficient validation and sanitisation of output, and the practical cases are familiar web bugs: rendered Markdown or HTML, hidden image tags such as an img src pointing at an attacker host with secrets in the query string, and malicious links presented as helpful content.32

Excessive agency and tool scope

Excessive agency means an application grants more functionality, permission or autonomy than its task requires. A tool that can send attacker-chosen data to an attacker-controlled destination can enable exfiltration. Restrict actions and resources per task, and enforce authorisation outside the model.31

System prompt leakage

An attacker may induce a model to reveal system instructions. Do not store secrets in prompts or rely on hidden instructions to enforce permissions. A leaked prompt can expose configuration or business rules, but leakage and unauthorised data access are different findings.32

Jailbreaks and automated attack search

Jailbreaks attempt to bypass model safety restrictions. Researchers test manual prompts, repeated variations and automated search techniques. Success and transfer to another model depend on the model, settings and evaluation conditions. Record attempts and outcomes rather than assuming a technique will work.62

Constrained agent design

The cited design-patterns paper describes ways to constrain what agents can do after reading untrusted content. Apply a pattern to a specific data flow and permission model. Test which attacks it blocks and which legitimate tasks it limits.79

Use fictional data and authorised sandboxes. Remove employer details and secrets from any portfolio write-up. Time estimates exclude setup. Check model and cloud costs before running tests, set spending limits, and delete lab resources afterwards.

Three exercises

Work through these in order. Open-source code can still incur model, cloud or hardware costs. Record your setup, results and limitations.

1Build an injection catalogue against your own system promptabout 3 h

You can name six distinct injection and jailbreak families, and report per family how many of a fixed number of attempts produced the target behaviour, before and after a keyword filter.26

  1. Write a small chat wrapper around any model you can access locally, with a system prompt that holds a fake secret and a rule never to reveal it.
  2. Run one payload from each family in the OWASP cheat sheet: direct override, system prompt extraction, base64 or hex encoding, typoglycemia, best-of-N variants, role-play jailbreak.
  3. Add a naive blocklist for phrases like 'ignore previous instructions' and re-run the same set.
  4. Record which families still succeed and how many attempts each needed, given non-deterministic responses.
  5. Write a one page table: family, example payload, observed impact, why the filter missed it.

Tools: a local open-weight model runner, Python, OWASP cheat sheet payload families

Check your work
  • Your table has one row per family with the payload, model response and count of target behaviours out of total attempts. Use only synthetic secrets and label them clearly.
  • For every family you can state whether adding the blocklist changed the outcome, including the families where it changed nothing, and the blocklist rule text is quoted in the write-up.
2Indirect injection to exfiltration, then close the trifectaabout 5 h

You can run an end-to-end indirect injection attempt through a document the user never read, report whether it produced an outbound request, and show which single architectural change would remove that path regardless.5123

  1. Build a summariser that fetches a local HTML page and passes it to the model, plus a tool that returns a fake private record.
  2. Host a page containing hidden instructions telling the assistant to read the private record and include an image tag whose URL carries the data.
  3. Render the model's Markdown output in a browser and confirm the outbound request in your own web server log.
  4. Apply three fixes separately: strip HTML and Markdown from output, allowlist outbound hosts, remove private data from the context for this task.
  5. Report which fix removed which leg of the lethal trifecta and what capability each one cost the user.

Tools: Python, a local HTTP server, a local open-weight model runner

Check your work
  • Your own web server log is quoted with its timestamp, showing either a request carrying the fake record or no such request, and the Markdown the model produced is saved next to it.
  • Each of the three fixes is applied on its own and re-tested, with a recorded result, the trifecta leg it removes, and the user capability it costs.
3Measure a defence with AgentDojoabout 8 h

You can quote attack success and task utility numbers for a defence you ran yourself, and argue for a design pattern instead of a detector.87

  1. Install AgentDojo, including the transformers extra needed for the prompt injection detector, and configure a model backend you can access.
  2. Run one suite undefended with the attack that has tool knowledge, and record task utility and attack success.
  3. Re-run the same suite with the tool filter defence, then with the prompt injection detector, and record both numbers again.
  4. For the tasks that still fail, state which agent capability made the attack possible.
  5. Pick one of the design patterns from the ETH Zurich paper, say which of your failing tasks it would remove, and name the utility you lose.

Tools: AgentDojo, Python, a model backend you already have access to

Check your work
  • You can produce AgentDojo run artefacts for all three configurations (undefended, tool filter, injection detector) with suite name, model and package version recorded.
  • Task utility and attack success are reported for each configuration as counts over the suite's cases, and one design pattern is named with the specific failing tasks it would remove and the utility it costs.

Practice questions

Written from the concepts above, not collected from a named employer. Open one, answer it out loud, then tick the points you covered; the score stays in this browser.

Why can't you fix prompt injection by telling the model in the system prompt to ignore instructions found in retrieved content?Instruction/data confusion

Say your answer out loud or write it down, then tick what you covered:

0 of 3 covered

A team wants an assistant that reads the shared support inbox, looks up customer records and can send email. What do you tell them?The lethal trifecta

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

Distinguish a jailbreak from a prompt injection, and explain why the fixes differ.Jailbreaks and automated attack search

Say your answer out loud or write it down, then tick what you covered:

0 of 3 covered

What is improper output handling and how would you test for it in an LLM feature?Improper output handling

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

How do automated jailbreak techniques change how you plan a testing engagement?Universal and Transferable Adversarial Attacks on Aligned Language Models

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

You have to decide between adding an injection detector and redesigning the agent. How do you frame the trade-off?Constrained agent design

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

Your system prompt contains an internal pricing rule and a list of tool names. What is your advice?System prompt leakage

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

How would you evidence to a governance or audit reader that an LLM feature was tested, not just reviewed?OWASP Top 10 for LLM Applications 2026

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

Sources

Every numbered claim above links here. P = the platform's own coding of 48 job postings.

  1. The lethal trifecta for AI agents: private data, untrusted content, and external communication Simon Willison
  2. LLM Prompt Injection Prevention Cheat Sheet OWASP Cheat Sheet Series
  3. Top 10 Risk & Mitigations for LLMs and Gen AI Apps (2025 risk list) OWASP GenAI Security Project
  4. OWASP Top 10 for LLM Applications 2026 OWASP GenAI Security Project
  5. Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection Greshake, Abdelnabi et al. (arXiv)
  6. Universal and Transferable Adversarial Attacks on Aligned Language Models Zou et al. (arXiv)
  7. Design Patterns for Securing LLM Agents against Prompt Injections Beurer-Kellner, Tramèr et al. (arXiv)
  8. AgentDojo: a dynamic environment to evaluate attacks and defenses for LLM agents ETH Zurich SPY Lab (GitHub)
  9. Design Patterns for Securing LLM Agents against Prompt Injections (paper notes) Simon Willison
  10. Tokens and language models Google for Developers
  11. Context windows Anthropic
  12. API and data retention Anthropic

Resources

Free first. Levels: intro means no prior knowledge of this skill; working means you can apply it on a project; advanced means research depth or specialist tooling.

Level Format

Gaps the research could not fill with a good free source: Four existing items (PortSwigger Web LLM attacks labs, HackAPrompt, NVIDIA garak, the OWASP prompt injection prevention cheat sheet) are still worth keeping, but the search and fetch budget ran out before their URLs appeared in a tool result today, so they are not re-listed here; re-verify and restore them.; No free structured course found that ends in a recognised certificate for LLM security; the free options are short or self-guided.; No free hands-on lab found specifically for insecure output handling (LLM output driving XSS, SQL or shell) separate from prompt injection labs.; No free GRC artefact found that maps prompt injection and output handling controls to ISO/IEC 42001 or EU AI Act obligations at control level.; No free vendor-neutral lab found for multimodal or image-borne injection.