Join our Newsletter — 33% off our NHI Course
Home› Guides› Terminal Escape Sequence Injection Guide: Hostile Output in…
Guide Application Security

Terminal Escape Sequence Injection Guide: Hostile Output in Logs, CLIs and AI Agent Sessions

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 11 November 2026 13 min read
On this page

A terminal does not just display text: it obeys control sequences embedded in that text, so any tool that prints untrusted data to a terminal lets the author of that data rewrite the screen, change the clipboard or, in the worst cases, type commands. The problem dates back to xterm bugs in 2003, but it keeps returning through new channels: Kubernetes event fields, log files viewed with cat or tail, file names, and now output from LLM-powered command line tools and MCP servers. This guide explains how terminal escape sequence injection works, which sequences matter, where hostile output enters, and how developers and platform teams neutralise it. It is written for developers of CLI tools and AI agents, SOC analysts who read logs in terminals, and platform engineers who own developer workstations.

Key takeaways

  • The terminal is an interpreter. The ESC byte (0x1B) starts sequences that move the cursor, change colours, set the window title, write the clipboard and query the terminal, and the terminal acts on them wherever they appear in output.
  • Deception is the common outcome, execution the severe one. Most attacks hide or overwrite text so a human approves the wrong thing; a smaller set of terminal bugs, such as title and font reports, turned output into typed input.
  • AI agents make it worse. Prompt injection can make a model emit escape sequences, and MCP tool descriptions can hide instructions from the user while the model still reads them.
  • Neutralise at the point of display. Any program that prints untrusted strings should replace control characters by default and allow formatting only from its own code, not from data.
  • Keep terminals current and locked down. Disable remote title changes, title and font reports and clipboard writes where the terminal allows it, and patch terminal emulators like any other client software.

How escape sequences work

Terminal emulators follow the ECMA-48 and DEC VT conventions that xterm documents in its control sequences reference. Three families matter for security:

  • CSI (Control Sequence Introducer, ESC followed by [): cursor movement, erasing lines and the screen, colours and text attributes (SGR), scroll regions and mode switches. The C1 control character 0x9B can act as a one-byte CSI in some terminals, so filters that only look for 0x1B can miss it.
  • OSC (Operating System Command, ESC followed by ]): ends with BEL or ST. OSC 0, 1 and 2 set the icon name and window title. OSC 50 sets the font. OSC 52 sets selection data (the clipboard) from base64 text. OSC 8 is a widely adopted convention for clickable hyperlinks whose visible text can differ from the target.
  • Reports and queries: some sequences ask the terminal to reply, for example CSI 21 t asks xterm to report its window title. The reply is written into the terminal's input stream, which is the root of the most serious bugs.

Plain control characters also matter: carriage return and backspace overwrite what is already on the line, and bell or long runs of characters can be used for nuisance or denial of service. MITRE classifies the weakness as CWE-150, Improper Neutralization of Escape, Meta, or Control Sequences.

What an attacker can do

CapabilitySequences involvedEffect on the userDocumented examples
Hide or overwrite textSGR colours, cursor movement, erase line or screen, carriage returnA log line, diff or tool description looks benign while the real content is hiddenTrail of Bits on MCP tool descriptions (2025); Embrace The Red on LLM output (2024)
Spoof tool outputAny display sequence in a data fieldOperators trust falsified status, events or file namesCVE-2021-25743, kubectl did not neutralise sequences in raw output such as Event fields
Mislead approvalsSequences in a file name or promptUser approves access to a different file than the one shownCVE-2024-27936, cited by CWE-150
Deceptive linksOSC 8 hyperlinksVisible text shows one domain, click goes elsewhere; links can carry data outTrail of Bits (2025); Embrace The Red (2024)
Write the clipboardOSC 52Next paste contains attacker text, possibly a command with a trailing newlineEmbrace The Red (2024); xterm can disable it through allowWindowOps
Inject input through reportsTitle report (CSI 21 t), font operations (OSC 50)The terminal replies with attacker-chosen text into the shell's inputCVE-2003-0063 xterm; CVE-2022-45063 xterm before 375; CVE-2024-38396 iTerm2 3.5.x before 3.5.2 with tmux integration
Bypass bracketed pasteEarly end-of-paste marker inside pasted textPasted text runs instead of waiting for EnterCVE-2021-31701 MinTTY, CVE-2021-37326 Xshell, CVE-2021-40147 ZOC
Denial of serviceRapid title changes, huge outputTerminal or whole desktop freezesCVE-2021-33500 PuTTY (fixed in 0.75), CVE-2021-28848 MinTTY

The execution class depends on specific terminal bugs and on shell configuration. CVE-2022-45063, for example, needed xterm font operations to be allowed and relied on Zsh vi line-editing mode; the CVE record notes that some Linux distributions do not allow font operations by default. Treat execution as possible but uncommon on current, patched terminals, and treat deception as the everyday risk.

Where hostile output comes from

  • Logs: any field an outsider controls (user agent, user name, URL path, email subject) can carry escape bytes into a log that an analyst later reads with tail -f. OWASP describes log injection mainly as forging lines with newlines; escape sequences add the ability to hide or rewrite lines on screen. See the Secure Logging Vocabulary and Application Security Events Guide.
  • Cluster and cloud metadata: object names, labels, annotations and event messages written by one tenant and printed by another user's CLI, as in the kubectl case.
  • Files and repositories: file names, commit messages, README files and package metadata printed by build tools, package managers and git wrappers.
  • Network responses: HTTP bodies, DNS TXT records and banners printed by curl, diagnostic scripts and scanners.
  • Chat and collaboration data: CyberArk showed a contact's display name changing window titles through a messaging client.
  • LLM output: a web page or document read by a model can carry a prompt injection that tells the model to emit escape sequences, which the CLI then prints. See the Prompt Injection Guide.
  • MCP tool descriptions and results: text the user rarely reads in raw form but the model always reads. See the Local MCP Server Security Guide.

AI agent sessions: why this is now a priority

Coding agents and LLM command line tools print large volumes of text that came from somewhere else: web pages, issues, files, tool results. Two published research pieces set out the risk. In December 2024, Embrace The Red's "Terminal DiLLMa" showed prompt-injected model output hiding text, writing the clipboard, creating hyperlinks that leaked prompt data and, in macOS Terminal, triggering DNS requests without a click. In April 2025, Trail of Bits showed ANSI codes in MCP tool descriptions and outputs hiding instructions from the user while the model followed them, and reported that the coding agent version it tested (Claude Code 0.2.76) did not filter them at that time. Products change quickly, so test the versions you run rather than relying on either finding.

The agent setting changes the threat in three ways:

  • The human is the last control: approval prompts for commands and file access only work if the screen shows the truth. Escape sequences attack that review step, which OWASP LLM05:2025 Improper Output Handling covers when model output reaches a downstream interpreter without validation.
  • The model and the user see different things: hidden text is invisible on screen but present in the context window, which is the same gap exploited by invisible Unicode. See the ASCII Smuggling and Invisible Prompts guide.
  • Agents hold credentials: a developer terminal running an agent usually has cloud, Git and package registry tokens loaded. A misled approval can expose them. See the AI Coding Agents Security Guide.

Defences for developers of CLIs, agents and log tools

  1. Inventory display paths: list every place your tool prints data it did not generate: API fields, file contents, model output, tool results, error messages from remote services.
  2. Neutralise by default: replace C0 controls (except newline and tab where needed), DEL and C1 controls (0x80 to 0x9F) with visible escapes such as \x1b or caret notation before printing. Trail of Bits suggests replacing every 0x1B byte as a minimum; covering 0x9B and carriage return as well closes common gaps.
  3. Separate formatting from data: let your own code add colour after sanitising, so data can never carry its own formatting. Offer an explicit opt-in flag for raw output, as Embrace The Red recommends.
  4. Use allow lists, not block lists: if some formatting from data must pass (for example colourised build logs), allow only SGR colour codes and strip everything else, especially OSC, cursor movement and reports.
  5. Encode logs at write time: OWASP ASVS 5.0 requirement V16.4.1 asks that logging components encode data to prevent log injection. Structured JSON logs with escaped strings help, but check that your viewer does not unescape them back to raw bytes.
  6. Show hyperlink targets: render link destinations in full, or strip OSC 8 from untrusted text, and require confirmation before opening.
  7. Test end to end: add test fixtures that contain escape sequences to every field you display, including model output and MCP tool descriptions, and assert that the terminal shows escaped text. Run them in the terminals your users actually use.
  8. Roll out safely: ship sanitisation behind a flag for one release with a warning when sequences are stripped, check user reports of lost colour, then make it the default. Rolling back means turning the flag off, not removing the code.

Defences for terminal users and platform teams

ControlHowTrade-off
Patch terminal emulatorsTrack xterm, iTerm2, PuTTY, MinTTY (Git Bash, Cygwin), Windows Terminal and SSH clients in software inventory and update themLow; often missed because terminals are not seen as attack surface
Disable remote title changesPuTTY "Disable remote-controlled window title changing"; MobaXterm "Lock terminal title"Lose dynamic titles showing host or directory
Disable window operations and font opsxterm allowWindowOps and allowFontOps resources set to false (also disables OSC 52 clipboard writes in xterm)Remote clipboard copy over SSH stops working
Restrict clipboard writesUse the terminal's setting to block or prompt for OSC 52 where offeredSame as above
Keep bracketed paste onShell and terminal support for mode 2004, on patched versionsNone for most users
View untrusted files safelycat -v, less without -R or -r, or open in an editorNo colour in logs
Review before pastingPaste unknown commands into an editor firstSmall friction; also defends against paste-and-run lures. See the ClickFix and Fake CAPTCHA Paste-and-Run Attacks Guide

For a small team, patched terminals, safe viewing habits and a short note in the developer onboarding guide cover most of the risk. Larger organisations with internal CLIs, log tooling and agent platforms should make output sanitisation a secure coding standard and add it to code review checklists for any tool that prints external data.

Detection and measurement

Detection is hard after the fact because the effect happens on a screen, so focus on finding sequences in data before a human reads it.

  • Log pipeline scanning: alert when 0x1B, 0x9B or other control bytes appear in fields that should be printable text (user agents, user names, URLs). Count them per source.
  • Agent and MCP review: scan MCP tool descriptions and agent transcripts for control bytes during onboarding of a new server. See How to audit MCP servers on developer laptops.
  • Metrics: share of internal CLIs with sanitisation tests (target 100%); number of terminal emulator versions in the fleet below the vendor's fixed release; count of control-byte detections in logs per month; median days to patch a terminal emulator CVE; share of MCP servers reviewed for hidden content before approval.

Framework mapping

FrameworkReferenceRelevance
MITRE CWECWE-150The weakness: escape, meta or control sequences not neutralised before reaching a downstream component
MITRE CAPECCAPEC-93 Log Injection-Tampering-ForgingForging and hiding log content
OWASP ASVS 5.0V16.4.1Logging components encode data to prevent log injection
OWASP Top 10 for LLM Applications 2025LLM01 Prompt Injection, LLM05 Improper Output HandlingModel output carrying sequences into a terminal
NIST SP 800-53 Rev. 5SI-10, SI-15, AU-9Input validation, output filtering, protection of audit information
NIST CSF 2.0PR.PS-04, DE.AE-02Log records made available for monitoring; analysis of adverse events depends on trustworthy display
MITRE ATT&CK v20T1564 Hide Artifacts, T1036 Masquerading, T1204 User ExecutionClosest techniques for hiding content, disguising output and getting a user to run attacker input; no technique is specific to terminal escapes

Common failure patterns

  • Filtering only ESC: stripping 0x1B while leaving the C1 byte 0x9B or carriage return still lets text be overwritten in some terminals.
  • Trusting "internal" data: Kubernetes events, ticket titles and commit messages feel internal, but any user who can write them can target anyone who reads them, as CVE-2021-25743 showed.
  • Escaping in storage, unescaping in display: JSON logs store \u001b safely, then a pretty-printer or jq -r turns it back into a live byte on screen.
  • Showing raw model output: agent CLIs that render model text and tool results verbatim let a prompt injection decide what the approving human sees.
  • Ignoring terminal patching: terminal emulators and SSH clients sit outside patch reports because they are "just tools", leaving title and paste bypass bugs open for years.

Practitioner checklist

  • List every internal CLI, log viewer and agent tool that prints external or user-supplied data.
  • Make control-character neutralisation the default in those tools, with an explicit opt-in for raw output.
  • Strip OSC sequences, cursor movement and reports from untrusted data; allow at most SGR colours.
  • Add escape-sequence fixtures to tests for every displayed field, including model output and MCP tool descriptions.
  • Encode log fields at write time (ASVS V16.4.1) and check viewers do not re-emit raw bytes.
  • Bring terminal emulators and SSH clients into software inventory and patch management.
  • Disable remote title changes, window and font operations and unprompted clipboard writes where terminals allow it.
  • Teach analysts and developers to view untrusted files with cat -v or less without raw mode.
  • Review MCP servers for hidden content before approval and re-review on updates.

Standards and references

Related NHI Mgmt Group resources: AI Coding Agents Security Guide · Unicode Security · Local MCP Server Security Guide · Linux Logging and auditd for Defenders Guide · Restricted Shells Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 11 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.