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/dep_audit.py

View on GitHub
#!/usr/bin/env python3
"""
dep_audit.py - Software composition analysis (SCA) + malicious-package triage.

Two complementary jobs an SBOM tool alone does not do well:
  1. KNOWN-CVE SCA: parse manifests/lockfiles, query OSV.dev (offline-capable),
     and flag dependencies with known vulnerabilities.
  2. MALICIOUS-PACKAGE / SUPPLY-CHAIN heuristics: detect the install-time
     execution + exfil patterns used by 2025-2026 worms (Shai-Hulud class):
     install lifecycle scripts, suspicious script bodies, typosquat distance to
     popular names, and the worm's known IOC artifacts.

Manifests parsed: package.json, package-lock.json, requirements*.txt, Pipfile.lock,
poetry.lock, pom.xml, go.mod, Cargo.lock, composer.json/lock, Gemfile.lock.

Dependencies:
  stdlib only for heuristics. `requests` (optional) for live OSV queries.

Usage:
  python3 dep_audit.py cve   ./repo                 # OSV lookup (needs network)
  python3 dep_audit.py malware ./repo               # supply-chain heuristics, offline
  python3 dep_audit.py all   ./repo --json sca.json

LEGAL: authorized review only.
"""
import argparse
import json
import os
import re
import sys

try:
    import requests
except ImportError:
    requests = None

OSV_API = "https://api.osv.dev/v1/query"

# Lifecycle hooks that run code on `npm install` / `pip install` etc.
INSTALL_HOOKS = ["preinstall", "install", "postinstall", "prepare", "prepublish"]

# IOC artifacts of the Shai-Hulud / Shai-Hulud 2.0 / Mini Shai-Hulud npm worm
# (Sep 2025 - 2026). Source: Microsoft, Datadog, Unit42, Wiz advisories.
WORM_IOCS = [
    "bundle.js", "setup_bun.js", "bun_environment.js",
    "shai-hulud-workflow.yml", "shai-hulud.yaml", "SHA1HULUD",
    "Shai-Hulud", "Sha1-Hulud",
]

# Script-body patterns indicating install-time exfil / credential theft.
MALICIOUS_SCRIPT = [
    (r"curl\s+[^|]*\|\s*(ba)?sh", "pipe-to-shell in install script"),
    (r"node\s+\S*bundle\.js", "runs bundle.js at install (Shai-Hulud class)"),
    (r"setup_bun\.js|bun_environment\.js", "Shai-Hulud 2.0 Bun payload loader"),
    (r"(trufflehog|TruffleHog)", "bundled secret scanner (worm credential harvest)"),
    (r"https://api\.github\.com/.*repos", "creates GitHub repo (worm exfil channel)"),
    (r"process\.env\.(NPM_TOKEN|GITHUB_TOKEN|AWS_|GCP_|AZURE_)", "reads CI secrets at install"),
    (r"\.npmrc|_authToken", "reads npm auth token"),
    (r"rm\s+-rf\s+(~|\$HOME|/)", "destructive fallback (Shai-Hulud 2.0)"),
    (r"eval\(.*atob\(|Buffer\.from\([^,]+,\s*['\"]base64", "base64-decoded eval (obfuscated payload)"),
    (r"child_process|exec\(|spawn\(", "spawns process in install script"),
]

# Most-typosquatted popular packages (npm/pypi).
POPULAR = ["react", "lodash", "express", "axios", "chalk", "debug", "next", "webpack",
           "requests", "numpy", "pandas", "flask", "django", "colorama", "pytest", "tensorflow"]

ECOSYSTEM = {
    "package.json": "npm", "package-lock.json": "npm",
    "requirements.txt": "PyPI", "Pipfile.lock": "PyPI", "poetry.lock": "PyPI",
    "pom.xml": "Maven", "go.mod": "Go", "Cargo.lock": "crates.io",
    "composer.json": "Packagist", "composer.lock": "Packagist", "Gemfile.lock": "RubyGems",
}


def levenshtein(a, b):
    if a == b:
        return 0
    if not a or not b:
        return max(len(a), len(b))
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]


def find_manifests(root):
    found = []
    skip = {".git", "dist", "build", "target"}
    for dp, dn, fn in os.walk(root):
        dn[:] = [d for d in dn if d not in skip and not (d == "node_modules" and dp != root)]
        for f in fn:
            if f in ECOSYSTEM:
                found.append((os.path.join(dp, f), ECOSYSTEM[f], f))
    return found


def parse_deps(path, fname):
    """Return list of (name, version) best-effort per manifest type."""
    deps = []
    try:
        raw = open(path, encoding="utf-8", errors="replace").read()
    except OSError:
        return deps
    if fname in ("package.json", "composer.json"):
        try:
            j = json.loads(raw)
            for sec in ("dependencies", "devDependencies", "require", "require-dev"):
                for n, v in (j.get(sec) or {}).items():
                    deps.append((n, str(v).lstrip("^~>=< ")))
        except json.JSONDecodeError:
            pass
    elif fname == "package-lock.json":
        try:
            j = json.loads(raw)
            for n, meta in (j.get("packages") or j.get("dependencies") or {}).items():
                name = n.split("node_modules/")[-1] if n else n
                if name:
                    deps.append((name, str((meta or {}).get("version", ""))))
        except json.JSONDecodeError:
            pass
    elif fname == "requirements.txt":
        for line in raw.splitlines():
            m = re.match(r"^\s*([A-Za-z0-9_.\-]+)\s*([=<>!~]=?)?\s*([\d.]+)?", line)
            if m and m.group(1) and not line.strip().startswith("#"):
                deps.append((m.group(1), m.group(3) or ""))
    elif fname == "go.mod":
        for m in re.finditer(r"^\s*([\w./\-]+)\s+v([\d][\w.\-]+)", raw, re.MULTILINE):
            deps.append((m.group(1), m.group(2)))
    elif fname == "Cargo.lock" or fname.endswith(".lock"):
        cur = {}
        for line in raw.splitlines():
            mn = re.match(r'name\s*=\s*"([^"]+)"', line)
            mv = re.match(r'version\s*=\s*"([^"]+)"', line)
            if mn:
                cur["n"] = mn.group(1)
            if mv and "n" in cur:
                deps.append((cur["n"], mv.group(1)))
                cur = {}
    return deps


def osv_query(name, version, ecosystem):
    if requests is None:
        return None
    body = {"package": {"name": name, "ecosystem": ecosystem}}
    if version:
        body["version"] = version
    try:
        r = requests.post(OSV_API, json=body, timeout=10)
        if r.ok:
            return r.json().get("vulns", [])
    except requests.RequestException:
        return None
    return []


def cmd_cve(root, results):
    if requests is None:
        print("[!] `requests` not installed; CVE mode needs it. pip install requests", file=sys.stderr)
        return
    for path, eco, fname in find_manifests(root):
        for name, ver in parse_deps(path, fname):
            vulns = osv_query(name, ver, eco)
            for v in (vulns or []):
                ids = ", ".join([v.get("id", "")] + [a.get("id", "") for a in v.get("aliases_list", [])][:3])
                results.append({"tool": "dep_audit", "rule": "known-cve", "cwe": "CWE-1395",
                                "severity": "error" if v.get("database_specific", {}).get("severity") in
                                ("CRITICAL", "HIGH") else "warning",
                                "file": path, "line": 0,
                                "message": f"{name}@{ver} ({eco}): {v.get('id')} {v.get('summary','')[:90]}"})


def cmd_malware(root, results):
    # 1. Install hooks + malicious script bodies in package.json
    for path, eco, fname in find_manifests(root):
        if fname != "package.json":
            continue
        try:
            j = json.loads(open(path, encoding="utf-8", errors="replace").read())
        except (OSError, json.JSONDecodeError):
            continue
        scripts = j.get("scripts", {}) or {}
        for hook in INSTALL_HOOKS:
            if hook in scripts:
                body = scripts[hook]
                results.append({"tool": "dep_audit", "rule": "install-hook", "cwe": "CWE-829",
                                "severity": "warning", "file": path, "line": 0,
                                "message": f"lifecycle '{hook}': {body[:100]}"})
                for pat, why in MALICIOUS_SCRIPT:
                    if re.search(pat, body, re.IGNORECASE):
                        results.append({"tool": "dep_audit", "rule": "malicious-install", "cwe": "CWE-506",
                                        "severity": "error", "file": path, "line": 0,
                                        "message": f"{why} in '{hook}': {body[:100]}"})
        # typosquat check on direct deps
        for n in list((j.get("dependencies") or {})) + list((j.get("devDependencies") or {})):
            base = n.split("/")[-1].lower()
            for pop in POPULAR:
                d = levenshtein(base, pop)
                if 0 < d <= 2 and base != pop:
                    results.append({"tool": "dep_audit", "rule": "typosquat", "cwe": "CWE-1357",
                                    "severity": "warning", "file": path, "line": 0,
                                    "message": f"'{n}' is edit-distance {d} from popular '{pop}' (possible typosquat)"})

    # 2. Worm IOC artifacts anywhere in the tree (incl. node_modules)
    for dp, dn, fn in os.walk(root):
        for f in fn:
            for ioc in WORM_IOCS:
                if ioc.lower() in f.lower():
                    results.append({"tool": "dep_audit", "rule": "worm-ioc", "cwe": "CWE-506",
                                    "severity": "error", "file": os.path.join(dp, f), "line": 0,
                                    "message": f"Shai-Hulud-class IOC artifact: {f}"})

    # 3. Scan body of suspicious script files for exfil patterns
    for dp, dn, fn in os.walk(root):
        for f in fn:
            if f in WORM_IOCS or f.endswith((".js", ".cjs", ".mjs")) and ("bundle" in f or "setup_bun" in f or "bun_environment" in f):
                p = os.path.join(dp, f)
                try:
                    body = open(p, encoding="utf-8", errors="replace").read()[:200000]
                except OSError:
                    continue
                for pat, why in MALICIOUS_SCRIPT:
                    if re.search(pat, body, re.IGNORECASE):
                        results.append({"tool": "dep_audit", "rule": "malicious-body", "cwe": "CWE-506",
                                        "severity": "error", "file": p, "line": 0,
                                        "message": f"{why}"})
                        break


def main():
    ap = argparse.ArgumentParser(description="SCA + malicious-package auditor")
    ap.add_argument("mode", choices=["cve", "malware", "all"])
    ap.add_argument("root", nargs="?", default=".")
    ap.add_argument("--json")
    args = ap.parse_args()

    results = []
    if args.mode in ("cve", "all"):
        cmd_cve(args.root, results)
    if args.mode in ("malware", "all"):
        cmd_malware(args.root, results)

    # dedupe
    uniq, seen = [], set()
    for r in results:
        k = (r["rule"], r["file"], r["message"])
        if k not in seen:
            seen.add(k)
            uniq.append(r)
    for r in uniq:
        print(f"[{r['cwe']}/{r['severity']}] {r['file']}  {r['message']}")
    print(f"\n[+] {len(uniq)} records", file=sys.stderr)
    if args.json:
        json.dump(uniq, 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