#!/usr/bin/env python3 """ MilkSad Labs — Defensive Cryptographic Entropy & Weak-PRNG Static Auditor License: MIT (For authorized defensive code auditing, CI/CD SAST, and bug bounty triage only.) Scans source code repositories for CWE-330 (Use of Insufficiently Random Values), CWE-338 (Use of Cryptographically Weak PRNG), and timestamp-seeded PRNG patterns similar to CVE-2023-31290 (Trust Wallet) and CVE-2023-39910 (MilkSad / Libbitcoin). Optionally queries an OpenAI-compatible LLM endpoint for defensive triage and patch drafting. """ from __future__ import annotations import argparse import json import os import re import sys import urllib.request from dataclasses import asdict, dataclass from pathlib import Path from typing import Dict, List, Optional, Tuple SUPPORTED_EXTS = { ".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".py", ".go", ".rs", ".java", ".kt", ".php", ".sol", ".swift", } SKIP_DIRS = { ".git", "node_modules", "dist", "build", "target", "vendor", ".venv", "venv", "__pycache__", ".next", "coverage", } CRYPTO_CONTEXT_RE = re.compile( r"(privkey|private_key|secret|seed|mnemonic|bip39|wallet|ecdsa|" r"nonce|salt|token|jwt|session|csrf|password|reset|otp|aes|chacha|" r"hmac|signature|signer|entropy|keygen|pubkey)", re.IGNORECASE, ) COMMENT_LINE_RE = re.compile(r"^\s*(//|#|/\*|\*)") @dataclass class Rule: rule_id: str cwe: str title: str languages: Tuple[str, ...] pattern: re.Pattern base_severity: str remediation: str RULES: List[Rule] = [ Rule( rule_id="ENTROPY-001", cwe="CWE-338", title="Mersenne Twister (MT19937) used in source code", languages=(".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".py", ".rs", ".js", ".ts"), pattern=re.compile(r"\b(std::mt19937|mt19937_64|mt19937|MersenneTwister|MT19937)\b"), base_severity="HIGH", remediation="Replace MT19937 with an OS CSPRNG (getrandom/BCryptGenRandom/SecRandomCopyBytes/OpenSSL RAND_bytes/crypto.getRandomValues).", ), Rule( rule_id="ENTROPY-002", cwe="CWE-330", title="Unix timestamp or clock value used to seed PRNG", languages=(".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".py", ".go", ".js", ".ts", ".java", ".php"), pattern=re.compile( r"(srand\s*\(.*time\s*\(|" r"mt19937(?:_64)?\s+\w+\s*\(.*time\s*\(|" r"seed\s*\(\s*(?:time\.time|Date\.now|System\.currentTimeMillis|time\.Now\(\)\.Unix|std::time|time\s*\()|" r"rand\.Seed\s*\(\s*time\.Now|" r"mt_srand\s*\(\s*time\s*\()" ), base_severity="CRITICAL", remediation="Never seed a PRNG with time/clock values. Draw at least 128-256 bits directly from the OS CSPRNG.", ), Rule( rule_id="ENTROPY-003", cwe="CWE-338", title="JavaScript/TypeScript Math.random() in potential security path", languages=(".js", ".jsx", ".ts", ".tsx", ".mjs"), pattern=re.compile(r"\bMath\.random\s*\("), base_severity="MEDIUM", remediation="Use Web Crypto API crypto.getRandomValues() or Node.js crypto.randomBytes() / crypto.randomUUID().", ), Rule( rule_id="ENTROPY-004", cwe="CWE-338", title="Python non-cryptographic random module used", languages=(".py",), pattern=re.compile(r"\b(random\.(random|randint|randrange|choice|choices|getrandbits|randbytes|seed))\s*\("), base_severity="MEDIUM", remediation="Use Python's `secrets` module (secrets.token_bytes / secrets.randbits) or os.urandom() for all cryptographic/security values.", ), Rule( rule_id="ENTROPY-005", cwe="CWE-338", title="Go math/rand imported or used instead of crypto/rand", languages=(".go",), pattern=re.compile(r'("math/rand"|"math/rand/v2"|\brand\.(NewSource|Intn|Read|Uint32|Uint64)\s*\()'), base_severity="MEDIUM", remediation="Import `crypto/rand` and use crypto/rand.Read() or crypto/rand.Int() for keys, nonces, and tokens.", ), Rule( rule_id="ENTROPY-006", cwe="CWE-338", title="Java java.util.Random or ThreadLocalRandom used", languages=(".java", ".kt"), pattern=re.compile(r"\b(new\s+Random\s*\(|java\.util\.Random|ThreadLocalRandom\.current\s*\()"), base_severity="MEDIUM", remediation="Use java.security.SecureRandom (without fixed or timestamp seeds).", ), Rule( rule_id="ENTROPY-007", cwe="CWE-330", title="Solidity on-chain block variables used as randomness source", languages=(".sol",), pattern=re.compile(r"\b(block\.timestamp|block\.difficulty|block\.prevrandao|blockhash\s*\()"), base_severity="HIGH", remediation="On-chain block attributes are predictable/manipulable by validators. Use Chainlink VRF or commit-reveal schemes.", ), Rule( rule_id="ENTROPY-008", cwe="CWE-338", title="C/C++ stdlib rand()/lcg or PHP rand()/mt_rand() used", languages=(".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".php"), pattern=re.compile(r"\b(rand\s*\(\s*\)|mt_rand\s*\(|lcg_value\s*\(|drand48\s*\()"), base_severity="MEDIUM", remediation="Use libsodium randombytes_buf(), OpenSSL RAND_bytes(), getrandom(), or PHP random_bytes()/random_int().", ), Rule( rule_id="ENTROPY-009", cwe="CWE-330", title="Rust SmallRng/StdRng seeded from predictable constant or u64", languages=(".rs",), pattern=re.compile(r"\b(SmallRng::seed_from_u64|StdRng::seed_from_u64|ChaCha20Rng::seed_from_u64)\s*\("), base_severity="HIGH", remediation="Use rand::rngs::OsRng or rand::thread_rng() / getrandom crate for cryptographic key material.", ), ] @dataclass class Finding: file: str line: int rule_id: str cwe: str severity: str title: str crypto_context_hits: List[str] snippet: str remediation: str llm_triage: Optional[str] = None def scan_file(path: Path) -> List[Finding]: ext = path.suffix.lower() if ext not in SUPPORTED_EXTS: return [] try: text = path.read_text(encoding="utf-8", errors="ignore") except OSError: return [] lines = text.splitlines() findings: List[Finding] = [] for idx, line in enumerate(lines, start=1): if COMMENT_LINE_RE.match(line): continue for rule in RULES: if ext not in rule.languages: continue if not rule.pattern.search(line): continue start = max(0, idx - 8) end = min(len(lines), idx + 8) window_text = "\n".join(lines[start:end]) ctx_hits = sorted(set(m.group(0).lower() for m in CRYPTO_CONTEXT_RE.finditer(window_text))) severity = rule.base_severity if ctx_hits: if severity == "MEDIUM": severity = "HIGH" elif severity == "HIGH": severity = "CRITICAL" elif rule.base_severity == "MEDIUM": # Downgrade non-crypto context noise to LOW severity = "LOW" snippet = "\n".join( f"{ln:4d}: {lines[ln - 1]}" for ln in range(max(1, idx - 3), min(len(lines), idx + 3) + 1) ) findings.append( Finding( file=str(path), line=idx, rule_id=rule.rule_id, cwe=rule.cwe, severity=severity, title=rule.title, crypto_context_hits=ctx_hits, snippet=snippet, remediation=rule.remediation, ) ) return findings def llm_defensive_triage(finding: Finding, base_url: str, model: str, api_key: str) -> str: """Ask an OpenAI-compatible LLM strictly for defensive root-cause verification and patch advice.""" prompt = ( "You are a defensive cryptography code auditor. Review the following static-analysis finding.\n" "Respond concisely in JSON with keys: is_true_positive (bool), entropy_risk_summary (string), " "recommended_patch (string). Do NOT write exploit or brute-force code.\n\n" f"File: {finding.file}:{finding.line}\n" f"Rule: {finding.rule_id} ({finding.cwe}) - {finding.title}\n" f"Crypto Context Keywords: {', '.join(finding.crypto_context_hits) or 'none'}\n" f"Code Window:\n{finding.snippet}\n" ) payload = json.dumps({ "model": model, "temperature": 0.1, "messages": [ {"role": "system", "content": "Strict defensive AppSec & Cryptography reviewer."}, {"role": "user", "content": prompt}, ], }).encode("utf-8") headers = {"Content-Type": "application/json"} if api_key: headers["Authorization"] = f"Bearer {api_key}" req = urllib.request.Request(f"{base_url.rstrip('/')}/chat/completions", data=payload, headers=headers) with urllib.request.urlopen(req, timeout=60) as resp: data = json.loads(resp.read().decode("utf-8")) return data["choices"][0]["message"]["content"].strip() def walk_target(target: Path) -> List[Finding]: results: List[Finding] = [] if target.is_file(): return scan_file(target) for root, dirs, files in os.walk(target): dirs[:] = [d for d in dirs if d not in SKIP_DIRS] for fname in files: results.extend(scan_file(Path(root) / fname)) return results def main() -> int: parser = argparse.ArgumentParser( description="MilkSad Labs Defensive Weak-PRNG & Entropy Static Auditor" ) parser.add_argument("target", help="File or directory path to audit") parser.add_argument("--min-severity", choices=["LOW", "MEDIUM", "HIGH", "CRITICAL"], default="MEDIUM") parser.add_argument("--json-out", help="Optional path to write JSON audit report") parser.add_argument("--llm-url", help="Optional OpenAI-compatible base URL (e.g. http://127.0.0.1:11434/v1)") parser.add_argument("--llm-model", default="qwen4-35b-a3b-uncensored", help="Model name for defensive triage") parser.add_argument("--llm-key", default=os.environ.get("OPENAI_API_KEY", ""), help="API key if required") args = parser.parse_args() order = {"LOW": 0, "MEDIUM": 1, "HIGH": 2, "CRITICAL": 3} findings = [ f for f in walk_target(Path(args.target)) if order[f.severity] >= order[args.min_severity] ] findings.sort(key=lambda f: (-order[f.severity], f.file, f.line)) if args.llm_url: for f in findings: if f.severity in ("HIGH", "CRITICAL"): try: f.llm_triage = llm_defensive_triage(f, args.llm_url, args.llm_model, args.llm_key) except Exception as exc: f.llm_triage = f"LLM triage skipped: {exc}" print(f"=== MilkSad Labs Defensive Entropy Audit: {len(findings)} finding(s) ===") for f in findings: print(f"\n[{f.severity}] {f.rule_id} ({f.cwe}) — {f.title}") print(f"Location : {f.file}:{f.line}") if f.crypto_context_hits: print(f"Context : {', '.join(f.crypto_context_hits)}") print(f"Fix : {f.remediation}") print(f.snippet) if f.llm_triage: print(f"LLM Audit: {f.llm_triage}") if args.json_out: Path(args.json_out).write_text( json.dumps([asdict(f) for f in findings], indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"\nJSON report written to: {args.json_out}") return 0 if __name__ == "__main__": sys.exit(main())