metavariable-regex
- See also
patterns,pattern-regex,metavariable-pattern,metavariable-comparison,$X,"..."
An item of patterns. It keeps the matches where the code bound to a metavariable matches a PCRE regular expression. The value is a mapping:
metavariable: the metavariable, bound by another item;regex: the regular expression;constant-propagation:trueorfalse, by defaultfalse.
The regex must match at the start of the text of the metavariable, and may end before its end: md5 keeps md5 and md5_hex, not new_md5. End it with $ to require the whole text.
By default, the regex is matched against the code as written, so a string literal includes its quotes. With constant-propagation: true, a metavariable bound to a constant is matched by its value instead: a string without its quotes, and a variable that holds a constant by the constant it holds.
Examples
Weak hash functions by name
weak-hash.yaml
rules: - id: weak-hash patterns: - pattern: hashlib.$ALG(...) - metavariable-regex: metavariable: $ALG regex: md5|sha1 message: $ALG is a weak hash languages: [python] severity: WARNINGweak-hash.py
import hashlib# ruleid: weak-hashhashlib.md5(data)# ruleid: weak-hashhashlib.sha1(data)# ok: weak-hashhashlib.sha256(data)# ok: weak-hashhashlib.new_md5(data)Command and result
$ opengrep test .
1/1: ✓ All tests passed
No tests for fixes found.Values through a variable
weak-alg.yaml
rules: - id: weak-alg-default patterns: - pattern: hashlib.new($ALG, ...) - metavariable-regex: metavariable: $ALG regex: '"(md5|sha1)"' message: weak hash languages: [python] severity: WARNING - id: weak-alg patterns: - pattern: hashlib.new($ALG, ...) - metavariable-regex: metavariable: $ALG regex: md5|sha1 constant-propagation: true message: weak hash languages: [python] severity: WARNINGweak-alg.py
import hashlib# ruleid: weak-alg-default, weak-alghashlib.new("md5", data)alg = "sha1"# ruleid: weak-alghashlib.new(alg, data)Command and result
$ opengrep test .
2/2: ✓ All tests passed
No tests for fixes found.weak-alg-default matches the literal with its quotes and does not match the variable. weak-alg matches the value in both places.