SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 57
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 57 of 90

Secure coding in Python

eval and exec dangerspickle risksyaml.safe_loadsubprocess without shell=TrueshlexDB-API parameter bindingsecrets module vs randomhashlib and hmac.compare_digestpathlib path safetyJinja2 autoescapeDjango and Flask security settingsBanditpip-auditvirtual environments

These are the notes for Cybersecurity Fundamentals (defensive), episode 57. Episode 56 covered Java's traps. Python is memory-safe too, but its superpower, making it very easy to run things (text as code, bytes as objects, shell commands), is exactly where its traps are. This episode trips each one in a toy program, fixes it, and then lets free tools find them for us. Every term is defined the first time it appears; the Glossary collects them.

Scope. Defensive and educational only. Every program is a toy that works on its own files; no real system is touched, and no working exploit for real software is shown. Samples were run on 12 Nov 2026 in the SyntaxPilot compiler (Python 3.13, PyYAML 6.0.3, Jinja2 3.1.6). The Bandit 1.9.4, pip-audit 2.10.1 and pip --require-hashes reports were produced separately on the same machine. Folder names in the output differ on your machine.

The seven traps

Trap Fix
Text that runs as code: eval, exec ast.literal_eval, or a small parser
Data that runs as code: pickle, yaml.load json, yaml.safe_load, or sign with hmac
Shell commands built from input: shell=True a list of arguments; shlex.quote
SQL built from input DB-API placeholders (?, %s)
Guessable tokens, timing leaks, ../ paths secrets, hmac.compare_digest, pathlib checks
Web templates and settings Jinja2 autoescape; Django/Flask production settings
Everything else Bandit, pip-audit, virtual environments, hash-pinned requirements

Problem 1: text that runs as code (eval, exec)

Real-life example: an office clerk who obeys any slip handed in ("add 2 and 3"... or "open the safe"), versus a clerk who only reads numbers.

  • eval(text) runs a string as a Python expression and returns the result.
  • exec(text) runs a string as Python statements (whole blocks of code).
  • If the text comes from a user, they can run any Python on your server: read files, delete data, start programs. This is code injection.
  • ast.literal_eval(text) only accepts Python literals: plain values (numbers, strings, bytes, booleans, None, lists, tuples, dicts, sets). Anything that would call a function or look up a name is refused with ValueError.

Demo 1: eval vs ast.literal_eval

# A calculator that "just evaluates" what the user types.
import ast

def calc_unsafe(text):
    return eval(text)                 # runs ANY Python expression

def calc_safe(text):
    return ast.literal_eval(text)     # only plain values: numbers, lists...

print("unsafe 2*21   ->", calc_unsafe("2*21"))
typed = "__import__('os').getcwd()"   # the user types CODE, not maths
print("unsafe (code) ->", calc_unsafe(typed))   # it ran: server's folder

print("safe [90, 85] ->", calc_safe("[90, 85]"))
try:
    calc_safe(typed)
except ValueError as e:
    print("safe (code)   -> refused:", str(e).split(":")[0])

Real output:

unsafe 2*21   -> 42
unsafe (code) -> /tmp/stage-...
safe [90, 85] -> [90, 85]
safe (code)   -> refused: malformed node or string on line 1

The unsafe calculator ran the user's code and printed the server's working folder. literal_eval refused it. Note that literal_eval does not do arithmetic like 2*21 (that's an operation, not a literal); for a real calculator write a tiny parser (for example with the ast module, allowing only number nodes and + - * /). "Sandboxing" eval by removing builtins is not safe; don't rely on it.

Problem 2: data that runs as code (pickle, YAML)

  • pickle turns Python objects into bytes (pickle.dumps) and back (pickle.loads). It is used for caches and saved machine-learning models.
  • The bytes describe how to rebuild the object, and that description can name any function to call. A class can control this with the special method __reduce__.
  • The Python docs: "The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling." They suggest signing data with hmac, or using json for untrusted data.
  • JSON (JavaScript Object Notation) holds only plain data: strings, numbers, booleans, null, lists and objects. Loading JSON can't run code.

Demo 2: pickle runs code on load (a harmless toy)

# pickle: LOADING bytes can run code. A harmless toy: it only prints.
import pickle, json

class Surprise:
    def __reduce__(self):              # tells pickle how to rebuild me...
        return (print, ("!! code ran while LOADING the pickle !!",))

data = pickle.dumps(Surprise())        # bytes someone sends us
print("about to load", len(data), "bytes...")
pickle.loads(data)                     # just loading runs print()

# json holds only plain data: loading it can never run code
order = json.loads('{"item": "chai", "qty": 2}')
print("json loaded:", order)

Real output:

about to load 79 bytes...
!! code ran while LOADING the pickle !!
json loaded: {'item': 'chai', 'qty': 2}

Loading alone ran a function chosen by whoever made the bytes. The same caution applies to anything built on pickle (shelve, many model-file formats; prefer formats like safetensors for ML weights from the internet).

YAML: safe_load

  • YAML is a popular human-friendly format for configuration files.
  • PyYAML's full and unsafe loaders understand special tags like !!python/object/apply: that build Python objects or call functions.
  • yaml.safe_load understands only plain data (strings, numbers, lists, dicts) and refuses those tags.
# YAML: the full loader can build Python objects; safe_load can't.
import yaml

doc = "item: chai\nqty: 2\n"
print("safe_load:", yaml.safe_load(doc))

tagged = "!!python/object/apply:os.getcwd []"   # a tag that CALLS a function
print("unsafe_load:", yaml.unsafe_load(tagged))  # it ran os.getcwd()
try:
    yaml.safe_load(tagged)
except yaml.YAMLError as e:
    print("safe_load refused:", str(e).split(" for")[0])

Real output:

safe_load: {'item': 'chai', 'qty': 2}
unsafe_load: /tmp/stage-...
safe_load refused: could not determine a constructor

(The full message is could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:os.getcwd'.) Always use yaml.safe_load for files you didn't write yourself.

Problem 3: shell commands from input (subprocess)

Real-life example: an assistant who reads your note aloud to the whole office ("print file X; and then fire Ravi") versus a form with a fixed "file name" box.

  • subprocess.run starts another program, like wc -l (count lines).
  • A shell (/bin/sh, bash) is the program that reads command lines. With shell=True and one string, Python hands the whole string to the shell, which treats ;, |, &&, $( ) and backticks as instructions to run more commands.
  • Command injection: user input that starts extra shell commands.
  • Fix: pass a list of arguments (["wc", "-l", name]). No shell is involved; the input is exactly one argument.
  • shlex.quote(s) wraps a string in safe quotes for a shell, if you truly must build a shell command string. os.system always uses a shell: avoid it.

Demo 3: shell=True vs a list

# Count the lines of a file the user names, with the wc command.
import subprocess, shlex

name = "notes.txt; echo INJECTED: a 2nd command ran"   # user's input
open("notes.txt", "w").write("chai\nsamosa\n")

# UNSAFE: shell=True, so the shell reads ';' as "run another command"
r = subprocess.run("wc -l " + name, shell=True,
                   capture_output=True, text=True)
print("shell=True :", r.stdout.strip().replace("\n", " | "))

# SAFE: a list of arguments, no shell. The input is ONE file name.
r = subprocess.run(["wc", "-l", name], capture_output=True, text=True)
print("list args  :", (r.stdout + r.stderr).strip())

print("shlex.quote:", shlex.quote(name))   # only if you need a shell

Real output:

shell=True : 2 notes.txt | INJECTED: a 2nd command ran
list args  : wc: 'notes.txt; echo INJECTED: a 2nd command ran': No such file or directory
shlex.quote: 'notes.txt; echo INJECTED: a 2nd command ran'

Also: a file name starting with - could be read as an option; put -- before user-supplied file names (["wc", "-l", "--", name]), and validate names.

Problem 4: SQL from input (DB-API parameter binding)

  • The DB-API (PEP 249) is the standard interface every Python database driver follows (connect, cursor, execute).
  • Drivers support placeholders; you pass the values as a separate argument to execute. sqlite3 uses ? (or :name); psycopg and mysqlclient use %s.
  • Gluing input in with +, % formatting or an f-string (f"...{x}...") is still gluing: injectable.
# DB-API parameter binding with sqlite3 (built into Python).
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users(name TEXT, pass TEXT)")
db.execute("INSERT INTO users VALUES ('asha', 'chai123')")
typed = "x' OR '1'='1"                       # attacker's password

q = "SELECT name FROM users WHERE name='asha' AND pass='" + typed + "'"
print("glued with + :", db.execute(q).fetchall())         # logged in!

rows = db.execute("SELECT name FROM users WHERE name=? AND pass=?",
                  ("asha", typed)).fetchall()
print("placeholders?:", rows)                             # rejected

Real output:

glued with + : [('asha',)]
placeholders?: []

ORMs such as Django's ORM and SQLAlchemy parameterise for you, as long as you don't build raw SQL strings with input (.raw(), text() with f-strings).

Problem 5: tokens, comparisons and file paths

secrets vs random; hashlib and hmac.compare_digest

  • random is a PRNG (a formula from a seed), "designed for modelling and simulation, not security or cryptography" (Python docs).
  • secrets (added in Python 3.6) gives "the most secure source of randomness that your operating system provides": secrets.token_urlsafe(), token_hex(), choice(), randbelow(). The docs say it "should be used in preference to" random for secrets.
  • hashlib makes hashes (fixed-size fingerprints) such as SHA-256.
  • hmac makes keyed hashes (signatures) and provides hmac.compare_digest(a, b), a constant-time comparison: it takes the same time whether the first or the last character differs.
  • == stops at the first different character, so the time it takes leaks how much of a guess was right. A timing attack measures those tiny differences.
# Tokens and comparisons for a password-reset link.
import random, secrets, hashlib, hmac

random.seed(2026)                       # random: a formula from a seed
print("random token  :", random.getrandbits(64))
random.seed(2026)
print("same seed     :", random.getrandbits(64), "<- predicted!")

print("secrets token :", secrets.token_urlsafe(16))   # OS randomness

stored = hashlib.sha256(b"reset-8841").hexdigest()     # what we saved
sent = hashlib.sha256(b"reset-8841").hexdigest()       # what the link sent
print("== equal?     :", stored == sent)               # stops early
print("compare_digest:", hmac.compare_digest(stored, sent))  # same time

Real output (the secrets token changes every run):

random token  : 5893448777124979737
same seed     : 5893448777124979737 <- predicted!
secrets token : yZfLdXJswMX_Tof4r-9ejw
== equal?     : True
compare_digest: True

For passwords, don't use plain SHA-256: use a slow salted hash (hashlib.scrypt, or the bcrypt/argon2-cffi packages).

pathlib path safety (path traversal)

Real-life example: "go to locker 5, then out the back door, to the office": the visitor leaves the locker room.

  • In a path, .. means "the parent folder". uploads/../secret.txt is really secret.txt, outside uploads.
  • Path traversal (directory traversal): using ../ (or absolute paths) in a file name to reach files outside the allowed folder.
  • pathlib.Path.resolve() turns a path into its real absolute location, following every .. and symbolic link. Path.is_relative_to(base) (Python 3.9+) checks the result is still inside base.
# Serve a user's file from the uploads folder only.
from pathlib import Path

BASE = Path("uploads").resolve()
BASE.mkdir(exist_ok=True)
(BASE / "menu.txt").write_text("chai 10, samosa 15")
Path("secret.txt").write_text("DB_PASSWORD=chai123")   # OUTSIDE uploads

def read_unsafe(name):
    return (BASE / name).read_text()                   # trusts the name

def read_safe(name):
    p = (BASE / name).resolve()                        # follow the ../
    if not p.is_relative_to(BASE):
        raise PermissionError(f"blocked: {name} is outside uploads/")
    return p.read_text()

print("unsafe menu.txt     :", read_unsafe("menu.txt"))
print("unsafe ../secret.txt:", read_unsafe("../secret.txt"))  # escaped!
print("safe   menu.txt     :", read_safe("menu.txt"))
try:
    read_safe("../secret.txt")
except PermissionError as e:
    print("safe   ../secret.txt:", e)

Real output:

unsafe menu.txt     : chai 10, samosa 15
unsafe ../secret.txt: DB_PASSWORD=chai123
safe   menu.txt     : chai 10, samosa 15
safe   ../secret.txt: blocked: ../secret.txt is outside uploads/

Note: BASE / "/etc/passwd" gives /etc/passwd (an absolute name replaces the base), which the same check also blocks. Better still, store uploads under random names you choose (secrets.token_hex(16)) and keep the original name only as data.

Problem 6: web templates and framework settings

Jinja2 autoescape

  • A template is a page with blanks (<p>{{ c }}</p>) that the program fills in. Jinja2 is Python's most used template engine (Flask uses it).
  • XSS, cross-site scripting (our web episodes): user text placed into a page as real HTML, so a <script> runs in every visitor's browser.
  • Escaping turns <, >, &, " into &lt;, &gt;, &amp;, &#34;, so the browser shows them as text.
  • Autoescape escapes every {{ }} value automatically. In plain Jinja2, Template(...) defaults to autoescape=False; the docs say "you are encouraged to explicitly configure autoescaping" and recommend select_autoescape() (on for .html, .htm, .xml). Flask's docs: "Flask automatically escapes HTML" in its templates. Never mark user input as safe (|safe, Markup(user_text)).
# Jinja2 templates: autoescape turns < > & " into harmless text.
from jinja2 import Environment

comment = '<script>alert("hi")</script>'          # what a user posted

raw = Environment(autoescape=False).from_string("<p>{{ c }}</p>")
print("autoescape off:", raw.render(c=comment))     # a real <script> tag!

safe = Environment(autoescape=True).from_string("<p>{{ c }}</p>")
print("autoescape on :", safe.render(c=comment))    # just text

Real output:

autoescape off: <p><script>alert("hi")</script></p>
autoescape on : <p>&lt;script&gt;alert(&#34;hi&#34;)&lt;/script&gt;</p>

Django and Flask security settings

Django and Flask are the two most popular Python web frameworks.

Setting Why
DEBUG = False in production (Flask: never run with debug=True publicly) debug pages show code, settings and sometimes an interactive console to anyone who triggers an error
SECRET_KEY from the environment, never in git it signs sessions and cookies; if it leaks, attackers can forge logged-in sessions
Django ALLOWED_HOSTS only answer requests for your real domain names
keep Django's CsrfViewMiddleware on (Flask: Flask-WTF CSRF) blocks cross-site request forgery
SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE (Django) / SESSION_COOKIE_SECURE (Flask), plus HttpOnly cookies travel only over HTTPS and can't be read by page scripts
use the ORM and templates as intended they parameterise SQL and escape HTML for you

Django ships a checker: python manage.py check --deploy lists missing production settings.

Problem 7: tools that find the rest

Bandit (static analysis)

  • Static analysis reads code without running it and flags risky patterns.
  • Bandit is a free static analyser for Python from PyCQA (the Python Code Quality Authority). Each finding has a test ID (e.g. B602), a severity and a confidence.

The toy app scanned:

import pickle, subprocess, yaml, random

def run(name):
    subprocess.run("wc -l " + name, shell=True)

def load(data):
    return pickle.loads(data)

def config(text):
    return yaml.load(text, Loader=yaml.Loader)

def calc(text):
    return eval(text)

def token():
    return random.random()

Real report (bandit -q -f custom --msg-template "{line}: {test_id} [{severity}] {msg}" app.py):

1: B403 [LOW] Consider possible security implications associated with pickle module.
4: B602 [HIGH] subprocess call with shell=True identified, security issue.
7: B301 [MEDIUM] Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
10: B506 [MEDIUM] Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().
13: B307 [MEDIUM] Use of possibly insecure function - consider using safer ast.literal_eval.
16: B311 [LOW] Standard pseudo-random generators are not suitable for security/cryptographic purposes.

Run bandit -r src/ in CI on every pull request. Mark a reviewed false positive with # nosec B311 and a comment explaining why.

pip-audit (known-vulnerable packages)

  • pip-audit checks installed packages or a requirements.txt against a database of known vulnerabilities (the PyPI advisory database / OSV), like OWASP Dependency-Check does for Java.
  • It checks the whole tree, including transitive dependencies.
$ cat requirements.txt
jinja2==2.10
requests==2.19.0
$ pip-audit -r requirements.txt
Found 49 known vulnerabilities in 4 packages
Name     Version ID              Fix Versions
-------- ------- --------------- -------------
jinja2   2.10    PYSEC-2021-66   2.11.3
jinja2   2.10    PYSEC-2019-217  2.10.1
requests 2.19.0  PYSEC-2018-28   2.20.0
requests 2.19.0  PYSEC-2023-74   2.31.0
idna     2.7     PYSEC-2024-60   3.7
urllib3  1.23    PYSEC-2019-133  1.24.2
...

(Excerpt of the real report; it lists every advisory.) idna and urllib3 were never listed: they are dependencies of requests. Fix by upgrading to the versions in "Fix Versions", then re-run.

Virtual environments and hash-pinned requirements

  • A virtual environment (python3 -m venv venv, then . venv/bin/activate) is a private folder of packages for one project, so projects don't share or mix versions, and you know exactly what each uses.
  • Pinning means listing exact versions (jinja2==3.1.6).
  • Hash-pinning also lists the SHA-256 hash of the exact file: jinja2==3.1.6 --hash=sha256:85ece445.... pip install --require-hashes -r requirements.txt refuses any file whose hash doesn't match, so a swapped or tampered package can't sneak in. Tools like pip-compile --generate-hashes (pip-tools) write these files for you.

Real output:

$ pip hash jinja2-3.1.6-py3-none-any.whl
--hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67

$ pip install --require-hashes -r bad.txt        (bad.txt has a wrong hash)
ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
    jinja2==3.1.6 from https://files.pythonhosted.org/.../jinja2-3.1.6-py3-none-any.whl (from -r bad.txt (line 1)):
        Expected sha256 0000000000000000000000000000000000000000000000000000000000000000
             Got        85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67

The whole chain

  1. eval(input) → ast.literal_eval or a real parser.
  2. pickle / yaml.load → json, yaml.safe_load, or an hmac signature.
  3. shell=True → a list of arguments; shlex.quote if you must.
  4. SQL with + or f-strings → ? / %s placeholders.
  5. random, ==, ../ → secrets, hmac.compare_digest, resolve() + is_relative_to().
  6. Templates → autoescape on; DEBUG off; SECRET_KEY out of git.
  7. The rest → Bandit, pip-audit, virtual environments, --require-hashes.

Common mistakes (and the fix)

Mistake What you see Why Fix
eval(request_text) unsafe (code) -> /tmp/... (the code ran) text runs as code ast.literal_eval(text) or a parser
pickle.loads(uploaded_bytes) !! code ran while LOADING the pickle !! loading calls functions json.loads, or verify an hmac first
yaml.load(text, Loader=yaml.Loader) Bandit B506; a !!python/... tag runs full loader builds objects yaml.safe_load(text)
subprocess.run("wc -l " + name, shell=True) INJECTED: a 2nd command ran the shell reads ; subprocess.run(["wc", "-l", "--", name])
f"... pass='{typed}'" in SQL [('asha',)] (logged in) input became SQL execute("... pass=?", (typed,))
random.getrandbits(64) as a token same seed : ... <- predicted! seeded PRNG secrets.token_urlsafe(16)
if token == stored: works, but leaks timing early exit hmac.compare_digest(token, stored)
open(BASE / name) unsafe ../secret.txt: DB_PASSWORD=chai123 .. escapes the folder resolve() + is_relative_to(BASE)
Environment() / autoescape=False for HTML a real <script> in the page no escaping autoescape=select_autoescape()
DEBUG = True in production full error pages for anyone debug info leaks DEBUG = False; manage.py check --deploy
SECRET_KEY = "abc123" committed key in git history secret in code os.environ["SECRET_KEY"]

Mini project: harden a toy file-share script

Write share.py with three commands: upload <path> (copy a file into uploads/ under a random secrets.token_hex(8) name and record the original name in SQLite), list (print records), and get <id> (print the file). Requirements: placeholders for every query, resolve()/is_relative_to() for every path, no shell=True, no eval/pickle. Then run bandit share.py and get it to zero findings, and keep its dependencies (if any) in a hash-pinned requirements.txt that pip-audit reports clean.

Practice

1. Make the calculator safe without eval (it must handle 2*21 and (10+5)/3).

Solution
import ast, operator as op
OPS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.USub: op.neg}

def calc(text):
    def walk(n):
        if isinstance(n, ast.Expression): return walk(n.body)
        if isinstance(n, ast.Constant) and type(n.value) in (int, float): return n.value
        if isinstance(n, ast.BinOp) and type(n.op) in OPS: return OPS[type(n.op)](walk(n.left), walk(n.right))
        if isinstance(n, ast.UnaryOp) and type(n.op) in OPS: return OPS[type(n.op)](walk(n.operand))
        raise ValueError("only numbers and + - * / are allowed")
    return walk(ast.parse(text, mode="eval"))

print(calc("2*21"), calc("(10+5)/3"))   # 42 5.0

ast.parse only parses; nothing runs. Every node type is checked against an allow-list.

2. Fix the wc toy two ways.

Solution
subprocess.run(["wc", "-l", "--", name], capture_output=True, text=True)        # best: no shell
subprocess.run("wc -l -- " + shlex.quote(name), shell=True, capture_output=True, text=True)  # if a shell is unavoidable

3. Sign a pickle (or any bytes) with hmac so you only load data you made.

Solution
import hmac, hashlib, os, pickle
KEY = os.environ["CACHE_KEY"].encode()

def dump(obj):
    data = pickle.dumps(obj)
    return hmac.new(KEY, data, hashlib.sha256).digest() + data

def load(blob):
    sig, data = blob[:32], blob[32:]
    if not hmac.compare_digest(sig, hmac.new(KEY, data, hashlib.sha256).digest()):
        raise ValueError("bad signature: not loading")
    return pickle.loads(data)

This proves the bytes came from someone with the key and weren't changed; it does not make untrusted pickles safe.

4. Why does (BASE / name).resolve() matter before is_relative_to, rather than checking the string for ".."?

Solution

A string check misses absolute paths (/etc/passwd), encodings, and symbolic links that point outside. resolve() computes the real final location, so the check is about where you actually end up.

5. pip-audit reports urllib3 1.23, but your requirements.txt lists only requests==2.19.0. What do you do?

Solution

urllib3 is a transitive dependency of requests. Upgrade requests to a fixed version (which allows a fixed urllib3), regenerate your pinned/hashed requirements (e.g. pip-compile --generate-hashes), and re-run pip-audit until it is clean.

Quick quiz

name = input()   # a file name from the user

A: subprocess.run("cat " + name, shell=True)
B: os.system("cat " + name)
C: subprocess.run(["cat", name])
D: subprocess.run(f"cat {name}", shell=True)

Which line is safe with user input?

Answer

C. A list of arguments uses no shell, so the whole input is one file name and ; or | can't start another command. A and D hand a glued string to the shell, and os.system (B) always uses a shell. For a file name, also check that the resolved path stays inside the folder you allow.

Interview questions

  1. Why is eval on user input dangerous, and what can you use instead? It runs arbitrary Python; use ast.literal_eval for literals, or parse and evaluate an allow-listed grammar.
  2. Why is unpickling untrusted data unsafe? Pickle data can tell the loader to call any importable function (via __reduce__), so loading runs code. Use JSON or sign the data.
  3. What does shell=True change in subprocess? The command string goes to /bin/sh, which interprets metacharacters (; | & $()), enabling command injection. Pass a list instead.
  4. How do you prevent SQL injection in Python? Pass values as parameters to execute (DB-API placeholders) or use an ORM correctly; never format SQL strings with input.
  5. When do you use secrets vs random? secrets for anything security-related (tokens, passwords, keys); random only for simulations and games.
  6. What is a timing attack and how does hmac.compare_digest help? Measuring how long a comparison takes reveals how many leading characters were correct; compare_digest takes constant time regardless.
  7. How do you stop path traversal with pathlib? Resolve the joined path and check is_relative_to(base); ideally store files under generated names.
  8. What do Bandit and pip-audit each check? Bandit statically analyses your own code for risky patterns; pip-audit checks your dependencies (including transitive ones) against known vulnerabilities.
  9. What does --require-hashes protect against? Installing a package file that differs from the one you pinned (tampering or a swapped artifact).

Glossary

Term Meaning
eval runs a string as a Python expression
exec runs a string as Python statements
code injection user input that ends up running as code
literal a plain value written directly: 42, "chai", [1, 2], {"a": 1}
ast.literal_eval evaluates only literals; refuses anything that runs code
ast Python's module for parsing code into a tree without running it
pickle Python's object serialization format; loading can run code
__reduce__ special method telling pickle how to rebuild an object (which function to call)
serialization / deserialization turning objects into bytes / rebuilding them
JSON a plain data format: strings, numbers, booleans, null, lists, objects
YAML a human-friendly data format, common for config files
YAML tag a !!... marker telling a loader what type to build
yaml.safe_load PyYAML loader for plain data only
subprocess Python module for running other programs
shell the program that reads command lines (/bin/sh, bash)
shell=True run the command through the shell, which interprets ; | &
command injection user input that starts extra shell commands
shlex.quote quotes a string so a shell treats it as one word
os.system runs a command string through the shell (avoid with input)
DB-API (PEP 249) the standard interface Python database drivers follow
placeholder / parameter binding ? or %s in SQL, with values passed separately
f-string f"...{x}...": string formatting; in SQL it is still gluing
ORM object-relational mapper (Django ORM, SQLAlchemy)
PRNG / seed a formula-based random generator / its starting number
secrets module for cryptographically secure random tokens (Python 3.6+)
hashlib module for hashes such as SHA-256
hmac keyed hashing (signatures); also compare_digest
constant-time comparison a comparison whose time doesn't depend on where the inputs differ
timing attack learning secrets by measuring how long operations take
path traversal using ../ or absolute paths to reach files outside an allowed folder
pathlib Python's object-oriented path module
resolve() gives the real absolute path, following .. and symlinks
is_relative_to() checks a path is inside another (Python 3.9+)
template / Jinja2 a page with blanks filled by the program / Python's main template engine
XSS cross-site scripting: user text placed into a page as live HTML/script
escaping turning < > & " into entities so they show as text
autoescape escaping every template value automatically
select_autoescape Jinja2 helper turning autoescape on for .html/.htm/.xml
Django / Flask the two most popular Python web frameworks
DEBUG framework setting showing detailed error pages; off in production
SECRET_KEY the key that signs sessions and cookies
ALLOWED_HOSTS Django's list of domain names the site answers
CSRF cross-site request forgery
secure / HttpOnly cookie sent only over HTTPS / not readable by page scripts
static analysis reading code without running it to find bugs
Bandit PyCQA's static security analyser for Python
PyCQA the Python Code Quality Authority, which maintains Bandit and other tools
# nosec Bandit comment marking a reviewed line as accepted
pip-audit tool that checks Python dependencies for known vulnerabilities
transitive dependency a dependency of a dependency
virtual environment (venv) a private folder of packages for one project
pinning listing exact package versions
hash-pinned requirements requirements listing each file's SHA-256 hash; installed with --require-hashes

Summary

  • In Python the danger is running things: don't eval/exec input, don't unpickle untrusted bytes, use yaml.safe_load.
  • Use argument lists instead of shell=True, and placeholders instead of gluing SQL.
  • secrets for tokens, hmac.compare_digest for comparing secrets, resolve() + is_relative_to() for paths.
  • Autoescape templates; DEBUG off and SECRET_KEY out of git in Django and Flask.
  • Let tools check: Bandit for your code, pip-audit for your packages, a venv per project and hash-pinned requirements.
  • Next episode: secure coding in JavaScript and Node.js.

Sources (fetched 12 Nov 2026)

  • Python docs, pickle: https://docs.python.org/3/library/pickle.html
  • Python docs, secrets: https://docs.python.org/3/library/secrets.html
  • Jinja2 API docs (autoescape, select_autoescape): https://jinja.palletsprojects.com/en/stable/api/
  • Flask templates (auto-escaping): https://www.mintlify.com/pallets/flask/concepts/templates
  • Bandit 1.9.4 (PyCQA): https://bandit.readthedocs.io/ ; pip-audit 2.10.1: https://pypi.org/project/pip-audit/ (versions and authors from pip show)