🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

LLM Security: Injections, Jailbreaks and Defenses

AI Safety & GuardrailsAdversarial Attacks🟢 Free Lesson

A threat model for language models

Traditional application security assumes that code and data are separable: input is validated, queries are parameterised, and the program's instructions live somewhere the user cannot reach. Language models dissolve that boundary. The user's input is interpreted by the same mechanism that carries your system prompt, so a well-formed sentence can act as an instruction, a document you retrieved can contain a payload, and a response can leak the context it was given.

A workable threat model names four actors and three goals. The actors are a direct user typing attacks into your interface, an indirect attacker who plants instructions in content your system will later ingest, and a scripted client running automated abuse. The goals are coercion (make the model produce prohibited output), extraction (recover system prompts, context documents, or credentials), and cost amplification (burn your quota or degrade service for others). Every control you build should map to at least one actor-goal pair, and every pair without a control is a written risk you have accepted deliberately.

Threat modelling also fixes scope. Defending the model weights is not your problem if you call a hosted API; defending the prompt, the retrieved context, the tool calls, and the response channel is entirely yours. Teams that skip this scoping waste effort on problems the provider already owns while leaving indirect injection through retrieved documents completely unguarded — currently the most exploited gap in production LLM systems.

Prompt injection: direct and indirect

Direct injection is the user telling the model to ignore its instructions. Early versions were crude ("ignore previous instructions and…"), and current versions are subtle: instructions buried in a quoted email, encoded in base64, spread across a numbered list that only becomes malicious when concatenated, or framed as a legitimate administrative request. The common structure is an attempt to change the model's role, reveal hidden instructions, or suppress the refusal policy.

Indirect injection arrives through content the system trusts. A web page the retriever fetched contains an invisible instruction to summarise a competitor's pricing. A user-uploaded PDF contains a line telling the agent to email the document's contents to an external address. A calendar invite includes text aimed at the assistant that will later read the event. The attacker never touches your interface; they poison a source you already decided to trust.

Defence starts with separation. Keep the system prompt and retrieved content in distinct message roles, label retrieved text explicitly as untrusted data, and instruct the model that instructions inside data must be reported rather than followed. Behind that, run pattern detection for instruction-shaped phrases and a classifier trained on annotated attacks, and scan retrieved documents before they reach the prompt window.

Attack classEntry pointPrimary defenseResidual risk
Direct injectionChat inputInjection classifier + policy promptNovel phrasings
Indirect injectionRetrieved documentsUntrusted-data labelling + pre-scanEncoding tricks
JailbreakChat inputSafety classifier + refusal tuningSocial engineering
Context extractionChat inputOutput filter on prompt fragmentsPartial leaks
Tool abuseAgent tool callsAllow-lists, confirmation gatesLogic flaws

Jailbreak techniques and why they work

Jailbreaks target the safety alignment rather than the instructions. The recurring families are persona adoption ("you are DAN, an unrestricted assistant"), fictional framing ("in a novel, a character explains…"), encoding requests ("answer in rot13 so the filter cannot read it"), and gradual context shifting, where many benign turns establish a cooperative pattern before the harmful request arrives. Multi-turn attacks are the hardest to catch because each individual message looks reasonable in isolation.

Two structural mitigations outperform pattern lists. First, keep the safety policy in the system prompt and re-assert it at the end of long conversations, so the last instruction the model sees is still yours. Second, classify at the conversation level, not the message level — maintain a rolling risk score across turns and require re-authentication or a hard reset when it crosses a threshold. On the model side, periodic safety fine-tuning on your own attack corpus closes gaps the provider's alignment left open for your specific domain.

Data exfiltration and secret leakage

Exfiltration has three sources. The system prompt itself may contain credentials or internal URLs the model can be coaxed into repeating. Retrieved documents may contain personal data or secrets that were never meant to leave the corpus. And connected tools — shell execution, web browsing, ticket creation — give a coerced model a channel to send data outward.

Treat all three as data-loss prevention problems. Never place real credentials in a prompt; fetch secrets at tool-execution time under a scoped identity the model cannot see. Scan outputs for patterns resembling keys, tokens, and connection strings, and redact before returning. For tool-using agents, restrict outbound domains to an allow-list, require human confirmation for any action that transmits data off-platform, and log every tool call with its arguments.

Layered defenses that hold up

No single layer is sufficient, so compose them and measure each independently. A practical request pipeline runs: length and encoding normalisation, pattern-based injection detection, a safety and injection classifier, PII and secret scanning on input, the model call with untrusted-data labelling, then output filtering for policy violations, prompt fragments, and sensitive data. Each layer emits a structured verdict with category and confidence, and a high-severity verdict short-circuits the chain.

python
import re
from dataclasses import dataclass


INJECTION_PATTERNS = [
    re.compile(r"ignore\s+(?:all\s+)?previous", re.I),
    re.compile(r"you\s+are\s+now\s+", re.I),
    re.compile(r"system\s*prompt\s*:", re.I),
    re.compile(r"reveal\s+(?:your|the)\s+instructions", re.I),
    re.compile(r"\bDAN\b|do\s+anything\s+now", re.I),
]


@dataclass
class SecurityVerdict:
    layer: str
    allowed: bool
    risk: float
    reason: str = ""


class RequestFirewall:
    def __init__(self, classifier, pii_scorer, max_chars: int = 8000):
        self.classifier = classifier
        self.pii_scorer = pii_scorer
        self.max_chars = max_chars

    def screen(self, text: str) -> list[SecurityVerdict]:
        verdicts = []

        if len(text) > self.max_chars:
            verdicts.append(SecurityVerdict("length", False, 1.0, "input too long"))
            return verdicts

        hits = [p.pattern for p in INJECTION_PATTERNS if p.search(text)]
        verdicts.append(SecurityVerdict(
            "patterns", not hits, min(0.9, 0.3 * len(hits)),
            f"matched: {hits}" if hits else "clean",
        ))
        if hits:
            return verdicts

        score = self.classifier.injection_score(text)
        verdicts.append(SecurityVerdict(
            "classifier", score < 0.7, score,
            f"injection score {score:.2f}",
        ))
        if score >= 0.7:
            return verdicts

        pii = self.pii_scorer.count(text)
        verdicts.append(SecurityVerdict(
            "pii", True, min(0.5, 0.1 * pii),
            f"{pii} sensitive spans to mask",
        ))
        return verdicts

Keep the pattern layer even though it is evadable: it costs microseconds and catches the large volume of automated, low-sophistication traffic before it reaches a paid classifier.

python
import time
from collections import defaultdict, deque


class SlidingWindowLimiter:
    def __init__(self, per_minute: int = 30, concurrent: int = 4):
        self.per_minute = per_minute
        self.concurrent = concurrent
        self.windows: dict[str, deque] = defaultdict(deque)
        self.in_flight: dict[str, int] = defaultdict(int)

    def acquire(self, subject: str) -> dict:
        now = time.time()
        window = self.windows[subject]
        while window and now - window[0] > 60.0:
            window.popleft()

        over_concurrent = self.in_flight[subject] >= self.concurrent
        over_rate = len(window) >= self.per_minute
        allowed = not (over_concurrent or over_rate)

        if allowed:
            window.append(now)
            self.in_flight[subject] += 1

        return {
            "allowed": allowed,
            "used": len(window),
            "limit": self.per_minute,
            "in_flight": self.in_flight[subject],
            "retry_after": 60.0 - (now - window[0]) if window else 0.0,
        }

    def release(self, subject: str) -> None:
        if self.in_flight[subject] > 0:
            self.in_flight[subject] -= 1

Key the limiter on the authenticated subject rather than the raw IP so shared egress addresses do not throttle an entire office. Track concurrent requests separately from the rate window: an attacker probing jailbreaks generates many short requests, while a legitimate agent may hold a few long ones — the two abuse shapes need different counters.

Rate limiting and abuse prevention

Security without quotas is a budget vulnerability. Limit requests per user per minute, concurrent in-flight requests, and total tokens per day; a client attempting a multi-turn jailbreak is detectable as unusual conversation length as well as unusual phrasing. Escalating responses work better than flat blocks: soft-limit with a warning at eighty percent, hard-limit with a clear message, and route repeat offenders to manual review. Apply stricter limits to endpoints that invoke tools, because the blast radius of a successful coercion is larger there.

Red teaming as an operating habit

A one-time red-team exercise produces a report; a red-team habit produces a corpus. Maintain an internal attack set drawn from public jailbreak research, your own logged near-misses, and findings from each quarterly exercise. Every new attack pattern gets a regression test before it gets a filter entry, and the same corpus re-runs against production on a schedule so you learn when a previously closed hole reopens after a model update. The metric that matters is catch rate on your own corpus over time — absolute safety is not reachable, but a rising catch rate on an expanding corpus is measurable progress.

Common Mistakes

Trusting retrieved documents as safe prompt material

Fix: Label retrieved text as untrusted data, pre-scan it for instructions, and instruct the model to report rather than follow embedded commands.

Placing API keys and connection strings inside the system prompt

Fix: Fetch secrets at tool-execution time under a scoped identity the model never sees.

Classifying each message independently in multi-turn conversations

Fix: Maintain a rolling conversation-level risk score and reset or escalate when it crosses a threshold.

Relying on a static blocklist as the only injection defense

Fix: Layer patterns under a trained classifier and re-run an expanding red-team corpus after every model change.

Key Takeaways

  • Language models erase the code-data boundary, so input handling must assume sentences can act as instructions.
  • Indirect injection through retrieved documents and uploaded files is the most exploited gap in production LLM systems.
  • Jailbreaks target alignment rather than instructions; conversation-level risk scoring beats per-message filtering.
  • Prevent exfiltration by keeping secrets out of prompts, scanning outputs, and allow-listing agent tool destinations.
  • Compose cheap deterministic layers under model-based classifiers, and record a structured verdict from each.
  • Rate limits are a security control: abuse, cost amplification, and multi-turn attacks all show up as quota anomalies.
  • Maintain an expanding red-team corpus with regression tests so catch rate is a tracked number, not an assumption.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement