--- name: software-data-integrity-failures description: > Security testing skill for OWASP A08:2025 — Software or Data Integrity Failures in Python web applications (FastAPI and Flask). Use this skill whenever the user wants to audit, detect, test, or fix integrity vulnerabilities including: insecure deserialization (pickle, yaml, jsonpickle, dill), mass assignment flaws, untrusted CDN/module inclusion, unsigned updates, CI/CD pipeline integrity, or Subresource Integrity (SRI) checks. Trigger this skill for ANY task involving pickle/deserialization security, CWE-502, CWE-915, CWE-829, CWE-345, or CWE-494, even if the user doesn't explicitly mention OWASP A08. --- # A08:2025 — Software or Data Integrity Failures ## Overview **OWASP rank:** #8 (2025) | **CWEs covered:** 14 | **Avg incidence:** 2.75% This category focuses on **failure to verify integrity of software, code, and data artifacts within your own environment** — distinct from A03's upstream supply chain focus. The core concern is: *can you trust what you're loading, deserializing, or executing?* **Key distinction from A03 (Supply Chain):** - A03 = upstream integrity (your dependencies, CI/CD pipelines) - A08 = runtime integrity (what you actually deserialize, include, or auto-update at runtime) --- ## Critical Risk Areas for Python ### 1. Insecure Deserialization — The #1 Python-Specific Risk `pickle.loads()` on untrusted input **equals arbitrary code execution** via `__reduce__`. This is the single most dangerous A08 vector in Python. **Dangerous functions/modules to flag:** | Module / Function | Risk | Safe Alternative | |---|---|---| | `pickle.loads()` / `pickle.load()` | RCE via `__reduce__` | JSON + Pydantic | | `cPickle.loads()` | Same as pickle | JSON + Pydantic | | `dill.loads()` | Superset of pickle, same RCE risk | JSON + Pydantic | | `jsonpickle.decode()` | Deserializes Python objects | `json.loads()` only | | `shelve.open()` | Backed by pickle | Redis/SQL store | | `yaml.load(data, Loader=None)` | Code execution via `!!python/object` | `yaml.safe_load()` | | `numpy.load(f, allow_pickle=True)` | RCE via pickled arrays | `allow_pickle=False` | | `torch.load(f)` | Pickle-backed by default | `weights_only=True` | **Detection pattern (static analysis):** ```python # Flag any of these patterns in source code DANGEROUS_PATTERNS = [ r'pickle\.loads?\(', r'cPickle\.loads?\(', r'dill\.loads?\(', r'jsonpickle\.decode\(', r'shelve\.open\(', r'yaml\.load\([^)]*(?!safe_load)', r'numpy\.load\([^)]*allow_pickle\s*=\s*True', r'torch\.load\([^)]*(?!weights_only\s*=\s*True)', ] ``` **If pickle is unavoidable — HMAC integrity check:** ```python import hmac, hashlib, pickle, os SECRET = os.environ["PICKLE_HMAC_SECRET"].encode() def safe_serialize(obj) -> bytes: data = pickle.dumps(obj) mac = hmac.new(SECRET, data, hashlib.sha256).digest() return mac + data # prepend 32-byte MAC def safe_deserialize(payload: bytes): mac, data = payload[:32], payload[32:] expected = hmac.new(SECRET, data, hashlib.sha256).digest() if not hmac.compare_digest(mac, expected): raise ValueError("Integrity check failed — data tampered") return pickle.loads(data) ``` --- ### 2. Mass Assignment (CWE-915) Occurs when `request.json` or form data is passed directly into ORM `.update()` without field filtering — allowing attackers to set fields like `is_admin=True` or `role="superuser"`. **Flask — Vulnerable pattern:** ```python # ❌ DANGEROUS — attacker can inject any field user = User.query.get(user_id) user.__dict__.update(request.json) db.session.commit() # Also dangerous: User.query.filter_by(id=user_id).update(request.json) ``` **Flask — Safe pattern:** ```python # ✅ SAFE — explicit allowlist ALLOWED_FIELDS = {"name", "email", "bio"} data = {k: v for k, v in request.json.items() if k in ALLOWED_FIELDS} User.query.filter_by(id=user_id).update(data) ``` **FastAPI — Pydantic prevents mass assignment by default:** ```python # ✅ FastAPI with Pydantic — only declared fields accepted class UserUpdate(BaseModel): name: str | None = None email: str | None = None bio: str | None = None # is_admin, role etc. cannot be set — they're not in the schema @router.patch("/users/{user_id}") async def update_user(user_id: int, body: UserUpdate, db: Session = Depends(get_db)): db.query(User).filter(User.id == user_id).update(body.model_dump(exclude_unset=True)) ``` **Detection pattern:** In Flask, scan for `request.json` or `request.form` flowing into `.update()`, `__dict__.update()`, or ORM bulk-update calls without an intermediate allowlist filter. --- ### 3. Subresource Integrity (SRI) for External Scripts/Styles If your Flask/FastAPI app renders HTML templates that load scripts or stylesheets from external CDNs, those resources must include SRI hashes to prevent CDN compromise from injecting malicious code. **Vulnerable Jinja2 template:** ```html ``` **Secure Jinja2 template:** ```html ``` **How to generate SRI hashes:** ```bash # Using openssl curl -sL https://cdn.example.com/lib.js | openssl dgst -sha384 -binary | openssl base64 -A # Or use srihash.org / unpkg.com automatically provides them ``` **Detection:** Scan Jinja2/HTML templates for `