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

View on GitHub
#!/usr/bin/env python3
"""
secret_crypto_audit.py - Source-code audit for hardcoded secrets (CWE-798),
high-entropy literals, weak/misused cryptography (CWE-327/328/326/330),
and missing-authentication / IDOR-style markers (CWE-862/639) heuristics.

Complements gitleaks/trufflehog: those verify live credentials; this is a fast,
offline, zero-dependency pass tuned for the audit report (CWE-tagged), and adds
crypto + authz heuristics those tools do not cover.

Subcommands:
  secrets  regex provider rules + Shannon-entropy generic detector
  crypto   weak algorithms, ECB mode, static IV/salt, weak RNG, missing MAC
  authz    routes/handlers that read an object id but never check ownership/role
  all      run all three

Dependencies: Python 3.8+ stdlib only.

Usage:
  python3 secret_crypto_audit.py secrets ./src --entropy 4.0
  python3 secret_crypto_audit.py crypto  ./src
  python3 secret_crypto_audit.py all     ./src --json out.json

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

SECRET_RULES = [
    ("AWS Access Key ID", r"\bAKIA[0-9A-Z]{16}\b", "CWE-798"),
    ("AWS Secret Key", r"(?i)aws.{0,20}['\"][0-9a-zA-Z/+]{40}['\"]", "CWE-798"),
    ("GitHub PAT", r"\bghp_[0-9A-Za-z]{36}\b", "CWE-798"),
    ("GitHub fine-grained PAT", r"\bgithub_pat_[0-9A-Za-z_]{82}\b", "CWE-798"),
    ("Slack token", r"\bxox[baprs]-[0-9A-Za-z-]{10,48}\b", "CWE-798"),
    ("Google API key", r"\bAIza[0-9A-Za-z\-_]{35}\b", "CWE-798"),
    ("Stripe live key", r"\bsk_live_[0-9A-Za-z]{24,}\b", "CWE-798"),
    ("Private key block", r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----", "CWE-321"),
    ("JWT", r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b", "CWE-798"),
    ("Generic password assign", r"(?i)(password|passwd|pwd|secret|api_?key|token)\s*[:=]\s*['\"][^'\"]{6,}['\"]", "CWE-798"),
    ("Connection string w/ creds", r"(?i)(jdbc|mongodb|postgres|mysql|redis|amqp)://[^:\s]+:[^@\s]+@", "CWE-798"),
    ("Slack webhook", r"https://hooks\.slack\.com/services/[A-Za-z0-9/]+", "CWE-798"),
]

# Common placeholders to suppress as false positives.
PLACEHOLDERS = re.compile(r"(?i)(example|changeme|placeholder|your[_-]?key|xxxx|<.*>|dummy|test|sample|redacted|\*{4,})")

CRYPTO_RULES = [
    ("Weak hash MD5", r"(?i)\b(MD5|hashlib\.md5|MessageDigest\.getInstance\(\s*['\"]MD5)", "CWE-328"),
    ("Weak hash SHA1", r"(?i)\b(SHA-?1\b|hashlib\.sha1|getInstance\(\s*['\"]SHA-?1)", "CWE-328"),
    ("Weak cipher DES/RC4", r"(?i)\b(DES|RC4|ARCFOUR|Blowfish|getInstance\(\s*['\"](DES|RC4|DESede))", "CWE-327"),
    ("ECB mode", r"(?i)(AES/ECB|MODE_ECB|['\"]ECB['\"]|Cipher\.getInstance\(\s*['\"]AES['\"]\s*\))", "CWE-327"),
    ("Static/zero IV", r"(?i)(IvParameterSpec\(\s*new byte\[|iv\s*=\s*(b?['\"]0{8,}|bytes\(16\))|new byte\[16\])", "CWE-329"),
    ("Weak RNG for security", r"(?i)(Math\.random\(\)|new Random\(\)|random\.random\(\)|rand\(\)|mt_rand\()", "CWE-330"),
    ("Hardcoded crypto key/salt", r"(?i)(SecretKeySpec\(\s*['\"]|salt\s*=\s*['\"][^'\"]{4,}|key\s*=\s*b?['\"][0-9a-fA-F]{16,})", "CWE-321"),
    ("Disabled cert validation", r"(?i)(verify\s*=\s*False|InsecureSkipVerify\s*:\s*true|rejectUnauthorized\s*:\s*false|CURLOPT_SSL_VERIFY(PEER|HOST)\s*,\s*0|TrustAllCerts)", "CWE-295"),
    ("JWT none / weak verify", r"(?i)(alg['\"]?\s*:\s*['\"]none|verify_signature\s*[:=]\s*False|algorithms\s*=\s*\[\s*\]|decode\([^)]*verify\s*=\s*False)", "CWE-347"),
    ("Encryption without MAC", r"(?i)(AES/CBC/NoPadding|MODE_CBC[^_])", "CWE-353"),
]

CODE_EXT = (".py", ".js", ".ts", ".jsx", ".tsx", ".java", ".kt", ".go", ".rb", ".php",
            ".cs", ".c", ".cpp", ".h", ".scala", ".yml", ".yaml", ".env", ".properties",
            ".json", ".xml", ".tf", ".sh")


def shannon(s):
    if not s:
        return 0.0
    freq = {c: s.count(c) for c in set(s)}
    return -sum((n / len(s)) * math.log2(n / len(s)) for n in freq.values())


def iter_files(root):
    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(CODE_EXT):
                yield os.path.join(dp, f)


def lines(path):
    try:
        return open(path, encoding="utf-8", errors="replace").read().splitlines()
    except OSError:
        return []


def scan_secrets(root, entropy_threshold):
    out = []
    rules = [(n, re.compile(p), c) for n, p, c in SECRET_RULES]
    token_rx = re.compile(r"['\"`]([A-Za-z0-9+/=_\-]{20,})['\"`]")
    for path in iter_files(root):
        for i, line in enumerate(lines(path), 1):
            for name, rx, cwe in rules:
                if rx.search(line) and not PLACEHOLDERS.search(line):
                    out.append(rec(cwe, "secret-rule", path, i, f"{name}: {line.strip()[:120]}"))
            # entropy generic detector
            for m in token_rx.finditer(line):
                tok = m.group(1)
                if shannon(tok) >= entropy_threshold and not PLACEHOLDERS.search(line) \
                   and not re.fullmatch(r"[0-9a-f]+|[A-Z_]+", tok):
                    out.append(rec("CWE-798", "high-entropy", path, i,
                                   f"entropy {shannon(tok):.2f}: {tok[:32]}..."))
    return out


def scan_crypto(root):
    out = []
    rules = [(n, re.compile(p), c) for n, p, c in CRYPTO_RULES]
    for path in iter_files(root):
        for i, line in enumerate(lines(path), 1):
            for name, rx, cwe in rules:
                if rx.search(line):
                    out.append(rec(cwe, "crypto", path, i, f"{name}: {line.strip()[:120]}"))
    return out


# IDOR/authz heuristic: a handler that pulls a record by an id from the request
# without any visible ownership/role guard in the same function.
ID_READ = re.compile(r"(?i)(findById|get_object_or_404|\.get\(\s*id|query.*WHERE\s+id|\.findOne\(\s*\{\s*[_]?id"
                     r"|objects\.get\(|\.first\(\)|getById|\bRepository\.find)")
AUTHZ_GUARD = re.compile(r"(?i)(owner|user_id\s*==|current_user|request\.user|@login_required|@require"
                         r"|hasRole|is_admin|authorize|can\(|policy|abort\(403|403|forbidden|principal)")
HANDLER = re.compile(r"(?i)(def\s+\w+|function\s+\w+|@(app|router)\.(get|post|put|delete)|@(Get|Post|Put|Delete)Mapping|public\s+\w+\s+\w+\()")


def scan_authz(root):
    out = []
    for path in iter_files(root):
        ls = lines(path)
        starts = [i for i, l in enumerate(ls) if HANDLER.search(l)]
        starts.append(len(ls))
        for a, b in zip(starts, starts[1:]):
            body = ls[a:b]
            id_hits = [a + j + 1 for j, l in enumerate(body) if ID_READ.search(l)]
            if id_hits and not any(AUTHZ_GUARD.search(l) for l in body):
                out.append(rec("CWE-639", "missing-authz", path, id_hits[0],
                               "object fetched by id with no ownership/role check in handler "
                               "-> possible IDOR/BOLA (verify reachability + auth context)"))
    return out


def rec(cwe, rule, path, line, msg):
    return {"tool": "secret_crypto_audit", "cwe": cwe, "rule": rule, "severity": "warning",
            "file": path, "line": line, "message": msg}


def main():
    ap = argparse.ArgumentParser(description="Secrets + crypto + authz source auditor")
    ap.add_argument("mode", choices=["secrets", "crypto", "authz", "all"])
    ap.add_argument("root", nargs="?", default=".")
    ap.add_argument("--entropy", type=float, default=4.0, help="Shannon entropy threshold (bits/char)")
    ap.add_argument("--json")
    args = ap.parse_args()

    results = []
    if args.mode in ("secrets", "all"):
        results += scan_secrets(args.root, args.entropy)
    if args.mode in ("crypto", "all"):
        results += scan_crypto(args.root)
    if args.mode in ("authz", "all"):
        results += scan_authz(args.root)

    for r in results:
        print(f"[{r['cwe']}] {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