SAASMENT

Security skill · Find and fix

Secure review: Python.

Review Python code (Django, Flask, FastAPI, scripts, data and ML pipelines) for language-specific security flaws such as unsafe deserialization with pickle and yaml, shell and subprocess injection, template injection, path traversal, weak randomness, assert-based checks, debug settings left on, and unpinned dependencies, then fix and verify with tests. Use when auditing or reviewing a Python codebase or pull request.

Download .zipInstall via MCPFind and fixMIT
  • Code review

Facts

Category
Find and fix
License
MIT
Tags
  • Code review
Version
1.0.0
Last updated
2026-12-02
Folder
secure-review-python/
MCP resource
skill://secure-review-python/SKILL.md
Files
  • SKILL.md
  • LICENSE
  • references/python-patterns.md
Standards

Original Saasment content. Saasment is in early access; this skill does not require joining it.

Install via MCP or as files

Connect your client to https://www.saasment.com/api/mcp (see client setup) and call get_skill:

{
  "name": "get_skill",
  "arguments": {
    "slug": "secure-review-python"
  }
}

Or download the .zip and unpack it into your agent's skills directory:

Terminal, from your project root (user-level: ~/.cursor/skills)

mkdir -p .cursor/skills
curl -fsSL https://www.saasment.com/ai-security/skills/secure-review-python/download.zip -o /tmp/secure-review-python.zip
unzip -o /tmp/secure-review-python.zip -d .cursor/skills
# result: .cursor/skills/secure-review-python/SKILL.md

Review SKILL.md before enabling a skill. Skills are instructions your agent will follow.

SKILL.md

---
name: secure-review-python
description: Review Python code (Django, Flask, FastAPI, scripts, data and ML pipelines) for language-specific security flaws such as unsafe deserialization with pickle and yaml, shell and subprocess injection, template injection, path traversal, weak randomness, assert-based checks, debug settings left on, and unpinned dependencies, then fix and verify with tests. Use when auditing or reviewing a Python codebase or pull request.
license: MIT
metadata:
  author: Saasment
  version: "1.0.0"
  category: both
  tags: "code-review"
---

# Secure review: Python (find and fix)

License: MIT. Copyright (c) 2026 Saasment. Source: https://www.saasment.com/ai-security/skills/secure-review-python

Python makes it easy to turn data into behavior: `pickle` can run code on load, `yaml.load` can build arbitrary objects, `subprocess` with `shell=True` hands a string to a shell, and templates can evaluate expressions. Web frameworks add their own switches (debug mode, allowed hosts, CSRF settings). This skill covers the Python-specific pass; run it together with `secure-code-review-checklist`.

## When to use

- You audit a Python service, library, script collection, notebook repository, or ML pipeline.
- A pull request adds file handling, parsing, subprocess calls, templates, or settings changes.
- A static analysis tool reported Python findings that need confirmation.

## Safe by default

- Review only code you own or are authorized to review. Run probes only in a local or test environment with synthetic data.
- Never load a pickle, joblib, or model file you did not create or cannot verify, not even to inspect it. Inspect such files with a tool that does not execute them, or in a disposable sandbox with no network and no secrets.
- Use a virtual environment for installs, and do not run `setup.py` or build hooks from an untrusted package on a machine with credentials.
- Keep probes harmless (unique marker strings, files in a temporary directory). Do not run payloads that change state or contact other systems.

## Procedure

1. **Inventory.** Identify Python version, framework, entry points (views, routes, CLI, workers, notebooks), how dependencies are pinned, and where settings and secrets come from.
2. **Search the risky APIs** (patterns in `references/python-patterns.md`):
   - Deserialization: `pickle`, `cPickle`, `marshal`, `shelve`, `dill`, `joblib.load`, `torch.load` without safe options, `yaml.load` without a safe loader (see `input-validation-deserialization-review`).
   - Code from strings: `eval`, `exec`, `compile`, `__import__` with user input.
   - Processes: `os.system`, `os.popen`, `subprocess` with `shell=True` or a string command built from input.
   - Files and archives: user input in `open`, `os.path.join`, `send_file`, `tarfile.extractall`, `zipfile.extractall` (path traversal).
   - Templates: `render_template_string`, `Template(user_input)`, Jinja environments without autoescape, `|safe` and `mark_safe` on user data.
   - SQL: f-strings, `%` formatting, or `.format` in queries; `.raw()`, `.extra()`, and `text()` with input (see `sql-injection-find-and-fix`).
   - Network: `requests` with a user-influenced URL, `verify=False`, missing timeouts (see `ssrf-find-and-fix`).
   - Randomness: `random` used for tokens, passwords, or identifiers (use `secrets`).
   - Checks that vanish: `assert` used for validation or authorization (it is removed under `python -O`).
3. **Check framework settings.** Django: `DEBUG`, `ALLOWED_HOSTS`, `SECRET_KEY` source, `SECURE_*` and cookie flags, CSRF middleware, `mark_safe`. Flask: `debug=True`, `SECRET_KEY`, session cookie flags. FastAPI: `Depends` on every protected route, response models that limit returned fields, permissive CORS.
4. **Check dependencies.** Lockfile or hashed requirements present, no unpinned installs in Dockerfiles or CI, advisory scan results triaged (see `dependency-cve-triage-and-patch`).
5. **Fix** with safe equivalents: `json` or a schema library instead of pickle for data; `yaml.safe_load`; `subprocess.run([...], shell=False)` with a validated argument list; `pathlib.Path.resolve()` plus a containment check; ORM parameters; `secrets.token_urlsafe()`; explicit `raise` or HTTP errors instead of `assert`; settings read from the environment with debug off by default.
6. **Add regression tests** that feed the hostile input and assert it is rejected or treated as literal text.

## Verification

- Confirm unsafe deserialization without running a payload: show that untrusted bytes reach `pickle.loads` or `yaml.load` by tracing the call path and adding a test that asserts the input type is validated before parsing. For `yaml`, a test that passes a tagged document and expects a safe-loader error confirms the fix.
- Confirm subprocess fixes with an argument that contains spaces, `;`, and `$()`; assert the program receives it as one literal argument.
- Confirm path fixes with `../` and absolute-path inputs against a temporary directory; assert the resolved path stays under the base.
- Run `python -X dev -W error` on the test suite where practical, plus your static analysis (for example Bandit) and dependency audit tool, and compare with the baseline.
- Confirm production settings in a test run of the deployed configuration: debug off, host list restricted, cookies marked secure and HTTP-only.

## Reporting

Table: id, file and line, bug class, reachable by whom, fix, regression test. Note any pickle or model files whose origin you could not verify.

## References

- Python `pickle` security warning: https://docs.python.org/3/library/pickle.html
- Python `subprocess` security considerations: https://docs.python.org/3/library/subprocess.html#security-considerations
- Python `secrets` module: https://docs.python.org/3/library/secrets.html
- Django deployment checklist: https://docs.djangoproject.com/en/stable/howto/deployment/checklist/
- Companion skills: `secure-code-review-checklist`, `input-validation-deserialization-review`, `sql-injection-find-and-fix`.

Helper files

LICENSE
MIT License

Copyright (c) 2026 Saasment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
references/python-patterns.md
# Python risky patterns

License: MIT. Copyright (c) 2026 Saasment.

Search leads only. Confirm that untrusted data reaches each hit before calling it a finding.

## Search commands

```bash
# Deserialization and code from strings
rg -n 'pickle\.loads?|cPickle|marshal\.loads?|shelve\.open|dill\.loads?|joblib\.load|torch\.load|yaml\.load\(|\beval\(|\bexec\(' --glob '*.py'

# Processes
rg -n 'os\.system|os\.popen|subprocess\.[a-z_]+\(.*shell\s*=\s*True' --glob '*.py'

# Archives and paths
rg -n 'extractall|send_file|send_from_directory|open\(.*request' --glob '*.py'

# Templates and raw HTML
rg -n 'render_template_string|mark_safe|\|safe\b|autoescape\s*=\s*False' --glob '*.{py,html,jinja,j2}'

# Weak randomness and assert-as-check
rg -n 'import random|random\.(random|randint|choice)|^\s*assert ' --glob '*.py'

# TLS verification off, missing timeouts
rg -n 'verify\s*=\s*False' --glob '*.py'
```

## Deserialization

```python
# Risky: pickle runs code from the data while loading
data = pickle.loads(request.body)

# Safer: a data-only format plus validation
payload = json.loads(request.body)
model = Payload.model_validate(payload)   # any schema library works

# Risky vs safer YAML
config = yaml.load(text)                  # can construct arbitrary objects
config = yaml.safe_load(text)
```

## Processes

```python
# Risky: the shell parses the string
subprocess.run(f"convert {filename} out.png", shell=True)

# Safer: argument list, no shell, validated input, timeout
subprocess.run(["convert", validated_name, "out.png"], check=True, timeout=30)
```

## Paths and archives

```python
from pathlib import Path

BASE = Path("/srv/uploads").resolve()

def safe_path(name: str) -> Path:
    candidate = (BASE / name).resolve()
    if BASE not in candidate.parents and candidate != BASE:
        raise ValueError("path escapes base directory")
    return candidate

# Archives: check every member name with the same containment test before extracting,
# and reject links, absolute paths, and entries whose resolved path leaves the target.
```

## Tokens and checks

```python
# Risky
token = "".join(random.choice(string.ascii_letters) for _ in range(32))
assert user.is_admin          # removed when Python runs with -O

# Safer
token = secrets.token_urlsafe(32)
if not user.is_admin:
    raise PermissionDenied()
```

## Framework settings to confirm

| Framework | Check |
| --- | --- |
| Django | `DEBUG = False`, narrow `ALLOWED_HOSTS`, secret key from the environment, `SESSION_COOKIE_SECURE`, `CSRF_COOKIE_SECURE`, `python manage.py check --deploy` |
| Flask | `debug` off, strong `SECRET_KEY` from the environment, cookie flags set, no `app.run(host="0.0.0.0", debug=True)` in deployed code |
| FastAPI | auth dependency on every protected route, response models that omit internal fields, CORS origins listed explicitly |

Related

Companion skills

Questions

How do I install the Secure review: Python skill?

Download https://www.saasment.com/ai-security/skills/secure-review-python/download.zip and unzip it into your agent's skills directory (for example .cursor/skills, .claude/skills, .agents/skills, or .github/skills) so that secure-review-python/SKILL.md exists. Or connect to https://www.saasment.com/api/mcp and call the get_skill tool with the slug secure-review-python.

What license is the Secure review: Python skill under?

It is original Saasment content under the MIT license, stated in the SKILL.md frontmatter and in the LICENSE file in the skill folder.

Is it safe to run this skill?

A skill is a set of instructions your agent follows, so read SKILL.md first. It tells the agent to test only systems you own or are authorized to test, to use test environments and synthetic data, and to avoid destructive probes. Downloading it does not run any code on your machine.

← All security skills

Try the platform.

Open the demo workspace with mock data. No login. Register from the banner when you want early access. No security team. No call.

Try the platform