GuardrailCustom rules with CEL

Custom rules with CEL

Add your own guardrail rule to a copy of a rule pack with a CEL expression over a tool call's parsed facts and a regex fallback, then validate and test it.

A custom rule lives in your own copy of a rule pack. It has a CEL expression that matches the parsed facts of a tool call (programs, paths, network targets, data flow) and a required regex pattern that runs when the call could not be parsed in full.

  • The CEL expression returns only true or false. true creates the finding defined in the YAML; the levels and the mode pick the action.
  • A CEL match can block only when the gateway read the call in full and the connector can block. A regex fallback match is recorded but never blocks.

The examples need Bash. On native Windows, use Git Bash or WSL.

Add a rule

This rule flags any command that reads /srv/payments/secrets.

Copy the closest pack

cp -r ~/.defenseclaw/policies/guardrail/default \
      ~/.defenseclaw/policies/guardrail/my-org

Add a rules file with its own category

~/.defenseclaw/policies/guardrail/my-org/rules/my-org.yaml
version: 1
category: my-org
rules:
  - id: ORG-PAYMENTS-SECRETS
    tool_call_only: true
    expression: >-
      f.commands.exists(c,
      defenseclaw.guardrail.semantic.v1.OperationKind.OPERATION_KIND_READ in c.operations &&
      f.paths.exists(p, p.command_id == c.id &&
      p.access == defenseclaw.guardrail.semantic.v1.PathAccess.PATH_ACCESS_READ &&
      (p.resolved == '/srv/payments/secrets' ||
      p.resolved.startsWith('/srv/payments/secrets/'))))
    pattern: '(?i)(?:^|\s)/srv/payments/secrets(?:/|\s|$)'
    title: "Payments secret directory read"
    severity: CRITICAL
    confidence: 0.95
    tags: [credential, payments, file-sensitive]

The expression joins the path to its command by id. A category that no other file uses adds rules; a category that matches a shipped one replaces that whole category.

Validate the pack

defenseclaw guardrail validate-pack ~/.defenseclaw/policies/guardrail/my-org
Rule pack valid: "/home/alice/.defenseclaw/policies/guardrail/my-org"
  rules: 284/288 enabled across 8 files
  files digest: 4b04e4ff… (the guardrail.custom_packs pin)

It runs offline. Exit codes: 0 valid, 1 invalid, 2 validator unavailable. What it checks is on Packs and rules.

Pin the pack and switch to it

defenseclaw guardrail use-pack ~/.defenseclaw/policies/guardrail/my-org

Add --connector codex to switch one agent. A running gateway loads the pack on its next reload.

Check it worked

defenseclaw guardrail list-packs
defenseclaw config get guardrail.custom_packs

list-packs shows my-org and who uses it; custom_packs shows its path and digest.

Validation does not prove a connector supplies the facts your expression reads. In observe mode, run a real command that reads the directory and a near miss, then read the alerts:

defenseclaw alerts --limit 25 --connector claudecode
defenseclaw alerts --connector claudecode --show 1

Secret findings hide rule IDs in the alert views: this rule can appear as redacted.secret.id-… with the title Secret finding. Match the alert by connector, time and session instead.

With the default pack's levels, this CRITICAL rule can block in action mode. A HIGH rule would only alert.

Undo

defenseclaw guardrail use-pack default

This also removes the pin for my-org.

Rule file fields

FieldContract
versionRule-file schema version. Use 1.
categoryFile-level group. Use a unique name unless you mean to replace a shipped category.
idStable finding ID. Keep it unique.
expressionBoolean CEL expression. It is compiled even when the rule is disabled.
patternRequired Go RE2 fallback for calls the gateway could not parse in full. Detection only.
tool_call_onlyLimits the regex fallback to tool calls. CEL always runs on tool calls only.
title, severity, confidence, tagsFinding details. Severity is LOW, MEDIUM, HIGH or CRITICAL; confidence is 0 to 1; tags must not be empty.

Fallback patterns and their pitfalls: Recipes.

Patterns

Prefer typed operations and joined facts over connector tool names. c.program is the normalized program name; c.executable keeps the token as typed. f.tool differs between connectors.

Require a complete argument list before an argument-sensitive claim:

CEL expression
f.commands.exists(c,
  c.argv_complete &&
  c.program in ['curl', 'curl.exe', 'wget', 'wget.exe'] &&
  defenseclaw.guardrail.semantic.v1.OperationKind.OPERATION_KIND_FETCH
    in c.operations)

A program DefenseClaw does not model has a known argument list but unknown paths and operations. A rule that reads only c.program, c.argv and c.argv_complete still matches it; a rule that needs its paths or operations does not.

Join the path to its command and check the directory boundary:

CEL expression
f.commands.exists(c,
  f.paths.exists(p,
    p.command_id == c.id &&
    p.access == defenseclaw.guardrail.semantic.v1.PathAccess.PATH_ACCESS_WRITE &&
    (p.resolved == '/etc/systemd/system' ||
     p.resolved.startsWith('/etc/systemd/system/'))))

resolved and active_home may be empty when the host context is unknown. An empty value is unknown, never safe.

Match an upload to a public or unresolved host:

CEL expression
f.commands.exists(c,
  defenseclaw.guardrail.semantic.v1.OperationKind.OPERATION_KIND_UPLOAD
    in c.operations &&
  f.network.exists(n,
    n.command_id == c.id &&
    n.action == defenseclaw.guardrail.semantic.v1.NetworkAction.NETWORK_ACTION_UPLOAD &&
    n.scope in [
      defenseclaw.guardrail.semantic.v1.NetworkScope.NETWORK_SCOPE_PUBLIC,
      defenseclaw.guardrail.semantic.v1.NetworkScope.NETWORK_SCOPE_UNKNOWN
    ]))

DefenseClaw does no DNS lookups while building facts, so a host name stays UNKNOWN. Include that scope to cover external host names.

Join the command to both edges of a file-to-network flow:

CEL expression
f.commands.exists(c,
  f.data_flows.exists(read,
    read.to_command_id == c.id &&
    read.from == defenseclaw.guardrail.semantic.v1.DataKind.DATA_KIND_FILE &&
    read.to == defenseclaw.guardrail.semantic.v1.DataKind.DATA_KIND_PROCESS) &&
  f.data_flows.exists(send,
    send.from_command_id == c.id &&
    send.from == defenseclaw.guardrail.semantic.v1.DataKind.DATA_KIND_PROCESS &&
    send.to == defenseclaw.guardrail.semantic.v1.DataKind.DATA_KIND_NETWORK))

The file read and the network send are separate edges through the process. Joining both to c.id avoids combining unrelated commands.

Facts reference

The only CEL variable is f, of type defenseclaw.guardrail.semantic.v1.Facts. Field names are snake case (f.active_home).

ValueTypeFields and use
f.toolstringThe tool name the connector reported. Prefer typed facts for portable rules.
f.cwdstringThe working directory, when known.
f.active_homestringThe active user's home on this host, when known. Never taken from the payload.
f.parseParseResultstatus, dialect and issues. CEL runs only after a complete parse.
f.commandslist<CommandFact>Program, argv, operations, redirects, wrappers, links between commands, completeness.
f.pathslist<PathFact>command_id, access, flavor, raw value, normalized, absolute and resolved.
f.networklist<NetworkFact>command_id, action, scheme, host, port, normalized host, scope, target kind, prefix length.
f.data_flowslist<DataFlowFact>Source and destination command IDs plus typed from and to. ID 0 is a file or network boundary.
f.artifactslist<ArtifactFact>Archive files a command names: command_id, role (PRODUCE, CONSUME), kind (ARCHIVE), paths and identity (a digest of the normalized path). The file is never opened.
f.archive_lineageslist<ArchiveArtifactLineage>An archive produced by one command and consumed by another: produced_by, consumed_by, normalized, authoritative.
Command fieldMeaning
id, parent_command_id, pipeline_idLinks between commands, wrappers and pipelines.
kindProcess or shell redirect.
dialectArgv, POSIX, PowerShell, cmd.exe, mixed or none.
effectExecute, preview or uncertain. Preview facts can detect but never enforce.
executable, programThe token as typed, and the normalized lower-case program name.
argv, arguments, argv_completeThe parsed list, quoting details, and whether the list is complete.
operationsTyped behaviors such as read, write, delete, upload or privilege change.
redirects, wrappersRedirect targets and wrapper programs.

Use fully qualified enum constants, for example defenseclaw.guardrail.semantic.v1.PathAccess.PATH_ACCESS_DELETE. Numeric comparisons and comparisons across enum families are refused.

EnumValues
OperationKindEXECUTE, READ, WRITE, APPEND, DELETE, COPY, MOVE, LIST, SEARCH, FETCH, UPLOAD, CONNECT, LISTEN, TUNNEL, NETWORK_SCAN, DECODE, PROCESS_KILL, DISK_WRITE, PRIVILEGE, PERMISSION_CHANGE, CONFIG_CHANGE, ACCOUNT_CHANGE, SCHEDULE, CONTAINER_RUN, WORKLOAD_EXEC, NAMESPACE_ENTER, ROOT_CHANGE, ENVIRONMENT_READ, CREDENTIAL_READ, POLICY_BYPASS
PathAccessREAD, WRITE, APPEND, DELETE, EXECUTE, LIST, METADATA, CONNECT
PathFlavorUNKNOWN, POSIX, WINDOWS, DEVICE, REGISTRY
NetworkActionCONNECT, LISTEN, DOWNLOAD, UPLOAD, DNS, TUNNEL, SCAN
NetworkScopeUNKNOWN, LOOPBACK, LINK_LOCAL, PRIVATE, PUBLIC
NetworkTargetKindUNKNOWN, SINGLE_HOST, SINGLE_ADDRESS_CIDR, MULTI_ADDRESS_CIDR, RANGE, LIST, GENERATED
DataKindSTDIN, STDOUT, FILE, NETWORK, PROCESS
CommandEffectEXECUTE, PREVIEW, UNCERTAIN
ParseStatusCOMPLETE, PARTIAL, UNSUPPORTED, INVALID, LIMIT_EXCEEDED, AMBIGUOUS, NOT_APPLICABLE
ArtifactRolePRODUCE, CONSUME
ArtifactKindARCHIVE

The schema is internal/guardrail/semanticpb/facts.proto. Types, admitted syntax and cost limits are on CEL engine. Which connectors supply which facts: Tool-call state.

Checklist

  • Use a unique category and a unique, stable rule ID.
  • Join related facts by command ID, never by list position.
  • Prefer c.program and typed operations over tool names.
  • Treat empty context fields as unknown, not safe.
  • Keep the fallback pattern to the same intent as the expression.
  • Validate the whole pack, then test a match and a near miss on each connector in observe mode.