Application security
suggest changeMost security bugs in Python applications don't come from broken cryptography. They come from a handful of everyday mistakes: building SQL or shell commands out of strings, unpickling data from the network, joining user-supplied file names to a directory, putting secrets in logs, or trusting a URL the user typed. They all have the same root cause: data from outside the program gets treated as code or as a trusted value.
This article goes through the common classes of vulnerabilities and shows the vulnerable code, an attack on it, and the fix. The rules of thumb behind all of them:
- Treat all external input as hostile. That means request parameters, headers, cookies, uploaded files, environment variables set by others, database contents written by users, and responses from other services.
- Keep data and code apart. Use APIs that take data as separate arguments (query parameters, argument lists, templates with autoescaping) instead of gluing strings together.
- Validate with allow-lists. Say what is allowed (
idis an int,sortis one of three column names) rather than trying to list everything bad. - Fail closed. If a check can't decide, reject.
- Least privilege. Run with the minimum database rights, file permissions and network access the code needs, so a bug does less damage.
All examples were run with Python 3.13, Jinja2 3.1, defusedxml 0.7 and bandit 1.9.
SQL injection
Formatting user input into SQL lets the input change the query:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, is_admin INTEGER)")
db.executemany("INSERT INTO users (name, is_admin) VALUES (?, ?)",
[("alice", 1), ("bob", 0), ("carol", 0)])
def find_user_bad(name):
sql = f"SELECT id, name FROM users WHERE name = '{name}'"
print("SQL:", sql)
return db.execute(sql).fetchall()
def find_user(name):
return db.execute("SELECT id, name FROM users WHERE name = ?", (name,)).fetchall()
print(find_user_bad("bob"))
print(find_user_bad("x' OR '1'='1"))
print(find_user("x' OR '1'='1"))
print(find_user("bob"))
SQL: SELECT id, name FROM users WHERE name = 'bob'
[(2, 'bob')]
SQL: SELECT id, name FROM users WHERE name = 'x' OR '1'='1'
[(1, 'alice'), (2, 'bob'), (3, 'carol')]
[]
[(2, 'bob')]
The input x' OR '1'='1 closes the string literal and adds a condition that is always true, so the "find one user" query returns every row. With other inputs an attacker can read other tables (UNION SELECT ...) or, with drivers that allow multiple statements, modify data.
The fix is to always pass values as parameters. The driver sends them separately from the SQL text (or escapes them correctly), so they can never become SQL syntax. Each DB-API driver has its own placeholder style: ? or :name for sqlite3, %s or %(name)s for psycopg and MySQL drivers. Note that %s in psycopg is a placeholder, not Python string formatting: pass the values as the second argument to execute(), never use % or f-strings yourself.
Placeholders work only for values. Table names, column names, ASC/DESC and the number of items in an IN (...) list can't be parameters. Build those parts from an allow-list and generate the right number of placeholders:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, created TEXT)")
db.executemany("INSERT INTO users (name, created) VALUES (?, ?)",
[("carol", "2026-03-01"), ("alice", "2026-01-15"), ("bob", "2026-02-10")])
SORTABLE = {"name": "name", "created": "created", "id": "id"}
def list_users(order_by="id", descending=False, names=None):
column = SORTABLE.get(order_by)
if column is None:
raise ValueError(f"cannot sort by {order_by!r}")
sql = "SELECT name FROM users"
params = []
if names:
placeholders = ", ".join("?" * len(names))
sql += f" WHERE name IN ({placeholders})"
params.extend(names)
sql += f" ORDER BY {column} {'DESC' if descending else 'ASC'}"
return [r[0] for r in db.execute(sql, params)]
print(list_users("created"))
print(list_users("name", descending=True, names=["alice", "bob"]))
try:
list_users("name; DROP TABLE users")
except ValueError as e:
print("ValueError:", e)
# named parameters
row = db.execute("SELECT id FROM users WHERE name = :name", {"name": "bob"}).fetchone()
print(row)
['alice', 'bob', 'carol']
['bob', 'alice']
ValueError: cannot sort by 'name; DROP TABLE users'
(3,)
ORMs and query builders such as SQLAlchemy parameterize for you, but they also have escape hatches (text(), .raw(), .extra()) where the same rules apply. See sqlite3 module for more on the DB-API.
Command injection
shell=True hands the whole string to a shell (/bin/sh on Unix, cmd.exe on Windows), which interprets ;, &&, |, $(...), backticks and redirections:
import shlex
import subprocess
import sys
user_input = "report.txt && echo INJECTED"
# BAD: the string is interpreted by a shell (sh on Unix, cmd.exe on Windows)
r = subprocess.run(f"echo {user_input}", shell=True, capture_output=True, text=True)
print("shell=True:", r.stdout.splitlines())
# GOOD: a list of arguments, no shell; the input is one argument, whatever it contains
show_args = [sys.executable, "-c", "import sys; print(sys.argv[1:])"]
r = subprocess.run([*show_args, user_input], capture_output=True, text=True, check=True)
print("list args: ", r.stdout.strip())
# if you truly need a POSIX shell, quote every untrusted piece
print(shlex.quote(user_input))
print(shlex.join(["grep", "-r", user_input, "logs/"]))
shell=True: ['report.txt ', 'INJECTED']
list args: ['report.txt && echo INJECTED']
'report.txt && echo INJECTED'
grep -r 'report.txt && echo INJECTED' logs/
With a list of arguments and no shell, the program receives user_input as a single argument no matter what characters it contains. This is the default for subprocess.run(), so the rule is simply: pass a list and don't use shell=True. The same goes for os.system() and os.popen(), which always use a shell. Avoid them.
If you need shell features like pipes, either chain two subprocess.run() calls in Python, or quote every untrusted piece with shlex.quote() / shlex.join(). These quote for POSIX shells only; they don't protect you from cmd.exe.
A list of arguments doesn't protect against argument injection. If an attacker controls a value that starts with -, the tool may treat it as an option:
import subprocess
import sys
# a stand-in for any CLI tool that takes options and file names
tool = """
import argparse
p = argparse.ArgumentParser()
p.add_argument("--force", action="store_true")
p.add_argument("files", nargs="*")
a = p.parse_args()
print(f"force={a.force} files={a.files}")
"""
filename = "--force" # a "file name" chosen by an attacker
cmd = [sys.executable, "-c", tool]
print(subprocess.run([*cmd, filename], capture_output=True, text=True).stdout, end="")
print(subprocess.run([*cmd, "--", filename], capture_output=True, text=True).stdout, end="")
force=True files=[]
force=False files=['--force']
Most tools stop parsing options at --, so put it before untrusted file names, or reject values that start with -. Real examples are git options like --upload-pack=... and tar --checkpoint-action=exec=..., which run arbitrary commands. Also pass a full path to the executable, or make sure PATH is under your control, so a planted git.exe in the working directory isn't run instead. More on running programs in Subprocess Library.
Code injection: eval, exec and pickle
eval() and exec() run any Python code, so calling them on input is remote code execution. Restricting __builtins__ doesn't make them safe: there are well-known ways to get back to os through object attributes. To turn text into data, use a parser that only understands data:
import ast
import json
# BAD: eval() runs any expression, including imports and function calls
payload = "__import__('sys').version_info[:2]" # could be os.system("...")
print(eval(payload))
for text in ["[1, 2, {'a': (3, 4)}]", "__import__('os').getcwd()"]:
try:
print(ast.literal_eval(text))
except ValueError as e:
print("literal_eval refused:", str(e).split(":")[0])
print(json.loads('{"a": [1, 2, 3]}'))
(3, 13)
[1, 2, {'a': (3, 4)}]
literal_eval refused: malformed node or string on line 1
{'a': [1, 2, 3]}
ast.literal_eval() accepts only literals: strings, bytes, numbers, tuples, lists, dicts, sets, booleans and None. json.loads() is even stricter and is the right choice for anything that comes over the network. See ast.literal_eval.
pickle is just as dangerous as eval. A pickle is a small program for a stack machine, and loading it can call any function:
import pickle
class Exploit:
def __reduce__(self):
# pickle will call print(...) while loading; an attacker would use os.system
return (print, ("code ran during pickle.loads()!",))
data = pickle.dumps(Exploit())
print(data[:40])
obj = pickle.loads(data) # never unpickle data you didn't produce yourself
print("loaded:", obj)
b'\x80\x04\x95<\x00\x00\x00\x00\x00\x00\x00\x8c\x08builtins\x94\x8c\x05print\x94\x93\x94\x8c\x1fcode r'
code ran during pickle.loads()!
loaded: None
The attacker's object never even needs to exist in your code: __reduce__ tells pickle.loads() to call print, and it could just as well name os.system. The same applies to everything built on pickle: shelve, pandas.read_pickle(), joblib.load(), torch.load() with weights_only=False, and multiprocessing connections. Rules:
- Never unpickle data that came from users, the network, or a shared location others can write to. Use JSON, MessagePack or Protocol Buffers instead.
- If you must store pickles somewhere you don't fully trust (such as a cache), sign them with HMAC (see below) and check the signature before calling
loads(). - YAML has the same problem: use
yaml.safe_load(), neveryaml.load()with the unsafeLoader.
More in Pickle data serialization.
Path traversal
Joining a user-supplied name to a directory is not safe. .. components walk out of the directory, and joining an absolute path to a Path throws away the base entirely:
import tempfile
from pathlib import Path
base = Path(tempfile.mkdtemp()) / "uploads"
(base / "docs").mkdir(parents=True)
(base / "docs" / "a.txt").write_text("hello")
(base.parent / "secret.txt").write_text("top secret")
def read_upload_bad(name):
return (base / name).read_text() # BAD: "../secret.txt" escapes base
def safe_path(root, name):
root = root.resolve()
p = (root / name).resolve()
if not p.is_relative_to(root):
raise PermissionError(f"path escapes {root.name}/: {name!r}")
return p
print(read_upload_bad("../secret.txt"))
absolute = str(base.parent / "secret.txt") # base / "/abs/path" ignores base!
for name in ["docs/a.txt", "../secret.txt", "docs/../../secret.txt", absolute]:
try:
print("ok:", safe_path(base, name).read_text())
except PermissionError as e:
print("PermissionError:", e if name != absolute else "absolute path refused")
top secret
ok: hello
PermissionError: path escapes uploads/: '../secret.txt'
PermissionError: path escapes uploads/: 'docs/../../secret.txt'
PermissionError: absolute path refused
The fix is to resolve the final path (which collapses .. and follows symlinks) and check it is still inside the base directory with Path.is_relative_to(). Don't compare strings with startswith(): /srv/uploads-old starts with /srv/uploads. Better still, don't use user-provided names for storage at all: save uploads under a random name (secrets.token_hex(16)) and keep the original name in the database.
Archives have the same problem ("zip slip"): a member named ../../.bashrc or an absolute path or a symlink can write anywhere. Since Python 3.12, tarfile has extraction filters. The "data" filter refuses paths outside the destination, links pointing outside it, device files, and it strips setuid bits. It becomes the default in Python 3.14, but pass it explicitly to be safe on older versions:
import io
import tarfile
import tempfile
from pathlib import Path
# build a malicious archive in memory
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as tar:
for name in ["ok.txt", "../escaped.txt"]:
info = tarfile.TarInfo(name)
data = b"payload"
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
dest = Path(tempfile.mkdtemp()) / "out"
buf.seek(0)
with tarfile.open(fileobj=buf) as tar:
try:
tar.extractall(dest, filter="data")
except tarfile.FilterError as e:
print(type(e).__name__, "for", repr(e.tarinfo.name))
print(sorted(p.name for p in dest.parent.rglob("*")))
OutsideDestinationError for '../escaped.txt'
['ok.txt', 'out']
zipfile.extractall() already removes .. and leading slashes from member names, but it doesn't limit the total size. Check ZipInfo.file_size for each member before extracting so a small "zip bomb" can't fill the disk. See Using Python TarFile.extractall.
XML
XML parsers support entities, which enable two attacks. "Billion laughs" uses nested entities that expand a tiny document into gigabytes. XXE (XML external entities) makes the parser read local files or fetch URLs. The standard library's parsers don't fetch external entities, and the bundled expat (2.4.1+) limits entity amplification, but a moderate expansion still gets through. Other libraries, such as lxml, have different defaults. The defusedxml package is a drop-in replacement that rejects entity declarations entirely:
import xml.etree.ElementTree as ET
import defusedxml.ElementTree as DET
def lol_doc(levels):
ents = ['<!ENTITY e0 "lol">']
ents += [f'<!ENTITY e{i} "{f"&e{i-1};" * 10}">' for i in range(1, levels + 1)]
return f"<!DOCTYPE r [{''.join(ents)}]><r>&e{levels};</r>"
print(len(ET.fromstring(lol_doc(4)).text)) # 400-byte doc -> 30,000 chars
try:
ET.fromstring(lol_doc(9)) # would be 3 GB
except ET.ParseError as e:
print("ParseError:", e)
try:
DET.fromstring(lol_doc(4))
except Exception as e:
print(type(e).__name__, e)
print(DET.fromstring("<user><name>bob</name></user>").findtext("name"))
30000
ParseError: limit on input amplification factor (from DTD and entities) breached: line 1, column 531
EntitiesForbidden EntitiesForbidden(name='e0', system_id=None, public_id=None)
bob
Use defusedxml.ElementTree (or defusedxml.lxml, defusedxml.minidom) to parse any XML that comes from outside. Its API matches the standard library's for parsing. Building XML is covered in Manipulating XML.
Cross-site scripting (XSS)
If a web application puts user input into HTML without escaping, the input can contain markup and scripts that run in other users' browsers, with access to their session:
import html
from urllib.parse import quote, urlsplit
from jinja2 import Environment, select_autoescape
from markupsafe import Markup
comment = '<img src=x onerror="alert(document.cookie)">'
print(f"<p>{comment}</p>") # BAD: the browser runs the script
print(f"<p>{html.escape(comment)}</p>") # escapes & < > " '
print(f'<a href="/search?q={quote(comment, safe="")}">')
env = Environment(autoescape=select_autoescape(default_for_string=True))
t = env.from_string("<p>{{ c }}</p> {{ trusted }}")
print(t.render(c=comment, trusted=Markup("<b>ok</b>")))
# escaping doesn't make a URL safe: check the scheme too
for url in ["https://example.com/u/1", "javascript:alert(1)", " JavaScript:alert(1)"]:
ok = urlsplit(url.strip()).scheme.lower() in ("http", "https")
print(repr(url), "->", "allowed" if ok else "rejected")
<p><img src=x onerror="alert(document.cookie)"></p>
<p><img src=x onerror="alert(document.cookie)"></p>
<a href="/search?q=%3Cimg%20src%3Dx%20onerror%3D%22alert%28document.cookie%29%22%3E">
<p><img src=x onerror="alert(document.cookie)"></p> <b>ok</b>
'https://example.com/u/1' -> allowed
'javascript:alert(1)' -> rejected
' JavaScript:alert(1)' -> rejected
- Use a template engine with autoescaping turned on. Jinja2 does this in Flask by default for
.htmltemplates. Django templates always escape. When you create a Jinja2Environmentyourself, autoescaping is off unless you passautoescape=. - Mark something as safe (
Markup,|safe,mark_safe) only if it's HTML your own code produced, never for user input. - Escaping is context-specific.
html.escape()is right for element content and quoted attributes. URLs insidehrefneed the scheme checked, sincejavascript:URLs survive HTML escaping. Data for inline<script>blocks should go throughjson.dumps()and be put in adata-attribute, or use Jinja2's|tojsonfilter. - If users can submit rich HTML (comments with formatting), sanitize it with an allow-list library such as
nh3. Don't write regular expressions to strip tags. - Add a
Content-Security-Policyheader as a second line of defense, and set cookies withHttpOnly(see Cookies).
Secrets, tokens and timing
Tokens that grant access (session IDs, password reset links, API keys, CSRF tokens) must be unguessable. The random module is a Mersenne Twister: fast and fine for simulations, but its output can be predicted after observing about 624 values. Use secrets for anything security related:
import hashlib
import hmac
import random
import secrets
print(secrets.token_urlsafe(32)) # session IDs, reset links, API keys
print(secrets.token_hex(16))
print(secrets.randbelow(1_000_000)) # e.g. a 6-digit one-time code
print("".join(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(8)))
# random is predictable: the same seed gives the same "token"
random.seed(42); a = random.getrandbits(64)
random.seed(42); b = random.getrandbits(64)
print(a == b)
def check_api_key(given: str, expected: str) -> bool:
# == stops at the first differing byte; compare_digest takes the same time
return hmac.compare_digest(given.encode(), expected.encode())
key = secrets.token_urlsafe(32)
print(check_api_key(key, key), check_api_key("guess", key))
# store only a hash of API keys, like passwords (a fast hash is fine for random keys)
stored = hashlib.sha256(key.encode()).hexdigest()
print(hmac.compare_digest(hashlib.sha256(key.encode()).hexdigest(), stored))
hgprOAzmNb9o3EtgUHZBj4y0WCwToNlZUMZsZAFigKc
2c72ef7dd6172ad223d336c0dbf12ef2
74779
TKR8HA4K
True
True False
True
secrets.token_urlsafe(32) gives 256 bits of randomness, encoded so it can go straight into a URL or a cookie. See also Create cryptographically secure random numbers.
Comparing a secret with == returns as soon as one character differs, so the response time leaks how many leading characters were right. Over many requests an attacker can use that to recover the value one character at a time. hmac.compare_digest() takes the same time wherever the difference is. Use it whenever you compare a secret, token, signature or hash with user input.
Password hashing
Passwords need a deliberately slow, salted hash, so that a leaked database can't be cracked quickly. Plain SHA-256 is wrong for passwords: a GPU computes billions per second. The standard library has hashlib.scrypt, which is both slow and memory-hard:
import base64
import hashlib
import hmac
import os
N, R, P = 2**17, 8, 1 # OWASP-recommended scrypt cost
MAXMEM = 256 * 1024 * 1024 # N*R*128 bytes = 128 MiB needed; default limit is 32 MiB
def hash_password(password: str) -> str:
salt = os.urandom(16)
key = hashlib.scrypt(password.encode(), salt=salt, n=N, r=R, p=P, dklen=32, maxmem=MAXMEM)
b64 = lambda b: base64.b64encode(b).decode()
return f"scrypt${N}${R}${P}${b64(salt)}${b64(key)}"
def verify_password(password: str, stored: str) -> bool:
_, n, r, p, salt, key = stored.split("$")
salt, key = base64.b64decode(salt), base64.b64decode(key)
got = hashlib.scrypt(password.encode(), salt=salt, n=int(n), r=int(r), p=int(p),
dklen=len(key), maxmem=MAXMEM)
return hmac.compare_digest(got, key)
h = hash_password("correct horse")
print(h)
print(verify_password("correct horse", h), verify_password("wrong", h))
print(hash_password("correct horse") == h) # random salt: same password, new hash
scrypt$131072$8$1$bY6cr/2fG8lB7Cq7uc20/g==$Fsz02qfntjqj6dMgpBGcBR8CIo8r+E+aTTUwoSizmNY=
True False
False
The parameters are stored with the hash, so you can raise the cost later and rehash on the next successful login. In production the argon2-cffi package (Argon2id, the current OWASP first choice) or bcrypt give you the same thing with less code: PasswordHasher().hash(pw) / .verify(hash, pw). Other things that matter as much as the algorithm: rate-limit login attempts, give the same error for "no such user" and "wrong password", and never log passwords. See also Secure Password Hashing.
Signing data with HMAC
When you hand data to a client and need to know it comes back unchanged, sign it with HMAC. Typical cases are download links, unsubscribe links, stateless session cookies and cache entries. Only someone with the key can produce a valid signature:
import hashlib
import hmac
import time
from urllib.parse import parse_qs, urlencode, urlsplit
SECRET = b"load-me-from-the-environment"
def sign_url(path: str, user_id: int, ttl: int = 3600) -> str:
expires = int(time.time()) + ttl
msg = f"{path}|{user_id}|{expires}".encode()
sig = hmac.new(SECRET, msg, hashlib.sha256).hexdigest()
return f"{path}?{urlencode({'uid': user_id, 'exp': expires, 'sig': sig})}"
def verify_url(url: str) -> int:
parts = urlsplit(url)
q = {k: v[0] for k, v in parse_qs(parts.query).items()}
msg = f"{parts.path}|{q['uid']}|{q['exp']}".encode()
expected = hmac.new(SECRET, msg, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, q["sig"]):
raise PermissionError("bad signature")
if int(q["exp"]) < time.time():
raise PermissionError("link expired")
return int(q["uid"])
url = sign_url("/download/report.pdf", 42)
print(verify_url(url))
for bad in [url.replace("uid=42", "uid=43"),
url.replace("report.pdf", "payroll.pdf"),
sign_url("/download/report.pdf", 42, ttl=-1)]:
try:
verify_url(bad)
except PermissionError as e:
print("PermissionError:", e)
42
PermissionError: bad signature
PermissionError: bad signature
PermissionError: link expired
Sign everything the server relies on, including the path and the expiry time, otherwise an attacker can move a valid signature to a different resource. Use a separate key for each purpose. Signing doesn't encrypt: the user ID is visible in the URL. For tokens that carry claims, use a standard format like JWT (see JWT) or itsdangerous, which is what Flask uses for its session cookie.
Keeping secrets out of code and logs
Credentials committed to a repository stay in its history forever. Load them from the environment or a secrets manager at startup, fail fast if one is missing, and make sure they can't leak through repr(), error pages or logs:
import logging
import os
import re
import sys
from dataclasses import dataclass, field
class Secret:
"""Holds a sensitive string; never shows it in repr, str or f-strings."""
__slots__ = ("_value",)
def __init__(self, value: str):
self._value = value
def get(self) -> str:
return self._value
def __repr__(self):
return "Secret('********')"
__str__ = __repr__
@dataclass(frozen=True)
class Config:
db_url: str
api_key: Secret = field(repr=False)
def load_config() -> Config:
try:
return Config(db_url=os.environ.get("DB_URL", "sqlite:///app.db"),
api_key=Secret(os.environ["API_KEY"]))
except KeyError as e:
sys.exit(f"missing required environment variable {e}")
os.environ["API_KEY"] = "sk_live_9f8e7d6c5b4a" # normally set outside the program
cfg = load_config()
print(cfg)
print(f"using key {cfg.api_key}")
print(len(cfg.api_key.get()))
class RedactFilter(logging.Filter):
PATTERN = re.compile(r"(sk_live_|password=)\S+")
def filter(self, record):
record.msg = self.PATTERN.sub(r"\1[REDACTED]", record.getMessage())
record.args = ()
return True
logging.basicConfig(format="%(levelname)s %(message)s", level=logging.INFO, stream=sys.stdout)
logging.getLogger().handlers[0].addFilter(RedactFilter())
logging.info("calling API with key %s", cfg.api_key.get())
logging.info("login form: user=bob password=hunter2")
Config(db_url='sqlite:///app.db')
using key Secret('********')
20
INFO calling API with key sk_live_[REDACTED]
INFO login form: user=bob password=[REDACTED]
- A wrapper like
Secret(orpydantic.SecretStr) makes accidental printing harmless: you have to call.get()deliberately. - Tracebacks and debug pages print local variables. Never run Flask or Django with debug mode on in production: the Werkzeug debugger lets anyone who can reach it execute code.
- Redact in logging as a safety net, but don't rely on it. Prefer not passing secrets to log calls at all. More on configuring logging in Logging.
- Add a secret scanner (such as
gitleaksor GitHub's push protection) to catch keys before they're committed.
Server-side request forgery (SSRF)
If your server fetches URLs that users provide (webhooks, "import from URL", link previews), an attacker can point it at internal services that are not reachable from outside. The classic targets are cloud metadata endpoints such as 169.254.169.254, which hand out credentials, admin panels on localhost, and databases on the private network. Check the scheme, resolve the host, and reject anything that isn't a public address:
import ipaddress
import socket
from urllib.parse import urlsplit
def check_public_url(url: str) -> list[str]:
"""Raise ValueError unless url is http(s) and its host resolves only to public IPs."""
parts = urlsplit(url)
if parts.scheme not in ("http", "https") or not parts.hostname:
raise ValueError(f"unsupported URL: {url}")
port = parts.port or (443 if parts.scheme == "https" else 80)
try:
infos = socket.getaddrinfo(parts.hostname, port, proto=socket.IPPROTO_TCP)
except socket.gaierror:
raise ValueError(f"cannot resolve {parts.hostname}") from None
addrs = sorted({info[4][0] for info in infos})
for a in addrs:
if not ipaddress.ip_address(a).is_global:
raise ValueError(f"{parts.hostname} resolves to non-public {a}")
return addrs
for url in ["http://93.184.215.14/", "http://localhost:8080/admin",
"http://169.254.169.254/latest/meta-data/", "http://10.0.0.5/",
"http://[::ffff:127.0.0.1]/", "http://evil.example@127.0.0.1/",
"file:///etc/passwd"]:
try:
print("allowed:", url, check_public_url(url))
except ValueError as e:
print("blocked:", e)
allowed: http://93.184.215.14/ ['93.184.215.14']
blocked: localhost resolves to non-public 127.0.0.1
blocked: 169.254.169.254 resolves to non-public 169.254.169.254
blocked: 10.0.0.5 resolves to non-public 10.0.0.5
blocked: ::ffff:127.0.0.1 resolves to non-public ::ffff:127.0.0.1
blocked: 127.0.0.1 resolves to non-public 127.0.0.1
blocked: unsupported URL: file:///etc/passwd
ipaddress.ip_address(a).is_global is False for loopback, private (10/8, 192.168/16, ...), link-local, and other reserved ranges, for both IPv4 and IPv6, including IPv4-mapped IPv6 addresses. Resolving the name is essential: localhost, internal.corp, or a public domain with an A record of 127.0.0.1 all look harmless as strings.
Two more details. First, a DNS server controlled by the attacker can return a public IP during your check and a private one when the HTTP client resolves the name again ("DNS rebinding"). Connect to the IP you checked, or do the check in a proxy that all outgoing requests go through. Second, turn off automatic redirects (allow_redirects=False in requests, follow_redirects=False in httpx) or check every hop, because a public URL can redirect to an internal one.
Denial of service: regexes and unbounded input
A server that does unbounded work for one request can be taken down with a few requests. Regular expressions with nested quantifiers backtrack exponentially on input that almost matches ("ReDoS"):
import re
import time
patterns = {
"evil": re.compile(r"^(\w+\s?)*$"), # nested quantifiers: exponential backtracking
"safe": re.compile(r"^\w+(?:\s\w+)*$"), # same language, only one way to match
"atomic": re.compile(r"^(?>\w+\s?)*$"), # atomic group (3.11+): no backtracking into it
}
for n in (20, 22, 24):
s = "a" * n + "!" # almost matches, then fails at the end
times = []
for name, rx in patterns.items():
t = time.perf_counter()
rx.match(s)
times.append(f"{name} {time.perf_counter() - t:.4f}s")
print(f"n={n}: " + ", ".join(times))
n=20: evil 0.0977s, safe 0.0000s, atomic 0.0000s
n=22: evil 0.4816s, safe 0.0000s, atomic 0.0000s
n=24: evil 1.8272s, safe 0.0000s, atomic 0.0000s
Each extra character roughly doubles the time for the bad pattern, so 30 characters would take minutes. Avoid nested quantifiers like (a+)* and alternations that overlap like (a|a)*. Python 3.11 added atomic groups (?>...) and possessive quantifiers *+, ++, which never backtrack. Limit the input length before matching, and consider the re2 bindings (google-re2), which guarantee linear time, for patterns that come from users. See Regular Expressions.
Limit sizes everywhere input enters the program:
import io
import json
import sys
# int(str) is quadratic in the number of digits; Python limits it by default
print(sys.get_int_max_str_digits())
try:
int("9" * 5000)
except ValueError as e:
print("ValueError:", e)
MAX_BODY = 1024 * 1024 # 1 MiB
def read_json_body(stream, content_length: int | None):
if content_length is None or content_length > MAX_BODY:
raise ValueError("request body too large or missing Content-Length")
data = stream.read(content_length + 1) # don't trust the header: read at most limit+1
if len(data) > content_length:
raise ValueError("body longer than Content-Length")
return json.loads(data)
print(read_json_body(io.BytesIO(b'{"name": "bob"}'), 15))
for body, length in [(b"x" * 10, 2_000_000_000), (b'{"a": 1}' + b" " * 100, 8)]:
try:
read_json_body(io.BytesIO(body), length)
except ValueError as e:
print("ValueError:", e)
4300
ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5000 digits; use sys.set_int_max_str_digits() to increase the limit
{'name': 'bob'}
ValueError: request body too large or missing Content-Length
ValueError: body longer than Content-Length
- Converting a huge string to
inttakes quadratic time, so Python 3.11+ refuses strings over 4300 digits by default. Leave that limit on. - Cap request body size in the web server or framework (
MAX_CONTENT_LENGTHin Flask,DATA_UPLOAD_MAX_MEMORY_SIZEin Django,client_max_body_sizein nginx), and also cap JSON nesting depth, number of uploaded files and paginationlimitparameters. - Always set timeouts on outgoing network calls:
requests.get(url, timeout=10). Without one, a slow server can tie up a worker forever. requests has no default timeout.
TLS
ssl.create_default_context(), urllib, requests and httpx verify certificates and host names by default. The vulnerability is turning that off:
import ssl
ctx = ssl.create_default_context()
print(ctx.verify_mode == ssl.CERT_REQUIRED, ctx.check_hostname)
print(ctx.minimum_version.name)
# BAD: what verify=False / _create_unverified_context() give you
bad = ssl._create_unverified_context()
print(bad.verify_mode == ssl.CERT_NONE, bad.check_hostname)
# raising the floor to TLS 1.3 is one line
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
print(ctx.minimum_version.name)
True True
TLSv1_2
True False
TLSv1_3
verify=False (or an unverified context) means anyone on the network path can impersonate the server and read everything, including the credentials you send. If a server uses a private CA, pass its certificate bundle instead: requests.get(url, verify="/etc/ssl/internal-ca.pem") or ssl.create_default_context(cafile=...). Python's default minimum is TLS 1.2. Raise it to TLS 1.3 if all your peers support it.
Authentication and authorization
These bugs are about logic rather than a dangerous function, so tools can't find them. Check them in code review:
- Check authorization on every request, on the server. Hiding a button isn't access control. Look up objects scoped to the current user (
Order.objects.get(id=order_id, owner=request.user)) so changing/orders/41to/orders/42in the URL doesn't show someone else's order. This bug is called IDOR (insecure direct object reference). - Don't bind request data straight to models.
User(**request.json)lets a client setis_admin=True. Copy only the fields the client may change, or use a schema (pydantic, marshmallow) listing them. - Protect state-changing requests from CSRF. Use your framework's CSRF protection for form posts and
SameSitecookies. Never change state in aGEThandler. - Rotate session IDs at login and invalidate them at logout. Make password reset tokens single-use and short-lived.
- Rate-limit login, password reset and other expensive endpoints.
Dependencies and automated tools
Your application includes all its dependencies' code. Keep them patched and know what's installed:
- Pin and lock versions (
uv lock,pip-tools, Poetry) and install with hashes (pip install --require-hashes -r requirements.txt), so a tampered or swapped package fails to install. - Audit for known vulnerabilities with
pip-audit, which checks your environment or a requirements file against the PyPI advisory database. Run it in CI. - Watch for typosquatting.
reqeustsis notrequests. Check the package name and project page before adding a dependency. - Scan your own code with bandit, a static analyzer for common Python security mistakes. Ruff includes the same checks as its
Srules.
Here is a file with several of the mistakes from this article:
import pickle
import subprocess
import sqlite3
import requests
def run(cmd):
return subprocess.run(cmd, shell=True)
def load(data):
return pickle.loads(data)
def find(db, name):
return db.execute(f"SELECT * FROM users WHERE name = '{name}'")
def fetch(url):
return requests.get(url, verify=False)
PASSWORD = "hunter2"
$ bandit -q -f custom --msg-template "{line}: {test_id} [{severity}] {msg}" app.py
1: B403 [LOW] Consider possible security implications associated with pickle module.
2: B404 [LOW] Consider possible security implications associated with the subprocess module.
8: B602 [HIGH] subprocess call with shell=True identified, security issue.
11: B301 [MEDIUM] Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
14: B608 [MEDIUM] Possible SQL injection vector through string-based query construction.
17: B501 [HIGH] Call to requests with verify=False disabling SSL certificate checks, security issue.
17: B113 [MEDIUM] Call to requests without timeout
19: B105 [LOW] Possible hardcoded password: 'hunter2'
Static tools report patterns, not proven bugs. The import subprocess warning is just a reminder to look. Mark a false positive with # nosec B602 and a comment explaining why, rather than disabling the check globally. They also miss logic bugs, like a missing authorization check. Automated tools add to code review, they don't replace it.
Summary
| Risk | Don't | Do |
|---|---|---|
| SQL injection | f"... WHERE name = '{name}'" |
execute("... WHERE name = ?", (name,)), allow-list identifiers |
| Command injection | shell=True, os.system() |
subprocess.run([prog, arg]), -- before untrusted args |
| Code execution | eval(), pickle.loads(), yaml.load() on input |
json.loads(), ast.literal_eval(), yaml.safe_load() |
| Path traversal | base / user_name |
resolve() + is_relative_to(base), random storage names |
| Archives | extractall() without a filter |
tar.extractall(dest, filter="data"), check sizes |
| XML | parsing untrusted XML with entities | defusedxml.ElementTree.fromstring() |
| XSS | f-strings into HTML | autoescaping templates, html.escape(), check URL schemes |
| Weak tokens | random for tokens |
secrets.token_urlsafe(32) |
| Timing leaks | token == given |
hmac.compare_digest(token, given) |
| Passwords | SHA-256, MD5, plain text | hashlib.scrypt, Argon2id, bcrypt |
| Tampering | trusting client-held data | HMAC-sign it, verify before use |
| Leaked secrets | secrets in code and logs | environment / secrets manager, Secret wrapper, redaction |
| SSRF | fetching any user URL | allow http(s) only, resolve and require is_global, no blind redirects |
| DoS | unbounded input, nested regex quantifiers, no timeouts | size limits, safe or atomic regexes, timeout= |
| TLS | verify=False |
default verification, custom CA bundle if needed |
| Dependencies | unpinned, never audited | lock with hashes, pip-audit, bandit in CI |