SAST with Semgrep
Semgrep is a fast, open-source static analyser that matches code patterns, not text: a rule written as subprocess.run(..., shell=True, ...) matches that call however it is formatted, with any arguments in between, and never matches a comment or a string that merely contains those words. It supports over 30 languages, runs in seconds, and its rules are short YAML files you can read and write yourself.
Semgrep's public registry has thousands of maintained rules (--config p/python, p/owasp-top-ten, --config auto), but fetching them needs the network. Every session here uses local rule files, which is also what you do for your organisation's own rules.
A first scan
mkdir -p shop/app && cd shop
cat > app/views.py <<'PY'
import hashlib
import subprocess
import pickle
def ping(host):
return subprocess.run("ping -c 1 " + host, shell=True)
def find_user(db, name):
return db.execute("SELECT * FROM users WHERE name = '%s'" % name)
def find_user_safe(db, name):
return db.execute("SELECT * FROM users WHERE name = ?", (name,))
def load_session(blob):
return pickle.loads(blob)
def password_hash(pw):
return hashlib.md5(pw.encode()).hexdigest()
PY
cat > semgrep-rules.yml <<'YML'
rules:
- id: subprocess-shell-true
languages: [python]
severity: ERROR
message: subprocess with shell=True runs the string through a shell; pass a list of arguments
pattern: subprocess.$FUNC(..., shell=True, ...)
- id: sql-string-format
languages: [python]
severity: ERROR
message: SQL built with % formatting is injectable; use a parameterised query
pattern: $DB.execute("..." % $X)
- id: pickle-loads
languages: [python]
severity: WARNING
message: pickle.loads on untrusted data can execute code
pattern: pickle.loads(...)
- id: weak-password-hash
languages: [python]
severity: WARNING
message: MD5 is not a password hash; use argon2, scrypt or bcrypt
pattern: hashlib.md5(...)
YML
semgrep scan --config semgrep-rules.yml --metrics=off --quiet app
echo "exit $?"
┌─────────────────┐
│ 4 Code Findings │
└─────────────────┘
app/views.py
❯❯❱ subprocess-shell-true
❰❰ Blocking ❱❱
subprocess with shell=True runs the string through a shell;
pass a list of arguments
6┆ return subprocess.run("ping -c 1 " + host,
shell=True)
❯❯❱ sql-string-format
❰❰ Blocking ❱❱
SQL built with % formatting is injectable; use a
parameterised query
9┆ return db.execute("SELECT * FROM users WHERE name =
'%s'" % name)
❯❱ pickle-loads
❰❰ Blocking ❱❱
pickle.loads on untrusted data can execute code
15┆ return pickle.loads(blob)
❯❱ weak-password-hash
❰❰ Blocking ❱❱
MD5 is not a password hash; use argon2, scrypt or bcrypt
18┆ return hashlib.md5(pw.encode()).hexdigest()
exit 0
Four findings, and find_user_safe (the parameterised query) wasn't flagged: the SQL rule only matches a string literal followed by %. Note the exit code 0: by default Semgrep reports and succeeds. The ❰❰ Blocking ❱❱ label under each finding is a hint for Semgrep's platform policies, not for the CLI: it doesn't change the exit code.
Making it a gate
| Option | Effect |
|---|---|
--error |
exit 1 if there are findings |
--severity ERROR |
only run rules of that severity (repeatable) |
--json, --sarif, --gitlab-sast, --junit-xml |
machine-readable reports (SARIF for GitHub code scanning, the GitLab format for merge request widgets) |
--baseline-commit <ref> |
report only findings introduced since that commit (diff-aware scanning) |
--exclude, --include, .semgrepignore |
skip paths such as tests/ or vendored code |
A typical CI step fails on ERROR rules and keeps a full report for everything:
mkdir -p shop/app && cd shop
cat > app/views.py <<'PY'
import hashlib, subprocess
def ping(host):
return subprocess.run("ping -c 1 " + host, shell=True)
def password_hash(pw):
return hashlib.md5(pw.encode()).hexdigest()
PY
cat > semgrep-rules.yml <<'YML'
rules:
- id: subprocess-shell-true
languages: [python]
severity: ERROR
message: subprocess with shell=True runs the string through a shell
pattern: subprocess.$FUNC(..., shell=True, ...)
- id: weak-password-hash
languages: [python]
severity: WARNING
message: MD5 is not a password hash
pattern: hashlib.md5(...)
YML
semgrep scan --config semgrep-rules.yml --metrics=off --quiet --json -o semgrep.json app
jq -r '.results[] | "\(.extra.severity) \(.check_id) \(.path):\(.start.line)"' semgrep.json
semgrep scan --config semgrep-rules.yml --metrics=off --quiet --severity ERROR --error app > /dev/null
echo "gate (ERROR rules only): exit $?"ERROR subprocess-shell-true app/views.py:3
WARNING weak-password-hash app/views.py:5
gate (ERROR rules only): exit 1
In the pipelines
# GitHub Actions: Semgrep in its official container, SARIF uploaded to code scanning
semgrep:
runs-on: ubuntu-24.04
container: semgrep/semgrep:1.182.1 # pin the version
permissions:
contents: read
security-events: write # for the SARIF upload
steps:
- uses: actions/checkout@v7
- run: semgrep scan --config .semgrep/ --metrics=off --sarif -o semgrep.sarif --error
- uses: github/codeql-action/upload-sarif@v4
if: always()
with:
sarif_file: semgrep.sarif# GitLab CI: findings appear in the merge request's security widget
semgrep:
image: semgrep/semgrep:1.182.1
script:
- semgrep scan --config .semgrep/ --metrics=off --gitlab-sast -o gl-sast-report.json --error
artifacts:
when: always
reports:
sast: gl-sast-report.jsonKeep rule files in the repository (.semgrep/), so a rule change is reviewed like any other change. Teams that want the registry rules but offline CI download a pinned snapshot of them into the repository. The Semgrep AppSec Platform (the commercial service) adds managed policies, cross-file dataflow ("Pro" rules) and triage; semgrep ci connects a pipeline to it.
Limits
Semgrep's open-source engine analyses one file at a time and follows data only within a function (unless you use taint rules, next lesson). It will miss an injection whose input arrives through three helper functions in other modules, and some findings are false positives. Treat it as a fast net for known-bad patterns, not as a proof of safety.
Test yourself
Why didn't the SQL rule flag db.execute("... ?", (name,))?
- Semgrep skipped the function
- The pattern only matches a string literal formatted with %, and the safe call has no %
- The rule has a bug
- Parameterised queries are ignored by default
Semgrep reports findings but the CI job is green. What is missing?
- --json
- --error (exit 1 when there are findings)
- --quiet
- --metrics=off
What does --baseline-commit origin/main do in a PR pipeline?
- Scans only main
- Reports only findings introduced since that commit
- Fixes findings
- Downloads rules