OWASP LLM10:2026 Improper Output Handling: safe sinks for agent output

Model output is untrusted input. Parameterised SQL, argument arrays, path checks, sandboxes and encoding in TypeScript, and the few outputs where a person should see the exact string first.

· 8 min read

LLM10:2026 Improper Output Handling is the last entry in the OWASP Top 10 for LLM Applications 2026. OWASP defines it as “insufficient validation, sanitization, and handling of the outputs generated by large language models before they are passed downstream to other components and systems.” In 2025 it was LLM05, and it fell the furthest of any entry, from fifth to tenth. It also grew: it now spans the insecure code that assistants generate at scale.

The reasoning is short. Prompt input can steer what a model writes, so passing that output on unchecked gives whoever wrote the prompt “indirect access to additional functionality”. In a browser that ends as XSS or CSRF; on a backend as SSRF, privilege escalation or remote code execution. In an agent, the prompt includes every web page, email and tool result it reads, so the person steering the output may not be your user at all.

OWASP draws the borders itself. Output that is merely wrong is LLM07:2026 Misinformation, checking what goes into the model is LLM01:2026 Prompt Injection, and an agent holding more power than it needs is LLM03:2026 Excessive Agency. This entry is about what your code does with the text once the model has written it.

Every sink needs its own handling

Mitigation 1 sets the stance: “Treat the model as any other user, adopting a zero-trust approach”. Mitigation 4 adds that the encoding depends on where the output lands. OWASP’s seven examples of risk map onto the places an agent’s output goes:

A shell, exec or eval
Example 1: remote code execution. Fix: no shell string, an argument array, a sandbox for generated code.
A database
Example 3: SQL injection. Fix: parameterised queries, and a read-only role when the model writes the query.
A file path
Example 4: path traversal. Fix: resolve the path and check it stays inside one folder.
A browser or an email
Examples 2 and 5: XSS and phishing. Fix: encode for HTML, and a strict Content Security Policy.
A terminal, log or IDE pane
Example 6: ANSI escapes and control characters that spoof text or write to the clipboard (OSC 52). Fix: neutralise them.
A Markdown renderer
Example 7: an auto-loaded image whose URL carries conversation data to an attacker. Fix: no automatic fetches outside an allow-list.

Queries and file paths

Mitigation 5 asks for “parameterized queries or prepared statements for all database operations involving LLM output.” The cleanest way to get there is a tool that takes typed arguments instead of SQL. Scenario 3 is the reason: a chat feature that writes SQL for the user, and a user who asks it to delete every table.

// SQL: the model fills typed arguments. Your code writes the SQL and binds the values.
const SORTS = { newest: "created_at DESC", largest: "total DESC" } as const;
const DATE = /^\d{4}-\d{2}-\d{2}$/;

async function findOrders(args: { since: string; sort: string }, session: Session) {
  if (!DATE.test(args.since)) throw new Error("since must be a date");
  // Column names cannot be parameters, so the ORDER BY comes from the list above.
  const sort = Object.hasOwn(SORTS, args.sort) ? SORTS[args.sort as keyof typeof SORTS] : SORTS.newest;
  return db.query(
    `SELECT id, total, status FROM orders
      WHERE workspace_id = $1 AND customer_id = $2 AND created_at >= $3
      ORDER BY ${sort} LIMIT 100`,
    // The workspace and the customer come from the session, never from the model.
    [session.workspaceId, session.customerId, args.since]
  );
}

// Text-to-SQL, where the model must write the query: the connection is the limit.
// report_reader is a login role with SELECT on three reporting views and nothing else.
const reports = new Pool({ connectionString: process.env.REPORT_READER_URL, statement_timeout: 5000 });

// File paths: the model names a file, your code decides whether it is inside the root.
const ROOT = await realpath("/srv/agent-files");

async function openForWrite(name: string) {
  const full = path.resolve(ROOT, name); // "../../etc/passwd" resolves outside ROOT
  const parent = await realpath(path.dirname(full)); // a symlinked folder resolves too
  if (parent !== ROOT && !parent.startsWith(ROOT + path.sep)) {
    throw new Error("outside the agent's folder");
  }
  // O_NOFOLLOW: the file itself may not be a link to somewhere else.
  const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW;
  return open(path.join(parent, path.basename(full)), flags, 0o600);
}
  • Values are bound, names are chosen. A column or sort order cannot be a parameter, so it comes from a fixed list.
  • Text-to-SQL gets a role, not a filter. Trying to spot a dangerous statement in the text is a losing game. A login role with SELECT on a few views cannot drop anything, whatever the model writes.
  • Paths are checked after resolving. Comparing the raw string misses ../ and symbolic links. Resolve first, then check the result is under the root.

Commands and generated code

Example 1 is the oldest: output “entered directly into a system shell or similar function such as exec or eval”. A shell reads ;, | and $( ) as instructions. An argument array passed to the program has no such characters, only arguments.

const run = promisify(execFile);
const REF = /^[A-Za-z0-9._\/-]{1,100}$/;

// The model picks a tool and fills in a branch name. It never writes a shell string.
async function gitLog(ref: string) {
  // An argument starting with "-" would be read as an option, so it is refused.
  if (!REF.test(ref) || ref.startsWith("-")) throw new Error("not a branch or tag name");
  // execFile hands git an argument array with no shell, so ; | $( ) are only characters.
  const { stdout } = await run("git", ["log", "--oneline", "-n", "20", ref, "--"], {
    cwd: repo,
    timeout: 10_000,
    maxBuffer: 1_000_000,
  });
  return stdout;
}

// Generated code runs in a throwaway container: no network, read-only, small and short-lived.
async function runGenerated(dir: string) {
  const name = `gen-${randomUUID()}`;
  try {
    return await run("docker", [
      "run", "--rm", "--name", name,
      "--network=none", "--read-only", "--cap-drop=ALL",
      "--security-opt=no-new-privileges", "--user=65534:65534",
      "--memory=256m", "--cpus=1", "--pids-limit=64",
      "--mount", `type=bind,src=${dir},dst=/code,readonly`,
      "node:22-slim", "node", "/code/main.js",
    ], { timeout: 30_000, maxBuffer: 1_000_000 });
  } catch (error) {
    // The timeout stops the docker client, not the container, so stop that too.
    await run("docker", ["kill", name]).catch(() => undefined);
    throw error;
  }
}

Scenario 6 is about the code itself: an application “compiles and deploys LLM-generated code without human review or security testing.” Running generated code in a container with no network and a read-only file system answers the running half. The deploying half needs the same review, tests and scanning you would give a colleague’s pull request.

Browsers, email and terminals

Mitigations 3 and 4 ask you to encode output for its context, and mitigation 6 adds a strict Content Security Policy as a second layer against XSS. Two mitigations deal with sinks people forget: mitigation 8 for control characters written to terminals and logs, and mitigation 9 for renderers that fetch whatever an image link points at.

// Browser: model text is text. React escapes it, so never reach for dangerouslySetInnerHTML.
<p className="answer">{reply.text}</p>

// Email templates and other HTML you build by hand: encode for HTML.
const HTML: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (c) => HTML[c]);

// Markdown, if you render it: no raw HTML, and images and links only from origins you
// trust, so an image URL cannot carry the conversation to someone else's server.
const TRUSTED = new Set(["https://docs.example.com", "https://cdn.example.com"]);
function allowedUrl(href: string): boolean {
  try {
    return TRUSTED.has(new URL(href).origin); // a javascript: URL's origin is "null"
  } catch {
    return false; // relative or malformed: never fetched
  }
}

// Terminals, log files and IDE panes: control characters become visible codes.
// This catches ANSI escapes, OSC 52 clipboard writes, BEL, backspace and carriage return.
const CONTROL = /[\x00-\x08\x0B-\x1F\x7F-\x9F]/g; // keeps tab and newline
function forTerminal(text: string): string {
  return text.replace(CONTROL, (c) => `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
}

OWASP is specific about mitigation 9: disable auto-rendering of Markdown images, link previews and iframes by default, and where you need them, allow only listed origins or fetch through a server-side proxy that “strips data-bearing query parameters”. Scenario 2 shows why: a summariser reads a page with an injection in it and sends the user’s data to an attacker’s server.

Where a person’s approval fits

Honestly, not often. Everything above makes the output safe by construction, and a gate in front of it adds little. Asking a person about every shell command is possible, and tiring: after the fortieth ls, nobody reads the forty-first.

A few outputs cannot be made safe that way, because running the model’s text is the whole point: a generated database migration, a one-off command on a production host, a bulk UPDATE. For those, show a person the exact string your code will execute, computed after every rewrite, and run that string and nothing else:

// The whole text must fit in one request (64 KB of JSON), and escaping quotes and
// newlines can double its size, so the cap leaves room.
const MAX_REVIEW_BYTES = 24_000;

/** The exact text that will run, after every rewrite. The model's draft is only input. */
function finalText(draft: string): string {
  // withoutHiddenCharacters is in the LLM01 article: what is shown is what runs.
  const text = withoutHiddenCharacters(draft).replace(/\r\n?/g, "\n").trim();
  // Backspace, ESC and other controls can make the text shown differ from what runs.
  if (/[\x00-\x08\x0B-\x1F\x7F-\x9F]/.test(text)) {
    throw new Error("contains control characters; refuse it rather than show it");
  }
  if (Buffer.byteLength(text) > MAX_REVIEW_BYTES) {
    throw new Error("too long to show in full; split it into smaller steps");
  }
  return text;
}

export async function runMigration(draft: string) {
  const sql = finalText(draft);
  const sha256 = createHash("sha256").update(sql).digest("hex");
  const version = await prod.schemaVersion(); // read by your code, not reported by the model

  await approvals.guard(
    {
      action: "db.migration.run",
      // Facts your code counted. Never the model's "adds an index, safe to run".
      summary: `Run migration ${sha256.slice(0, 12)} on production: ${sql.split("\n").length} lines, in full below`,
      details: { sql, sha256, database: "production", schema_version: version },
      ttlSeconds: 3600,
    },
    async () => {
      // Up to an hour may have passed. If the schema moved, this SQL was approved for another one.
      if ((await prod.schemaVersion()) !== version) {
        throw new Error("schema changed since asking; ask again with a fresh draft");
      }
      try {
        await prod.migrate(sql); // the string in details, byte for byte
      } catch (error) {
        log.error({ err: error, sha256 }, "approved migration failed");
        // It may be partly applied: never retry on your own, and keep the raw error off the record.
        throw new Error(`migration ${sha256.slice(0, 12)} failed and may be partly applied`);
      }
      return `applied ${sha256.slice(0, 12)}`;
    }
  );
}

// A one-off production command: same idea, its own action name.
// The host is chosen by the person who started the run, never named by the model.
export async function runProdCommand(draft: string, host: ProdHost) {
  const command = finalText(draft);
  await approvals.guard(
    {
      action: "shell.prod.run",
      summary: `Run a ${command.split("\n").length}-line command on ${host.name}, in full below`,
      details: { command, host: host.name },
    },
    // Exactly what was shown, run as a user with only the rights the job needs.
    async () => {
      try {
        await ssh(host, command);
      } catch (error) {
        log.error({ err: error, host: host.name }, "approved command failed");
        throw new Error("the command failed and may have partly run");
      }
      return "ran"; // a fixed note: the command's output stays off the record
    }
  );
}

Rules then keep those kinds with a person:

# Generated migrations need two people (Team plan). No allow rule can answer for them.
{ "action": "db.migration.run", "effect": "ask", "approvals": 2 }

# One-off production commands and bulk updates always wait for a person.
{ "action": "shell.prod.run", "effect": "ask" }
{ "action": "db.bulk_update.run", "effect": "ask" }
  • One action name per kind. Rules read the action name and the agent key, never the details. A migration, a production command and a bulk update get their own names and their own ask rules. The most cautious rule wins, so a broad allow rule such as db.* cannot answer for them.
  • The model does not describe its own command. The summary holds facts your code counted, and the details hold the text itself. A manipulated model can call a destructive migration “a small index change”; a hash and a line count cannot lie that way.
  • No edited versions. A person may approve a changed wording, and guard refuses to act on it unless you pass acceptChanges. Leave it off: a rewritten sentence is not a rewritten query. Ask again with new text instead.
  • Check again after the wait. An approval for one schema version says nothing about the next. If the state moved, ask again.
  • A failure may have half-happened. guard records the error’s message as the outcome, so throw your own short one, log the cause with the hash, and let a person decide what comes next.

The string has to be the one that runs, character for character. That is why finalText strips hidden characters before hashing and showing. VariantGate’s inbox checks too: summaries and details are shown as text, never as HTML, and invisible characters such as zero-width spaces and direction controls are drawn as red marks with a warning above the request. The details are on Security.

Coding agents and shell commands

Coding agents are the one place where approving shell commands is routine. Claude Code’s PreToolUse hook can send each Bash call to the inbox as shell.run, with the command itself as the summary, so the person reads what will run rather than Claude’s description of it. The setup is in the Claude Code guide.

Two cautions. A rule matches the action, not the command, so a rule for shell.run covers every command, and with the hook on, every command waits for a person. That suits sessions with few commands or high stakes; for everyday work, a sandboxed agent is the better control. And in six of the seven coding agents we compared, a hook that times out lets the call run anyway; check yours with coding agent hooks that fail open.

What an approval service does not cover

Almost all of LLM10 happens in your own code, between the model and the sink, where an approval service never looks:

  • Encoding and parameterising. HTML and JavaScript encoding, bound queries, argument arrays and path checks. OWASP points to the Application Security Verification Standard for the details (mitigation 2).
  • Rendering. A Content Security Policy, no raw HTML in Markdown, no automatic fetches, and control characters neutralised in terminals and logs.
  • Reviewing generated code. A person glancing at a 200-line page in an inbox will not reliably spot the XSS in it. Tests, scanners and a real code review will do better.
  • Monitoring. Mitigation 7 asks for logging and monitoring that spot unusual patterns in model output. The record of approvals covers the few actions that asked, not the output in general.

Where an approval does help is the narrow case above: text that must run as written, shown in full, under its own action name. The tool risk checker sorts an MCP tool list into what only looks and what acts, which shows where those cases are. The rest of the 2026 list is in our overview of the OWASP Top 10 for LLM Applications 2026, and the input side of this entry is in LLM01:2026 Prompt Injection.

Sources

  1. OWASP GenAI Security Project: OWASP GenAI LLM Top 10 2026, LLM10:2026 Improper Output Handling
  2. OWASP: Top 10 for LLM Applications 2025
  3. OWASP Application Security Verification Standard

Give your agents somewhere to ask.

Free for 100 requests a month. Sign in with your email and have a first request waiting a few minutes from now.

Start free