Security and hardening · Intermediate · 20 min
Find security bugs in your code with Semgrep
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Semgrep 1.187.0 (checked on the python:3.15-slim image)
You will scan a small Flask and Express codebase with Semgrep Community Edition, read a finding and its data flow, fix the real bugs, record one reviewed exception, write a rule of your own and set a baseline so a check fails only on new findings.
On this page
Semgrep reads source code and reports lines that match rules: a rule says, in something close to the code's own syntax, "this shape is a bug". It never runs your program. That makes it fast and safe to point at any code, and it shapes what it can find.
Static analysis is good at code-level mistakes with a recognisable shape: user input pasted into a SQL string, a shell command built from a request, eval on a query parameter, a debug flag left on. It cannot tell whether your access rules are right, whether a user should see another user's invoice, whether a server is configured safely, or whether a dependency has a known vulnerability. It also produces false positives, because a rule sees a pattern and not your intent. Treat every finding as a question for a person to answer, not a verdict.
You will use Semgrep Community Edition 1.187.0, the free command-line engine. It follows data within one function. Tracking data across functions and files is part of Semgrep's paid platform, so single-function taint results here are the expected ceiling, not a bug. You need no account for anything in this tutorial, and every scan runs with metrics switched off.
The practice codebase is a tiny shop with a Flask API and an Express page, with bugs planted on purpose. Neither app is ever run: Semgrep only reads the files, so you do not install Flask or Express.
Step 1 · Install Semgrep with pipx
pipx installs a Python command-line tool into its own environment, so Semgrep's dependencies cannot clash with anything else on the machine. Install pipx and git from Ubuntu's archive, then Semgrep at a pinned version:
sudo apt-get update
sudo apt-get install -y pipx git
pipx install semgrep==1.187.0
pipx ensurepathpipx ensurepath adds ~/.local/bin to your shell's PATH. Open a new terminal after it, or run source ~/.bashrc, so the shell finds semgrep.
On macOS, brew install pipx gives you pipx and the remaining commands are the same. Semgrep's own docs note that the Homebrew formula for Semgrep often lags behind PyPI, so pipx is the better route for a pinned version.
The download is around 75 MB, once. If you pay for data by the megabyte, run this step on Wi-Fi; later scans with registry rules fetch only a few hundred kilobytes each.
Check it worked
semgrep --versionIt prints 1.187.0. To move to a later release, run pipx install --force semgrep==<version> with the version you want.
Step 2 · Create a small codebase with planted bugs
Make a throwaway project with two folders, api for the Python service and web for the Node.js one:
mkdir -p ~/semgrep-demo/api ~/semgrep-demo/web
cd ~/semgrep-demo
cat > api/app.py <<'PY'
import sqlite3
import subprocess
from flask import Flask, request
app = Flask(__name__)
def db():
return sqlite3.connect("shop.db")
@app.get("/products")
def products():
name = request.args.get("name", "")
query = f"SELECT id, name FROM products WHERE name = '{name}'"
rows = db().execute(query).fetchall()
return {"products": rows}
@app.get("/ping")
def ping():
host = request.args.get("host", "127.0.0.1")
out = subprocess.run(f"ping -c 1 {host}", shell=True, capture_output=True)
return out.stdout
@app.get("/health")
def health():
return {"ok": True}
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
PY
cat > web/server.js <<'JS'
const express = require("express");
const { exec } = require("node:child_process");
const app = express();
app.get("/hello", (req, res) => {
res.send("<h1>Hello " + req.query.name + "</h1>");
});
app.get("/convert", (req, res) => {
exec("convert " + req.query.file + " out.png", (err) => {
res.send(err ? "failed" : "done");
});
});
app.get("/calc", (req, res) => {
res.send(String(eval(req.query.expr)));
});
app.listen(3000);
JSBefore you scan, note what a careful reviewer would flag by eye, so you can compare it with what the tool reports:
/productspastesnameinto SQL (SQL injection)./pingbuilds a shell command fromhost(command injection).- The Flask app runs with
debug=True, which exposes an interactive debugger. /hellowritesnameinto HTML unescaped (cross-site scripting)./convertbuilds a shell command fromfile(command injection)./calcpasses a query parameter toeval(code injection).
Check it worked
find ~/semgrep-demo -type f | sortIt lists /home/<you>/semgrep-demo/api/app.py and /home/<you>/semgrep-demo/web/server.js, with your own home folder in place of /home/<you>.
Step 3 · Scan with registry rulesets
The Semgrep Registry publishes rulesets maintained by Semgrep and its community. p/python and p/javascript cover common security mistakes in each language, including Flask and Express. Pass each with --config, and add --metrics=off, because by default the CLI sends anonymous usage data whenever it pulls rules from the Semgrep server:
cd ~/semgrep-demo
semgrep scan --config p/python --config p/javascript --metrics=off .Semgrep downloads the two rulesets, parses both files and prints each finding under its file name. The summary ends with something like Ran 219 rules on 2 files: 11 findings. The exact numbers move as the registry changes.
Several bugs produce more than one finding, because overlapping rules look at the same line from different angles. The ping line, for example, is flagged by a taint rule (subprocess-injection), a general rule about user data in subprocess and an audit rule that fires on any shell=True.
Check it worked
Compare the output with your list. When this was written, the scan reported the SQL string in /products, the shell command in /ping, debug=True and host="0.0.0.0" in Flask, the HTML in /hello, and eval in /calc. It did not report the exec call in /convert on line 11 of web/server.js. Rulesets are written for common shapes and every one has gaps. You will close this one with a rule of your own in step 6.
Step 4 · Read a finding and its data flow
Each finding has four parts worth reading in order:
- The rule ID, such as
python.flask.security.injection.tainted-sql-string.tainted-sql-string. It names the language, framework and kind of problem. You use it to look the rule up and to ignore it precisely. - The message, which explains the risk and usually the fix.
- The
Details:link, a shortsg.runaddress that opens the rule's source and examples in the registry. - The lines that matched.
Rules come in two broad kinds. A pattern rule matches a code shape, such as any subprocess call with shell=True, whether or not input reaches it. A taint rule tracks data from a source, such as request.args, to a sink, such as execute(), and only reports when the data gets there. Ask Semgrep to show the path for taint findings:
cd ~/semgrep-demo
semgrep scan --config p/python --metrics=off --dataflow-traces api/app.pyUnder the tainted-sql-string finding, Semgrep now prints three blocks: where the taint comes from (line 15, request.args.get), the variables it flows through (name) and how it reaches the sink (the f-string on line 16).
Work through a finding with three questions. Can an outsider control the source? Does anything on the path clean or check the value? What happens if the value contains the attacker's syntax, such as a quote or a semicolon? For /products the answers are yes, nothing, and the query changes, so it is a true positive.
Check it worked
In the output, find the Taint comes from: block under tainted-sql-string and confirm it points at line 15. If you see no trace blocks, check that --dataflow-traces is in the command; it only changes text and SARIF output, not --json.
Step 5 · Fix the real bugs and record one exception
Most findings deserve a fix, not a comment. Here, the SQL query takes a parameter instead of an f-string, the ping runs from a list of arguments with no shell and only for an allowed host, and debug mode is read from an environment variable that is off unless set.
One finding is different. host="0.0.0.0" makes Flask listen on every network interface. That is a risk on a laptop on café Wi-Fi, but if this service runs in a container behind a reverse proxy, the proxy needs it. Suppose your team has reviewed that and accepts it. Mark the line with nosemgrep and the rule ID, and write the reason above it, so the next reviewer sees why the line is allowed and who decided.
Replace api/app.py with the fixed version:
cd ~/semgrep-demo
cat > api/app.py <<'PY'
import os
import sqlite3
import subprocess
from flask import Flask, abort, request
app = Flask(__name__)
def db():
return sqlite3.connect("shop.db")
@app.get("/products")
def products():
name = request.args.get("name", "")
rows = db().execute(
"SELECT id, name FROM products WHERE name = ?", (name,)
).fetchall()
return {"products": rows}
@app.get("/ping")
def ping():
host = request.args.get("host", "127.0.0.1")
if host not in {"127.0.0.1", "example.com"}:
abort(400)
out = subprocess.run(["ping", "-c", "1", host], capture_output=True)
return out.stdout
@app.get("/health")
def health():
return {"ok": True}
if __name__ == "__main__":
# The app runs in a container behind a reverse proxy, which must reach it
# on every interface. Reviewed 2026-11-26.
app.run( # nosemgrep: python.flask.security.audit.app-run-param-config.avoid_app_run_with_bad_host
host="0.0.0.0",
debug=os.environ.get("FLASK_DEBUG") == "1",
)
PY
semgrep scan --config p/python --metrics=off api/The comment goes on the first line of the match, which here is app.run(. Always name the rule: a bare # nosemgrep silences every rule on that line, including ones added to the ruleset later.
Check it worked
The scan summary shows Findings: 0. To confirm the exception is still visible to reviewers, run the scan with suppressions ignored:
semgrep scan --config p/python --metrics=off --disable-nosem api/That run reports exactly one finding, avoid_app_run_with_bad_host, on the app.run( line. A search for nosemgrep across the repository is a quick audit of every exception your team has made.
Step 6 · Write your first rule and scan with local rules only
The registry missed /convert. You can write a rule for it in a few lines. A rule file is YAML: an ID, the languages, a severity, a message for whoever sees the finding, and the pattern. In a pattern, $CMD is a metavariable that matches any expression, and ... matches any number of arguments. pattern-not removes matches you know are safe; here, exec with one fixed string.
cd ~/semgrep-demo
mkdir -p rules
cat > rules/exec-built-command.yaml <<'YAML'
rules:
- id: exec-with-built-command
languages: [javascript, typescript]
severity: ERROR
message: >-
exec() hands this command to a shell, and the command is built from
variables. Input that reaches it can add its own shell syntax. Use
execFile() with a fixed program and an array of arguments.
patterns:
- pattern: exec($CMD, ...)
- pattern-not: exec("...", ...)
YAML
semgrep scan --validate --config rules/ --metrics=off
semgrep scan --config rules/ --metrics=off .--validate checks the rule file's syntax. The second scan uses only your rule. It needs no network, no account and no registry, so you can run it on a plane or in a locked-down build server. This rule is a pattern rule, not a taint rule: it flags any exec whose command is not a fixed string, wherever the value came from. That is the right trade-off for a call this dangerous.
Check it worked
The output shows one finding, rules.exec-with-built-command, on line 11 of web/server.js. Semgrep adds the folder name, rules., to the front of the ID when it loads rules from a folder; use that full ID in any nosemgrep comment. Before relying on a rule, give it test cases with ruleid: and ok: comments and run semgrep --test, as in the regression tests tutorial linked at the end.
Step 7 · Fail a check only on new findings with a baseline
The JavaScript file still has three known problems. On a real codebase, the first scan often reports hundreds, and a check that fails on all of them gets switched off. A baseline lets you adopt Semgrep today: findings that already exist at a chosen commit are hidden, and only findings introduced since then are reported. The old ones go on a list to fix over time.
--baseline-commit needs a git repository with no unstaged changes. Commit the current code as main, then add a new route on a branch, the way a pull request would:
Git needs a name and email for each commit. The two git config lines set them for this throwaway repository only, so they disappear when you delete it; if you already use git, they override your usual identity here and nowhere else:
cd ~/semgrep-demo
git init -b main
git config user.name "Semgrep Demo"
git config user.email "semgrep-demo@example.com"
git add .
git commit -m "Shop code before Semgrep"
git switch -c add-thumbnails
cat >> web/server.js <<'JS'
app.get("/thumbnail", (req, res) => {
exec(`convert ${req.query.src} -resize 200x200 thumb.png`, (err) => {
res.send(err ? "failed" : "done");
});
});
JS
git commit -am "Add thumbnail route"Now scan the branch against main, with the registry ruleset and your rule together. --error makes Semgrep exit with code 1 when it reports anything, which is what fails a CI job:
cd ~/semgrep-demo
semgrep scan --config p/javascript --config rules/ --metrics=off --error --baseline-commit main . || echo "Semgrep exited with $?"In a CI job for a pull request, the baseline is the point where the branch left main. The job needs the full git history, not a shallow clone, so it can find that commit:
git fetch origin main
semgrep scan --config p/python --config p/javascript --config rules/ --metrics=off --error --baseline-commit "$(git merge-base origin/main HEAD)" .You can also set the commit in the SEMGREP_BASELINE_COMMIT environment variable instead of the flag.
Check it worked
Semgrep says it is reporting findings introduced by the Add thumbnail route commit, and the summary shows one finding: rules.exec-with-built-command on line 23, the new /thumbnail route. The three older JavaScript findings are not shown. The last line reads Semgrep exited with 1. Delete the new route or switch it to execFile, commit, and the same command prints no findings and exits 0.
Step 8 · Clean up
Remove the practice project and uninstall Semgrep:
cd ~
rm -rf ~/semgrep-demo
pipx uninstall semgrepSemgrep also keeps a small settings folder, ~/.semgrep. If you sign in to Semgrep for other work, the folder holds that login, so only remove it if you have not used Semgrep before:
rm -rf ~/.semgrepCheck it worked
semgrep --version now reports command not found, and ls ~/semgrep-demo reports that the folder does not exist. pipx and git stay installed, and so does the ~/.local/bin line that pipx ensurepath added to your shell profile (such as ~/.bashrc). It is harmless while pipx is installed; if you remove pipx too, delete that line from the profile.
Next steps
- Fix the SQL bug properly in both languages and see where parameters are not enough: prevent SQL injection in Python and Node.js.
- Test your own rules with
semgrep --testand run them on every pull request: keep fixes fixed with security tests and custom Semgrep rules. - Compare pattern matching with a query database that follows data across files: understand CodeQL and GitHub code scanning.
- Decide what to fix first when a scanner reports hundreds of issues: triage security scanner findings.
Related tutorials
- Write custom Fail2ban jails and filters for your own appsYou will have Fail2ban 1.1 banning repeated failed sign-ins to your own app and to an nginx basic-auth area, with filters you tested against sample logs, your own addresses allow-listed, and longer bans for repeat offenders.
- Validate file uploads before you store or serve themYou will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.
- Use SSH certificates instead of copying keys to every serverYou will run a small SSH certificate authority with ssh-keygen, log in to an Ubuntu 26.04 server with an eight-hour user certificate, give the server a host certificate so clients stop asking about fingerprints, and revoke a certificate the server then refuses.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials