Skip to main content
TIPGetting started with rule writing? Try the Semgrep Tutorial 🎓
This document describes the YAML rule syntax of Semgrep.

Schema

Required

All required fields must be present at the top level of a rule immediately under the rules key.
INFOOnly one of the following keys are required: pattern, patterns, pattern-either, pattern-regex

Language extensions and languages key values

The following table includes languages supported by Semgrep, accepted file extensions for test files that accompany the rules, and valid values that Semgrep rules require in the languages key.
INFOTo see the maturity level of each supported language, see the following references:

Optional

The following field is optional, but if used, it must be nested underneath a patterns or pattern-either field. The following fields are optional, but if used, they must be nested underneath a patterns field.

Operators

pattern

The pattern operator looks for code matching its expression. This can be basic expressions like $X == $X or unwanted function calls like hashlib.md5(...).
The preceding pattern matches the following:

patterns

The patterns operator performs a logical AND operation on one or more child patterns. This is useful for chaining multiple patterns together where all patterns must be true.
The preceding pattern matches the following:

patterns operator evaluation strategy

The order in which the child patterns are declared in a patterns operator does not affect the final result. A patterns operator is always evaluated in the same way:
  1. Semgrep evaluates all positive patterns, including pattern-insides, patterns, pattern-regexes, and pattern-eithers. Each range matched by one of these patterns is intersected with the ranges matched by the other operators. The result is a set of positive ranges. The positive ranges carry metavariable bindings. For example, in one range,$X can be bound to the function call foo(), and in another range $X can be bound to the expression a + b.
  2. Semgrep evaluates all negative patterns, including pattern-not-insides, pattern-nots, and pattern-not-regexes. This provides a set of negative ranges which are used to filter the positive ranges. This results in a strict subset of the positive ranges computed in the previous step.
  3. Semgrep evaluates all conditionals, including metavariable-regexes, metavariable-patterns, and metavariable-comparisons. These conditional operators can only examine the metavariables bound in the positive ranges in step 1 and have been filtered through the negative patterns in step 2. Note that metavariables bound by negative patterns are not available here.
  4. Semgrep applies all focus-metavariables by computing the intersection of each positive range with the range of the metavariable on which you want to focus. Again, the only metavariables available to focus on are those bound by positive patterns.

pattern-either

The pattern-either operator performs a logical OR operation on one or more child patterns. This is useful for chaining multiple patterns together where any may be true.
The preceding pattern matches the following:
This rule checks for the use of Python standard library functions hashlib.md5 or hashlib.sha1. Depending on their usage, these hashing functions are considered insecure.

pattern-regex

The pattern-regex operator searches files for substrings matching the given Perl-Compatible Regular Expressions (PCRE) pattern. PCRE is a full-featured regular expression (regex) library that is widely compatible with Perl, as well as with the respective regex libraries of Python, JavaScript, Go, Ruby, and Java. This is useful for migrating existing regular expression code search capability to Semgrep. Patterns are compiled in multiline mode. For example, ^ and $ match at the beginning and end of lines, respectively, in addition to the beginning and end of input.
CAUTIONPCRE2 supports some Unicode character properties, but not some Perl properties. For example, \p{Egyptian_Hieroglyphs} is supported, but \p{InMusicalSymbols} isn’t.

Example: pattern-regex combined with other pattern operators

The preceding pattern matches the following:

Example: pattern-regex used as a standalone, top-level operator

The preceding pattern matches the following:
INFOSingle (') and double (") quotes behave differently in YAML syntax. Single quotes are typically preferred when using backslashes (\) with pattern-regex.
Note that you may bind a section of a regular expression to a metavariable by using named capturing groups. In this case, the name of the capturing group must be a valid metavariable name.
The preceding pattern matches the following:

pattern-not-regex

The pattern-not-regex operator filters results using a PCRE2 regular expression in multiline mode. This is most useful when combined with regular-expression-only rules, providing an easy way to filter findings without having to use negative lookaheads. pattern-not-regex works with regular pattern clauses, too. The syntax for this operator is the same as pattern-regex. This operator filters findings that have any overlap with the supplied regular expression. For example, if you use pattern-regex to detect Foo==1.1.1 and it also detects Foo-Bar==3.0.8 and Bar-Foo==3.0.8, you can use pattern-not-regex to filter the unwanted findings.
The preceding pattern matches the following:

focus-metavariable

The focus-metavariable operator focuses on, or zooms in on, the code region matched by a single metavariable or a list of metavariables. For example, to find all functions’ arguments annotated with the type bad, you may write the following pattern:
This works, but it matches the entire function definition. Sometimes, this is not desirable. If the definition spans hundreds of lines, they are all matched. In particular, if you are using Semgrep AppSec Platform and you have triaged a finding generated by this pattern, the same finding shows up again as new if you make any change to the definition of the function! To specify that you are only interested in the code matched by a particular metavariable, which, in the example, is $ARG, use focus-metavariable.
The preceding pattern matches the following:
Note that focus-metavariable: $ARG is not the same as pattern: $ARG! Using pattern: $ARG finds all the uses of the parameter x, which is not the desired behavior! (Note that pattern: $ARG does not match the formal parameter declaration, because in this context $ARG only matches expressions.)
The preceding pattern matches the following:
In short, focus-metavariable: $X is not a pattern in itself. It does not perform any matching; it only focuses the matching on the code already bound to $X by other patterns. On the other hand, pattern: $X matches $X against your code (and in this context, $X only matches expressions)!

Including multiple focus metavariables using set intersection semantics

Include more focus-metavariable keys with different metavariables under the pattern to match results only for the overlapping region of all the focused code:
The preceding pattern matches the following:
INFOTo make a list of multiple focus metavariables using set union semantics that matches the metavariables regardless of their position in code, see Including multiple focus metavariables using set union semantics documentation.

metavariable-regex

The metavariable-regex operator searches metavariables for a PCRE2 regular expression. This is useful for filtering results based on a metavariable’s value. It requires the metavariable and regex keys and can be combined with other pattern operators.
The preceding pattern matches the following:
Regex matching is left anchored. To allow prefixes, use .* at the beginning of the regex. To match the end of a string, use $. The following example, using the same expression as above but anchored on the right, finds no matches:
INFOInclude quotes in your regular expression when using metavariable-regex to search string literals. For more details, see include-quotes code snippet.

metavariable-pattern

The metavariable-pattern operator matches metavariables with a pattern formula. This is useful for filtering results based on a metavariable’s value. It requires the metavariable key, and precisely one key of pattern, patterns, pattern-either, or pattern-regex. This operator can be nested as well as combined with other operators. For example, the metavariable-pattern can be used to filter out matches that do not match specific criteria:
The preceding pattern matches the following:
INFOIn this case, it is possible to start a patterns AND operation with a pattern-not, because there is an implicit pattern: ... that matches the content of the metavariable.
The metavariable-pattern is also helpful in combination with pattern-either:
The preceding pattern matches the following:
TIPIt is possible to nest metavariable-pattern inside metavariable-pattern!
INFOThe metavariable should be bound to an expression, a statement, or a list of statements, for this test to be meaningful. A metavariable bound to a list of function arguments, a type, or a pattern always evaluates to false.

metavariable-pattern with nested language

If the metavariable’s content is a string, then it is possible to use metavariable-pattern to match this string as code by specifying the target language via the language key. See the following examples of metavariable-pattern:
EXAMPLES OF METAVARIABLE-PATTERN

Example: Match JavaScript code inside HTML

The preceding pattern matches the following:

Example: Filter regex matches

The preceding pattern matches the following:

metavariable-comparison

The metavariable-comparison operator compares metavariables against a basic Python comparison expression. This is useful for filtering results based on a metavariable’s numeric value. The metavariable-comparison operator is a mapping that requires the metavariable and comparison keys. It can be combined with other pattern operators in the following Semgrep Playground example. This matches code such as set_port(80) or set_port(443), but not set_port(8080). Comparison expressions support simple arithmetic as well as composition with Boolean operators to allow for more complex matching. This is particularly useful for checking that metavariables are divisible by particular values, such as enforcing that a specific value is even or odd.
The preceding pattern matches the following:
Building on the previous example, this still matches code such as set_port(80), but it no longer matches set_port(443) or set_port(8080). The comparison key accepts a Python expression using:
  • Boolean, string, integer, and float literals.
  • Boolean operators not, or, and and.
  • Arithmetic operators +, -, *, /, and %.
  • Comparison operators ==, !=, <, <=, >, and >=.
  • Function int() to convert strings into integers.
  • Function str() to convert numbers into strings.
  • Function today() that gets today’s date as a float representing epoch time.
  • Function strptime() that converts strings in the format "yyyy-mm-dd" to a float representing the date in epoch time.
  • Lists, together with the in, and not in infix operators.
  • Strings, together with the in and not in infix operators, for substring containment.
  • Function re.match() to match a regular expression (without the optional flags argument).
  • Function lower() converts strings to lower case.
  • Function upper() converts strings to upper case.
You can use Semgrep metavariables such as $MVAR, which Semgrep evaluates as follows:
  • If $MVAR binds to a literal, then that literal is the value assigned to $MVAR.
  • If $MVAR binds to a code variable that is a constant, and constant propagation is enabled (as it is by default), then that constant is the value assigned to $MVAR.
  • Otherwise, the code bound to the $MVAR is kept unevaluated, and its string representation can be obtained using the str() function, as in str($MVAR). For example, if $MVAR binds to the code variable x, str($MVAR) evaluates to the string literal "x".

Legacy metavariable-comparison keys

INFOYou can avoid using the legacy keys described below (base: int and strip: bool) by using the int() function, as in int($ARG) > 0o600 or int($ARG) > 2147483647.
The metavariable-comparison operator also takes optional base: int and strip: bool keys. These keys set the integer base the metavariable value should be interpreted as and remove quotes from the metavariable value, respectively.
The preceding pattern matches the following:
This interprets metavariable values found in code as octal. As a result, Semgrep detects 0700, but it does not detect 0400.
The preceding pattern matches the following:
This removes quotes (', ", and `) from both ends of the metavariable content. As a result, Semgrep detects "2147483648", but it does not detect "2147483646". This is useful when you expect strings to contain integer or float data.

metavariable-name

TIP
  • metavariable-name requires a Semgrep account and the use of Semgrep’s proprietary engine since it requires name resolution information. This means that it does not work with the --oss-only flag.
  • While optional, you can improve the accuracy of metavariable-name by enabling cross-file analysis.
The metavariable-name operator adds a constraint to the types of identifiers a metavariable can match. Currently, the only constraint supported is on the module or namespace from which an identifier originates. This is useful for filtering results in languages that don’t have a native syntax for fully qualified names, or languages where module names may contain characters that are not legal in identifiers, such as JavaScript or TypeScript.
The preceding pattern matches the following:
If a match should occur if the metavariable matches one of a variety of matches, there is also a shorthand modules key, which takes a list of module names.
This can be useful in instances where there may be multiple API-compatible packages that share an issue.

pattern-not

The pattern-not operator is the opposite of the pattern operator. It finds code that does not match its expression. This is useful for eliminating common false positives.
The preceding pattern matches the following:
Alternatively, pattern-not accepts a patterns or pattern-either property and negates everything inside the property.

pattern-inside

The pattern-inside operator keeps matched findings that reside within its expression. This is useful for finding code within other pieces of code, such as functions or if blocks.
The preceding pattern matches the following:

pattern-not-inside

The pattern-not-inside operator keeps matched findings that do not reside within its expression. It is the opposite of pattern-inside. This is useful for finding code that’s missing a corresponding cleanup action like disconnect, close, or shutdown. It’s also helpful in finding problematic code that isn’t inside code that mitigates the issue.
The preceding pattern matches the following:
The preceding rule identifies files that are opened but never closed, potentially leading to resource exhaustion. It looks for the open(...) pattern and not a following close() pattern. The $F metavariable ensures that the same variable name is used in the open and close calls. The ellipsis operator allows any arguments to be passed to open and any sequence of code statements to be executed between the open and close calls. The rule ignores how open is called or what happens up to a close call; it only needs to make sure close is called.

Metavariable matches

matching operates differently for logical AND (patterns) and logical OR (pattern-either) parent operators. Behavior is consistent across all child operators: pattern, pattern-not, pattern-regex, pattern-inside, pattern-not-inside.

Metavariables in logical ANDs

values must be identical across sub-patterns when performing logical AND operations with the patterns operator. Example:
This rule matches the following code:
The example rule doesn’t match this code:

Metavariables in logical ORs

matching does not affect the matching of logical OR operations with the pattern-either operator. Example:
The preceding rule matches both examples below:

Metavariables in complex logic

matching still affects subsequent logical ORs if the parent is a logical AND. Example:
The preceding rule matches both examples below:
The example rule doesn’t match this code:

options

Enable, disable, or modify the following matching features: The complete list of available options can be consulted in the Semgrep matching engine configuration module. Please note that options not included in the table above are considered experimental and may change or be removed without notice.

fix

The fix top-level key allows simple pattern fixes by suggesting an alternative for each match. Run semgrep with --autofix to apply the changes to the files. Example:
For more information about fix and --autofix see Rule-defined fix documentation.

metadata

Provide additional information for a rule with the metadata: key, such as a related CWE, likelihood, or OWASP. Example:
The metadata are also displayed in the output of Semgrep if you’re running it with --json. Rules with category: security have additional metadata requirements. See Including fields required by security category for more information.

min-version and max-version

Each rule supports optional fields min-version and max-version specifying minimum and maximum Semgrep versions. If the Semgrep version being used doesn’t satisfy these constraints, the rule is skipped without causing a fatal error. Example rule:
Another use case is when a newer version of a rule works better than before but relies on a new feature. In this case, you can use min-version and max-version to ensure that either the older or the newer rule is used, but not both. The rules would look like this:
The min-version/max-version feature has been available since Semgrep 1.38.0. It is intended primarily for publishing rules that rely on newly released features without causing errors in older Semgrep installations.

category

Provide a category for users of the rule. For example: best-practice, correctness, maintainability. For more information, see Semgrep Registry rule requirements.

paths

Exclude a rule in paths

To ignore a specific rule on specific files, set the paths: key with one or more filters. These filters are glob patterns that apply to file paths relative to the project root. This works like the command-line filters --exclude and --include, but in a rule-specific manner. Example:
When invoked from the project root with semgrep -f rule.yaml src, the preceding rule runs on file paths inside src/, but no results are returned for:
  • Any file whose name ends in .jinja2
  • Any file whose name ends in _test.go that exists in a folder named backend, such as src/backend/server_test.go
  • Any file under src/tests/
  • Any file matching the /src/static/*.js glob pattern, such as src/static/hello.js, but not old/src/static/hello.js
Path filters use paths relative to the project root, so the selected set of files for a rule does not depend on the current working directory. For example, if rule.yaml is at the project root, these commands select the same files for the rule:
Rule paths filters use Semgrepignore v2 / Gitignore-style glob semantics for anchoring and ** matching. They are not identical to .semgrepignore or .gitignore files.Patterns can match file paths or directory paths. A directory pattern such as /src/tests applies to files under that directory.A leading slash anchors the pattern to the project root. For example, /*.c matches b.c at the project root, but not a/b.c.Semgrep currently treats patterns with a slash in the middle, such as src/*.c, as floating (unanchored) for backward compatibility. These patterns are ambiguous and may produce warnings. Prefer an explicit form:
  • /src/*.c to anchor the pattern to the project root
  • **/src/*.c to keep floating, directory-agnostic matching
Other patterns without a slash, such as *.c, remain unanchored and match at any depth.

Limit a rule to paths

Conversely, to run a rule only on specific files, set a paths: key with one or more of these filters. For example, consider the following repository layout:
When invoked from the project root with semgrep -f rule.yaml app/, Semgrep scans files under app/, and the rule returns results only for:
  • Files whose name ends in _test.go, such as app/backend/server_test.go
  • Files inside app/server, app/schemata, or their subdirectories
  • Files matching the /app/static/*.js glob pattern
  • All .js files at any depth under app/tests/
If you are writing tests for your rules, add any test file or directory to the included paths as well.
When mixing inclusion and exclusion filters, the exclusion filters take precedence.
Example:
The preceding rule returns results from app/schemata/scan.py but not from app/schemata/scan_internal.py.

Additional examples

This section contains more complex rules that perform advanced code searching.

Complete useless comparison

The preceding rule makes use of many operators. It utilizes pattern-either, patterns, pattern, and pattern-inside to carefully consider different cases, and employs pattern-not-inside and pattern-not to exclude specific unnecessary comparisons.

Full specification

The full configuration-file format is defined as a jsonschema object.