🔎 Last updated · Editorial policy · Report an error
TL;DR: Semgrep lets you write lightweight, pattern-based rules that catch vulnerable code before it merges. In this lab you’ll write two custom rules (hardcoded secrets and SQL string concatenation), run them locally against a deliberately vulnerable Flask/Express repo, and gate your GitHub Actions pipeline so the bad commit is rejected with a nonzero exit code.
Lab setup and authorization note
Authorization: Everything in this tutorial runs against a vulnerable repo you create yourself on your own machine or your own GitHub repository. Never run scanners or exploit code against systems you don’t own or have explicit written permission to test.
You’ll need Python 3.9+, Git, and a GitHub account for the CI portion. Create a lab directory and a deliberately vulnerable app:
mkdir semgrep-lab && cd semgrep-lab
git init
mkdir app
cat > app/server.py <<'EOF'
from flask import Flask, request
import sqlite3
app = Flask(__name__)
# hardcoded credential - should be flagged
DATABASE_PASSWORD = "SuperSecret123!"
@app.route("/user")
def get_user():
user_id = request.args.get("id")
conn = sqlite3.connect("users.db")
# string-concatenated SQL - should be flagged
query = "SELECT * FROM users WHERE id = '" + user_id + "'"
return str(conn.execute(query).fetchall())
if __name__ == "__main__":
app.run(debug=True)
EOF
git add -A && git commit -m "initial vulnerable app"
Install Semgrep
Install via pip (or brew install semgrep on macOS, or the official Docker image):
pip install semgrep
semgrep --version
Expected output:
1.68.0
Verify the install works by running the built-in rules against your repo:
semgrep scan --config auto --severity WARNING
You should see findings from the community ruleset, including a generic hardcoded-secret hit and possibly an ORM/SQL injection hit. Community rules are great, but custom rules let you enforce your team’s own patterns — that’s what we’ll write next.
Write custom rule #1: hardcoded secrets
Semgrep rules are YAML. Create a rules/ directory and add rules/hardcoded-secret.yaml:
rules:
- id: hardcoded-secret-assignment
patterns:
- pattern: $VAR = $VALUE
- metavariable-regex:
metavariable: $VALUE
regex: "(?i).*?(secret|password|passwd|token|api_key).*"
- metavariable-regex:
metavariable: $VAR
regex: "(?i).*(secret|password|passwd|token|api_key|key).*"
message: >
Hardcoded credential detected in $VAR. Load secrets from environment
variables or a secrets manager instead.
severity: ERROR
languages: [python, javascript]
metadata:
category: security
Key pieces:
patternis a code pattern — Semgrep matches it structurally, not as plain text, so it works across formatting differences.metavariable-regexnarrows matches: here we require both a variable name and an assignment containing secret-ish terms.languagesmakes this rule work on both our Flask and any Express files.
Test it:
semgrep scan --config rules/
Expected output (truncated):
app/server.py
server.py:5:5
hardcoded-secret-assignment
Hardcoded credential detected in DATABASE_PASSWORD. Load secrets from environment
variables or a secrets manager instead.
5 DATABASE_PASSWORD = "SuperSecret123!"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ran 1 rules on 1 files: 1 findings
1 errors (only 1 shown)
Write custom rule #2: unsanitized SQL concatenation
The classic injection pattern: user input concatenated into a query string. Add rules/sql-concat.yaml:
rules:
- id: sql-query-concatenation
mode: taint
pattern-sources:
- pattern: flask.request.args.get(...)
- pattern: flask.request.form.get(...)
- pattern: $REQ.query.$FIELD
- pattern: $REQ.body.$FIELD
pattern-sinks:
- pattern: $CONN.execute($QUERY + ...)
- pattern: $QUERY = ... + ...
pattern-sinks:
- patterns:
- pattern-either:
- pattern: $CONN.execute($Q)
- pattern: $CONN.query($Q)
- pattern: $CONN.all($Q)
- pattern-not: $CONN.execute($Q, ...)
message: >
Untrusted request data flows into a SQL query via string concatenation.
Use parameterized queries: conn.execute("... WHERE id = ?", (user_id,))
severity: ERROR
languages: [python, javascript]
metadata:
category: security
This is a taint-mode rule — a big step up from pattern matching. Semgrep tracks data from sources (user-controlled request input) to sinks (SQL execution) and only reports when untrusted data actually reaches the sink. The pattern-not excludes parameterized calls, so safe code won’t be flagged.
Remove the duplicate pattern-sinks block if you copy-pasted — the final file should have exactly one pattern-sinks section:
rules:
- id: sql-query-concatenation
mode: taint
pattern-sources:
- pattern: flask.request.args.get(...)
- pattern: $REQ.query.$FIELD
pattern-sinks:
- patterns:
- pattern-either:
- pattern: $CONN.execute($Q)
- pattern: $CONN.query($Q)
- pattern-not: $CONN.execute($Q, ...)
message: >
Untrusted request data flows into a SQL query via string concatenation.
Use parameterized queries instead.
severity: ERROR
languages: [python, javascript]
Run both rules together and check the exit code:
semgrep scan --config rules/ --error; echo "exit code: $?"
Expected output:
app/server.py
rule sql-query-concatenation: Untrusted request data flows into a SQL query ...
rule hardcoded-secret-assignment: Hardcoded credential detected ...
ran 2 rules on 1 files: 2 findings
exit code: 1
The --error flag makes Semgrep exit 1 on any findings — that’s what makes a pipeline gate possible. Exit code 0 means clean.
Fix the findings (prove the rule isn’t noise)
Replace the vulnerable code with parameterized queries and an environment variable:
cat > app/server.py <<'EOF'
import os
from flask import Flask, request
import sqlite3
app = Flask(__name__)
DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
@app.route("/user")
def get_user():
user_id = request.args.get("id")
conn = sqlite3.connect("users.db")
query = "SELECT * FROM users WHERE id = ?"
return str(conn.execute(query, (user_id,)).fetchall())
if __name__ == "__main__":
app.run(debug=True)
EOF
semgrep scan --config rules/ --error; echo "exit code: $?"
Expected output:
ran 2 rules on 1 files: 0 findings
exit code: 0
Clean rules that catch real bugs and stay quiet on fixed code — that’s the goal. Temporarily revert so we can watch CI reject the bad commit: git stash.
Wire Semgrep into GitHub Actions as a blocking gate
Create the workflow file:
mkdir -p .github/workflows
cat > .github/workflows/semgrep.yml <<'EOF'
name: semgrep-gate
on: [pull_request, push]
jobs:
semgrep:
runs-on: ubuntu-latest
container:
image: semgrep/semgrep
steps:
- uses: actions/checkout@v4
- name: Run custom Semgrep rules
run: semgrep scan --config rules/ --error --metrics=off
EOF
The critical part is --error: without it, Semgrep reports findings but exits 0, and the check passes anyway. --metrics=off keeps telemetry off your lab.
Commit everything and push:
git stash pop
git add -A
git commit -m "add vulnerable handler and semgrep rules"
git remote add origin git@github.com:YOURUSER/semgrep-lab.git
git push -u origin main
Watch the bad commit get rejected
On GitHub, open the Actions tab and click the failing run:
Run semgrep scan --config rules/ --error --metrics=off
app/server.py
rule sql-query-concatenation: Untrusted request data flows into a SQL query ...
rule hardcoded-secret-assignment: Hardcoded credential detected ...
ran 2 rules on 1 files: 2 findings
Error: Process completed with exit code 1.
The job shows a red ❌. To make the gate mandatory, go to Settings → Branches → Add branch protection rule, set Require status checks to pass before merging, and select semgrep-gate. Now the PR cannot be merged while Semgrep fails — the bad commit is blocked, not just noted.
Push the fixed version and the run goes green:
git apply -R vulnerability.patch 2>/dev/null || sed -i 's/"'"'"'" + user_id + "'"'"'"/?/' app/server.py
git add -A && git commit -m "parameterize query, env-inject secret" && git push
# Actions run: semgrep-gate ✔ passed (exit code 0)
Tuning tips for real repos
- Start in report mode: run CI with
--erroromitted for a week to gauge false positives, then flip it on once the rules are tuned. - Suppress deliberately: an inline
# nosemgrep: sql-query-concatenationcomment documents an accepted exception instead of silently editing the rule. - Layer rulesets: combine custom rules with community ones:
semgrep scan --config rules/ --config p/owasp-top-ten --error. - Test your rules: add
focus-annotated example code under atests/block in each YAML file so rule regressions are caught by CI too.
Defender takeaways
- Make the gate blocking, not advisory: always pair Semgrep CI runs with
--errorand required status checks — a scanner that can’t fail a build is a dashboard, not a control. - Write taint rules for injection classes: source-to-sink tracking (user input → SQL/command/exec sinks) dramatically cuts false positives versus naive pattern matching, so developers trust and keep the gate.
- Version your rules with your code: keep the
rules/directory in the same repo, require review for rule changes, and add test cases so a weakened rule can’t slip through silently.

