Writing Semgrep Rules
Registry rules catch generic mistakes. The most valuable rules are often your own: "every requests call needs a timeout", "never call our legacy crypto_v1 module", "every Flask route needs @login_required". Semgrep rules are short enough that the person who fixes an incident can write the rule that prevents the next one, in the same pull request.
The rule language
| Key | Meaning |
|---|---|
pattern |
code to match; ... matches any arguments or statements, $X is a metavariable that matches any expression and can be reused |
patterns |
a list that must all hold (logical AND) |
pattern-either |
any of the sub-patterns (OR) |
pattern-not |
exclude matches of this pattern |
pattern-inside / pattern-not-inside |
only (or never) inside this context, e.g. inside a function with a decorator |
metavariable-regex |
the text bound to $X must match a regex |
pattern-regex |
plain regex, for files Semgrep can't parse or text-like checks |
mode: taint |
dataflow: values from pattern-sources must not reach pattern-sinks without passing a pattern-sanitizers |
fix |
an autofix template (semgrep --autofix) |
A rule with tests
Rules are code, so they get tests. Semgrep's test format puts annotated examples next to the rule: # ruleid: <id> above a line that must match, # ok: <id> above one that must not. semgrep --test checks every annotation:
mkdir rules
cat > rules/requests-timeout.yml <<'YML'
rules:
- id: requests-without-timeout
languages: [python]
severity: ERROR
message: requests.$METHOD() without timeout= can hang a worker forever
patterns:
- pattern: requests.$METHOD(...)
- metavariable-regex:
metavariable: $METHOD
regex: ^(get|post|put|patch|delete|head)$
- pattern-not: requests.$METHOD(..., timeout=$T, ...)
YML
cat > rules/requests-timeout.py <<'PY'
import requests
# ruleid: requests-without-timeout
requests.get("https://api.example.com/items")
# ruleid: requests-without-timeout
requests.post(url, json=payload, headers=auth)
# ok: requests-without-timeout
requests.get("https://api.example.com/items", timeout=5)
# ok: requests-without-timeout
session = requests.Session()
PY
semgrep --test --metrics=off rules/
echo "exit $?"
┌─────────────┐
│ Scan Status │
└─────────────┘
Scanning 1 file with 1 Code rule:
Scanning 1 file.
1/1: ✓ All tests passed
No tests for fixes found.
exit 0
Run semgrep --test in the pipeline of the repository that holds your rules, so a rule change that suddenly matches everything (or nothing) fails before it reaches other teams.
Taint mode: follow the data
Pattern rules see one expression. Taint rules follow values through assignments within a function: a value from a source (user input) that reaches a sink (a shell, a SQL query) without a sanitizer is a finding:
mkdir app
cat > app/routes.py <<'PY'
import os, shlex
from flask import Flask, request
app = Flask(__name__)
@app.route("/backup")
def backup():
name = request.args.get("name")
target = "/backups/" + name
os.system("tar czf " + target + ".tgz /data") # tainted value reaches a shell
@app.route("/backup-safe")
def backup_safe():
name = shlex.quote(request.args.get("name"))
os.system("tar czf /backups/" + name + ".tgz /data") # sanitised first
@app.route("/version")
def version():
os.system("cat /etc/os-release") # no user input involved
PY
cat > taint.yml <<'YML'
rules:
- id: flask-input-to-shell
languages: [python]
severity: ERROR
message: request data reaches os.system; use subprocess with a list, or shlex.quote
mode: taint
pattern-sources:
- pattern: flask.request.$ANYTHING
pattern-sanitizers:
- pattern: shlex.quote(...)
pattern-sinks:
- pattern: os.system(...)
YML
semgrep scan --config taint.yml --metrics=off --quiet --json app | jq -r '.results[] | "\(.check_id) line \(.start.line)"'flask-input-to-shell line 10
Only line 10 is reported: the value flowed from request.args through name and target into os.system. The quoted version and the constant command are clean. A grep for os.system would have flagged all three.
Suppressions and baselines
- Inline:
# nosemgrep: requests-without-timeouton the line (always name the rule, and add the reason in the comment). Review new suppressions like code. - Paths:
.semgrepignore(gitignore syntax) for vendored code, generated files and tests. - Baseline:
--baseline-commitreports only what a branch introduced:
mkdir app && cd app && git init -q
printf 'import requests\nrequests.get("https://a.example", timeout=3)\nrequests.get("https://legacy.example")\n' > client.py
git add . && git commit -qm "existing code with one old finding"
cat >> client.py <<'PY'
requests.get("https://b.example")
requests.get("https://c.example") # nosemgrep: requests-without-timeout -- streaming endpoint, timeout set on the adapter
PY
git commit -qam "new calls"
cat > ../rule.yml <<'YML'
rules:
- id: requests-without-timeout
languages: [python]
severity: ERROR
message: requests call without timeout=
patterns:
- pattern: requests.$METHOD(...)
- pattern-not: requests.$METHOD(..., timeout=$T, ...)
YML
echo "full scan:"
semgrep scan --config ../rule.yml --metrics=off --quiet --json . | jq -r '.results[] | " client.py:\(.start.line)"'
echo "since HEAD~1:"
semgrep scan --config ../rule.yml --metrics=off --quiet --json --baseline-commit HEAD~1 . | jq -r '.results[] | " client.py:\(.start.line)"'full scan:
client.py:3
client.py:4
since HEAD~1:
client.py:4
The full scan finds the old call on line 3 and the new one on line 4; the suppressed line 5 is silent. The baseline scan reports only line 4, the finding this branch introduced: that is the right gate for a pull request, while the full scan feeds the backlog.
Test yourself
What does pattern-not: requests.$METHOD(..., timeout=$T, ...) add to the rule?
- It matches calls with a timeout
- It excludes calls that already pass timeout=, wherever the argument is
- It sets a default timeout
- Nothing
What does a # ok: <rule-id> annotation mean in a Semgrep test file?
- The finding is accepted
- The next line must not match the rule;
semgrep --testfails if it does - Skip the rule
- Autofix the line
Why is taint mode better than pattern: os.system(...) for command injection?
- It's faster
- It reports only when untrusted input actually reaches the sink without sanitising, so constant commands aren't flagged
- It scans more files
- It fixes the code