#!/usr/bin/env python3 """kev-check.py: which of the vulnerabilities on this machine are on CISA's Known Exploited Vulnerabilities (KEV) list? From https://jwatte.com/blog/kev-nightly-cross-check-small-business/ Needs: Python 3.8+ (standard library only) and Trivy (https://trivy.dev) on PATH or --trivy. Read-only: it scans and reports. It never installs, updates or restarts anything. kev-check.py host scan this machine's OS and language packages (run as root) kev-check.py image NAME [NAME...] scan container images (e.g. nginx:1.27) kev-check.py path DIR [DIR...] scan lockfiles under a folder (package-lock.json, requirements.txt, go.sum...) kev-check.py gate DIR for a pre-push step: exit 0 = no KEV hit, 1 = KEV hit, 2 = could not check Options: --kev-file FILE (use a saved KEV JSON, for offline machines), --trivy PATH, --json OUT. The KEV feed is cached in ~/.cache/kev-check/kev.json; a failed download falls back to the cache and says so. With no feed and no cache it exits 2: it never reports "0 hits" without data. """ import json, os, subprocess, sys, time, urllib.request from pathlib import Path FEEDS = [ "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json", "https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json", ] CACHE = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "kev-check" def die(msg, code=2): print(f"kev-check: {msg}", file=sys.stderr) sys.exit(code) def load_kev(kev_file=None): if kev_file: data = json.loads(Path(kev_file).read_text(encoding="utf-8")) return data, f"file {kev_file}" CACHE.mkdir(parents=True, exist_ok=True) cache = CACHE / "kev.json" for url in FEEDS: try: req = urllib.request.Request(url, headers={"User-Agent": "kev-check/1.0"}) with urllib.request.urlopen(req, timeout=60) as r: data = json.loads(r.read().decode("utf-8")) if data.get("vulnerabilities"): tmp = cache.with_suffix(".tmp") tmp.write_text(json.dumps(data), encoding="utf-8") tmp.replace(cache) return data, url except Exception as e: # try the next source print(f"kev-check: could not fetch {url}: {e}", file=sys.stderr) if cache.exists(): data = json.loads(cache.read_text(encoding="utf-8")) age = (time.time() - cache.stat().st_mtime) / 86400 return data, f"CACHED copy, {age:.1f} days old (download failed)" die("no KEV data: download failed and there is no cache. Use --kev-file.") def trivy(trivy_bin, mode, target): cmd = [trivy_bin, mode, "--quiet", "--format", "json", "--scanners", "vuln", "--disable-telemetry", "--timeout", "15m"] if mode == "rootfs": cmd += ["--skip-dirs", "/proc,/sys,/dev,/run,/var/lib/docker,/var/lib/containers,/home/*/.cache"] cmd.append(target) p = subprocess.run(cmd, capture_output=True, text=True) if p.returncode != 0: raise RuntimeError(f"trivy {mode} {target} failed: {p.stderr.strip()[-400:]}") return json.loads(p.stdout or "{}") def findings(report, where): out = [] for res in report.get("Results") or []: for v in res.get("Vulnerabilities") or []: out.append({ "cve": v.get("VulnerabilityID", ""), "pkg": v.get("PkgName", ""), "installed": v.get("InstalledVersion", ""), "fixed": v.get("FixedVersion", "") or "no fix yet", "severity": v.get("Severity", ""), "where": f"{where}: {res.get('Target', '')}", }) return out def main(argv): args, opts, i = [], {}, 0 while i < len(argv): if argv[i] in ("--kev-file", "--trivy", "--json"): if i + 1 >= len(argv): die(f"{argv[i]} needs a value") opts[argv[i]] = argv[i + 1] i += 2 elif argv[i] in ("-h", "--help"): print(__doc__) return 0 else: args.append(argv[i]) i += 1 if not args or args[0] not in ("host", "image", "path", "gate"): print(__doc__) return 2 mode, targets = args[0], args[1:] if mode == "host": targets = ["/"] if not targets: die(f"{mode} needs at least one target") trivy_bin = opts.get("--trivy", "trivy") try: subprocess.run([trivy_bin, "--version"], capture_output=True, check=True) except Exception: die(f"trivy not found ({trivy_bin}); install it or pass --trivy PATH") kev, source = load_kev(opts.get("--kev-file")) by_cve = {v["cveID"]: v for v in kev.get("vulnerabilities", [])} tmode = {"host": "rootfs", "image": "image", "path": "fs", "gate": "fs"}[mode] all_f, scanned = [], [] for t in targets: if tmode == "fs" and not Path(t).is_dir(): die(f"not a folder: {t}") try: rep = trivy(trivy_bin, tmode, t) except Exception as e: die(str(e)) f = findings(rep, t) scanned.append((t, len(f))) all_f += f hits = [] for f in all_f: k = by_cve.get(f["cve"]) if k: hits.append({**f, "product": f"{k.get('vendorProject', '')} {k.get('product', '')}".strip(), "due": k.get("dueDate", ""), "ransomware": k.get("knownRansomwareCampaignUse", "") == "Known"}) hits.sort(key=lambda h: (not h["ransomware"], h["due"], h["cve"])) seen, rows = set(), [] for h in hits: # one row per CVE + package + version + place key = (h["cve"], h["pkg"], h["installed"], h["where"]) if key not in seen: seen.add(key) rows.append(h) cves = sorted({h["cve"] for h in rows}) rw = sorted({h["cve"] for h in rows if h["ransomware"]}) crit = sorted({f["cve"] for f in all_f if f["severity"] == "CRITICAL" and f["fixed"] != "no fix yet"} - set(cves)) print(f"# KEV cross-check, {time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime())}\n") print(f"**{len(rows)} KEV hits ({len(cves)} distinct CVEs), {len(rw)} ransomware-flagged.** " f"KEV source: {source}; catalog {kev.get('catalogVersion', '?')}, {len(by_cve)} entries.\n") print("Scanned (a count of 0 findings in total would be suspicious):") for t, n in scanned: print(f"- {t}: {n} vulnerability findings") if rows: print("\n| CVE | KEV product | Ransomware | Due | Package | Installed | Fixed in | Where |") print("|---|---|---|---|---|---|---|---|") for h in rows: print(f"| {h['cve']} | {h['product']} | {'Known' if h['ransomware'] else ''} | {h['due']} | " f"{h['pkg']} | {h['installed']} | {h['fixed']} | {h['where']} |") print(f"\nNot on KEV but CRITICAL with a fix available: {len(crit)} distinct CVEs (patch these next).") if "--json" in opts: Path(opts["--json"]).write_text(json.dumps({"source": source, "hits": rows, "scanned": scanned}, indent=1), encoding="utf-8") if mode == "gate": return 1 if rows else 0 return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))