reference

Pattern syntax

A pattern is a piece of code in the language of the rule, with placeholders that make it match more than one piece of code. Opengrep parses the pattern and the target files into syntax trees and compares the trees, so line breaks, spacing, comments and the kind of quotes around a string make no difference.

Patterns are used by pattern and the other pattern keys of a rule, by the items of a taint rule, and by --pattern on the command line. A pattern must be valid code of the language, apart from its placeholders; a pattern that does not parse makes the rule invalid.

NameSummary
...Match any sequence of arguments, statements, elements or calls.
$XMatch any expression or name, bind it, and require the same code where the name repeats.
(TYPE $X)Match an expression only when it has a given type.
<... ...>Match an expression that contains code matching an inner pattern, at any depth.
"..."Match string literals: any string, a bound string, or a string that matches a regular expression.
imports and aliasesA qualified name in a pattern also matches the same name imported under another name.

Some rule options extend what a pattern matches. For example, constant_propagation, which is on by default, lets a literal in a pattern match a variable known to hold that value.

Examples

Formatting and comments are ignored

rule.yaml
rules:  - id: shell-true    pattern: subprocess.run($CMD, shell=True)    message: a command is run through the shell    languages: [python]    severity: WARNING
app.py
subprocess.run(    cmd,  # built above    shell = True,)
Command and result
$ opengrep scan -q --config rule.yaml app.py
app.py

  warn  shell-true
  a command is run through the shell

     1: subprocess.run(
     2:     cmd,  # built above
     3:     shell = True,
     4: )