Triaging and Tuning Scanner Results
Work through a real scanner report: decide which findings are true positives, false positives and false negatives, record each decision, tune with the narrowest tool that works (an inline suppression, a path ignore, a taint rule), and triage dependency advisories by runtime scope and reachability.
Contentsand lesson path
On this page
- The problem
- Step 1: Scan the repository
- Step 2: Triage each result
- Step 3: Tune with the narrowest tool
- Step 4: Fix the true positive
- Step 5: Triage dependency advisories
- Check your understanding
- Apply it
- Review prompt
Lessons of Secure Coding & Code Review
- Where Security Review Fits in Delivery Concept · 15 min
- Tracing Untrusted Input from Source to Sink Worked example · 25 min
- Static, Dependency and Secret Scanning in CI Lab · 30 min
- Triaging and Tuning Scanner Results Worked example · 20 min
- Fixes That Stay Fixed Lab · 25 min
- Secure Code Review Check Knowledge check · 6 questions
What you will learn
- Configure static analysis, dependency scanning and secret scanning in CI, triage results into true and false positives, and tune rules to reduce noise.
Prerequisites: Web Application Security
01. The problem
A scanner is only useful if people trust its results. Lesson 3 added Semgrep, pip-audit and Gitleaks to CI. A month later the notes team complains: the scan flags a training example nobody ships, it warns about a backup command that cannot be influenced by users, and nobody remembers which warnings were already checked. Meanwhile a real flaw in a new search endpoint went through without a single finding.
That mix is normal. Every finding falls into one of four boxes. A true positive is a real problem the tool found. A false positive is a finding that is not a real problem in this context. A true negative is safe code the tool correctly ignores. A false negative is a real problem the tool missed, and it is the most dangerous box because nobody sees it.
In this worked example you triage the report for a small repository, record each decision with a reason, tune the scan so it reports the real flaw and stops reporting the two non-issues, and then triage dependency advisories. You need the virtual environment from lesson 3 (Semgrep 1.185.0, pip-audit 2.10.1) and a new folder called triage-lab.
02. Step 1: Scan the repository
The repository has three Python files. Create them, plus the rule file and report printer from lesson 3, which are repeated here so the folder is complete.
mkdir -p triage-lab/notes_api triage-lab/docs/examples triage-lab/rules triage-lab/tools
cd triage-lab"""Search endpoint (lab sample)."""
from flask import request
def search_titles(conn):
words = request.args.get("q", "")
sql = "SELECT id, title FROM notes WHERE title LIKE '%" + words + "%'"
return conn.execute(sql).fetchall()import subprocess
def backup():
# constant command, no request data involved
subprocess.run("sqlite3 notes.db .dump > backup.sql", shell=True, check=True)"""Known-bad snippets shown in the team's code-review training. Never imported."""
def example(conn, name):
return conn.execute(f"SELECT * FROM users WHERE name = '{name}'")rules:
- id: sql-built-from-string
languages: [python]
severity: ERROR
message: SQL text built from a variable; pass values as ? parameters
pattern-either:
- pattern: $CONN.execute(f"...")
- pattern: $CONN.execute("..." % ...)
- pattern: $CONN.execute("..." + ...)
- id: subprocess-shell-true
languages: [python]
severity: WARNING
message: shell=True runs the string through /bin/sh; check what reaches it
pattern: subprocess.run(..., shell=True, ...)"""Print one line per finding from a Semgrep or Gitleaks JSON report."""
import json
import sys
data = json.load(open(sys.argv[1]))
if isinstance(data, dict): # Semgrep: {"results": [...]}
for r in data["results"]:
rule = r["check_id"].split(".")[-1]
print(f"{r['path']}:{r['start']['line']} {r['extra']['severity']} {rule}")
print(f"{len(data['results'])} Semgrep finding(s)")
else: # Gitleaks: [...]
for r in data:
print(f"{r['File']}:{r['StartLine']} {r['RuleID']} {r['Secret']}")
print(f"{len(data)} Gitleaks finding(s)")semgrep scan --metrics=off --disable-version-check --quiet --config rules/ \
--json -o step1.json .
python3 tools/findings.py step1.jsondocs/examples/bad_queries.py:5 ERROR sql-built-from-string
notes_api/backup.py:6 WARNING subprocess-shell-true
2 Semgrep finding(s)03. Step 2: Triage each result
For each finding, ask three questions in order. First, can untrusted data reach this sink? A sink is the dangerous operation, here an SQL call or a shell command. Second, is this code shipped and run? Code in examples, generated files or dead modules has different risk from production code. Third, is there already a control that stops the attack? Answer from the code, not from the rule name.
docs/examples/bad_queries.py is a deliberately bad snippet used in training slides. It is never imported or deployed, so the finding is a false positive in this repository. notes_api/backup.py passes a constant string to the shell; no request data can reach it, so it is also a false positive today. That judgement can change if someone later builds the command from user input, which is why the rule should stay on.
Now look for what is missing. notes_api/search.py takes q from the request and concatenates it into SQL text, which is a real injection flaw. The pattern rule did not match because the string is first stored in the variable sql and only then passed to execute. That is a false negative, and it is the most important result of this triage.
Record every decision where the next reviewer will find it. A small CSV file in the repository is enough. Save this as triage-lab/triage.csv.
finding,decision,why,action
docs/examples/bad_queries.py:5,false positive,training sample; never imported,ignore dir
notes_api/backup.py:6,false positive,constant string; no request data,nosemgrep
notes_api/search.py:8,false negative,request value reaches SQL via a variable,taint rule04. Step 3: Tune with the narrowest tool
Choose the smallest change that fixes each result, because every suppression is also a place where a future real bug can hide. From narrowest to broadest:
- An inline suppression on one line, naming the rule and the reason.
- A path ignore for files that are not part of the product.
- A better rule, for example one that follows data instead of matching text.
- Disabling a rule for the whole repository, which is rarely right because it also hides the cases the rule was written for.
For the training sample, add the folder to .semgrepignore. Be careful: when a repository has its own .semgrepignore, Semgrep uses that file instead of its built-in default list, which skips folders such as tests/, node_modules/ and .venv/. In a real repository, copy the default entries you still want into your file, or add the line :include .gitignore. This lab has none of those folders, so one line is enough, and the explicit file makes the choice visible in review. For the backup command, add a nosemgrep comment that names the rule and the reason on the line above the call. Change notes_api/backup.py to:
import subprocess
def backup():
# constant command, no request data involved
# nosemgrep: subprocess-shell-true -- constant string, reviewed in PR 118
subprocess.run("sqlite3 notes.db .dump > backup.sql", shell=True, check=True)For the missed flaw, add a taint rule. Taint mode tracks data from a source (where untrusted input enters, here Flask's request.args) to a sink (the SQL text argument of execute), across assignments and string operations. focus-metavariable makes the rule report only when tainted data reaches the SQL text, not the separate parameters tuple. Save it as triage-lab/rules/sql-taint.yml, create the ignore file and scan again.
rules:
- id: request-data-in-sql
languages: [python]
severity: ERROR
message: Request data reaches SQL text; pass it as a ? parameter instead
mode: taint
pattern-sources:
- pattern: flask.request.$ANY.get(...)
- pattern: flask.request.$ANY[...]
pattern-sinks:
- patterns:
- pattern: $CONN.execute($SQL, ...)
- focus-metavariable: $SQLprintf 'docs/examples/\n' > .semgrepignore
semgrep scan --metrics=off --disable-version-check --quiet --config rules/ \
--json -o step3.json .
python3 tools/findings.py step3.jsonnotes_api/search.py:8 ERROR request-data-in-sql
1 Semgrep finding(s)The two false positives are gone, each for a recorded reason, and the real flaw is now reported. Taint rules can also be told about sanitizers, functions that make data safe for a sink. For example, if a handler converts a page number with int(...) before building SQL, adding int(...) under pattern-sanitizers stops that safe case from being reported without weakening the rule elsewhere.
05. Step 4: Fix the true positive
Fix the search by passing the search words as a bound parameter. The % wildcards become part of the value, not part of the SQL text. Replace notes_api/search.py and scan with --error, the way the CI gate does.
"""Search endpoint (lab sample)."""
from flask import request
def search_titles(conn):
words = request.args.get("q", "")
sql = "SELECT id, title FROM notes WHERE title LIKE ?"
return conn.execute(sql, ("%" + words + "%",)).fetchall()semgrep scan --metrics=off --disable-version-check --quiet --error --config rules/ \
--json -o step4.json .
echo "exit=$?"
python3 tools/findings.py step4.jsonexit=0
0 Semgrep finding(s)In a real fix you would also add a test with a search term that contains an apostrophe, as in lesson 3, so the behaviour is proven and not only the scanner's silence.
06. Step 5: Triage dependency advisories
Dependency reports need the same judgement. Two facts change the priority of an advisory. Scope: does the package run in production, or only on developer machines and in CI? Reachability: does your code use the vulnerable part of the package? Keep runtime and development dependencies in separate files so the gate can treat them differently. Copy deps.py from lesson 3 into tools/, then audit both files.
"""Summarise a pip-audit JSON report: one line per package and advisory."""
import json
import sys
report = json.load(open(sys.argv[1]))
seen = set()
for dep in report["dependencies"]:
for vuln in dep.get("vulns", []):
key = (dep["name"], vuln["id"])
if key in seen:
continue # the same advisory can be listed more than once
seen.add(key)
cve = next((a for a in vuln["aliases"] if a.startswith("CVE-")), "-")
fix = ", ".join(vuln["fix_versions"]) or "no fix yet"
print(f"{dep['name']} {dep['version']} {cve:<15} fixed in {fix}")
print(f"{len(seen)} advisory(ies)")printf 'flask==3.1.3\nrequests==2.34.2\n' > requirements.txt
printf 'black==23.1.0\n' > requirements-dev.txt
for f in requirements.txt requirements-dev.txt; do
pip-audit -r $f --no-deps --disable-pip --progress-spinner off \
-f json -o audit.json 2>/dev/null
echo "$f: exit=$?"
python3 tools/deps.py audit.json
donerequirements.txt: exit=0
0 advisory(ies)
requirements-dev.txt: exit=1
black 23.1.0 CVE-2024-21503 fixed in 24.3.0
black 23.1.0 CVE-2026-32274 fixed in 26.3.1
black 23.1.0 CVE-2026-31900 fixed in 26.3.0
black 23.1.0 - fixed in 26.10.1
4 advisory(ies)The runtime file is clean, so the blocking gate passes. black is a code formatter that only runs on your own source code during development, so its advisories go into the backlog with a deadline rather than blocking every merge. That is a decision about priority, not permission to ignore it: upgrade it in the next maintenance window.
Reachability works the same way for runtime packages. An advisory for requests 2.31.0, CVE-2024-35195, applies when a Session first makes a request with certificate checks turned off (verify=False): later requests on the same connection could skip the checks too. If your code never uses verify=False, the vulnerable path is not reachable, and the upgrade can go out on the normal schedule. If it does, it is urgent. Some scanners compute reachability automatically; when yours does not, a quick search for the vulnerable function is often enough.
07. Check your understanding
08. Apply it
For the skill project, triage every finding the three scanners reported on the sample repository. Give each one a line in a triage.csv with the decision and a one-line rationale, apply the narrowest tuning for each false positive, and look for at least one false negative by reading a handler the scanner was silent about.
09. Review prompt
From memory, define true and false positives and negatives, and say why a false negative is the most dangerous. List the four tuning options from narrowest to broadest, and name the two facts that change the priority of a dependency advisory.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.