Regex cookbook

RE2 regex patterns for DefenseClaw guardrails, quoted from the shipped strict pack — secrets, prompt injection, exfiltration endpoints and enterprise data — with what makes each one precise.

DefenseClaw compiles every guardrail pattern with Go's standard regexp package, which is RE2-based. The creator's regex tester catches incompatible features before you export. Every rule quoted on this page ships in the strict pack under policies/guardrail/strict/rules/; the recipe catalog lists all of them.

Regex detection is not trusted-action proof

Patterns remain useful for broad, portable detection. On authenticated tool actions, however, a raw or custom regex match stays detection-only unless a separate complete, code-owned proof for the same rule authorizes enforcement. See the CEL engine runtime boundary.

RE2 in 30 seconds

RE2 never backtracks: matching time grows linearly with the input, so no pattern can hang the gateway. In exchange, these PCRE features do not work:

  • Lookarounds: (?=…), (?!…), (?<=…), (?<!…)
  • Backreferences: \1, \2, \k<name>
  • Atomic groups: (?>…)
  • Possessive quantifiers: *+, ++, ?+

If your pattern needs any of those, the creator turns the input field red and names the feature. Re-author it with a non-capturing group and tighter character classes. A rule's fallback pattern can be at most 2,048 bytes.

Anatomy of a good rule

policies/guardrail/strict/rules/secrets.yaml (excerpt)
- id: SEC-AWS-KEY
  pattern: '\b(?:AKIA|ASIA)[0-9A-Z]{16}\b'
  title: "AWS access key"
  severity: CRITICAL
  confidence: 0.95
  tags: [credential]

What makes this work:

  • A fixed prefix. AKIA and ASIA are the AWS long-term and temporary key markers. Without them, the pattern would match any 20-character upper-case string.
  • An exact length. {16} after the prefix matches the real key length, and the \b word boundaries stop it matching inside a longer token.
  • Honest confidence. confidence records how often a match is a real key. The shipped SEC-OPENAI-V2 rule (sk-[a-zA-Z0-9]{40,}) uses 0.85 because other vendors also use an sk- prefix.
  • Useful tags. Tags group findings when you triage them in dashboards.

Patterns by category

Secrets

IDPatternCatches
SEC-AWS-KEY\b(?:AKIA|ASIA)[0-9A-Z]{16}\bAWS access key IDs, except the AWS documentation example AKIAIOSFODNN7EXAMPLE
SEC-GITHUB-TOKEN(?:ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9]{36,}GitHub personal, OAuth, user, server and refresh tokens
SEC-PRIVKEY-----BEGIN (?:RSA |EC |OPENSSH |PGP |DSA )?PRIVATE KEY-----Complete PEM and OpenSSH private keys: the header, a key body that parses and the footer. A header line alone, public keys and certificates don't match
SEC-OPENAIsk-proj-[a-zA-Z0-9]{20,}OpenAI project keys
SEC-SLACK-WEBHOOKhttps://hooks\.slack\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[a-zA-Z0-9]+Slack incoming-webhook URLs, which carry their own secret

A match is a finding only when the matched text can be a real secret. The gateway drops documented public examples, such as the AWS sample key, and filler such as placeholder or changeme. SEC-PRIVKEY matches only a whole key block. So a quick test with the AWS sample key or a bare -----BEGIN RSA PRIVATE KEY----- line gets no finding. These are Claude Code Bash tool calls against the shipped default pack. A regex match in a tool call is reported as an alert and does not block the call:

Bash tool callFinding
echo AKIA3FKJ2M5NQ7XZ8BWVSEC-AWS-KEY
echo AKIAIOSFODNN7EXAMPLEnone: the AWS documentation example key
echo -----BEGIN RSA PRIVATE KEY-----none: a header line with no key
cat of a key that ssh-keygen -t ed25519 wrote, in the tool outputSEC-PRIVKEY

Prompt injection

Plain-language injection is the hardest shape to match precisely, so the shipped rules anchor the phrase to the start of a sentence, a list item or a role label. A line can also start with an agent timestamp envelope such as [Thu 2026-10-29 09:40 UTC] , which OpenClaw puts before the user text. That keeps a sentence that merely mentions the phrase from matching:

policies/guardrail/strict/rules/trust-exploit.yaml (excerpt)
- id: TRUST-IGNORE-PREVIOUS
  pattern: '(?im)(?:^|^\[[^\]\n]{0,64}\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}[^\]\n]{0,32}\]\s*|[.!?;,:]\s*|(?:[-*>•]|<!--|["''])\s*|\b(?:task|instruction|system|assistant)\s*:\s*)(?:(?:please,?|(?:can|could|will|would)\s+you(?:\s+please)?|i\s+(?:want|need)\s+you\s+to(?:\s+please)?|now,?|next,?|you\s+(?:must|should|need\s+to))\s+)?ignore\s+(?:all\s+)?(?:previous|prior|above|earlier)\s+(?:instructions|rules|guidelines|context)'
  title: "Ignore previous instructions"
  severity: CRITICAL
  confidence: 0.90
  tags: [prompt-injection]

For ambiguous wording, enable the LLM judge as a second opinion rather than widening the regex.

Unicode zero-width obfuscation

The shipped rule looks for sustained insertion of zero-width characters after ASCII letters or digits. Requiring ten insertions catches deliberately split tokens while avoiding isolated formatting artifacts and ordinary emoji ZWJ sequences.

policies/guardrail/strict/rules/trust-exploit.yaml (excerpt)
- id: OBFUSC-UNICODE-ZWSP
  pattern: '(?:[A-Za-z0-9][\x{200B}\x{200C}\x{200D}\x{FEFF}][\s\S]*?){10,}'
  title: Zero-width character obfuscation
  severity: HIGH
  confidence: 0.95
  tags: [prompt-injection, obfuscation]

What counts toward the threshold

The counted characters are U+200B (zero-width space), U+200C (zero-width non-joiner), U+200D (zero-width joiner), and U+FEFF (byte-order mark). Each must immediately follow an ASCII alphanumeric character. Nine insertions do not match, and a ZWJ between two emoji does not count.

Exfiltration endpoints and download-and-run

Known collection endpoints are matched as a whole host name, so webhook.site matches but mywebhook.site.example doesn't:

policies/guardrail/strict/rules/c2.yaml (excerpt)
- id: C2-WEBHOOK-SITE
  pattern: '(?i)(?:^|[^a-zA-Z0-9-])webhook\.site(?:[^a-zA-Z0-9.-]|$)'
  title: "webhook.site (known exfil)"
  severity: HIGH
  confidence: 0.90
  tags: [exfiltration, c2]

Tool-call rules pair a CEL expression with the regex fallback. Here the fallback catches a wget download piped into an interpreter when the call can't be parsed:

policies/guardrail/strict/rules/commands.yaml (excerpt)
- id: CMD-PIPE-WGET
  tool_call_only: true
  expression: >-
    f.commands.exists(c, c.argv_complete && c.program in ['wget', 'wget.exe'] &&
    (defenseclaw.guardrail.semantic.v1.OperationKind.OPERATION_KIND_FETCH in c.operations ||
    defenseclaw.guardrail.semantic.v1.OperationKind.OPERATION_KIND_UPLOAD in c.operations))
  pattern: '(?i)\bwget\b\s+[^|]*\|\s*(?:[/\w.-]+/)?(?:bash|zsh|sh|dash|ksh|python(?:[0-9.]*)?|perl|ruby)\b'
  title: "wget piped to shell"
  severity: CRITICAL
  confidence: 0.95
  tags: [execution, download-exec]

See Authoring CEL rules for the expression side.

Enterprise data shape

Numeric-only patterns are the easiest to false-positive, so the shipped rules encode the structure of the number instead of only its length. The SSN rule rejects area numbers that are never issued (000, 666, 9xx) and all-zero groups:

policies/guardrail/strict/rules/enterprise-data.yaml (excerpt)
- id: ENT-BULK-SSN
  pattern: '\b(?:00[1-9]|0[1-9][0-9]|[1-5][0-9]{2}|6[0-5][0-9]|66[0-5]|66[7-9]|6[7-9][0-9]|[78][0-9]{2})-(?:0[1-9]|[1-9][0-9])-(?:000[1-9]|00[1-9][0-9]|0[1-9][0-9]{2}|[1-9][0-9]{3})\b'
  title: "US Social Security Number"
  severity: CRITICAL
  confidence: 0.85
  tags: [pii, regulated]
- id: ENT-CC-VISA
  pattern: '\b4\d{3}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b'
  title: "Visa credit card number"
  severity: CRITICAL
  confidence: 0.80
  tags: [pii, pci]

Suppressions can't quiet these rules: they filter only LLM-judge findings (see the suppression cookbook). If a numeric rule is noisy in your environment, narrow its pattern or disable it in your own pack.

Patterns to avoid

  • An unanchored .* or [\s\S]*. It lets a match span unrelated text, so two harmless words far apart become a finding. Bound the gap ([\s\S]{0,120}) or anchor both sides.
  • Short or common prefixes on their own. sk- or ghp alone match ordinary text; pair a prefix with the exact length and character class of the real value.
  • Nested quantifiers such as (\w+)+. RE2 still runs them in linear time, but they are a sign of a pattern that matches far more than intended. The creator's REGEX_REDOS check flags them.
  • Case-insensitive matching without (?i). Use the inline flag so the engine and your tester agree.

Workflow

In the policy creator Rule pack section, paste the pattern. The creator runs it through V8, the RE2 lint and the nested-quantifier check, plus your should match and should NOT match examples. Then export the pack and run defenseclaw guardrail validate-pack on it. Live Test evaluates only the OPA/Rego policy, not regex rules.