metavariable-pattern
- See also
patterns,metavariable-regex
An item of patterns. It keeps the matches where the code bound to a metavariable matches a further pattern. The value is a mapping with:
metavariable: the metavariable, bound by another item;- one of
pattern,pattern-either,patternsorpattern-regex, matched against that code; language, optionally: the language in which the code is read, when it differs from that of the rule. Withgeneric, for example, the text of a string can be matched word by word.
Examples
A query built from strings
sql-concat.yaml
rules: - id: sql-concat patterns: - pattern: $CURSOR.execute($QUERY, ...) - metavariable-pattern: metavariable: $QUERY pattern-either: - pattern: '"..." + $X' - pattern: f"..." message: a SQL query built from strings languages: [python] severity: ERRORsql-concat.py
def find_user(cursor, name): # ruleid: sql-concat cursor.execute("SELECT * FROM users WHERE name = '" + name + "'") # ruleid: sql-concat cursor.execute(f"SELECT * FROM users WHERE name = '{name}'") # ok: sql-concat cursor.execute("SELECT * FROM users WHERE name = %s", (name,))Command and result
$ opengrep test .
1/1: ✓ All tests passed
No tests for fixes found.Words inside a string
drop-table.yaml
rules: - id: drop-table patterns: - pattern: $CURSOR.execute("$SQL", ...) - metavariable-pattern: metavariable: $SQL language: generic pattern: DROP TABLE $T message: a query that drops a table languages: [python] severity: WARNINGdrop-table.py
# ruleid: drop-tablecursor.execute("DROP TABLE users")# ok: drop-tablecursor.execute("SELECT * FROM users")Command and result
$ opengrep test .
1/1: ✓ All tests passed
No tests for fixes found.