metavariable-comparison
- See also
patterns,metavariable-regex
An item of patterns. It keeps the matches for which an expression over the metavariables is true. The value is a mapping:
comparison: the expression, in Python syntax. It can use the metavariables, numbers and strings, arithmetic (+,-,*,%), comparisons (<,<=,>,>=,==,!=),and,orandnot, and the conversionsint()andstr();metavariable: the metavariable the comparison is about. It is needed only withstrip;strip:trueto remove the quotes around the value of the metavariable first, so that a string such as"80"compares as the number 80.
Examples
A short RSA key
short-rsa-key.yaml
rules: - id: short-rsa-key patterns: - pattern: rsa.generate_private_key(..., key_size=$SIZE, ...) - metavariable-comparison: metavariable: $SIZE comparison: $SIZE < 2048 message: RSA keys shorter than 2048 bits are weak languages: [python] severity: ERRORshort-rsa-key.py
from cryptography.hazmat.primitives.asymmetric import rsa# ruleid: short-rsa-keyrsa.generate_private_key(public_exponent=65537, key_size=1024)# ok: short-rsa-keyrsa.generate_private_key(public_exponent=65537, key_size=4096)Command and result
$ opengrep test .
1/1: ✓ All tests passed
No tests for fixes found.A number written as a string
low-port.yaml
rules: - id: low-port-default patterns: - pattern: app.run(port=$PORT) - metavariable-comparison: metavariable: $PORT comparison: $PORT < 1024 message: a privileged port languages: [python] severity: INFO - id: low-port patterns: - pattern: app.run(port=$PORT) - metavariable-comparison: metavariable: $PORT comparison: $PORT < 1024 strip: true message: a privileged port languages: [python] severity: INFOlow-port.py
# ruleid: low-port-default, low-portapp.run(port=80)# ruleid: low-portapp.run(port="80")app.run(port=8080)Command and result
$ opengrep test .
2/2: ✓ All tests passed
No tests for fixes found.