🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Security: Injection, Secrets, and Hashing

Python SecurityđŸŸĸ Free Lesson

Python Security: Injection, Secrets, and Hashing

Security bugs in Python services are rarely exotic. They are string-built SQL, a token committed to git, a password table full of unsalted digests, a pickle loaded from user input, a file path taken from a query parameter. Every one of them belongs to a small set of recurring mistakes, and every one has a boring, systematic fix. This lesson walks the highest-frequency categories in the order an attacker would probe them, with the stdlib-first approach that keeps a service auditable.

What You'll Learn

  • 1Eliminate SQL and shell injection by construction rather than by filtering
  • 2Separate validation of input from presentation of output
  • 3Store and rotate secrets so they never enter version control
  • 4Hash and verify passwords with a salted, deliberately slow algorithm

Injection: fix it at construction, not with escaping

Injection happens wherever data is interpreted as instructions: SQL, a shell command, a template, a regex that can be made to backtrack. The reliable defence is structural — never assemble instructions from data. In SQL that means placeholders, always, regardless of how harmless the value looks; the driver sends the statement and the parameters separately, so a quote character in the data can never terminate the literal.

python
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
conn.executemany(
    "INSERT INTO users (name) VALUES (?)",
    [("alice",), ("bob",), ("mallory",)],
)

# Attacker sends: ' OR 1=1 --
name = "' OR 1=1 --"
bad = f"SELECT * FROM users WHERE name = '{name}'"
print(conn.execute(bad).fetchall())     # 3 rows — the filter is gone

# The parameterised form sends SQL and data on separate channels
rows = conn.execute(
    "SELECT id, name FROM users WHERE name = ?", (name,)
).fetchall()
print(rows)                             # []

The shell has the same structure. Pass an argument vector and the operating system hands each element to the program verbatim, so metacharacters in the value are just characters in one argument.

python
import subprocess

path = "photo.png; rm -rf ~"
result = subprocess.run(["echo", path], capture_output=True, text=True)
print(result.stdout.strip())            # the whole string is a single argument
# subprocess.run(f"echo {path}", shell=True)   # never: the shell reads the ';'

Filtering is not a substitute. Blocklists miss encodings, comments, and alternate syntaxes; allowlists for identifiers (table and column names) are legitimate because placeholders only bind values, so dynamic identifiers must be validated against a known set. When you must build an identifier, map the caller's choice to a fixed string yourself rather than interpolating anything the caller supplied.

Validation decides what is true; sanitisation decides how it looks

Validation checks that an incoming value matches the shape your logic requires and rejects it otherwise, while sanitisation is about rendering text safely in a particular destination. Confusing the two produces code that strips angle brackets from an email address and then happily stores 999999999 as an account balance.

python
from pydantic import BaseModel, Field, ValidationError

class Signup(BaseModel):
    email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$")
    age: int = Field(ge=13, le=120)
    handle: str = Field(pattern=r"^[a-z0-9_]{3,20}$")


try:
    Signup(email="not-an-email", age=999, handle="ok")
except ValidationError as exc:
    print(exc.errors()[0]["loc"], exc.errors()[0]["type"])

account = Signup(email="[email protected]", age=34, handle="ada")
print(account.model_dump())

Validate at the boundary — the HTTP handler, the queue consumer, the CLI parser — so the interior of the program can assume well-formed data, and reject rather than repair. Repairing input silently is how DROP TABLE becomes DROP TABLE with the spaces squeezed out and still working.

Secrets: they are configuration, and configuration is not source code

A key in a commit is compromised forever, because history travels: it lands in clones, in CI logs, in archive downloads, and in every fork. Treat credentials as environment-specific configuration injected at runtime, and make the failure loud when one is missing rather than falling back to a default.

python
import os
from pathlib import Path

from dotenv import load_dotenv

# loads a local .env that is listed in .gitignore and never deployed
load_dotenv(Path(__file__).resolve().parent / ".env")


def required(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"missing required environment variable: {name}")
    return value


STRIPE_KEY = required("STRIPE_API_KEY")
DB_URL = required("DATABASE_URL")

Beyond the environment file: add .env and credential paths to .gitignore before the first secret exists, rotate any key that has ever been committed (history rewrite is not rotation), prefer your cloud provider's secret store or keyring for anything long-lived, and scope each credential to the single service that uses it so one leak does not become two. Keep secrets out of tracebacks too — logging a full request body or a connection URL is the same leak with extra steps.

Passwords: salt, stretch, compare in constant time

Fast hashes are wrong for passwords by design; the point is to make each guess expensive for the attacker while staying acceptable for one legitimate login. Use a dedicated algorithm — Argon2 or bcrypt — or the stdlib's pbkdf2_hmac, with a fresh random salt per user and an iteration count you can raise over time.

python
import hashlib
import hmac
import os

ITERATIONS = 600_000


def hash_password(password: str) -> bytes:
    salt = os.urandom(16)
    digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, ITERATIONS)
    return b"|".join((str(ITERATIONS).encode(), salt, digest))


def verify_password(password: str, stored: bytes) -> bool:
    iterations, salt, expected = stored.split(b"|", 2)
    candidate = hashlib.pbkdf2_hmac(
        "sha256", password.encode(), salt, int(iterations)
    )
    return hmac.compare_digest(candidate, expected)


stored = hash_password("correct horse battery staple")
print(verify_password("correct horse battery staple", stored))
print(verify_password("wrong password", stored))

Three details carry most of the weight. The salt is stored with the hash so it is unique per user and available at verification; hmac.compare_digest compares without leaking how many bytes matched through timing; and the stored record carries its own iteration count so you can rehash on next login when you raise the cost. Never roll your own construction from SHA-256 alone — that is fast, unsalted, and instantly crackable with a rainbow table.

Deserialisation and dynamic execution

pickle is an executable format: unpickling attacker-controlled bytes runs arbitrary constructors and can call anything reachable from your imports. It is safe for data you produced yourself in the same trusted process and unsafe for everything else — cookies, uploads, cache entries from a shared store, messages on a queue that other services can publish to.

The same reasoning covers the rest of the family. yaml.load without a safe loader can construct arbitrary objects; use yaml.safe_load. eval, exec, and compile turn text into code, and ast.literal_eval is the narrow alternative when you only need literals. marshal and shelve are not safe against hostile input either. JSON has no code paths, which is why it should be the default interchange format across trust boundaries.

Errors and logs leak as happily as endpoints

An exception message that echoes a query, a traceback rendered to the browser, or a debug endpoint left enabled in production all hand an attacker your schema and your file layout for free. Return a generic failure to the client with a correlation id, log the detail server-side, and keep the debug flag off outside development. Framework defaults are usually right; the leaks appear when someone catches an exception and returns str(exc) because it was convenient during development.

Logging needs the same discipline as storage. Redact known sensitive keys at the handler level rather than trusting every call site to remember, avoid logging full request bodies, and treat URLs as untrusted — query strings routinely carry tokens and reset codes. Finally, keep dependencies current and run a scanner in CI: a large share of real breaches exploit a vulnerability that was disclosed and patched months before the incident, which makes patching cheaper than any clever application-level defence.

Paths, URLs, and the rest of the boundary

File paths from user input invite traversal, so resolve the candidate and confirm it stays inside the intended root before opening it, and never let a caller supply the base directory. Server-side requests invite SSRF: an internal metadata endpoint or an admin-only service is reachable from your backend, so allowlist outbound destinations instead of trusting the URL. Redirects, template names, module imports, and regex patterns are all the same problem wearing different clothes — a value from outside becoming a decision inside.

ThreatTypical Python mistakeStructural fix
SQL injectionf-string in executePlaceholders; allowlist identifiers
Command injectionshell=True with user inputArgument vector, no shell
Secret exposureKey committed or loggedEnvironment or secret store; rotate
Password theftUnsalted fast digestArgon2, bcrypt, or PBKDF2 with salt
Remote code executionpickle or yaml.load on inputJSON; safe loaders only
Path traversalConcatenated user pathResolve and confirm the root

Common Mistakes

Escaping quotes as the primary defence against SQL injection

Fix: Use parameterised queries; escaping rules differ per database and break under encodings you do not control

Generating a password hash with hashlib.sha256 in one line

Fix: Use a slow, salted KDF such as Argon2, bcrypt, or pbkdf2_hmac with a per-user random salt

Loading a pickle or YAML document received over the network

Fix: Treat both as code; exchange JSON or a schema-validated format across any trust boundary

Removing a leaked key from the latest commit

Fix: Rotate the key immediately — history, clones, and CI logs still hold the old one

Best Practices

  • Validate at the trust boundary and let the interior assume well-formed data
  • Fail fast on a missing secret instead of falling back to an empty string or a default
  • Keep credentials out of git, logs, and tracebacks by filtering them at the logging handler
  • Compare secrets with hmac.compare_digest and store the KDF parameters alongside the digest
  • Run a dependency scanner in CI and keep the framework patched; most disclosed exploits target known versions

Interview Questions

Q1: Why are placeholders safe when string concatenation is not?

The SQL text and the parameter values travel to the database through separate channels. The parser sees only the parameterised statement, so a quote in the data cannot change where a literal ends.

Q2: Why not hash a password with plain SHA-256?

It is far too fast: a GPU can test billions of guesses per second, and without a salt identical passwords produce identical digests, enabling precomputed tables. A password KDF adds a per-user salt and a deliberate cost factor.

Q3: Is it acceptable to unpickle data from your own cache?

Only if the cache cannot be written by anyone else and the key cannot be replaced by an attacker. If another service or user can influence the bytes, unpickling is remote code execution.

Q4: What is the correct response to a secret found in git history?

Rotate it first, then revoke access, then clean history if the leak was severe. Removing the file in a new commit does not invalidate anything, because clones and logs retain the old value.

Key Takeaways

  • Build instructions from templates and bind data to placeholders; never filter your way to safe SQL
  • Validate at the boundary, reject instead of repairing, and keep sanitisation separate as a rendering concern
  • Secrets belong in the environment or a secret store, and a leaked key is rotated, not deleted
  • Password storage needs a salted, slow algorithm plus constant-time comparison and stored cost parameters
  • Anything that executes or reconstructs objects from bytes — pickle, yaml.load, eval — is code, and must never see untrusted input
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement