Custom Rules for Kingfisher¶
Kingfisher's candidate detector catalog is sourced from the Betterleaks catalog and selected Veles detectors, with rare first-party exceptions. Generally useful detectors and validation improvements must go upstream to Betterleaks. Direct inclusion requires a specific documented reason to ship in Kingfisher itself, source/license provenance, tests, and a retirement condition; it is not a shortcut around upstream contribution. When Betterleaks provides equivalent detection and live validation, its detector is preferred and the redundant Veles detector can be retired after compatibility review. Detection-only overlap does not replace Veles validation or operational capabilities.
The current built-in catalog contains 503 rules, including five first-party connection-string rules, selected Veles rules, and hidden component/helper rules. See the built-in rules listing for the per-rule catalog and capability counts.
Filename-only detectors are not imported into the built-in catalog: a filename alone is not evidence of an exposed secret. Content detectors may still restrict matching by path. Custom Kingfisher YAML and Betterleaks TOML rules continue to support explicit filename-only/path-only rules.
The Betterleaks source is pinned to v2.0.0-rc.7. It adds betterleaks.mapbox-secret-token and updates betterleaks.mapbox-api-token to detect bare structured sk./pk. tokens while preserving upstream payload-shape and entropy filters. Mapbox validation requires TokenValid; revoked, expired, malformed, and invalid responses remain inactive even with HTTP 200. Explicit analysis may look up at most 100 secret tokens for scopes; missing tokens:read permission does not invalidate a token. Harness PAT analysis adds user/account identity and confirmed read capability; SATs do not gain PAT user identity. All 22 selected Veles rules remain bundled because rc.7 does not replace their complete coverage.
Existing detectors include Labelbox and Recursion API keys, NuGet API keys, Tailscale enrollment, legacy, OAuth client, SCIM, and webhook keys, Bitbucket Data Center HTTP access tokens (betterleaks.bitbucket-data-center-token), Cloudflare cfut_ user tokens and cfat_ account tokens (betterleaks.cloudflare-api-key.2), and Tableau personal access tokens beginning with + or /. Cloudflare account-token validation requires a nearby account ID; the hidden betterleaks.cloudflare-account-id.1 component is optional for detection and searched within 5L (the match line and up to four lines before or after). Without it, a cfat_ token remains unvalidated. The former betterleaks.cloudflare-api-key rule is now betterleaks.cloudflare-api-key.1; scan --rule cloudflare-api-key continues to select both formats. Direct validation requires an unambiguous selector: use validate --rule cloudflare-api-key.2 for the new token formats.
AWS access IDs remain findings when no secret key falls within the component window. Validation and revocation still require a matching secret key.
Kingfisher fully supports loading both the Kingfisher rule format (.yml/.yaml) and Betterleaks TOML (.toml) for custom rules. Either format can be used for shared or private detections.
Existing rule files require no changes for the rules/scanner 2.0 Rust library release. HTTP service authentication (validation.content.auth) is optional: omitting it preserves the existing request, candidate-token headers, body and response matchers, without requiring OAuth2 credentials or a token exchange. The auth: None migration applies only to Rust struct literals, not YAML or TOML.
The Betterleaks TOML format is supported for custom rules as well as for Kingfisher's built-in catalog. Use it for generally useful detectors that should be developed and shared through Betterleaks. Custom Betterleaks TOML rules are automatically placed in the custom. namespace.
The YAML schema documented below is the Kingfisher rule format. It supports detection, validation, revocation, components, and checksum requirements for custom rules. The built-in catalog is maintained separately: the maintainer tool combines imported detectors and the small first-party exception source in the same compressed bundle and readable betterleaks.yml, veles.yml, and kingfisher.yml files. These generated files preserve the same rules and collection metadata; they are not maintained separately. Each file cites its sources, and the provenance manifest records its hash and per-rule origins, including Kingfisher-authored helpers. See the crate documentation for loading, licensing, and regeneration details.
A rule in the Kingfisher rule format is a YAML document that describes how to detect and optionally validate or revoke secrets. With custom rules you can:
- Extend Kingfisher without touching Rust code
- Tune sensitivity via entropy and confidence
- Plug in live checks against external services
Load .toml, .yml, or .yaml custom rules with --rules-path. They are additive to built-ins; pass --load-builtins=false for a custom-only scan. A rules directory can contain both formats, or you can repeat --rules-path to load separate files:
kingfisher scan --rules-path ./company.yml --rules-path ./team.toml ./src/
kingfisher rules check --rules-path ./custom-rules/ --load-builtins=false --no-update-check
rules check verifies that each examples entry has at least one match that survives the scan-time content filters, and that each negative_examples entry has none. Both checks use the scanner's secret capture selection, entropy threshold, built-in safe-list, pattern requirements (including checksums), and rule filters. A filtered positive example or a surviving negative example is an error, even without --warnings-as-errors, with one compatibility exception: a positive example rejected only by ignore_if_contains produces a warning because that option is intended for runtime filtering. The example is rechecked with only substring filtering disabled; entropy, safe-list, checksum, and rule-filter failures still produce errors. Use --warnings-as-errors to make the substring warnings fail the check. Negative examples still apply ignore_if_contains.
Examples contain only content, so these checks do not apply source-path restrictions, source prefilters, inline ignore comments, or dependency resolution. They do not make live validation requests. Include realistic, non-placeholder positive examples and negative examples for inputs that the pattern or content filters should reject.
Kingfisher's imported-rules-capabilities.yml is not another rule format. Its source-specific sections may bind existing imported detectors to operational validation, access-map, revocation, confidence, authority, narrow filter behavior, or derive bare token patterns with bare: true, but must not contain detector regexes. See the overlay reference.
Veles support is built-in-only. crates/kingfisher-rules/data/veles-rules.yml pins an OSV-SCALIBR commit and selects upstream Veles plugin IDs that have explicit import adapters; --rules-path does not accept Veles source or configuration.
Configured confidence¶
Rules use their configured confidence (low, medium, or high) for selection and reporting. The CLI's --confidence and SDK confidence options select those static levels before native regex compilation. There are no dynamic confidence upgrades, demotions, or runtime confidence variants; filters cannot change individual findings' confidence. After --exclude-rule exclusions, an explicit --rule selector whose remaining matches are all below that minimum produces an error; lower --confidence instead of expecting the selector to override it. This also applies when combining an explicit selector with --rule all. Rule inspection via rules list and rules check defaults to low confidence (all levels) and accepts --confidence to narrow inspection. Selectors whose matches are all explicitly excluded are ignored.
Existing custom Kingfisher YAML and Betterleaks TOML files still load without edits. Legacy one-string-argument setConfidence(...) and filter.setConfidence(...) calls return that string for expression compatibility but do not change confidence. The argument is not interpreted or validated as a confidence level, so calls such as setConfidence("bogus") remain loadable. Rejection filters and association helpers remain active. Built-in imports omit the unused confidence-only computations.
Connection-string password rules¶
Five embedded rules detect database passwords at medium confidence. They load by default in the CLI, Rust's get_builtin_rules(None), and Python's Rules().
The catalog also includes betterleaks.generic-api-key at static low confidence, without its upstream confidence-upgrade computation and with all rejection filters preserved. The CLI, Python, and Node default minimum of medium excludes it before native regex compilation, selecting 502 of the 503 built-ins. Opt in with --confidence low, Python's Rules(confidence="low"), or Node's Rules.load({ confidence: "low" }). betterleaks.generic-credential-uri stays medium; generic-password and generic-username remain excluded from the catalog. Custom YAML/TOML files remain loadable; the configured-confidence policy applies to them too.
Their IDs use the kingfisher.connection-string.password. prefix with suffixes unquoted, double-quoted, single-quoted, odbc-braced, and jdbc-query:
- Semicolon-delimited strings require same-line
Server,Host,Data Source, orDSNbeforePasswordorPwd. SQL Server JDBC URLs support unquoted and braced passwords. - PostgreSQL, MySQL, and MariaDB JDBC URLs support the case-sensitive
password=query property, including MySQLloadbalance/replication, bare preceding flags, and&separators. Findings retain source percent encoding. JDBC userinfo URLs remain covered bybetterleaks.generic-credential-uri.
Passwords contain 4–128 bytes; doubled ODBC closing braces count as one unit. Weak literals remain eligible (min_entropy: 0). Placeholder exclusions use documented pattern_requirements.ignore_if_contains: case-insensitive substrings can suppress real passwords containing a marker. Disable these exclusions with --no-ignore-if-contains.
These rules report only passwords and perform no validation or revocation. The existing Jdbc validator supports PostgreSQL but needs the full connection URI. ODBC validation requires backend-specific parsing and clients; DSN-only strings also need local driver configuration. SQL Server validation would require TDS support.
This is a temporary exception restoring coverage lost in the 2.x catalog migration (#558); replace it when focused Betterleaks coverage becomes available. See coverage limits, provenance, and the upstream exception.
Select this family with:
kingfisher scan ./src --rule kingfisher.connection-string.password \
--format toon --no-validate --no-update-check
Betterleaks v2 programs¶
Predicate bodies support local let declarations and expression sequences; the last expression supplies the result. Existing YAML/TOML rules need no edits. See the cryptographic reference for Kingfisher's extended crypto.* functions, byte encodings and complete authentication examples.
Custom TOML supports validate, analyze, and revoke Expr programs, named finding.captures and components[id].captures, optional components, valueGroup, specificity, tags, keywords, and path-only rules. A higher specificity suppresses a contained value from another rule on the same line; equal specificity preserves ties. Unknown TOML keys, invalid component references, and malformed programs fail loading. The optional malformedPrivateKey filter helper is a Kingfisher-only extension; custom TOML that uses it is not portable to upstream Betterleaks. Do not use it in upstream detector contributions. It decodes Base64 armor and checks supported private-key container structure offline. For known ASN.1 labels (PKCS#8, RSA, EC and DSA), source wrappers must contain Base64 bytes that can start an ASN.1 SEQUENCE. Placeholder text, runtime references, and marker-manipulation code without that payload are rejected regardless of their names. This check uses no minimum key-size cutoff and does not evaluate source code. Plausible partial payloads, unfamiliar encodings, encrypted material and recognized BER container/octet-string forms are retained conservatively. These bounded checks do not establish cryptographic or live validity; unrecognized OpenSSH, OpenPGP and future-format source wrappers remain conservative. Built-in private-key candidates stop at an explicit END marker, including short placeholder envelopes, so a malformed fixture cannot consume a following key. For supported unencrypted containers, an impossible decoded header is rejected even when the remaining Base64 has invalid length or padding.
[extend] supports path, useDefault, and disabledRules, with at most two inheritance steps. As in Betterleaks, paths resolve from the working directory. Child rules replace inherited rules with the same ID; global filters and prefilters compose in order. useDefault reads the archived Betterleaks source offline and imports its rules into the custom namespace.
[[rules]]
id = "acme-token"
description = "Acme token"
regex = '''\b(acme_[A-Za-z0-9]{32})\b'''
validate = '''
let r = http.get("https://api.example.com/me", {"Authorization": "Bearer " + finding.secret});
r.status == 200 ? {"result": "valid", "analysis": {"id": r.json.id}} : validate.unknown(r)
'''
analyze = '''
{"identity": {"id": string(validation.analysis.id)}, "capabilities": analysis.capabilities({"read": true})}
'''
revoke = '''
let r = http.delete("https://api.example.com/tokens/self", {"Authorization": "Bearer " + finding.secret});
r.status == 204 ? {"result": "revoked"} : revoke.unknown(r)
'''
Scanning never executes revocation. Analysis is an explicit access-map operation or SDK call after confirmed validation; private validation.analysis evidence is retained internally and omitted from validation reports. Revocation runs fresh through the explicit revoke command/API, without automatically rerunning validation or analysis. A submitted request without confirmation has an unknown outcome.
Kingfisher YAML can also contain Expr source directly; existing AST definitions remain supported:
validation:
type: Betterleaks
content:
expression: >-
let r = http.get("https://api.example.com/me", {"Authorization": "Bearer " + finding.secret});
r.status == 200 ? {"result": "valid"} : validate.unknown(r)
revocation:
type: Betterleaks
content:
expression: >-
let r = http.delete("https://api.example.com/tokens/self", {"Authorization": "Bearer " + finding.secret});
r.status == 204 ? {"result": "revoked"} : revoke.unknown(r)
YAML also accepts optional specificity (default 0), tags, and keywords. Keywords select rules case-insensitively using the complete raw or decoded source fragment, before content filters run. A keyword outside a Base64 payload cannot authorize a match inside that decoded payload. Empty keyword lists impose no gate.
Validation response identity metadata¶
Successful validation can include a small identity summary in the response's metadata object, shown as __Response in pretty output and retained in structured reports. Kingfisher reuses evidence from the existing validation operation; it does not execute analyze, perform additional identity lookups, or infer permissions. The existing --redact behavior still hides validation responses, including these identity summaries. For example, AWS STS GetCallerIdentity produces:
{"result":"valid","metadata":{"arn":"arn:aws:iam::123456789012:user/example","account":"123456789012","userid":"example-user-id"}}
The ARN identifies the caller principal, which may be an IAM user, root, or an assumed-role session rather than a user.
| Provider | Identity metadata |
|---|---|
| AWS | arn, account, userid |
| Hugging Face | id, username, and the reported token role when recognized |
| GitHub | id, username |
| GitLab, Fastly | user_id, token_id |
| CircleCI personal tokens | id, username |
| GCP service accounts (existing) | credential_type, project_id, client_email |
| GCP application-default credentials (existing) | credential_type, client_id |
| Azure service principals (existing) | tenant_id, client_id |
| Azure Storage, App Configuration, Service Bus (existing) | Storage account, endpoint/key ID, or host/entity path, as applicable |
GCP's authorized-user client_id identifies the OAuth client, not the end user. Google API-key validation does not identify an owner; it retains its existing activity/restriction metadata without adding owner lookups.
The new summaries use explicit scalar-field allowlists for the corresponding Kingfisher provider capability (validation.content.capabilities.access_map). Private analysis maps, authentication objects, organization memberships, and profile details are not copied wholesale. Values must be nonblank strings of at most 2,048 UTF-8 bytes, without Unicode control (Cc) or format (Cf) characters. Credential-bearing values are omitted, including substring echoes of primary and component secrets of any nonzero length. Other strings within the actual finding and components inputs, including captures, become substring filters only at eight UTF-8 bytes: a short region or numeric capture must not suppress an unrelated identity. Unrelated globals are not inspected. GitLab's "0" token-ID sentinel is omitted.
Explicit public metadata from a rule takes precedence. Failed or inconclusive validation never receives these summaries, and the original private handoff remains available to explicit analysis. Auto-inclusion requires an explicit built-in provider capability; custom TOML imports do not infer one from a rule ID. Existing custom YAML/TOML rules retain their previous output without edits or new schema fields, including any explicit rule-authored public metadata. Treat identity-bearing reports as sensitive even though these fields are not credentials.
Using rules from Rust and Python¶
The CLI, kingfisher-scanner, and kingfisher_sdk share rule loading, capture selection, entropy checks, pattern_requirements, and Liquid filters. Requirements run during detection for raw and decoded Base64 matches, before component resolution, redaction, or live validation. A parsed requirement is enforced, not just inspection metadata.
| Rule behavior | Rust crates and Python SDK |
|---|---|
| YAML/TOML loading, confidence, path restrictions and Betterleaks expressions | Shared rule loader and compiled database; supply the logical path for path-aware scans |
| Character minimums, custom special characters, ignored substrings and checksums | Enforced by default, including named-capture checksum context and missing-capture policy |
Required/optional components and within | Python retains full-match context automatically. Rust callers needing exact full-match windows use Scanner::scan_blob_with_context and Validator::with_scan_context; existing vector-only methods retain their historical location-based association |
verify_candidates: true | Shared fixed-origin eligibility, ranking, 16-combination budget, deadline and four-search concurrency limit; only explicit validation sends requests |
| Validation types, HTTP/gRPC matchers, OAuth2, Liquid/Expr signing and encryption | Shared validation engine; enable Rust's validation feature and call Validator explicitly |
| HTTP/AWS/GCP and multi-step revocation | Shared revocation engine; Python requires confirm=True |
visible: false | Helpers remain in SDK results for association; filter finding.visible only when reporting |
| Examples, negative examples and references | Rule metadata for inspection/checking; examples are not scan-time allowlists |
Within each SDK validation batch, identical rules and resolved credential inputs reuse definitive active/inactive results even with different remaining attempt budgets. Inconclusive failures and cancellations are not memoized, so a later occurrence can retry. Different rules and component values remain independent; separate batches recheck. Scanning stays offline. CLI report switches, configuration files, source enumeration, endpoint/TLS overrides and rate limits are application policy; configure embedding APIs explicitly as described in the Rust guide and Python guide.
1. Rule Schema¶
Each Kingfisher YAML rule file defines one or more entries under a top‑level rules: list. Every entry supports the following fields:
rules:
- name: # (string) Human-friendly rule name
id: # (string) Unique identifier (e.g. custom.aws.secret-key)
pattern: | # (multi-line regex) Detection pattern
(?xi)
aws
(?:.|[\n\r]){0,32}?
\b([[:alnum:]/+=]{40})\b
min_entropy: 3.5 # (float) Minimum Shannon entropy
confidence: medium # (enum: low | medium | high)
examples: # (list) strings that must match
- AWS_SECRET="AKIA…"
negative_examples: # (optional list) strings that must not survive detection
- AWS_SECRET="not-a-secret"
references: # (optional list) context URLs
- https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html
visible: true # (bool) hide helper matches when false
depends_on_rule: # (optional) capture chaining
- rule_id: custom.aws.access-key-id
variable: AKID # referenced as {{ AKID }}
pattern_requirements: # (optional) character/word requirements
min_digits: 1 # require at least 1 digit
min_uppercase: 1 # require at least 1 uppercase letter
min_lowercase: 1 # require at least 1 lowercase letter
min_special_chars: 1 # require at least 1 special character
special_chars: "!@#$%^&*()" # optional: custom special character set
ignore_if_contains: # optional: drop matches containing these words
- test
validation: # (optional) live validation
type: Http
content:
request:
method: GET
url: https://api.example.com/v1/check
headers:
X-Secret: "{{ TOKEN }}"
X-Id: "{{ AKID }}"
response_is_html: true # by default, validation responses containing HTML or considered invalid. Set to `true` if you expect HTML returned from a validation response
response_matcher:
- report_response: true # always include raw payload
- type: StatusMatch
status: [200] # positive check
- type: StatusMatch
status: [401,403]
negative: true # negative check → must NOT match
- type: HeaderMatch
header: content-type
expected: ["application/json"]
- type: JsonValid
# NOTE: Some providers are gRPC-only (no REST endpoint). For those, use Grpc validation.
validation:
type: Grpc
content:
request:
url: https://api.example.com/<package>.<Service>/<Method>
headers:
content-type: application/grpc
te: trailers
Authorization: "Bearer {{ TOKEN }}"
# Raw bytes are allowed (YAML \u0000 escapes become NUL bytes).
body: "\u0000\u0000\u0000\u0000\u0000"
response_matcher:
- report_response: true
- type: HeaderMatch
header: grpc-status
expected: ["0"]
revocation: # (optional) revoke a secret
type: Http
content:
request:
method: POST
url: https://api.example.com/v1/revoke
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- report_response: true
- type: StatusMatch
status: [200, 202]
AWS access key revocation can use:
GCP service account key revocation can use:
Built-in revocation is credential-family-specific, not provider-wide. See the provider contracts and required inputs for Notion OAuth, Resend, Twilio key SIDs, Vercel AI Gateway, GCP API keys, Anthropic ordinary keys, OpenAI project/admin keys, and existing GitHub, Slack, and Hugging Face bindings. RubyGems requires an owner/manual or authorized-partner flow; no account-wide reset is used. Owner-ID flows require an explicit full-token-to-ID mapping and separate management credentials, not masked prefix/name matching. Missing inputs fail before mutation. GCP pending operations and new GitHub App 202 submissions remain unknown rather than confirmed revoked. Existing primary actions and custom YAML/TOML behavior are unchanged; existing 202-only GitHub/Hugging Face success flags still mean report acceptance, not verified completion.
Multi-Step Revocation¶
Some services require a 2-step revocation process: 1. Lookup Step: Make a request to retrieve an ID or token 2. Delete Step: Use that ID to perform the actual revocation
For these cases, use HttpMultiStep:
revocation:
type: HttpMultiStep
content:
steps:
- name: lookup_token_id # Step 1: Get the token ID
request:
method: GET
url: https://api.example.com/v1/tokens/current
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [200]
extract: # Extract values from response
TOKEN_ID: # Variable name (uppercase)
type: JsonPath # Extraction method
path: "$.data.id" # JSONPath to the value
- name: revoke_token # Step 2: Delete using the ID
request:
method: DELETE
url: https://api.example.com/v1/tokens/{{ TOKEN_ID }}
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- report_response: true
- type: StatusMatch
status: [204]
| Field | What it does |
|---|---|
| name | Friendly name shown in reports |
| id | Unique text ID (namespace.v#) used internally |
| pattern | Regex used to spot secrets (free‑spacing & flags allowed) |
| min_entropy | Threshold to guard against low‑complexity false positives |
| confidence | Suggests severity: low → high |
| examples | Good matches; used for testing |
| negative_examples | Inputs that must not match after content filtering; used for testing |
| visible | false to hide non‑secret captures (e.g. IDs) |
| depends_on_rule | Chain rules: use captures from one rule in another's validation |
| pattern_requirements | Require character types and/or exclude placeholder words from matches |
| validation | Configure Assumed, Http, Grpc, typed validators, or Raw exception-path checks |
| allow_internal_ips | Request permission to validate against internal IPs. Defaults to false. See internal IP validation. |
| fallbacks | Up to two named HTTP alternatives, disabled unless explicitly enabled; see fallbacks |
| revocation | Configure HTTP, AWS, or multi-step revocation for a detected secret |
Validation Types¶
Kingfisher supports these validation types:
Assumed: a rule-level marker for secret material accepted with high confidence without live validation. It produces theAssumed Valid (Not Live-Validated)finding status and is included by theactionablefilter, but not by the strictactivefilter. In colorized pretty output it uses the same bright color as an active credential but with a locked icon. It counts as skipped validation by default and as successful validation with theactionablefilter.HttpandGrpc: YAML-native validation flows. Prefer these first.- Typed validators: schema-level validation families already modeled in the rule schema, such as
AWS,AzureStorage,Coinbase,CredentialUri,Ethereum,GCP,MongoDB,MySQL,Postgres,Jdbc, andJWT.CredentialUridispatches a namedURIcapture (falling back toTOKEN) to HTTPS Basic Auth, SMTP AUTH, or a supported database validator while leaving other unsupported schemes unvalidated.Ethereumis deterministic and network-free; it validates key material and derives an address without claiming the address is active. - Raw validators: provider-specific or protocol-specific exception paths dispatched through
validation: type: Raw.
Internal IP validation¶
Add allow_internal_ips: true alongside validation in a trusted custom Kingfisher YAML rule to declare that it needs access to internal IPs. Pass --enable-rule-internal-ips on the CLI to honor the declaration. The rule defaults to false when the field is omitted.
Existing YAML and Betterleaks TOML rules work without edits. Use --enable-internal-ips-for to allow a rule from either format by ID, including a YAML rule that omits the field or sets it to false. See the CLI examples.
Overlapping rules and validation deduplication¶
A token can match multiple rules. Kingfisher keeps those findings separate and does not choose a winning provider. Each matching rule with a validator is validated independently; for example, a token matching both OpenAI and DeepSeek rules can produce one request and result for each provider. Repeated occurrences of the same rule and validation input are grouped into one request, while dependency values are included when relevant. Rules without validation, Assumed rules, and non-authoritative rules make no live validation request. Report deduplication also includes the rule ID, so different rules remain separate. --no-dedup controls reported occurrences and does not disable this internal validation grouping.
Rules without a validation block produce Not Attempted findings. They are not treated as active, inactive, or skipped because no validation result was produced.
An assumed validation is configured as:
A Kingfisher custom private-key rule can use this marker when its high-signal format can be accepted without a provider request; its findings are reported as Assumed Valid (Not Live-Validated).
Raw validation looks like this:
Use Raw only when the provider check cannot be expressed reliably with Http or Grpc and does not justify a new reusable validator family. Raw validator implementations live in crates/kingfisher-scanner/src/validation/raw.rs.
Typed validators are safer and more reusable because the validator kind is part of the schema. Raw validators are string-dispatched; an unknown content name is reported as an unimplemented, unverified validation result. If you need a Rust-backed exception path for one provider, prefer Raw; reserve new typed validators for stable validation families that can be reused across rules.
The Ethereum family uses content: private_key, public_key, or mnemonic. Mnemonics use the standard m/44'/60'/0'/0/0 path and explicitly assume an empty BIP-39 passphrase, so the reported address is a candidate. Validation responses contain only allowlisted derivation metadata and never the private key or seed phrase.
Ordered HTTP fallback endpoints¶
Primary only is the default. Existing Kingfisher YAML and Betterleaks TOML rules need no edits. Keep the existing validation: and revocation: definitions as the primary configuration. Add an optional rule-level fallbacks: list only when you want additional HTTP environments.
Fallback environments require --fallbacks on the CLI, .http_fallbacks(true) on Rust's ValidatorBuilder/ValidationEngine, or Validator(http_fallbacks=True) in Python. Without opt-in, fallback templates are not rendered, their hosts are not resolved or contacted, and fallback-only variables are not required. Existing explicit --endpoint and template-variable overrides still determine the primary. The flag does not enable automatic revocation: scan and validate never revoke credentials. Revocation remains a separate, explicitly invoked operation.
Each fallback has a unique id and chooses one of these forms:
Reuse the primary logic, not the primary destination. These options copy the request/action settings so they need not be duplicated. You still provide the fallback target in url, revocation_url, or revocation_urls; the primary URL(s) are never inherited. For example, both environments can use the same Bearer header and response matchers while contacting different service instances.
reuse_primary_validation_logic | Required fields | Meaning |
|---|---|---|
true | Fallback-level url: | Copy the primary HTTP validation, replacing only request.url. Keep its method, headers, body, matchers, multipart and authentication. A separate validation: is forbidden. |
false or omitted | Complete validation: { type: Http, content: ... } | Independent HTTP validation. Nothing is merged with the primary. A fallback-level url: is forbidden. |
Incomplete or mixed forms are configuration errors, not implicit inheritance.
Revocation has an independent choice, also defaulting to false:
reuse_primary_revocation_logic | Configuration | Meaning |
|---|---|---|
true, primary Http | Required revocation_url: | Copy the complete primary action, replacing only its request URL. |
true, primary HttpMultiStep | Required revocation_urls: | Copy the complete primary program, replacing each step URL in order. Exactly one nonblank URL per step (one or two steps). |
false or omitted | Optional complete revocation: | Independent action; if omitted, revocation is unavailable for this fallback. |
Primary revocation must exist and be HTTP or HTTP multi-step when reuse is true. Do not combine reuse with a separate revocation: definition. URL overrides are forbidden when reuse is false. revocation_url is for a single request only; revocation_urls is for multi-step only. Headers, methods, bodies, response matchers and extractors are preserved without merging or other overrides. Both switches default to false.
For an existing two-step primary program, the reuse form looks like this:
fallbacks:
- id: secondary
reuse_primary_validation_logic: true
url: https://secondary.example.com/v1/me
reuse_primary_revocation_logic: true
revocation_urls:
- "{{ VALIDATION_ORIGIN }}/v1/tokens"
- "{{ VALIDATION_ORIGIN }}/v1/tokens/{{ TOKEN_ID }}"
The primary program's first-step extractor must provide TOKEN_ID; its extractor and final-step response matchers are copied unchanged. No primary URLs are reused as mutation destinations.
There may be at most two fallbacks (three environments including primary). This safety cap is not relaxed by --no-limits. IDs use ASCII letters, digits, _, -, or .; primary is reserved. Nested fallbacks, references to other fallbacks, and non-HTTP fallback validators are not supported. Repeated YAML is preferable to ambiguous header or matcher merging.
rules:
- id: custom.example.token
name: Example service token
pattern: '\b(svc_[A-Za-z0-9]{32})\b'
validation:
type: Http
content:
request:
method: GET
url: https://primary.example.com/v1/me
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [200]
- type: JsonValid
revocation:
type: Http
content:
request:
method: DELETE
url: https://primary.example.com/v1/tokens/self
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [204]
fallbacks:
- id: secondary
reuse_primary_validation_logic: true # Reuse GET, headers and response matchers.
url: https://secondary.example.com/v1/me
reuse_primary_revocation_logic: true # Reuse DELETE, headers and response matchers.
revocation_url: https://secondary.example.com/v1/tokens/self
- id: legacy-service
# reuse_primary_validation_logic defaults to false.
validation:
type: Http
content:
request:
method: POST
url: https://legacy.example.com/check
headers:
X-API-Key: "{{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [200]
- type: WordMatch
words: ['"authenticated":true']
# Primary only, even if the rule declares fallbacks:
kingfisher scan ./repo --rules-path ./custom-rules.yml --format toon
# Explicit permission to send candidates to configured fallback environments:
kingfisher scan ./repo --rules-path ./custom-rules.yml --fallbacks --format toon
kingfisher validate --rules-path ./custom-rules.yml --rule custom.example.token \
--fallbacks --format toon 'svc_a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6'
Validation always starts at primary, then tries enabled fallbacks in declaration order and stops at the first matcher-confirmed success. Alternatives do not add detection rules or duplicate a finding. Each endpoint uses the configured retries and response-size limit within one overall deadline; a slow endpoint can consume the remaining budget. If none succeeds, any inconclusive attempt keeps the final outcome inconclusive. Inactive means every enabled endpoint rejected it; without opt-in this means only the primary, not every possible environment. An enabled fallback with missing inputs also keeps the result inconclusive, with credential-free diagnostics naming the missing variables. For validate, --arg continues to map only to primary validation variables; use named --var inputs for fallback-only fields.
Successful HTTP validation privately retains VALIDATION_URL, VALIDATION_ORIGIN, VALIDATION_ENDPOINT_INDEX (zero-based), and the enabled VALIDATION_ENDPOINT_COUNT. A named fallback also retains VALIDATION_FALLBACK_ID. Result-based revocation uses only that environment's resolved action: an independent revocation: or explicit primary revocation reuse with replacement URL(s). If neither is configured, revocation is unavailable. Reuse of validation does not imply reuse of revocation. Selected fallback actions and legacy revocation URL lists must use the accepted origin. Primary scalar actions retain their configured destination, even when fallbacks are enabled; primary validation and revocation may use different origins. A revocation_urls list maps existing steps; it is not a list of alternative mutation targets. Validation may try environments in order; revocation never falls back to another environment. Redirects are disabled, and response extractors cannot overwrite selection variables. If a crypto-templated fallback URL uses a prior response after a mutating step, start it with a fixed origin matching validation or {{ VALIDATION_ORIGIN }} followed by /, ?, or #. URLs may contain secrets; selection snapshots stay out of ordinary reports.
Validate, select, then revoke¶
revoke --fallbacks performs validation itself, retains the verified endpoint internally, and executes only that environment's resolved action. No preceding validate command or manual endpoint variables are needed:
kingfisher revoke --rules-path ./custom-rules.yml --rule custom.example.token \
--fallbacks --format toon 'svc_a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6'
The command requires one unambiguous rule with HTTP validation. It checks primary first, then the configured alternatives, stopping at the first verified-active result. If validation is inactive, inconclusive, skipped, unavailable, or times out, no revocation action runs. If the first verified environment has no revocation configured or lacks action inputs, the command also stops; it does not continue searching for another environment to mutate. Validation retries are allowed, but HTTP mutations are never automatically retried or moved to another environment.
Pass credential/supporting values using --var NAME=VALUE. With --fallbacks, --arg maps alphabetically across validation and possible action inputs, excluding internal endpoint state and values extracted by earlier revocation steps. Named variables are recommended for compound credentials. TOKEN and VALIDATION_* endpoint-selection variables are determined internally and cannot be overridden. For private services, use one of the internal-IP validation options. The selection phase uses the same address checks and TLS policy as direct validation.
--timeout bounds the whole validation phase, including fallback attempts and validation retries. Revocation retains its individual HTTP/AWS request/step timeouts. --retries controls validation retries and read-only revocation lookup retries, never mutation retries. A timeout after submission can mean the action occurred; verify provider state before retrying manually.
Without --fallbacks, revoke retains legacy direct-primary behavior and does not add validation requests. scan and validate never revoke automatically.
JSON/TOON output includes a safe fallback_id when validation or revocation selects a named alternative; private endpoint URLs remain internal. Scan-generated fallback revoke commands use the same validate-to-select workflow rather than forwarding old VALIDATION_* values, so the environment is re-established when executed. SDK result-based revocation instead reuses its exact retained validation snapshot without revalidation or an additional execution-policy setting.
Legacy scalar request.url rules retain their behavior. Legacy url: [...] inputs remain readable, but additional URLs require the same explicit execution opt-in and are limited to two when enabled. Longer legacy lists still load and try the primary and first two alternatives, with a warning that remaining URLs are ignored. Do not mix those lists with named fallbacks. Their legacy revocation URL lists select the corresponding validated index; missing or mismatched selections fail before mutation. Use named profiles for new rules.
OAuth2 authentication for HTTP verification services¶
Use validation.content.auth.oauth2 when an internal verifier requires its own access token. The resource-owner password grant authenticates the scanner to that service; {{ TOKEN }} remains the candidate secret being checked.
validation:
type: Http
content:
auth:
oauth2:
token_endpoint: https://idp.example.com/oauth2/token
token_header: X-Proxy-Authorization # Optional; defaults to Authorization
ropc:
username_env: KF_VERIFIER_USERNAME
password_env: KF_VERIFIER_PASSWORD
client_id: kingfisher
client_secret_env: KF_VERIFIER_CLIENT_SECRET # Optional
scope: verify # Optional
request:
method: GET
url: https://verifier.example.com/verify
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [200]
- type: WordMatch
words: ['"valid":true']
The complete example rule can be loaded with --rules-path. Replace the endpoints and response matchers with your service's contract. Set the named environment variables before running:
kingfisher rules check --rules-path crates/kingfisher-scanner/examples/fixtures/acme-oauth2.yml --load-builtins=false --no-update-check
kingfisher scan ./src --rules-path company-rules.yml --load-builtins=false --format json
username and password may be configured directly instead of username_env and password_env; choose exactly one form for each. client_secret and client_secret_env are optional alternatives. Prefer environment references over stored literal credentials. CLI JSON inspection and Python Rules.detail() redact literal OAuth2 username, password and client_secret values as [REDACTED], while retaining environment references. Direct Rust configuration serialization remains lossless and can expose literals; treat it as sensitive. Credentials are form encoded in the token request; a client secret, when supplied, is sent as client_secret in that form.
Tokens are shared across concurrent checks within one validation session and reused until shortly before expires_in. Without an expiry, they are refreshed after 54 seconds (a 60-second lifetime with an early-refresh margin). Failed exchanges use exponential cooldowns from 1 to 64 seconds, including after cancellation. Token responses are capped at 64 KiB. Authentication failures are inconclusive validation results, never proof that the candidate secret is invalid.
Both endpoints use HTTPS with strict certificate verification, even with --ignore-certs or Rust's ValidationEngine::use_lax_tls option. OAuth2 uses separate transports so those options and custom validator HTTP clients cannot weaken protection of the scanner's password-grant credentials or service access token. HTTPS requests retain environment proxy and NO_PROXY behavior; use a trusted certificate for internal services. The only plain-HTTP exception is loopback with an internal-IP validation opt-in for local development. In Rust, use allow_internal_ips(true). Those loopback HTTP token and verifier requests connect directly, bypassing all proxies so plaintext credentials cannot be sent through an ambient proxy. This exception does not disable proxies for HTTPS or other validator traffic. Verifier origins and token endpoints must be literal operator configuration; finding templates cannot choose their hosts. Redirects are disabled for both exchanges, and the access token is sent only to the configured verifier origin. Internal HTTPS services also require the internal-IP opt-in. Token responses are never reported, and access tokens echoed by a verifier are redacted.
The token header must not collide with a configured request header, standard User-Agent/Accept headers, or reserved transport headers. Use X-Proxy-Authorization when the candidate already occupies Authorization. This auth block is supported for HTTP validation, not revocation.
For Rust struct literals, rules 2.0.0 adds HttpValidation.auth: Option<Box<HttpValidationAuth>>: specify auth: None when unused, or auth: Some(Box::new(HttpValidationAuth { oauth2: config })) with OAuth2Config and its ropc: OAuth2PasswordCredentials. YAML without auth remains valid. Scanner 2.0.0 consumers must also use rules 2.x types; see the Rust migration guide.
SMTP authentication¶
SMTP checks authenticate without sending a message. The built-in betterleaks.generic-credential-uri rule validates smtp://user:password@host:587 and smtps://user:password@host:465 through CredentialUri. Percent-encode reserved characters in URI usernames and passwords.
For separate environment variables or configuration fields, load the custom SMTP rule example:
The example associates SMTP_PASSWORD with nearby SMTP_HOST, SMTP_USERNAME, and optional SMTP_PORT fields using invisible helper rules. It also accepts lowercase configuration keys and : assignments. Customize its custom.smtp namespace, patterns, and eight-line dependency windows for your organization. Missing required fields within the window suppress the password finding; distinct competing hosts, usernames, or ports skip validation instead of guessing a credential pair. Separate fields are currently supported through custom rules, rather than a built-in detector.
The Raw input contract is validation: {type: Raw, content: smtp} with the password in TOKEN, the host in SMTP_HOST, the username in SMTP_USERNAME, and an optional SMTP_PORT. Hosts must be bare hostnames/IPs; bracket IPv6 addresses. An explicit port selects one endpoint, using implicit TLS on port 465 and mandatory STARTTLS on other ports. smtps URIs use implicit TLS on any explicit port and default to 465. Without a port, smtp URIs and separate fields try 587 with STARTTLS, 465 with implicit TLS, then 25 with STARTTLS. Each fallback probe has a three-second budget; an explicit port has a ten-second budget. The overall validation timeout also applies. Probing stops after the first definitive authentication result.
Only advertised AUTH PLAIN or LOGIN mechanisms are used, after TLS succeeds. SMTP 235 means active; SMTP 535 means rejected credentials. Connection failures, TLS errors, timeouts, unsupported mechanisms, and other replies are inconclusive. Server reply text is omitted from reports. Internal targets require an internal-IP validation opt-in, and TLS follows the existing validation TLS policy. SMTP provides no portable credential-revocation operation.
gRPC Validation (Grpc)¶
Some services (notably CLI/SDK control planes) are gRPC-only. For these, validation: type: Http is not sufficient because gRPC status is typically returned via HTTP/2 trailers (grpc-status, grpc-message). Kingfisher’s Grpc validator performs an HTTP/2 request and evaluates matchers against the merged headers+trailers.
Grpc is currently intended for unary requests and expects you to provide a fully-qualified method URL:
validation:
type: Grpc
content:
request:
url: https://api.modal.com/modal.client.ModalClient/ClientHello
headers:
content-type: application/grpc
te: trailers
x-modal-token-id: "{{ TOKEN_ID }}"
x-modal-token-secret: "{{ TOKEN }}"
x-modal-client-type: "1"
x-modal-client-version: "1.0.0"
body: "\u0000\u0000\u0000\u0000\u0000" # Empty protobuf frame
response_matcher:
- report_response: true
- type: HeaderMatch
header: grpc-status
expected: ["0"]
responser_matcher variants. Multiple can be used
| Variant | Required keys | Behavior |
|---|---|---|
| StatusMatch | status (list\negative (bool, default false) | Pass when codes match (or don’t match if negative). |
| WordMatch | words (list\match_all_words (bool)negative (bool) | Word/substring checks in body. |
| HeaderMatch | header (string)expected (list\match_all_values (bool) | Header value assertions. |
| JsonValid | – | Pass only if body parses as JSON. Use when response is expected as JSON data |
| XmlValid | – | Pass only if body parses as well-formed XML. Use when response is expected as XML data |
| ReportResponse | report_response (bool) | Include raw payload in finding for debugging. |
2. Multi-Step Revocation¶
Some APIs require a two-step revocation process:
- Step 1 (Lookup): Query the API to retrieve an internal ID, token identifier, or other metadata
- Step 2 (Delete): Use the extracted value(s) to perform the actual revocation/deletion
Kingfisher supports up to 2 sequential steps in a revocation workflow. Each step can extract values from its response, making them available as variables in subsequent steps.
Response Extractors¶
Values can be extracted from HTTP responses using the following methods:
| Extractor Type | Description | Example |
|---|---|---|
| JsonPath | Extract from JSON response using JSONPath syntax | $.data.id, $.items[0].token_id |
| Regex | Extract using regex with a capture group | "token_id":\s*"([^"]+)" |
| Header | Extract an HTTP response header value | X-Token-ID |
| Body | Use the entire response body as-is | - |
| StatusCode | Extract the HTTP status code as a string | - |
Multi-Step Revocation Schema¶
revocation:
type: HttpMultiStep
content:
steps:
- name: <step_name> # Optional: human-readable step name
request: # Standard HTTP request configuration
method: GET|POST|DELETE|...
url: https://api.example.com/...
headers:
Header-Name: "value"
body: "optional request body"
response_matcher: # Required for final step only
- type: StatusMatch
status: [200]
extract: # Optional: extract variables from response
VARIABLE_NAME: # Variable name (uppercase recommended)
type: JsonPath|Regex|Header|Body|StatusCode
path: "$.path.to.value" # For JsonPath
pattern: "regex pattern" # For Regex (use first capture group)
name: "header-name" # For Header
- name: <next_step> # Subsequent steps can use extracted variables
request:
method: DELETE
url: https://api.example.com/tokens/{{ VARIABLE_NAME }}
response_matcher:
- type: StatusMatch
status: [204]
Multi-Step Revocation Requirements¶
- Minimum 1, Maximum 2 steps: You must define at least 1 step and no more than 2 steps
- Final step requires response_matcher: The last step must include a
response_matcherto determine success/failure - Intermediate steps are optional: Earlier steps don't require response matchers but can have them for validation
- Variables flow forward: Variables extracted in step 1 are available in step 2 via Liquid templates (e.g.,
{{ TOKEN_ID }}) - All standard Liquid filters apply: You can use filters on extracted variables just like with
{{ TOKEN }}
Example 1: Basic Two-Step Revocation¶
This example shows a service that requires looking up a token's ID before deletion:
rules:
- name: Example Service Token
id: custom.example.token
pattern: |
(?xi)
example_token_
[A-Za-z0-9]{32}
min_entropy: 3.5
examples:
- example_token_abc123def456ghi789jkl012mno345
validation:
type: Http
content:
request:
method: GET
url: https://api.example.com/v1/auth/verify
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [200]
revocation:
type: HttpMultiStep
content:
steps:
# Step 1: Look up the token ID
- name: lookup_token_id
request:
method: GET
url: https://api.example.com/v1/tokens/current
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [200]
extract:
TOKEN_ID:
type: JsonPath
path: "$.data.token_id"
# Step 2: Delete the token using the ID
- name: delete_token
request:
method: DELETE
url: https://api.example.com/v1/tokens/{{ TOKEN_ID }}
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- report_response: true
- type: StatusMatch
status: [204]
Example 2: Using Multiple Extraction Methods¶
This example demonstrates extracting values using different methods:
revocation:
type: HttpMultiStep
content:
steps:
# Step 1: Get metadata from multiple sources
- name: get_token_metadata
request:
method: GET
url: https://api.service.com/tokens/info
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [200]
extract:
# Extract from JSON body
TOKEN_ID:
type: JsonPath
path: "$.id"
# Extract from response header
ACCOUNT_ID:
type: Header
name: X-Account-ID
# Extract using regex
TOKEN_TYPE:
type: Regex
pattern: '"type":\s*"([^"]+)"'
# Step 2: Use all extracted values
- name: revoke_token
request:
method: POST
url: https://api.service.com/accounts/{{ ACCOUNT_ID }}/tokens/{{ TOKEN_ID }}/revoke
headers:
Authorization: "Bearer {{ TOKEN }}"
Content-Type: application/json
body: '{"token_type":"{{ TOKEN_TYPE }}"}'
response_matcher:
- type: StatusMatch
status: [200, 204]
Example 3: Complex JSONPath Extraction¶
JSONPath supports nested objects and array indexing:
extract:
# Extract from nested object
USER_ID:
type: JsonPath
path: "$.data.user.id"
# Extract from array (first element)
FIRST_TOKEN_ID:
type: JsonPath
path: "$.tokens[0].id"
# Extract from nested array
SESSION_ID:
type: JsonPath
path: "$.data.sessions[0].session_id"
Example 4: Single-Step Migration Path¶
Existing single-step revocations remain unchanged and continue to work:
# This continues to work as before
revocation:
type: Http
content:
request:
method: DELETE
url: https://api.service.com/tokens/revoke
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- type: StatusMatch
status: [204]
When to Use Multi-Step Revocation¶
Use multi-step revocation when:
- The API requires looking up an ID first: Some services don't accept the token directly for revocation
- You need metadata from the token: The revocation endpoint requires additional information only available via a separate API call
- The service uses indirect revocation: The token must be associated with another resource (session, key, credential) that needs to be identified first
Do NOT use multi-step revocation when:
- The API accepts the token directly: Use the simpler single-step
Httprevocation - You need more than 2 steps: Kingfisher supports a maximum of 2 steps
- The service provides a native revocation method: Use
AWSorGCPtypes when applicable
Cryptographic authentication¶
Custom rules can perform ECDH, ECDSA, authenticated encryption and key derivation without a native provider validator (#587). The shared implementation lives in kingfisher-rules; the Betterleaks expression runtime lives in kingfisher-scanner. The CLI and Rust/Python/Node SDK validators use these same rule capabilities, not separate SDK cryptography APIs. Existing YAML/TOML rules and legacy filters keep working without edits. These additions are Kingfisher extensions: a Betterleaks expression or TOML rule using them is not necessarily portable to upstream Betterleaks.
Key formats and limits¶
Lengths below are decoded bytes, not Base64 character counts. Curve and signature-format names are literal, case-sensitive strings.
| Operation | Accepted material / contract |
|---|---|
P-256 | Private: raw 32-byte big-endian scalar; public: 65-byte uncompressed SEC1 (04 \|\| x \|\| y). ECDH returns 32 bytes. ECDSA hashes the message with SHA-256. |
P-384 | Private: raw 48-byte big-endian scalar; public: 97-byte uncompressed SEC1. ECDH returns 48 bytes. ECDSA hashes the message with SHA-384. |
| EC containers | P-256/P-384 also accept unencrypted RFC 5915 EC PRIVATE KEY or PKCS#8 PRIVATE KEY PEM for private arguments, and SPKI PUBLIC KEY PEM for public arguments. The first matching PEM block is used. The curve must match. |
X25519 | ECDH/public-key derivation only: raw private and public keys are 32 bytes; shared secret is 32 bytes. Not an ECDSA curve. |
| ECDSA signatures | p1363 (default): fixed-width r \|\| s, 64 bytes for P-256 or 96 for P-384. der: ASN.1 DER signature. Pass the message, not a precomputed digest. |
| AES-GCM | AES-128 or AES-256 key (16 or 32 bytes), 12-byte nonce, arbitrary plaintext/AAD. Sealed output is ciphertext \|\| tag with a 16-byte tag. No unauthenticated plaintext is returned on failure. |
| HKDF-SHA256 | Input key material, salt and info are bytes; output length 1–8160 bytes. Use protocol-specific info/domain separation. |
| PBKDF2-HMAC-SHA256 | Password and salt are bytes; iterations 1–1,000,000, output 1–65,536 bytes, and total work iterations * ceil(length / 32) <= 4,000,000. |
| Cumulative budget | Each expression program and each Liquid request attempt shares one work budget across the new cryptographic calls, including those repeated by map/filter or {% for %}. URL, headers, body, and multipart fields share the budget, as do response extractors within each revocation step. The budget allows one maximal small-input PBKDF2 derivation plus roughly 1,000 inexpensive operations. Elliptic-curve operations count more, especially P-384. Each HTTP validation retry has a fresh budget. A read-only revocation retry resends the rendered request. Input sizes also count; PBKDF2 salt and HKDF info are charged for every 32-byte output block. Valid iteration/output lengths can therefore still exceed the budget. Both rule formats report exhausted budgets as unavailable with reason invalid_configuration. |
| Scan-time templates | Pattern-requirement checksums support sha384, sha512 and hmac_sha512 alongside legacy helpers such as sha256. Key agreement, signing, encryption, key derivation and random-byte filters are reserved for validation and revocation. Invalid checksum template syntax produces a warning when the rule loads. Candidates that require the invalid template fail the checksum. |
| Ed25519 | Raw 32-byte private seed, 32-byte public key, 64-byte signature; not a 64-byte expanded private key or Ed25519ph. |
| Randomness | OS-backed cryptographic random bytes; requested length 1–65,536. |
Liquid binary filters¶
Every binary input and binary output in this table uses standard padded Base64, including messages, keys, signatures, AAD and KDF salt/info. EC key arguments (ecdh, ec_public_key, ecdsa_sign, ecdsa_verify) also accept PEM text directly, so a captured PEM TOKEN needs no b64enc; Base64 of the PEM still works. An empty byte string is ''. Curve/format strings and integer arguments are not encoded. Verification/equality return booleans. Do not pipe arbitrary binary data through the legacy text-oriented b64dec/b64url_dec: their UTF-8 conversion can lose bytes. Chain the encoded output directly into the next binary filter. Use b64enc only to introduce UTF-8 text into that chain.
In the signatures below, *_b64 denotes Base64-encoded bytes; brackets indicate an optional argument and are not Liquid syntax.
| Liquid pipeline | Result |
|---|---|
public_b64 \| ecdh: private_b64, curve | Shared secret, Base64; apply HKDF before using as an encryption key. |
private_b64 \| ec_public_key: curve | Public key, Base64 (uncompressed SEC1 for P-curves; raw X25519). |
message_b64 \| ecdsa_sign: private_b64, curve [, format] | Signature, Base64; format defaults to p1363. |
message_b64 \| ecdsa_verify: public_b64, signature_b64, curve [, format] | Boolean signature check. |
plaintext_b64 \| aes_gcm_encrypt: key_b64, nonce_b64 [, aad_b64] | Sealed ciphertext/tag, Base64; omitted AAD is empty. |
sealed_b64 \| aes_gcm_decrypt: key_b64, nonce_b64 [, aad_b64] | Authenticated plaintext, Base64; omitted AAD is empty. |
ikm_b64 \| hkdf_sha256: salt_b64, info_b64, length | Derived bytes, Base64. |
password_b64 \| pbkdf2_sha256: salt_b64, iterations, length | Derived bytes, Base64. |
seed_b64 \| ed25519_public_key | Raw public key, Base64. |
message_b64 \| ed25519_sign: seed_b64 | Signature, Base64. |
message_b64 \| ed25519_verify: public_b64, signature_b64 | Boolean signature check. |
'' \| random_bytes: length | Random bytes, Base64; pipeline input is ignored. |
a_b64 \| constant_time_eq: b_b64 | Boolean comparison of decoded bytes, not their encoded spelling. |
Text hashing/HMAC follows the existing text-filter convention instead: text | sha384 and text | sha512 return lowercase hex, like sha256; text | hmac_sha512: key_text returns standard Base64, like hmac_sha384. The HMAC input and key are literal UTF-8 text, not Base64-decoded keys. For arbitrary binary HMAC inputs, use the expression functions below.
For example, this one template preserves binary data through ECDH → HKDF → AES:
{%- assign shared_b64 = PINNED_PEER_PUBLIC_B64 | ecdh: EPHEMERAL_PRIVATE_B64, 'X25519' -%}
{%- assign salt_b64 = '' | random_bytes: 16 -%}
{%- assign info_b64 = 'provider/identity/v1' | b64enc -%}
{%- assign key_b64 = shared_b64 | hkdf_sha256: salt_b64, info_b64, 32 -%}
{%- assign nonce_b64 = '' | random_bytes: 12 -%}
{%- assign message_b64 = '{"operation":"identity"}' | b64enc -%}
{{- message_b64 | aes_gcm_encrypt: key_b64, nonce_b64 -}}
Betterleaks expression functions¶
Expression helpers consume and return raw bytes, unless noted. bytes(text) introduces UTF-8 bytes; hex.decode(text), base64.decode(text) and base64url.decode(text) decode wire encodings without a lossy string conversion. The decoders also accept bytes that hold UTF-8 encoded text. Use hex.encode(raw), base64.encode(raw) or base64url.encode(raw) for output (standard padded Base64 or unpadded URL-safe Base64 respectively). Do not convert keys, shared secrets or decrypted binary data with string(raw).
| Expression call | Result |
|---|---|
crypto.ecPublicKey(curve, private) | Public-key bytes. |
crypto.ecdh(curve, private, peerPublic) | Shared-secret bytes. |
crypto.ecdsaSign(curve, private, message [, format]) | Signature bytes; default p1363. |
crypto.ecdsaVerify(curve, public, message, signature [, format]) | Boolean signature check. |
crypto.aesGcmEncrypt(key, nonce, plaintext [, aad]) | Sealed ciphertext/tag bytes; default AAD is empty bytes. |
crypto.aesGcmDecrypt(key, nonce, sealed [, aad]) | Authenticated plaintext bytes; default AAD is empty bytes. |
crypto.hkdfSha256(ikm, salt, info, length) | Derived bytes. |
crypto.pbkdf2Sha256(password, salt, iterations, length) | Derived bytes. |
crypto.ed25519PublicKey(seed) | Public-key bytes. |
crypto.ed25519Sign(seed, message) | Signature bytes. |
crypto.ed25519Verify(public, message, signature) | Boolean signature check. |
crypto.randomBytes(length) | Random bytes. |
crypto.constantTimeEqual(a, b) | Boolean comparison of bytes. |
crypto.sha384(message), crypto.sha512(message) | Lowercase hex strings, matching legacy crypto.sha256, not raw digests. |
crypto.hmacSha384(key, message), crypto.hmacSha512(key, message) | Raw HMAC bytes; the key comes first. |
Complete advanced rules¶
Load the complete cryptographic-authentication scaffold for two equivalent rules: a Liquid Http validator and a YAML Betterleaks expression program. Both associate a nearby, invisible client-ID component, generate an independent ephemeral X25519 exchange key, derive an AES-256 key with HKDF, encrypt a read-only identity request, and sign the full envelope with the candidate P-256 key. The file specifies the canonical AAD/signing bytes and response contract. Its published RFC test keys are nonproduction; even the illustrative peer pin has a publicly known private counterpart.
kingfisher rules check --rules-path crates/kingfisher-scanner/examples/rules/cryptographic-auth.yml --load-builtins=false --no-update-check
This check is offline: it validates loading/detection examples, not a real provider or successful live authentication. The literal https://crypto.example.invalid/v1/verify endpoint is deliberately nonfunctional. Before live use, replace the fixed origin, trusted peer pin, wire format and success contract with the provider's reviewed protocol; do not capture hosts or peer keys from untrusted source. The example has no revocation action.
Liquid assignments are local to a template: generating a nonce in a header does not make it available to the body. Keep coupled values in one template, as in the scaffold. Crypto templates are parsed but not rendered during offline input preparation, so preparation does not generate randomness or repeat expensive operations. Only unambiguous external requirements are diagnosed there; execution still checks inputs in the branches actually taken. Http validation remains a single request; HttpMultiStep is a revocation type, not a new validation schema. Expression programs can use existing HTTP calls when a reviewed protocol requires a challenge before its proof.
A header applying a new cryptographic filter aborts the request on parsing, rendering, or HTTP header-conversion failure, and validation is reported as unavailable rather than inactive. A filter name in plain text, a string literal, or a Liquid comment/raw block does not enable this policy. Legacy HTTP header errors (including existing hash/HMAC filters) still omit that header without aborting, preserving rules from 2.19.1 and earlier. Require the provider to reject missing authentication, and never accept an unauthenticated landing page as proof.
Cryptographic validation safety¶
- Pin the peer key and HTTPS origin in trusted configuration; keep TLS verification enabled. Never let a finding select where credentials or proofs are sent.
- Feed raw ECDH output through HKDF with the provider's salt/info. Keep exchange keys separate from signing keys unless the protocol explicitly requires reuse.
- Never reuse an AES-GCM nonce with the same key. Generate fresh ephemeral keys, salt and nonces per request; random nonces still require collision/volume limits for long-lived keys. Authenticate protocol context with AAD and enforce replay protection according to the provider's protocol.
- A local signature check, successful decryption, HTTP 200 or parseable JSON alone does not prove a credential is active. Require the provider's authoritative current-status signal and bind it to the expected identity/request. Liquid
WordMatchis a substring check, not a structural JSON assertion: the scaffold assumes its exact canonical success-body contract; prefer expression JSON field checks for more complex responses. - Keep KDF costs within the bounds above, and choose reviewed fixed costs instead of accepting attacker-selected iterations or output sizes.
- Malformed keys/encodings, unsupported curves/formats and authentication failures must fail closed, never become valid results or partial plaintext. Do not catch cryptographic errors and continue with an empty/default secret.
- The shared primitives and Kingfisher validation diagnostics omit cryptographic inputs. Applications rendering raw Liquid templates must not log or return full engine errors: Liquid may attach runtime inputs or source expressions outside the filter itself. Map parser/render failures to a static, safe error instead. Avoid logging keys, shared secrets, plaintext, raw provider bodies or detailed failure causes; do not expose a decryption/signature oracle. Leave
report_responseoff. - Keep validation read-only. Add revocation only for an explicitly supported, narrowly scoped provider action with reliable success semantics and separate operator authorization; these helpers do not enable revocation automatically.
3. Templating with Liquid¶
Kingfisher leverages the Liquid template engine for dynamic parts of HTTP request bodies, headers, query parameters, and multipart payloads. The engine supports both built-in and custom filters to manipulate the captured secret (TOKEN) or other named captures ({{ NAME }}).
Using Liquid Filters in Validation and Revocation¶
- Capture Injection: The unnamed capture from your regex becomes {{ TOKEN }}. Named captures are made available as uppercase variables (e.g. {{ RDMVAL }}).
- Filter Pipeline: You can chain filters using the pipe (|) syntax:
Built-in & Custom Liquid Filters¶
Common filters are listed below; ECDH, ECDSA, AES-GCM, KDF, Ed25519 and binary randomness/comparison filters are covered in the cryptographic reference.
| Filter | Parameters | Description | Example |
|---|---|---|---|
b64enc | – | Base64-encodes the input using the standard alphabet. | {{ TOKEN \| b64enc }} |
b64url_enc | – | URL-safe Base64 (no padding). Useful for JWT headers & payloads. | {{ TOKEN \| b64url_enc }} |
b64dec | – | Decodes a Base64 string. | {{ "aGVsbG8=" \| b64dec }} |
b64url_dec | – | Decodes a URL-safe Base64 string (with or without padding). | {{ "Kys_Pw" \| b64url_dec }} |
sha256 | – | Computes the SHA-256 hex digest of the input. | {{ TOKEN \| sha256 }} |
sha384, sha512 | – | SHA-384/SHA-512 lowercase hex digest of text input. | {{ TOKEN \| sha512 }} |
bip39_valid | – | Returns true only for a checksum-valid English BIP-39 mnemonic; the temporary normalized phrase is wiped on drop. | {{ MNEMONIC \| bip39_valid }} |
luhn_valid | – | Returns a boolean Luhn checksum result for at least two ASCII digits; ignores ASCII spaces and hyphens. No card issuer, length or account-existence check. | {{ MATCH \| luhn_valid }} |
iban_valid | – | Returns a boolean for generic IBAN structure (5–34 ASCII alphanumeric characters, two letters then two digits) and MOD-97 checksum; ignores ASCII spaces and case. No country registry, country-specific length or account-existence check. | {{ MATCH \| iban_valid }} |
crc32 | – | Computes the CRC32 checksum of the input and returns a decimal value. | {{ TOKEN \| crc32 }} |
crc32_dec | digits (integer, optional) | Computes the CRC32 checksum and returns the last digits decimal characters (zero-padded). Defaults to the full value when omitted. | {{ TOKEN \| crc32_dec: 6 }} |
crc32_hex | digits (integer, optional) | Computes the CRC32 checksum and returns the last digits hexadecimal characters (zero-padded). Defaults to the full value when omitted. | {{ TOKEN \| crc32_hex: 8 }} |
crc32_le_b64 | len (integer, optional) | Computes the CRC32 checksum, encodes the little-endian bytes using Base64, and optionally truncates to the first len characters. | {{ TOKEN \| crc32_le_b64: 6 }} |
hmac_sha1 | key (string) | Computes HMAC-SHA1 over the input, returns Base64-encoded result. | {{ TOKEN \| hmac_sha1: "secret-key" }} |
hmac_sha256 | key (string) | Computes HMAC-SHA256 over the input, returns Base64-encoded result. | {{ TOKEN \| hmac_sha256: "secret-key" }} |
hmac_sha384 | key (string) | Computes HMAC-SHA384 over the input, returns Base64-encoded result. | {{ TOKEN \| hmac_sha384: "secret-key" }} |
hmac_sha384_hex | key (string) | Computes HMAC-SHA384 over the input, returns lowercase hexadecimal output. | {{ TOKEN \| hmac_sha384_hex: "secret-key" }} |
hmac_sha512 | key (text string) | HMAC-SHA512 over text input; text key, standard Base64 output. | {{ TOKEN \| hmac_sha512: "secret-key" }} |
hmac_sha256_b64key | key (string, base64-encoded) | Decodes the key from Base64 to raw bytes, then computes HMAC-SHA256. Returns Base64. Use for Azure SAS and other protocols where the signing key is base64-encoded. | {{ to_sign \| hmac_sha256_b64key: TOKEN }} |
random_string | len (integer, optional) | Generates a cryptographically-secure random alphanumeric string of the specified length (default: 32). | {{ "" \| random_string: 16 }} |
prefix | len (integer, optional) | Returns the first len characters from the string (default: full). | {{ TOKEN \| prefix: 6 }} |
suffix | len (integer, optional) | Returns the last len characters from the string (default: full). | {{ TOKEN \| suffix: 6 }} |
base62 | width (integer, optional) | Encodes the input number as Base62, left-padding with zeros as needed. | {{ TOKEN \| crc32 \| base62: 6 }} |
url_encode | – | Percent-encodes the input according to RFC 3986. | {{ TOKEN \| url_encode }} |
json_escape | – | Escapes special characters so a string can be safely injected into JSON contexts. | {{ TOKEN \| json_escape }} |
unix_timestamp | – | Returns the current Unix epoch time in seconds (UTC). | {{ "" \| unix_timestamp }} |
unix_timestamp_ms | – | Returns the current Unix epoch time in milliseconds (UTC). | {{ "" \| unix_timestamp_ms }} |
iso_timestamp | – | Returns the current UTC timestamp in full ISO-8601 format (may include fractional seconds). | {{ "" \| iso_timestamp }} |
iso_timestamp_no_frac | – | Current ISO-8601 timestamp (UTC) without fractional seconds. | {{ "" \| iso_timestamp_no_frac }} |
rfc1123_date | – | Returns the current RFC-1123 timestamp in GMT. | {{ "" \| rfc1123_date }} |
uuid | – | Generates a random UUIDv4 string. | {{ "" \| uuid }} |
jwt_header | – | Builds a minimal JWT header JSON ({"typ":"JWT","alg":…}) and Base64URL-encodes it. | {{ "HS256" \| jwt_header }} |
rsa_sha256 | key (string, PEM) | Signs the input with RSA PKCS#1 v1.5 and SHA-256 (RS256); returns unpadded Base64URL. Accepts unencrypted PKCS#1/PKCS#8 RSA private keys. | {{ signing_input \| rsa_sha256: TOKEN }} |
jwt_sign | key (string, PEM) | Signs a JSON claims object as a complete RS256 JWT. Accepts unencrypted PKCS#1/PKCS#8 RSA private keys; issuer and timestamps are explicit claims. | {{ payload \| jwt_sign: TOKEN }} |
replace | from (string), to (string) | Replaces every occurrence of from with to in the input string. | {{ "hello world" \| replace: "world", "mars" }} |
newline | – | Returns a single newline character (\n). Useful inside YAML block scalars where a literal newline would break indentation. | {{ "" \| newline }} |
base36 | width (integer, optional) | Encodes the input number as Base36, left-padding with zeros as needed. | {{ TOKEN \| crc32 \| base36: 6 }} |
Chaining & Composition: Filters can be stacked; e.g.:
Runtime Values: Filters like unix_timestamp and uuid are evaluated at runtime, enabling nonces, timestamps, and unique IDs in your requests.
Stable Request Values: HTTP and gRPC validation requests also expose stable per-request template variables. Use these when the same generated value must appear in multiple places within one request. Currently: - REQUEST_RFC1123_DATE - REQUEST_UNIX_MILLIS
Signing RS256 JWTs¶
Use jwt_sign to sign a JSON claims object and produce the complete JWT in one filter. Pass the complete PEM text as the signing key; invalid, encrypted, and non-RSA keys produce a template error. The existing jwt_header, b64url_enc, and rsa_sha256 filters remain available for custom headers and signing inputs.
For a GitHub App custom rule, capture the PEM as TOKEN and associate a nearby numeric APP_ID using depends_on_rule. This header creates a short-lived JWT:
Authorization: >-
{%- assign now = "" | unix_timestamp -%}
{%- assign iat = now | minus: 60 -%}
{%- assign exp = now | plus: 540 -%}
{%- capture payload -%}{"iss":{{ APP_ID | json_escape }},"iat":{{ iat }},"exp":{{ exp }}}{%- endcapture -%}
Bearer {{ payload | jwt_sign: TOKEN }}
Use it with HTTP GET https://api.github.com/app, Accept: application/vnd.github+json, and response matchers StatusMatch (status: [200]) and JsonValid. GitHub uses iss to select the App's public key when verifying the signature; see its JWT authentication guide. This is a custom-rule pattern; built-in private-key detection does not perform this check.
How depends_on_rule Works¶
- Dependency Declaration:
In your YAML rule definition, you add adepends_on_rulesection. Here you specify: - rule_id: The identifier of the rule whose output is required.
-
variable: The name (typically in uppercase) that will be used to reference the captured value from the dependency rule.
-
Chaining Captures:
After matching a blob, Kingfisher resolves each dependency against matches in that same blob. One distinct captured value (for example, an access key ID) is made available to the dependent rule. Repeated occurrences of the same value count as one candidate. -
Using the Captured Value:
This captured value can then be used during the validation phase. For instance, if you have a rule for an Algolia Admin API Key that depends on an Algolia Application ID (captured asAPPID), the validation logic can incorporate theAPPIDvalue to confirm that the secret matches the expected pattern or format for that specific account. -
Detection vs validation:
depends_on_rulesupplies capture chaining and validation context. A required dependency withwithinalso gates detection, as described below. Dependencies do not require parser verification.
Dependency windows and ambiguous pairs¶
within limits candidates using full regex-match spans in the same blob. Line amounts include the primary line: 2L allows one line before and one after a single-line primary match; it is not a radius of two lines.
| Window | Candidate start may appear |
|---|---|
1L | On a line covered by the primary match |
2L | Up to one line before or after the primary match |
3L | Up to two lines before or after |
+2L | On the primary line(s) or the next line |
-2L | On the primary line(s) or the preceding line |
8C | From 8 bytes before the primary start to less than 8 bytes after its end |
C measures byte offsets, not Unicode characters. Directions also apply to C. Comma-separated limits such as 2L,20C combine line and column constraints. 0 or an empty window allows the whole blob.
A required dependency with within and no candidate removes the primary finding. Without within, a missing required dependency retains the finding and skips validation with status 428. optional: true permits an absent dependency.
By default, multiple distinct values in the eligible window retain the finding but skip validation with status 428 and an ambiguous dependency explanation. Kingfisher does not send a credential to a guessed endpoint. Narrow the window or use direct validation with explicit variables to resolve the association. Comment and README matches can participate; dependency matching does not interpret imports or exclude comments. A lone comment candidate is therefore still eligible.
Opt-in candidate verification¶
A dependency that supplies a credential component can opt into bounded try-and-verify pairing:
depends_on_rule:
- rule_id: custom.service.secret
variable: CLIENT_SECRET
within: "5L"
verify_candidates: true
Built-in opt-ins cover AWS access keys and session tokens, BrowserStack, ClickHouse Cloud, MongoDB Atlas service accounts, PlanetScale, Razorpay, and Wiz. AWS session tokens may try both access-key IDs and secrets within the same total combination budget.
Private YAML rules can enable it for typed AWS validation or Http validation with a literal, fixed HTTP(S) URL, no Host header override, and no multipart uploads. Supported Betterleaks expressions may call aws.validate, or http.get and http.post with a provably fixed HTTP(S) origin and literal header names without a Host override. URLs may concatenate dynamic values after a literal prefix containing the complete origin and a slash; dynamic hosts and indirect URL variables remain unsupported. Pure helper calls are limited to validate.unknown, bytes, base64.encode, and strings.urlQueryEscape. HTTP validation disables redirects for any rule with a verify_candidates dependency, including findings with an unambiguous component. This keeps redirect policy consistent when ordinary validation and candidate searches share cached results. Discovered endpoint dependencies and unsupported validators retain strict ambiguity handling, even if opted in. Every ambiguous dependency must be eligible before a search starts. Variables or helper-rule IDs naming a URL, URI, host, domain, endpoint, address, port, or server are excluded from candidate verification even when opted in. Typed AWS validation additionally accepts only AKID and AWS_SECRET_ACCESS_KEY, the dependency variables that it consumes.
Candidates remain restricted to the dependency window and are deduplicated by value. Matching assignment-name prefixes rank first (for example, kms_aws_key / kms_aws_secret or production_client_id / production_client_secret), then shared bracketed-object or INI-section context, then byte distance. These are ordering hints, not proof of association. Failed name matches fall back to other candidates. Multiple ambiguous components are combined in ranked order without materializing their full Cartesian product.
A search tries at most 16 distinct combinations, with a total time budget of 30 seconds or --validation-timeout, whichever is shorter (10 seconds by default). At most four searches run concurrently across repositories, one combination at a time per search. Existing request retries and provider rate limits still apply; retries can make more than one request per combination. The time budget includes waiting for a search slot. Each complete credential combination uses the normal validation cache. A successful secret remains available for other access-key IDs.
Only authoritative successful validation selects a pair and clears its ambiguity. Exhausted budgets and searches with no successful combination remain unresolved (status 428); timeouts, throttling, and unavailable verification remain inconclusive. They do not establish that the primary credential is inactive. --no-validate leaves multi-candidate findings ambiguous, even when assignment names match. Unselected candidate values are internal and never included in reports or generated validation commands; the selected values obey --redact.
Association happens before deduplication. Identical secrets with different resolved contexts remain separate findings, so a bare definition cannot hide a paired occurrence. Context is not inferred across files. JSON/JSONL findings expose dependent_captures (including BASEURL when captured) and ambiguous_dependencies (variable-to-candidate-count). Resolved values are omitted with --redact because components can themselves contain secrets.
For self-hosted validation, see provider endpoint overrides. These global overrides apply to scanning as well as direct validation. CredentialUri HTTP validation honors --tls-mode off; scan-time lax requires the rule's tls_mode: lax opt-in, just like HTTP rules. Direct validate applies lax globally.
Use depends_on_rule to require one rule before another runs:¶
depends_on_rule:
- rule_id: custom.algolia.app-id # helper rule ID
variable: APPID # captured as {{ APPID }}
- Capture flow: First rule captures
APPID→ second rule injects{{ APPID }}into the validation HTTP request - Visible control: set
visible: falseon the supporting rule so it doesn’t clutter your report for non-secret matches - Primary secret rule: leave the secret rule visible unless it is also only a helper; helper rules should usually be the ones marked
visible: false
Algolia Example¶
Consider this example rule for an Algolia Application ID and Admin Key combination. To validate that this is an active credential, both must be matched:
rules:
- name: Algolia Admin API Key
id: custom.algolia.admin-key
pattern: |
(?xi)
algolia
(?:.|[\n\r]){0,32}?
\b
(
[a-z0-9]{32}
)
\b
min_entropy: 3.5
confidence: medium
examples:
- algolia_api_key = "ij1mut5oe606wlrf5z4u8u31264z3gag"
validation:
type: Http
content:
request:
headers:
X-Algolia-API-Key: '{{ TOKEN }}'
X-Algolia-Application-Id: '{{ APPID }}'
method: GET
response_matcher:
- report_response: true
- status:
- 200
type: StatusMatch
url: https://{{ APPID }}-dsn.algolia.net/1/keys
depends_on_rule:
- rule_id: "custom.algolia.app-id"
variable: APPID
- name: Algolia Application ID
id: custom.algolia.app-id
pattern: |
(?xi)
algolia
(?:.|[\n\r]){0,16}?
\b
(
[A-Z0-9]{10}
)
\b
min_entropy: 3.5
visible: false
confidence: medium
examples:
- algolia_app_id = "WRB8YLFW7Y"
How It Works:¶
- Algolia Application ID Rule (
custom.algolia.app-id):
This rule scans for an Algolia Application ID—a 10-character alphanumeric string. It is marked with visible: false so that even if it matches, the finding is not directly reported. Its primary role is to provide a supporting value for other rules rather than to be flagged as a secret by itself.
-
Algolia Admin API Key Rule (
custom.algolia.admin-key): This rule detects the Algolia Admin API Key using a regex pattern. It includes a depends_on_rule property that specifies a dependency on the Algolia Application ID rule. -
The dependency declares that the rule requires the output of the Algolia Application ID rule, and the captured value is assigned to the variable APPID.
- In the validation section, this captured
APPIDis used dynamically in the HTTP request (for example, in the headerX-Algolia-Application-Idand in the URL).
The dependency mechanism (depends_on_rule) ensures that:
- Non-secret data (like an application ID) is captured without cluttering the scan report (thanks to visible: false).
- The secret (the API key) is validated in context, with the necessary supporting information automatically injected.
- Rules remain modular and extensible; you can update the dependent rule or its pattern independently, and the change will automatically be reflected where the value is used.
The visible: false Property¶
The visible: false property tells Kingfisher to hide the finding from the final scan report. This is particularly useful for rules that capture data not meant to be reported as a secret, but rather to serve as supporting context for another rule.
For example, a rule might match a username, an email address, an AWS Access Key ID, or an Application ID. While these pieces of information are captured during scanning, they are not secrets on their own. Instead, they are used by other rules—via the depends_on_rule mechanism—to validate an associated secret. By marking such rules as visible: false, you prevent these non-secret findings from cluttering your report, yet their values remain available for dependent rules.
visible: false helps keep the scan output focused on actual secrets while still capturing important contextual data needed for comprehensive validation.
Regex Authoring¶
Kingfisher uses Hyperscan/Vectorscan-compatible regular expressions. Write patterns for the credential format documented by the provider, then add only enough surrounding context to avoid generic matches.
- Start multi-line patterns with
(?x)for free-spacing mode. Use(?xi)only when the entire expression is intentionally case-insensitive; otherwise scope it to contextual text, for example(?i:api[_-]?key), and keep the token format case-sensitive. - Prefer POSIX character classes for token alphabets: use
[[:alnum:]]for letters and digits, and[[:xdigit:]]for hexadecimal values. Add only documented extra characters, such as[[:alnum:]_=-]; do not use an alphanumeric class when the provider specifies a narrower format. - With
(?i)or(?xi), character ranges are already case-insensitive. Do not write redundant ranges such as[a-zA-Z]or[a-fA-F]; use a semantic POSIX class where applicable, or a single range such as[A-Z]when the token format genuinely requires letters only. - Put the secret in one unnamed capture, which becomes
{{ TOKEN }}. Use(?:...)for structural groups, and add named captures only when validation or a checksum needs their values. - Hyperscan/Vectorscan does not support lookaround. Use bounded context,
min_entropy, andpattern_requirementsto reduce false positives instead of lookahead or lookbehind. - Bound flexible separators and cross-line context (for example,
(?:.|[\n\r]){0,32}?) so a rule cannot consume an unbounded region of a file. Prefer a provider prefix, field name, or assignment delimiter over a broad keyword alone. - Include positive examples for every rule. When a nearby format is easy to confuse with a real credential, test it against a fixture or a targeted scan. Check an individual file with
kingfisher rules checkbefore running the rule-crate tests.
POSIX Character Classes¶
Hyperscan/Vectorscan supports POSIX character classes inside bracket expressions, written as [[:name:]]. These are the classes relevant to rule authoring:
| Class | Matches | ASCII equivalent |
|---|---|---|
[:alnum:] | Letters and digits | [a-zA-Z0-9] |
[:alpha:] | Letters only | [a-zA-Z] |
[:digit:] | Digits | [0-9] |
[:lower:] | Lowercase letters only | [a-z] |
[:upper:] | Uppercase letters only | [A-Z] |
[:xdigit:] | Hexadecimal digits | [0-9A-Fa-f] |
[:blank:] | Space and tab | [ \t] |
[:space:] | Whitespace | [ \t\r\n\v\f] |
[:punct:] | Punctuation characters | [\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E] |
[:graph:] | Visible characters (no space) | [\x21-\x7E] |
[:print:] | Printable characters | [\x20-\x7E] |
[:cntrl:] | Control characters | [\x00-\x1F\x7F] |
Notes:
[:alnum:]is the workhorse for token alphabets; it covers both letter cases and digits.[:lower:]and[:upper:]match a single case by default. Under(?i)/(?xi)they become case-insensitive, so[:lower:]will also match uppercase letters and vice versa.[:digit:]matches only0-9; it does not include letters. For letters and digits use[:alnum:]; for lowercase letters and digits combine them as[[:lower:][:digit:]].[:xdigit:]matches0-9,a-f, andA-Fregardless of the(?i)flag.- Classes can be combined inside one bracket expression, for example
[[:alnum:]_=-]adds underscore, equals, and hyphen to the alphanumeric set.
Checksum Intelligence¶
Modern API tokens increasingly include built-in checksums, short internal digests that make each credential self-verifiable. For background, see GitHub's write-up on newer token formats and why checksums reduce false positives.
The Kingfisher rule format supports checksum-aware matching, enabling offline structural verification of credentials without calling third-party APIs.
By validating each token's internal checksum, when supported by the token format, Kingfisher filters structurally invalid or fake tokens before validation runs.
Why this matters
- Offline verification: no API call is required.
- Industry-aligned: compatible with prefix and checksum token designs such as modern PATs.
- Lower false positives: invalid tokens are filtered out by structure alone.
The checksum block below documents the Liquid templating and capture requirements for implementing this behavior in a custom rule.
Character Requirements¶
The pattern_requirements field allows you to specify data type requirements for matched secrets. This is particularly useful when:
- Your regex pattern must be permissive (due to Vectorscan limitations)
- You want to enforce password complexity requirements
- You need to filter out low-quality matches that lack certain character types
Kingfisher's regex engine (Hyperscan) does not support lookahead assertions like (?=.*\d) to require specific character types. Instead, use the pattern_requirements field to filter matches post-detection.
Requirements validate the selected secret when there is one unnamed capture (or no captures). Named captures or multiple capture groups select the full regex match instead. MATCH is this selected requirement input; FULL_MATCH is always capture zero. Named checksum captures are available under their original names and uppercase aliases. Failed or unrenderable checksums discard the candidate; skip_if_missing only allows missing context/captures, not template errors or mismatches.
Available Requirements¶
pattern_requirements:
min_digits: 1 # Require at least 1 digit (0-9)
min_uppercase: 1 # Require at least 1 uppercase letter (A-Z)
min_lowercase: 1 # Require at least 1 lowercase letter (a-z)
min_special_chars: 1 # Require at least 1 special character
special_chars: "!@#$%^&*" # Optional: define which characters are "special"
ignore_if_contains: # Optional: reject matches containing any of these (case-insensitive)
- test
- demo
checksum: # Optional: compare rendered values to drop mismatched formats
actual:
template: "{{ MATCH | suffix: 6 }}" # Liquid template for the observed checksum
requires_capture: checksum # (optional) skip unless this capture is present
expected: "{{ BODY | crc32 | base62: 6 }}" # Liquid template to render the expected checksum
skip_if_missing: true # (optional) treat missing captures as legacy tokens
All fields are optional. If special_chars is not specified, the default set includes: !@#$%^&*()_+-=[]{}|;:'",.<>?/\~`
ignore_if_contains performs a case-insensitive substring check. If any entry (after trimming whitespace) appears within the match, the match is discarded. This is helpful for dropping known dummy tokens such as "test" or "demo" that otherwise satisfy the regex.
The optional checksum block renders Liquid templates against the match to determine whether the captured checksum matches your expectation. Both templates gain access to {{ MATCH }}, {{ FULL_MATCH }}, and every named capture in two forms: the original capture name and its uppercase alias (e.g. {{ body }} and {{ BODY }}). Use helper filters like suffix, crc32, and base62 to mirror provider-specific checksum pipelines. If a required capture is missing or the rendered values differ, Kingfisher skips the finding—logging the reason, including checksum lengths, at the DEBUG level. Set skip_if_missing to true to treat absent captures as legacy matches.
When any of these filters remove a match it is logged at the DEBUG level so you can see exactly why the skip occurred. If you need to keep every match even when one of these substrings appears, pass --no-ignore-if-contains to kingfisher scan. The flag disables only substring exclusions; character minimums and checksums still run.
Example: Luhn and IBAN checksums¶
Use a boolean filter result as the observed checksum and compare it with the quoted string 'true'. These are offline format checks. Add organization-specific context and length constraints to the regex.
rules:
- name: Example payment card
id: acme.structured.card
pattern: '\bcard[=: ]+([0-9](?:[ -]?[0-9]){12,18})\b'
confidence: medium
pattern_requirements:
checksum:
actual:
template: '{{ MATCH | luhn_valid }}'
expected: 'true'
For IBANs, use iban_valid in the same block. It performs the MOD-97 check described by Swift with generic IBAN structure, not country-specific account validation. Both filters reject other punctuation and non-ASCII digits; IBAN also rejects hyphens. See the complete custom rule fixture and runnable Python example.
Are requires_capture and skip_if_missing equivalent?¶
requires_capture - Optional field that names a specific regex capture that must be present before the checksum templates are evaluated. - In the engine, Kingfisher checks whether that capture exists in the match context. If it’s missing, the behavior falls back to whatever skip_if_missing dictates (fail or treat as a legacy match).
skip_if_missing - Boolean switch that controls what happens when Kingfisher can’t render the checksum—because there’s no match context or a required capture is absent. - true: silently skip (pass) the match so legacy, non-checksum tokens are still accepted. - false: treat the situation as a validation failure.
In short, requires_capture identifies which capture must exist, while skip_if_missing determines whether missing data is a hard failure or an allowed legacy case.
Example: Secure API Key¶
rules:
- name: Secure API Key
id: custom.secure_api.1
pattern: |
(?xi)
api[_-]?key
(?:.|[\n\r]){0,32}?
\b
([[:alnum:]!@#$%^&*]{20,})
\b
min_entropy: 4.0
confidence: high
pattern_requirements:
min_digits: 1 # Must contain at least 1 digit
min_uppercase: 1 # Must contain at least 1 uppercase letter
min_lowercase: 1 # Must contain at least 1 lowercase letter
min_special_chars: 1 # Must contain at least 1 special character
ignore_if_contains:
- test
examples:
- api_key = "MyS3cur3K3y!2024"
- 'api-key: "Abc123!@#Token"'
In this example: - The regex pattern is permissive: [[:alnum:]!@#$%^&*]{20,} matches any combination of those characters - The pattern_requirements filters out matches that don't have at least one of each required type - A match like "abcdefghijklmnopqrst" would be rejected (no uppercase, no digit, no special) - A match like "Abc123!SecureToken" would be accepted (has all required types) - A match like "Test123!SecureToken" would be rejected because it contains the ignore_if_contains term test
Example: Excluding Dummy Values¶
rules:
- name: Token without placeholders
id: custom.token.2
pattern: |-
(?i)token[:=]\s*([[:alnum:]]{12,})
pattern_requirements:
ignore_if_contains:
- placeholder
- sample
examples:
- token: "REALVALUE1234"
Example: Custom Special Characters¶
rules:
- name: Token with Custom Special Chars
id: custom.token.1
pattern: |
(?xi)
token
(?:.|[\n\r]){0,16}?
\b([[:alnum:]$%^]{16,})\b
min_entropy: 3.5
confidence: medium
pattern_requirements:
min_special_chars: 2
special_chars: "$%^" # Only these characters count as "special"
examples:
- token = "abc$%defgh123456"
How It Works¶
- Vectorscan regex matches a pattern in the input
- Entropy check filters low-complexity matches (if
min_entropyis set) - Character requirements check filters matches that don't meet the criteria
- Validation checks verify the secret is live (if
validationis configured)
Matches that fail the character requirements check are silently dropped with a debug log message.
Writing Custom Rules¶
When writing custom rules, consider the following best practices:
- Multi-line Regex: Write your regex patterns over multiple lines for clarity. Use the
(?x)flag to enable free-spacing mode. - Optimize for Performance: Structure your regex to minimize backtracking. Use non-capturing groups where possible and keep the pattern as concise as possible.
- Validation Integration: Define a
validationsection if you want to verify the detected secret. PreferHttporGrpc; use an existing typed validator when the rule matches a supported validator family; useRawonly for rare provider-specific exception paths. You can use Liquid templating to insert dynamic values where supported. Use the unnamed capture asTOKENand any named captures in uppercase. - Revocation Integration: Define a
revocationsection if you want to revoke a detected secret. It uses the same HTTP request format and template variables asvalidation. - Test with Examples: Always include examples that should match, and run
kingfisher rules checkfor the changed rule file.
Examples¶
Below are some examples to guide you in writing custom rules
Anthropic API Key¶
rules:
- name: Anthropic API Key
id: custom.anthropic.api-key
pattern: |
(?xi)
\b
(
sk-ant-api
\d{2,4}
-
[\w\-]{93}
AA
)
\b
min_entropy: 3.3
confidence: medium
examples:
- sk-ant-api668-Clm512odot9WDD7itfUU9R880nefA1EtYZDbpE-C9b0XQEWpqFKf9DQUo03vOfXl16oSmyar1CLF1SzV3YzpZJ6bahcpLAA
references:
- https://docs.anthropic.com/claude/reference/authentication
validation:
type: Http
content:
request:
body: |
{
"model": "claude-3-haiku-20240307",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "respond only with 'success'"}
]
}
headers:
Content-Type: application/json
anthropic-version: "2023-06-01"
x-api-key: '{{ TOKEN }}'
method: POST
response_matcher:
- report_response: true
- status:
- 200
type: StatusMatch
- type: WordMatch
words:
- '"type":"message"'
- "credit balance is too low"
url: https://api.anthropic.com/v1/messages
FileIO Secret Key¶
rules:
- name: FileIO Secret Key
id: custom.fileio.api-key
pattern: |
(?xi)
\b
fileio
(?:.|[\n\r]){0,32}?
(?:SECRET|PRIVATE|ACCESS|KEY|TOKEN)
(?:.|[\n\r]){0,16}?
\b
(
[A-Z0-9]{16}
(?:\.[A-Z0-9]{7}){2}
\.[A-Z0-9]{8}
)
\b
min_entropy: 3.3
confidence: medium
examples:
- fileio SECRETKEY = Z9Y8X7W6V5U4T3S2R1Q0.P9O8N7M6L5K4J3H2G1F
- fileio.PRIVATE.TOKEN = F0E1D2C3B4A596877869.5E4D3C2B1A0Z9Y8X7W6V
- fileio_key = M8N6B4V2C0X9Z7L5K3J1.H2G4F6D8S0A9P7O5I3U1
validation:
type: Http
content:
request:
method: GET
url: https://file.io/api/v2/account
headers:
Authorization: "Bearer {{ TOKEN }}"
response_matcher:
- report_response: true
- type: StatusMatch
status: [200]
- type: HeaderMatch
header: content-type
expected: ["application/json"]
- type: JsonValid
Advanced Example¶
This advanced example uses the liquid-rs filters included with Kingfisher to sign requests that validate Alibaba Cloud long-lived and STS temporary credential pairs:
rules:
- name: Alibaba Access Key ID
id: custom.alibabacloud.access-key-id
pattern: |
(?x)
\b
(
LTAI[A-Za-z0-9]{17,21}
)
\b
pattern_requirements:
min_digits: 2
min_uppercase: 1
min_lowercase: 1
min_entropy: 4.0
confidence: medium
visible: false
examples:
- LTAI8x2NiGqfyJGx7eLDhp12
- LTAI5GqyJGhp12ad31L5hpix
- name: Alibaba Access Key Secret
id: custom.alibabacloud.secret-key
pattern: |
(?x)
\b
(?:
(?i:alibaba|alibaba[\s_-]*cloud|aliyun)
|
LTAI[A-Za-z0-9]{17,21}
)
(?:.|[\n\r]){0,80}?
(?i:access[\s_-]*key[\s_-]*secret|access[\s_-]*secret|secret|token|key)
(?:.|[\n\r]){0,16}?
(?:
[=:]
|
["']\s*:\s*["']
)
\s*
["']?
(
[A-Za-z0-9]{30}
)
\b
["']?
min_entropy: 4.2
confidence: medium
examples:
- alibaba_secret = 7jkWdTjKLnSlGddwPR5gBn65PHcZG6
- alibaba-token = aJHKLnSlGddwPR5g7jkWdTBn65PHc5
- AccessKeyId=LTAI8x2NiGqfyJGx7eLDhp12 AccessKeySecret=7jkWdTjKLnSlGddwPR5gBn65PHcZG6
validation:
type: Http
content:
request:
method: GET
url: >
{%- assign nonce = "" | uuid | upcase -%}
{%- assign raw_timestamp = "" | iso_timestamp_no_frac -%}
{%- assign timestamp = raw_timestamp | replace: ":", "%3A" -%}
{%- capture params -%}
AccessKeyId={{ AKID | url_encode }}&Action=GetCallerIdentity&Format=JSON&SignatureMethod=HMAC-SHA1&SignatureNonce={{ nonce }}&SignatureVersion=1.0&Timestamp={{ timestamp }}&Version=2015-04-01
{%- endcapture -%}
{%- assign encoded_params = params | replace: "+", "%20" | replace: "*", "%2A" | replace: "%7E", "~" -%}
{%- assign query_string = encoded_params | url_encode | replace: "%2D", "-" | replace: "%2E", "." -%}
{%- assign signature_base_string = "GET&%2F&" | append: query_string -%}
{%- assign token_amp = TOKEN | append: "&" -%}
{%- assign hmacsignature = signature_base_string | hmac_sha1: token_amp | url_encode -%}
https://sts.aliyuncs.com/?{{ params }}&Signature={{ hmacsignature }}
headers:
Accept: application/json
response_matcher:
- report_response: true
- type: StatusMatch
status: [200]
- type: WordMatch
words: ['"Arn"']
depends_on_rule:
- rule_id: custom.alibabacloud.access-key-id
variable: AKID
- name: Alibaba STS Access Key ID
id: custom.alibabacloud.session-access-key-id
pattern: |
(?x)
\b
(
STS\.[A-Za-z0-9]{16,64}
)
\b
min_entropy: 3.0
confidence: medium
visible: false
examples:
- STS.NTKaenSkmLhG4HpM576UV
- STS.FJ6EMcS1JLZgAcBJSTDG1Z4CE
- name: Alibaba STS Security Token
id: custom.alibabacloud.session-secret-key
pattern: |
(?xi)
\b
(?:security[\s_-]*token|sts[\s_-]*token|x[\s_-]*oss[\s_-]*security[\s_-]*token|alibaba[\s_-]*cloud[\s_-]*security[\s_-]*token|aliyun[\s_-]*security[\s_-]*token)
(?:.|[\n\r]){0,16}?
(?:
[=:]
|
["']\s*:\s*["']
)
\s*
["']?
(
CAIS[A-Za-z0-9+/_=-]{20,1024}
)
(?:["'\s,;}&\]]|$)
min_entropy: 4.0
confidence: medium
visible: false
examples:
- securityToken = "CAISuwJ1q6Ft5B2yu9Kiaa5E0VnVJ8q2o3P4r5S6t7U8v9W0xYz"
- ALIBABA_CLOUD_SECURITY_TOKEN=CAIS/gF1q6Ft5B2yfSjIr5eDA9xjJCcl57eKC7A3ThnJA
- name: Alibaba STS Access Key Secret
id: custom.alibabacloud.session-token
pattern: |
(?x)
\b
(?:
(?i:alibaba|alibaba[\s_-]*cloud|aliyun|sts)
|
STS\.[A-Za-z0-9]{16,64}
)
(?:.|[\n\r]){0,120}?
(?i:access[\s_-]*key[\s_-]*secret|access[\s_-]*secret)
(?:.|[\n\r]){0,16}?
(?:
[=:]
|
["']\s*:\s*["']
)
\s*
["']?
(
[A-Za-z0-9]{30,64}
)
\b
["']?
min_entropy: 4.2
confidence: medium
examples:
- STS.NTKaenSkmLhG4HpM576UV AccessKeySecret=wyLTSmsyPGP1ohvvw8xYgB29dlGI8KMiH2pK
- "aliyun sts access_key_secret: 6itECZnhbG2RU6ktTSBSd6JxeLHKPWyBtSS62"
validation:
type: Http
content:
request:
method: GET
url: >
{%- assign nonce = "" | uuid | upcase -%}
{%- assign raw_timestamp = "" | iso_timestamp_no_frac -%}
{%- assign timestamp = raw_timestamp | replace: ":", "%3A" -%}
{%- capture params -%}
AccessKeyId={{ STS_AKID | url_encode }}&Action=GetCallerIdentity&Format=JSON&SecurityToken={{ SECURITY_TOKEN | url_encode }}&SignatureMethod=HMAC-SHA1&SignatureNonce={{ nonce }}&SignatureVersion=1.0&Timestamp={{ timestamp }}&Version=2015-04-01
{%- endcapture -%}
{%- assign encoded_params = params | replace: "+", "%20" | replace: "*", "%2A" | replace: "%7E", "~" -%}
{%- assign query_string = encoded_params | url_encode | replace: "%2D", "-" | replace: "%2E", "." -%}
{%- assign signature_base_string = "GET&%2F&" | append: query_string -%}
{%- assign token_amp = TOKEN | append: "&" -%}
{%- assign hmacsignature = signature_base_string | hmac_sha1: token_amp | url_encode -%}
https://sts.aliyuncs.com/?{{ params }}&Signature={{ hmacsignature }}
headers:
Accept: application/json
response_matcher:
- report_response: true
- type: StatusMatch
status: [200]
- type: WordMatch
words: ['"Arn"']
depends_on_rule:
- rule_id: custom.alibabacloud.session-access-key-id
variable: STS_AKID
- rule_id: custom.alibabacloud.session-secret-key
variable: SECURITY_TOKEN
Provider formats and context requirements¶
Built-in DeepSeek, Kimi/Moonshot, ZAI, and Voyage AI rules use bare: true in the Betterleaks capability overlay to derive medium-confidence patterns without provider assignments. MiniMax already matches bare tokens upstream. Token formats, entropy filters, and validation remain sourced from upstream. Both detection-only and validating scans use these patterns; live validation runs only after detection. Other contextual rules may still require a provider assignment before the token; a trailing comment does not satisfy it.
For extracted credential corpora, preserve provider assignments and required components or use validate with an explicit rule and endpoint. The pinned AWS access-token rule already recognizes ASIA IDs. AWS temporary credentials may require an access key ID, secret access key, and session token; a lone ASIA fragment does not establish a complete validatable credential.
New provider formats and length variants belong in the upstream Betterleaks catalog. Redacted shape masks alone do not establish reliable token boundaries, length ranges, or provider-specific validation behavior. Do not widen shared sk- patterns across providers solely to increase recall: that can send a token to the wrong provider. Use documented formats and synthetic positive/negative fixtures when proposing upstream variants.