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 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.
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.
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 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
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
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 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
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 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
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.
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
- 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.
- 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.
- Add a naive blocklist for phrases like 'ignore previous instructions' and re-run the same set.
- Record which families still succeed and how many attempts each needed, given non-deterministic responses.
- 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.
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
- Build a summariser that fetches a local HTML page and passes it to the model, plus a tool that returns a fake private record.
- Host a page containing hidden instructions telling the assistant to read the private record and include an image tag whose URL carries the data.
- Render the model's Markdown output in a browser and confirm the outbound request in your own web server log.
- Apply three fixes separately: strip HTML and Markdown from output, allowlist outbound hosts, remove private data from the context for this task.
- 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.
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
- Install AgentDojo, including the transformers extra needed for the prompt injection detector, and configure a model backend you can access.
- Run one suite undefended with the attack that has tool knowledge, and record task utility and attack success.
- Re-run the same suite with the tool filter defence, then with the prompt injection detector, and record both numbers again.
- For the tasks that still fail, state which agent capability made the attack possible.
- 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.
- The lethal trifecta for AI agents: private data, untrusted content, and external communication Simon Willison
- LLM Prompt Injection Prevention Cheat Sheet OWASP Cheat Sheet Series
- Top 10 Risk & Mitigations for LLMs and Gen AI Apps (2025 risk list) OWASP GenAI Security Project
- OWASP Top 10 for LLM Applications 2026 OWASP GenAI Security Project
- Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection Greshake, Abdelnabi et al. (arXiv)
- Universal and Transferable Adversarial Attacks on Aligned Language Models Zou et al. (arXiv)
- Design Patterns for Securing LLM Agents against Prompt Injections Beurer-Kellner, Tramèr et al. (arXiv)
- AgentDojo: a dynamic environment to evaluate attacks and defenses for LLM agents ETH Zurich SPY Lab (GitHub)
- Design Patterns for Securing LLM Agents against Prompt Injections (paper notes) Simon Willison
- Tokens and language models Google for Developers
- Context windows Anthropic
- 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.
- introThe lethal trifecta for AI agents: private data, untrusted content, and external communication Simon Willison, Guide freeGives you a one-sentence test for whether an agent or MCP setup can be turned into a data exfiltration path, with real vendor incidents listed.EngineerArchitectGovernanceConsultant
- introHackAPrompt Learn Prompting, Hands-on lab freeBuilds hands-on intuition for jailbreak and injection phrasing by forcing you to defeat graded defences before you test real systems.Red teamerEngineerConsultant
- introAgent Breaker (formerly Gandalf) Lakera, Hands-on lab freeLets you feel how guardrails fail by breaking increasingly defended chat and agent targets in the browser, with no setup or API keys.Red teamerEngineerConsultant
- introLLMVault: intentionally vulnerable OWASP LLM Top 10 training platform CyberSunil (GitHub), Hands-on lab freeNew self-hosted lab covering prompt injection, RAG and agent flaws, so pentesters and AppSec engineers can practise the 2026 Top 10 categories against broken targets.
- introRed Teaming LLM Applications DeepLearning.AI and Giskard, Course, about 1.5 h Free access may be time-limited; paid PRO assessments or accomplishments. Check current enrolment terms.Walks you through attacking sample chatbots with prompt injections, then automating the same probes, so you can run a first assessment yourself. Check the beta access terms; this listing does not promise permanent free access.Red teamerEngineerConsultant
- workingGuidelines for secure AI system development UK NCSC with CISA and international partners, Standard freeGives you lifecycle controls (secure design, deployment, operation) to attach prompt injection and output handling requirements to, in language auditors accept.ArchitectGovernanceConsultantEngineer
- workingPrompt Injection Prevention Cheat Sheet OWASP Cheat Sheet Series, Guide, about 1 h freeGives you a control checklist for input handling, privilege limits and output encoding to apply during code and design review.EngineerArchitectConsultant
- workingWeb LLM attacks PortSwigger Web Security Academy, Hands-on lab, about 4 h freeExploit LLM-driven APIs, indirect injection via data sources and unsafe output handling in graded labs that mirror real web app tests.Red teamerEngineerConsultant
- workingPrompt Airlines AI Security Challenge Wiz, Hands-on lab, about 3 h freeWork five stages against a customer service chatbot, including API and system prompt abuse, to practise a full app-level attack chain.Red teamerEngineerConsultant
- workingNIST AI 100-2e2025: Adversarial Machine Learning, A Taxonomy and Terminology of Attacks and Mitigations NIST, Standard freeGives you the government-recognised naming for direct and indirect prompt injection and their mitigations, which regulators and enterprise reviewers expect you to use.GovernanceArchitectResearcherConsultant
- workingMITRE ATLAS MITRE, Standard freeLets you map jailbreak and injection activity to tactics and techniques with documented case studies, so detection and reporting line up with ATT&CK habits.Red teamerArchitectGovernanceConsultantResearcher
- workinggarak: LLM vulnerability scanner NVIDIA, Tool freeRun a broad probe set against a model or app to get a first list of injection, leakage and jailbreak weaknesses to triage.Red teamerEngineerResearcher
- workingNot what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection Greshake et al. (arXiv), Paper freeThe paper that named indirect prompt injection; read it to build threat models covering retrieved documents, email and web content as attack channels.Red teamerEngineerArchitectResearcherConsultant
- workingDamn Vulnerable LLM Agent Reversec Labs (formerly WithSecure Labs), Hands-on lab freeYou hijack a ReAct agent's Thought/Action/Observation loop and chain it into SQL injection, which is the pattern behind most real agent findings.Red teamerEngineerConsultant
- workingPromptfoo LLM red teaming documentation Promptfoo, Tool freeShows how to generate adversarial inputs, grade responses and wire the run into CI/CD, separating model-layer from application-layer test goals.EngineerRed teamerConsultant
- workingOWASP Top 10 for LLM Applications 2026 OWASP GenAI Security Project, Standard freeNew edition with re-ranked risks drawn from reported incidents and mappings to NIST, MITRE ATLAS, CWE and the Agentic Top 10; everyone citing the 2025 list should switch.
- workingagent-threat-rules: open detection-rule standard for AI agent threats Agent Threat Rule project (GitHub), Tool freeExecutable, testable rules for prompt injection, tool poisoning, context exfiltration and MCP attacks give SOC analysts and engineers a shared detection format instead of ad hoc regexes.
- workingAI Red Teamer Job Role Path Hack The Box Academy, with Google, Course Paid Academy path; confirm which subscription or module purchases include this path and exam.Work through dedicated prompt injection and LLM output-handling modules with graded exercises, then evidence the skill on a profile employers recognise.Red teamerEngineerConsultant
- advancedAgentDojo: environment for evaluating prompt injection attacks and defences for LLM agents ETH Zurich SPY Lab, Hands-on lab freeLets you measure attack success and utility loss for a candidate defence on realistic tool-using tasks instead of arguing from single examples.ResearcherRed teamerEngineer
- advancedDesign Patterns for Securing LLM Agents against Prompt Injections Beurer-Kellner et al. (arXiv), Paper freeGives you named architectural patterns (action selector, plan then execute, context minimisation and others) to propose when filtering alone is not enough.ArchitectEngineerResearcherConsultant
- advancedUniversal and Transferable Adversarial Attacks on Aligned Language Models (GCG) Zou et al. (arXiv), Paper freeExplains optimised adversarial suffixes and their transfer between models, the baseline every jailbreak benchmark and guardrail evaluation still compares against.ResearcherRed teamerEngineer
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.
Paid options
These courses and certifications cover parts of this topic. Compare their syllabus and practice format with the free resources. An exam listing is not a training course. Showing 6 of 14: ones postings name first, then the most focused on this skill. All paid options.
- Cost
- Paid exam; optional online training is separate. Check current member and non-member prices in the IAPP store.
- Duration
- 100 questions, 2.75 hours plus a 15-minute break; exam must be taken within one year of purchase
- Format
- exam only
- Prerequisite
- none stated
- Renewal
- 2-year term; 20 continuing education credits plus a maintenance fee (covered by IAPP membership, otherwise USD 250 at recertification)
- Provider page checked
- 2026-09-26
- In the 48 postings
- Named in 1 of 48 postings: a plus.
Study or assessment format: A structured exam syllabus on AI governance, law and lifecycle risk. Optional training is a separate product; check what your employer or contract requires.
Related free material: The NIST AI Risk Management Framework, the EU AI Act text, ISO/IEC 42001 summaries and OWASP LLM guidance are free and cover most of the same subject matter.
- Cost
- not stated on the provider page
- Duration
- 16 hours on-demand, 16 CPE credits, six courses plus assessments
- Format
- self-paced
- Prerequisite
- familiarity with cybersecurity principles, roles and frameworks recommended but not required
- Provider page checked
- 2026-09-26
- In the 48 postings
- Not named in any of the 48 postings.
Study or assessment format: CPE credit and a Credly badge for structured coverage of AI regulation alignment, secure-by-design AI planning and AI blind spots in security tooling, which suits GRC leads who need ISC2 CPEs anyway.
Related free material: NIST AI RMF, the EU AI Act text, ISO/IEC 42001 summaries and free regulator guidance cover the alignment and governance content without a fee.
- Cost
- not stated on the provider page
- Duration
- 90-question exam; six-month eligibility period from registration to sitting the exam
- Format
- exam only
- Prerequisite
- An active CISM or CISSP certification is required, plus a US$50 application processing fee; five years from passing the exam to apply
- Renewal
- ISACA Continuing Professional Education policy applies; the annual credit number is not stated on the page we fetched
- Provider page checked
- 2026-09-26
- In the 48 postings
- Not named in any of the 48 postings.
Study or assessment format: An AI security management credential requiring an active CISM or CISSP. Review its governance, risk and technology domains before deciding whether it fits your responsibilities.
Related free material: The same ground is largely covered free by the NIST AI RMF, OWASP's LLM and agentic security material and ISO/IEC 42001 overviews.
- Cost
- not stated on the provider page
- Duration
- 11 modules; self-paced, sold by access duration (lab extensions in 30-day increments for Course & Cert Bundle learners)
- Format
- self-paced
- Prerequisite
- As stated: advanced level, for experienced cybersecurity practitioners, red teamers and AI professionals; solid cybersecurity fundamentals and basic familiarity with AI systems including LLMs
- Renewal
- OSAI does not expire; the OSAI+ designation expires 3 years from issuance, maintained by one of three continuing education paths. Passing OSAI+ may qualify for 40 CPE points, self-submitted to ISC2
- Provider page checked
- 2026-09-26
- In the 48 postings
- Not named in any of the 48 postings.
Study or assessment format: A specialist practical assessment for AI red teaming. Check the current syllabus, eligibility and lab access; recognition of another certificate does not establish demand for this one.
Related free material: OWASP LLM Top 10, prompt injection writeups and free CTF-style prompt hacking games cover most attack classes with no proctored assessment.
- Cost
- not stated on the provider page
- Duration
- 3 days instructor-led or 18 hours self-paced, 18 CPEs
- Format
- mixed
- Prerequisite
- not stated
- Provider page checked
- 2026-09-26
- In the 48 postings
- Not named in any of the 48 postings.
Study or assessment format: Structured practice in using AI tooling as part of an offensive engagement, with an associated GIAC exam. Confirm whether the exam is included.
Related free material: Open-source offensive AI tooling, conference talks and the MITRE ATLAS case studies cover most of the individual techniques without a fee.
- Cost
- not stated on the provider page
- Duration
- 30+ guided exercises, 60 days browser-based lab access, 36 CPE points, one exam attempt included
- Format
- self-paced
- Prerequisite
- not stated
- Provider page checked
- 2026-09-26
- In the 48 postings
- Not named in any of the 48 postings.
Study or assessment format: One of the few paid exams scoped to Model Context Protocol specifically: attacking, assessing and hardening MCP servers including tool poisoning, prompt injection, supply chain and agentic defences.
Related free material: The MCP specification, OWASP agentic security guidance and public MCP tool-poisoning research already describe these attack patterns, and you can run a vulnerable MCP server locally for free.