Lesson 50 of 52Real projects
Python Security Pitfalls
The Python-specific ways code gets owned: pickle, eval, shell and SQL injection, weak tokens, path traversal, archives, ReDoS, assert and your dependencies.
You are reviewing a pull request for an internal reporting tool. It caches reports by pickling them into a shared bucket, converts uploads with subprocess.run(f"pdftotext {name} out.txt", shell=True), makes password-reset tokens with random.choices, extracts customer archives with extractall, and checks permissions with assert user.is_admin. Every line works in the demo, and every one of them is a security bug. None of them is exotic: they are the standard library used the convenient way. This lesson goes through the Python-specific pitfalls that show up in real code reviews, in security scanners, and in interviews. API Security covered HTTP, authorisation and CORS, and Security Habits for Developers covered the basics of password storage. Here the focus is on the language and its standard library.
Deserialisation: pickle runs code
pickle does not store data. It stores instructions for rebuilding objects, and one of those instructions is "call this function with these arguments". Any object can choose what that function is through __reduce__. So pickle.loads on bytes from an attacker means the attacker runs code on your machine.
Press Run (⌘ Enter) to see what happens.STACK_GLOBAL looks up builtins.print, and REDUCE calls it. Swap print for os.system and the string for a shell command, and the victim's process runs it. The victim's code never mentioned Payload; it does not need to.
The attacker only needs write access to where you read pickles from: a cache, a queue, an upload folder, a model file from the internet.
The same applies to everything built on pickle: shelve, pandas.read_pickle, joblib.load, and most machine-learning checkpoint formats. marshal is not safe for untrusted data either. Rules that hold up:
- For data that crosses a trust boundary, use JSON (or MessagePack, Protocol Buffers, Parquet). These formats can only describe data.
- For YAML, use
yaml.safe_load. Plainyaml.loadwith the full or unsafe loader can construct arbitrary Python objects. - For model weights, prefer safetensors. Recent PyTorch versions default
torch.loadtoweights_only=True; never turn that off for a file you downloaded. NumPy'snp.loadrefuses pickled arrays unless you passallow_pickle=True, so do not. - Pickle is fine for data your own process wrote and only your process can modify, such as a local
multiprocessingqueue.
Report class. Are they right?eval, exec and ast.literal_eval
eval runs any expression, so eval(user_input) is remote code execution with one call. People try to make it safe by removing builtins. It does not work, because every object in Python can reach every class through introspection:
Press Run (⌘ Enter) to see what happens.From an empty tuple the attacker walked up to object and down to every loaded class, including the ones that import modules and open files. There is no reliable sandbox for eval inside CPython.
If you need to read Python-literal syntax (a config value like [1, 2, 3]), use ast.literal_eval, which parses and only accepts literals. Still cap the input length: very deep nesting can exhaust the parser. For anything richer, such as user-defined formulas, write a small parser that walks ast nodes against an allowlist, or use a dedicated expression library.
Injection: shells, arguments and SQL
API Security showed the core rule for subprocesses: pass a list, never shell=True with user input. Here is why, plus two details beyond it.
Press Run (⌘ Enter) to see what happens.- With a list of arguments, no shell parses the string, so
;and|are just characters in a strange filename. - If a shell is unavoidable (a pipeline you cannot rewrite),
shlex.quoteeach untrusted piece. It is POSIX-only, so it does not protectcmd.exe. - A list still allows argument injection: a filename like
--output=/etc/cron.d/xis read by the program as an option. Put--before user-supplied positional arguments, which most Unix tools treat as "no more options", or reject values that start with-.
For SQL, the database driver sends parameters separately from the query text, so the quote in nobody' OR '1'='1 is just part of a name. Type checkers can enforce this: annotate a query parameter as typing.LiteralString and the checker rejects any string built from runtime input, such as an f-string with a variable in it. Python 3.14's t-strings go further: t"... {name}" produces a Template object rather than a str, so a library can see which parts were interpolated and turn them into parameters. Check whether your database library supports them before relying on it.
Tokens, comparisons and passwords
random is a Mersenne Twister. It is fast and reproducible, which is exactly wrong for secrets: after observing 624 32-bit outputs, an attacker can reconstruct its internal state and predict every future value. Anything an attacker must not guess comes from secrets, which reads the operating system's cryptographic generator.
Press Run (⌘ Enter) to see what happens.== on strings stops at the first differing character, so its timing leaks how much of a guess was right. Over many requests an attacker can recover a signature or API key one character at a time. hmac.compare_digest takes the same time however much matches. Use it whenever you compare a secret, signature or token.
For passwords, a fast hash is the wrong tool. SHA-256 is designed to be fast, so a GPU tries billions of guesses per second against a leaked table. Use a deliberately slow, salted algorithm. In Python that means argon2-cffi (Argon2id) or bcrypt:
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher() # sensible Argon2id defaults, salt included
def hash_password(password: str) -> str:
return ph.hash(password) # store this whole string
def check_password(stored: str, password: str) -> bool:
try:
ph.verify(stored, password)
except VerifyMismatchError:
return False
return True # also call ph.check_needs_rehash(stored) after loginhashlib.scrypt and hashlib.pbkdf2_hmac are in the standard library and acceptable when you cannot add a dependency, but you must pick the cost parameters yourself; check OWASP's current recommendations.
Paths, archives and temp files
Whenever a user-supplied string becomes part of a path, assume it contains ../. Two facts make this worse in Python than people expect: joining with an absolute path throws away everything before it, and .. is only resolved when you call resolve().
Press Run (⌘ Enter) to see what happens.The check is resolve first, then compare. resolve() collapses .. and follows symlinks, and is_relative_to confirms the result is still inside the folder. Checking the raw string for ".." misses absolute paths, symlinks and encoded variants. Better still, never use the user's string as a name at all: store the upload under an ID you generate and keep the original name in the database.
Archives have the same bug inside them, known as zip slip: a member named ../../app/config.py or a symlink pointing at /etc. Since Python 3.14, tarfile extraction applies the "data" filter by default, which rejects members that escape the destination, absolute paths, links outside it, and device files. On older versions you must pass filter="data" yourself, and you should pass it explicitly anyway so the intent is clear. zipfile's extractall cleans member names, but if you write members out yourself with open(dest / member.filename, "wb"), you have reintroduced the bug. Also check file_size totals before extracting, because a small archive can expand to fill a disk (a zip bomb).
Temporary files at fixed names like /tmp/report.csv are a race: another user on the machine can create that path first, as a symlink to a file you can write to. Use tempfile.NamedTemporaryFile, mkstemp or TemporaryDirectory, which create unpredictable names with safe permissions.
What does this print on Linux or macOS?
from pathlib import Path
print(Path("/srv/app/uploads") / "/etc/passwd")Parsers that can be turned against you: XML and regex
XML has features most applications never use but parsers support: entities that expand to other entities (the "billion laughs" attack, a few kilobytes that expand to gigabytes) and external entities that read local files or make network requests. The standard library parsers have improved, and the Python docs keep a table of which attack affects which parser and Expat version. For XML from outside your organisation, the simple rule is defusedxml, a drop-in replacement for the standard parsers with the dangerous features off.
Regular expressions can hang a server. Python's re engine backtracks: when a match fails, it tries every other way of splitting the input. With nested quantifiers, the number of ways grows exponentially with input length. This is ReDoS (regular expression denial of service):
Press Run (⌘ Enter) to see what happens.Each two extra characters multiply the time by about four. Thirty characters in a form field is enough to pin a CPU core for minutes. Defences: avoid nested or overlapping quantifiers like (a+)+ and (\w|\d)*, cap input length before matching, and use atomic groups (?>...) or possessive quantifiers like a++ (both added in Python 3.11), which forbid backtracking into the group. For patterns that users supply, use an engine without backtracking, such as Google's RE2 through a Python binding.
assert is not a security check
assert statements are removed when Python runs with -O, and some deployments do that. A permission check written as an assertion disappears silently:
Press Run (⌘ Enter) to see what happens.Use assert for internal invariants and tests. For anything that guards data or permissions, write if not user.is_admin: raise PermissionError(...).
Match each risky call to its safer replacement.
Your dependencies and your secrets
Most Python code in production was written by someone else, and installing a package can run its code. Supply-chain attacks target exactly that:
- Typosquatting:
reqeustsorpython-dateutilspublished with a malicious payload. Copy install names from official docs, and review new dependencies in pull requests like code. - Dependency confusion: an attacker publishes your internal package name on PyPI with a higher version. uv's default index strategy only takes a package from the first index that has it, which blocks the classic attack; with pip and
--extra-index-url, the highest version from any index wins. Name internal packages with a prefix you have registered, or configure a single private index. - Known vulnerabilities: run
pip-auditin CI and on a schedule, as API Security showed. - Lockfiles with hashes:
uv.lockrecords a hash for every file, so a swapped file on the index fails the install instead of running.
Secrets belong in environment variables or a secret manager, loaded once through a settings object, never in source or in logs. Mark secret fields with repr=False on dataclasses or SecretStr in Pydantic so a stray print(settings) does not leak them.
Finally, let tools find the easy cases. Ruff's S rules (ported from the Bandit project) flag pickle.loads, yaml.load, eval, shell=True, assert, hard-coded passwords, random for security and more:
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "S"]
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"] # assert is fine in testsA linter will not understand your authorisation rules, but it catches the patterns in this lesson for free on every commit.
assert request.user.is_staff. Production runs python -O. What happens when a non-staff user calls it?That checklist is the last piece of the Real projects unit. Next, you put it to work in a project: a small habit tracker for the terminal, built stage by stage from a data model to tested, working code.
- deserialisation attack
- Supplying crafted bytes to a loader like pickle so that loading them runs the attacker's code.
- ast.literal_eval
- Parses a string containing only Python literals, and rejects calls, names and attributes.
- argument injection
- User input read as a command-line option, such as a filename starting with
--. - constant-time comparison
- Comparing secrets in time that does not depend on how many characters match, as
hmac.compare_digestdoes. - path traversal
- Using
../or absolute paths in input to read or write files outside the intended folder. - zip slip
- An archive member whose name escapes the extraction folder.
- ReDoS
- A denial of service caused by a regex that backtracks exponentially on crafted input.