Files
Claude-BugHunter/scripts/refresh-cve-index.py
Sachin SharmaandClaude Opus 4.7 0bca621b27 Phase 3.2: CISA KEV coverage refresh script (+ workflow template)
Closes the "currency drift" gap. Pulls the CISA Known Exploited
Vulnerabilities catalog, greps the repo for indexed CVE IDs, surfaces
missing entries from vendors that map to our skill stack.

Components shipped:

- scripts/refresh-cve-index.py — pulls KEV JSON, scope-filters by vendor
  (Apache, Atlassian, Cisco, Citrix, F5, Fortinet, GitLab, Ivanti,
  Jenkins, Microsoft, Oracle, Palo Alto, Pulse, Red Hat, SonicWall,
  Spring, VMware, WordPress, Drupal, Joomla, PHP, Adobe). Out-of-scope
  filter for browser/kernel/mobile-internal CVEs that don't map to
  bug-bounty / external-red-team work. --markdown flag for the snapshot
  file format.
- docs/cve-coverage.md — committed snapshot (KEV 2026.05.15: 1592 total
  vulns, 91 indexed in this repo, 54 in-scope gaps in 180-day lookback).
- docs/automation/cve-refresh.yml.template — GitHub Actions workflow
  template. To install, move it to .github/workflows/ after granting
  the workflow scope:
    gh auth refresh -h github.com -s workflow
    mkdir -p .github/workflows
    mv docs/automation/cve-refresh.yml.template .github/workflows/cve-refresh.yml
    git add .github/workflows/cve-refresh.yml && git commit && git push
  The workflow runs weekly (Mondays 14:00 UTC), opens/updates a single
  tracking issue if gaps are detected, labels it cve-coverage + automation.

First run found 91 already-indexed CVEs covering Log4Shell, ToolShell,
Jenkins CVE-2024-23897, Spring CVE-2022-22963, Apache CVE-2021-41773
plus the ~85 cited across the Pattern Library docs from Phase 3.

Highest-priority coverage gaps detected (from KEV last 180 days):
CVE-2026-42897 (Microsoft Exchange XSS), CVE-2026-20182 (Cisco
SD-WAN auth bypass), CVE-2026-6973 (Ivanti EPMM), CVE-2026-0300
(PAN-OS), CVE-2026-34197 (Apache ActiveMQ), CVE-2025-53521 (F5 BIG-IP).
Each is a candidate for a new disclosed-reports / skill entry.

Currency drift problem solved: the repo can now answer "are we current
with CISA KEV?" every Monday, not "we were current when we last looked".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 14:51:57 +05:30

228 lines
8.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""
refresh-cve-index.py — pull CISA KEV catalog, diff against repo's disclosed-reports
and hunt-* skill content, surface coverage gaps.
Runs locally and via the .github/workflows/cve-refresh.yml weekly job.
Usage:
scripts/refresh-cve-index.py [--days N] [--vendors VENDOR1,VENDOR2,...]
Exit codes:
0 — coverage acceptable (all recent in-scope CVEs are indexed)
1 — gaps detected (script printed the list)
"""
from __future__ import annotations
import argparse
import datetime
import json
import re
import sys
import urllib.request
from pathlib import Path
KEV_FEED = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
# Vendors/products whose CVEs map cleanly to our skill stack.
# Add new entries here when you add an enterprise-platform skill.
IN_SCOPE_VENDORS = {
"Apache",
"Atlassian", # Confluence, Jira, Bitbucket
"Cisco", # ASA, AnyConnect, Talos
"Citrix",
"F5",
"Fortinet",
"GitLab",
"Ivanti", # Pulse Secure successor
"Jenkins",
"Microsoft", # SharePoint, Exchange, AD, IIS
"Mitre", # webgoat etc, edge cases
"Oracle", # WebLogic, MySQL
"Palo Alto Networks",
"Pulse Secure",
"Red Hat", # JBoss
"SonarSource",
"SonicWall",
"Spring",
"VMware",
"WordPress",
"Drupal",
"Joomla",
"PHP Group",
"Adobe", # ColdFusion
}
# CVEs the index doesn't need to ack-by-name (kernel CVEs, hardware, mobile, browser internals).
# These are operationally not in scope for a bug-bounty/external-red-team skill stack.
OUT_OF_SCOPE_VENDOR_PREFIXES = {
"Google", "Apple", "Mozilla", "Linux", "Microsoft Edge",
"Samsung", "Adobe Acrobat", "Adobe Reader",
}
def fetch_kev() -> dict:
"""Fetch the CISA KEV JSON feed."""
req = urllib.request.Request(
KEV_FEED,
headers={"User-Agent": "Claude-BugHunter-CVE-Refresh/1.0"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
def find_indexed_cves(repo_root: Path) -> set[str]:
"""Grep the repo for CVE-YYYY-N patterns we already document."""
pattern = re.compile(r"CVE-\d{4}-\d{4,7}")
indexed = set()
for sub in ("docs/disclosed-reports", "skills"):
for p in (repo_root / sub).rglob("*.md"):
try:
text = p.read_text(encoding="utf-8")
except Exception:
continue
indexed.update(pattern.findall(text))
return indexed
def in_scope(vuln: dict) -> bool:
vendor = vuln.get("vendorProject", "")
if any(vendor.startswith(p) for p in OUT_OF_SCOPE_VENDOR_PREFIXES):
return False
if vendor in IN_SCOPE_VENDORS:
return True
# Fallback for vendors not explicitly listed — fuzzy product match
product = (vuln.get("product") or "").lower()
name = (vuln.get("vulnerabilityName") or "").lower()
hint = product + " " + name
in_scope_hints = (
"wordpress", "drupal", "joomla", "apache", "tomcat", "nginx",
"spring", "struts", "weblogic", "jboss", "jenkins", "gitlab",
"confluence", "jira", "bitbucket", "sharepoint", "exchange",
"fortinet", "fortigate", "fortios", "cisco asa", "anyconnect",
"citrix", "netscaler", "pulse", "ivanti", "panorama", "globalprotect",
"vcenter", "esxi", "horizon", "workspace one", "vmware",
"atlassian", "sonarqube", "sonarsource",
)
return any(h in hint for h in in_scope_hints)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--days", type=int, default=180,
help="Show CVEs added to KEV within this many days (default 180)")
ap.add_argument("--vendors", help="Comma-separated vendor filter (overrides IN_SCOPE_VENDORS)")
ap.add_argument("--max", type=int, default=50, help="Max gaps to print (default 50)")
ap.add_argument("--markdown", action="store_true", help="Emit markdown for docs/cve-coverage.md")
args = ap.parse_args()
repo_root = Path(__file__).resolve().parent.parent
if args.markdown:
log = []
say = lambda s="": log.append(s)
else:
say = print
say(f"Repo root: {repo_root}" if not args.markdown else "")
if not args.markdown:
print(f"Fetching CISA KEV catalog from {KEV_FEED}")
feed = fetch_kev()
total = feed.get("count", 0)
if args.markdown:
say("# CISA KEV coverage snapshot")
say()
say(f"Auto-generated by `scripts/refresh-cve-index.py`. Re-run with:")
say()
say("```bash")
say(f"scripts/refresh-cve-index.py --markdown --days {args.days} --max {args.max} > docs/cve-coverage.md")
say("```")
say()
say(f"- **CISA KEV catalog version:** {feed.get('catalogVersion')}")
say(f"- **Total KEV vulnerabilities:** {total}")
else:
say(f"CISA KEV catalog version: {feed.get('catalogVersion')} ({total} vulnerabilities)")
indexed = find_indexed_cves(repo_root)
if args.markdown:
say(f"- **CVE IDs indexed in this repo:** {len(indexed)}")
else:
say(f"CVE IDs already indexed in our repo: {len(indexed)}")
if indexed:
sample = sorted(indexed)[-5:]
say(f" e.g. (newest 5 alphabetically): {sample}")
cutoff = datetime.date.today() - datetime.timedelta(days=args.days)
vendor_filter = set(v.strip() for v in args.vendors.split(",")) if args.vendors else None
in_scope_total = 0
in_scope_covered = 0
gaps = []
for v in feed.get("vulnerabilities", []):
try:
date_added = datetime.date.fromisoformat(v["dateAdded"])
except Exception:
continue
if date_added < cutoff:
continue
if vendor_filter:
if v.get("vendorProject", "") not in vendor_filter:
continue
elif not in_scope(v):
continue
in_scope_total += 1
cve_id = v["cveID"]
if cve_id in indexed:
in_scope_covered += 1
else:
gaps.append((date_added, v))
if args.markdown:
say()
say(f"## Coverage report ({args.days}-day lookback, in-scope vendors only)")
say()
say(f"- **In-scope CVEs:** {in_scope_total}")
say(f"- **Already indexed:** {in_scope_covered}")
say(f"- **Gaps:** {len(gaps)}")
say()
else:
say()
say(f"=== Coverage report (CVEs in KEV in the last {args.days} days, in-scope only) ===")
say(f" In-scope CVEs: {in_scope_total}")
say(f" Already indexed: {in_scope_covered}")
say(f" Gaps: {len(gaps)}")
say()
if not gaps:
if args.markdown:
say("All in-scope KEV entries in the lookback window are indexed. Nothing to do.")
print("\n".join(log))
else:
say("All in-scope KEV entries in the lookback window are indexed. Nothing to do.")
return 0
gaps.sort(key=lambda t: t[0], reverse=True)
if args.markdown:
say(f"## Top {min(len(gaps), args.max)} in-scope CVEs NOT indexed (newest first)")
say()
say("| Date added | CVE | Vendor | Product | Vulnerability |")
say("|---|---|---|---|---|")
for date_added, v in gaps[:args.max]:
name = (v.get('vulnerabilityName','') or '').replace("|", "\\|")[:90]
say(f"| {date_added} | `{v['cveID']}` | {v.get('vendorProject','')} | {v.get('product','')} | {name} |")
say()
say("**To close a gap:** add a Pattern Library entry in `docs/disclosed-reports/hunt-<class>.md` and an exploit summary in `skills/hunt-<class>/SKILL.md`.")
print("\n".join(log))
else:
say(f"Top {min(len(gaps), args.max)} in-scope KEV entries NOT indexed (newest first):")
say()
for date_added, v in gaps[:args.max]:
say(f" {date_added} {v['cveID']:18s} {v.get('vendorProject',''):20s} {v.get('product',''):30s} {v.get('vulnerabilityName','')[:80]}")
say()
say(f"To add coverage: pick a CVE, add a Pattern Library entry in docs/disclosed-reports/hunt-<class>.md")
say(f"plus an exploit summary in skills/hunt-<class>/SKILL.md.")
return 1
if __name__ == "__main__":
sys.exit(main())