#Why this matters
Security automation scripts, API backends, and administrative utilities constantly read untrusted data from HTTP parameters, filenames, log lines, and user forms. Earlier lessons covered parsing text and calling network services in Python; once your code acts on external input, a single careless assumption can let a user read arbitrary files, run shell commands, or learn internal server paths from a crash message.
Secure input handling is not about memorizing clever attack payloads. It is about enforcing strict boundaries between data and execution, and keeping failures predictable when unexpected input arrives.
#Input validation: allow-lists over block-lists
Validation checks whether incoming data conforms to what the application expects before any business logic runs. A block-list tries to strip or reject known bad characters such as ;, |, or ../. Block-lists routinely fail because attackers use alternate encodings, uppercase variants, or overlooked metacharacters. An allow-list defines the exact permitted shape and rejects everything else.
| Approach | How it decides | Typical outcome |
|---|---|---|
| Block-list | Rejects known dangerous patterns | Bypassed by encoding or missed syntax |
| Allow-list | Accepts only known-good format and range | Rejects unexpected input by default |
| Canonicalization + containment | Resolves path or encoding before checking | Prevents ../ and symlink escapes |
Consider a utility that reads a report file requested by name. Joining strings directly allows ../../etc/passwd to escape the reports folder. Using pathlib.Path.resolve() combined with an allow-list regex closes both syntactic and path-based escapes:
import re
from pathlib import Path
BASE_DIR = Path("/var/app/reports").resolve()
NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,40}\.txt$")
def read_report(filename: str) -> str:
if not NAME_RE.fullmatch(filename):
raise ValueError("Invalid report name")
target = (BASE_DIR / filename).resolve()
if not target.is_relative_to(BASE_DIR):
raise ValueError("Path escapes base directory")
return target.read_text(encoding="utf-8")Notice the order: validate the syntax first, resolve the canonical path on disk, and verify that the resolved target remains inside BASE_DIR.
#Safe OS command execution
Many automation scripts shell out to tools like ping, grep, or tar. Passing a formatted string to subprocess.run(..., shell=True) hands the string to /bin/sh or cmd.exe. If a caller supplies 10.10.10.5; id, the shell executes ping and then runs id.
- Untrusted inputvalidate format (e.g. ipaddress)
- Pass args listsubprocess.run(["ping", "-c", "1", ip], shell=False)
- OS execveexecutes binary directly without shell parsing
Follow three rules whenever Python interacts with the operating system:
- Prefer standard-library modules (
pathlib,shutil,tarfile,socket) over external binaries whenever Python already provides the feature. - Use argument lists with
shell=False(Python's default), so each list element becomes a singleargventry rather than shell syntax. - Guard against argument injection by validating values first and placing
--before positional user arguments on tools that accept it, so a filename like--checkpoint-action=exec=...is never parsed as an option.
Static analysis tools catch unsafe command calls automatically. Running bandit against a project directory flags dangerous patterns such as shell=True (B602):
$ bandit -q -r lab_tool.py
>> Issue: [B602:subprocess_popen_with_shell_equals_true] subprocess call with shell=True identified, security issue.
Severity: High Confidence: High
Location: ./lab_tool.py:8:4
8 return subprocess.run(f"ping -c 1 {host}", shell=True, check=True)Replacing the string command with ipaddress.ip_address(host) validation and subprocess.run(["ping", "-c", "1", str(ip)], check=True) removes the shell parser entirely and clears the bandit finding.
#Error handling that fails closed
Errors reveal how code behaves under stress. Two mistakes dominate real applications: failing open and leaking internals.
Failing open happens when an authorization or validation check hits an exception and lets execution continue anyway, for example using a bare except Exception: pass around a token check. Always fail closed: if a check cannot complete cleanly, deny the request or raise an error.
Leaking internals happens when an application returns raw Python tracebacks, database errors, or full filesystem paths to the user. Attackers use those details to map libraries, file layouts, and query structures. Instead, log the full diagnostic error on the server with a request ID and return a generic message to the caller:
import logging
import uuid
logger = logging.getLogger("lab_app")
def handle_lookup(filename: str) -> tuple[int, str]:
try:
return 200, read_report(filename)
except ValueError:
return 400, "Invalid report identifier."
except OSError:
ref = uuid.uuid4().hex[:8]
logger.exception("Report read failed ref=%s", ref)
return 500, f"Internal error. Reference: {ref}"#Common mistakes
- Client-side validation only: JavaScript checks in a browser improve usability, never security, because anyone can send raw requests with
curl. - Validating before decoding: Checking for
../before URL-decoding or normalizing paths misses%2e%2e%2f. - Assuming
shell=Falseprevents all abuse: Even without a shell, passing unvalidated user strings as flags can trigger argument injection unless you validate values or insert--. - Silencing exceptions with
except: pass: Swallowing errors hides operational bugs and can accidentally bypass security checks.
#Summary
- Use allow-lists to enforce exact expected types, lengths, and character sets, and canonicalize file paths before verifying directory containment.
- Avoid
shell=True; prefer standard-library modules orsubprocess.runwith an argument list, and scan code withbandit. - Design error handling to fail closed, logging full details server-side while returning only generic messages and reference IDs to callers.