-
Notifications
You must be signed in to change notification settings - Fork 94
feat(security): add canary token and tool allowlist sandbox hooks #564
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
24ba5cd
feat(security): add canary token and tool allowlist sandbox hooks
waynesun09 9ed5090
fix(security): omit allowed tool list from block reason string
waynesun09 ee584fa
feat(security): add canary pretool hook to catch exfiltration via too…
waynesun09 f37b860
fix(security): harden hooks based on multi-agent code review
waynesun09 9868ba5
fix(security): case-insensitive canary matching and test env isolation
waynesun09 a3f5867
test(security): add case-insensitive and MCP tool canary tests
waynesun09 f84c91e
fix(security): correct default triage allowlist MCP tool names
waynesun09 175bc37
fix(security): remove default triage allowlist, fail-closed on unset env
waynesun09 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| #!/usr/bin/env python3 | ||
| """Claude Code PostToolUse hook: canary token leak detection. | ||
|
|
||
| Checks whether a pre-injected canary token appears in tool results. | ||
| If the canary leaks, the agent is exfiltrating the system prompt or | ||
| secrets, or poisoned content echoed the token back. | ||
|
|
||
| This hook blocks (exit 1) on canary detection because a canary leak | ||
| is a definitive exfiltration signal requiring immediate termination. | ||
|
|
||
| Protocol: reads JSON from stdin (tool_name, tool_input, tool_result), | ||
| writes JSON to stdout if blocking. Exit 0 = allow, exit 1 = block. | ||
|
|
||
| Environment variables: | ||
| FULLSEND_CANARY_TOKEN: The canary string to watch for in tool results. | ||
| If unset, the hook is a no-op (allow all). | ||
|
|
||
| Known limitations: | ||
| - Plain substring match only. Encoded representations (base64, | ||
| URL-encoding, hex escaping) will evade detection. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import os | ||
| import sys | ||
| from datetime import UTC, datetime | ||
|
|
||
| FINDINGS_PATH = "/tmp/workspace/.security/findings.jsonl" | ||
| MAX_INPUT_BYTES = 10 * 1024 * 1024 # 10 MB | ||
|
|
||
| _ERR_MALFORMED = '{"decision":"block","reason":"CANARY_HOOK_ERROR: malformed JSON input"}' | ||
| _ERR_UNEXPECTED = ( | ||
| '{"decision":"block","reason":"CANARY_HOOK_ERROR: unexpected error reading input"}' | ||
| ) | ||
| _ERR_OVERSIZED = '{"decision":"block","reason":"CANARY_HOOK_ERROR: input exceeds 10 MB limit"}' | ||
|
|
||
|
|
||
| def log_finding(name: str, severity: str, detail: str, action: str) -> None: | ||
| trace_id = os.environ.get("FULLSEND_TRACE_ID", "") | ||
| finding = { | ||
| "trace_id": trace_id, | ||
| "timestamp": datetime.now(UTC).isoformat(), | ||
| "phase": "hook_posttool", | ||
| "scanner": "canary_posttool", | ||
| "name": name, | ||
| "severity": severity, | ||
| "detail": detail, | ||
| "action": action, | ||
| } | ||
| try: | ||
| os.makedirs(os.path.dirname(FINDINGS_PATH), exist_ok=True) | ||
| with open(FINDINGS_PATH, "a") as f: | ||
| f.write(json.dumps(finding) + "\n") | ||
| except OSError: | ||
| pass | ||
|
|
||
|
|
||
| def main() -> None: | ||
| try: | ||
| raw = sys.stdin.read(MAX_INPUT_BYTES + 1) | ||
| if len(raw) > MAX_INPUT_BYTES: | ||
| sys.stdout.write(_ERR_OVERSIZED) | ||
| sys.exit(1) | ||
| if not raw.strip(): | ||
| sys.exit(0) | ||
| hook_input = json.loads(raw) | ||
| except json.JSONDecodeError: | ||
| sys.stdout.write(_ERR_MALFORMED) | ||
| sys.exit(1) | ||
| except Exception: # noqa: BLE001 | ||
| sys.stdout.write(_ERR_UNEXPECTED) | ||
| sys.exit(1) | ||
|
|
||
| canary = os.environ.get("FULLSEND_CANARY_TOKEN", "").strip() | ||
| if not canary: | ||
| sys.exit(0) | ||
|
|
||
| tool_result = hook_input.get("tool_result", "") | ||
| if not isinstance(tool_result, str): | ||
| tool_result = json.dumps(tool_result) | ||
|
|
||
| if canary.lower() in tool_result.lower(): | ||
| tool_name = hook_input.get("tool_name", "unknown") | ||
| reason = f"CANARY_LEAKED: canary token found in {tool_name} result" | ||
| log_finding("canary_leak", "critical", reason, "block") | ||
| json.dump({"decision": "block", "reason": reason}, sys.stdout) | ||
| sys.exit(1) | ||
|
|
||
| sys.exit(0) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| """Tests for canary_posttool.py PostToolUse hook.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import os | ||
| import subprocess | ||
| import sys | ||
|
|
||
| HOOK_PATH = os.path.join(os.path.dirname(__file__), "canary_posttool.py") | ||
|
|
||
|
|
||
| def _run_hook(stdin_data: str, env_extra: dict[str, str] | None = None) -> tuple[int, str]: | ||
| env = {k: v for k, v in os.environ.items() if k != "FULLSEND_CANARY_TOKEN"} | ||
| env.update(env_extra or {}) | ||
| result = subprocess.run( | ||
| [sys.executable, HOOK_PATH], | ||
| input=stdin_data, | ||
| capture_output=True, | ||
| text=True, | ||
| env=env, | ||
| ) | ||
| return result.returncode, result.stdout | ||
|
|
||
|
|
||
| def test_no_canary_configured_allows_all(): | ||
| env = {k: v for k, v in os.environ.items() if k != "FULLSEND_CANARY_TOKEN"} | ||
| result = subprocess.run( | ||
| [sys.executable, HOOK_PATH], | ||
| input=json.dumps({"tool_name": "Bash", "tool_result": "some output"}), | ||
| capture_output=True, | ||
| text=True, | ||
| env=env, | ||
| ) | ||
| assert result.returncode == 0 | ||
| assert result.stdout == "" | ||
|
|
||
|
|
||
| def test_canary_not_present_allows(): | ||
| code, stdout = _run_hook( | ||
| json.dumps({"tool_name": "Bash", "tool_result": "normal output"}), | ||
| {"FULLSEND_CANARY_TOKEN": "SECRET_CANARY_xyz"}, | ||
| ) | ||
| assert code == 0 | ||
| assert stdout == "" | ||
|
|
||
|
|
||
| def test_canary_leaked_blocks(): | ||
| code, stdout = _run_hook( | ||
| json.dumps({"tool_name": "Bash", "tool_result": "found SECRET_CANARY_xyz in output"}), | ||
| {"FULLSEND_CANARY_TOKEN": "SECRET_CANARY_xyz"}, | ||
| ) | ||
| assert code == 1 | ||
| response = json.loads(stdout) | ||
| assert response["decision"] == "block" | ||
| assert "CANARY_LEAKED" in response["reason"] | ||
|
|
||
|
|
||
| def test_canary_in_json_tool_result_blocks(): | ||
| code, stdout = _run_hook( | ||
| json.dumps( | ||
| {"tool_name": "mcp__github__issue_read", "tool_result": {"body": "SECRET_CANARY_xyz"}} | ||
| ), | ||
| {"FULLSEND_CANARY_TOKEN": "SECRET_CANARY_xyz"}, | ||
| ) | ||
| assert code == 1 | ||
| response = json.loads(stdout) | ||
| assert response["decision"] == "block" | ||
|
|
||
|
|
||
| def test_malformed_json_fails_closed(): | ||
| code, stdout = _run_hook( | ||
| "not valid json{{{", | ||
| {"FULLSEND_CANARY_TOKEN": "SECRET_CANARY_xyz"}, | ||
| ) | ||
| assert code == 1 | ||
| response = json.loads(stdout) | ||
| assert response["decision"] == "block" | ||
| assert "malformed" in response["reason"].lower() | ||
|
|
||
|
|
||
| def test_case_insensitive_canary_blocks(): | ||
| code, stdout = _run_hook( | ||
| json.dumps({"tool_name": "Bash", "tool_result": "leaked secret_canary_XYZ in output"}), | ||
| {"FULLSEND_CANARY_TOKEN": "SECRET_CANARY_xyz"}, | ||
| ) | ||
| assert code == 1 | ||
| response = json.loads(stdout) | ||
| assert response["decision"] == "block" | ||
| assert "CANARY_LEAKED" in response["reason"] | ||
|
|
||
|
|
||
| def test_empty_stdin_allows(): | ||
| code, stdout = _run_hook( | ||
| "", | ||
| {"FULLSEND_CANARY_TOKEN": "SECRET_CANARY_xyz"}, | ||
| ) | ||
| assert code == 0 | ||
| assert stdout == "" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.