Python security pitfalls

From makifbaysal/tasktrooper · View interactive version

Python security pitfalls is an AI agent skill from the GitHub repository makifbaysal/tasktrooper. Use when reviewing Python changes - Django, Flask and FastAPI handlers, subprocess, SQL, Jinja2, format strings, and data/ML code that loads pickles, models, notebooks or remote model code

How to use this skill

Skill file

Python Security Pitfalls (services, data and ML)

Overview

Python's dangerous calls are few and well known — pickle, eval, shell=True, f-string SQL — but data and ML code uses them as everyday tools: models are pickles, configs are YAML, notebooks evaluate whatever they are given. The question is always where the bytes come from.

1. Model and Data Loading (CWE-502) — the data/ML hot spot

Loading a pickle-based file runs code chosen by whoever wrote the file.

# ❌ an uploaded or downloaded model file executes code on load
model = torch.load(path, weights_only=False)
clf = joblib.load(user_upload)
df = pd.read_pickle(s3_key_from_request)
arr = np.load(path, allow_pickle=True)
cfg = yaml.load(text, Loader=yaml.Loader)

# ✅
model.load_state_dict(safetensors.torch.load_file(path))
arr = np.load(path)                    # allow_pickle defaults to False
cfg = yaml.safe_load(text)

A finding when the file can come from outside the trust boundary: an upload, a URL, a user-chosen hub id, a shared bucket other tenants write. A model the team trains and ships in its own artifact store is not attacker input.

2. Code Evaluation

# ❌ template = "{user.__class__.__init__.__globals__[SECRET_KEY]}"
message = template.format(user=user)
# ✅ user text is the value, never the format
message = "Hello {name}".format(name=user.name)

3. Commands (CWE-78)

# ❌
os.system(f"zip -r {out} {folder}")
subprocess.run(f"git log {ref}", shell=True)
# ✅
subprocess.run(["git", "log", "--", ref], check=True)

shlex.quote is acceptable when a shell is truly required; shell=True with a constant string is fine.

4. SQL (CWE-89)

cursor.execute(f"… {x}"), cursor.execute("… %s" % x), SQLAlchemy text(f"…"), Django .raw(f"…"), .extra(where=[…]), RawSQL. Safe: cursor.execute("… %s", (x,)), ORM filters, text("… :x").bindparams(x=x).

5. Templates and XSS (CWE-79, CWE-1336)

6. Framework Specifics

Django: @csrf_exempt on a cookie-authenticated view; a production settings change to DEBUG = True or ALLOWED_HOSTS = ["*"] with host-built absolute URLs (reset-link poisoning); SECRET_KEY literal in production settings; DRF permission_classes = [AllowAny] or a serializer with fields = "__all__" on a writable endpoint.

Flask: app.run(debug=True) reachable beyond localhost — the Werkzeug debugger console executes code; send_file(os.path.join(...)) with <path:…> routes (path-traversal-and-file-handling).

FastAPI: a new APIRouter included without the dependencies=[Depends(current_user)] its siblings carry; an endpoint returning the ORM object with no response_model, leaking every column; a Pydantic request model that includes role/is_admin.

7. Files, XML, Crypto, Transport

8. Notebooks and Pipelines

Common Mistakes

Red Flags

References (names and links only)

Bandit · PyTorch torch.load security note · Hugging Face security · Django security · CWE-78, 79, 89, 502, 617, 1336 · OWASP Top 10:2025 A08

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.