"""CVSS 3.1 calculator and analysis of CISA's Known Exploited Vulnerabilities catalog. Python 3.9+, standard library only. Calculator: python3 cvss_analysis.py --score "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" Analysis: python3 cvss_analysis.py Inputs, kept beside this file so the analysis can be repeated exactly: cisa-kev-2026.10.27.json catalog snapshot. Required. The script cannot rebuild it. cve-metrics.json CVSS metrics from each CVE record. Rebuilt from the live CVE List if deleted. epss-snapshot.json EPSS scores for the catalog entries. Rebuilt from the live API if deleted. epss_scores-2026-11-18.csv.gz FIRST's full daily EPSS file for that date. Used in frozen runs only. With all four files present the run is frozen and must reproduce the published figures. A rebuilt file holds live data, which changes daily, so the frozen-figure checks are skipped.""" import collections import concurrent.futures import csv import datetime import gzip import hashlib import io import itertools import json import math import pathlib import statistics import sys import time import urllib.parse import urllib.request HERE = pathlib.Path(__file__).resolve().parent KEV_FILE = HERE / "cisa-kev-2026.10.27.json" METRICS_FILE = HERE / "cve-metrics.json" EPSS_FILE = HERE / "epss-snapshot.json" EPSS_ALL_FILE = HERE / "epss_scores-2026-11-18.csv.gz" CVE_URL = "https://raw.githubusercontent.com/CVEProject/cvelistV5/main/cves/{year}/{bucket}xxx/{cve}.json" EPSS_URL = "https://api.first.org/data/v1/epss" EPSS_ALL_URL = "https://epss.empiricalsecurity.com/epss_scores-current.csv.gz" # ---- CVSS 3.1 base and temporal formulas, from the FIRST specification ---- AV = {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2} AC = {"L": 0.77, "H": 0.44} UI = {"N": 0.85, "R": 0.62} CIA = {"H": 0.56, "L": 0.22, "N": 0.0} PR_UNCHANGED = {"N": 0.85, "L": 0.62, "H": 0.27} PR_CHANGED = {"N": 0.85, "L": 0.68, "H": 0.5} E = {"X": 1, "H": 1, "F": 0.97, "P": 0.94, "U": 0.91} RL = {"X": 1, "U": 1, "W": 0.97, "T": 0.96, "O": 0.95} RC = {"X": 1, "C": 1, "R": 0.96, "U": 0.92} def roundup(value): """Round up to one decimal, as defined in Appendix A of the 3.1 specification.""" integer = int(round(value * 100000)) return integer / 100000.0 if integer % 10000 == 0 else (math.floor(integer / 10000) + 1) / 10.0 def parse(vector): return dict(part.split(":") for part in vector.split("/")[1:]) def base_score(vector): m = parse(vector) changed = m["S"] == "C" iss = 1 - (1 - CIA[m["C"]]) * (1 - CIA[m["I"]]) * (1 - CIA[m["A"]]) impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if changed else 6.42 * iss privileges = (PR_CHANGED if changed else PR_UNCHANGED)[m["PR"]] exploitability = 8.22 * AV[m["AV"]] * AC[m["AC"]] * privileges * UI[m["UI"]] if impact <= 0: return 0.0 total = impact + exploitability return roundup(min(1.08 * total if changed else total, 10)) def temporal_score(vector): m = parse(vector) return roundup(base_score(vector) * E[m.get("E", "X")] * RL[m.get("RL", "X")] * RC[m.get("RC", "X")]) VALID = {"AV": AV, "AC": AC, "PR": PR_UNCHANGED, "UI": UI, "S": {"U": 0, "C": 0}, "C": CIA, "I": CIA, "A": CIA} OPTIONAL = {"E": E, "RL": RL, "RC": RC} # Environmental metrics are valid in a 3.1 vector. This script recognizes them but does not score them. ENVIRONMENTAL = {"CR": "XHML", "IR": "XHML", "AR": "XHML", "MAV": "XNALP", "MAC": "XLH", "MPR": "XNLH", "MUI": "XNR", "MS": "XUC", "MC": "XHLN", "MI": "XHLN", "MA": "XHLN"} def validate(vector): """Return an error message, or None when the 3.1 vector is well formed.""" parts = vector.strip().split("/") if parts[0] != "CVSS:3.1": return "the vector must start with CVSS:3.1 (this calculator does not score 2.0, 3.0 or 4.0)" seen = {} for part in parts[1:]: if part.count(":") != 1: return f"cannot read '{part}'" name, value = part.split(":") allowed = VALID.get(name) or OPTIONAL.get(name) or ENVIRONMENTAL.get(name) if allowed is None: return f"unknown metric '{name}'" if value not in allowed: return f"'{value}' is not a valid value for {name}" if name in seen: return f"metric {name} appears twice" seen[name] = value missing = [name for name in VALID if name not in seen] return f"missing base metrics: {', '.join(missing)}" if missing else None def severity(score): return "None" if score == 0 else "Low" if score < 4 else "Medium" if score < 7 else "High" if score < 9 else "Critical" def percent(part, whole): return f"{part / whole:.1%}" def get(url, timeout=60): request = urllib.request.Request(url, headers={"User-Agent": "cvss-analysis-script"}) with urllib.request.urlopen(request, timeout=timeout) as reply: return reply.read() if len(sys.argv) > 1: if len(sys.argv) != 3 or sys.argv[1] != "--score": raise SystemExit('usage: python3 cvss_analysis.py --score "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"') problem = validate(sys.argv[2]) if problem: raise SystemExit("Invalid vector: " + problem) base = base_score(sys.argv[2]) print(f"Base score: {base} ({severity(base)})") if any(name in parse(sys.argv[2]) for name in OPTIONAL): temporal = temporal_score(sys.argv[2]) print(f"Temporal score: {temporal} ({severity(temporal)})") if any(name in parse(sys.argv[2]) for name in ENVIRONMENTAL): print("Environmental metrics are present. This calculator does not compute an environmental score.") raise SystemExit(0) # ---- 1. Formula checks against the worked examples in the specification ---- assert base_score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") == 9.8 assert base_score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H") == 10.0 assert base_score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N") == 0.0 assert validate("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") is None assert validate("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H") is not None assert validate("CVSS:4.0/AV:N") is not None assert validate("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/CR:H/MAV:N") is None assert validate("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H/ZZ:1") is not None print("1. formula and validation checks passed: 9.8, 10.0 and 0.0") # ---- 2. Every possible CVSS 3.1 base vector ---- possible = [base_score(f"CVSS:3.1/AV:{av}/AC:{ac}/PR:{pr}/UI:{ui}/S:{s}/C:{c}/I:{i}/A:{a}") for av, ac, pr, ui, s, c, i, a in itertools.product("NALP", "LH", "NLH", "NR", "UC", "HLN", "HLN", "HLN")] bands = collections.Counter(severity(x) for x in possible) print("2. possible vectors:", len(possible), "| distinct scores:", len(set(possible)), "|", {name: percent(bands[name], len(possible)) for name in ("Critical", "High", "Medium", "Low", "None")}) # ---- 3. Catalog snapshot and CVE records ---- if not KEV_FILE.exists(): raise SystemExit(f"Missing {KEV_FILE.name}. The catalog snapshot must be downloaded with the article.") FROZEN = METRICS_FILE.exists() and EPSS_FILE.exists() and EPSS_ALL_FILE.exists() print(" mode:", "frozen reproduction from published data files" if FROZEN else "live refresh, figures will differ") EXPECTED_HASHES = { "cisa-kev-2026.10.27.json": "1b932c01923ad07012c4f5bddf1fa22f9f043d6eaeeb4866a234e175d6fbddc7", "cve-metrics.json": "5705df6f84f061afdbb07aadd9241ededd74e55fa9ae15f6e3ec464f922ce5b1", "epss-snapshot.json": "0f4142517509cd415099688c58ea504cd6753f1c3f2c02f382396c32ca3baa2b", "epss_scores-2026-11-18.csv.gz": "3b77048ef8d0b3cec3d7a941bf8d0e39212f40e48071307f61074a6a69fa7b3d", } for path in (KEV_FILE, METRICS_FILE, EPSS_FILE, EPSS_ALL_FILE): if path.exists(): actual = hashlib.sha256(path.read_bytes()).hexdigest() print(f" sha256 {actual} {path.name}") if FROZEN and actual != EXPECTED_HASHES[path.name]: raise SystemExit(f"SHA-256 mismatch for {path.name}: expected {EXPECTED_HASHES[path.name]}, got {actual}. " "This is not the published file, so the run is not a reproduction.") catalog = json.loads(KEV_FILE.read_text()) entries = catalog["vulnerabilities"] ids = sorted({entry["cveID"] for entry in entries}) print("3. catalog version", catalog["catalogVersion"], "| entries", len(entries), "| unique CVE IDs", len(ids)) assert len(ids) == len(entries), "duplicate CVE IDs in the catalog" def fetch_metrics(cve): year, number = cve.split("-")[1:] record, problem = None, None for attempt in range(4): # retry temporary failures try: record = json.loads(get(CVE_URL.format(year=year, bucket=int(number) // 1000, cve=cve), 30)) break except Exception as error: problem = error time.sleep(2 * (attempt + 1)) if record is None: return cve, {"error": str(problem)} found = [] containers = [("cna", record["containers"]["cna"])] + [ ((adp.get("providerMetadata") or {}).get("shortName") or "adp", adp) for adp in record["containers"].get("adp", [])] for source, container in containers: for metric in container.get("metrics", []): for key in ("cvssV4_0", "cvssV3_1", "cvssV3_0", "cvssV2_0"): if key in metric: found.append({"version": key, "source": source, "score": metric[key].get("baseScore"), "vector": metric[key].get("vectorString")}) return cve, {"metrics": found} if METRICS_FILE.exists(): cache = json.loads(METRICS_FILE.read_text()) else: with concurrent.futures.ThreadPoolExecutor(16) as pool: records = dict(pool.map(fetch_metrics, ids)) unresolved = sorted(cve for cve, r in records.items() if "error" in r) if unresolved: # never cache a failure as if it were a record without metrics raise SystemExit(f"{len(unresolved)} CVE records could not be read after retries: {unresolved[:10]}") cache = {"fetched": datetime.date.today().isoformat(), "records": records} METRICS_FILE.write_text(json.dumps(cache, indent=0, sort_keys=True)) records = cache["records"] assert set(records) == set(ids), "the metrics file does not cover exactly the catalog's CVE IDs" assert not any("error" in r for r in records.values()), "the metrics file contains failed records" print(" CVE records read on", cache["fetched"], "| records", len(records), "| failed 0") def metrics(cve, version=None): rows = records.get(cve, {}).get("metrics", []) return [r for r in rows if version is None or r["version"] == version] # ---- 4. Calculator against every published 3.1 vector ---- candidates = [(cve, r) for cve in ids for r in metrics(cve, "cvssV3_1")] not_scorable = [(cve, r) for cve, r in candidates if not r["vector"] or not r["vector"].startswith("CVSS:3.1") or r["score"] is None] pairs = [pair for pair in candidates if pair not in not_scorable] invalid = [(cve, r["vector"], validate(r["vector"])) for cve, r in pairs if validate(r["vector"])] print("4. cvssV3_1 metric entries:", len(candidates), "| without a 3.1 vector or a score:", len(not_scorable), "| malformed 3.1 vectors:", len(invalid)) for cve, r in not_scorable: print(f" excluded {cve} | source {r['source']} | score {r['score']} | vector {r['vector']}") if invalid: raise SystemExit("Malformed CVSS 3.1 vectors in CVE records: " + "; ".join(f"{c} {v} ({why})" for c, v, why in invalid[:10])) has_temporal = lambda vector: any(f"/{name}:" in vector for name in ("E", "RL", "RC")) match_base = [p for p in pairs if abs(base_score(p[1]["vector"]) - p[1]["score"]) < 1e-9] mismatch = [p for p in pairs if p not in match_base] with_t = [p for p in pairs if has_temporal(p[1]["vector"])] without_t = [p for p in pairs if not has_temporal(p[1]["vector"])] t_base = [p for p in with_t if p in match_base] t_temporal = [p for p in with_t if p not in match_base and abs(temporal_score(p[1]["vector"]) - p[1]["score"]) < 1e-9] unexplained = [p for p in mismatch if p not in t_temporal] print(" 3.1 vector and score pairs:", len(pairs), "| match base formula:", len(match_base), "| differ:", len(mismatch), "| match rate:", percent(len(match_base), len(pairs))) print(" with temporal metrics:", len(with_t), "| equal base:", len(t_base), "| equal temporal only:", len(t_temporal), "| neither:", len(with_t) - len(t_base) - len(t_temporal)) print(" without temporal metrics:", len(without_t), "| equal base:", sum(p in match_base for p in without_t), "| differ:", sum(p not in match_base for p in without_t)) print(" unexplained mismatches:") for cve, r in unexplained: print(f" {cve} | source {r['source']} | published {r['score']} | formula {base_score(r['vector'])} | {r['vector']}") # ---- 5. One version 3 score per catalog entry ---- # Selection policy, applied in this order and never by position in the record: # version 3.1 before 3.0; within a version the CNA's score, then CISA-ADP, then other providers by name; # within one provider the highest score, then the vector text, so the choice is deterministic. def provider_rank(source): return (0, "") if source == "cna" else (1, "") if source == "CISA-ADP" else (2, source) def choose(cve, versions=("cvssV3_1", "cvssV3_0")): for version in versions: rows = [r for r in metrics(cve, version) if r["score"] is not None] if rows: return min(rows, key=lambda r: (provider_rank(r["source"]), -r["score"], r["vector"] or "")) return None v3_conflicts = [cve for cve in ids if len({r["score"] for r in metrics(cve) if r["version"] in ("cvssV3_1", "cvssV3_0") and r["score"] is not None}) > 1] v3_multiple = [cve for cve in ids if len([r for r in metrics(cve) if r["version"] in ("cvssV3_1", "cvssV3_0") and r["score"] is not None]) > 1] chosen = {cve: choose(cve) for cve in ids} chosen = {cve: r for cve, r in chosen.items() if r} values = [r["score"] for r in chosen.values()] no_v3 = [cve for cve in ids if cve not in chosen] only_v4 = [cve for cve in no_v3 if metrics(cve, "cvssV4_0")] print("5. entries with more than one version 3 score:", len(v3_multiple), "| with conflicting version 3 scores:", len(v3_conflicts)) print(" entries with a version 3 score:", len(values), "| without:", len(no_v3), "| of those, with a 4.0 score:", len(only_v4), "| with no CVSS score at all:", sum(1 for cve in no_v3 if not metrics(cve))) print(" score source:", dict(collections.Counter("CNA" if r["source"] == "cna" else r["source"] for r in chosen.values()).most_common())) print(" score version:", dict(collections.Counter(r["version"] for r in chosen.values()))) band = collections.Counter(severity(v) for v in values) print(" distribution:", {name: (band[name], percent(band[name], len(values))) for name in ("Critical", "High", "Medium", "Low")}) print(" median:", statistics.median(values), "| mean:", round(statistics.mean(values), 2), "| High or Critical:", percent(band["High"] + band["Critical"], len(values))) print(" most common scores:", collections.Counter(values).most_common(4)) vectors = [r["vector"] for r in chosen.values() if r["vector"]] for name in ("AV", "AC", "PR", "UI", "S"): counts = collections.Counter(parse(v)[name] for v in vectors) print(f" {name}:", {k: percent(n, len(vectors)) for k, n in counts.most_common()}) # ---- 6. CVSS 4.0 ---- v4 = [cve for cve in ids if metrics(cve, "cvssV4_0")] chosen_v4 = {cve: choose(cve, ("cvssV4_0",)) for cve in v4} v4_conflicts = [cve for cve in v4 if len({r["score"] for r in metrics(cve, "cvssV4_0")}) > 1] print(" 4.0 score source:", dict(collections.Counter("CNA" if r["source"] == "cna" else r["source"] for r in chosen_v4.values())), "| entries with conflicting 4.0 scores:", len(v4_conflicts)) both = [(chosen[cve]["score"], chosen_v4[cve]["score"]) for cve in v4 if cve in chosen] print("6. entries with a 4.0 score:", len(v4), percent(len(v4), len(ids)), "| scored under both:", len(both)) if both: print(" mean v3:", round(statistics.mean(a for a, b in both), 2), "| mean v4:", round(statistics.mean(b for a, b in both), 2), "| v4 lower:", sum(b < a for a, b in both), "| v4 higher:", sum(b > a for a, b in both), "| equal:", sum(a == b for a, b in both)) largest = sorted(((cve, chosen[cve]["score"], chosen_v4[cve]["score"]) for cve in v4 if cve in chosen), key=lambda row: -abs(row[2] - row[1]))[:3] print(" largest differences (CVE, v3, v4):", largest) print(" entries scoring exactly 10.0:", sum(v == 10.0 for v in values)) # ---- 7. EPSS for the catalog entries ---- if EPSS_FILE.exists(): epss_cache = json.loads(EPSS_FILE.read_text()) else: scores, dates = {}, set() for start in range(0, len(ids), 100): query = urllib.parse.urlencode({"cve": ",".join(ids[start:start + 100])}) reply = json.loads(get(EPSS_URL + "?" + query)) for row in reply["data"]: if row["cve"] in scores: raise SystemExit("EPSS API returned a CVE twice: " + row["cve"]) scores[row["cve"]] = float(row["epss"]) dates.add(row.get("date")) if len(dates) != 1: raise SystemExit(f"EPSS scores carry more than one date: {sorted(dates)}") epss_cache = {"score_date": dates.pop(), "scores": scores} EPSS_FILE.write_text(json.dumps(epss_cache, indent=0, sort_keys=True)) epss = epss_cache["scores"] missing_epss = sorted(set(ids) - set(epss)) extra_epss = sorted(set(epss) - set(ids)) assert not extra_epss, "EPSS file holds CVE IDs that are not in the catalog" assert all(0.0 <= value <= 1.0 for value in epss.values()), "EPSS score outside 0 to 1" print(" catalog entries without an EPSS score:", len(missing_epss), missing_epss[:5]) kev_epss = list(epss.values()) print("7. EPSS score date:", epss_cache["score_date"], "| catalog entries with EPSS:", len(kev_epss), "| median:", round(statistics.median(kev_epss), 4), "| at least 0.1:", percent(sum(v >= 0.1 for v in kev_epss), len(kev_epss)), "| at least 0.5:", percent(sum(v >= 0.5 for v in kev_epss), len(kev_epss)), "| below 0.01:", percent(sum(v < 0.01 for v in kev_epss), len(kev_epss))) by_band = collections.defaultdict(list) for cve, r in chosen.items(): if cve in epss: by_band[severity(r["score"])].append(epss[cve]) for name in ("Critical", "High", "Medium", "Low"): row = by_band[name] print(f" {name}: {len(row)} entries | median EPSS {statistics.median(row):.4f} | at least 0.1: {percent(sum(v >= 0.1 for v in row), len(row))}") # ---- 8. EPSS for every scored CVE ---- def read_full_epss(raw): """Parse and validate FIRST's daily file. Raises ValueError on any structural problem.""" text = gzip.decompress(raw).decode() comment = next((line.strip("#") for line in text.splitlines() if line.startswith("#")), "") table = list(csv.reader(io.StringIO("\n".join(line for line in text.splitlines() if not line.startswith("#"))))) if not table or table[0][:2] != ["cve", "epss"]: raise ValueError(f"unexpected columns: {table[0] if table else None}") rows = table[1:] if not rows: raise ValueError("no data rows") if any(len(row) != len(table[0]) for row in rows): raise ValueError("a row has the wrong number of fields") names = [row[0] for row in rows] if len(set(names)) != len(names): raise ValueError("a CVE identifier appears more than once") scores = [float(row[1]) for row in rows] if not all(0.0 <= value <= 1.0 for value in scores): raise ValueError("a score is outside 0 to 1") return comment, table[0], scores full_epss_done = False try: raw = EPSS_ALL_FILE.read_bytes() if FROZEN else get(EPSS_ALL_URL, 180) comment, columns, all_scores = read_full_epss(raw) full_epss_done = True print("8. full EPSS file:", "published dated file" if FROZEN else "LIVE download, not the published snapshot", "| comment:", comment, "| columns:", columns) print(" validated rows:", len(all_scores), "| median:", round(statistics.median(all_scores), 5), "| at least 0.1:", f"{sum(v >= 0.1 for v in all_scores) / len(all_scores):.2%}", "| at least 0.5:", f"{sum(v >= 0.5 for v in all_scores) / len(all_scores):.2%}", "| below 0.01:", percent(sum(v < 0.01 for v in all_scores), len(all_scores))) except Exception as problem: if FROZEN: raise SystemExit(f"The published full EPSS file could not be read or validated: {problem}") print("8. full EPSS comparison UNAVAILABLE in this live run:", problem) # ---- 9. One metric at a time, from the 9.8 vector ---- start_vector = dict(AV="N", AC="L", PR="N", UI="N", S="U", C="H", I="H", A="H") print("9. change one metric from the 9.8 vector:") for name, value in (("AV", "A"), ("AV", "L"), ("AV", "P"), ("AC", "H"), ("PR", "L"), ("PR", "H"), ("UI", "R"), ("S", "C"), ("C", "L"), ("C", "N"), ("A", "L"), ("A", "N")): changed = dict(start_vector, **{name: value}) vector = "CVSS:3.1/" + "/".join(f"{k}:{changed[k]}" for k in ("AV", "AC", "PR", "UI", "S", "C", "I", "A")) print(f" {name}:{value} -> {base_score(vector)} {severity(base_score(vector))}") # ---- 10. Identifier year against the year the entry was added ---- years = [(int(entry["dateAdded"][:4]), int(entry["cveID"].split("-")[1])) for entry in entries] gaps = [added - issued for added, issued in years] old = sum(1 for added, issued in years if issued <= 2018) print("10. added in the identifier year:", percent(sum(g == 0 for g in gaps), len(gaps)), "| three or more years later:", percent(sum(g >= 3 for g in gaps), len(gaps)), "| identifier year 2018 or earlier:", old, percent(old, len(gaps))) # ---- Checks ---- assert len(possible) == 2592 and len(set(possible)) == 84 assert catalog["catalogVersion"] == "2026.10.27" and len(entries) == 1760 assert len(match_base) + len(mismatch) == len(pairs) assert sum(band.values()) == len(values) if FROZEN: # Headline figures published in the article. They must hold for the published data files. assert cache["fetched"] == "2026-11-19" and epss_cache["score_date"].startswith("2026-11-18") assert (len(pairs), len(match_base), len(mismatch)) == (1626, 1604, 22) assert (len(with_t), len(t_base), len(t_temporal)) == (229, 210, 18) assert len(without_t) == 1397 and len(unexplained) == 4 assert len(values) == 1681 and len(no_v3) == 79 and len(only_v4) == 79 assert (band["Critical"], band["High"], band["Medium"], band["Low"]) == (571, 899, 202, 9) assert statistics.median(values) == 8.8 and round(statistics.mean(values), 2) == 8.35 assert collections.Counter(values).most_common(3) == [(9.8, 385), (7.8, 312), (8.8, 278)] assert len(v4) == 115 and len(both) == 36 assert len(kev_epss) == 1760 and not missing_epss assert sum(1 for added, issued in years if issued <= 2018) == 439 assert full_epss_done and len(all_scores) == 408395 and "score_date:2026-11-18" in comment print("\nFrozen-figure checks passed") print("Checks passed") else: print("\nLive refresh: frozen-figure checks skipped") print("Run finished" + ("" if full_epss_done else " WITHOUT the full EPSS comparison"))