Recognizing Dangerous Code Patterns
Recognize risky concatenation, Python exec(), unsafe deserialization, filesystem operations, and HTML rendering before reviewing remote code execution.
Dangerous code patterns let data gain unintended authority. A string may become SQL, a program, a shell command, an object graph, a filesystem path, or browser markup. The review starts by identifying that change in meaning.
Work through the patterns, inspect Python’s exec() directly, and choose safer designs before attempting the remote code execution case.
What you should be able to do
- Recognize where a value becomes instructions or resource selection.
- Review Python exec(), process calls, and deserialization accurately.
- Trace filesystem and HTML boundaries to their receiving context.
- Distinguish a risky API from a reachable, supported finding.
The pattern behind the patterns: data becomes instructions
Most applications have a data plane: user names, search terms, document contents, report filters, uploaded files, and API values. They also have a control plane: SQL structure, shell grammar, program code, object constructors, path selection, and HTML syntax. A vulnerability appears when the application lets a less-trusted value alter the control plane without a deliberate authorization or interpretation boundary.
Consider a report service. A user chooses a report ID and requests a preview. The service may read metadata, query a database, render a template, and produce an HTML response. A report title is ordinary data when stored in a database column. The same title becomes powerful if concatenated into a SQL statement, passed to exec(), interpreted as a template, used as a filename, or inserted into innerHTML. The string itself did not change. Its destination changed.
For each suspicious line, make a five-column trace:
| Question | Reviewer note |
|---|---|
| Source | Who can set the value, directly or earlier through stored data? |
| Transformation | Was it decoded, parsed, trimmed, mapped, concatenated, or substituted? |
| Sink | Which interpreter or sensitive operation consumes it? |
| Boundary | Which rule should keep data from acquiring control? |
| Evidence | Which line or test proves the rule holds or fails? |
Do not stop after identifying a scary API name. A fixed internal string passed to exec() has a very different exposure from a string built from a request body. Equally, a harmless-looking helper such as formatReport() can be the point where request data becomes SQL syntax. Review the entire path and record the proof.
A useful first pass
Scan changed code and nearby helpers for these signals:
- A query, command, expression, template, path, or HTML fragment built with concatenation or interpolation.
- A function named exec, eval, compile, system, spawn with a shell, deserialize, loads, readObject, parseTemplate, renderHtml, or setInnerHTML.
- A file operation whose path includes a request parameter, upload name, database field, or archive entry.
- A parser whose output is later treated as trusted because it is "already in the database."
- A validator that checks shape but not the safety property required by the destination.
This list is a triage aid, not a vulnerability verdict. Some calls are safe because the executable text is fixed and the variable remains an argument or parameter. Some calls are unsafe despite an innocent name because a helper eventually invokes an interpreter. Your goal is to determine which bytes can change grammar.
This is the recurring pattern behind injection, unsafe execution, and some deserialization flaws. Inspect the point where interpretation changes.
Request. The caller controls operation. A string type check says what kind of value it is, not what authority it should receive.
operation = request.json["operation"]
if not isinstance(operation, str):
raise BadRequest()
Assembly. The service combines caller input with a program template. The important question is whether the resulting program is constrained to a fixed set of behaviors.
program = "result = " + operation
Execution. Python exec() executes the supplied Python statements. The service is granting the text the authority of the interpreter process.
exec(program, execution_context)
Resources. Inspect the credentials, files, network access, and objects available to the process. These determine the impact; the function name alone does not establish the full blast radius.
Review question: Can the feature select a server-owned operation without evaluating caller-supplied program text?
String concatenation: where values cross into grammar
Concatenation is not inherently unsafe. Combining a first and last name for display is normal. The risk depends on what parses the result. When a string is sent to a SQL engine, shell, template engine, regular-expression compiler, or another parser, attacker-controlled characters may stop being data and become syntax.
Read this original Python example. The route gets a report identifier from a URL and asks a repository helper for one row:
def report_page(request, connection):
report_id = request.path_params["report_id"]
report = load_report(connection, report_id)
if report is None:
return not_found()
return render_report(report)
def load_report(connection, report_id):
statement = "SELECT id, title FROM reports WHERE id = '" + report_id + "'"
return connection.execute(statement).fetchone()
The source is the URL path parameter. The transformation is concatenation into the SQL statement. The sink is connection.execute(). The rule is that an identifier must be interpreted as a value in the WHERE clause, never as part of the query grammar. A reviewer should not conclude that the route is safe because the variable is called report_id or because the page expects an ID. Names and UI expectations do not constrain an HTTP request.
The safer form keeps SQL structure fixed and binds a value through the database driver's parameter mechanism:
def load_report(connection, report_id):
statement = "SELECT id, title FROM reports WHERE id = ?"
return connection.execute(statement, (report_id,)).fetchone()
The exact placeholder syntax depends on the driver. Parameterization separates query structure from values; validation can also check the expected identifier format and length, but validation is not a substitute for binding. If an application chooses a table or column dynamically, ordinary placeholders usually cannot represent identifiers. In that case select from a small, trusted mapping of allowed names rather than accepting arbitrary request text as SQL structure.
Now compare a shell command:
import subprocess
def create_preview(request):
output_name = request.query_params["name"]
command = "convert /srv/uploads/source.png /srv/previews/" + output_name
subprocess.run(command, shell=True, check=True)
The vulnerable boundary is not merely "uses subprocess." It is that a shell parses a string containing user-controlled text. If a library can transform the image, use that instead. If a separate program is necessary, choose a fixed executable, pass arguments as a list with shell=False, validate the output name for this operation, and use a controlled output directory. Passing an argument list prevents shell parsing of the value, but it does not automatically prevent option injection or path traversal inside the called program.
from pathlib import Path
import re
import subprocess
PREVIEW_ROOT = Path("/srv/previews")
IMAGE_TOOL = "/usr/bin/convert"
def create_preview(request):
output_name = request.query_params["name"]
if not re.fullmatch(r"[a-z0-9-]{1,40}\.png", output_name):
raise ValueError("Invalid preview name")
destination = PREVIEW_ROOT / output_name
subprocess.run(
[IMAGE_TOOL, "/srv/uploads/source.png", str(destination)],
shell=False,
check=True,
timeout=20,
)
This example still requires operational review: is IMAGE_TOOL the actual installed binary, can that program interpret a filename as an option, what permissions does the process have, and can another actor replace files in the directory? The important improvement is that the request value is not assembled into shell grammar. OWASP's OS Command Injection Defense Cheat Sheet recommends avoiding OS command calls where possible and separating commands from arguments when they are unavoidable.
Concatenation that looks protected but is not
Watch for "escape" helpers with undocumented contracts. A helper called sanitize() may remove HTML tags while the resulting value is used in SQL. SQL escaping may be specific to a driver and encoding. URL encoding may make a value safe as one URL component while doing nothing for HTML, SQL, or shell syntax. A reviewer should ask: safe for which parser and which position inside that parser?
Also watch for second-order flows. A user may create a report title today; a privileged worker may read that title tomorrow and concatenate it into a command. The worker's input is a database row, but its origin remains untrusted. A stored value does not become trusted merely because it crossed a database boundary.
Python exec(): when text becomes Python code
Python's exec() executes Python code supplied as a string or code object. It is not a data parser. A program that constructs a string from an external value and passes it to exec() is allowing that value to influence executable Python syntax. The Python documentation explicitly warns against untrusted input for this function. The related eval() function evaluates an expression, which is narrower in form but still interprets Python code and is unsafe for untrusted expressions.
Consider an analytics product that lets a user select a calculation by name:
def calculate_metric(request, rows):
operation = request.json["operation"]
expression = "result = " + operation + "(rows)"
scope = {"rows": rows, "sum_values": sum_values, "mean_values": mean_values}
exec(expression, scope)
return scope["result"]
The intended operations may be sum_values and mean_values. The code gives operation a stronger role: it contributes to Python source text. The source is request JSON; the transformation is concatenation into expression; the sink is exec(). The scope dictionary lists functions, but it is not a security boundary. Even if a particular payload cannot access a useful object in a quick manual test, the design asks a general-purpose language interpreter to process untrusted text. That is the wrong primitive for selecting one of two operations.
Use a fixed mapping of operation names to trusted callables:
OPERATIONS = {
"sum": sum_values,
"mean": mean_values,
}
def calculate_metric(request, rows):
operation_name = request.json["operation"]
operation = OPERATIONS.get(operation_name)
if operation is None:
raise ValueError("Unsupported operation")
return operation(rows)
The mapping changes the trust boundary. The request may choose which permitted capability runs, but cannot write Python syntax. The operation must still have appropriate data access and resource limits. If each operation can read an entire tenant's data, the route must also verify authorization for those rows. Removing code injection does not prove the endpoint is otherwise secure.
Why filtering and restricted dictionaries are weak answers
Suppose a developer rejects semicolons, parentheses, or words such as import before calling exec(). Python has many forms of expression, object access, whitespace, encoding, and composition. A denylist is a bet that the developer enumerated every dangerous form now and after future code changes. It also leaves the general-purpose interpreter in the request path. The reviewer should recommend removing the interpreter from untrusted control, not just adding more rejected strings.
Passing empty dictionaries for globals or locals also does not create a secure sandbox. Python's documentation explains that builtins may be inserted into a globals dictionary lacking a builtins key, and even deliberately restricted evaluation environments can expose surprising object capabilities. A secure design uses a purpose-built parser for the specific data language the product needs.
If the product accepts arithmetic expressions, define a small grammar or parse an abstract syntax tree and allow only named operators and bounded numeric literals; do not execute arbitrary Python source.
from decimal import Decimal
def apply_operation(name: str, left: str, right: str) -> Decimal:
a = Decimal(left)
b = Decimal(right)
if name == "add":
return a + b
if name == "subtract":
return a - b
raise ValueError("Unsupported operation")
This bounded example does not cover every product requirement. It illustrates a critical design move: the application implements the permitted operations itself rather than invoking a language interpreter. A reviewer should also check input size, numeric precision, division rules if added, and denial-of-service limits. A safe grammar for syntax injection can still consume too much CPU or memory if operands are unbounded.
Distinguish exec() from process execution
The name "exec" appears in several ecosystems. Python's built-in exec() interprets Python code inside the process. A function such as JavaScript's child_process.exec() starts a shell command in another process. A database driver's execute() sends a query to a database parser. They have different payload languages and defenses. In a review finding, name the actual interpreter and how the input reaches it. Saying only "exec is dangerous" is too vague to guide a fix.
The feature needs only count and total operations. Which replacement most directly constrains the caller’s capability?
Unsafe deserialization: when data reconstructs behavior
Serialization turns an object or data structure into bytes for storage or transfer. Deserialization reverses that process. A safe mental model is that serialized input from a user, another service, a cache, an archive, or a database can be modified by an attacker unless its origin and integrity are established. Some formats represent plain data; others can instruct a runtime to instantiate objects or invoke behavior while loading.
Python's pickle is a clear example. Its official documentation warns that unpickling untrusted data can execute arbitrary code. This is not a minor parser configuration detail. It is a property of a format designed for Python objects, not untrusted API traffic.
import base64
import pickle
def restore_filter(request):
encoded = request.json["saved_filter"]
value = base64.b64decode(encoded)
return pickle.loads(value)
The base64 decode changes representation, not trust. The source is request JSON, and pickle.loads is the sink. A type check after loads is too late if loading itself can execute behavior. A signature can establish integrity when every signer and key is trusted and the key is protected, but it does not make arbitrary external pickle data safe for a public endpoint.
If the product only needs a filter containing a status and time range, use a data-only format and validate the schema:
from datetime import date
ALLOWED_STATUSES = {"open", "closed", "pending"}
def parse_filter(payload: dict) -> dict:
if set(payload) != {"status", "from_date"}:
raise ValueError("Unexpected filter fields")
status = payload["status"]
if not isinstance(status, str) or status not in ALLOWED_STATUSES:
raise ValueError("Invalid status")
raw_date = payload["from_date"]
if not isinstance(raw_date, str) or len(raw_date) != 10:
raise ValueError("Invalid date")
return {"status": status, "from_date": date.fromisoformat(raw_date)}
JSON parsing by itself is not authorization or complete validation. The parsed fields still need bounds and business rules, and a status filter may leak records if the subsequent query omits a tenant predicate. The improvement is that the input contains data that the application validates and interprets through fixed code, not a serialized object graph capable of behavior.
In other languages, unsafe deserialization may appear as generic object mapping, custom type annotations, polymorphic class names, or framework-specific "restore state" helpers. Do not assume every deserialize call is exploitable. Ask whether the input can select types or behavior, whether the object graph includes gadgets with side effects, and whether a safer data representation meets the requirement. OWASP's Deserialization Cheat Sheet gives language-specific guidance.
The integrity question
Reviewers often hear, "This blob comes from our own database." Trace who could write that row. Could a user save the blob through a profile setting? Could a third-party webhook update it? Could another compromised tenant access the cache key? Could an attacker replace a file in a shared directory? The immediate source may be internal storage while the original author remains outside the trust boundary.
Where a signed serialized format is necessary, verify key ownership, rotation, algorithm choice, and what the signature covers. Do not use "signed" as a synonym for "authorized." A signature proves a particular issuer generated or approved bytes; it does not prove the current user may perform an action represented by those bytes.
Filesystem operations: when a name becomes a path
Applications often accept an upload name, export label, report ID, or archive entry and turn it into a path. The danger is not limited to the familiar sequence "..". The security rule is that the caller may select only an intended object inside an intended storage boundary, even after path normalization, symbolic links, alternative separators, archive extraction, and races are considered.
Read this TypeScript example:
import { readFile } from 'node:fs/promises';
import path from 'node:path';
const REPORT_ROOT = '/srv/app/reports';
export async function downloadReport(request: Request) {
const url = new URL(request.url);
const name = url.searchParams.get('name') ?? '';
const filePath = path.join(REPORT_ROOT, name);
const bytes = await readFile(filePath);
return new Response(bytes);
}
The source is name in the URL. The transformation is path.join(). The sink is readFile(). path.join normalizes a path; it does not authorize the resolved file. A reviewer should identify both possible confidentiality impact and the file-read permission of the server process. The same pattern with writeFile(), unlink(), or archive extraction may affect integrity or availability instead.
A strong design uses an opaque, validated identifier to look up a stored server-controlled path and checks ownership of the selected record:
export async function downloadReport(request: Request, session: Session) {
const url = new URL(request.url);
const reportId = url.searchParams.get('reportId');
if (!reportId || !/^[a-z0-9]{24}$/.test(reportId)) {
return new Response('Invalid report', { status: 400 });
}
const report = await database.report.findFirst({
where: { id: reportId, ownerId: session.userId },
});
if (!report) return new Response('Not found', { status: 404 });
const bytes = await objectStore.get(report.storageKey);
return new Response(bytes, { headers: { 'Content-Type': 'application/pdf' } });
}
The caller chooses a report ID but not a filesystem path. The query binds ownership to the authenticated actor. The storage key is generated by the server and should not be writable through an untrusted field. This example assumes objectStore.get and session are correctly implemented; a real review checks those boundaries as well.
If a filesystem path must include a user-controlled component, a reviewer should ask for a precise containment strategy: normalize and compare paths according to the platform, reject absolute paths and separators where they are not needed, avoid following untrusted symlinks, constrain allowed extensions and lengths, and account for the possibility that a file changes between validation and use.
A simple prefix check on raw strings is not sufficient: "/srv/reports-old" starts with "/srv/reports" but is not inside it. Prefer a design that never accepts a path when an object ID would do.
Archive entries and temporary files
The file boundary also appears in ZIP or TAR extraction. An archive entry may contain a nested path; extracting it without validating its destination can write outside the extraction root. Symlinks inside archives can complicate checks. A reviewer should examine the archive library's extraction semantics, not assume it rejects dangerous entries. Temporary files deserve similar attention: predictable names, shared directories, and a later rename can create races or unintended overwrite. The question is always who chooses the destination at the time of the sensitive operation.
Unsafe HTML rendering: when text becomes browser code
Many web frameworks escape text by default. The dangerous pattern is bypassing that protection through raw HTML APIs, manual template concatenation, or a component that treats a string as trusted markup. The same user-supplied message can be safe in a text node and unsafe when interpreted by an HTML parser.
function showComment(container: HTMLElement, comment: string) {
container.innerHTML = '<p>' + comment + '</p>';
}
The source is comment, which may be saved earlier. The transformation builds an HTML fragment; innerHTML is the sink. The browser parses the result as markup, including any syntax the comment contains. A reviewer should trace the origin of comment and the display context, then look for a safer rendering API.
function showComment(container: HTMLElement, comment: string) {
const paragraph = document.createElement('p');
paragraph.textContent = comment;
container.replaceChildren(paragraph);
}
textContent treats comment as text rather than HTML. If the product truly needs user-authored rich text, a reviewed HTML sanitizer with a narrow allowlist may be appropriate, followed by careful handling of URL schemes and any later DOM transformations. Sanitization is not interchangeable with encoding: encoding preserves text in a specific output context; sanitization permits a controlled subset of markup. Avoid placing user data into event handlers, script blocks, CSS, or arbitrary URL destinations.
OWASP's XSS Prevention Cheat Sheet explains why the correct defense depends on the browser context.
Context is the deciding factor
Do not write "HTML escape all input" as a universal fix. A value rendered as ordinary HTML text needs a different treatment from a value inside a quoted attribute, URL, JavaScript string, CSS value, or raw HTML editor. Many frameworks already encode normal text; manually pre-encoding at input may double-encode harmless content and leave an unsafe alternate output path. Trace the value to the exact rendering API and choose the control there.
A user name can be safe in one component and dangerous in another if the second uses a raw HTML escape hatch.
Replace an open-ended interpreter with a fixed operation
The product needs only a count or a total. Identify how the fixed dispatcher narrows the caller’s capability.
operation = request.json["operation"]
exec(operation, {"rows": rows})
Reveal the safer implementation
operations = {
"count": lambda rows: len(rows),
"total": lambda rows: sum(row.amount for row in rows),
}
name = request.json["operation"]
if not isinstance(name, str) or name not in operations:
raise BadRequest("Unknown operation")
result = operations[name](authorized_rows)
The caller chooses a name from a fixed map, while the server owns the executable behavior. authorized_rows must come from a separately enforced access policy. This is a teaching example for a fixed feature, not a sandbox for arbitrary Python.
A cross-pattern review of one feature
Imagine a customer support tool with a "saved report" feature. A customer saves a filter, an administrator imports a template bundle, and the server renders an HTML preview. The implementation includes these fragments in different files:
#file: api.py
def preview(request):
saved = repository.load(request.user.id, request.json["report_id"])
return renderer.preview(saved)
#file: repository.py
def load(user_id, report_id):
row = db.execute(
"SELECT payload FROM saved_reports WHERE owner_id = ? AND id = ?",
(user_id, report_id),
).fetchone()
return row["payload"] if row else None
#file: renderer.py
def preview(payload):
report = pickle.loads(payload)
namespace = {"report": report}
exec("title = " + report.title_expression, namespace)
return html_response("<h1>" + namespace["title"] + "</h1>")
The repository query is parameterized and scoped to the owner. That is good, but it does not make the whole feature safe. The saved payload may have been written by the customer; unpickling it may execute behavior. The title_expression may become Python code through exec(). The resulting title may become HTML markup. The review needs three independent boundaries. Fixing one does not erase the others.
An effective review comment separates them:
- Deserialize data safely. Store a data-only schema such as JSON with explicit fields and bounds. Do not unpickle customer-controlled bytes.
- Select behavior explicitly. Store a permitted title template ID or fixed operation, not Python source to execute.
- Render text in its context. Use the framework's escaped text component or a text node, not HTML concatenation.
This example demonstrates why "the database query is safe" does not settle a feature review. Security properties attach to particular crossings. A path can contain one safe crossing and several unsafe ones. Conversely, finding an unsafe API call in an unreachable debug function does not establish a reachable vulnerability. Follow the data, actor, and execution path.
How to decide whether a suspicious pattern is exploitable
In code review, an alarming function is evidence of risk, not the entire finding. Ask the following in order:
- Reachability: Can a real actor invoke the path in a supported deployment? Is it a test helper, a startup migration, an administrator-only operation, or a public request?
- Control: Which bytes can that actor choose? Are they direct request fields, stored fields, files, or responses from another service?
- Transformation: Does a parser or validator reduce the value to a fixed safe form? Is that control applied on this path and before the sink?
- Interpretation: Does the sink parse the value as instructions, select a file, create behavior, or merely store or display inert data?
- Privilege: What can the interpreter or operation access? A process running with broad filesystem and network privileges creates a larger impact than an isolated worker.
- Evidence: Can you construct a safe, non-destructive test that proves the boundary? Which code lines and test assertions support your conclusion?
Use cautious language when evidence is incomplete. "The public route appears to pass user-controlled expression text to exec(); I could not verify whether an upstream allowlist restricts it" is more useful than claiming confirmed remote code execution without tracing the allowlist. If a compensating control exists, determine whether it is mandatory, comprehensive, and tested. If it is only a UI restriction, it does not protect the backend.
A review worksheet
For each candidate, write:
Actor: A signed-in customer. Source: Saved title expression supplied through the report API. Path: API → repository → renderer. Sink: Python exec(). Boundary: Customer data must not become Python source. Evidence: The renderer concatenates the stored value into source text; the API schema accepts a string without mapping it to a fixed operation. Impact to verify: Code execution under the renderer's service account, dependent on deployment permissions. Fix: Replace expression execution with an allowlisted operation or data-only template.
That paragraph is short because the trace is specific. A longer list of alarming functions without actor, path, and sink would be less actionable.
A process API receives an argument array instead of a shell command string. What still deserves review?
Practice: classify five findings
For each scenario, decide whether the code shown establishes a vulnerability, a safe pattern, or a question that needs more evidence. Explain the source, sink, and missing or present boundary before reading the notes.
- A public route takes a user-selected "sort" value and looks it up in a constant mapping to one of three SQL column names. It then assembles the selected constant column name into a query and binds the search term as a value.
- A scheduled internal job calls exec() on a constant, version-controlled string that defines a fixed helper function. The job accepts no external input, but the process has broad permissions.
- An API reads a base64 field from a POST body and passes the decoded bytes to pickle.loads(), then checks that the returned value is a dict.
- A React component renders a user name as ordinary JSX text. A nearby legacy widget copies the same name into innerHTML after replacing "<" with an empty string.
- A download endpoint takes a report ID, queries by both ID and session user ID, then reads a server-generated object-storage key from the returned row.
Compare your reasoning
- The shown pattern can be safe for injection if the mapping is truly fixed and the query uses the mapped constant. Verify the mapping's values, access scope, and any alternate query path. A user-selected sort direction may need a separate fixed mapping.
- The code shown does not establish an external injection path. Broad process permissions increase the consequence of a future bug, and dynamic execution may be unnecessary, but a finding must not claim attacker-controlled execution without a source.
- This is an unsafe deserialization path. The later dict check happens after unpickling. Base64 changes encoding, not trust. Replace the format with validated data where feasible.
- The ordinary JSX text is normally escaped by React. The legacy widget is suspicious: deleting "<" is not a complete, context-aware control and may alter benign names. Verify exactly how the browser interprets the assembled HTML; replace raw HTML with a text API.
- The shown design has strong object selection boundaries, assuming the session and storage key are trustworthy. Verify the row's storage key cannot be set by another user and that storage access is scoped.
If you disagreed, write down what evidence would change your answer. The purpose is to avoid both false confidence and false positives.
Apply the method to a real code case
Open the RCE code review challenge. Your task is to identify the remote code execution path yourself. Before selecting a line, write a short trace:
- Which actor can reach the feature, and which input or stored value can that actor influence?
- Which helper transforms that value?
- Which operation interprets it as code or commands?
- What privileges would that operation have in the deployment shown?
- What safer design would preserve the intended feature without executing untrusted syntax?
Do not assume the answer is the first function whose name sounds dangerous. Follow the input to the sensitive operation and confirm the failure at the trust boundary. If the case uses a function named exec, determine which language and runtime that function belongs to; Python's exec() and a shell-executing API have different behavior even when the security principle is similar.
Worked review: a configurable export pipeline
The next exercise combines several patterns in one invented feature. A customer can create an export profile containing a title, a sort field, and a filename. A scheduled worker later creates a CSV file. Read the code as if you were reviewing a change to the worker. The request handler is shown because the worker's database input was once supplied by a customer.
def save_profile(request, db):
profile = {
"tenant_id": request.session.tenant_id,
"title": request.json["title"],
"sort": request.json["sort"],
"filename": request.json["filename"],
}
db.export_profiles.insert(profile)
return accepted()
def run_export(profile_id, db, storage):
profile = db.export_profiles.get(profile_id)
sql = "SELECT * FROM orders ORDER BY " + profile["sort"]
rows = db.execute(sql).fetchall()
filename = "/srv/exports/" + profile["filename"]
storage.write_csv(filename, rows, title=profile["title"])
return filename
Start by describing what is known. The fields are persisted through a request handler, so the worker receives stored user input, not trusted configuration. The source is the profile creation request; the database is a storage hop. There are two distinct interpreter questions. The sort field enters SQL grammar after ORDER BY, where a value placeholder usually cannot stand in for a column identifier. The filename enters a filesystem path.
The title may or may not be dangerous: that depends on how write_csv serializes a title. It could be a plain CSV cell, an HTML preview, or a formula interpreted by spreadsheet software. The code shown does not establish the title sink, so mark it as a follow-up question, not a confirmed third injection.
The SQL query has another concern separate from concatenation: it selects all orders without a tenant predicate. A reviewer should not combine that with the sort injection as though they were the same root cause. First determine whether the worker has a tenant-specific database view or whether every profile exports every order. If not, it may be a cross-tenant data exposure even if the sort field is perfectly validated. Findings should point to the independent broken rules so each fix can be verified.
For the sort field, ask whether the application has a small supported set such as newest, oldest, and amount. If so, map the public names to fixed SQL fragments. A good mapping does not simply reject quotes and semicolons; it decides which complete column and direction combinations the product permits. For the filename, an opaque server-generated identifier is often simpler than accepting a name that becomes a path.
If users must choose a download name, keep that display name as metadata while writing to a server-generated storage key. Check the storage API's behavior with symlinks, absolute paths, and overwrite semantics before claiming a path check is sufficient.
SORT_SQL = {
"newest": "created_at DESC",
"oldest": "created_at ASC",
"amount": "total_amount DESC",
}
def run_export(profile_id, db, storage):
profile = db.export_profiles.get(profile_id)
sort_sql = SORT_SQL.get(profile["sort"])
if sort_sql is None:
raise ValueError("Unsupported sort")
rows = db.execute(
"SELECT id, total_amount, created_at FROM orders "
"WHERE tenant_id = ? ORDER BY " + sort_sql,
(profile["tenant_id"],),
).fetchall()
storage.write_csv_by_key(
"exports/" + profile["tenant_id"] + "/" + new_random_id(),
rows,
display_name=profile["filename"],
title=profile["title"],
)
This revision shows two different boundaries. The sort key chooses a trusted fragment; the tenant ID remains a bound value. The storage key is generated by the server, while the user's filename is display metadata. The code is still a review sketch, not a complete production implementation.
The reviewer must verify that profile.tenant_id was assigned by the server on creation, that the worker cannot be asked to run another tenant's profile without permission, and that the storage API treats the generated key as a key rather than an arbitrary local path. Also inspect how a CSV consumer treats the title and other string cells; formula injection is a separate output-context issue if spreadsheet software interprets leading formula characters.
Now write an evidence table for the original version. Mark the SQL grammar and path selection as demonstrated unsafe designs because the shown source and sinks connect. Mark actual cross-tenant export as conditional on database isolation, and title interpretation as unknown until write_csv is inspected. This distinction matters in code review: the team can act on a design flaw immediately without inventing a payload or exaggerating every possible downstream consequence.
Which review note is a hypothesis rather than a confirmed vulnerability?
Review calibration: scary names, harmless uses, and missed paths
A good reviewer does not label every use of a dangerous API equally. Consider a migration script containing exec() with a constant string defined in source control. If only a release engineer can change that string, the code path may still be brittle and difficult to audit, but it is not the same remote input path as request text passed to exec(). State the difference.
Conversely, a helper called loadPreset() may fetch a customer-controlled database value and pass it to pickle.loads. The harmless name and trusted-looking database wrapper do not remove the untrusted origin.
Use three questions to calibrate a finding. First, can the attacker influence the bytes at the sink? Include indirect paths through stored records, queue messages, caches, and imported files. Second, does the sink interpret those bytes as structure or merely preserve them as data? A parameterized SQL driver preserves a value; a string-assembled query lets it affect grammar.
Third, what authority does the sink have? A local test process with no sensitive data and a production worker with credentials have different impact even when the same code is present.
A common false positive is a fixed command with a user value passed as a distinct argument to a program that treats it strictly as data. The argument array is relevant evidence, but the review is incomplete until you check whether the program interprets that argument as an option or filename with special meaning.
A common false negative is a template or Markdown renderer that looks like presentation code yet allows raw HTML, scriptable URLs, or unsafe components. You have to inspect renderer options and output context, not just the framework name.
When a team says a validator protects a sink, read the validator's exact contract. A regex that allows letters and digits may be adequate for a simple output basename but irrelevant to a SQL sort expression that needs only a fixed enum. A path normalization helper may prevent one form of traversal while still allowing symlink escape or overwrite. An HTML sanitizer might be configured for body fragments but reused inside an attribute or URL.
Write down the accepted alphabet, normalization order, and final parser context; only then can you say the validation matches the sink.
For a final self-check, revisit the five patterns in this lecture and classify each by interpreter. SQL concatenation goes to a database query parser. Python exec() goes to the Python interpreter. Pickle loading goes to object reconstruction with executable behavior. A filename goes to filesystem resolution and access checks. Unsafe HTML goes to the browser's HTML and script interpretation. This classification yields actionable replacements: bind values, map permitted operations, parse data-only formats, generate controlled storage keys, and render text in the right output context.
Key takeaways
- A dangerous pattern matters when an attacker-controlled value reaches a sink that interprets it or selects a protected resource.
- Keep untrusted values as values: bind database parameters, pass process arguments without a shell, map operation names to fixed functions, parse data-only formats, select files through server-controlled identifiers, and render text as text.
- Python's exec() executes Python code. It is not a safe parser or sandbox for user input.
- A validator is meaningful only when it enforces the property required by the specific destination.
- Trace each boundary separately. A safe query does not make later deserialization, execution, or HTML rendering safe.
Glossary
Source: A value an attacker can influence, including stored data or data received through another service.
Sink: An operation where that value may affect code execution, a query, a filesystem action, or rendered output.
Interpreter: A component that assigns syntax and behavior to input, such as a SQL engine, shell, Python runtime, template engine, or browser HTML parser.
Parameterization: Keeping a command or query structure fixed while supplying values through an API designed for arguments.
Deserialization: Reconstructing data or objects from stored or transmitted bytes; some formats can reconstruct behavior.
Path traversal: Choosing a filesystem target outside the intended root through path components, normalization, links, or extraction behavior.
Output encoding: Representing data so a specific output parser treats it as data in a specific context.
Frequently asked questions
Is every use of exec() a vulnerability?
No. The key question is whether an attacker can influence executable code that reaches it and what that code can access. A constant internal string is not the same as request-derived Python source. Even when no attacker path exists, replacing unnecessary dynamic execution can simplify maintenance and reduce future risk.
Is filtering dangerous characters enough before dynamic execution?
Usually not. General-purpose language grammars are too rich for a small denylist to be a reliable sandbox. Define the operations the product actually permits and implement or select those operations through fixed code.
Does JSON automatically make deserialization safe?
JSON normally represents data rather than arbitrary Python objects, which is an important difference from pickle. It can still carry unbounded or invalid data, and the resulting values can be misused later in SQL, HTML, paths, authorization decisions, or resource-intensive operations. Parse, validate, authorize, and use it in the correct context.
Does using an argument array make process execution safe?
It avoids shell parsing of argument values when the process API truly invokes the executable directly. The executable may still interpret options, paths, URLs, or configuration values dangerously. Fix the executable path, validate arguments for that program, and run with limited privileges.
Where should I look first in a large review?
Start at changed entry points and search for calls that interpret strings or select resources. Trace one call upstream to find attacker control and one call downstream to find impact. Then expand across helpers, storage, and background jobs as evidence requires.