#!/usr/bin/env python3
"""Verify every CVE / CISA KEV claim in this repo against the official CISA KEV feed.

What it checks (exit 1 on any mismatch):
  1. 07-kev-hunting/kev-manifest.json vs the feed: every CVE marked inKev must be
     in the feed with the same vendorProject, product, vulnerabilityName,
     dateAdded and dueDate; every CVE marked "not in KEV" must still be absent.
  2. Every hunt pack's generated "kev-verify" block (status, Sources, Verified
     line) and the intel-only table in 07-kev-hunting/README.md match what this
     script renders from the manifest (run with --write to regenerate them).
  3. Every CVE ID mentioned anywhere in the docs / site is in the manifest
     (catches typos and untracked CVEs).
  4. KEV claims in prose and on the site agree with the feed: "KEV: listed",
     "In CISA KEV", "· KEV", data-kev="yes" ... only for CVEs that are in the
     feed; "not listed", "Not in CISA KEV", data-kev="no" ... only for CVEs that
     are not; every "added YYYY-MM-DD" / "due YYYY-MM-DD" next to a CVE equals
     the feed's dateAdded / dueDate.

It never changes anything unless you pass --write (local use only; CI never
writes or commits). Stdlib only.

Usage:
  python3 tools/verify_kev.py                      # fetch the live feed and check
  python3 tools/verify_kev.py --feed kev.json      # check against a saved copy
  python3 tools/verify_kev.py --report out.md      # also write a Markdown report
  python3 tools/verify_kev.py --write [--stamp]    # regenerate blocks (and, with
                                                   # --stamp, the Verified date/version)
Exit codes: 0 = all claims match, 1 = mismatch, 2 = feed could not be loaded.
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import re
import sys
import urllib.request
from pathlib import Path

FEED_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
# CISA's own GitHub copy of the same feed, used only if cisa.gov can't be reached
MIRROR_URL = "https://raw.githubusercontent.com/cisagov/kev-data/main/known_exploited_vulnerabilities.json"
KEV_SEARCH = "https://www.cisa.gov/known-exploited-vulnerabilities-catalog?search_api_fulltext={cve}"
NVD = "https://nvd.nist.gov/vuln/detail/{cve}"
ROOT = Path(__file__).resolve().parent.parent
MANIFEST = "07-kev-hunting/kev-manifest.json"
FIELDS = ("vendorProject", "product", "vulnerabilityName", "dateAdded", "dueDate")

BEGIN = "<!-- kev-verify:begin (generated by tools/verify_kev.py --write from 07-kev-hunting/kev-manifest.json; do not edit by hand) -->"
END = "<!-- kev-verify:end -->"
INTEL_BEGIN = "<!-- kev-verify-intel:begin (generated by tools/verify_kev.py --write; do not edit by hand) -->"
INTEL_END = "<!-- kev-verify-intel:end -->"
BLOCK_RE = re.compile(r"<!-- kev-verify:begin.*?-->.*?<!-- kev-verify:end -->", re.S)
INTEL_RE = re.compile(r"<!-- kev-verify-intel:begin.*?-->.*?<!-- kev-verify-intel:end -->", re.S)

# Files whose prose / markup is scanned for KEV claims (rule 4) and CVE IDs (rule 3).
SCAN_GLOBS = ("README.md", "START_HERE.md", "NOISY_DATA.md", "07-kev-hunting/*.md",
              "08-nodered-flow-audit/*.md", "web/*.html", "06-ghostaction-supply-chain/*.md")

# Pages generated from the feed itself (tools/gen_kev_week.py): every CVE ID on
# them comes straight from the CISA feed, so the "tracked in the manifest"
# check (rule 3) does not apply. The claim checks (rule 4) still run on them.
GENERATED_FEED_PAGES = {"web/kev-this-week.html"}

CVE_RE = re.compile(r"CVE-(\d{4})-(\d{4,7})((?:\s*/\s*\d{4,7}(?![\d.]))*)", re.I)
POSITIVE = re.compile(r"KEV: listed|(?<!not )\bIn CISA KEV\b|\bNow in CISA KEV\b|\bKEV-listed\b|"
                      r"·\s*KEV\b(?!\s*[:-])|\bKEV \d{4}-\d{2}-\d{2}|^\|.*\|\s*Listed\b", re.I | re.M)
NEGATIVE = re.compile(r"\bnot listed\b|\bnot in (?:CISA )?KEV\b|\bnot KEV\b|\bNone in CISA KEV\b|"
                      r"\bnot yet in (?:CISA )?KEV\b", re.I)
ADDED = re.compile(r"(?:added|KEV)\s*:?\s*(\d{4}-\d{2}-\d{2})", re.I)
DUE = re.compile(r"\bdue\b[:\s]*((?:\d{4}-\d{2}-\d{2}(?:\s*\([^)]*\))?(?:\s*/\s*)?)+)", re.I)
DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
VERIFIED = re.compile(r"verified (?:against CISA KEV |against the CISA feed )?(?:on )?(\d{4}-\d{2}-\d{2}) "
                      r"\(catalog(?: version)? ([\d.]+)\)", re.I)
DATA_ATTR = re.compile(r'data-cve="([^"]*)"[^>]*?data-kev="(yes|no)"')


# --------------------------------------------------------------------------- load
def load_feed(source: str) -> dict:
    if re.match(r"https?://", source):
        req = urllib.request.Request(source, headers={
            "User-Agent": "soc-home-lab verify_kev.py (+https://github.com/szzxli/soc-home-lab)",
            "Accept": "application/json"})
        with urllib.request.urlopen(req, timeout=60) as resp:
            data = json.load(resp)
    else:
        data = json.loads(Path(source).read_text(encoding="utf-8"))
    if not isinstance(data, dict) or not isinstance(data.get("vulnerabilities"), list):
        raise ValueError("feed has no 'vulnerabilities' list")
    return data


def load_manifest(root: Path = ROOT) -> dict:
    return json.loads((root / MANIFEST).read_text(encoding="utf-8"))


def feed_index(feed: dict) -> dict:
    return {v.get("cveID", "").upper(): v for v in feed["vulnerabilities"]}


# ------------------------------------------------------------------------- render
def _cve_line(cve: str, m: dict) -> str:
    if m["inKev"]:
        return (f"> - **{cve}** · {m['vendorProject']} {m['product']} · **in CISA KEV** "
                f"(\"{m['vulnerabilityName']}\") · added {m['dateAdded']} · federal due {m['dueDate']}")
    note = m.get("note", "not in CISA KEV")
    return f"> - **{cve}** · {m['vendorProject']} {m['product']} · **not in CISA KEV** ({note})"


def render_pack_block(pack: dict, manifest: dict) -> str:
    cves, data, ver = pack["cves"], manifest["cves"], manifest["verified"]
    lines = [BEGIN, "> **CISA KEV status**"]
    if not cves:
        lines.append("> - No CVE assigned → no CISA KEV entry and no NVD entry exist for this case.")
    lines += [_cve_line(c, data[c]) for c in cves]
    src = []
    if cves:
        if len(cves) == 1:
            src.append(f"[CISA KEV]({KEV_SEARCH.format(cve=cves[0])})")
            src.append(f"[NVD]({NVD.format(cve=cves[0])})")
        else:
            src.append("CISA KEV: " + " · ".join(
                f"[{c.split('-')[-1]}]({KEV_SEARCH.format(cve=c)})" for c in cves))
            src.append("NVD: " + " · ".join(f"[{c.split('-')[-1]}]({NVD.format(cve=c)})" for c in cves))
    else:
        src.append(f"[CISA KEV catalog]({KEV_SEARCH.format(cve='').rstrip('=').split('?')[0]})")
    if pack.get("vendorAdvisory"):
        va = pack["vendorAdvisory"]
        src.append(f"Vendor advisory: [{va['label']}]({va['url']})")
    lines += [">", "> **Sources:** " + " · ".join(src), ">",
              f"> **Verified against CISA KEV on {ver['date']} (catalog version {ver['catalogVersion']}).** "
              "Re-checked weekly by [`tools/verify_kev.py`](https://github.com/szzxli/soc-home-lab/blob/main/tools/verify_kev.py).",
              END]
    return "\n".join(lines)


def render_intel_block(manifest: dict) -> str:
    ver, data = manifest["verified"], manifest["cves"]
    rows = [INTEL_BEGIN,
            f"Verified against CISA KEV on {ver['date']} (catalog version {ver['catalogVersion']}).",
            "",
            "| CVE | KEV entry (vendor · product · name) | Added | Federal due | Why no lab | Sources |",
            "|---|---|---|---|---|---|"]
    for item in manifest["intel"]:
        c = item["cve"]
        m = data[c]
        src = [f"[CISA KEV]({KEV_SEARCH.format(cve=c)})", f"[NVD]({NVD.format(cve=c)})"]
        if item.get("vendorAdvisory"):
            src.append(f"[{item['vendorAdvisory']['label']}]({item['vendorAdvisory']['url']})")
        status = (f"{m['vendorProject']} · {m['product']} · {m['vulnerabilityName']}"
                  if m["inKev"] else "**not in CISA KEV**")
        rows.append(f"| {c} | {status} | {m.get('dateAdded', '—')} | {m.get('dueDate', '—')} | "
                    f"{item['why']} | {' · '.join(src)} |")
    rows.append(INTEL_END)
    return "\n".join(rows)


# ------------------------------------------------------------------------- checks
def check_manifest(manifest: dict, feed: dict) -> list:
    problems, idx = [], feed_index(feed)
    for cve, m in manifest["cves"].items():
        entry = idx.get(cve.upper())
        if m["inKev"] and entry is None:
            problems.append(f"{cve}: manifest says in KEV, but it is NOT in the CISA KEV feed")
        elif not m["inKev"] and entry is not None:
            problems.append(f"{cve}: manifest says not in KEV, but CISA added it on "
                            f"{entry.get('dateAdded')} (due {entry.get('dueDate')}) — update the pack")
        elif m["inKev"]:
            for f in FIELDS:
                if (m.get(f) or "").strip() != (entry.get(f) or "").strip():
                    problems.append(f"{cve}: {f} is {m.get(f)!r} in the manifest, "
                                    f"{entry.get(f)!r} in the CISA KEV feed")
    for pack in manifest["packs"]:
        for c in pack["cves"]:
            if c not in manifest["cves"]:
                problems.append(f"pack {pack['id']}: {c} missing from manifest 'cves'")
    for item in manifest["intel"]:
        if item["cve"] not in manifest["cves"]:
            problems.append(f"intel: {item['cve']} missing from manifest 'cves'")
    return problems


def check_blocks(manifest: dict, root: Path = ROOT) -> list:
    problems = []
    for pack in manifest["packs"]:
        path = root / pack["file"]
        if not path.exists():
            problems.append(f"{pack['file']}: pack file missing")
            continue
        found = BLOCK_RE.findall(path.read_text(encoding="utf-8"))
        want = render_pack_block(pack, manifest)
        if len(found) != 1:
            problems.append(f"{pack['file']}: expected exactly one kev-verify block, found {len(found)}")
        elif found[0] != want:
            problems.append(f"{pack['file']}: kev-verify block is out of date (run tools/verify_kev.py --write)")
    readme = root / "07-kev-hunting/README.md"
    found = INTEL_RE.findall(readme.read_text(encoding="utf-8"))
    if found != [render_intel_block(manifest)]:
        problems.append("07-kev-hunting/README.md: intel-only KEV table missing or out of date "
                        "(run tools/verify_kev.py --write)")
    return problems


def _units(text: str, is_md: bool):
    """Yield (line_no, text) units: table rows / HTML lines alone, list items and
    paragraphs joined with their continuation lines."""
    if not is_md:
        for n, line in enumerate(text.splitlines(), 1):
            yield n, line
        return
    cur, start = [], 0
    for n, line in enumerate(text.splitlines(), 1):
        s = line.strip()
        new_item = bool(re.match(r"\s*(?:[-*+] |\d+\. )", line))
        if not s or s.startswith(("#", "|", ">", "<!--")) or new_item:
            if cur:
                yield start, " ".join(cur)
                cur = []
            if s.startswith(("|", ">")) or (s.startswith("#") and "CVE" in s.upper()):
                yield n, s
                continue
            if not s or s.startswith(("#", "<!--")):
                continue
        if not cur:
            start = n
        cur.append(s)
    if cur:
        yield start, " ".join(cur)


def _cves_in(text: str) -> list:
    out = []
    for m in CVE_RE.finditer(text):
        year = m.group(1)
        out.append(f"CVE-{year}-{m.group(2)}")
        for extra in re.findall(r"\d{4,7}", m.group(3) or ""):
            out.append(f"CVE-{year}-{extra}")
    return sorted(set(c.upper() for c in out))


def scan_claims(manifest: dict, feed: dict, root: Path = ROOT) -> list:
    problems, idx, known = [], feed_index(feed), set(manifest["cves"])
    files = sorted({p for g in SCAN_GLOBS for p in root.glob(g)})
    for path in files:
        rel = path.relative_to(root).as_posix()
        raw = path.read_text(encoding="utf-8")
        text = BLOCK_RE.sub("", INTEL_RE.sub("", raw))  # generated blocks are checked in rule 2
        is_md = path.suffix == ".md"
        ver = manifest["verified"]
        for m in VERIFIED.finditer(text):
            if (m.group(1), m.group(2)) != (ver["date"], ver["catalogVersion"]):
                n = text[:m.start()].count("\n") + 1
                problems.append(f"{rel}:{n}: says verified {m.group(1)} (catalog {m.group(2)}); manifest says "
                                f"{ver['date']} (catalog {ver['catalogVersion']}) — run --write and update this line")
        for n, unit in _units(text, is_md):
            clean = unit.replace("*", "")
            cves = _cves_in(clean)
            for c in cves:
                if rel in GENERATED_FEED_PAGES:
                    continue  # feed-generated page: rule 4 below still applies
                if c not in known and not c.endswith(("-YYYY", "-NNNNN")):
                    problems.append(f"{rel}:{n}: {c} is not tracked in {MANIFEST} (typo or untracked CVE?)")
            for m in DATA_ATTR.finditer(unit):
                tile_cves = [c.upper() for c in m.group(1).split()]
                for c in tile_cves:
                    if (c in idx) != (m.group(2) == "yes"):
                        problems.append(f"{rel}:{n}: data-kev=\"{m.group(2)}\" for {c}, but the feed says "
                                        f"{'in' if c in idx else 'not in'} KEV")
            if not cves or DATA_ATTR.search(unit):
                continue
            pos, neg = bool(POSITIVE.search(clean)), bool(NEGATIVE.search(clean))
            if pos and not neg:
                for c in cves:
                    if c not in idx:
                        problems.append(f"{rel}:{n}: claims {c} is in KEV, but it is not in the CISA KEV feed")
            if neg and not pos:
                for c in cves:
                    if c in idx:
                        problems.append(f"{rel}:{n}: claims {c} is not in KEV, but CISA added it on "
                                        f"{idx[c].get('dateAdded')}")
            in_kev = [idx[c] for c in cves if c in idx]
            if not in_kev:
                continue
            added_ok = {e.get("dateAdded") for e in in_kev}
            due_ok = {e.get("dueDate") for e in in_kev}
            for m in ADDED.finditer(clean):
                if m.group(1) not in added_ok:
                    problems.append(f"{rel}:{n}: KEV 'added {m.group(1)}' near {', '.join(cves)}; "
                                    f"feed dateAdded is {', '.join(sorted(added_ok))}")
            for m in DUE.finditer(clean):
                for d in DATE.findall(m.group(1)):
                    if d not in due_ok:
                        problems.append(f"{rel}:{n}: KEV 'due {d}' near {', '.join(cves)}; "
                                        f"feed dueDate is {', '.join(sorted(due_ok))}")
    return problems


def verify(manifest: dict, feed: dict, root: Path = ROOT) -> list:
    return check_manifest(manifest, feed) + check_blocks(manifest, root) + scan_claims(manifest, feed, root)


# -------------------------------------------------------------------------- write
def _insert_block(text: str, block: str) -> str:
    if BLOCK_RE.search(text):
        return BLOCK_RE.sub(lambda _m: block, text, count=1)
    lines = text.splitlines(keepends=True)
    at = 1
    for i, line in enumerate(lines[:8]):
        if line.startswith(("Work top to bottom", "Companion:")):
            at = i + 1
    return "".join(lines[:at]) + "\n" + block + "\n" + "".join(lines[at:])


def write_blocks(manifest: dict, root: Path = ROOT) -> list:
    changed = []
    for pack in manifest["packs"]:
        path = root / pack["file"]
        old = path.read_text(encoding="utf-8")
        new = _insert_block(old, render_pack_block(pack, manifest))
        if new != old:
            path.write_text(new, encoding="utf-8")
            changed.append(pack["file"])
    readme = root / "07-kev-hunting/README.md"
    old = readme.read_text(encoding="utf-8")
    if INTEL_RE.search(old):
        new = INTEL_RE.sub(lambda _m: render_intel_block(manifest), old, count=1)
        if new != old:
            readme.write_text(new, encoding="utf-8")
            changed.append("07-kev-hunting/README.md")
    else:
        changed.append("07-kev-hunting/README.md (no intel markers found; add them where the table belongs)")
    return changed


def report_md(problems: list, feed: dict, manifest: dict) -> str:
    head = (f"CISA KEV feed: catalog version **{feed.get('catalogVersion')}**, released "
            f"{feed.get('dateReleased')}, {len(feed['vulnerabilities'])} entries. "
            f"Repo last verified {manifest['verified']['date']} (catalog "
            f"{manifest['verified']['catalogVersion']}). Tracked CVEs: {len(manifest['cves'])}.")
    if not problems:
        return f"## KEV verification: all claims match\n\n{head}\n"
    body = "\n".join(f"- {p}" for p in problems)
    return (f"## KEV verification: {len(problems)} mismatch(es)\n\n{head}\n\n{body}\n\n"
            "Fix: update `07-kev-hunting/kev-manifest.json` and the affected text, then run "
            "`python3 tools/verify_kev.py --write --stamp` locally and open a PR. "
            "This job only reports; it never commits.\n")


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--feed", default=None,
                    help="feed URL or local JSON path (default: cisa.gov, falling back to CISA's GitHub copy)")
    ap.add_argument("--repo", default=str(ROOT), help="repo root (default: this repo)")
    ap.add_argument("--report", help="write a Markdown report to this path")
    ap.add_argument("--write", action="store_true", help="regenerate the kev-verify blocks")
    ap.add_argument("--stamp", action="store_true",
                    help="with --write: set the Verified date/catalog version from the feed "
                         "(only if the manifest matches the feed)")
    args = ap.parse_args(argv)
    root = Path(args.repo)
    feed, errors = None, []
    for source in ([args.feed] if args.feed else [FEED_URL, MIRROR_URL]):
        try:
            feed = load_feed(source)
            print(f"feed source: {source}")
            break
        except Exception as exc:  # network / parse problems are not mismatches
            errors.append(f"{source}: {exc}")
    if feed is None:
        print("ERROR: could not load the CISA KEV feed:\n  " + "\n  ".join(errors), file=sys.stderr)
        if args.report:
            Path(args.report).write_text("## KEV verification could not run\n\nFeed error(s):\n\n"
                                         + "\n".join(f"- {e}" for e in errors) + "\n")
        return 2
    manifest = load_manifest(root)
    if args.write:
        if args.stamp:
            mp = check_manifest(manifest, feed)
            if mp:
                print("Not stamping: manifest disagrees with the feed:\n  " + "\n  ".join(mp))
                return 1
            manifest["verified"] = {"date": dt.date.today().isoformat(),
                                    "catalogVersion": feed.get("catalogVersion", "unknown")}
            (root / MANIFEST).write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n",
                                         encoding="utf-8")
        for c in write_blocks(manifest, root):
            print(f"updated {c}")
    problems = verify(manifest, feed, root)
    rep = report_md(problems, feed, manifest)
    if args.report:
        Path(args.report).write_text(rep, encoding="utf-8")
    print(rep)
    return 1 if problems else 0


if __name__ == "__main__":
    raise SystemExit(main())
