Skip to content

hypnguyen1209/offensive-claude / skills/vulnerability-analysis

vulnerability-analysis

Unverified

Use when auditing source code for vulnerabilities — drive CodeQL/Semgrep/Joern to taint untrusted data source-to-sink across injection, memory safety, deserialization/prototype-pollution, secrets/crypto/authz/race, and supply-chain risks

scripts/deser_gadget_scan.py

View on GitHub
#!/usr/bin/env python3
"""
deser_gadget_scan.py - Detect insecure-deserialization sinks and the dependency
preconditions for known gadget chains (Java/.NET/PHP/Python/JS), plus client-side
prototype-pollution sinks.

Two jobs:
  1. SINK DETECTION: flag every deserialization entrypoint reachable from
     untrusted data (readObject, unserialize, pickle.loads, yaml.load,
     node-serialize, RSC Flight decode, _.merge with __proto__ paths).
  2. GADGET PRECONDITION CHECK: parse dependency manifests and warn when a
     library known to host published gadget chains is present (so a sink becomes
     weaponizable, not just theoretical).

Dependencies: Python 3.8+ stdlib only.

Usage:
  python3 deser_gadget_scan.py sinks  ./src
  python3 deser_gadget_scan.py gadgets ./   # scans pom.xml, *.csproj, composer.json, requirements*, package.json
  python3 deser_gadget_scan.py all    ./src --json deser.json

LEGAL: authorized review only. Identifies risk; does not generate payloads.
"""
import argparse
import json
import os
import re
import sys

DESER_SINKS = {
    "java": {
        "ext": (".java", ".kt"),
        "pat": [r"\.readObject\(", r"\.readUnshared\(", r"new ObjectInputStream",
                r"XMLDecoder", r"SerializationUtils\.deserialize\(", r"toObject\(",
                r"yaml\.load\(", r"new Yaml\(\)\.load\(", r"@JsonTypeInfo"],
        "cwe": "CWE-502",
    },
    "dotnet": {
        "ext": (".cs",),
        "pat": [r"BinaryFormatter", r"\.Deserialize\(", r"LosFormatter", r"ObjectStateFormatter",
                r"JavaScriptSerializer", r"TypeNameHandling\s*=\s*TypeNameHandling\.(All|Auto|Objects)",
                r"NetDataContractSerializer", r"SoapFormatter"],
        "cwe": "CWE-502",
    },
    "php": {
        "ext": (".php", ".phtml", ".inc"),
        "pat": [r"unserialize\(", r"yaml_parse\(", r"->__wakeup", r"->__destruct"],
        "cwe": "CWE-502",
    },
    "python": {
        "ext": (".py",),
        "pat": [r"pickle\.loads?\(", r"cPickle\.loads?\(", r"_pickle\.loads?\(",
                r"yaml\.load\((?!.*Loader\s*=\s*yaml\.SafeLoader)", r"jsonpickle\.decode\(",
                r"dill\.loads?\(", r"marshal\.loads\(", r"shelve\.open\("],
        "cwe": "CWE-502",
    },
    "js": {
        "ext": (".js", ".ts", ".jsx", ".tsx"),
        "pat": [r"node-serialize", r"\bunserialize\(", r"funcster", r"serialize-to-js",
                r"\bvm2\b", r"decodeReply\(", r"decodeAction\(", r"createFromReadableStream\("],
        "cwe": "CWE-502",
    },
    "proto_pollution": {  # client/server-side prototype pollution sinks
        "ext": (".js", ".ts", ".jsx", ".tsx"),
        "pat": [r"_\.merge\(", r"_\.mergeWith\(", r"_\.defaultsDeep\(", r"_\.set\(",
                r"_\.setWith\(", r"_\.zipObjectDeep\(", r"_\.unset\(", r"_\.omit\(",
                r"\bmerge\(.*req\.", r"Object\.assign\(.*JSON\.parse",
                r"\[\s*['\"]__proto__", r"\[\s*['\"]constructor"],
        "cwe": "CWE-1321",
    },
}

# Libraries that host PUBLISHED gadget chains -> presence makes a sink exploitable.
GADGET_LIBS = {
    # Java (ysoserial chains)
    "commons-collections": "ysoserial CommonsCollections1-7 RCE chains",
    "commons-beanutils": "ysoserial CommonsBeanutils1 chain",
    "spring-core": "ysoserial Spring1/Spring2 chains",
    "groovy": "ysoserial Groovy1 chain",
    "c3p0": "ysoserial C3P0 chain (URLClassLoader)",
    "javax.xml.bind": "JdbcRowSetImpl JNDI gadget",
    "snakeyaml": "SnakeYAML ScriptEngineManager RCE (yaml.load)",
    "log4j-core": "JNDI lookup gadget (Log4Shell-class)",
    # .NET (ysoserial.net)
    "Json.NET": "ysoserial.net ObjectDataProvider w/ TypeNameHandling",
    "Newtonsoft.Json": "ysoserial.net TypeNameHandling.Auto/All gadget",
    # PHP (phpggc chains)
    "monolog/monolog": "phpggc Monolog RCE chains",
    "guzzlehttp/guzzle": "phpggc Guzzle RCE/FW chains",
    "laravel/framework": "phpggc Laravel RCE chains",
    "symfony/symfony": "phpggc Symfony chains",
    # JS
    "node-serialize": "IIFE RCE on untrusted unserialize",
    "react-server-dom-webpack": "CVE-2025-55182 React2Shell RSC Flight decode RCE (<19.0.1/19.1.2/19.2.1)",
    "react-server-dom-turbopack": "CVE-2025-55182 React2Shell RSC Flight decode RCE",
    "react-server-dom-parcel": "CVE-2025-55182 React2Shell RSC Flight decode RCE",
    # Python
    "PyYAML": "yaml.load() w/o SafeLoader -> python/object/apply RCE",
}

MANIFESTS = {
    "pom.xml": r"<artifactId>([\w.\-]+)</artifactId>",
    "build.gradle": r"['\"][\w.\-]+:([\w.\-]+):",
    "composer.json": r"\"([\w.\-]+/[\w.\-]+)\"\s*:",
    "package.json": r"\"([@\w./\-]+)\"\s*:",
    "requirements.txt": r"^([A-Za-z0-9_.\-]+)",
    "Pipfile": r"^([A-Za-z0-9_.\-]+)\s*=",
}


def iter_files(root, exts):
    skip = {"node_modules", ".git", "vendor", "venv", ".venv", "dist", "build", "target", "__pycache__"}
    for dp, dn, fn in os.walk(root):
        dn[:] = [d for d in dn if d not in skip]
        for f in fn:
            if f.endswith(exts):
                yield os.path.join(dp, f)


def scan_sinks(root):
    out = []
    for lang, spec in DESER_SINKS.items():
        compiled = [re.compile(p) for p in spec["pat"]]
        for path in iter_files(root, spec["ext"]):
            try:
                with open(path, encoding="utf-8", errors="replace") as fh:
                    for i, line in enumerate(fh, 1):
                        if any(r.search(line) for r in compiled):
                            out.append({"tool": "deser_gadget_scan", "lang": lang,
                                        "cwe": spec["cwe"], "rule": f"{lang}-deser-sink",
                                        "severity": "error", "file": path, "line": i,
                                        "message": line.strip()[:160]})
            except OSError:
                continue
    return out


def scan_gadgets(root):
    out = []
    skip = {"node_modules", ".git", "vendor"}
    for dp, dn, fn in os.walk(root):
        dn[:] = [d for d in dn if d not in skip]
        for f in fn:
            if f in MANIFESTS:
                path = os.path.join(dp, f)
                rx = re.compile(MANIFESTS[f], re.MULTILINE)
                try:
                    content = open(path, encoding="utf-8", errors="replace").read()
                except OSError:
                    continue
                names = set(rx.findall(content))
                for name in names:
                    short = name.split("/")[-1].split(":")[-1]
                    for lib, desc in GADGET_LIBS.items():
                        if lib.lower() == name.lower() or lib.lower() == short.lower() \
                           or lib.lower() in name.lower():
                            out.append({"tool": "deser_gadget_scan", "rule": "gadget-lib-present",
                                        "cwe": "CWE-502", "severity": "warning",
                                        "file": path, "line": 0,
                                        "message": f"gadget library '{lib}' present -> {desc}"})
    return out


def main():
    ap = argparse.ArgumentParser(description="Deserialization sink + gadget precondition scanner")
    ap.add_argument("mode", choices=["sinks", "gadgets", "all"])
    ap.add_argument("root", nargs="?", default=".")
    ap.add_argument("--json")
    args = ap.parse_args()

    results = []
    if args.mode in ("sinks", "all"):
        results += scan_sinks(args.root)
    if args.mode in ("gadgets", "all"):
        results += scan_gadgets(args.root)

    for r in results:
        print(f"[{r['cwe']}/{r['severity']}] {r['file']}:{r['line']}  {r['message']}")
    print(f"\n[+] {len(results)} records", file=sys.stderr)
    if args.json:
        json.dump(results, open(args.json, "w", encoding="utf-8"), indent=2)
        print(f"[+] -> {args.json}", file=sys.stderr)


if __name__ == "__main__":
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall