Tracing Untrusted Input from Source to Sink
Review two small pull requests by following untrusted input from where it enters to where it is used: a sort option that reaches SQL text, where a placeholder cannot help and an allow-list can, and a preview URL that passes through two clean-looking helpers before the server fetches it.
Contentsand lesson path
On this page
- The problem
- Step 1: Find the source and the sink
- Step 2: Test what reaches the sink
- Step 3: Follow input across helpers
- Step 4: Check the fix with negative cases
- 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
- Perform a focused manual security review of a pull request with a checklist derived from OWASP ASVS, tracing untrusted input from source to sink.
Prerequisites: Web Application Security
01. The problem
Most injection-style flaws have the same shape. Data that an outsider controls enters the program at a source: a query-string parameter, a form field, a header, a file, a message from a queue. It travels through propagators, code that copies or transforms it, such as helper functions, string formatting or a database round trip. It becomes dangerous at a sink: an operation where data can change what the program does, such as SQL text, a shell command, an HTML template or an outgoing HTTP request.
Reviewing a pull request "line by line" often misses these flaws, because the source and the sink sit in different functions or files and each piece looks harmless. Source-to-sink tracing is the habit of picking each untrusted input in the diff and following it until it is either made safe or reaches a sink.
In this worked example you review two changes to a book catalogue. You need Python 3.10 or later, no packages, and a folder called trace-lab. All code runs locally against an in-memory SQLite database; the URL checks never open a network connection.
02. Step 1: Find the source and the sink
The first pull request adds a sort option to the book list, read from ?sort= in the URL. The author wrote three versions while experimenting; all three are in the file so you can compare them. Save it as trace-lab/catalogue.py.
"""Book listing for a small catalogue: three versions of the same sort option."""
import sqlite3
SORTABLE = {"title": "title", "year": "year", "newest": "year DESC"}
def make_db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE books (title TEXT, year INTEGER)")
conn.executemany("INSERT INTO books VALUES (?, ?)",
[("Middlemarch", 1871), ("Dune", 1965), ("Emma", 1815)])
return conn
def list_books_unsafe(conn, sort):
# the request value becomes part of the SQL text
return conn.execute(f"SELECT title FROM books ORDER BY {sort}").fetchall()
def list_books_bound(conn, sort):
# a placeholder binds a value, so this sorts by a constant string
return conn.execute("SELECT title FROM books ORDER BY ?", (sort,)).fetchall()
def list_books(conn, sort):
column = SORTABLE.get(sort)
if column is None:
raise ValueError(f"unsupported sort {sort!r}")
return conn.execute(f"SELECT title FROM books ORDER BY {column}").fetchall()Write the trace down as you would in a review comment: source sort from the query string, propagator the f-string, sink the SQL text passed to execute. Nothing between the source and the sink checks the value. The question is not whether the input looks odd, but whether it can change the structure of the query instead of just its data.
03. Step 2: Test what reaches the sink
Run each version with an ordinary value and with a value that is a small SQL expression. This is a safe experiment on your own in-memory database. Save the script as trace-lab/try_sort.py and run it.
from catalogue import list_books, list_books_bound, list_books_unsafe, make_db
def titles(rows):
return [row[0] for row in rows]
conn = make_db()
print("unsafe, title ", titles(list_books_unsafe(conn, "title")))
print("unsafe, -year ", titles(list_books_unsafe(conn, "-year")))
print("bound, year ", titles(list_books_bound(conn, "year")))
print("safe, newest", titles(list_books(conn, "newest")))
try:
list_books(conn, "-year")
except ValueError as exc:
print("safe, -year rejected:", exc)python3 try_sort.pyunsafe, title ['Dune', 'Emma', 'Middlemarch']
unsafe, -year ['Dune', 'Middlemarch', 'Emma']
bound, year ['Middlemarch', 'Dune', 'Emma']
safe, newest ['Dune', 'Middlemarch', 'Emma']
safe, -year rejected: unsupported sort '-year'Read the lines one by one.
- The unsafe version with
-yearsorted newest first. The value was not treated as a column name; SQLite evaluated it as an expression. Any value that reaches this sink is parsed as SQL, which is the root of SQL injection. - The "bound" version did not sort at all. SQL defines no order when every row has the same sort key; SQLite happens to return this small table in the order the rows were inserted. A placeholder (
?) passes a value, andORDER BY 'year'sorts every row by the same constant string. Placeholders protect values such as a tag or an id, but they cannot carry identifiers such as column names, table names or the wordsASCandDESC. Many reviewers suggest "just use a parameter" here, and the code then silently stops working. - The safe version maps the user's choice to a fixed piece of SQL through an allow-list, the dictionary
SORTABLE. Only text the developer wrote can reach the query, and anything else is rejected with an error the handler can turn into a 400 response.
This matches OWASP ASVS 5.0 requirement 1.2.4, which asks that database queries use parameterised queries or are otherwise protected from injection; the OWASP Query Parameterization Cheat Sheet shows the value case.
04. Step 3: Follow input across helpers
The second pull request adds cover previews: the handler takes a URL from the query string and returns the first part of the image. The handler is two lines long and looks clean, so a quick review might approve it. Save the file as trace-lab/previews.py and trace url.
"""Cover previews: the handler looks clean, the risk is two calls further down."""
import urllib.request
from urllib.parse import urlsplit
ALLOWED_HOSTS = {"covers.example.org", "images.example.org"}
def preview_handler(args): # source: args comes from the query string
return fetch_preview(args["url"])
def fetch_preview(url): # propagator: passes the value on unchanged
return download(url)
def download(url): # sink: the server opens whatever URL it is given
with urllib.request.urlopen(url, timeout=5) as resp:
return resp.read(200_000)
def check_preview_url(url):
"""The fix: call this in fetch_preview before download()."""
parts = urlsplit(url)
if parts.scheme != "https":
raise ValueError("only https is allowed")
if parts.hostname not in ALLOWED_HOSTS:
raise ValueError("host is not on the allow-list")
return urlThe trace goes preview_handler (source) → fetch_preview (propagator) → download (sink). The sink is an outgoing request made by the server. If any URL is accepted, a caller can make the server fetch addresses that only the server can reach: an admin page on 127.0.0.1, an internal service, or a cloud provider's metadata endpoint that hands out credentials. This flaw is called server-side request forgery (SSRF). ASVS 5.0 requirement 1.3.6 asks for exactly this check: validate the URL against an allow-list of protocols, domains, paths and ports before calling another service.
A type check in the handler would not help; the value is a perfectly valid string. What matters is where it ends up, which is why you follow it through every helper. Scanners can do some of this tracing, but they often lose the trail across files, through frameworks or through a database round trip, so a reviewer still needs to do it.
05. Step 4: Check the fix with negative cases
The fix is check_preview_url, which fetch_preview should call before download. It accepts only https and only hosts on an exact allow-list. Test it with one good URL and several that must be refused. Save this as trace-lab/try_urls.py and run it; no request is sent, the script only calls the check.
from previews import check_preview_url
for url in ["https://covers.example.org/b/9.jpg",
"http://covers.example.org/b/9.jpg",
"https://covers.example.org.other.test/9.jpg",
"https://127.0.0.1/admin"]:
try:
check_preview_url(url)
print("allowed ", url)
except ValueError as exc:
print("rejected", url, "-", exc)python3 try_urls.pyallowed https://covers.example.org/b/9.jpg
rejected http://covers.example.org/b/9.jpg - only https is allowed
rejected https://covers.example.org.other.test/9.jpg - host is not on the allow-list
rejected https://127.0.0.1/admin - host is not on the allow-listThe third URL matters most. A check written as url.startswith("https://covers.example.org") or hostname.endswith("example.org") would accept it, although the host belongs to someone else. Comparing the parsed hostname with an exact set avoids that. An allow-list of hosts is not the whole defence: the fetch should also refuse redirects, or check each redirect target, and run with a short timeout and a size limit, as download does. The OWASP SSRF Prevention Cheat Sheet lists these layers.
06. Check your understanding
07. Apply it
For the skill project, open the pull request in the intentionally vulnerable sample repository and list every new untrusted input in the diff. For each one, write a three-part trace (source, propagators, sink or "made safe by …") in your review notes, and add a review comment wherever a trace ends at a sink without a control.
08. Review prompt
From memory, define source, propagator and sink, and name four kinds of sink. Explain why a placeholder cannot fix the sort option, and list three things a URL check must do to stop SSRF.
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.