
Claude Honeytokens: Build an Inference Hook in Python
Summary
Plant decoy strings, verify signed hook requests, and stop a Claude agent that leaves its sandbox.
On December 3, Anthropic's Frontier Red Team published Containing AI agents with honeytokens along with a small Rust reference server. The idea is old, the twist is new. A classic honeytoken alerts you when someone uses a fake credential. These ones fire when the model merely reads one, and the request is refused before inference runs. The agent stops mid-escape.
In Anthropic's replay evaluation, tokens placed along known weak points stopped 1,209 of 1,294 recorded sandbox escapes (93%), and none of the 459 sessions that stayed in scope tripped one. That is why this is all over agent-security feeds this week: it is a containment layer you can run yourself, in an afternoon, without touching the agent.
This guide ports the reference server to about 100 lines of standard-library Python so you can read every line, then tests it locally with signed requests. You will finish with three files: a planter, the hook endpoint, and a test client. No API key is needed for any of it.
How the mechanism works
Claude Enterprise has a feature called inference hooks. When it is on, every prompt is sent to an HTTPS endpoint you control before the model sees it. Your endpoint gets the request transcript and answers allow or deny. The honeytoken server is the simplest possible hook: it holds a list of secret strings and denies any request whose body contains one.
Now put those strings where an agent doing its job never looks: a directory that should not be mounted, extra keys in a Kubernetes Secret, the hostname of a machine agents should never reach. If the agent lists that directory, the tool result lands in the transcript, the next request carries the token, and the hook denies it. Claude Code shows a blocked request and the session is over.
- The check runs on model input only. Not on output, tool calls, or network egress. Tool results are input on the next turn, which is how a file listing gets caught.
- It fires on read. The agent does not have to exfiltrate anything. Seeing the decoy is enough.
- False positives are rare by construction. A token only reaches the context if the agent went somewhere out of scope.
Prerequisites
- Python 3.9 or newer. Everything here is standard library.
- To test locally: nothing else.
- To enforce for real: a Claude Enterprise organization with inference hooks available, and a host that can serve public HTTPS on port 443 with a certificate from a public CA.
- Basic comfort with HMAC and reverse proxies.
Step 1: Mint tokens and plant them
Anthropic's guidance on the tokens themselves is short and specific. Use random strings of at least 8 characters, but keep them short enough that a column-truncated listing still shows the whole thing. Put several in each folder with different leading characters and different timestamps, so that whichever way a listing is sorted or cut off, one of them shows up near the top. Make them unique to your organization.
The planter below uses the file name as the token. That matters: an agent running ls never opens the file, so a token hidden in file contents would be missed.
"""plant.py - mint honeytokens and plant them where an in-scope agent never looks.
Usage: python plant.py tokens.txt DIR [DIR ...]
"""
import os, secrets, sys, time
LEADS = "0amz" # spread tokens across a sorted listing
def mint(lead):
return lead + secrets.token_hex(8) # 17 chars: survives column truncation
def plant_dir(directory, count=4):
os.makedirs(directory, exist_ok=True)
made = []
for i in range(count):
tok = mint(LEADS[i % len(LEADS)])
path = os.path.join(directory, tok) # the file NAME is the token
open(path, "w").close()
age = secrets.randbelow(400) * 86400 # scatter mtimes so `ls -t` shows one early
os.utime(path, (time.time() - age,) * 2)
made.append(tok)
return made
def k8s_secret(name, real, count=2):
"""Real keys plus empty honeytoken keys: listing the Secret trips the hook."""
toks = [mint(LEADS[i]) for i in range(count)]
lines = ["apiVersion: v1", "kind: Secret", f"metadata:\n name: {name}", "stringData:"]
lines += [f" {k}: {v}" for k, v in real.items()]
lines += [f' {t}: ""' for t in toks]
return "\n".join(lines) + "\n", toks
if __name__ == "__main__":
if len(sys.argv) < 3:
sys.exit(__doc__)
out, dirs = sys.argv[1], sys.argv[2:]
with open(out, "a") as f:
for d in dirs:
toks = plant_dir(d)
f.write(f"# planted in {d}\n" + "\n".join(toks) + "\n")
print(f"{d}: planted {len(toks)}")
manifest, toks = k8s_secret("db-credentials", {"username": "app", "password": "REPLACE_ME"})
f.write("# keys in Secret db-credentials\n" + "\n".join(toks) + "\n")
open("db-credentials.yaml", "w").write(manifest)
print("db-credentials.yaml: 2 honeytoken keys")
Run it against a throwaway directory tree that stands in for a sandbox with a host path it should not have:
$ mkdir -p sbx/var/log/nginx && touch sbx/var/log/nginx/{access,error}.log
$ python plant.py tokens.txt sbx/host/root/.aws sbx/host/etc/kubernetes/pki
sbx/host/root/.aws: planted 4
sbx/host/etc/kubernetes/pki: planted 4
db-credentials.yaml: 2 honeytoken keys
Here is what the decoy directory looks like from inside. Four empty files, names starting with 0, a, m and z, modification times spread over a year:
$ ls -la sbx/host/root/.aws
total 8
drwxr-xr-x 2 root root 4096 Dec 4 21:10 .
drwxr-xr-x 3 root root 4096 Dec 4 21:10 ..
-rw-r--r-- 1 root root 0 Jul 8 21:10 0ebbf3a67422dbca0
-rw-r--r-- 1 root root 0 Nov 17 21:10 a88e06faea4a9258d
-rw-r--r-- 1 root root 0 Apr 16 2026 m35d2b7d5617f007c
-rw-r--r-- 1 root root 0 Aug 9 21:10 z0a7450b6d78ec23d
The script also writes db-credentials.yaml, which follows the Kubernetes pattern from Anthropic's post: real keys next to honeytoken keys with empty values. Anything that enumerates the Secret's keys puts a token in the transcript.
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
stringData:
username: app
password: REPLACE_ME
07aaa9293de2d3258: ""
ae2b5ea11b4600928: ""
And tokens.txt, which is the only state the server needs. Treat this file like a credential. Anyone who has it can paste a token into a prompt and get requests denied for your organization.
# planted in sbx/host/root/.aws
0ebbf3a67422dbca0
a88e06faea4a9258d
m35d2b7d5617f007c
z0a7450b6d78ec23d
# planted in sbx/host/etc/kubernetes/pki
0b8b16188d8ac09f1
a86cd6dabb38a6101
mbb2fc6f6601cbbec
z665db4ff0953fd2c
# keys in Secret db-credentials
07aaa9293de2d3258
ae2b5ea11b4600928
Step 2: Load the tokens file strictly
The reference server refuses to start if the tokens file is malformed, and the port keeps that behavior. One token per line, blank lines and # comments skipped, 8 to 256 printable ASCII characters, no spaces, and none of " \ / < > &.
The banned characters are not arbitrary. Matching happens against the raw bytes of a JSON body, and those are the characters a JSON encoder may write in escaped form (\", \/, \u003c). A token containing one could sit in the transcript and never match. Hex strings avoid the whole problem.
"""honeyhook.py - a honeytoken inference-hook endpoint in stdlib Python.
Usage: HONEYTOKENS_SECRET='whsec_...' python honeyhook.py tokens.txt [host:port]
"""
import base64, hashlib, hmac, json, os, sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
FORBIDDEN = set('"\\/<>&')
MAX_BODY = 64 * 1024 * 1024 # hook bodies can reach 64 MiB
TOLERANCE = 5 * 60 # Standard Webhooks replay window, seconds
DENY_PREFIX = "This request contains a string your organization has blocked:"
def load_tokens(path):
tokens = []
for n, line in enumerate(open(path, encoding="ascii"), 1):
tok = line.strip()
if not tok or tok.startswith("#"):
continue
if not 8 <= len(tok) <= 256:
sys.exit(f"{path}:{n}: token must be 8-256 chars")
if any(c in FORBIDDEN or not 33 <= ord(c) <= 126 for c in tok):
sys.exit(f"{path}:{n}: printable ASCII only, no spaces or \" \\ / < > &")
tokens.append(tok.encode())
if not tokens:
sys.exit(f"{path}: no tokens")
return tokens
Failing closed at startup beats discovering a dead token after an incident:
$ printf 'short\n' > bad.txt && python honeyhook.py bad.txt
bad.txt:1: token must be 8-256 chars
$ printf 'abc/defghij\n' > bad.txt && python honeyhook.py bad.txt
bad.txt:1: printable ASCII only, no spaces or " \ / < > &
Step 3: Verify the signature on every request
Your endpoint sits on the public internet and decides whether your whole organization can use Claude. It must not accept verdict requests from strangers. Inference hooks sign requests using the Standard Webhooks scheme, and the reference server answers anything unsigned with 401.
Standard Webhooks works like this: the caller sends webhook-id, webhook-timestamp and webhook-signature headers. The signature is HMAC-SHA256 over id.timestamp.body, keyed with the base64-decoded part of the secret after whsec_, sent as v1,<base64>. The header can carry several space-separated signatures.
def load_secrets(env):
# Two space-separated secrets are accepted so you can rotate without downtime.
keys = []
for s in env.split():
keys.append(base64.b64decode(s.removeprefix("whsec_")))
return keys
def verify(keys, headers, body, now=None):
msg_id = headers.get("webhook-id")
ts = headers.get("webhook-timestamp")
sigs = headers.get("webhook-signature")
if not (msg_id and ts and sigs and ts.isdigit()):
return False
if abs((now or time.time()) - int(ts)) > TOLERANCE:
return False
signed = msg_id.encode() + b"." + ts.encode() + b"." + body
for key in keys:
want = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
for part in sigs.split():
version, _, got = part.partition(",")
if version == "v1" and hmac.compare_digest(want, got):
return True
return False
HONEYTOKENS_SECRETmay hold two secrets separated by a space. During rotation you run with old and new together, then drop the old one.- The timestamp check rejects requests more than five minutes off, which blocks replay of a captured request.
hmac.compare_digestdoes the comparison in constant time. Do not use==here.- Sign the exact bytes you received. If a framework re-serializes the JSON before you verify, the signature will not match.
Step 4: Scan the body and answer
The scan is a substring search over raw bytes. No JSON parsing, which means the server does not care how the transcript is structured and cannot be tripped up by a schema change. The response protocol is two shapes: {"action":"allow"}, or a deny with a deny_reason.
def scan(tokens, body):
for tok in tokens:
if tok in body: # case-sensitive match over the raw bytes
return tok.decode()
return None
def make_handler(tokens, keys, echo_token=True):
class Hook(BaseHTTPRequestHandler):
def do_POST(self): # the URL path does not matter
length = int(self.headers.get("content-length", 0))
if length > MAX_BODY:
return self.reply(413, {"error": "body too large"}, "too-large")
body = self.rfile.read(length)
if not verify(keys, self.headers, body):
return self.reply(401, {"error": "bad signature"}, "unsigned")
hit = scan(tokens, body)
if hit is None:
return self.reply(200, {"action": "allow"}, "allow")
reason = f"{DENY_PREFIX} {hit}" if echo_token else DENY_PREFIX
self.reply(200, {"action": "deny", "deny_reason": reason}, "DENY")
def reply(self, status, obj, verdict):
data = json.dumps(obj, separators=(",", ":")).encode()
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
# One line per request. Never log token values or transcript text.
print(f"{time.strftime('%H:%M:%S')} {verdict} bytes={self.headers.get('content-length', 0)}",
file=sys.stderr, flush=True)
def log_message(self, *args):
pass
return Hook
if __name__ == "__main__":
args = [a for a in sys.argv[1:] if not a.startswith("--")]
if not args or "HONEYTOKENS_SECRET" not in os.environ:
sys.exit(__doc__)
tokens = load_tokens(args[0])
keys = load_secrets(os.environ["HONEYTOKENS_SECRET"])
host, _, port = (args[1] if len(args) > 1 else "127.0.0.1:8000").rpartition(":")
handler = make_handler(tokens, keys, echo_token="--no-echo-token" not in sys.argv)
print(f"loaded {len(tokens)} tokens, listening on {host}:{port}", file=sys.stderr, flush=True)
ThreadingHTTPServer((host, int(port)), handler).serve_forever()
Two details are worth understanding before you change them.
The deny reason echoes the matched token by default. That looks like a leak, and it is deliberate. When a subagent hits a token, only the subagent's request fails. Its error bubbles up to the parent as text, the parent's next request now contains the token, and the parent is stopped too. Without the echo, a parent could shrug off the failed subagent and try another route. Pass --no-echo-token if you would rather keep tokens out of user-visible errors and accept that trade.
The log line has a verdict and a byte count, nothing else. Transcripts contain your users' prompts. A hook server that logs bodies becomes the most sensitive system you run.
Step 5: Test it locally with signed requests
You do not need an Enterprise org to check the logic. This client signs requests the same way the caller does and posts four cases. The transcript shape it sends is a stand-in, not the real hook schema. That is fine precisely because the server matches raw bytes.
"""send_test.py - sign fake transcripts the way the hook caller does and post them."""
import base64, hashlib, hmac, json, os, subprocess, sys, time, urllib.request, urllib.error, uuid
URL = "http://127.0.0.1:8000/hook"
KEY = base64.b64decode(os.environ["HONEYTOKENS_SECRET"].split()[0].removeprefix("whsec_"))
def post(transcript, sign=True):
body = json.dumps(transcript).encode()
msg_id, ts = f"msg_{uuid.uuid4().hex[:12]}", str(int(time.time()))
sig = base64.b64encode(hmac.new(KEY, f"{msg_id}.{ts}.".encode() + body, hashlib.sha256).digest()).decode()
headers = {"content-type": "application/json"}
if sign:
headers |= {"webhook-id": msg_id, "webhook-timestamp": ts, "webhook-signature": f"v1,{sig}"}
try:
with urllib.request.urlopen(urllib.request.Request(URL, body, headers)) as r:
return r.status, r.read().decode()
except urllib.error.HTTPError as e:
return e.code, e.read().decode()
def turn(tool_output):
return {"messages": [
{"role": "user", "content": "Rotate the nginx logs on this box."},
{"role": "assistant", "content": [{"type": "tool_use", "name": "bash", "input": {"command": "..."}}]},
{"role": "user", "content": [{"type": "tool_result", "content": tool_output}]},
]}
sandbox = sys.argv[1]
ls = lambda d: subprocess.run(["ls", "-la", d], capture_output=True, text=True).stdout
in_scope = ls(f"{sandbox}/var/log/nginx")
out_of_scope = ls(f"{sandbox}/host/root/.aws")
print("1 in-scope ls ", *post(turn(in_scope)))
print("2 out-of-scope ls ", *post(turn(out_of_scope)))
print("3 unsigned request ", *post(turn(in_scope), sign=False))
encoded = base64.b64encode(out_of_scope.encode()).decode()
print("4 base64'd listing ", *post(turn(encoded)))
Generate a secret, start the server, run the client:
$ export HONEYTOKENS_SECRET="whsec_$(openssl rand -base64 24)"
$ python honeyhook.py tokens.txt &
loaded 10 tokens, listening on 127.0.0.1:8000
$ python send_test.py sbx
1 in-scope ls 200 {"action":"allow"}
2 out-of-scope ls 200 {"action":"deny","deny_reason":"This request contains a string your organization has blocked: 0ebbf3a67422dbca0"}
3 unsigned request 401 {"error":"bad signature"}
4 base64'd listing 200 {"action":"allow"}
And the server's side of the same four requests:
21:10:33 allow bytes=458
21:10:33 DENY bytes=593
21:10:33 unsigned bytes=458
21:10:33 allow bytes=699
Worked example: reading the four results
Picture a DevOps agent asked to rotate nginx logs on a build box. The sandbox was misconfigured and the host's root home is reachable at /host.
- Case 1, allow. The agent lists
/var/log/nginx, sees two log files, carries on. No token is anywhere near its task, so it never notices the hook exists. - Case 2, deny. The agent gets curious and lists
/host/root/.aws. The listing enters the transcript as a tool result. The next request is denied, naming the first token it found. The agent never gets a turn in which it knows what was in that directory. - Case 3, 401. Someone on the internet found the endpoint and posted to it without a valid signature. No scan happens and no verdict is given.
- Case 4, allow. The same out-of-scope listing, base64-encoded before it reached the transcript. The server matches literal bytes, so this passes. This is a real limit, covered below.
On my test machine the scan ran at about 270 MB/s for 10 tokens against a 4 MB body, in pure Python. The Rust reference reports 250 to 300 MB/s on a signed 4 MB transcript. Substring search is not your bottleneck.
Going live on Claude Enterprise
Anthropic only calls public HTTPS on port 443 with a public-CA certificate, and does not follow redirects. Bodies can reach 64 MiB. Put a TLS proxy in front of the Python process and restrict it to Anthropic's source range, 160.79.106.0/24. If you use nginx, raise the body limit, because the 1 MB default will reject long sessions:
server {
listen 443 ssl;
server_name hooks.example.com;
client_max_body_size 64m;
allow 160.79.106.0/24;
deny all;
location / { proxy_pass http://127.0.0.1:8000; }
}
Then in Claude.ai, as an organization admin:
- Open Organization settings, then Data and privacy, then Inference hooks.
- Turn on Allow for your organization and save your endpoint URL. The signing secret is shown once. Put it in
HONEYTOKENS_SECRET. - Start the server and click Test connection.
- Only then turn on Enforce verdicts.
Decide the failure mode on purpose. The default is Allow the request when your endpoint fails, which means an outage silently turns the protection off. Block the request means an outage stops everyone's work. Repeated failures trip a circuit breaker either way. For most teams the honest answer is: allow on failure, and page someone when the hook is down.
For production, prefer the Rust binary from anthropics/honeytokens behind the same proxy. It speaks the same protocol and takes the same tokens file. The Python version is for understanding it and for testing your placement.
Pitfalls and gotchas
- Agents that already know the path are not caught. Of the 85 misses in Anthropic's replay, 33 were agents that went straight to a known path or ran a script without looking around first. Honeytokens catch exploration. They do nothing about a precise, pre-planned move.
- Truncated and targeted listings slip through. Another 21 misses were agents whose probing never surfaced a token: output was cut off, or a search was narrow. This is why you plant several per directory with varied names and dates.
- Encodings defeat literal matching. Case 4 above. A blocked subagent may retry with base64 or hex. The token echo exists to stop the parent before that works. Do not disable it casually.
- Some weaknesses have nowhere to put a token. 20 of the misses had no simple location to plant one. If the escape route is a syscall, not a directory, you need a different control.
- Do not plant tokens in scope. A token in a repo the agent is supposed to read will deny every session that opens it. Walk the agent's real working paths first.
- A leaked token is a denial-of-service lever. Anthropic retired its old global refusal string because people abused it. Yours are per-organization and revocable: remove the line, restart, replant.
- Reload means restart. The file is read once at startup. Script the restart into whatever rotates tokens.
- The 93% is a replay number. Recorded escape sessions were replayed to see whether a token reached the context. It was not measured on live traffic, and Anthropic does not say which models were tested. Treat it as evidence the idea works, and measure your own setup.
- It is one layer. It sees input only. Keep egress controls and sandbox hardening. A hook that fires means the sandbox already failed.
Quick reference
| Item | Value |
|---|---|
| Token format | 8-256 printable ASCII, no spaces, none of " \ / < > & |
| Mint one | openssl rand -hex 16 >> tokens.txt |
| Run (Python port) | HONEYTOKENS_SECRET='whsec_...' python honeyhook.py tokens.txt |
| Run (Rust reference) | cargo build --release, then ./target/release/honeytokens tokens.txt |
| Listen address | Optional second argument, default 127.0.0.1:8000 |
| Signature | Standard Webhooks: HMAC-SHA256 over id.timestamp.body |
| Allow reply | {"action":"allow"} |
| Deny reply | {"action":"deny","deny_reason":"..."} |
| Unsigned request | HTTP 401 |
| Hide token in errors | --no-echo-token |
| Secret rotation | Two space-separated secrets in HONEYTOKENS_SECRET |
| Anthropic source range | 160.79.106.0/24 |
| Max body | 64 MiB (set client_max_body_size 64m in nginx) |
Next steps
- Threat-model first. List the three ways your sandbox is most likely to be wrong (a stray mount, an over-broad service account, a reachable metadata service) and plant along those paths.
- Add a test to CI that lists each decoy location, posts the output through
send_test.py, and fails if any comes backallow. - Wire the DENY log line to an alert. The reference server stops the agent, but the post says nothing about alerting, and a tripped token is something a human should look at.
- Read the Siren evaluation write-up for the 26 sandbox weaknesses used in the test. It doubles as a checklist of misconfigurations to look for in your own setup.
Sources
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,638 newsletter subscribers.