Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 80 ยท Secure Coding

Python Security Pitfalls

Learn the Python features that most often cause vulnerabilities, such as eval, pickle, shell=True, yaml.load, temp files and assert, and the safer alternatives.

Python is friendly, and some of its most convenient features are dangerous when they touch untrusted data. A function that "just evaluates a string" or "just restores an object" is, from an attacker's point of view, a way to run code on your machine. None of these features is a bug in Python; they are sharp tools that were designed for trusted input.

In this lesson you'll see six common pitfalls, why each one is exploitable, and the safer alternative to use. The demos use harmless payloads that only print a message, so you can see the problem without causing any. The wider principle, never trusting data from outside your boundary, comes from Secure Coding Principles.

eval and exec

eval(text) compiles and runs a Python expression; exec(text) runs statements. If any part of text comes from a user, that user can run arbitrary Python: read files, delete data, call the network. A common reason people reach for eval is parsing something simple, like a number or a list. For that, ast.literal_eval accepts only Python literals (numbers, strings, lists, dicts, tuples, booleans, None) and refuses everything else.

Python eval versus ast.literal_eval

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The unsafe parser happily executes the last two inputs. Swap the harmless calls for os.system("...") and you have remote code execution. For configuration use JSON or TOML; for math use a real expression parser or the ast module with a strict allow-list of node types. Note that even eval(text, {"__builtins__": {}}) is not a sandbox: known tricks escape it.

pickle and unsafe deserialization

pickle turns Python objects into bytes and back. To rebuild an object, the format lets the data name any function to call. A pickle is therefore not data, it is a program that runs when you call pickle.loads. The attacker's version of an object chooses the function through the __reduce__ method:

Python A pickle that runs a function on load

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The rule: never unpickle data from an untrusted source, including files users upload, cookies, cache entries that others can write, and network messages. Use JSON, MessagePack or Protocol Buffers for exchange. If you must pickle between your own trusted processes, sign the bytes with an HMAC (see HMAC and Message Authentication) and verify before loading. A fuller discussion is in SSRF, Unsafe Deserialization and XXE.

subprocess and shell=True

When you run an external program, there are two very different ways to do it. With shell=True the whole string is handed to a shell (/bin/sh), which interprets characters like ;, &&, |, $() and backticks. If part of the string is user input, the user can add their own commands. With a list of arguments and no shell, each item is passed to the program exactly as given, and there is nothing to inject into.

Browsers have no processes to start, so this demo shows what the shell would see and how a list keeps the input as one argument:

Python How a shell splits user input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Prefer subprocess.run([...], check=True, timeout=10) with a fixed program name and arguments, never os.system, and never shell=True with formatted strings. Better still, avoid shelling out when a library does the job (use the zipfile module instead of calling unzip). Validate values with an allow-list too, because an argument that begins with - may be read as an option by the program.

yaml.load

YAML is popular for configuration, and the PyYAML function yaml.load with the old default loader could construct arbitrary Python objects, including ones that run commands, from tags like !!python/object/apply:. It has the same problem as pickle. The safe call is yaml.safe_load, which builds only plain data types:

Python
import yaml

text = """
name: demo
workers: 4
"""
config = yaml.safe_load(text)          # safe: dicts, lists, strings, numbers
# yaml.load(text, Loader=yaml.UnsafeLoader)   # never for untrusted input

In current PyYAML, yaml.load requires an explicit Loader, which was added precisely because of these incidents. Search your code for yaml.load( and Loader=yaml.Loader or UnsafeLoader.

Temporary files

Writing to /tmp/report.txt is predictable. On a shared machine another user can create that name first as a link to a sensitive file (a symlink attack), or read your data before you delete it. The deprecated tempfile.mktemp() returns a name without creating the file, which leaves a race between "choose name" and "open". Use tempfile.mkstemp, NamedTemporaryFile or TemporaryDirectory, which create the file atomically with a random name and restrictive permissions.

Python Random, atomically created temp files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When you receive a file name from a user, never join it to a directory unchecked; see path traversal in Input Validation and Sanitization.

assert is not a security check

assert condition is a debugging aid. When Python runs with the optimization flag -O (or PYTHONOPTIMIZE is set), every assert statement is removed. If you use assert user.is_admin to guard an action, the guard disappears in an optimized deployment. This demo compiles the same source twice to show the effect:

Python Asserts vanish when optimized

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use if ...: raise for anything that enforces security or validates input, and keep assert for checking your own assumptions in tests and development.

More pitfalls to check for

  • random for secrets: use the secrets module for tokens and keys (see Randomness, Key Management and Secrets).
  • == for secrets: use hmac.compare_digest.
  • Weak hashes for passwords: use scrypt or Argon2 (Password Storage Done Right).
  • SQL built with f-strings: use parameters (SQL Injection and Parameterized Queries).
  • requests.get(url, verify=False): disables TLS certificate checking.
  • Binding debug servers to 0.0.0.0, and running Flask or Django with debug=True in production.
  • Regular expressions on untrusted input with nested quantifiers can freeze your server.

Static analyzers such as Bandit flag most of these automatically; you'll see how in Security Code Review, SAST and Testing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You need to turn the string "[1, 2, 3]" from a user into a list. What is the safest choice?

    literal_eval and JSON parse only data. eval and exec run code, and pickle can call arbitrary functions.
  2. 2. Why is pickle.loads on untrusted bytes dangerous?

    A pickle is a set of instructions for rebuilding objects, including calling callables, so loading hostile pickles can execute code.
  3. 3. What is the main security advantage of subprocess.run(["tool", arg]) over a string with shell=True?

    With an argument list, user input stays a single argument and characters like ; or && have no special meaning.
  4. 4. Why should access checks not rely on assert?

    Optimized mode strips asserts, so a guard written as an assert can silently vanish in production.
  5. 5. Which tempfile approach avoids predictable names and races?

    mkstemp and NamedTemporaryFile pick a random name and create the file atomically with restrictive permissions.

Summary

  • eval, exec, pickle, yaml.load with unsafe loaders and shell=True all turn untrusted data into code execution; the fixes are ast.literal_eval or JSON, yaml.safe_load and argument lists.
  • Never unpickle untrusted bytes. Use data-only formats, and sign anything you must pickle.
  • Use tempfile helpers rather than fixed or guessed paths.
  • Enforce security with if and exceptions, never with assert.
  • Run a static analyzer to catch these patterns early.

Next: Memory Safety and Why Languages Matter, which explains why some whole classes of bugs do not exist in Python at all.