LevelUpWith

Explore / AI Engineering

Securing LLM Apps and Agents: Attack, Defend, Harden

Model the threats to tool-using agents, break them with prompt injection and exfiltration, then harden them with least privilege, sandboxing, a vetted MCP and skill supply chain, guardrails, red-teaming and incident response.

Read lesson 1 free →

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor.

Photographic 3D course artwork for Securing LLM Apps and Agents: Attack, Defend, Harden

Expert · 40 levels · 4 free · Created Nov 2026 · Professionally curated by levelupwith.com

What's inside

  1. Level 1: Anatomy of an Agent as an Attack SurfaceFree
    Take apart the agent loop (model, system prompt, context window, tools, data sources, web access and memory) and see that every part an attacker can write to or read from is attack surface.
    • Draw the loop of a small tool-using agent and mark every input that comes from outside the developer's control
    • Explain why an agent that can take actions carries more risk than a chatbot that only returns text
    • List which assets a coding agent on their own laptop can reach: files, credentials, network and shell
  2. Level 2: Trust Boundaries and Data FlowsFree
    Build a data-flow threat model of an agent that marks where trusted instructions and untrusted content cross, and who the principals are: user, developer, tool owner and third parties.
    • Produce a data-flow diagram for a sample email-and-calendar agent with its trust boundaries marked
    • Sort each piece of context into trusted, semi-trusted or untrusted by who can influence it
    • Name the attacker for each boundary and describe what that attacker controls
  3. Level 3: One Channel: Why Instructions and Data Mix
    See why a language model has no hard line between code and data, unlike a parameterised SQL query, and why that makes every token in context a possible instruction.
    • Contrast SQL injection, which parameterised queries fix, with prompt injection, which has no equivalent fix, in a short Python or TypeScript example
    • Show that delimiters and 'ignore any instructions in the data' wording lower but do not remove injection success on one model
    • Explain why role tags and system prompts are soft preferences the model learned, not boundaries it enforces
  4. Level 4: Jailbreaks vs Prompt Injection
    Separate jailbreaks (a user getting past the model's safety training) from prompt injection (third-party content taking over the application's intent), and see why they need different defences.
    • Classify a set of real-style attack transcripts as jailbreak, direct injection or indirect injection
    • Explain why a model that resists jailbreaks well can still be fully open to indirect injection
    • Name who is harmed and who is the attacker in each case, so the right owner fixes it
  5. Level 5: Tools, Excessive Agency and the Confused Deputy
    Treat each tool as a capability given to whoever controls the model's context, and learn how too much functionality, permission or autonomy turns an agent into a confused deputy.
    • Audit a tool list for too much functionality, too much permission and too much autonomy
    • Describe a confused-deputy attack where an agent uses the user's authority on an attacker's behalf
    • Rewrite one broad tool, such as run_sql or send_http, as a narrower one and explain the risk it removes
  6. Level 6: Memory, RAG and Persistent State Risks
    Learn how retrieval indexes, vector stores, long-term memory and conversation history let an attack persist across sessions and users.
    • Show how one poisoned document in a RAG corpus reaches answers for many users
    • Find the places where an agent writes to memory that it will later read as trusted context
    • Propose provenance tags and per-tenant isolation for a shared vector store
  7. Level 7: OWASP Top 10 for LLMs and Agentic Apps
    Place agent risks in the OWASP Top 10 for LLM Applications (the 2026 edition, with the 2025 numbering for comparison) and the OWASP Top 10 for Agentic Applications (ASI01 to ASI10, published December 2025).
    • Map each threat from their Level 2 diagram to an OWASP LLM entry and an OWASP agentic entry, such as ASI01 Agent Goal Hijack or ASI02 Tool Misuse
    • Explain how the agentic list differs in scope from the LLM application list
    • Check entry names and numbers against the official genai.owasp.org pages instead of secondary summaries
  8. Level 8: MITRE ATLAS and a Written Threat Model
    Use MITRE ATLAS tactics and techniques to describe how an attack unfolds end to end, then write a short threat-model document that the rest of the course will test and harden.
    • Express one agent attack as a chain of ATLAS tactics, from reconnaissance to exfiltration or impact
    • Write a one-page threat model for a sample agent covering assets, attackers, entry points and ranked risks
    • Explain where ATLAS and OWASP overlap and when to reach for each
  9. Level 9: Lab Setup: A Multi-Model Vulnerable Agent
    Build a small, deliberately vulnerable tool-using agent in Python or TypeScript that can switch between Claude, OpenAI, Gemini and a local open-weight model, so every attack in this phase can be compared side by side.
    • Run the same agent loop and tool schema against at least two hosted APIs and one local open-weight model
    • Log every prompt, tool call and tool result to a local trace file for later analysis
    • Keep the lab safe with fake data, a canary secret and no real credentials or outbound network access
  10. Level 10: Direct Injection and Hidden Context Exposure
    Run direct prompt injection to override application instructions and pull out system prompts, tool schemas and other hidden context, and learn why hidden context must never hold secrets.
    • Extract the system prompt and tool definitions from the lab agent on more than one model
    • Measure success rate over repeated trials instead of trusting a single attempt
    • Move a credential out of the prompt into server-side code and explain why that is the only real fix
  11. Level 11: Indirect Injection via Web Pages and Documents
    Plant instructions in web pages, PDFs and files that the agent reads while doing a normal task, and watch them take over its goal without the user ever typing anything hostile.
    • Build a poisoned web page and document that redirect the lab agent's task
    • Hide payloads with tricks such as white-on-white text, HTML comments and metadata, and show which ones survive each model's input pipeline
    • Record which models follow the injected goal and how often
  12. Level 12: Injection via Tool Outputs, Email and MCP
    Deliver injections through tool results, such as email bodies, issue trackers, API responses and MCP tool output, and through invisible Unicode characters, the channels agents trust most by default.
    • Inject the lab agent through a fake email or ticket returned by a tool call
    • Encode a payload in invisible Unicode tag characters and write a detector that strips or flags them
    • Explain why tool output must be treated as untrusted even when the tool itself is first-party
  13. Level 13: Exfiltration Through Rendered Output
    Steal data through what the client renders, such as markdown images, auto-fetched links and link unfurling, the zero-click pattern behind EchoLeak.
    • Exfiltrate the lab canary secret through a markdown image URL to a local listener
    • Block the channel with an image-domain allowlist or a Content Security Policy and confirm the attack fails
    • List the rendering features in their own UI that could leak data without a click
  14. Level 14: Exfiltration Through Tools and Side Channels
    Move data out through the agent's own actions, such as HTTP and fetch tools, email sending, file writes to shared places, code execution and DNS lookups, even when output rendering is locked down.
    • Chain an indirect injection with a send or fetch tool to leak the canary
    • Find covert channels such as DNS lookups, URL query strings and commit messages in a sample agent's tool set
    • Explain why output filtering alone cannot stop tool-based exfiltration
  15. Level 15: Why Prompt Injection Is Not Solved
    Evaluate model-side defences, including instruction hierarchy training, spotlighting and datamarking, and vendor injection classifiers, against adaptive attacks, and see why success rates fall but never reach zero.
    • Apply spotlighting or datamarking to the lab agent and measure the change in attack success rate on each model
    • Show that an attacker who adapts to a fixed defence gets their success rate back up
    • Explain why a 1% bypass rate is still a failure when attackers can retry at scale
  16. Level 16: Spotting the Lethal Trifecta
    Learn to spot the lethal trifecta (access to private data, exposure to untrusted content and a way to communicate externally) and treat any agent that has all three as exploitable.
    • Audit three agent configurations and mark which legs of the trifecta each one has
    • Show that combining tools from separate MCP servers can complete the trifecta even when each server looks safe alone
    • Write a trifecta checklist to add to the Level 8 threat model
  17. Level 17: Breaking a Leg: Remove Egress or Exposure
    Defend by architecture instead of detection: remove one leg of the trifecta per task or session, such as cutting outbound communication or untrusted input, and accept the loss of features that comes with it.
    • Re-run the Level 13 and 14 attacks after removing the agent's outbound channels and confirm they fail
    • Design a 'tainted session' rule that drops external tools once untrusted content enters the context
    • Explain the usefulness cost of each leg removed and how to explain it to product owners
  18. Level 18: The Dual LLM Pattern
    Split the agent into a privileged LLM that plans and calls tools and a quarantined LLM that reads untrusted content but cannot act, passing results by reference.
    • Build a dual-LLM version of the lab agent where untrusted text reaches the planner only as opaque variables
    • Show that the Level 11 web-page injection can no longer reach tool calls
    • Find the remaining gaps, such as a quarantined model that lies in its output or a user who pastes results back in
  19. Level 19: Plan-Then-Execute and Control-Flow Integrity
    Fix the agent's plan before it reads untrusted data, then track where data flows, as in CaMeL-style designs, so injected content can change values but not which actions run.
    • Build a plan-then-execute loop that commits to a tool sequence before reading any untrusted content
    • Add simple provenance tags to values and block tagged data from flowing into sensitive tool arguments
    • Name the attacks plan-then-execute does not stop, such as poisoned arguments within an approved plan
  20. Level 20: Capability-Scoped Tools and Policy Enforcement
    Design narrow tools with typed, limited arguments and enforce permission rules in deterministic code outside the model, so a fully hijacked model still cannot do damage.
    • Replace a generic send_email tool with one limited to approved recipients and templates, in Python or TypeScript
    • Write a policy layer that validates every tool call against per-task capabilities before it runs
    • Show that the hardened tools defeat the Level 14 exfiltration chain on every model in the lab
  21. Level 21: Short-Lived, Scoped Credentials for Agent Tools
    Swap the agent's long-lived API keys for narrowly scoped, short-lived tokens issued per task, so a hijacked agent can only reach a little, and only for a short time.
    • Replace a hard-coded API key in a Python or TypeScript agent with a per-task token whose scope and expiry are set by the host application, not the model
    • Map each tool to the smallest set of permissions it needs and show that a hijacked tool call fails outside that scope
    • Explain the trade-offs of token lifetime, refresh and revocation when an agent runs a long multi-step job
  22. Level 22: Human Approval Gates That Hold Up
    Design approval steps for high-risk agent actions that show the human what will actually happen and that stand up to approval fatigue and approval text written by an attacker.
    • Sort an agent's tools into auto-allow, needs-approval and deny tiers based on how reversible and how far-reaching each action is
    • Build an approval prompt that shows the exact tool arguments and data destinations, generated by code rather than written by the model
    • Find and fix an approval flow that an injected instruction can get past by rewording a harmful action to look harmless
  23. Level 23: Policy Enforcement Outside the Model
    Move security decisions out of the prompt and into a deterministic policy layer that checks every tool call and tracks where data came from before anything runs.
    • Put a policy check between the model and its tools that allows or blocks calls based on arguments, caller context and data labels
    • Tag data from untrusted sources and block it from reaching tools that send data out, even when the model asks for it
    • Explain why rules enforced by code are worth more than instructions in the system prompt, and where they still leave gaps
  24. Level 24: Layering Defences and Naming What's Left
    Combine the phase's patterns into a layered design for one agent and write down honestly what attacks still get through.
    • Apply plan-then-execute, capability-scoped tools, scoped credentials and approval gates together to an agent that has all three legs of the trifecta
    • Re-run earlier injection attacks against the layered design and record which layer stopped each one
    • Write a short residual-risk note that says plainly which attacks are still possible and why
  25. Level 25: Model Supply Chain: Weights and Provenance
    Treat open-weight models and their loaders as third-party code, and check where they came from, whether they have been altered and whether they are safe to deserialize.
    • Explain why pickle-based model files can run code when loaded and why safetensors-style formats lower that risk
    • Check a downloaded model against a published hash and record where it came from before loading it in an isolated environment
    • Judge a model's source using its model card, publisher identity and revision pinning instead of a download count
  26. Level 26: MCP Tool Poisoning and Description Injection
    See how an MCP server's tool names, descriptions and results can carry instructions that steer an agent, including instructions about other servers' tools.
    • Build a malicious MCP tool whose description hijacks an agent's use of a separate, trusted tool, then watch it work
    • Audit the tool metadata of an installed MCP server for hidden instructions before connecting it
    • Explain why the model's context window has no trust boundary between tools from different servers
  27. Level 27: Rug Pulls: Pinning and Change Detection
    Defend against a trusted MCP server or skill that changes its behaviour after you approve it, by pinning versions and spotting changed tool definitions.
    • Pin MCP servers and skills to exact versions or content hashes rather than floating tags
    • Write a check that fingerprints tool definitions at approval time and blocks the session when they change
    • Show a simulated rug pull being caught at connection time rather than after data has leaked
  28. Level 28: Signing, Registries and Allowlists
    Control which MCP servers, skills and packages an agent may load, using signature checks, internal registries and explicit allowlists.
    • Verify a signed package or artifact and refuse to load it when the signature or publisher identity does not match
    • Set up an allowlist that limits an agent host to approved MCP servers and skills, with a documented review process
    • Explain what signing proves (who published it, and that it is unchanged) and what it does not prove (that it is safe)
  29. Level 29: Sandboxing Agent Code Execution
    Contain code the agent writes or runs by comparing process, container, user-space-kernel and microVM isolation, and the common ways each one is escaped.
    • Run agent-generated code in a container with no root access, a read-only filesystem, and CPU, memory and time limits
    • Compare process, container, gVisor-style and microVM isolation by how strong the isolation is, how fast it starts and what it costs to run
    • Find escape paths in a deliberately weak sandbox, such as mounted sockets, host paths and credentials left in the environment
  30. Level 30: Egress Control and Covert Exfiltration
    Cut off the external-communication leg of the trifecta at the network layer, including side channels such as DNS, image URLs and links the agent renders.
    • Route all agent network traffic through an egress proxy with a per-tool allowlist of destination domains
    • Exfiltrate data through DNS lookups and rendered markdown images, then block each channel
    • Explain why an allowlist of 'safe' domains can still leak data through open redirects or user-generated content on those domains
  31. Level 31: Data Leakage in Logs, Traces and Retention
    Stop prompts, tool results and secrets from leaking through observability tools, provider-side retention and agent memory.
    • Redact secrets and personal data from agent traces before they leave the process, and test the redaction with seeded canary values
    • Write down where each piece of agent data is stored, who can read it and how long it is kept, including on the model provider's side
    • Stop untrusted content from being written into long-term memory where it could act as a stored injection later
  32. Level 32: Guardrail Models: Wiring Input and Output Checks
    Put guardrail classifiers in front of and behind the model, and learn what each type is built to detect.
    • Add an open-weight guardrail classifier and a provider moderation endpoint to the input and output paths of the same agent
    • Tell apart classifiers built for harmful content, jailbreaks and indirect injection, and pick the right one for each point in the pipeline
    • Measure how much latency and cost each guardrail adds to a single agent turn
  33. Level 33: Measuring Guardrails and Adaptive Attacks
    Measure guardrails honestly with labelled datasets, and see how adaptive attackers get past classifiers that score well on fixed benchmarks.
    • Measure a guardrail's catch rate and false-positive rate on a labelled set of attack and harmless prompts
    • Get past a guardrail with paraphrasing, encoding or splitting the payload across turns, and record what it missed
    • Explain why a guardrail lowers risk but cannot be the layer that breaks the trifecta
  34. Level 34: Automated Attack Suites
    Use open-source red-teaming frameworks to generate and run injection, jailbreak and exfiltration attacks against an agent at scale.
    • Run an automated attack scan with a framework such as garak, PyRIT or promptfoo against agents built on two different model providers
    • Write custom attack probes aimed at your own agent's tools and data instead of generic chatbot attacks
    • Sort the findings by real impact rather than by the raw count of successful attacks
  35. Level 35: Red-Teaming in CI as Regression Tests
    Turn known attacks into repeatable security tests that run on every change to prompts, tools, models or dependencies.
    • Build a CI job that replays a set of attack cases against the agent and fails the build when an exfiltration succeeds
    • Handle the model's non-deterministic output with repeated trials, success-rate thresholds and checks on tool calls instead of exact text matches
    • Re-run the suite automatically when the model version, an MCP server or a system prompt changes
  36. Level 36: Detecting Agent Attacks in Production
    Instrument agents so that injections, unusual tool use and exfiltration attempts show up in monitoring before or while they do damage.
    • Log every tool call, the data labels involved and every policy decision as structured security events
    • Write detection rules for warning signs such as triggered canary tokens, blocked egress attempts and sudden changes in tool-call patterns
    • Separate the alerts that need someone to act straight away from the signals that belong in a review
  37. Level 37: Incident Response for Agent Compromise
    Practise detecting, containing, investigating and reviewing an agent security incident from start to finish.
    • Run a containment playbook: disable affected tools, revoke credentials, quarantine poisoned memory and pin or remove the suspect server
    • Rebuild what happened from traces and find which piece of untrusted content carried the injection
    • Write a blameless post-incident review that turns the attack into a new CI regression test and a design fix
  38. Level 38: Capstone Part 1: Attack the Agent
    Threat-model and attack a small tool-using agent with private data, web access and outbound tools, and record every successful compromise.
    • Write a threat model for the capstone agent that maps where the trifecta appears, its trust boundaries and its supply-chain inputs
    • Carry out at least one direct injection, one indirect injection, one tool-poisoning attack and one exfiltration against the agent
    • Record each finding with a reproduction, its impact and a matching OWASP or MITRE ATLAS category
  39. Level 39: Capstone Part 2: Harden and Prove the Fixes
    Apply the course's defences to the capstone agent and prove they work by re-running every attack as an automated suite.
    • Break at least one trifecta leg in each attack path using design patterns, scoped credentials, sandboxing and egress control
    • Turn every Part 1 attack into a CI test and show each one now fails, including results for repeated trials
    • Record the remaining risk and the cost of hardening: added latency, more approval prompts and reduced capability
  40. Level 40: Final Challenge: Secure an Agent End to End Exam
    Review the whole course by securing an unfamiliar agent from threat model through to incident response, under realistic limits and with honest notes on what remains unsolved.
    • Find and rank the risks in an unfamiliar agent across injection, permissions, supply chain, sandboxing, data handling and monitoring
    • Deliver a hardened design with a tested attack suite, a detection plan and an incident playbook
    • Defend your design choices, stating plainly where current practice is unsettled and which risks you accept

Access

Levels 1 and 2 are free to read, no account needed. Levels 3 and 4 are free with a free account, and so are 20 answers from the AI tutor. Every level, the podcast edition and the AI tutor come with All Access at £4.99/month or any Creator plan — see pricing.

Read lesson 1 free →

More like this