This comprehensive guide explains LLM securityβprotecting applications built on large language models from misuse, data theft, and manipulation. It differs fundamentally from traditional application security because LLMs cannot reliably separate instructions from data within a single text stream, making attackers able to steer the model through carefully crafted prompts rather than breaking into servers. The guide maps attack surfaces, names OWASP risks, demonstrates prompt injection and system prompt extraction techniques, and provides layered defensive strategies with testing approaches.
- Core vulnerability: instructions and data mergeUnlike databases where code and data are separate, LLMs receive both as one text stream in the context window. The model has no internal notion of trust or provenance, so it cannot reliably distinguish developer rules from sentences planted in retrieved documents or user input. This single fact explains most LLM vulnerabilities and why stricter prompts alone cannot solve them.
- Direct versus indirect prompt injection attacksDirect injection occurs when an attacker types instructions into user-visible inputs like chat boxes. Indirect injection hides instructions in external content the system retrievesβweb pages, emails, documentsβthat the victim never sees. EchoLeak (CVE-2025-32711) exemplifies indirect injection with no authentication or victim action required, earning a CVSS score of 9.3. OWASP and multiple sources state no complete fix exists for prompt injection.
- System prompts are not secretsA study of 14,904 custom GPTs found 92.2% were vulnerable to system prompt extraction. Attackers override refusals by reframing requests in different formats or languages. The leaked text reveals the bot's rules, tool names, and escalation logicβa map for follow-on attacks. OWASP explicitly states system prompts should not be treated as security controls; keep credentials, role logic and authorisation outside prompts.
- Data leakage through multiple channelsSensitive data leaks when the model accesses information the current user should not seeβsecrets in system prompts, documents retrieved for wrong persons, or internal data sent to external LLM APIs, which counts as vendor disclosure. Output flows into other systems without encoding or validation, introducing XSS, SQL injection, and command execution. Redaction layers at trust boundaries and output encoding mitigate this.
- Layered defence with trust boundariesNo single control stops LLM attacks. The blueprint separates untrusted content and labels it, redacts data at system edges before external APIs see it, gives tools minimal privilege, requires human approval for risky actions, validates and encodes output, filters retrieval by user permissions, and monitors all interactions. Trust boundaries sit between users and backend, backend and external LLM APIs, the model and tools, and the model and output sinks.
- Unbounded consumption drains budgetsOWASP LLM10 covers uncontrolled use where attackers or buggy loops send huge prompts, force long outputs, or hammer endpoints until services collapse. Controls include per-identity quotas counting requests and tokens, input and output size caps enforced before model calls, and hard spend caps with alerts below them. Testing on local infrastructure verifies rejection logic works without surprise invoices.
- Testing beyond raw model scanningSecurity testing uses three layers: Garak scans the raw model, PyRIT simulates multi-turn attacks across messages, and Promptfoo tests the full application including system prompt, RAG, and tool calling, acting as a CI gate. Testing only the raw model gives false coverage because real risk lives in system prompts, retrieved documents, and attached tools. Every confirmed bypass becomes a permanent regression test.
- OWASP 2025 edition and naming requirementsThe OWASP Top 10 for LLM Applications 2025 v2.0 lists 10 risks including LLM01 Prompt Injection, LLM02 Sensitive Information Disclosure, LLM07 System Prompt Leakage (new in 2025), and LLM10 Unbounded Consumption. Sources disagree on current editions; practitioners must cite the specific edition they referenceβfor example 'LLM07, OWASP 2025 v2.0'βto avoid arguments and ensure consistent threat communication.
Bottom line: LLM security requires layered defences outside the model itself because no prompt can fully prevent attacks: enforce authentication and authorisation in the API layer, separate untrusted content at the system level, validate and encode all outputs, give tools minimal privileges, and test the whole application including retrieval and tool wiring, not just the raw model. Treat the system prompt as readable, keep secrets and access control rules out of it, and turn every confirmed bypass into a reg
β±οΈ 60 min Β· Beginner Β· 2 hands-on labs
Imagine your team ships a support chatbot on Monday. By Wednesday someone has pasted a clever sentence into the chat box, and the bot is reading out its own hidden rules and offering to look up another customer's order. Nobody broke into a server. They only typed words. That is the problem llm security exists to solve, and it behaves differently from the application security you may already know.
In this Tutorial I will show you how an LLM application is put together, where its trust boundaries sit, and where an attacker can get text into the model. We will name the OWASP Top 10 risks and be careful about which edition we cite. Then we will run a basic prompt injection and a system prompt extraction against an intentionally vulnerable SecurityElites lab, never against a real product.
After that we will build the defences in layers, because no single prompt can stop these attacks. We will finish with a simple test plan using Garak, PyRIT and Promptfoo, so you can attack your own application before somebody else does.
π― What You Will Be Able to Do
β Before You Start
- Basic understanding of web applications and HTTP APIs
- Familiarity with what a chatbot or LLM does from a user's view
- A SecurityElites lab account (free tier is enough for the beginner labs)
π In This Tutorial
- What LLM Security Means and Why It Differs
- Anatomy of an LLM Application
- Mapping the Attack Surface and Threat Model
- The OWASP Top 10 for LLM Applications at a Glance
- Prompt Injection: Direct and Indirect
- Worked Demo: Injecting and Extracting a System Prompt
- Data Leakage, Output Handling and Excessive Agency
- LLM API Security and Unbounded Consumption
- Defensive Controls: A Layered Blueprint
- Security Testing and Red Teaming LLM Apps
- Your Lab Practice and Next Steps
- Your checklist
- What I want you to remember
- Questions people ask
What LLM Security Means and Why It Differs
I am going to start with a plain definition. LLM security is the practice of protecting applications built on large language models (LLMs) from misuse, data theft, manipulation and abuse. It covers the model, but also everything wired around it: the prompts, the documents it reads, the tools it can call and the systems that consume its answers. This page is the pillar for the whole topic, so I will point you to deeper pages as we go.
Before anything else, let me give you the vocabulary. You will see these words in every section that follows, so take a minute with them.
π Words I just used
Now the key idea. In classic application security, code and data are separate. A database query has a fixed shape, and we pass user input as a parameter, so it cannot rewrite the query. An LLM has no such separation. Instructions and data arrive as one stream of text, and the model has no internal notion of trust or provenance. It cannot reliably tell the developer's rules from a sentence inside a web page it was asked to summarise.
That single fact explains most LLM vulnerabilities. It is why a clever sentence can override your rules, and why you cannot fix the problem by writing a stricter prompt. The defence has to live in the system around the model.
π§ Quick check
Anatomy of an LLM Application
I want you to see the parts before we talk about attacks. You cannot secure a system you cannot draw. Here is a reference architecture for a typical LLM application, and we will walk through it box by box.
- User (untrusted)
- App backend (your code)
- System prompt + user input
- LLM API (outside your boundary)
- RAG store and tools or agents
- Output sink (browser, database, shell)
The user types a message. This is untrusted, always. The app backend is your code. It builds the prompt by joining the system prompt, the user message, chat history and any retrieved documents. It then sends that bundle to the LLM API, which is often run by an outside vendor.
The model may ask for more. In a RAG setup, the backend queries a vector store (a database that finds documents by meaning) and adds the results to the context. In an agent setup, the model can emit tool calls, and the backend runs them: search the web, read a file, create a ticket. Finally the answer lands in an output sink, which is whatever consumes it: a web page, a SQL query, a script, another agent.
Next, mark the trust boundaries on that picture. I draw them in four places.
βοΈ Where I draw trust boundaries
Notice that retrieved documents and tool results also cross a boundary on the way in. Anyone who can write to an indexed source can write into the model's context. For the full treatment of that store, read the RAG security guide. For agents and their tools, the agentic AI security guide and the MCP security guide go further.
Mapping the Attack Surface and Threat Model
With the diagram in hand, we can list where an attacker gets in and what they want. This is the start of threat modelling: naming entry points, naming assets, then asking what can go wrong between them. It is the foundation of sound llm application security.
Entry points first. Every place text can reach the context window is one.
βοΈ Entry points to list for your own app
Assets next: the system prompt, any secrets near it, customer data in retrieved documents, the tools and their permissions, your API budget, and the trust users place in the answers. Put entry points on the left and assets on the right, then draw the paths between them. Each path is a threat to test.
To describe attackers consistently, I use the vocabulary from NIST AI 100-2e2025, *Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations*, published in March 2025. It classifies attacks along five dimensions: the type of AI system, the life-cycle stage, the attacker's goal (availability, integrity or privacy), the attacker's capabilities, and the attacker's knowledge of the learning process. For generative AI it covers supply chain attacks, direct and indirect prompt injection, misuse and agent security.
A quick example. Say a support bot summarises customer emails. Goal: privacy. Capability: the attacker can only send an email. Knowledge: none of your internals. Life-cycle stage: deployment. That is an indirect injection threat, and now it is written down in a way your team can review.
For RAG, add one question: does retrieval run with the end user's permissions, or as a privileged app identity? The first limits leakage to what that user could already see. The second exposes everything indexed. For agents, follow the method in the AI agent threat modelling guide.
π§ Quick check
The OWASP Top 10 for LLM Applications at a Glance
I want you to meet the list that most people in llm security use as a shared map. The OWASP Top 10 for LLM Applications names the ten risks that show up most often in apps built on large language models. Think of it as a checklist of where to look first, not a full threat model.
One thing before the list. Sources disagree on which edition is current. One guide says a 2026 edition has been published, with the 2025 list still widely cited. Another says the 2025 edition is still current. Prompt injection is number one in both. So I will name the edition I use: 2025, version 2.0. You should do the same in your notes and reports.
π Words I just used
Two entries were new in 2025: System Prompt Leakage (LLM07) and Vector and Embedding Weaknesses (LLM08). The second appeared because many companies use RAG and agent pipelines instead of fine-tuning models. One guide cites 53% of companies as choosing that approach.
Each risk gets a full explanation in the OWASP Top 10 for LLM Applications guide. For agent-specific risks, read the OWASP Top 10 for Agentic Applications explained.
π§ Quick check
Prompt Injection: Direct and Indirect
Prompt injection is the top risk in the OWASP list, so I want you to understand it properly. It means adversarial instructions are mixed in with ordinary content, and the model follows the attacker's intent instead of yours. It works because the model cannot reliably tell instructions from data. Everything arrives as text in one context window.
There are two forms. In direct injection, the attacker types the instructions into a user-visible input, such as the chat box. In indirect injection, the instructions are hidden in external content that the system retrieves, such as a web page, an email or a document. The victim never sees the attacker's text, and may not do anything at all.
- Attacker plants text in a document
- App retrieves the document
- Text enters the context window
- Model follows hidden instructions
- Tool or output acts on them
A real example is EchoLeak, tracked as CVE-2025-32711. It is cited as an indirect prompt injection with a CVSS score of 9.3. It needed no authentication and no action from the victim. That is why indirect injection worries defenders more than a user typing something rude into a chatbot.
There is an uncomfortable truth here. One guide says there is no complete fix, and OWASP states it is unclear whether fool-proof prevention methods exist. Indirect injection is a system-level problem caused by mixing trusted and untrusted inputs. Prompts and model tuning alone cannot solve it. What helps is layering: trust boundaries, least-privilege tools, human approval for risky actions, output checks and continuous testing.
For more depth, read direct versus indirect injection in the secure development lesson, and the AI red teaming guide for how testers probe for it. For retrieval pipelines specifically, see the RAG security guide.
π§ Quick check
Worked Demo: Injecting and Extracting a System Prompt
Now I will show you system prompt extraction in practice. The system prompt is the hidden instruction set the developer gives the model. We will attack an intentionally vulnerable bot in the SecurityElites lab, never a real product. Follow along in the lab below.
This guided lab has the steps written beside it, so you can match my demo as you go. Use only this lab for the practice.
βΈ Ask the bot what it can help with, and read its tone and limits.
βΈ Ask directly for its instructions and note how it refuses.
βΈ Try asking it to restate its setup in a different format or language.
βΈ Compare the answers and look for fragments of the hidden text.
What to notice: How refusal wording hints at what rules exist Whether a change of format changes the bot's willingness Which details appear in the leaked text
π§ Probe, override, extract
Look at what such a leak reveals: the bot's rules, its tool names and its escalation logic. That is a map for the next attack. A study of 14,904 custom GPTs found 92.2% were vulnerable to system prompt extraction, so assume extraction is possible.
Prompts can also leak through error messages, conversation summaries, memory recall or agent-to-agent communication, and output filtering helps as one mitigation. For a second practice target that stores a secret in the prompt, try the lab below after reading the secure development lesson.
This is a second beginner target, where the bot has been told to keep something back.
βΈ Chat normally first and learn what the bot does.
βΈ Think about why a rule written in text can be argued with.
βΈ Vary your approach rather than repeating one request.
What to notice: Whether the bot ever reveals more than it should How a secret in a prompt is only as safe as the prompt
Data Leakage, Output Handling and Excessive Agency
I want to take three risks together in this section, because in a real LLM security review they chain into one another. Data leaks out of the model, unsafe output flows into other systems, and agent tools turn a clever prompt into a real action. If you can see the chain, you can break it.
Start with leakage. An LLM application leaks data when the model can see something the current user should not. Common sources are secrets pasted into the system prompt, documents retrieved for the wrong person, and sensitive text sent to an outside model API. OWASP lists this as LLM02 Sensitive Information Disclosure. The model does not know who is allowed to see what. Your application has to decide that before the text ever reaches the context window.
There is also a quieter leak. When your app calls an external LLM API, that API sits outside your trust boundary. Sending internal data to it counts as disclosure to that vendor. So I want a redaction or masking layer at the edge of your boundary, before anything leaves.
Now output handling, which OWASP calls LLM05 Improper Output Handling. Treat everything the model writes like untrusted user input. If your app drops it into a web page, a database query, a shell command or a URL fetch without checks, you can get XSS, SQL injection, command execution or SSRF downstream. The model is simply a new route for the old bugs.
The same reply is harmless as text and dangerous as markup. Encoding on output is the fix.
Finally, Excessive Agency (LLM06). OWASP names three root causes: excessive functionality, excessive permissions and excessive autonomy. When an agent can call tools, a successful injection triggers real actions, not only bad text. For the full picture, read agentic AI security and agent attacks.
π§ Quick check
LLM API Security and Unbounded Consumption
I treat LLM API security as ordinary API security with two twists: every call costs real money, and the model on the other end can be talked into things. So let me show you the controls in the order I would apply them.
First, authenticate every caller. No anonymous endpoint should reach the model. Use API keys or tokens tied to a person or a service, and keep those keys on the server, never in browser code or a mobile app where anyone can read them.
Second, enforce authorisation outside the model. OWASP is clear that credentials, authorisation rules and role logic should stay out of prompts, and that checks belong in the API layer. If the only thing stopping a user reading another customer's record is a sentence in the system prompt, you have no protection at all.
- Client request
- Authenticate caller
- Authorise action and data
- Quota and rate limit
- LLM call
- Validate output
Third, limit consumption. OWASP calls this LLM10 Unbounded Consumption. An attacker, or just a buggy loop, can send huge prompts, force long outputs or hammer the endpoint until your bill or your service collapses. The key controls are per-identity quotas, token limits and spend caps.
π§ Setting sensible limits
Last, model theft. If your model or fine-tuned weights are valuable, an attacker may try to copy behaviour by sending many queries. Quotas, monitoring for unusual query patterns and strict access to model files all make that harder.
Defensive Controls: A Layered Blueprint
There is no single switch that gives you LLM security. Prompt injection has no complete fix, so I build layers, each one assuming the one before it will sometimes fail. Here is the blueprint I want you to carry away, and you can see how it is built in practice in secure AI development for LLM apps.
- Untrusted input
- Separate and label content
- Redact at the edge
- Model with least-privilege tools
- Validate and encode output
- Human approval for risky actions
- Monitor and log
π§ The layers, one at a time
For the retrieval layer in depth, see the RAG security guide, and for the full risk list, the OWASP Top 10 for LLM Applications guide.
π§ Quick check
Security Testing and Red Teaming LLM Apps
I want to show you how we find weaknesses before an attacker does. Good llm security work does not stop at building controls. You have to attack your own application, record what got through, and make sure it never gets through again.
The OWASP GenAI Red Teaming Guide structures an engagement across four areas. Model evaluation looks at the model's own behaviour. Implementation testing covers your system prompt, retrieval and tool wiring. Infrastructure assessment checks the hosting, keys and APIs around it. Runtime behaviour analysis watches what the live system actually does. Most beginners only touch the first area, and that is the trap.
- Garak scans the raw model
- PyRIT runs multi-turn attacks
- Promptfoo tests the full app
- CI gate checks thresholds
- Bypass becomes a regression test
One suggested layered approach uses three tools. Garak scans the raw model. PyRIT simulates multi-turn attacks, where the attacker builds up over several messages. Promptfoo tests the whole application, including the system prompt, RAG and tool calling, and can act as a CI gate. CI means continuous integration, the automated checks that run whenever code changes.
Two habits turn testing into protection. First, every confirmed bypass becomes a permanent regression test, so a fix cannot quietly break later. Second, automated red-team evaluations run in CI and fail the build when a category threshold is missed. Run all of this only against your own apps or a lab. For tool choices, see AI security testing tools compared, and for method, the practical AI red teaming guide.
π§ Quick check
Your Lab Practice and Next Steps
Now it is your turn. I want you to practise the llm security ideas from this guide on a target built to be attacked, not on anyone else's system. Start with the guided lab, because the steps are written beside it, then move to the harder one.
We start here because it shows system prompt extraction with help, and it proves that a prompt is not a secret.
βΈ Ask for the system prompt directly first and note how it is refused.
βΈ Follow the guided steps beside the lab and try asking for the content in a different format.
βΈ Try a translation or an encoding style request and compare the replies.
βΈ Write down which phrasing changed the bot's behaviour.
What to notice: Blocking the direct request did not protect the content. The refusal logic lived inside the model, which is the weak point. What an attacker would learn from a leaked prompt.
Next, a lab with no written steps, so you rely on your own reasoning about instructions versus data.
βΈ Probe the bot with ordinary questions to learn how it behaves.
βΈ Think about what the system prompt probably says and how to contradict it.
βΈ Vary your approach when one framing is refused.
βΈ Keep notes of each attempt, as you would for a regression test.
What to notice: The model follows instructions from whoever sounds convincing. A rule written in a prompt is not an enforced control.
βοΈ Success criteria
For the learning path, read in this order. Begin with secure AI development, then the OWASP LLM Top 10 guide. Go deeper with RAG security, agentic AI security and MCP security. If you are new to the wider field, the ethical hacking roadmap gives context.
Your Checklist
βοΈ LLM application security review
π« Mistakes I See Most Often
What I Want You to Remember
π§ Check Your Understanding
β Questions People Ask
What is LLM security and how is it different from traditional application security?
What are the OWASP Top 10 risks for LLM applications?
What is the difference between direct and indirect prompt injection?
Can prompt injection be completely prevented?
How does system prompt extraction work and how do you protect against it?
How can LLM applications leak sensitive data and how do you prevent it?
How do you secure an LLM API and the tools or agents connected to it?
π§© Every Tutorial in the LLM Application Security series
- Direct Prompt Injection vs Indirect Prompt Injection: Complete Comparison β Learn direct vs indirect prompt injection: how each works, how to test them in a lab,…
- Indirect Prompt Injection 2026 β When Web Pages Attack Your AI Agent β How indirect prompt injection works: hidden instructions in web pages, emails and files that hijack AI…
- How to Test LLM Data Exfiltration Vulnerabilities in 2026 | AI LLM Hacking Course Day 31 of 90 β Master LLM data exfiltration in 2026. Covert output channels, URL-based exfiltration, embedding leakage, membership inference attacks…
- OWASP Top 10 for LLM Applications 2026: Complete Security Guide β Learn the owasp top 10 llm applications 2026 list, what changed from 2025, and how to…
π Keep Learning on SecurityElites
- MCP Security 2027: Complete Model Context Protocol Security Guide β Learn mcp security from architecture to defence: map trust boundaries, spot tool poisoning and rug pulls, fix OAuth…
- AI Agent Threat Modelling: A Practical Security Methodology β Learn ai agent threat modelling step by step: map assets, trust boundaries, identities, tools and data flows, then…
- OWASP Top 10 for Agentic Applications 2026: Every Risk Explained β Learn the OWASP top 10 agentic applications ASI01 to ASI10, with examples, attack paths and fixes, then test…
- Agentic AI Security: Complete Guide to AI Agent Attacks, Risks and Defence β Learn agentic ai security end to end: map agent attack surfaces, model threats, hijack a lab agent, and…
- AI malware news: how fake AI tools are being used to steal passwords β Malware in Hugging Face models, trojanized AI coding skills and an Android banking trojan that profiles victims. What…
π Sources I Checked
- OWASP Top 10 for LLM Applications: The 2025 List Explained
- OWASP Top 10 for LLM Applications: 2026 and 2025
- OWASP Top 10 2025 for LLM Applications: Whatβs new? Risks, and Mitigation Techniques – Confident AI
- OWASP Top 10 for LLM Applications (2025): A Practitioner's Breakdown
- Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations (NIST AI 100-2e2025) – OECD.AI
- NIST AI 100-2 Adversarial ML Taxonomy Guide
- Defenses Against Prompt Attacks Learn Surface Heuristics
- Prompt Injection Attacks: How They Work & Defenses 2026
Written by Mr Elite. Reviewed by Mr Elite, last reviewed on .

