SECURITY ENGINEERING · PART 8 · WRITING SECURE CODE · CODE · 113 OF 229

Secure Coding in Python: Pitfalls and Fixes

Python is forgiving, which is why its security pitfalls are easy to hit. This episode covers the mistakes that appear most in Python code review: SQL injection with string formatting, command injection via shell=True, dangerous functions (eval, pickle, yaml.load), SSRF, path traversal, template injection in Jinja and Flask, unsafe defaults in requests and XML parsers, secrets in code, and the safe pattern for each.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 11

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Parameterise SQL
  • no shell=True
  • never eval/pickle/yaml.load untrusted
  • allowlist URLs and paths
  • secrets module
  • Bandit

Notes

SQL injection

First, SQL injection. In Python the usual culprit is an f-string or percent formatting that drops user input straight into a query. The fix is parameters: pass placeholders and a tuple of values, and let the database driver bind them safely. Note the placeholder style is the driver's, not Python's string formatting. ORMs like Django and SQLAlchemy parameterise for you, but their raw query escape hatches, raw and text, reintroduce the risk if you format input into them.

queries
# WRONG: formatted into SQL
cur.execute(f"select * from u
  where name = '{name}'")

# RIGHT: parameters, driver binds
cur.execute("select * from u
  where name = %s", (name,))

# ORMs: Django/SQLAlchemy bind for
# you; raw()/text() can reintroduce it

Command injection

Command injection is next. Running a command with shell equals true and a formatted string means a shell parses it, so an attacker adds a semicolon or pipe and runs their own commands. The fix is to pass the command as a list of arguments with no shell, so the program receives the host as a single argument and nothing is interpreted. Never pass user input through os dot system or shell equals true. If you truly need a shell feature, validate the input against a strict allowlist first.

subprocess
# WRONG: a shell parses this
subprocess.run(f"ping {host}",
  shell=True)

# RIGHT: arguments as a list,
# no shell involved
subprocess.run(["ping", "-c", "1",
  host])

# never pass user input to
# os.system or shell=True

Dangerous functions

A family of functions turns data into code, and must never touch untrusted input. Eval and exec run arbitrary code. Pickle's loads runs code during deserialisation, like Java's problem, so never unpickle outside data. The plain yaml dot load can instantiate objects; always use safe load. The safe replacements are specific: ast dot literal eval for a Python literal, json for data interchange, and yaml safe load for YAML. If you are reaching for eval, there is almost always a better way.

Never on untrusted input
  • eval() / exec(): run arbitrary code; almost never needed
  • pickle.loads(): deserialising runs code (like Java)
  • yaml.load(): use yaml.safe_load
  • input() in Python 2: evaluated
  • use: ast.literal_eval for literals, json for data, safe_load for YAML

SSRF and requests

Server-side request forgery appears wherever Python fetches a URL, usually with the requests library. If the URL comes from the user, an attacker points it at internal services or the cloud metadata endpoint. The fix is the same as in any language: allowlist the host and scheme, resolve the DNS and check the address is not private, and be aware that requests follows redirects by default, which can bypass a naive check. And never set verify equals false, which disables TLS certificate checking entirely.

server-side fetches
  • requests.get(user_url): SSRF to internal hosts and cloud metadata
  • fix: allowlist host and scheme, resolve and check the IP, block private ranges
  • also: requests follows redirects by default
  • verify=False disables TLS checks: never do it

Path traversal

Path traversal happens when a user controls part of a file path. Joining a base directory with a user-supplied name looks safe, but a name containing dot dot slash escapes upward to files like the system password file. The fix is to resolve the final path and confirm it still sits inside the intended base directory before opening it, and to validate the filename against an allowlist of characters. The same care applies to extracting archives, where a crafted entry name can write outside the target directory.

safe file paths
# WRONG: user controls the path
open(os.path.join(base, name))
# name = "../../etc/passwd"

# RIGHT: resolve and confirm it
# stays inside base
p = (base / name).resolve()
if not p.is_relative_to(base):
    raise ValueError
# also validate the filename

Template injection

Template injection is a Python-flavoured trap. Rendering a user-supplied string as a template, such as render template string, lets an attacker reach Python objects and run code. Pass user input as data to a fixed template; never let users supply the template text. Keep Jinja's autoescaping on to prevent cross-site scripting, and avoid the safe filter on untrusted data. And in Flask, never run with debug equals true in production, which exposes a console to attackers.

Jinja / Flask pitfalls
  • SSTI: never render a user string AS a template render_template_string(user)
  • pass data to the template, not template text from users
  • keep Jinja autoescaping on; {% autoescape %} and avoid |safe on untrusted data
  • Flask: never put secrets or debug=True in production

Defaults and the rest

A few more, briefly. Validate input with a library like pydantic or your framework's validators, on the server. For XML, the standard library parsers are unsafe by default, so use the defusedxml package to block external entity attacks. For tokens, keys and password resets, use the secrets module, never the random module, as we saw in Part three. Keep secrets in environment variables or a vault, never in code. And run the security linters Bandit and pip-audit in your pipeline to catch most of this automatically.

A few more
  • validate with pydantic or framework validators, on the server
  • XML: use defusedxml to block XXE (stdlib parsers are unsafe by default)
  • tokens/keys: secrets module, never random
  • secrets: env vars or a vault, never in code or git
  • run Bandit and pip-audit in CI

Common mistakes

The recurring Python findings. F-strings or percent formatting building SQL. Shell equals true with user input. Eval, exec, pickle or plain yaml load on untrusted data. The requests library with verify equals false, or fetching an unchecked user URL. User-controlled file paths. Rendering user input as a template, or running Flask with debug on in production. And the random module used for security tokens, or secrets committed in code. Linters catch most of these, so run them.

Avoid these
  • f-strings or % building SQL
  • shell=True with user input
  • eval, exec, pickle, yaml.load on untrusted data
  • requests with verify=False or an unchecked user URL
  • user-controlled file paths
  • rendering user input as a template; debug=True
  • random for tokens; secrets in code

Say it like this

In the interview: I parameterise SQL rather than f-strings. I never use shell equals true; I pass arguments as a list. I never eval, exec, pickle or plainly yaml-load untrusted data, using literal eval, json or safe load. I allowlist and check URLs to prevent SSRF, confine user-controlled file paths to a base directory, keep template autoescaping on, use the secrets module for tokens, and run Bandit and pip-audit. Most Python security bugs come from a short list, and this is it.

In the interview
  • "Parameterise SQL, never
  • f-strings. No shell=True; pass
  • args as a list. Never eval, pickle or yaml.load untrusted
  • data; use literal_eval, json, safe_load. Allowlist URLs for SSRF, confine file paths, keep autoescaping on, use the secrets module, and run Bandit
  • and pip-audit."

Interview questions

Q1How do you prevent SQL injection in Python?

Use parameterised queries: pass placeholders and values separately so the database driver binds them, rather than building SQL with f-strings or percent formatting. With ORMs, prefer their query APIs and avoid formatting user input into raw() or text() escape hatches.

Q2Why is subprocess with shell=True dangerous?

With shell=True the command string is parsed by a shell, so user input containing shell metacharacters can run arbitrary commands. Passing the command as a list of arguments without a shell avoids interpretation and prevents command injection.

Q3Why are eval, exec and pickle dangerous in Python?

eval and exec execute arbitrary code, and pickle.loads executes code while deserialising. On untrusted input they allow remote code execution. Use ast.literal_eval for literals, json for data interchange, and yaml.safe_load instead of yaml.load.

Q4What is the safe way to load YAML in Python?

Use yaml.safe_load, which only constructs standard types. The plain yaml.load can instantiate arbitrary Python objects from the document, which is unsafe for untrusted input.

Q5How do you prevent path traversal in Python?

Resolve the final path and verify it remains inside the intended base directory before using it, for example with pathlib resolve and is_relative_to, and validate the filename. Apply the same check when extracting archive entries.

Q6What is server-side template injection in Flask or Jinja?

Rendering a user-controlled string as a template, such as with render_template_string, lets an attacker access Python objects and execute code. Templates should be fixed, with user input passed only as data, and autoescaping kept enabled.

Q7Which module should you use for security tokens in Python?

The secrets module, which draws on the operating system's cryptographically secure source. The random module is predictable and must not be used for tokens, salts, passwords or any security-sensitive value.

Q8What tools scan Python code for security issues?

Bandit for insecure code patterns such as eval, shell=True and weak randomness, and pip-audit or Safety for known vulnerabilities in dependencies. Running both in CI catches most common Python security mistakes automatically.