Semgrep Syntax Rules for Python Security Anti-Patterns

Semgrep identifies static security anti-patterns in Python codebases by matching abstract syntax trees using a human-readable rule syntax that mirrors standard Python code. By combining the ellipsis operator (...), metavariables ($VAR), boolean rule combinators, and dedicated taint tracking keys, Semgrep allows security engineers to define precise patterns for identifying vulnerabilities such as command injection, insecure deserialization, and hardcoded credentials without the complexity of traditional compiler-based AST queries.

Basic Code Pattern Matching

Semgrep rules use valid Python code fragments as patterns. Unlike regular expressions, Semgrep understands Python's abstract syntax, meaning whitespace, indentation style, and comment placements do not affect matching:

pattern: hashlib.md5()

This pattern matches any call to hashlib.md5(), regardless of whether it is written across multiple lines or surrounded by inline comments.

The Ellipsis Operator (...)

The ellipsis operator acts as a wildcard for zero or more elements, such as arguments, statements, or list items. In Python rules, it abstracts away code that is irrelevant to the vulnerability:

Metavariables

Metavariables represent dynamic code constructs, such as variable names, expressions, or function identifiers. They begin with a $ and consist of uppercase letters:

Deep Expression Operator (<... $X ...>)

The deep expression operator finds an expression nested at any depth inside another code structure. For example, detecting user-controlled data inside an SQL query string:

pattern: cursor.execute(<... $INPUT ...>)

This matches $INPUT whether it is passed directly, concatenated via +, formatted via .format(), or included in an f-string.

Rule Composition and Context Filters

Security rules often require positive and negative conditions to eliminate false positives. Semgrep coordinates sub-patterns using boolean composition keys:

Taint Mode Syntax

For vulnerabilities involving data flow—such as Server-Side Request Forgery (SSRF) or SQL Injection—Semgrep employs dedicated taint-tracking syntax (mode: taint):