python-security-pitfalls
БесплатноБез исполняемых скриптовНе проверенUse when reviewing Python changes - Django, Flask and FastAPI handlers, subprocess, SQL, Jinja2, format strings, and data/ML code that loads pickles, models…
от makifbaysal★ 123 звезды на GitHubОб этом скилле
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)
torch.loaddefaults toweights_only=Truefrom PyTorch 2.6; on an older pinned torch the plain call is unsafe.- Hugging Face
from_pretrained(..., trust_remote_code=True)runs Python from the model repository; with a user-chosen repo id it is remote code execution. - Keras
load_model(..., safe_mode=False)allows Lambda-layer code. - Celery or Kombu with
accept_content=["pickle"], pickled values in a shared Redis or cache,shelve,dill,cloudpickleon data another party writes. - Prefer safetensors, ONNX, skops, JSON, Parquet.
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
eval,exec,compile,__import__/importlib.import_modulewith input.DataFrame.query(expr)/pd.eval(expr)with a user-built expression — evaluation, not filtering.- Format-string injection: a user-supplied format string can walk attributes.
# ❌ 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)
- Flask
render_template_string(f"…{user}…")→ server-side template injection. jinja2.Environment()has autoescape off by default outside Flask/Django; rendering HTML with it is XSS unlessautoescape=select_autoescape().- Django
mark_safe,|safe,{% autoescape off %},format_htmlmisused with pre-joined strings.
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
tarfile.extractall()withoutfilter="data"(default only on Python 3.14+);os.path.join(base, user)with absolute input.lxmlparsing untrusted XML with entity resolution; preferdefusedxml.randomfor tokens →secrets;hashlib.md5/sha256for passwords → argon2/bcrypt.requests.get(..., verify=False),ssl._create_unverified_context().tempfile.mktemp()(race) →mkstemp/NamedTemporaryFile.assert user.is_adminas an access check — removed underpython -O(CWE-617).
8. Notebooks and Pipelines
- Notebook injection is reported only with a concrete untrusted-input path (a papermill parameter from a request, a cell that evals fetched text).
- Committed notebook outputs that print tokens, connection strings or customer rows are leaked secrets/data — check outputs, not only code cells.
- Orchestrator templates (Airflow
params/dag_run.confinbash_command, dbt Jinja with run-time vars) → injection-and-dangerous-sinks.
Common Mistakes
- Flagging
pickle.loadon an artifact the
Установить python-security-pitfalls в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл python-security-pitfalls?
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
Как установить скилл python-security-pitfalls?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл python-security-pitfalls запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic