"""sql-injection-in-the-exploited-record.py: SQL injection (CWE-89) in NVD and in CISA's Known Exploited Vulnerabilities. What it does: from a saved snapshot of two public US-government sources, it answers "is SQL injection still exploited" with counts instead of a Top-10 rank: 1. the share of published CVEs whose NVD record lists CWE-89, per publication year (NVD CVE API 2.0 totals per calendar quarter, rejected CVEs excluded); 2. how many entries of the CISA KEV catalogue are CWE-89, by the year CISA added them, how that share compares with CWE-89's share of all published CVEs, the vendors involved, and how many CISA marks as used in ransomware campaigns; 3. the time from NVD publication to KEV listing, for CVEs published after the catalogue began (3 November 2021). "CWE-89" means: the NVD record lists CWE-89 among its weaknesses (from NVD or from the CVE's numbering authority); that is what the NVD API's cweId filter matches, so both sides of every comparison use the same definition. KEV's own `cwes` field is counted as a cross-check. Inputs: --raw DIR folder of the raw responses (gzipped JSON, as saved by --fetch) --fetch DIR download the snapshot into DIR first (about 230 requests; 8 s apart for the NVD API, which allows 5 requests per 30 s without an API key; about 35 minutes) --csv-dir DIR write sql-injection-in-the-exploited-record.csv (per year) and sql-injection-kev-entries.csv Output: tables on stdout; the two CSVs with --csv-dir. Sources: https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json (CISA, public domain) https://services.nvd.nist.gov/rest/json/cves/2.0 (NIST NVD). This product uses the NVD API but is not endorsed or certified by the NVD. Run: python code/sql-injection-in-the-exploited-record.py --fetch kev_nvd_raw --csv-dir out python code/sql-injection-in-the-exploited-record.py --raw kev_nvd_raw Standard library only (Python 3.9+). """ from __future__ import annotations import argparse import collections import csv import datetime as dt import glob import gzip import json import os import re import statistics import time import urllib.parse import urllib.request KEV_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json" NVD = "https://services.nvd.nist.gov/rest/json/cves/2.0" UA = "passwordpassword-research/1.0 (public-data snapshot; +https://passwordpassword.com/how-this-site-is-made.html)" KEV_START = dt.date(2021, 11, 3) # BOD 22-01 published the catalogue FIRST_YEAR = 1999 QUARTERS = ((1, 3, 31), (4, 6, 30), (7, 9, 30), (10, 12, 31)) # Our classification of the product in each KEV CWE-89 entry (from the KEV vendorProject/product fields), # written 2026-10-30. Entries added to KEV after that are reported as "not classified". PRODUCT_KIND = { "CVE-2026-114625": "network or security product", "CVE-2026-76461": "network or security product", "CVE-2026-9586": "phone system", "CVE-2026-72898": "business or data application", "CVE-2026-60137": "web platform or CMS", "CVE-2026-9082": "web platform or CMS", "CVE-2026-42208": "AI developer tooling", "CVE-2026-21643": "network or security product", "CVE-2024-43468": "IT management or monitoring", "CVE-2025-57819": "phone system", "CVE-2025-25257": "network or security product", "CVE-2025-25181": "business or data application", "CVE-2020-29574": "network or security product", "CVE-2024-9465": "network or security product", "CVE-2024-9379": "network or security product", "CVE-2024-29824": "IT management or monitoring", "CVE-2024-6670": "IT management or monitoring", "CVE-2023-48788": "network or security product", "CVE-2023-46748": "network or security product", "CVE-2021-44026": "web platform or CMS", "CVE-2023-34362": "managed file transfer", "CVE-2016-2386": "business or data application", "CVE-2017-18362": "IT management or monitoring", "CVE-2018-7841": "building automation", "CVE-2021-20028": "network or security product", "CVE-2019-12989": "network or security product", "CVE-2020-5722": "phone system", "CVE-2020-17463": "web platform or CMS", "CVE-2021-42258": "business or data application", "CVE-2019-7481": "network or security product", "CVE-2021-20016": "network or security product", "CVE-2020-12271": "network or security product", } # ---------------------------------------------------------------- fetch (optional) def nvd_url(**params) -> str: flags = [k for k, v in params.items() if v is None] + ["noRejected"] q = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None}) return NVD + "?" + (q + "&" if q else "") + "&".join(flags) def fetch(raw: str) -> None: os.makedirs(raw, exist_ok=True) last = [0.0] def get(url, name, nvd=True): path = os.path.join(raw, name + ".json.gz") if os.path.exists(path): return json.loads(gzip.open(path).read()) for attempt in range(4): if nvd: time.sleep(max(0.0, 8.0 - (time.time() - last[0]))) try: req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=180) as r: body = r.read() break except Exception as e: print(" retry", attempt + 1, e) time.sleep(30 * (attempt + 1)) finally: last[0] = time.time() else: raise SystemExit("giving up on " + url) with gzip.open(path, "wb") as f: f.write(body) with open(os.path.join(raw, "fetch_log.jsonl"), "a", encoding="utf-8") as f: f.write(json.dumps({"url": url, "file": name + ".json.gz", "bytes": len(body), "user_agent": UA, "fetched_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}) + "\n") return json.loads(body) get(KEV_URL, "cisa_kev", nvd=False) start, total = 0, None while total is None or start < total: total = get(nvd_url(resultsPerPage=2000, startIndex=start, hasKev=None), f"nvd_haskev_{start:06d}")["totalResults"] start += 2000 get(nvd_url(resultsPerPage=1), "nvd_total_all") get(nvd_url(resultsPerPage=1, cweId="CWE-89"), "nvd_cwe89count_all") today = dt.date.today() for year in range(FIRST_YEAR, today.year + 1): for q, (m1, m2, d2) in enumerate(QUARTERS, 1): a, b = dt.date(year, m1, 1), dt.date(year, m2, d2) if a > today: break win = dict(pubStartDate=f"{a}T00:00:00.000Z", pubEndDate=f"{b}T23:59:59.999Z") get(nvd_url(resultsPerPage=1, **win), f"nvd_count_{year}q{q}") get(nvd_url(resultsPerPage=1, cweId="CWE-89", **win), f"nvd_cwe89count_{year}q{q}") # ---------------------------------------------------------------- analysis def load(raw: str, name: str) -> dict: return json.loads(gzip.open(os.path.join(raw, name + ".json.gz")).read()) def nvd_cwes(cve: dict) -> set[str]: return {d["value"] for w in cve.get("weaknesses", []) for d in w.get("description", [])} def analyse(raw: str) -> dict: kev_doc = load(raw, "cisa_kev") kev = kev_doc["vulnerabilities"] nvd_kev = {} for path in sorted(glob.glob(os.path.join(raw, "nvd_haskev_*.json.gz"))): for v in json.loads(gzip.open(path).read())["vulnerabilities"]: nvd_kev[v["cve"]["id"]] = v["cve"] # 1. NVD per year (sum of quarter totals) years = collections.defaultdict(lambda: [0, 0]) for path in glob.glob(os.path.join(raw, "nvd_count_*q*.json.gz")): y, q = re.search(r"nvd_count_(\d{4})q(\d)", path).groups() years[int(y)][0] += json.loads(gzip.open(path).read())["totalResults"] years[int(y)][1] += load(raw, f"nvd_cwe89count_{y}q{q}")["totalResults"] total_all = load(raw, "nvd_total_all")["totalResults"] cwe89_all = load(raw, "nvd_cwe89count_all")["totalResults"] # 2. KEV entries, CWE-89 by NVD weaknesses (and by KEV's own field as a cross-check) rows = [] for k in kev: cve = nvd_kev.get(k["cveID"]) pub = dt.date.fromisoformat(cve["published"][:10]) if cve else None added = dt.date.fromisoformat(k["dateAdded"]) rows.append({"cve": k["cveID"], "vendor": k["vendorProject"], "product": k["product"], "name": k["vulnerabilityName"], "added": added, "published": pub, "ransomware": k.get("knownRansomwareCampaignUse", ""), "sqli_nvd": bool(cve and "CWE-89" in nvd_cwes(cve)), "sqli_kev": "CWE-89" in k.get("cwes", []), "in_nvd": cve is not None}) sq = [r for r in rows if r["sqli_nvd"]] cwe_rank = collections.Counter(c for k in kev for c in set(k.get("cwes", []))) nvd_rank = collections.Counter(c for r in rows if r["in_nvd"] for c in nvd_cwes(nvd_kev[r["cve"]]) if c.startswith("CWE-")) def days(rs): return [(r["added"] - r["published"]).days for r in rs if r["published"] and r["published"] >= KEV_START] retrieved = {} for log in (os.path.join(raw, "fetch_log.jsonl"), os.path.join(raw, "..", "fetch_log.jsonl")): if os.path.exists(log): for line in open(log, encoding="utf-8"): e = json.loads(line) retrieved[os.path.basename(e["file"])] = e["fetched_utc"][:10] return {"kev_doc": kev_doc, "rows": rows, "sq": sq, "years": dict(years), "total_all": total_all, "cwe89_all": cwe89_all, "cwe_rank": cwe_rank, "nvd_rank": nvd_rank, "days_sq": days(sq), "days_all": days(rows), "retrieved": retrieved} def pct(a, b): return 100.0 * a / b if b else 0.0 def report(a: dict) -> None: rows, sq, years = a["rows"], a["sq"], a["years"] kd = a["kev_doc"] print(f"CISA KEV catalogue version {kd['catalogVersion']} ({kd['count']} entries); NVD totals as fetched.") print(f"\n1. NVD: {a['cwe89_all']:,} of {a['total_all']:,} non-rejected CVEs list CWE-89 " f"({pct(a['cwe89_all'], a['total_all']):.2f}%).") print(f"{'year':<6}{'CVEs':>9}{'CWE-89':>9}{'share':>8}{'KEV adds':>10}{'KEV CWE-89':>12}") kev_y = collections.Counter(r["added"].year for r in rows) kev_sq_y = collections.Counter(r["added"].year for r in sq) for y in sorted(years): t, s = years[y] print(f"{y:<6}{t:>9,}{s:>9,}{pct(s, t):>7.2f}%{kev_y.get(y, 0):>10}{kev_sq_y.get(y, 0):>12}") print(f"(the per-year rows sum to {sum(t for t, _ in years.values()):,} CVEs and " f"{sum(s for _, s in years.values()):,} CWE-89 CVEs published since {FIRST_YEAR})") n_kev = len(rows) rank = sorted(a["nvd_rank"].items(), key=lambda kv: (-kv[1], kv[0])) pos = [c for c, _ in rank].index("CWE-89") + 1 if "CWE-89" in a["nvd_rank"] else None print(f"\n2. KEV: {len(sq)} of {n_kev} entries ({pct(len(sq), n_kev):.2f}%) are CWE-89 in NVD " f"(rank {pos} of {len(rank)} CWEs named on KEV entries); KEV's own cwes field marks " f"{sum(r['sqli_kev'] for r in rows)}; {sum(not r['in_nvd'] for r in rows)} KEV entries had no NVD record in the snapshot.") print(" top CWEs on KEV entries (NVD weaknesses): " + ", ".join(f"{c} {n}" for c, n in rank[:15])) # shares over the same publication window for y0 in (2022,): t = sum(years[y][0] for y in years if y >= y0) s = sum(years[y][1] for y in years if y >= y0) k_all = [r for r in rows if r["published"] and r["published"].year >= y0] k_sq = [r for r in k_all if r["sqli_nvd"]] print(f" CVEs published {y0}-: CWE-89 is {pct(s, t):.2f}% of NVD ({s:,}/{t:,}) and " f"{pct(len(k_sq), len(k_all)):.2f}% of KEV ({len(k_sq)}/{len(k_all)})") rw_sq = sum(r["ransomware"] == "Known" for r in sq) rw_all = sum(r["ransomware"] == "Known" for r in rows) print(f" known ransomware campaign use: {rw_sq} of {len(sq)} CWE-89 entries ({pct(rw_sq, len(sq)):.1f}%) vs " f"{rw_all} of {n_kev} all entries ({pct(rw_all, n_kev):.1f}%)") vend = collections.Counter(r["vendor"] for r in sq) kinds = collections.Counter(PRODUCT_KIND.get(r["cve"], "not classified") for r in sq) print(" product kinds (our classification): " + ", ".join(f"{k} {n}" for k, n in kinds.most_common())) print(" vendors of CWE-89 entries: " + ", ".join(f"{v} {n}" for v, n in sorted(vend.items(), key=lambda kv: (-kv[1], kv[0])))) print(f" CWE-89 entries by NVD publication year: " + ", ".join( f"{y} {n}" for y, n in sorted(collections.Counter(r["published"].year for r in sq if r["published"]).items()))) ds, da = a["days_sq"], a["days_all"] print(f"\n3. Days from NVD publication to KEV listing, CVEs published on or after {KEV_START}:") for lab, d in (("CWE-89", ds), ("all KEV", da)): if d: print(f" {lab:<8} n={len(d):>4} median {statistics.median(d):>6.1f} " f"within 7 days {sum(x <= 7 for x in d):>4} ({pct(sum(x <= 7 for x in d), len(d)):.0f}%) " f"within 30 days {sum(x <= 30 for x in d):>4} ({pct(sum(x <= 30 for x in d), len(d)):.0f}%) " f"listed before NVD publication {sum(x < 0 for x in d)}") def write_csvs(a: dict, out: str) -> None: os.makedirs(out, exist_ok=True) ret = a["retrieved"] kev_day = ret.get("cisa_kev.json.gz", "") nvd_day = max((v for k, v in ret.items() if k.startswith("nvd_")), default="") kev_y = collections.Counter(r["added"].year for r in a["rows"]) kev_sq_y = collections.Counter(r["added"].year for r in a["sq"]) with open(os.path.join(out, "sql-injection-in-the-exploited-record.csv"), "w", newline="", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["year", "nvd_cves_published", "nvd_cves_cwe89", "cwe89_share_pct", "kev_entries_added", "kev_entries_added_cwe89", "nvd_retrieved", "kev_retrieved", "kev_catalog_version"]) for y in sorted(a["years"]): t, s = a["years"][y] w.writerow([y, t, s, f"{pct(s, t):.2f}", kev_y.get(y, 0), kev_sq_y.get(y, 0), nvd_day, kev_day, a["kev_doc"]["catalogVersion"]]) with open(os.path.join(out, "sql-injection-kev-entries.csv"), "w", newline="", encoding="utf-8") as f: w = csv.writer(f, lineterminator="\n") w.writerow(["cve", "vendor", "product", "kev_name", "kev_date_added", "nvd_published", "days_published_to_kev", "known_ransomware_use", "kev_cwes_field_has_cwe89", "product_kind_ours", "retrieved"]) for r in sorted(a["sq"], key=lambda r: (r["added"], r["cve"])): w.writerow([r["cve"], r["vendor"], r["product"], r["name"], r["added"], r["published"] or "", (r["added"] - r["published"]).days if r["published"] else "", r["ransomware"], "yes" if r["sqli_kev"] else "no", PRODUCT_KIND.get(r["cve"], "not classified"), kev_day]) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--raw") ap.add_argument("--fetch") ap.add_argument("--csv-dir") a = ap.parse_args() raw = a.fetch or a.raw if not raw: ap.error("give --raw DIR (a saved snapshot) or --fetch DIR") if a.fetch: fetch(a.fetch) res = analyse(raw) report(res) if a.csv_dir: write_csvs(res, a.csv_dir) if __name__ == "__main__": main()