Why the scanner reports a path through your validator#
A taint finding says a value from a source reached a sink. When your code runs that value through its own validation function on the way, the scanner usually does not know what the function does. Semgrep's engine source at v1.187.0 describes its default as "the assumption that function calls always propagate taint": an unknown call passes taint from its arguments to its result. Your validator looks to the engine like any other function, so the finding survives it.
The fixture below is constructed. A Flask route serves files from one directory, and checked_name in a separate module limits the name to letters, digits, _ and - followed by .txt:
# validate.py
_NAME = re.compile(r"[A-Za-z0-9_-]{1,64}\.txt")
def checked_name(name: str) -> str:
"""Return name if it is a plain .txt file name, else raise ValueError."""
if not _NAME.fullmatch(name):
raise ValueError(f"bad file name: {name!r}")
return name
# files.py
BASE = os.path.join(os.path.dirname(__file__), "files", "public")
@app.route("/download")
def download():
name = checked_name(request.args.get("name", ""))
with open(os.path.join(BASE, name)) as f:
return f.read()
A local taint rule treats flask.request.args.get(...) as the source and the first argument of open as the sink:
rules:
- id: request-to-open
mode: taint
languages: [python]
severity: ERROR
message: Request data reaches the path passed to open()
pattern-sources:
- pattern: flask.request.args.get(...)
pattern-sinks:
- patterns:
- pattern-inside: open($PATH, ...)
- focus-metavariable: $PATH
Semgrep 1.187.0, run as semgrep scan --config rule.yaml app/ --dataflow-traces, reports the path through the validator (box drawing and blank lines trimmed):
app/files.py
request-to-open
Request data reaches the path passed to open()
12┆ with open(os.path.join(BASE, name)) as f:
Taint comes from:
11┆ name = checked_name(request.args.get("name", ""))
Taint flows through these intermediate variables:
11┆ name = checked_name(request.args.get("name", ""))
This is how taint reaches the sink:
12┆ with open(os.path.join(BASE, name)) as f:
The trace is accurate about the data flow and silent about meaning. It shows checked_name on the path and nothing about what checked_name allows through.
Test the validator, then declare it#
The decision rests on one fact the scanner cannot supply: does the function stop every value that would let open escape BASE? Two kinds of value do that here. A name with .. segments climbs out of the directory, and an absolute path replaces it, because, per the Python 3.11 os.path.join documentation, "If a segment is an absolute path (which on Windows requires both a drive and a root), then all previous segments are ignored and joining continues from the absolute path segment."
A short script calls the validator directly with an ordinary name and both attack shapes, then sends one through the route with Flask's test client:
checked_name('readme.txt') -> 'readme.txt'
checked_name('../private/config.txt') raised ValueError
checked_name('/etc/hostname.txt') raised ValueError
GET /download?name=../private/config.txt -> 500
Both shapes raise, and the route fails closed (the uncaught ValueError becomes a 500; a real handler would return 400). The full-match pattern admits no / and no . outside the extension, so no traversal value can pass. That is the evidence that justifies a declaration. Add the function to the rule:
pattern-sanitizers:
- pattern: validate.checked_name(...)
The same scan now reports Ran 1 rule on 2 files: 0 findings. The source comments in the same Semgrep file state what the declaration does: "Sanitizers do allow you to completely remove taint from data". Keep the direct test next to the validator, because the declaration will keep clearing findings after the function changes.
When the validator checks the wrong property#
The disconfirmation is a small edit that a maintainer could make to accept names from subdirectories. The pattern now runs against the last path component, and the function still returns the original string:
def checked_name(name: str) -> str:
"""Return name if it is a plain .txt file name, else raise ValueError."""
if not _NAME.fullmatch(os.path.basename(name)):
raise ValueError(f"bad file name: {name!r}")
return name
The function name, the call site and the docstring are unchanged, so the sanitizer declaration still matches. The scan with the declared sanitizer still says Ran 1 rule on 2 files: 0 findings. The same direct test tells a different story:
checked_name('readme.txt') -> 'readme.txt'
checked_name('../private/config.txt') -> '../private/config.txt'
checked_name('/etc/hostname.txt') -> '/etc/hostname.txt'
GET /download?name=../private/config.txt -> 200 db_password=hunter2
The function validates the basename and returns the path. Every traversal value passes, and the route returns a file from outside the public directory. With the declaration in place, the scanner reports nothing; without it, the original finding would have stayed open and pointed at the right line.
This is why the declaration needs evidence of its own. A sanitizer entry is matched by name and call shape. It says nothing about the function's body, and the body is where the defect is.
What to record with the declaration#
A declared sanitizer is a standing dismissal of every future finding that passes through it. Record three things next to it.
- The property it enforces, stated for the sink: "rejects any name containing a path separator or
..", not "validates file names". - The direct test that exercises the attack shapes for that sink, kept in the test suite so a change to the function fails a test before it reaches review.
- The sinks it covers. A function that is enough for
opensays nothing about SQL text or shell arguments. Scope the declaration to the rule for that sink rather than adding it to every taint rule.
If the function only checks and the call site ignores its result (for example if not is_ok(name): abort(400) followed by a use of name), the return-value declaration above does not describe your code. Test that call site as written before deciding what to declare.
Decide from the direct test#
| What the finding says | Evidence to collect | Decision |
|---|---|---|
| Taint path passes through your validator | A direct test of the validator with the attack shapes for this sink | Declare it as a sanitizer for this rule if every shape is rejected or rewritten |
| Taint path passes through your validator, which checks a different value than it returns | The same direct test | Fix the validator; keep the finding open until the test passes |
| Finding cleared after a sanitizer was declared | The test that justified the declaration, run against the current function | Keep the dismissal only while that test passes |
| Validator used as a guard, value used afterwards | A test of the call site, not only of the function | Decide from the call site's behavior |
| Validator enough for one sink, rule covers several | Which sinks the rule includes | Scope the declaration to the sink it was tested against |
For telling a taint path apart from a single-line pattern match, see the guide to pattern-match and data-flow findings. When a reviewer comment rather than a scanner raised the validation question, the guide to input validation review comments covers that case.