Skip to content

About

Behavioral hijack detection for AI agent tool calls: PyOD + sequence models + hard rules, with an honest precision-at-realistic-attack-rate evaluation

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

hijackwatch

Behavioral hijack detection for AI agent tool calls. It watches what an agent does (which tools it calls, with what arguments, in what order, and where data flows) and flags sessions that look like a prompt-injection hijack: secret exfiltration, unexpected network calls, persistence writes, payments to destinations the user never mentioned.

Think "PyOD for agent traces": PyOD outlier models and a sequence model learn your normal tool-call behavior, and a few hard rules catch the attacks you never want to miss.

demo

The demo replays hook events from a session hijacked by a poisoned README. Nothing is executed: the key is a fake placeholder and the URL is 127.0.0.1.


Read this first: how well does it work?

Not as well as a headline AUROC would suggest, and this README says so up front.

Hijacks are rare events, so the metric that matters is precision at a realistic attack rate. If 2% of sessions are attacked, a detector with 80% recall and a 5% false-positive rate is wrong about 3 times for every real attack it finds (precision about 25%). This is the base-rate problem from fraud detection, and the audit preprint arXiv 2610.41803 showed that published agent-trace detectors fall apart under it.

So the evaluation harness:

  • trains every detector on benign traces only, because you will never have labelled attacks from your own agents;
  • sets the alert threshold on a separate benign calibration set (1% target FPR), so the test set never chooses the threshold;
  • splits by task, world or agent, never by trace, which defeats AgentDrift's documented world-identity leakage;
  • reports precision at 1% and 2% prevalence with exact Clopper–Pearson intervals, plus held-out-tool and cross-dataset protocols.

Hybrid detector (learned + rules), mean of 3 seeds, threshold set at a 1% target FPR on held-out benign traces:

protocol AUROC recall measured FPR precision @ 2% attack rate
AgentDojo, in-distribution (5 real LLMs) 0.84 16% 0.7% ~52% (wide CI: 6–96%)
AgentDojo, held-out tools 0.80 28% 9.0% 6.9%
AgentDrift, in-distribution (world split) 0.82 11% 0.45% 37%
AgentDrift, held-out tools 0.71 7% 0.76% 17%
Cross-dataset AgentDrift → AgentDojo 0.78 18% 3.8% 8.6%
Cross-dataset AgentDojo → AgentDrift 0.68 7% 0.64% 21%
ASB (templated), held-out agents 0.56 11% 0% (n=90) upper bound only
Real Claude Code sessions, rules only – 6/6 designed attack families spliced in; 1/3 of stealthy uploads 1 of 27 sessions see REAL_WORLD.md
Real Claude Code sessions, learned hybrid – – 33% of sessions not usable with a 27-session baseline
Live claude -p smoke test (3 sessions, 12 calls) – model refused the poisoned README itself; forced exfil got ask + critical 0 high/critical on benign calls (1 medium, log-only) see LIVE_TEST.md

Full tables, including every PyOD model, per-compliance-pattern recall and resisted-attack flag rates: results/RESULTS.md. Real Claude Code sessions: results/REAL_WORLD.md. Live Claude Code smoke test: results/LIVE_TEST.md.

What the numbers say

  1. Learned detectors alone are not deployable as blockers. At a 1% target FPR they find a small minority of hijacks on AgentDojo and AgentDrift, and precision at a 2% attack rate is modest even in-distribution.
  2. Unseen tools break calibration. Hold out 30% of AgentDojo's tools and the false-positive rate climbs far above its 1% target. Novelty detectors flag "new" as "bad", and every new MCP server is new.
  3. Cross-dataset transfer is weak. That's expected for a learned baseline, and it's the reason to fit on your own traces.
  4. Hard rules are precise but narrow. On real Claude Code sessions, after fixing three over-broad patterns, the high/critical rules fired 1.09 times per 1,000 tool calls, and they caught every spliced attack of the kinds they were written for. They catch essentially nothing on AgentDojo and AgentDrift, whose attacks are payments and emails rather than secret exfiltration.
  5. Provenance is the most useful learned-free signal. "This sink's destination came from a tool output, not from the user" (tainted_sink) fires on about half of AgentDojo hijacks. Its false-positive rate is too high to block on, but it is a strong alert feature.
  6. On a small personal baseline the learned layer is noise. It alerted on 33% of held-out real sessions with a 27-session baseline. Run it alert-only, and re-measure once you have hundreds of sessions.

Hence the default: hard rules can block (opt-in); learned scores only alert.

Known limitations

  • AgentDrift and ASB are not recorded behavior. AgentDrift is LLM-generated synthetic data. ASB ships no recorded runs, so its traces here are templated from its tool and task inventories; treat it as a tool-name stress test only.
  • AgentDojo covers 5 models with a single attack family (important_instructions), and has only 97 benign tasks per model.
  • Development leakage. v0.1 parameters were set while the in-distribution splits were visible. Trust the held-out-tool and cross-dataset numbers more.
  • The real-world check is small. It is one developer's 27 sessions, and the rule fixes were derived from the same sessions.
  • The rules are bypassable. Exfil without touching a known secret path, encoding tricks, or splitting an action across tools can evade them. That gap is what the learned layer is meant to cover, and today it does so poorly.

How it works

collector (Claude Code hook | transcripts | MCP proxy*)  ->  ToolCall events
   -> SessionAnalyzer: per-call facts + session state (secrets touched, tainted values)
       -> hard rules                                  -> alert / ask / block
       -> Featurizer -> PyOD (ECOD, IForest, HBOS, ...) \
       -> n-gram LM over tools + capabilities            +-> calibrated hybrid -> alert

* planned

Features. Tool names are abstracted to capabilities (READ, SEARCH, WRITE, EXEC, NET_READ, EGRESS, MONEY, AUTH, ...), so unseen tools still score sensibly. On top of that:

  • argument-type signatures
  • sensitive paths (~/.ssh, .env, cloud credentials, ...)
  • secrets in arguments
  • new and raw-IP hosts and known drop-box services
  • shell command patterns
  • capability and tool bigram novelty
  • provenance: sink destinations that came from tool outputs instead of the user

Hard rules:

rule severity fires when
secret_then_egress critical a secret was read earlier and data now leaves (upload, egress tool, URL payload)
secret_in_outbound_args critical outbound arguments contain secret material or fragments of a secret read earlier
remote_code_exec high curl ... | sh, base64 -d | sh, or reverse-shell patterns
exfil_destination high known drop-box/tunnel services or a raw public IP
persistence_write high writes to shell rc files, authorized_keys, git hooks, agent settings, LaunchAgents, cron
sensitive_read medium touches ~/.ssh, .env, credentials, ...
secret_then_network medium a plain GET after a secret read
tainted_sink medium a payment, message or permission sink whose destination came from a tool output

Install

uv tool install git+https://github.com/bishtashish708/hijackwatch

Python 3.12+. pipx install git+https://github.com/bishtashish708/hijackwatch works too.

Claude Code (project scope)

This writes hooks into <project>/.claude/settings.local.json only, never your global config. It is alert-only by default; --mode ask asks you to confirm high/critical calls, and --mode block denies them.

hijackwatch install --project-dir . --mode alert

Or load it as a plugin. The hijackwatch CLI must be on your PATH:

claude --plugin-dir /path/to/hijackwatch/plugin

Fit a baseline from your own history (optional)

hijackwatch import-transcripts --out ~/.hijackwatch/history.jsonl
hijackwatch fit ~/.hijackwatch/history.jsonl --fpr 0.01
hijackwatch score ~/.hijackwatch/history.jsonl --only-alerts

With a fitted model, the Stop hook scores each session in a detached background process, because PyOD and scikit-learn imports take 1–2 s. Learned alerts are shown at your next prompt. The PreToolUse path runs only the rules and stays in pure Python: about 125 ms per hook call in a live session, including interpreter start-up.

Other commands

hijackwatch check traces.jsonl   # rules only; exit 1 on high/critical (CI-friendly)
hijackwatch alerts -n 20         # recent alerts

The trace format is one JSON object per line: {"id", "calls": [{"tool", "args", "result"}], "context", "label"}. Any agent framework can emit it.

Privacy

  • Everything stays local. No network calls and no telemetry. Data lives under ~/.hijackwatch (override with HIJACKWATCH_HOME).
  • The hook stores tool inputs and outputs. Outputs are truncated to 20 KB per call; they're needed for secret and provenance tracking. Delete ~/.hijackwatch/sessions whenever you like.
  • Transcript import is read-only.
  • Demo and tests only: HIJACKWATCH_LOCAL_IS_EXTERNAL=1 makes loopback addresses count as external, so sandboxed demos can exercise the egress rules.

Positioning

approach learns your baseline evaluated at realistic attack rates
Snyk Agent Scan static config scan – –
Invariant Guardrails rules / policy language – –
NeMo Guardrails, LlamaFirewall classifiers + LLM judge on content – –
LLM Guard, Rebuff prompt classifiers (archived) – –
CaMeL capability-based isolation (by design) – –
Docker MCP Gateway, ToolHive isolation + logs – –
Claude Code hook collections fixed block patterns – –
Praetor (arXiv 2604.26274) learned allowed patterns, structured workflows ✓ –
hijackwatch behavior: PyOD + sequence LM + hard rules + provenance ✓ ✓

hijackwatch complements content classifiers and isolation; it doesn't replace them. It looks at actions, not text, so it can catch a hijack whatever wording the injection used. It can also miss one that looks like normal work.

Reproduce the benchmarks

git clone https://github.com/bishtashish708/hijackwatch && cd hijackwatch
uv sync
./scripts/fetch_data.sh                    # AgentDojo runs, AgentDrift, ASB (~400 MB, gitignored)
uv run python scripts/run_benchmarks.py    # ~4 min, writes results/RESULTS.md
uv run pytest -q
uv run python demo/make_gif.py             # re-render the demo GIF (or: vhs demo/demo.tape)

Datasets: AgentDojo, AgentDrift (CC BY 4.0), ASB. Only their public files are used, and none are redistributed here.

Roadmap

  • MCP stdio proxy collector; LangGraph and OpenAI Agents SDK callbacks
  • more live Claude Code red-team runs (web page, issue, MCP tool output; weaker models), beyond the first poisoned-README smoke test
  • understand exclusion flags (find -not -path, --exclude) in sensitive_read
  • a step-level localization metric on AgentDrift
  • per-capability calibration so new tools don't blow up the FPR

License

MIT

About

Behavioral hijack detection for AI agent tool calls: PyOD + sequence models + hard rules, with an honest precision-at-realistic-attack-rate evaluation

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages