Skip to content

Latest commit

 

History

History
452 lines (393 loc) · 30.3 KB

scanners.md

File metadata and controls

452 lines (393 loc) · 30.3 KB

Scanners

--scanner selects a scanner adapter to run, writes its raw JSON evidence into the results artifact, and can be repeated to compare multiple scanners in one run:

clawscan ./my-skill \
  --scanner skillspector \
  --scanner cisco

Discover the scanner catalog from the CLI:

clawscan scanners
clawscan scanners skillspector

When writing a results bundle with --output, each scanner result's outputPath points to its raw JSON evidence beside the main artifact. Target, profile, and scanner names are sanitized for filesystem use; colliding paths receive numeric suffixes so every report is preserved. Read the recorded outputPath instead of reconstructing a filename from a target or scanner ID.

Cancellation and incomplete evidence

The scan CLI handles SIGINT and SIGTERM as cancellation, stops starting work, and best-effort writes already-known evidence before exiting nonzero. A library caller's RunContext.Context applies across preparation, sequential scanners, judge preparation, commands and judge retries. A stage's existing timeout is an additional cap, not a renewal of the caller's deadline. Now controls artifact timestamps only; deadlines use Go contexts and the monotonic clock.

Check status and complete before using a new artifact as a security result:

  • completed with complete: true means the requested run finished.
  • running with complete: false is a checkpoint, not a terminal receipt.
  • canceled, deadline_exceeded, or failed with complete: false is an operational failure, never a benign verdict, publisher rejection, or security block. Its gate is error; completed stages' fired gateRules remain visible.
  • Unstarted stages have status: not_started; interrupted stages are failed. A failed scanner prevents judge execution. Valid raw evidence, warnings, findings and completeness information remain attached to their stage. Failed stages' raw JSON stays inline and is not exported as a standalone scanner report.

--output writes atomic JSON checkpoints before stages and a terminal artifact on normal return, including error return. Artifact and raw-report replacements are private (at most 0600, retaining more restrictive existing permissions and the process umask). Outputs aliasing explicit targets, scanner fixtures, context, config, or on-disk judge prompt/schema inputs are rejected before execution; symlinked parents and existing hard links are included in that check. If an output is inside a directory target, checkpoints are omitted and only the terminal artifact is written after target-dependent work, so scanners and judges do not inspect this run's own pending output. Existing files in the target are still inspected, not hidden by their filenames. --json also emits available partial evidence on operational failure; readable JSON does not imply exit status zero. Filesystem errors can prevent all disk evidence. SIGKILL, process crashes, blocked OS I/O and an exhausted supervisor grace period cannot guarantee a final artifact. A checkpoint may survive instead, and must remain incomplete.

ClawScan keeps child commands in the inherited process group. It never signals a host/user process group or creates scanner groups that escape a supervisor. Its command context kills the direct child and bounds inherited-pipe draining to 100ms; this is not descendant cleanup proof. processCleanup: unknown deliberately makes no claim of descendant absence. A process-tree supervisor must retain ownership through TERM, KILL and independent absence verification, even when the CLI has already returned or the command leader exited early. Plain CLI signals and library cancellation alone do not guarantee descendant termination. Docker-client cancellation likewise does not prove container termination; the container supervisor must clean up exact owned containers, using run/command labels where configured. Do not deploy a cancellation contract that assumes killing the Docker client removes its containers.

Cancelable custom library implementations must implement ContextCommandRunner or ContextScannerRunner as appropriate. Legacy synchronous callbacks remain supported without a cancelable context; they are not moved into detached goroutines to fabricate timely cancellation. HTTP implementations must honor the supplied request context. Finalization writes only retained evidence; it does not resume scanning, retry the judge, or extend the work deadline.

Benchmark runs carry the same additive status, complete, and error fields. Both supported datasets retain already completed and interrupted cases on an operational error, with known remaining cases marked not_started. Partial aggregates are written best-effort and emitted with --json, but the command fails. ID requests, row requests, retry waits, archive requests and extraction share the caller context. A failed required judge/scanner cannot fall back to a clean prediction; predictions export rejects incomplete evidence. Applicable scanner verdict exits and unsupported-target skips retain their existing semantics, and unsuccessful observations remain visible in case evaluations.

Adding a built-in scanner adapter

First evaluate the scanner with a custom profile and discuss built-in adoption with maintainers. Adding an adapter also means maintaining its dependency, target support, and output contract.

Implement the adapter in internal/runner/ and register it in defaultScannerAdapters in scanner_registry.go. Declare required and optional environment variables, install and verification commands, and supported target kinds in the registry. Preserve upstream JSON evidence and report skipped or failed scans explicitly. Command-backed scanners use the Docker runner by default; include a pinned runtime dependency when the adapter requires it.

Add fixture-backed tests for valid output, malformed output, process failures, and unsupported targets. Update this scanner catalog and the README catalog, then run the Go tests, go vet, and make docs-site from the contributing guide. Never put credentials in flags, fixtures, or scan artifacts.

Profile scanner configuration

A trusted config can mix built-in scanner IDs with user-defined command scanners. The config schema uses the existing profiles.<name>.scanners list:

version: 1

profiles:
  review:
    scanners:
      - id: skillspector
        gate:
          rules:
            - id: do-not-install
              path: risk_assessment.recommendation
              equals: DO_NOT_INSTALL
              action: block
            - id: critical-finding
              path: filtered_findings[].severity
              equals: CRITICAL
              action: block
      - id: aig
        gate:
          rules:
            - id: any-result
              path: runs[].results[]
              exists: true
              action: warn
      - id: my-scanner
        command: my-scanner --json {{target}}
        env:
          - MY_SCANNER_MODE
        secretEnv:
          - MY_SCANNER_TOKEN
        targets:
          - skill
          - plugin
        gate:
          rules:
            - id: high-risk
              path: result.risk
              equals: high
              action: warn
          blockOnExitCode: nonzero

String entries select built-in scanners without gate policy. An object with a registered built-in id and no command selects that built-in and can attach gate rules. The rules inspect its existing JSON output; the scanner does not need to implement ClawScan-specific policy or change its exit codes.

An object with a command defines a user-provided scanner for that config-backed run. The same JSON rules work for built-in and command scanners:

Field Required Meaning
id yes Scanner ID using lowercase letters, digits, _, and -, starting with a letter or digit, at most 64 characters. It must not match a built-in scanner ID.
command yes Shell command to execute. Unquoted {{target}} is replaced with the safely passed resolved target; do not wrap the placeholder in shell quotes.
env no Required non-secret environment variable names passed to the scanner. Their values are not automatically redacted from scanner error text.
secretEnv no Required secret environment variable names passed to the scanner. Their values are redacted from scanner error text regardless of how the names are spelled.
targets no Supported target kinds: skill, plugin, template, and/or url. Defaults to skill and url.
gate no JSON and/or exit-code policy applied after the scanner completes.

JSON gate rules

gate.rules evaluates the scanner's raw JSON without rewriting it. Every rule has:

Field Required Meaning
id yes Stable name reported in gateRules; IDs must be unique within one scanner gate.
path yes One path or an ordered list of aliases. Paths use dotted object fields, with [] after a field to traverse every array item. Separate alternative field names with the pipe character. Array indexes and other expression syntax are not supported.
action yes warn or block.
equals one condition Matches a string, number, or boolean exactly. String comparison is case-sensitive.
exists one condition Must be true; matches when the path resolves to at least one value.
normalize no identifier makes string equals matching case-insensitive and treats spaces and hyphens like underscores. It cannot be used with numbers, booleans, or exists.
fallback no root makes the first path whose root field exists authoritative, even when a nested field is missing. Use this when a preferred filtered collection must override legacy raw collections.

Specify exactly one of equals or exists: true. A rule fires at most once, even when several paths or array items match. The fired artifact records the path that matched. A path list is an ordered fallback: ClawScan evaluates the first path with a non-empty value and ignores later aliases, whether or not its value matches. Empty strings and null fall through to the next alias. An explicitly empty traversed array remains authoritative, letting a preferred filtered result override legacy raw-result fields. Missing paths, empty arrays, and type mismatches do not fire. Within one path segment, | alternatives are resolved separately for each object, using the first present field; if that field is empty, the rule can still fall through to the next path. For fallback: root, a present root field prevents later path aliases from being consulted. For example, findings[].severity|risk_severity checks severity and then risk_severity on each finding. An immutable third-party scanner can be gated without a wrapper:

scanners:
  - id: third-party
    command: third-party scan --json {{target}}
    gate:
      rules:
        - id: critical-risk
          path:
            - result.risk
            - result.risk_level
          equals: critical
          normalize: identifier
          action: block
        - id: any-policy-violation
          path: result.violations[]
          exists: true
          action: warn

Exit-code rules

Each exit-code rule accepts one integer from 0 through 124, a list such as [1, 2, 3], or the string nonzero. The block and warning rules may not claim the same exit code. Exit codes 125 and above are reserved for shell, container-runtime, and signal failures, so ClawScan does not treat them as scanner verdicts. For example:

gate:
  blockOnExitCode: [2, 3]
  warnOnExitCode: 1

JSON and exit-code rules can be combined on the same scanner. A gate-eligible process exit code is preserved alongside raw JSON, and all fired rules participate in the same strongest-action decision.

After every selected scanner finishes, ClawScan records the strongest fired action as the top-level artifact gate: block wins over warn, and an artifact with no fired rules records "gate": "pass". Each fired rule is also listed in gateRules with its scanner ID, rule ID, and action. Exit-code rules include exitCode; JSON rules include path and, for equals, the matched value. Gate actions are record-only: block does not stop later scanners or the judge, and it does not change ClawScan's process exit status. For enforcement, inspect gate and gateRules on a single run, runs[].gate and runs[].gateRules in a batch, or cases[].run.gate and cases[].run.gateRules in a benchmark. The human scan summary aggregates the strongest batch action; the benchmark summary does not aggregate gate actions.

Skipped or failed scanners do not fire gate rules. A nonzero command that still returned valid JSON has status completed and can fire both JSON and exit-code rules. Valid JSON from a timeout, signal, or reserved infrastructure exit is still preserved, but the failed scanner does not fire gate rules and its exitCode is omitted.

The command must write JSON to stdout. ClawScan preserves valid stdout as the scanner's raw evidence; empty or non-JSON stdout produces a failed scanner result. Required environment variables are checked before any scanner starts. Artifacts record each requirement as only present or missing.

Do not print secrets into evidence. ClawScan preserves valid scanner stdout as raw JSON evidence, so any secret the scanner writes into that JSON is persisted. Values declared in secretEnv are redacted from scanner error text, but ClawScan does not rewrite raw evidence. A user-defined scanner must not echo its API keys, tokens, or other credentials into the JSON report it emits.

User-defined scanners use the same execution path as built-in command-backed scanners. They run in the Docker sandbox by default, and declared env and secretEnv names are added to its environment allowlist. Put every sensitive value in secretEnv; values declared only in env are treated as non-secret and may appear in scanner error text. ClawScan preserves valid scanner stdout as raw JSON evidence, so scanner authors must not print secrets into that JSON. Use --sandbox off only when you intentionally want the command to run on the host. User-defined scanners are local to the resolved config and do not appear in the built-in clawscan scanners catalog.

Trust boundary: only load user-defined scanners from config files you control. A scanner entry is executable code. The default sandbox limits its host access, but does not make an untrusted command safe to run.

Target kinds

Clawscan classifies each explicit target before dispatching scanners and records the result in the artifact target.kind field:

Kind Detected when Notes
skill default for local files and directories Historical behavior; a directory usually holds SKILL.md.
plugin directory (or selected manifest) holds openclaw.plugin.json or a supported bundle marker Native identity comes from id; bundle identity comes from canonical name normalization. Host paths are never used as identity.
url http/https input Local file and directory scanners skip URLs.

The built-in clawhub profile runs only the aig-mcp scanner for plugin targets, described below. SkillSpector and Socket also support plugins when selected explicitly or through a custom profile. Other scanners that assume skill layouts return an explicit skipped result naming the unsupported kind, and adapters can opt in per kind as upstream tools add plugin support. A directory carrying both SKILL.md and openclaw.plugin.json is rejected as ambiguous rather than guessed; point Clawscan directly at the desired manifest to disambiguate a valid dual-layout package.

Supported bundle markers are .codex-plugin/plugin.json, .claude-plugin/plugin.json, and .cursor-plugin/plugin.json. Their non-empty name becomes a lowercase, hyphen-normalized identity, matching OpenClaw. Names with path separators or control characters, or without a canonical slug, fail closed instead of using an artifact-directory fallback. Bundle metadata reads are bounded to 256 KiB, require UTF-8, and cannot follow links outside the root. Directories mixing bundle markers, native manifests, or SKILL.md are ambiguous; select the desired manifest explicitly. A selected bundle manifest scans the whole surrounding artifact, not just its marker directory. All companion files and suspicious findings remain in scanner and judge scope. Explicit native manifest selection and the native identifier grammar are unchanged.

Plugin code audit with aig-mcp

Native OpenClaw plugins run in-process in the gateway with its full permissions, so aig-mcp audits plugin code with Tencent A.I.G's aig-mcp-scan (pinned to 0.2.0 in the runtime image). It analyzes plugin and template targets and skips skill, file and URL targets. The separate clawhub-template profile retains every shipped file and uses a Template-aware prompt; see the Template audit contract. The following plugin-specific behavior is unchanged. The built-in clawhub profile lists it under pluginScanners, so a plugin is reviewed by aig-mcp and the judge only; SkillSpector and the aig skill scanner are not run or recorded for plugins, and skills keep those scanners. For each plugin directory the adapter:

  • copies the whole plugin into a private temporary workspace, leaving out only node_modules directories (bundled third-party code is out of scope and makes the LLM agent slow and noisy). Embedded skills, hooks, scripts, dist/ or build/ output, and .git/ and clawscan-results/ content stay in the copy: unlike the judge workspace, scanner staging filters nothing else, so authored code is audited wherever it lives. Symlinks that leave the plugin are refused, and a plugin with more than 20,000 files or 256 MiB outside node_modules fails instead of being audited partly;
  • runs aig-mcp-scan --repo plugin --language en [-m <model>] [-u <base url>] -p <prompt> -o aig-mcp-scan.sarif.json in that workspace, never in the original target. The prompt explains the in-process plugin runtime (api.registerTool, prompt hooks, registerHttpRoute), prioritizes malicious or undeclared behavior, and puts embedded skills, hooks, scripts and compiled output in scope. aig-mcp-scan leaves dist/, build/, .git/, __pycache__/, .venv/ and venv/ out of the directory summary it shows the model and truncates that summary at 200 files, so the prompt lists the omitted files (every file for plugins over 200 files; up to 400 paths, source files and SKILL.md first);
  • passes credentials only through LLM_API_KEY or OPENAI_API_KEY, and the model and endpoint only through the aig settings DEFAULT_MODEL and DEFAULT_BASE_URL. These default to OpenAI's endpoint for OpenAI or Codex credentials and otherwise to aig-mcp-scan's own defaults, and are always passed as -m/-u so generic OPENAI_BASE_URL or LLM_MODEL values meant for other tools never apply;
  • keeps the upstream SARIF unchanged as the scanner's raw evidence. It is the only scanner evidence in the judge workspace (scanners/aig-mcp.json); the clawhub Decisions judge passes its findings to the model as bounded, normalized evidence, and a --judge override that renders clawhub/prompt.md receives the raw SARIF. Benchmarks map SARIF levels to severities (error high, warning or absent medium, note low, otherwise info): a high finding predicts malicious, any other finding suspicious.

aig-mcp-scan 0.2.0 gives its agent a shell and file writes during static audits, and prompt injection in the audited plugin could reach them; its tool lookup is also case-insensitive, and its MCP client tools accept any URL the model supplies. The runtime image's patch never registers the shell, limits static audits to an allow-list of read-only tools matched on canonical (trimmed, lowercase) names, so the MCP tools are rejected before lookup, refuses model-chosen MCP destinations before any transport is created, and keeps every read confined to the audited directory. Upstream keeps only a 20,000-character prefix of any tool result over 40,000 characters in the model's history, so the patch also caps read_file at 30,000 characters with an explicit continuation and adds read_file_chunk (character-offset reads) and search_files (bounded literal search) so the rest of a large or compiled file is visible to the model. The image build runs those checks and fails if the patch stops applying or the registered tools change. It also runs the real aig-mcp-scan CLI against a loopback model stub that injects remote MCP calls, and fails if a loopback canary (also set as the HTTP(S) proxy) receives any connection. The adapter therefore expects the Docker sandbox: with --sandbox off it fails unless AIG_MCP_SCAN_ALLOW_HOST_EXEC=1 acknowledges a disposable host. A plain pip install aig-mcp-scan (and clawscan install aig-mcp) is unpatched; host consumers such as a ClawHub worker must install the patched build from docker/clawscan-runtime instead. Adopting a ClawScan release with this profile change therefore needs the runtime image published first and any host worker updated before its ClawScan pin moves; until then, plugin scans fail closed rather than running without aig-mcp.

Each scanner command against a plugin target gets a 30-minute budget, instead of the 20 minutes used for skills, because the whole plugin is audited as one artifact. A run that hits the budget is cancelled and fails like any other command failure.

Failures are never reported as clean scans. aig-mcp-scan exits 0 and writes SARIF marked scanNote: complete even when its audit did not finish, so the adapter also reads its output. Any of these marks aig-mcp failed with the upstream error and a bounded stderr tail, and the judge does not start:

  • a non-zero exit, or missing or invalid SARIF;
  • model calls that failed (LLM chat failed after retries, LLM chat error, retry 5 times) or an exhausted iteration budget (Max iterations (80) reached), logged as WARNING or ERROR records on stderr. INFO records and continuation lines that merely quote these words (a model report, a file name) do not count;
  • any run whose scanNote is not complete, including a missing one;
  • an unusable final report. Upstream keeps the last of three format attempts even when none matched, so a refusal or plain prose would otherwise score 100 with no findings. The patched runtime exits with an error instead, both for that and when any <vuln> finding block cannot be parsed. Only an explicit <empty> result, or findings that all parse, produce SARIF.

An imported --scanner-result aig-mcp=<path> gets the same SARIF and scanNote checks. Its logs are not available, so an imported report from an audit that exhausted its iterations still reads scanNote: complete and cannot be detected; import only reports whose scanner run ClawScan itself checked. A profile's plugin-only scanner accepts --scanner-result without --scanner, and a run against a non-plugin target with such a result fails instead of ignoring it. A plugin file over 64 MiB fails staging, matching the read tools' per-file limit.

Plugin targets are never auto-discovered. Zero-target discovery still scans only child skill directories under ./skills; pass a plugin directory explicitly to avoid silently scanning arbitrary package directories. Pointing Clawscan at an openclaw.plugin.json file scans the surrounding plugin directory.

Plugin ids follow OpenClaw's install grammar, including @scope/name ids. Manifests accept the same JSON5 syntax as OpenClaw, including comments, trailing commas, single-quoted strings, and unquoted keys.

Available scanners

Want to add your scanner to the list? Follow the guide in docs/scanners.md

ID Name Repo Description Required env vars Local dependency setup
agentverus AgentVerus repo Local file or directory scanner invoked through agentverus-scanner. none npm install --save-dev agentverus-scanner
aig Tencent AI-Infra-Guard repo Tencent Zhuque Lab's local directory scanner invoked through aig-skill-scan. Produces SARIF 2.1.0 with SkillTrustBench T01-T09 evidence. LLM_API_KEY or OPENAI_API_KEY
Optional configDEFAULT_MODEL, REASONING_EFFORT (requires the patched runtime), AIG_SERVICE_TIER (Sol only), DEFAULT_BASE_URL, DEFAULT_MODEL_CONTEXT_WINDOW, LOG_LEVEL.
pip install aig-skill-scan
aig-mcp Tencent AI-Infra-Guard MCP scanner repo Tencent Zhuque Lab's LLM-driven MCP server code audit invoked through aig-mcp-scan, run on OpenClaw plugin and Template targets (skill, file and URL targets are skipped). Audits a bounded temporary copy of the whole plugin without node_modules, using an OpenClaw plugin audit prompt, and produces SARIF 2.1.0 with MCP01-MCP10 evidence. Runs in the Docker sandbox, whose runtime image removes the agent's shell and file-write tools. LLM_API_KEY or OPENAI_API_KEY
Optional configDEFAULT_MODEL, DEFAULT_BASE_URL (same defaults as aig), DEFAULT_MODEL_CONTEXT_WINDOW, AIG_MCP_SCAN_ALLOW_HOST_EXEC=1 (required with --sandbox off).
runtime image (patched aig-mcp-scan==0.2.0); pip install aig-mcp-scan==0.2.0 is unpatched
cisco Cisco AI Defense skill-scanner repo Local file or directory scanner invoked through skill-scanner with JSON report output. Optional upstream env vars enable LLM, VirusTotal, and Cisco AI Defense analyzers. none
Optional configSKILL_SCANNER_LLM_API_KEY, SKILL_SCANNER_LLM_PROVIDER, SKILL_SCANNER_LLM_MODEL, SKILL_SCANNER_LLM_BASE_URL, SKILL_SCANNER_LLM_USER, SKILL_SCANNER_LLM_API_VERSION, SKILL_SCANNER_LLM_FORCE_JSON_OBJECT, SKILL_SCANNER_META_LLM_API_KEY, SKILL_SCANNER_META_LLM_MODEL, SKILL_SCANNER_META_LLM_BASE_URL, SKILL_SCANNER_META_LLM_API_VERSION, AWS_PROFILE, AWS_REGION, GOOGLE_APPLICATION_CREDENTIALS, VIRUSTOTAL_API_KEY, AI_DEFENSE_API_KEY, AI_DEFENSE_API_URL.
uv pip install cisco-ai-skill-scanner
relyable Relyable repo Functional re-derivation evidence: does the skill still do what its docs claim, recomputed? Emits the strongest grade that applies. exogenous: a declared rederive.json property manifest (idempotence / round-trip), with both sides of the relation computed from the skill's own code and the result mutation-tested against vacuity. self_spec: re-runs the author's own committed oracle (shipped tests or documented I/O examples). cold_golden: when an LLM key is set, a code-blind model infers goldens from SKILL.md alone and abstains unless the docs pin exact behavior; divergences are reported as unconfirmed, never as accusations. non_rederivable: the honest floor, never a fabricated pass. Functional axis only; complements the security scanners and does not detect malware or prompt injection. Skill code runs only inside the Docker sandbox (or with an explicit opt-in), in a scrubbed environment, and the scanner fails closed otherwise. Not preinstalled in the clawscan-runtime image. none
Optional configRELYABLE_SCAN_ALLOW_HOST_EXEC — explicit ack that the host is disposable when running with --sandbox off.

RELYABLE_LLM_API_KEY (+ RELYABLE_LLM_PROVIDER anthropic
openai, RELYABLE_LLM_MODEL, RELYABLE_LLM_BASE_URL) — explicit per-scanner opt-in that enables the cold_golden lane; key presence only is ever recorded in the payload. Generic ANTHROPIC_API_KEY/OPENAI_API_KEY are honored by standalone relyable-scan but are deliberately not auto-forwarded by ClawScan.
skillspector NVIDIA SkillSpector repo Local skill or OpenClaw plugin file/directory scanner. Uses LLM mode when provider env vars are set; otherwise runs with --no-llm. none
Optional configSKILLSPECTOR_PROVIDER, SKILLSPECTOR_MODEL, SKILLSPECTOR_REASONING_EFFORT, SKILLSPECTOR_TEMPERATURE, SKILLSPECTOR_SEED, SKILLSPECTOR_SERVICE_TIER (Sol only), SKILLSPECTOR_MODEL_REGISTRY, SKILLSPECTOR_LOG_LEVEL, SKILLSPECTOR_SSL_VERIFY, NVIDIA_INFERENCE_KEY, OPENAI_API_KEY, OPENAI_BASE_URL, ANTHROPIC_API_KEY, ANTHROPIC_PROXY_ENDPOINT_URL, ANTHROPIC_PROXY_API_KEY, ANTHROPIC_PROXY_API_VERSION.
uv tool install git+https://github.com/NVIDIA/skillspector.git
snyk Snyk Agent Scan repo Local skill scanner invoked through uvx snyk-agent-scan. SNYK_TOKEN verifies uvx launcher
socket Socket CLI repo Local file or directory scanner using Socket's public CLI full-scan path. SOCKET_CLI_API_TOKEN npm install -g socket

SkillSpector scans the target itself for every profile; no profile scans a filtered copy. With the Docker sandbox, the target is mounted read-only and the scanner's result directory is its working directory.

Snyk Agent Scan 0.6 reports named findings in risk_indexes maps under scan_path_responses. ClawScan preserves that upstream JSON and includes those findings in issues_found; clean components with empty risk maps contribute zero. Operator-owned gate rules that inspect Snyk's older issues arrays need to use the current Snyk JSON schema.