Python: which everyday calls turn into vulnerabilities?

Before your next release, move off Python 3.10 and older2, keep pickle-based loaders away from outside data, and run Ruff's S rules and pip-audit in CI. Judge everything else by whether input stays data: never code, a shell command, SQL text, a template or a path outside the directory you meant.

Reviewed
Next review
Version
1.1
Written for
Developers and tech leads writing production Python, and the security people who review it

If you only do five things

  1. Never load outside data with pickle-based loaders.

    pickle, shelve, unsafe yaml.load() and torch.load(weights_only=False) can run code while loading567. Use json, yaml.safe_load() and safetensors instead.

  2. Pass data as arguments, never as code.

    Bind SQL values as parameters, call subprocess with a list and no shell=True, and never render user text as a template. SQL injection ranks 2nd and OS command injection 9th in the 2025 CWE Top 251.

  3. Run a supported Python and patch it.

    Python 3.10 reached end of life on 1 October 20262 and missed October's fix for compromised certificate authority keys3. Patch within the patching sheet's deadlines.

  4. Let tools find the obvious ones.

    Run Ruff's S rules and pip-audit in CI. Ruff flags pickle, yaml.load(), shell=True, SQL built from strings, missing timeouts and verify=False23.

  5. Validate at every boundary, at runtime.

    Type hints aren't enforced at runtime21. Use pydantic models with extra="forbid" and strict types: by default pydantic ignores unknown fields and turns "123" into 12322.

Review a Python pull request

  1. Where does outside data enter?

    Find request handlers, CLI arguments, queue consumers, uploads and downloaded models. Each should become a pydantic model or form before other code uses it.

  2. Does it reach a loader?

    Search for pickle, shelve, yaml.load, torch.load and from_pretrained. Data from outside needs a format that can't run code.

  3. Does it reach something that runs strings?

    Check SQL text, subprocess, eval, template source and ** unpacking into ORM calls.

  4. Does it reach the file system?

    Paths from input need resolve() plus is_relative_to(). Archives need filter="data", an empty directory and size limits.

  5. Does it reach the network?

    Calls need a timeout and certificate checks. URLs from users need an allowlist against server-side request forgery, 22nd in the CWE Top 251.

Python traps and what to use instead

  • pickle.loads(), shelve and yaml.load(). Unpickling can run arbitrary code5, and shelve and multiprocessing's Connection.recv() use pickle6. Use json, and yaml.safe_load() for YAML5.
  • torch.load() and trust_remote_code=True. PyTorch has defaulted to weights_only=True since 2.67, but before 2.10.0 that mode could still run code8. Prefer safetensors10. trust_remote_code=True runs code from the Hub repository on your machine9.
  • eval() and ast.literal_eval(). Ruff's S307 suggests literal_eval() in place of eval()23, but Python's docs advise against it for untrusted data: small inputs can exhaust memory or crash the process11. Use json.loads().
  • subprocess.run(cmd, shell=True). With a shell, quoting is your job12. Pass a list such as ["convert", src, dst] without shell=True12, and put -- before values that may start with a dash, which programs read as options.
  • SQL in f-strings, % or .format(). Pass values as parameters (%s in psycopg) or in a Python 3.14 t"..." string, which psycopg 3.3 parameterizes; an f in its place pastes values into the SQL13. In Django, never unpack a user-supplied dict with ** into QuerySet methods: that still allowed SQL injection in February 202614.
  • Templates built from user input. render_template_string() or from_string() on user text can lead to remote code execution15. Pass input as variables to fixed template files, and set autoescape=select_autoescape(), since Jinja doesn't escape by default16.
  • tarfile.extractall(). Pass filter="data" before Python 3.14, which made it the default17. It isn't a sandbox: from June to October 2026 the PSF published seven advisories for archives that got past the filters4. Extract into a new empty directory with OS-level limits17.
  • os.path.join(base, name) and Path(base) / name. An absolute name discards base18. Resolve the result, then check is_relative_to(base.resolve()); on unresolved paths that check ignores ..18.
  • requests.get(url) without timeout=, or with verify=False. Requests never times out unless told to, and verify=False accepts any certificate. It trusts the CA list in certifi, so keep certifi updated19.
  • assert for checks. python -O and PYTHONOPTIMIZE=1 skip asserts; aiohttp's POST parsing could then loop forever (CVE-2025-69227)20. Raise exceptions for permission and input checks.

Tools that catch it

  • Ruff's S rules. Add "S" to extend-select in [tool.ruff.lint]. Fix S301 (pickle), S506 (YAML), S602 (shell), S608 (SQL), S202 (tar), S113 (timeouts) and S311 (random) first23.
  • Bandit for ML code. B614 flags torch.load()10; Ruff has no such rule23.
  • pip-audit. It checks environments, requirements and, with --locked, pylock.*.toml files against PyPI or OSV advisories24.

What changed in 2026

  • Python 3.10 is end of life. Support ended on 1 October 2026, and 3.15.0 shipped on 9 October2.
  • A CA compromise reached Python's trust stores. After October's emSign incident, install certifi 2026.10.19, pip 26.2.2 and uv 0.13.6 or later in every virtual environment, move to Python 3.11.18, 3.12.16, 3.13.18, 3.14.10 or 3.15.2 and rebuild images without cached layers3.

What you can skip

  • defusedxml for standard library parsers. Expat doesn't read local files or open connections by default, and Python's XML docs warn of entity expansion only for Expat before 2.7.227. Check pyexpat.EXPAT_VERSION in CI and turn off S313 to S31923.
  • Noisy lint rules. Turn off S603, which fires on every subprocess call without a shell, and preview rules S403 and S404, which fire on any import of pickle or subprocess23.
  • A find_class allowlist for pickle. Change the format. PyTorch's own restricted unpickler needed a code execution fix in 20268.

Mistakes that cost the most

  • Shipping with the debugger on. Flask's debugger runs Python sent from the browser28. Django's DEBUG = True leaks source excerpts and settings; run manage.py check --deploy in CI29.
  • Trusting FastAPI's OAuth2PasswordBearer. It only extracts the token. Verify the signature, exp, iss and aud with PyJWT and a fixed algorithms list22.
  • Ignoring .pth files. Their import lines run at every interpreter start, as do the .start files Python 3.15 adds to replace them25. The malicious LiteLLM 1.107.0 shipped cook.pth and sitecustomize.py26. The supply-chain sheet covers the rest.

What this looks like for your code

New project

  • Start on Python 3.14 or 3.15, where tar extraction uses the data filter by default17.
  • Turn on Ruff's S rules and pip-audit in the first CI pipeline.
  • Give every input type a pydantic model with extra="forbid".

Existing codebase

  • Move every image off Python 3.10 or older first.
  • Fix Ruff's S301, S506, S602 and S608 hits in code that handles outside input first.
  • Set TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 wherever models load7.

High-assurance or regulated

  • Block new CodeQL security-extended alerts; private code needs paid Code Security30.
  • Parse untrusted archives and models in a separate process with OS-level limits17.
  • Subscribe to security-announce@python.org and close every advisory4.