Notes
SQL injection
First, SQL injection. In Python the usual culprit is an f-string or percent formatting that drops user input straight into a query. The fix is parameters: pass placeholders and a tuple of values, and let the database driver bind them safely. Note the placeholder style is the driver's, not Python's string formatting. ORMs like Django and SQLAlchemy parameterise for you, but their raw query escape hatches, raw and text, reintroduce the risk if you format input into them.
# WRONG: formatted into SQL
cur.execute(f"select * from u
where name = '{name}'")
# RIGHT: parameters, driver binds
cur.execute("select * from u
where name = %s", (name,))
# ORMs: Django/SQLAlchemy bind for
# you; raw()/text() can reintroduce it Command injection
Command injection is next. Running a command with shell equals true and a formatted string means a shell parses it, so an attacker adds a semicolon or pipe and runs their own commands. The fix is to pass the command as a list of arguments with no shell, so the program receives the host as a single argument and nothing is interpreted. Never pass user input through os dot system or shell equals true. If you truly need a shell feature, validate the input against a strict allowlist first.
# WRONG: a shell parses this
subprocess.run(f"ping {host}",
shell=True)
# RIGHT: arguments as a list,
# no shell involved
subprocess.run(["ping", "-c", "1",
host])
# never pass user input to
# os.system or shell=True Dangerous functions
A family of functions turns data into code, and must never touch untrusted input. Eval and exec run arbitrary code. Pickle's loads runs code during deserialisation, like Java's problem, so never unpickle outside data. The plain yaml dot load can instantiate objects; always use safe load. The safe replacements are specific: ast dot literal eval for a Python literal, json for data interchange, and yaml safe load for YAML. If you are reaching for eval, there is almost always a better way.
- eval() / exec(): run arbitrary code; almost never needed
- pickle.loads(): deserialising runs code (like Java)
- yaml.load(): use yaml.safe_load
- input() in Python 2: evaluated
- use: ast.literal_eval for literals, json for data, safe_load for YAML
SSRF and requests
Server-side request forgery appears wherever Python fetches a URL, usually with the requests library. If the URL comes from the user, an attacker points it at internal services or the cloud metadata endpoint. The fix is the same as in any language: allowlist the host and scheme, resolve the DNS and check the address is not private, and be aware that requests follows redirects by default, which can bypass a naive check. And never set verify equals false, which disables TLS certificate checking entirely.
- requests.get(user_url): SSRF to internal hosts and cloud metadata
- fix: allowlist host and scheme, resolve and check the IP, block private ranges
- also: requests follows redirects by default
- verify=False disables TLS checks: never do it
Path traversal
Path traversal happens when a user controls part of a file path. Joining a base directory with a user-supplied name looks safe, but a name containing dot dot slash escapes upward to files like the system password file. The fix is to resolve the final path and confirm it still sits inside the intended base directory before opening it, and to validate the filename against an allowlist of characters. The same care applies to extracting archives, where a crafted entry name can write outside the target directory.
# WRONG: user controls the path
open(os.path.join(base, name))
# name = "../../etc/passwd"
# RIGHT: resolve and confirm it
# stays inside base
p = (base / name).resolve()
if not p.is_relative_to(base):
raise ValueError
# also validate the filename Template injection
Template injection is a Python-flavoured trap. Rendering a user-supplied string as a template, such as render template string, lets an attacker reach Python objects and run code. Pass user input as data to a fixed template; never let users supply the template text. Keep Jinja's autoescaping on to prevent cross-site scripting, and avoid the safe filter on untrusted data. And in Flask, never run with debug equals true in production, which exposes a console to attackers.
- SSTI: never render a user string AS a template render_template_string(user)
- pass data to the template, not template text from users
- keep Jinja autoescaping on; {% autoescape %} and avoid |safe on untrusted data
- Flask: never put secrets or debug=True in production
Defaults and the rest
A few more, briefly. Validate input with a library like pydantic or your framework's validators, on the server. For XML, the standard library parsers are unsafe by default, so use the defusedxml package to block external entity attacks. For tokens, keys and password resets, use the secrets module, never the random module, as we saw in Part three. Keep secrets in environment variables or a vault, never in code. And run the security linters Bandit and pip-audit in your pipeline to catch most of this automatically.
- validate with pydantic or framework validators, on the server
- XML: use defusedxml to block XXE (stdlib parsers are unsafe by default)
- tokens/keys: secrets module, never random
- secrets: env vars or a vault, never in code or git
- run Bandit and pip-audit in CI
Common mistakes
The recurring Python findings. F-strings or percent formatting building SQL. Shell equals true with user input. Eval, exec, pickle or plain yaml load on untrusted data. The requests library with verify equals false, or fetching an unchecked user URL. User-controlled file paths. Rendering user input as a template, or running Flask with debug on in production. And the random module used for security tokens, or secrets committed in code. Linters catch most of these, so run them.
- f-strings or % building SQL
- shell=True with user input
- eval, exec, pickle, yaml.load on untrusted data
- requests with verify=False or an unchecked user URL
- user-controlled file paths
- rendering user input as a template; debug=True
- random for tokens; secrets in code
Say it like this
In the interview: I parameterise SQL rather than f-strings. I never use shell equals true; I pass arguments as a list. I never eval, exec, pickle or plainly yaml-load untrusted data, using literal eval, json or safe load. I allowlist and check URLs to prevent SSRF, confine user-controlled file paths to a base directory, keep template autoescaping on, use the secrets module for tokens, and run Bandit and pip-audit. Most Python security bugs come from a short list, and this is it.
- "Parameterise SQL, never
- f-strings. No shell=True; pass
- args as a list. Never eval, pickle or yaml.load untrusted
- data; use literal_eval, json, safe_load. Allowlist URLs for SSRF, confine file paths, keep autoescaping on, use the secrets module, and run Bandit
- and pip-audit."