Docs

Runtime Shield

Runtime Shield provides real-time threat detection for Claude Code tool calls and OpenClaw AI agents. It is available on all plans. Shield evaluation runs on every tool call regardless of plan tier -- plan limits only affect event visibility in the Activity page, not protection.


Claude Code Runtime Shield

Runtime Shield for Claude Code evaluates every tool call before Claude Code executes it, blocking dangerous operations in real time. It runs as a pair of HTTP hooks (PreToolUse and PostToolUse) that send tool calls to Clawkeeper's detection engine for evaluation.

How It Works

  1. Claude Code is about to execute a tool (Bash, Write, Read, Edit, Glob, Grep, WebFetch, etc.)
  2. The PreToolUse HTTP hook sends the tool name and input to POST /api/v1/claude-code/evaluate
  3. Clawkeeper runs the detection engine: 55+ regex patterns, command analysis, path checking, and org policy enforcement
  4. Returns allow ({}) or deny ({hookSpecificOutput: {permissionDecision: "deny", reason: "..."}})
  5. Claude Code blocks the tool call or proceeds based on the response
  6. After execution, the PostToolUse hook sends the result to POST /api/v1/claude-code/audit for the audit trail and output-side threat detection

The entire evaluation happens in under 5ms on cache hit. Org data (plan, policies, shield config) is cached in-memory for 30 seconds, eliminating database round-trips on repeated calls within the same session.

Detection Patterns

The detection engine includes 55+ patterns organized by tool type. Each pattern is tuned for developer workflows -- normal development activity (running tests, editing source files, using git) should never trigger a detection.

Bash Command Patterns

Patterns that detect dangerous commands a compromised session might execute:

CategoryExamplesSeverity
Credential exfiltrationcat .env | curl, piping secrets to network commands, embedding credentials via subshellCritical
Reverse shellsbash -i >& /dev/tcp, netcat with exec, python/perl/ruby socket connects, base64-encoded payloads piped to shellCritical
Security control bypassDisabling firewalls (ufw disable, iptables -F), SELinux/AppArmor teardown, stopping endpoint protection agentsCritical
Destructive operationsrm -rf /, recursive deletion of home/system directoriesCritical
Privilege escalationSetting SUID/SGID bits (chmod u+s)Critical
History tamperingClearing shell history, unsetting HISTFILE, shredding log filesHigh
SSH key exfiltrationReading private keys combined with network commands in the same chainCritical
Cryptominingxmrig, cpuminer, stratum+tcp pool connections, curl-to-bash mining scriptsCritical
DNS exfiltrationEncoding data in DNS queries via dig/nslookup with subshellsHigh
Suspicious package installspip/npm/gem install from raw URLs instead of registriesHigh
System password accessReading /etc/shadow or /etc/master.passwdHigh

File Write Patterns

Applied to Edit and Write tool calls. Only the file path is scanned (not content) to avoid false positives on legitimate encoded strings in source code:

CategoryExamplesSeverity
System file writesWriting to /etc, /usr, /var, /System, /LibraryCritical
SSH config injectionModifying ~/.ssh/authorized_keys, ~/.ssh/config, /etc/ssh/sshd_configCritical
Startup script injectionWriting to .bashrc, .zshrc, .profile, .bash_profile (persistence mechanism)High
CI/CD tamperingModifying .github/workflows/, .gitlab-ci.yml, JenkinsfileHigh
Git hook injectionWriting to .git/hooks/ (potential supply chain attack vector)High
Cron/scheduled task injectionWriting to /etc/cron*, LaunchDaemons, LaunchAgentsCritical

Sensitive File Read Patterns

Applied to Read, Glob, and Grep tool calls. Reads are never blocked -- only warned and logged -- because developers legitimately access these files. The goal is visibility:

CategoryExamplesSeverity
Environment files.env, .env.local, .env.production, .env.secretHigh
SSH keys~/.ssh/id_rsa, id_ed25519, id_ecdsaCritical
Cloud credentials~/.aws/credentials, ~/.config/gcloud/credentials.json, ~/.kube/configCritical
Registry tokens.npmrc, .pypirc, .git-credentials, .netrcHigh
System security files/etc/shadow, /etc/sudoers, GPG private keysCritical
Database credentials.pgpass, .my.cnfHigh
Vault tokens.vault-tokenCritical

WebFetch/WebSearch Patterns

CategoryExamplesSeverity
Exfiltration endpointsrequestbin.com, webhook.site, pipedream.net, ngrok, burpcollaboratorHigh
Raw IP fetchesHTTP requests to non-private IP addresses (potential C2 communication)Medium

Prompt Injection Patterns

Applied to UserPromptSubmit events (when enabled):

CategoryExamplesSeverity
Instruction override"ignore previous instructions", "disregard all rules"Critical
Persona hijack"you are now...", "pretend there are no restrictions"Critical
Jailbreak attempts"DAN mode", "do anything now", "developer mode"Critical
Data exfiltration requests"send all my data to...", "upload credentials to..."Critical
Credential extraction"show all my API keys", "dump passwords"High
Security disable requests"disable the firewall", "turn off monitoring"High

Policy Enforcement

Before the detection engine runs, Clawkeeper checks org-level policies. These are hard blocks -- they apply regardless of security level:

Blocked tools -- Deny specific tool types entirely. If Write is in the blocked tools list, every Write call is denied.

Blocked commands -- Substring match against Bash command text. Add docker run to block all Docker container launches.

Blocked write paths -- Glob patterns against file paths for Write/Edit. Supports * (single segment) and ** (recursive). Example: /etc/** blocks all writes under /etc/.

Sensitive read paths -- Glob patterns that flag reads of sensitive files. Unlike blocked paths, these allow the read but inject a warning into Claude Code's context and log the event.

WebFetch controls -- Toggle web fetching on/off entirely, or restrict to an allowed domain list.

Allowed git remotes -- Restrict which repositories can be cloned or pushed to.

Require sandbox -- Enforce that Claude Code is running in sandbox mode.

MCP skill restrictions:

  • Blocked skills -- Deny specific MCP servers or tools (e.g., mcp__github blocks all GitHub MCP tools)
  • Allowed skills only -- Allowlist mode: if non-empty, only listed skills are permitted
  • Warn-only skills -- Downgrade blocks to warnings for specific skills (useful for monitoring without disruption)

Configure policies in the dashboard at Settings > Claude Code Policies.

Group Policy Overrides

When an Identity Provider (IdP) is connected, policies can be overridden per group. Group overrides follow a most restrictive wins merge strategy -- group policies ADD restrictions on top of the org default, they never reduce security. For example, if the org blocks Write and a group also blocks Bash, members of that group have both tools blocked.

Security level overrides also follow most-restrictive-wins: if the org is set to "moderate" and the group override is "strict", group members get "strict".

Audit Trail

Every tool call is logged via the PostToolUse hook to POST /api/v1/claude-code/audit:

  • Verdict: passed, blocked, or warned
  • Severity: critical, high, or medium
  • Matched pattern: the specific detection pattern that triggered (e.g., credential_exfil, ssh_config_write)
  • Tool name: Bash, Write, Edit, Read, Glob, Grep, WebFetch, MCP skills, etc.
  • Input summary: truncated command/path for context (80 chars for commands, 120 chars for paths)
  • Session ID: links the event to a specific Claude Code session
  • Host: resolved via hostname, session ID, working directory, or most-recently-active fallback

The audit endpoint also runs output-side threat detection on tool results. For observation tools (Read, Glob, Grep, WebFetch, WebSearch), it scans the output for prompt injection patterns. For other tools, it runs the standard shield detection engine on the output text. This catches cases where a tool's output contains injected instructions designed to manipulate Claude Code's behavior.

Events are searchable on the Activity page, filterable by host, verdict, severity, pattern, and time range.

When log_all_tool_calls is enabled in policies, every tool call is recorded -- including passed evaluations. This provides complete visibility into Claude Code activity across your fleet.

Configuration

  1. Go to Settings > Claude Code Policies in the dashboard
  2. Set the security level (paranoid, strict, moderate, or minimal)
  3. Toggle auto-block on or off
  4. Add blocked tools, commands, write paths, and skills as needed
  5. Configure sensitive read paths for visibility into credential access
  6. Save -- policies sync to the evaluation endpoint automatically via the in-memory cache (30-second TTL)

The hooks are configured on each workstation. See the Installation guide for setup instructions.

Fail-Open Design

The evaluation endpoint is designed to never cause a "hook error" in Claude Code. If anything goes wrong (malformed request, database error, unhandled exception), the endpoint returns an allow response. This ensures that a Clawkeeper outage or misconfiguration does not break your development workflow.


OpenClaw Runtime Shield

For organizations running OpenClaw AI agents, Runtime Shield provides real-time prompt injection defense across all messaging channels.

Dual-Layer Architecture

LayerProtectsHow
Proxy layerWeb chat, Console, HTTP /v1/chat/completionsIntercepts in the Next.js chat proxy route before forwarding to the gateway
Hook layerExternal channels (Telegram, Discord, WhatsApp)OpenClaw message:received hook runs inside the gateway process

Both layers use the same detection engine and write to the same shield_events table. The proxy layer is the only protection for web and Console chat -- OpenClaw's message:received hook does not fire for Control UI or HTTP API requests.

On cloud instances, both layers are enabled automatically during provisioning.

Installation

clawkeeper.sh shield install

This installs the Runtime Shield skill into ~/.openclaw/skills/runtime-shield/ and the hook into ~/.openclaw/hooks/runtime-shield/. The skill activates automatically on the next OpenClaw session.

Prerequisites

  • OpenClaw installed and configured
  • Node.js / npm available
  • Clawkeeper API key (for dashboard connectivity; optional for local-only mode)

5 Detection Layers

Runtime Shield for OpenClaw runs 5 detection layers in sequence on every message:

Layer 1: Regex Patterns -- Pattern-based detection for known injection techniques: persona hijack, instruction override, boundary escape (XML tags, markdown separators, special tokens), social engineering, encoding/obfuscation (base64, zero-width characters, homoglyphs), tool/data exfiltration, and command injection.

Layer 2: Semantic Scoring -- Weighted anomaly scoring across 5 signal categories:

SignalWeight
Persona hijack0.30
Instruction overwrite0.25
Boundary escape0.20
Social engineering0.15
Encoding obfuscation0.10

Flags when combined score exceeds 0.20.

Layer 3: Context Integrity -- Validates turn types and detects impersonation: tool response impersonation in user messages, system message markers in user input, multi-role conversation injection.

Layer 4: Blacklist -- Exact match plus fuzzy matching (Levenshtein distance of 2 or less). 19 default entries plus custom entries configurable via the dashboard. Fuzzy matching catches typo-based evasion attempts.

Layer 5: Entropy Heuristic -- Statistical analysis for obfuscation: Shannon entropy analysis (threshold 4.5), base64 block detection, context flooding, and repetition/low-diversity detection.

Slash Commands

Use these inside any OpenClaw session with Runtime Shield installed:

CommandDescription
/shield statusCurrent level, session stats, dashboard connection
/shield level <level>Override security level locally
/shield blacklist add/remove/listManage local blacklist
/shield log [count]Show recent events from local log
/shield syncForce policy re-sync from dashboard
/shield statsDetection statistics since startup

API Reference

POST /api/v1/shield/events

Upload detection events from the OpenClaw skill to the dashboard.

curl -X POST https://clawkeeper.dev/api/v1/shield/events \
  -H "Authorization: Bearer ck_live_..." \
  -H "Content-Type: application/json" \
  -d '{"events": [{"hostname": "my-host", "detection_layer": "regex", "verdict": "blocked", "severity": "critical", "security_level": "strict", "input_hash": "abc123..."}]}'

GET /api/v1/shield/policy

Pull the current shield policy for your organization.

curl https://clawkeeper.dev/api/v1/shield/policy \
  -H "Authorization: Bearer ck_live_..."

POST /api/v1/shield/heartbeat

Signal that the shield is active on a host.

curl -X POST https://clawkeeper.dev/api/v1/shield/heartbeat \
  -H "Authorization: Bearer ck_live_..." \
  -H "Content-Type: application/json" \
  -d '{"hostname": "my-host", "shield_version": "1.0.0"}'

Security Levels

Both Claude Code and OpenClaw shields share the same security level system:

LevelBlock whenWarn whenPass when
ParanoidAny single pattern match--All patterns clean
Strict (default)High or critical severity matchMedium severity matchAll patterns clean
ModerateCritical severity onlyHigh severity matchEverything else
MinimalExplicit blacklist match or multiple critical flagsSingle critical/high flagEverything else

For Claude Code, the security level also governs policy enforcement: "paranoid" and "strict" levels block on high/critical detections, while "moderate" and "minimal" only block the most severe threats. Sensitive file reads are never blocked regardless of security level -- they are always downgraded to warnings.

Dashboard and Insights

The Runtime Shield dashboard at /security shows:

  • Stats -- total events, blocked, warned, passed, unique patterns
  • Timeline -- stacked area chart of events over 24h or 7d
  • Top patterns -- most common attack patterns with severity breakdown
  • Policy panel -- security level, blacklist, trusted sources
  • Event feed -- paginated, filterable event stream

Shield events from both Claude Code and OpenClaw appear in the same dashboard and Activity page. Filter by detection_layer to separate them: claude_code for Claude Code events, regex/semantic/context/blacklist/entropy for OpenClaw layer-specific events.

Insights

Runtime Shield generates 3 insight types on the Insights page:

  • Attack Surge -- 10+ blocked events in 1 hour across your fleet
  • Targeted Host -- single host receives 5+ blocks in 1 hour
  • New Pattern -- previously unseen attack pattern detected

Privacy

  • Full raw user messages and tool inputs never leave your machine in their entirety
  • The dashboard receives SHA-256 hashes, detection metadata, verdicts, truncated input summaries (80-120 chars), and severity data
  • For Claude Code: tool input is summarized (command prefix, file path, URL) -- full command text is not stored
  • For OpenClaw: local logs are stored in ~/.clawkeeper/shield-logs/ (daily rotation, JSONL format)
  • Dashboard connection is optional for OpenClaw -- the shield works fully offline with last-synced policy

FAQ

Does Runtime Shield slow down Claude Code? No. The evaluation endpoint responds in under 5ms on cache hit. Org data is cached in-memory for 30 seconds. The detection engine uses pattern matching only -- no network calls or ML inference in the critical path.

Does it slow down OpenClaw agents? No. Detection runs in under 1ms for typical messages. The 5 layers use pattern matching and scoring -- no external calls in the detection path.

What happens if Clawkeeper is unreachable? For Claude Code: the hooks fail-open. If the evaluate endpoint is down or returns an error, the tool call proceeds. For OpenClaw: events are logged locally and queued for upload. The shield continues with the last-synced policy.

Does it count against my scan limits? No. Shield events are independent of scanning.

Can I use OpenClaw shield without a Clawkeeper account? Yes. Install the skill and it works in local-only mode. You won't get fleet analytics or centralized policy, but all 5 detection layers run locally.

Why are file reads never blocked? Developers legitimately read credential files, environment configs, and SSH keys as part of their workflow. Blocking reads would cause constant false positives. Instead, reads of sensitive paths are logged and surfaced in the dashboard for review, giving security teams visibility without disrupting development.

What is the difference between policy blocks and detection blocks? Policy blocks (blocked tools, blocked commands, blocked write paths) are hard rules set by your organization -- they apply before the detection engine runs and are unconditional. Detection blocks come from the 55+ pattern matching engine and are subject to the security level (paranoid/strict/moderate/minimal) and auto-block toggle.