Rules

Writing Rules

The xgrep rule format and the rule features it supports.

Writing Rules

xgrep uses the Semgrep YAML rule format:

rules:
  - id: my-rule
    pattern: eval(...)
    message: Avoid using eval()
    severity: WARNING
    languages: [python]

Supported rule features include:

  • pattern, patterns, pattern-either, pattern-not, pattern-inside, pattern-not-inside
  • pattern-regex, pattern-not-regex
  • Metavariables ($VAR, $...ARGS)
  • metavariable-pattern, metavariable-regex, metavariable-comparison
  • focus-metavariable
  • fix (autofix support)
  • Taint analysis (mode: taint with pattern-sources, pattern-sinks, pattern-sanitizers, pattern-propagators) — see Taint analysis
  • Native analyzers (mode: analysis with analyzer:) for checks too context-dependent for patterns — see Analysis mode
  • Supply chain rules (r2c-internal-project-depends-on)
  • options including interfile: true for cross-file analysis
  • min-version / max-version for engine version constraints

For the precise semantics of each operator and metavariable form, see the Syntax reference. For the upstream specification, see the Semgrep rule syntax documentation.

Security metadata

Security rules (metadata.category: security or secrets) carry standardized classification metadata that flows into SARIF and GitLab reports:

metadata:
  category: security
  cwe:
    - 'CWE-918: Server-Side Request Forgery (SSRF)'
  owasp:
    - A10:2021 - Server-Side Request Forgery (SSRF)
  references:
    - https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html

Conventions:

  • cwe"CWE-N: Name" using the exact name from the MITRE CWE catalog. Use concrete weakness IDs, never category or view IDs (e.g. CWE-16, CWE-275, CWE-730 are categories, not weaknesses).
  • owasp — the OWASP Top 10 2021 category, written A0X:2021 - Category Name. Derive it from the CWE via the official Top 10:2021 CWE mapping (each category page lists its mapped CWEs); if the CWE is unmapped, use its nearest mapped ancestor in the CWE hierarchy. CWEs with no applicable 2021 category (denial-of-service, memory-safety, integer overflow, race conditions) omit the key — do not force-fit a category.
  • references — curated reading only, from official sources: owasp.org (including cheat sheets), NIST, IETF/RFC, W3C. No vendor or blog links. Do not add links that are derivable from the tags above — CWE definition and OWASP Top 10 category links are generated from the cwe/owasp entries by the output layer (SARIF, GitLab), never hand-written. Most rules therefore need no references at all.

Once you've written a rule, test it.

On this page