How to Triage Vulnerabilities in Python With CVSS, EPSS, and CISA KEV: Build a Decision Engine, Replay It on 71 Real KEV Additions, and See What Each Signal Missed
Read the CISA KEV catalog, FIRST EPSS scores and NVD CVSS data from Python, combine them into a five-bucket decision engine, and replay 71 real KEV additions to see what each signal caught, what it...
Security feeds hand you a flood of CVE numbers, and nobody can patch them all. Between the two daily EPSS files this tutorial uses later, 16,458 more CVEs were scored in just 30 days. So the question on a busy Monday is not “what is vulnerable?” but “what do we fix first?”
Table Of Content
- What you will build
- The words you need first
- Before you start
- Step 1: Create the lab folder and install the packages
- What the commands do
- Check that it worked
- Step 2: Read the CISA KEV catalog
- Write the first part of the shared reader
- Write and run the KEV script
- Read the output
- Step 3: Read EPSS scores
- Add the EPSS readers to sources.py
- Write and run the EPSS script
- Read the output
- Step 4: Read CVSS scores
- Add the NVD readers to sources.py
- Write and run the CVSS script
- Read the output
- Step 5: Combine the three signals into one decision
- Write the data types
- Write the decision rules
- Write the glue that fetches live data
- Run it on five real CVEs
- See every branch with made-up signals
- Step 6: Replay the engine on the day before each KEV listing
- Fetch the NVD records for those 71 CVEs
- Write and run the replay
- Read the output
- Step 7: Compare single rules by effort and coverage
- Write the backtest
- Run it
- Read the output
- Step 8: Test the rules and plant mistakes on purpose
- Write the tests
- Plant 13 mistakes and see whether the tests notice
- Check that everything works end to end
- Common mistakes and how to avoid them
- Where to go next
- Sources
An emergency room has the same problem. A nurse does not treat patients in the order they walk in. She sorts them by urgency with a few quick checks and clips a colored tag on each one. That sorting is called triage, and in this tutorial you will do it for vulnerabilities. You will learn what three public signals mean, read each one from Python, combine them into a small decision program, and then test that program against history: which CVEs CISA added to its exploited list in the 30 days after each of two test dates, and what each signal had said about them beforehand.
By the end you will have a lab folder with a reusable data reader, a decision engine that sorts any list of CVE IDs into five buckets and explains each choice, 20 passing tests, a mutation check that plants 13 mistakes to see whether the tests notice, and a backtest on real data. Nothing here needs a paid service, a cloud account or a vulnerability scanner. The only wait is about nine minutes in step 6, where the script pauses between calls so the NVD does not turn it away.
One limit up front: this tutorial ranks CVE IDs. It cannot tell you which CVEs affect your own software, because that needs an inventory of what you run. If your inventory is Python packages, our SBOM and pip-audit tutorial shows how to build one.
What you will build
sources.py, a shared reader with cached, rate-limit-friendly functions for the CISA KEV catalog, FIRST EPSS scores and the NVD API;- three small scripts that let you look at each signal by itself (steps 2 to 4);
triage.py, a decision engine that turns the three signals into one bucket (P0 fix now, P1 fix this week, P2 fix this sprint, P3 routine, or WAIT) and says why;replay.pyandbacktest.py, which test the engine and each single rule against 71 CVEs that CISA added to KEV in two months, and count what each would have flagged and how much work it would have cost;test_triage.pyandmutants.py, 20 tests plus a check that plants 13 deliberate mistakes.
The words you need first
Read this list once. Every later step uses these terms.
- CVE. A Common Vulnerabilities and Exposures identifier such as
CVE-2021-44228. It names one publicly known flaw. By itself it says nothing about how dangerous the flaw is. - CNA. A CVE Numbering Authority is, in CISA’s words, “an organization authorized to assign and populate CVE IDs to vulnerabilities affecting products within their distinct, agreed-upon scope.” Vendors, open-source projects and research groups can all be CNAs, and a CNA may publish its own severity score. That is one reason a single CVE can carry several scores.
- NVD. The National Vulnerability Database, run by the US National Institute of Standards and Technology. It republishes CVE records, adds its own analysis and scores, and has a free REST API.
- CVSS. The Common Vulnerability Scoring System rates how severe a flaw is, from 0 to 10. FIRST, the organization that maintains it, says the Base Score “reflects the severity of a vulnerability according to its intrinsic characteristics which are constant over time and assumes the reasonable worst-case impact across different deployed environments.” It also warns that CVSS “is designed to measure the severity of a vulnerability and should not be used alone to assess risk.”
- EPSS. The Exploit Prediction Scoring System, a machine-learning model that, in FIRST’s words, “estimates the probability that a published CVE will be exploited in the wild in the next 30 days.” It is a number from 0 to 1 that is refreshed every day.
- KEV. CISA’s Known Exploited Vulnerabilities catalog: a list of CVEs with reliable evidence of exploitation in the wild. It is a yes-or-no signal, with a due date.
- Backtest. Replaying history to see how a rule would have performed. You pick a past day, apply the rule using only what was known on that day, and then look at what happened next.
The three signals answer three different questions. KEV asks “is anyone attacking this right now?” EPSS asks “how likely is it that someone will?” CVSS asks “how bad would it be if they did?” A good triage rule uses all three, in that order of trust.
Before you start
- Python 3.10 or newer. The code was run on Python 3.13.14. It uses the
str | Nonetype syntax, which older versions reject. - Any operating system. The lab ran on Windows 11; commands for macOS and Linux are shown too.
- Internet access to four hosts:
www.cisa.gov,api.first.org,epss.empiricalsecurity.comandservices.nvd.nist.gov. - About 15 MB of free disk space for downloaded data.
- Basic Python: you can read functions and dictionaries and run a script from a terminal. You do not need an account or an API key for anything.
Step 1: Create the lab folder and install the packages
A virtual environment is a private folder of Python packages for one project. It keeps this lab from changing, or being broken by, anything else on your computer. Pick the block for your system.
macOS and Linux (bash or zsh):
mkdir triage-lab
cd triage-lab
python -m venv .venv
source .venv/bin/activate
python -m pip install requests cvss pytest
Windows (PowerShell):
mkdir triage-lab
cd triage-lab
python -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install requests cvss pytest
If PowerShell refuses to run the activation script because of its execution policy, skip activation and type .venv\Scripts\python.exe in place of python in every command of this tutorial.
What the commands do
python -m venv .venvcreates the environment in a hidden folder named.venv.- The activation line makes
pythonandpiprefer to that folder in the current terminal window. Your prompt usually gains a(.venv)prefix. pip installadds three packages:requeststo talk to web services,cvssto compute CVSS scores from vector strings, andpytestto run tests.
Check that it worked
Run python -m pip list. On the machine used for this tutorial the list looked like this. Your version numbers may be newer.
Package Version
------------------ ----------
certifi 2026.11.20
charset-normalizer 3.5.3
colorama 0.4.6
cvss 3.6
idna 3.20
iniconfig 2.3.1
packaging 26.4
pip 26.1.2
pluggy 1.7.0
Pygments 2.21.0
pytest 9.2.0
requests 2.34.2
urllib3 2.8.0
You should see requests, cvss and pytest in the list. If python --version reports anything older than 3.10, install a newer Python first, or the type hints in later steps will raise a syntax error.
Step 2: Read the CISA KEV catalog
CISA adds a CVE to the catalog only when three things are true. Quoting its criteria:
- “The vulnerability has an assigned Common Vulnerabilities and Exposures (CVE) ID.”
- “There is reliable evidence that the vulnerability has been actively exploited in the wild.”
- “There is a clear remediation action for the vulnerability, such as a vendor-provided update.”
That makes KEV the strongest signal you can get for free, and also a narrow one: it holds only what CISA could confirm and tell you how to fix. For US federal civilian agencies the listing starts a clock. CISA writes that they “are required to remediate vulnerabilities in the KEV catalog within prescribed timeframes” and it adds that it “strongly recommends all stakeholders include a requirement to immediately address KEV catalog vulnerabilities as part of their vulnerability management plan.” Our decision program will follow that advice: a KEV listing puts a CVE in the top bucket.
Write the first part of the shared reader
Create a file named sources.py in your lab folder. It will grow over the next steps and hold every function that talks to the internet, so the other scripts stay short. This first part has two small helpers and the KEV reader.
# sources.py: cached readers for the CISA KEV catalog, FIRST EPSS scores and the NVD API
import csv
import gzip
import io
import json
import os
import time
from pathlib import Path
import requests
CACHE = Path(os.environ.get("TRIAGE_CACHE", "cache"))
CACHE.mkdir(parents=True, exist_ok=True)
HEADERS = {"User-Agent": "triage-lab/1.0 (tutorial script)"}
KEV_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
EPSS_API = "https://api.first.org/data/v1/epss"
EPSS_CURRENT = "https://epss.empiricalsecurity.com/epss_scores-current.csv.gz"
EPSS_DAY = "https://epss.empiricalsecurity.com/epss_scores-{day}.csv.gz"
NVD_API = "https://services.nvd.nist.gov/rest/json/cves/2.0"
NVD_PAUSE = float(os.environ.get("NVD_PAUSE", "6.5")) # seconds between live NVD calls without an API key
def get(url, **kwargs):
"""GET with up to four tries, waiting longer after each refusal (403, 429, 5xx)."""
for attempt in range(4):
response = requests.get(url, headers=HEADERS, timeout=90, **kwargs)
if response.status_code == 200:
return response
time.sleep(8 * (attempt + 1))
response.raise_for_status()
return response
def fresh(path, max_age_hours):
"""True when the cached file exists and is younger than max_age_hours."""
return path.exists() and time.time() - path.stat().st_mtime < max_age_hours * 3600
def load_kev(max_age_hours=12):
"""Return (header, {cveID: entry}) for the CISA KEV catalog, cached in CACHE/kev.json."""
path = CACHE / "kev.json"
if not fresh(path, max_age_hours):
path.write_bytes(get(KEV_URL).content)
data = json.loads(path.read_text(encoding="utf-8"))
header = {key: data[key] for key in ("catalogVersion", "dateReleased", "count")}
return header, {item["cveID"]: item for item in data["vulnerabilities"]}
CACHEis the folder where downloads are kept,cacheby default. You can point it elsewhere with theTRIAGE_CACHEenvironment variable. Keeping downloads means repeated runs do not hit the servers again.get()makes a web request and tries up to four times. After each refusal (an HTTP 403, 429 or 5xx answer) it waits longer before trying again, which is the polite way to behave toward public services.fresh()answers “is this cached file younger than N hours?”load_kev()downloads the KEV file at most once every 12 hours and returns two things: a small header (catalog version, release date, entry count) and a dictionary that maps each CVE ID to its entry. A dictionary makes the question “is this CVE in KEV?” a single lookup.
Write and run the KEV script
# step01_kev.py: read the CISA KEV catalog and look up CVEs in it
import collections
import datetime as dt
import sys
from sources import load_kev
header, kev = load_kev()
print("catalog", header["catalogVersion"], "released", header["dateReleased"][:10], "entries", header["count"])
newest = sorted(kev.values(), key=lambda item: item["dateAdded"], reverse=True)[:5]
print()
print("five newest entries")
for item in newest:
days = (dt.date.fromisoformat(item["dueDate"]) - dt.date.fromisoformat(item["dateAdded"])).days
print(f' {item["cveID"]} added {item["dateAdded"]} due {item["dueDate"]} (+{days} days) {item["vendorProject"]} {item["product"]}')
print()
print("fields of one entry:", ", ".join(newest[0]))
known = sum(1 for item in kev.values() if item["knownRansomwareCampaignUse"] == "Known")
print("known ransomware campaign use:", known, "of", len(kev))
gaps = collections.Counter(
(dt.date.fromisoformat(i["dueDate"]) - dt.date.fromisoformat(i["dateAdded"])).days
for i in kev.values()
if i["dateAdded"] >= "2026-01-01"
)
print("days from dateAdded to dueDate for entries added in 2026:", sorted(gaps.items()))
print()
for cve in sys.argv[1:]:
item = kev.get(cve)
print(cve, "->", "not in KEV" if item is None else f'in KEV since {item["dateAdded"]}, due {item["dueDate"]}')
Run it, giving it two CVE IDs to look up. Log4Shell (CVE-2021-44228) is a famous exploited flaw. CVE-2024-3094 is the backdoor found in the xz compression library.
python step01_kev.py CVE-2021-44228 CVE-2024-3094
catalog 2026.11.27 released 2026-11-27 entries 1808
five newest entries
CVE-2026-120705 added 2026-11-27 due 2026-11-30 (+3 days) OSGeo GeoServer
CVE-2026-129243 added 2026-11-27 due 2026-11-30 (+3 days) OSGeo GeoServer
CVE-2026-136716 added 2026-11-27 due 2026-11-30 (+3 days) Drupal Core
CVE-2026-103406 added 2026-11-25 due 2026-11-28 (+3 days) Hewlett Packard Enterprise (HPE) Juniper Session Smart Conductor and Session Smart Router
CVE-2026-133469 added 2026-11-25 due 2026-11-28 (+3 days) Vates Xen Orchestra
fields of one entry: cveID, vendorProject, product, vulnerabilityName, dateAdded, shortDescription, requiredAction, dueDate, knownRansomwareCampaignUse, forensicTriage, notes, cwes
known ransomware campaign use: 362 of 1808
days from dateAdded to dueDate for entries added in 2026: [(2, 2), (3, 182), (5, 1), (14, 95), (21, 44)]
CVE-2021-44228 -> in KEV since 2021-12-10, due 2021-12-24
CVE-2024-3094 -> not in KEV
Read the output
- The header line. On the day this was run the catalog was version 2026.11.27 and held 1,808 entries. Your numbers will be larger, because CISA keeps adding.
- The five newest entries. Three were added on 2026-11-27, including
CVE-2026-136716in Drupal Core, which we covered in a News post on Drupal’s second installer advisory. Each carries adueDatethree days afterdateAdded. - The due-date gaps. Among the entries added in 2026, the gap was 3 days for 182 entries, 14 days for 95 and 21 days for 44, with a few other values. Do not hard-code a number of days. Read
dueDatefrom each entry. - Ransomware use. The field
knownRansomwareCampaignUseis “Known” for 362 of the 1,808 entries, about one in five. A KEV entry that ransomware crews use deserves an extra push. - The two lookups. Log4Shell is in the catalog, added on 2021-12-10 with a due date of 2021-12-24.
CVE-2024-3094is not. Not being on the list does not mean a flaw is harmless. It means CISA has not listed it.
Common mistake. Treating KEV as a complete list of attacked flaws. CISA’s own criteria say a CVE needs reliable evidence and a clear fix before it is added, so real-world attacks can run ahead of the catalog. That is why the next two signals matter.
Step 3: Read EPSS scores
EPSS gives every CVE a probability between 0 and 1. FIRST says it publishes these numbers “every day for every CVE,” with ranking percentiles, and makes the data available as a daily CSV file and as an API. You will use both: the API for a handful of CVEs, and the daily file when you need every CVE at once.
Add the EPSS readers to sources.py
Add these two functions to the end of sources.py.
# sources.py (continued)
def load_epss(day="current"):
"""Return (header line, {cve: (epss, percentile)}) from the daily EPSS file of `day`."""
path = CACHE / f"epss_{day}.csv.gz"
if not fresh(path, 12 if day == "current" else 24 * 365):
url = EPSS_CURRENT if day == "current" else EPSS_DAY.format(day=day)
path.write_bytes(get(url).content)
text = gzip.decompress(path.read_bytes()).decode("utf-8")
header, _, body = text.partition("\n")
scores = {row["cve"]: (float(row["epss"]), float(row["percentile"])) for row in csv.DictReader(io.StringIO(body))}
return header.lstrip("#"), scores
def epss_api(cves, day=None):
"""Ask the FIRST EPSS API about up to 100 CVEs; CVEs it has no score for are missing from the result."""
params = {"cve": ",".join(cves)}
if day:
params["date"] = day
rows = get(EPSS_API, params=params).json()["data"]
return {row["cve"]: (float(row["epss"]), float(row["percentile"])) for row in rows}
load_epss(day)downloads the daily file for a date such as2026-10-15, or the newest file when you pass"current". Old daily files are treated as final and cached for a year; the current file is refreshed after 12 hours. The first line of the file is a comment that names the model version and the score date, and the function returns it with the scores. Each score is stored as a pair: probability first, percentile second.epss_api(cves)asks the API about several CVE IDs in one call. A CVE the model has not scored yet is simply missing from the answer. Remember that detail; it matters in step 5.
Write and run the EPSS script
# step02_epss.py: read EPSS scores for a few CVEs, then look at the whole daily file
import bisect
from sources import epss_api, load_epss
CVES = ["CVE-2021-44228", "CVE-2019-0708", "CVE-2023-38545", "CVE-2024-3094"]
print("1. Scores from the FIRST API")
for cve, (epss, percentile) in epss_api(CVES).items():
print(f" {cve} epss {epss:.5f} percentile {percentile:.5f}")
header, scores = load_epss()
values = sorted(epss for epss, _ in scores.values())
n = len(values)
print()
print("2. The daily file:", header)
print(" CVEs scored:", n)
for cut in (0.5, 0.1, 0.01, 0.001):
above = sum(1 for v in values if v >= cut)
print(f" EPSS >= {cut:<5} {above:>7} CVEs {100 * above / n:5.2f} percent")
print(f" median EPSS {values[n // 2]:.5f}; 90th percentile cut-off {values[int(n * 0.90)]:.5f}; 99th {values[int(n * 0.99)]:.5f}")
print()
print("3. A percentile is a rank, not a probability")
near = sorted(e for e, p in scores.values() if 0.949 <= p <= 0.951)
print(f" CVEs near the 95th percentile have EPSS between {near[0]:.5f} and {near[-1]:.5f}")
epss, percentile = scores["CVE-2024-3094"]
share = bisect.bisect_right(values, epss) / n
print(f" CVE-2024-3094: percentile {percentile:.5f}; share of all CVEs scoring at or below it {share:.5f}")
python step02_epss.py
1. Scores from the FIRST API
CVE-2024-3094 epss 0.30832 percentile 0.98660
CVE-2023-38545 epss 0.17957 percentile 0.97776
CVE-2021-44228 epss 0.99999 percentile 1.00000
CVE-2019-0708 epss 0.99999 percentile 1.00000
2. The daily file: model_version:v2026.06.15,score_date:2026-11-29T12:00:22Z
CVEs scored: 414215
EPSS >= 0.5 3424 CVEs 0.83 percent
EPSS >= 0.1 15145 CVEs 3.66 percent
EPSS >= 0.01 158303 CVEs 38.22 percent
EPSS >= 0.001 413438 CVEs 99.81 percent
median EPSS 0.00725; 90th percentile cut-off 0.03517; 99th 0.41478
3. A percentile is a rank, not a probability
CVEs near the 95th percentile have EPSS between 0.06972 and 0.07248
CVE-2024-3094: percentile 0.98660; share of all CVEs scoring at or below it 0.98660
Read the output
- The API rows. Log4Shell and the old Windows flaw BlueKeep (
CVE-2019-0708) both score 0.99999, the top of the scale.CVE-2024-3094scores 0.30832, about a 31 percent chance of exploitation activity in the next 30 days by the model’s reckoning, even though it is not in KEV. The API does not return rows in the order you asked for them. - The daily file. The header names the model version (
v2026.06.15) and the score date. The file scored 414,215 CVEs. - The thresholds. Only 0.83 percent of CVEs score 0.5 or more and 3.66 percent score 0.1 or more, but 38.22 percent score 0.01 or more. A cut-off of 0.01 flags almost four CVEs in ten, which is far too many to call urgent. The typical CVE sits near 0.007 (the median). This is why our rules use 0.10 for “this week” and treat 0.01 only as a supporting hint.
- Percentile is a rank, not a probability. CVEs near the 95th percentile have an EPSS between 0.0697 and 0.0725, about 7 percent. The last line proves what the column means: the percentile equals the share of all CVEs that score at or below this CVE’s score.
Common mistake. Reading “percentile 0.95” as “95 percent likely to be exploited.” It means “scores higher than about 95 percent of CVEs,” which here is a probability near 7 percent. Mixing the two columns up is easy because both run from 0 to 1, so the code in this tutorial always keeps the probability first and uses the percentile only for display.
Step 4: Read CVSS scores
A CVSS score comes with a vector string, a compact list of the facts behind the number. Take CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H. After the version, each pair is one fact: AV:N means the attack vector is the network, AC:L means low attack complexity, PR:N means no privileges are required, UI:N means no user has to click anything, S:U means the scope is unchanged, and C:H/I:H/A:H means high impact on confidentiality, integrity and availability. Together they give 9.8, Critical.
Those eight facts form the Base group, which is what the NVD and the CNAs usually publish. CVSS has more groups that only you can fill in. The v4.0 specification says Base values “are combined with default values that assume the highest severity for Threat and Environmental metrics to produce a score ranging from 0 to 10.” It then tells readers that “Consumers of CVSS should enrich the Base metrics with Threat and Environmental metric values specific to their use of the vulnerable system.” In v3.1 these are the Temporal and Environmental groups. You will try both in a moment.
Add the NVD readers to sources.py
The NVD API returns one JSON record per CVE, including every CVSS score it knows about, each tagged with the source that gave it. Add three more functions to the end of sources.py.
# sources.py (continued)
def nvd_record(cve):
"""Return the NVD record of one CVE, cached per CVE; a live call waits NVD_PAUSE seconds first."""
path = CACHE / "nvd" / f"{cve}.json"
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
time.sleep(NVD_PAUSE)
items = get(NVD_API, params={"cveId": cve}).json()["vulnerabilities"]
path.write_text(json.dumps(items[0]["cve"] if items else {}), encoding="utf-8")
return json.loads(path.read_text(encoding="utf-8"))
def cvss_rows(record):
"""Flatten the CVSS v4.0, v3.1 and v3.0 metrics of an NVD record into one row per source and version."""
rows = []
for key in ("cvssMetricV40", "cvssMetricV31", "cvssMetricV30"):
for metric in record.get("metrics", {}).get(key, []):
data = metric["cvssData"]
rows.append({
"version": data["version"],
"source": metric["source"],
"type": metric["type"],
"score": float(data["baseScore"]),
"severity": data["baseSeverity"],
"vector": data["vectorString"],
})
return rows
def best_cvss(rows):
"""Highest base score any source gave, or None when nobody scored the CVE."""
return max((row["score"] for row in rows), default=None)
nvd_record(cve)fetches one record and caches it as a JSON file per CVE. It sleepsNVD_PAUSEseconds (6.5 by default) before every live call. The NVD documentation explains why: “The public rate limit (without an API key) is 5 requests in a rolling 30 second window; the rate limit with an API key is 50 requests in a rolling 30 second window.” A pause of 6.5 seconds keeps you at or below five requests in any 30 seconds, and a CVE that is already cached costs nothing.cvss_rows(record)flattens the record’s CVSS v4.0, v3.1 and v3.0 entries into plain dictionaries: version, source, type, score, severity and vector. In this output the NVD’s own score is labeled Primary, and a CNA’s score is labeled Secondary. Older CVSS v2 scores are skipped on purpose.best_cvss(rows)returns the highest score any source gave, orNonewhen nobody scored the CVE. Taking the highest is a cautious choice for triage, and you may want a different one later.
Write and run the CVSS script
# step03_cvss.py: read CVSS vectors with the cvss package and compare what different sources say about one CVE
import sys
from cvss import CVSS3, CVSS4
from sources import cvss_rows, nvd_record
EXAMPLE = "CVE-2026-21589"
V3 = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
V4 = "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N"
print("1. One v3.1 vector split into its metrics")
c = CVSS3(V3)
base, temporal, environmental = c.scores()
print(" vector ", c.clean_vector())
print(" metrics ", {key: value for key, value in c.metrics.items() if key in ("AV", "AC", "PR", "UI", "S", "C", "I", "A")})
print(" base score", base, c.severities()[0])
print()
print("2. The same weakness with metrics you can fill in yourself (v3.1)")
for label, extra in [
("as published", ""),
("exploit code unproven (E:U)", "/E:U"),
("reachable only from the same subnet (MAV:A)", "/MAV:A"),
("attacker must act on the host itself (MAV:L)", "/MAV:L"),
]:
c = CVSS3(V3 + extra)
base, temporal, environmental = c.scores()
print(f" {label:<46} base {base} temporal {temporal} environmental {environmental}")
print()
print("3. The same weakness scored with v4.0")
for label, extra in [("all metrics at their worst", ""), ("proof of concept only (E:P)", "/E:P")]:
c = CVSS4(V4 + extra)
print(f" {label:<30} {c.base_score} {c.severity}")
cve = sys.argv[1] if len(sys.argv) > 1 else EXAMPLE
print()
print(f"4. What the NVD lists for {cve}")
for row in cvss_rows(nvd_record(cve)):
if row["vector"].startswith("CVSS:4"):
again = CVSS4(row["vector"]).base_score
else:
again = CVSS3(row["vector"]).scores()[0]
check = "matches" if float(again) == row["score"] else f"DIFFERS ({again})"
print(f' {row["source"]:<26} {row["type"]:<9} v{row["version"]:<4} {row["score"]:>4} {row["severity"]:<8} recomputed score {check}')
python step03_cvss.py CVE-2026-21589
The first run needs one NVD call and waits about seven seconds for it.
1. One v3.1 vector split into its metrics
vector CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
metrics {'AV': 'N', 'AC': 'L', 'PR': 'N', 'UI': 'N', 'S': 'U', 'C': 'H', 'I': 'H', 'A': 'H'}
base score 9.8 Critical
2. The same weakness with metrics you can fill in yourself (v3.1)
as published base 9.8 temporal 9.8 environmental 9.8
exploit code unproven (E:U) base 9.8 temporal 9.0 environmental 9.0
reachable only from the same subnet (MAV:A) base 9.8 temporal 9.8 environmental 8.8
attacker must act on the host itself (MAV:L) base 9.8 temporal 9.8 environmental 8.4
3. The same weakness scored with v4.0
all metrics at their worst 9.3 Critical
proof of concept only (E:P) 8.9 High
4. What the NVD lists for CVE-2026-21589
[email protected] Secondary v4.0 9.3 CRITICAL recomputed score matches
[email protected] Primary v3.1 7.5 HIGH recomputed score matches
Read the output
- Section 1 splits the vector into its eight base metrics and recomputes 9.8 Critical with the
cvsspackage. - Section 2 adds metrics from the other groups to the same vector. “Exploit code unproven” (
E:U) lowers the temporal score to 9.0. Saying the service is reachable only from the same subnet (MAV:A, a Modified Attack Vector) gives an environmental score of 8.8, and requiring the attacker to act on the host itself (MAV:L, a Local attack vector) gives 8.4. These numbers are yours. No database holds them for you, which is exactly the point of the quote above. - Section 3 scores a matching worst-case flaw with v4.0 and gets 9.3, not 9.8, and a proof-of-concept-only threat value (
E:P) lowers it to 8.9 High. Different CVSS versions use different math, so a v3.1 score and a v4.0 score are not interchangeable. - Section 4 is real data. For
CVE-2026-21589, Atlassian, as the CNA, published a v4.0 score of 9.3 Critical, while the NVD’s own v3.1 analysis says 7.5 High. Thecvsspackage reproduces both published numbers from their vectors, so neither is a typo. They are two honest answers to slightly different questions, and ourbest_cvss()function would report 9.3.
Common mistake. Taking the first CVSS number you see. FIRST’s own guide says CVSS “is designed to measure the severity of a vulnerability and should not be used alone to assess risk.” In step 7 you will see CVEs with a 2.3 point gap between sources.
Step 5: Combine the three signals into one decision
Now the useful part. The decision program checks the signals in a fixed order and stops at the first one that applies. The order is the policy: the strongest evidence comes first. These are example targets that you can change, not standards.
| Bucket | Rule (first match wins) | What to do |
|---|---|---|
| P0 fix now | The CVE is in KEV | Patch or mitigate immediately; use CISA’s due date as your deadline |
| P1 fix this week | EPSS is 0.10 or more | Schedule it within the week |
| P2 fix this sprint | CVSS is 9.0 or more, or EPSS is 0.01 or more together with CVSS 7.0 or more | Plan it into the next sprint |
| WAIT ask again tomorrow | EPSS or CVSS is still missing | Run the program again tomorrow; do not call it low |
| P3 routine patching | Everything else | Handle it in the normal patch cycle |
Write the data types
Create triage.py. The first part holds the thresholds and two small data classes. A Signals object is everything we know about one CVE. A Decision is the answer. Notice the two checks in __post_init__: they refuse an EPSS above 1 or a CVSS above 10, which catches the classic slip of passing a percentage where a probability belongs.
# triage.py: combine KEV, EPSS and CVSS into one decision per CVE
import sys
from dataclasses import dataclass
from sources import best_cvss, cvss_rows, epss_api, load_kev, nvd_record
EPSS_FIX_WEEK = 0.10 # a one in ten chance of exploitation activity in the next 30 days
EPSS_WATCH = 0.01
CVSS_CRITICAL = 9.0
CVSS_HIGH = 7.0
@dataclass(frozen=True)
class Signals:
cve: str
in_kev: bool = False
kev_due: str | None = None
ransomware: bool = False
epss: float | None = None # a probability from 0 to 1, or None when FIRST has no score yet
cvss: float | None = None # highest base score any source gave, or None when nobody scored it
def __post_init__(self):
if self.epss is not None and not 0.0 <= self.epss <= 1.0:
raise ValueError(f"EPSS is a probability between 0 and 1, got {self.epss}")
if self.cvss is not None and not 0.0 <= self.cvss <= 10.0:
raise ValueError(f"CVSS is a score between 0 and 10, got {self.cvss}")
@dataclass(frozen=True)
class Decision:
cve: str
bucket: str
reasons: tuple[str, ...]
Write the decision rules
# triage.py (continued)
def decide(s: Signals) -> Decision:
"""Turn the signals into one bucket. The order of the checks is the policy."""
if s.in_kev:
reasons = ["listed in CISA KEV"]
if s.kev_due:
reasons.append(f"CISA due date {s.kev_due}")
if s.ransomware:
reasons.append("used in ransomware campaigns")
return Decision(s.cve, "P0 fix now", tuple(reasons))
if s.epss is not None and s.epss >= EPSS_FIX_WEEK:
return Decision(s.cve, "P1 fix this week", (f"EPSS {s.epss:.3f} is at least {EPSS_FIX_WEEK}",))
if s.cvss is not None and s.cvss >= CVSS_CRITICAL:
note = "EPSS not published yet" if s.epss is None else f"EPSS only {s.epss:.3f}"
return Decision(s.cve, "P2 fix this sprint", (f"CVSS {s.cvss} is Critical", note))
if s.epss is not None and s.cvss is not None and s.epss >= EPSS_WATCH and s.cvss >= CVSS_HIGH:
return Decision(s.cve, "P2 fix this sprint", (f"EPSS {s.epss:.3f} and CVSS {s.cvss} are both raised",))
if s.epss is None or s.cvss is None:
missing = " and ".join(name for name, value in (("EPSS", s.epss), ("CVSS", s.cvss)) if value is None)
return Decision(s.cve, "WAIT ask again tomorrow", (f"no {missing} score yet",))
return Decision(s.cve, "P3 routine patching", ("low EPSS and below the CVSS thresholds",))
- Each
ifis one row of the table, in the same order. KEV wins over everything, even a tiny EPSS or a low CVSS. - A
Nonescore is never treated as zero. A CVE with no EPSS yet and a Critical CVSS goes to P2 and says that EPSS is missing. A CVE with a missing score and nothing alarming goes to WAIT. - Every decision carries its reasons as plain text, so a person can check the logic at a glance.
Write the glue that fetches live data
# triage.py (continued)
def gather(cves):
"""Collect the three signals for each CVE: the KEV file, the EPSS API and the NVD API."""
_, kev = load_kev()
scores = epss_api(list(cves))
signals = []
for cve in cves:
entry = kev.get(cve)
score = scores.get(cve)
signals.append(Signals(
cve=cve,
in_kev=entry is not None,
kev_due=entry["dueDate"] if entry else None,
ransomware=bool(entry) and entry["knownRansomwareCampaignUse"] == "Known",
epss=score[0] if score else None,
cvss=best_cvss(cvss_rows(nvd_record(cve))),
))
return signals
def describe(s, d):
"""One line per CVE: bucket, the raw signals and the reasons."""
epss = "none" if s.epss is None else f"{s.epss:.5f}"
cvss = "none" if s.cvss is None else str(s.cvss)
return f"{d.cve:<16} {d.bucket:<24} kev={'yes' if s.in_kev else 'no':<3} epss={epss:<8} cvss={cvss:<5} {'; '.join(d.reasons)}"
def main(argv):
if not argv:
sys.exit("usage: python triage.py CVE-ID [CVE-ID ...]")
for s in gather(argv):
print(describe(s, decide(s)))
if __name__ == "__main__":
main(sys.argv[1:])
gather() loads the KEV file, makes one EPSS API call for all CVEs, and reads each CVE’s NVD record, then builds one Signals object per CVE. describe() prints one line per CVE, and main() runs the whole thing for the IDs on the command line.
Run it on five real CVEs
python triage.py CVE-2021-44228 CVE-2026-123039 CVE-2026-114938 CVE-2026-99362 CVE-2026-98276
CVE-2021-44228 P0 fix now kev=yes epss=0.99999 cvss=10.0 listed in CISA KEV; CISA due date 2021-12-24; used in ransomware campaigns
CVE-2026-123039 P0 fix now kev=yes epss=0.00232 cvss=7.8 listed in CISA KEV; CISA due date 2026-11-16
CVE-2026-114938 P1 fix this week kev=no epss=0.72539 cvss=8.1 EPSS 0.725 is at least 0.1
CVE-2026-99362 P2 fix this sprint kev=no epss=0.01114 cvss=9.8 CVSS 9.8 is Critical; EPSS only 0.011
CVE-2026-98276 P3 routine patching kev=no epss=0.00171 cvss=7.8 low EPSS and below the CVSS thresholds
- CVE-2021-44228 (Log4Shell) is P0. It is in KEV, ransomware crews use it and its EPSS is 0.99999.
- CVE-2026-123039, the Check Point Gaia root flaw, is also P0 even though its EPSS is only 0.00232 and its CVSS is 7.8. The KEV listing outranks both numbers, which is the whole reason KEV comes first.
- CVE-2026-114938, the Java4Shell flaw in OpenJDK, is P1. It is not in KEV, but its EPSS is 0.725 even though its CVSS of 8.1 is not Critical. This is a case where EPSS adds information that CVSS lacks.
- CVE-2026-99362, the NFS2ROOT flaw in the Linux NFS server, is P2. Its CVSS is 9.8 but its EPSS is only 0.011, so the program says plainly: Critical CVSS, but EPSS only 0.011.
- CVE-2026-98276, the Linux kernel UDP use-after-free, is P3: EPSS 0.00171, CVSS 7.8, not in KEV. Yet CloudLinux said an exploit hit one of its servers on November 4. This is the honest limit of any scoring program. Signals lag behind news, so when you read a credible report of exploitation that the data does not show yet, move the CVE up by hand.
See every branch with made-up signals
Real CVEs rarely hit every branch on demand, so here is a tiny script that feeds the engine six invented cases. It also shows the rule about missing data.
# try_decide.py: run the decision engine on made-up signals to see every bucket and the missing-data rule
from triage import Signals, decide, describe
CASES = [
Signals("CVE-0000-0001", in_kev=True, kev_due="2026-12-04"),
Signals("CVE-0000-0002", epss=0.10, cvss=5.0),
Signals("CVE-0000-0003", epss=None, cvss=9.8),
Signals("CVE-0000-0004", epss=0.02, cvss=7.5),
Signals("CVE-0000-0005", epss=0.001, cvss=4.3),
Signals("CVE-0000-0006"),
]
for case in CASES:
print(describe(case, decide(case)))
python try_decide.py
CVE-0000-0001 P0 fix now kev=yes epss=none cvss=none listed in CISA KEV; CISA due date 2026-12-04
CVE-0000-0002 P1 fix this week kev=no epss=0.10000 cvss=5.0 EPSS 0.100 is at least 0.1
CVE-0000-0003 P2 fix this sprint kev=no epss=none cvss=9.8 CVSS 9.8 is Critical; EPSS not published yet
CVE-0000-0004 P2 fix this sprint kev=no epss=0.02000 cvss=7.5 EPSS 0.020 and CVSS 7.5 are both raised
CVE-0000-0005 P3 routine patching kev=no epss=0.00100 cvss=4.3 low EPSS and below the CVSS thresholds
CVE-0000-0006 WAIT ask again tomorrow kev=no epss=none cvss=none no EPSS and CVSS score yet
- Case 1 is in KEV with nothing else known: still P0.
- Case 2 sits exactly on the EPSS cut-off of 0.10: P1, because the rule says “0.10 or more.”
- Case 3 has a Critical CVSS and no EPSS: P2, and the reason says
EPSS not published yet. - Case 4 has two raised but not extreme signals (EPSS 0.02, CVSS 7.5): P2 for the “both raised” rule.
- Case 5 has low numbers everywhere: P3.
- Case 6 knows nothing: WAIT. It is not P3. Not knowing is different from being low.
Step 6: Replay the engine on the day before each KEV listing
A decision program is only worth trusting if you have seen how it behaves on real events. KEV gives us real events with dates: each CVE has a dateAdded. So we can ask: on the day before CISA listed this CVE, what would the engine have said? To keep the test manageable we use the 71 CVEs added from 2026-09-16 through 2026-11-14, the two 30-day windows that start on 2026-09-15 and 2026-10-15.
Fetch the NVD records for those 71 CVEs
The replay needs the CVSS scores of all 71 CVEs, and the next step needs three counts from the NVD. Add one last function to sources.py. It asks the NVD how many CVEs exist in total and how many are rated Critical and High on CVSS v3, using resultsPerPage of 1 so that only the total comes back.
# sources.py (continued)
def nvd_counts():
"""Count all CVEs and the CVSS v3 Critical and High ones in the NVD (three calls, cached)."""
path = CACHE / "nvd_counts.json"
if not path.exists():
counts = {}
for name, extra in (("all", {}), ("critical", {"cvssV3Severity": "CRITICAL"}), ("high", {"cvssV3Severity": "HIGH"})):
time.sleep(NVD_PAUSE)
params = {"resultsPerPage": 1, "noRejected": "", **extra}
counts[name] = get(NVD_API, params=params).json()["totalResults"]
counts["day"] = time.strftime("%Y-%m-%d")
path.write_text(json.dumps(counts), encoding="utf-8")
return json.loads(path.read_text(encoding="utf-8"))
Then write the fetch script and run it. It takes about nine minutes on the first run, because it makes 71 live calls with a 6.5 second pause between them. Do something else while it works. Later runs read the cache and finish at once.
# fetch_nvd.py: pre-fetch the NVD records the replay and the backtest need (about nine minutes without an API key)
from sources import load_kev, nvd_counts, nvd_record
START, END = "2026-09-16", "2026-11-14"
_, kev = load_kev(max_age_hours=24 * 365)
wanted = sorted(cve for cve, item in kev.items() if START <= item["dateAdded"] <= END)
print(len(wanted), "CVEs were added to KEV from", START, "through", END)
for number, cve in enumerate(wanted, 1):
nvd_record(cve)
if number % 10 == 0:
print(f" fetched {number} of {len(wanted)}", flush=True)
print(nvd_counts())
python fetch_nvd.py
71 CVEs were added to KEV from 2026-09-16 through 2026-11-14
fetched 10 of 71
fetched 20 of 71
fetched 30 of 71
fetched 40 of 71
fetched 50 of 71
fetched 60 of 71
fetched 70 of 71
{'all': 414483, 'critical': 30928, 'high': 77661, 'day': '2026-11-30'}
The last line shows the NVD totals: 414,483 CVEs, of which 30,928 are Critical and 77,661 are High on CVSS v3.
Write and run the replay
The replay groups the 71 listings by the day before each one. For each such day it asks the EPSS API for the scores as of that day (the API takes a date parameter), reads the cached NVD record, and runs decide(). A CVE whose NVD publication date is later than the day before is counted as “not public yet.” Nobody could have triaged it, because it did not exist.
# replay.py: what would the decision engine have said the day before CISA listed each CVE?
import collections
import datetime as dt
import sys
from sources import best_cvss, cvss_rows, epss_api, load_kev, nvd_record
from triage import Signals, decide
START, END = "2026-09-16", "2026-11-14"
def main(start=START, end=END):
_, kev = load_kev(max_age_hours=24 * 365)
added = sorted((item["dateAdded"], cve) for cve, item in kev.items() if start <= item["dateAdded"] <= end)
by_day = collections.defaultdict(list)
for date_added, cve in added:
day_before = (dt.date.fromisoformat(date_added) - dt.timedelta(days=1)).isoformat()
by_day[day_before].append(cve)
tally = collections.Counter()
examples = collections.defaultdict(list)
for day_before, cves in sorted(by_day.items()):
scores = epss_api(cves, day=day_before)
for cve in cves:
record = nvd_record(cve)
epss = scores[cve][0] if cve in scores else None
cvss = best_cvss(cvss_rows(record))
if record.get("published", "")[:10] > day_before:
bucket = "not public yet"
else:
bucket = decide(Signals(cve=cve, epss=epss, cvss=cvss)).bucket
tally[bucket] += 1
examples[bucket].append(f"{cve} (EPSS {'none' if epss is None else format(epss, '.3f')}, CVSS {cvss})")
print(f"CVEs added to KEV from {start} through {end}: {len(added)}")
print("Bucket the engine would have given each one on the day before it was listed")
print("(EPSS as of that day, CVSS as of today)")
for bucket in ("not public yet", "P1 fix this week", "P2 fix this sprint", "P3 routine patching", "WAIT ask again tomorrow"):
print(f" {bucket:<24}{tally[bucket]:>3}")
for bucket in ("P3 routine patching", "WAIT ask again tomorrow"):
if examples[bucket]:
print(f"examples for {bucket}:", "; ".join(examples[bucket][:3]))
if __name__ == "__main__":
main(*sys.argv[1:])
python replay.py
CVEs added to KEV from 2026-09-16 through 2026-11-14: 71
Bucket the engine would have given each one on the day before it was listed
(EPSS as of that day, CVSS as of today)
not public yet 18
P1 fix this week 9
P2 fix this sprint 21
P3 routine patching 19
WAIT ask again tomorrow 4
examples for P3 routine patching: CVE-2025-39964 (EPSS 0.003, CVSS 7.8); CVE-2026-53266 (EPSS 0.001, CVSS 8.8); CVE-2026-7273 (EPSS 0.003, CVSS 8.8)
examples for WAIT ask again tomorrow: CVE-2026-58704 (EPSS none, CVSS 8.8); CVE-2026-86950 (EPSS none, CVSS 8.8); CVE-2026-76418 (EPSS none, CVSS 8.6)
Read the output
- 18 of 71 were not public the day before they were listed. The CVE became public on the listing day or later. No triage program could have helped with those in advance, which is a reminder that a fast daily loop matters as much as any score.
- Of the other 53, the engine would have put 9 in P1 and 21 in P2, so 30 (57 percent) were already in a this-week or this-sprint bucket before CISA acted.
- 19 would have been P3 routine, with EPSS values of 0.001 to 0.003 and CVSS between 7.8 and 8.8 in the examples. After the listing, the engine would move each of them to P0 on the next run.
- 4 would have been WAIT because EPSS had no score yet. One of them,
CVE-2026-76418, is the Cisco ASA and FTD flaw from our News post.
Two honest caveats. EPSS here is as of the day before, but CVSS is today’s: the NVD may have added some scores after the listing. And the engine orders work, it does not predict listings, so a P3 that gets listed is not a bug. It is the reason the KEV check runs first every day.
Step 7: Compare single rules by effort and coverage
The replay shows what the whole engine does. This step asks a different question: how good is each single rule, and what does it cost? Two numbers describe a rule. Effort is the share of all CVEs it flags, which is the work it creates. Coverage is the share of the CVEs later added to KEV that it flagged. A third number, lift, divides coverage by effort. A lift of 1.0 means the rule does no better than flagging CVEs at random. A lift of 4.5 means it finds 4.5 times as many future KEV additions as random flagging of the same size would.
The design is a forward test, repeated twice. Take a start day, use only what was known that day (the EPSS file of that day), and count the CVEs added to KEV in the next 30 days, the period EPSS is meant to predict. The two start days are 2026-09-15 and 2026-10-15. The EPSS files for old dates are still online, so you can reproduce this.
Write the backtest
Create backtest.py. The first part holds three helpers. wilson() computes a 95 percent interval for a proportion, which matters because the samples are small. additions() lists the KEV additions in the window, and band() sorts a score into a band.
# backtest.py: what did EPSS and CVSS say before CISA added a CVE to KEV?
import datetime as dt
import math
import statistics
import sys
from sources import best_cvss, cvss_rows, load_epss, load_kev, nvd_counts, nvd_record
EPSS_CUTS = (0.5, 0.1, 0.05, 0.01)
def wilson(k, n, z=1.96):
"""95 percent Wilson interval for k hits out of n."""
if n == 0:
return 0.0, 0.0
p = k / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return centre - half, centre + half
def additions(kev, day, horizon):
"""CVEs whose KEV dateAdded falls in the `horizon` days after `day`."""
last = (dt.date.fromisoformat(day) + dt.timedelta(days=horizon)).isoformat()
return sorted(cve for cve, item in kev.items() if day < item["dateAdded"] <= last), last
def band(value):
if value is None:
return "no score"
return "9.0 or more" if value >= 9 else "7.0 to 8.9" if value >= 7 else "under 7.0"
The second part runs one forward test. It splits the KEV additions into those EPSS had scored on the start day and those it had not, then evaluates six single rules and one combined rule. The effort of an EPSS rule is counted directly in that day’s file. The effort of a CVSS rule comes from the three NVD counts, as a share of all CVEs.
# backtest.py (continued)
def forward_test(day, kev, counts, horizon=30):
_, scores = load_epss(day)
positives, last = additions(kev, day, horizon)
records = {cve: nvd_record(cve) for cve in positives}
scored = [cve for cve in positives if cve in scores]
later = [cve for cve in positives if cve not in scores]
cvss = {cve: best_cvss(cvss_rows(records[cve])) for cve in positives}
total = len(scores)
critical = counts["critical"] / counts["all"]
high = counts["high"] / counts["all"]
rules = [] # (label, share of all CVEs flagged, share is only an upper bound, CVEs caught)
for cut in EPSS_CUTS:
share = sum(1 for epss, _ in scores.values() if epss >= cut) / total
rules.append((f"EPSS >= {cut}", share, False, [c for c in scored if scores[c][0] >= cut]))
hit9 = [c for c in scored if (cvss[c] or 0) >= 9.0]
hit7 = [c for c in scored if (cvss[c] or 0) >= 7.0]
rules.append(("CVSS >= 9.0", critical, False, hit9))
rules.append(("CVSS >= 7.0", critical + high, False, hit7))
epss_tenth = next(rule for rule in rules if rule[0] == "EPSS >= 0.1")
rules.append(("EPSS >= 0.1 or CVSS >= 9.0", epss_tenth[1] + critical, True, sorted(set(epss_tenth[3]) | set(hit9))))
published = lambda cve: records[cve].get("published", "")[:10]
ages = [(dt.date.fromisoformat(day) - dt.date.fromisoformat(published(c))).days for c in scored if published(c)]
return {"day": day, "last": last, "rows": total, "positives": positives, "scored": scored, "later": later,
"published_after": sum(1 for c in later if published(c) > day), "ages": ages, "rules": rules,
"epss": {c: scores[c][0] for c in scored}, "cvss": cvss}
The last part prints one table per window and then a pooled table over both windows.
# backtest.py (continued)
def show(r):
print(f"Forward test from {r['day']}: KEV additions in the next 30 days, through {r['last']}")
print(f" EPSS scored {r['rows']} CVEs on {r['day']}")
print(f" added to KEV: {len(r['positives'])}; scored by EPSS that day: {len(r['scored'])}; not in that file: {len(r['later'])} ({r['published_after']} published in the NVD after that day)")
ages = sorted(r["ages"])
print(f" age of the {len(ages)} scored CVEs on that day: youngest {ages[0]} days, median {int(statistics.median(ages))}, oldest {ages[-1]}")
print(f" {'rule':<28}{'flags':>9} caught")
for label, share, upper, caught in r["rules"]:
print(f" {label:<28}{('<=' if upper else '') + f'{100 * share:.1f}%':>9} {len(caught):>2} of {len(r['scored'])}")
def main(days):
_, kev = load_kev(max_age_hours=24 * 365)
counts = nvd_counts()
print(f"NVD on {counts['day']}: {counts['all']} CVEs, {counts['critical']} Critical and {counts['high']} High on CVSS v3")
results = []
for day in days:
print()
r = forward_test(day, kev, counts)
show(r)
results.append(r)
scored = sum(len(r["scored"]) for r in results)
print()
print(f"Both windows together: {scored} CVEs that EPSS had already scored on the day each test started")
print(f" {'rule':<28}{'flags':>9} {'caught':>9} {'coverage (95% interval)':<26}lift")
for index, (label, _, upper, _) in enumerate(results[0]["rules"]):
caught = sum(len(r["rules"][index][3]) for r in results)
flags = sum(r["rules"][index][1] for r in results) / len(results)
low, high = wilson(caught, scored)
coverage = caught / scored
text = f"{100 * coverage:.0f}% ({100 * low:.0f} to {100 * high:.0f})"
lift = "" if upper else f"{coverage / flags:.1f}"
print(f" {label:<28}{('<=' if upper else '') + f'{100 * flags:.1f}%':>9} {caught:>3} of {scored} {text:<26}{lift}")
bands = {"under 0.01": 0, "0.01 to 0.1": 0, "0.1 or more": 0}
for r in results:
for epss in r["epss"].values():
bands["under 0.01" if epss < 0.01 else "0.01 to 0.1" if epss < 0.1 else "0.1 or more"] += 1
later = sum(len(r["later"]) for r in results)
print()
print(f"EPSS on the start day for the {scored} scored CVEs: {bands}")
print(f"KEV additions that EPSS had no score for on the start day: {later} of {later + scored}")
for title, group in (("scored", "scored"), ("not scored", "later")):
tally = {"9.0 or more": 0, "7.0 to 8.9": 0, "under 7.0": 0, "no score": 0}
for r in results:
for cve in r[group]:
tally[band(r["cvss"][cve])] += 1
print(f"Highest CVSS base score of the CVEs EPSS had {title}: {tally}")
spreads = []
for r in results:
for cve in r["positives"]:
rows = cvss_rows(nvd_record(cve))
if len(rows) > 1:
low, high = min(rows, key=lambda x: x["score"]), max(rows, key=lambda x: x["score"])
spreads.append((high["score"] - low["score"], cve, low, high))
spreads.sort(key=lambda item: -item[0])
print()
print("Widest disagreement between sources among these CVEs")
for gap, cve, low, high in spreads[:3]:
print(f' {cve}: {low["score"]} (v{low["version"]}, {low["source"]}) to {high["score"]} (v{high["version"]}, {high["source"]})')
if __name__ == "__main__":
main(sys.argv[1:] or ["2026-09-15", "2026-10-15"])
Run it
python backtest.py 2026-09-15 2026-10-15
NVD on 2026-11-30: 414483 CVEs, 30928 Critical and 77661 High on CVSS v3
Forward test from 2026-09-15: KEV additions in the next 30 days, through 2026-10-15
EPSS scored 373366 CVEs on 2026-09-15
added to KEV: 36; scored by EPSS that day: 14; not in that file: 22 (21 published in the NVD after that day)
age of the 14 scored CVEs on that day: youngest 6 days, median 214, oldest 4138
rule flags caught
EPSS >= 0.5 1.2% 3 of 14
EPSS >= 0.1 4.7% 4 of 14
EPSS >= 0.05 8.2% 5 of 14
EPSS >= 0.01 39.1% 6 of 14
CVSS >= 9.0 7.5% 6 of 14
CVSS >= 7.0 26.2% 13 of 14
EPSS >= 0.1 or CVSS >= 9.0 <=12.1% 8 of 14
Forward test from 2026-10-15: KEV additions in the next 30 days, through 2026-11-14
EPSS scored 389824 CVEs on 2026-10-15
added to KEV: 35; scored by EPSS that day: 13; not in that file: 22 (19 published in the NVD after that day)
age of the 13 scored CVEs on that day: youngest 1 days, median 22, oldest 884
rule flags caught
EPSS >= 0.5 1.1% 0 of 13
EPSS >= 0.1 4.4% 0 of 13
EPSS >= 0.05 7.9% 0 of 13
EPSS >= 0.01 37.9% 3 of 13
CVSS >= 9.0 7.5% 3 of 13
CVSS >= 7.0 26.2% 7 of 13
EPSS >= 0.1 or CVSS >= 9.0 <=11.9% 3 of 13
Both windows together: 27 CVEs that EPSS had already scored on the day each test started
rule flags caught coverage (95% interval) lift
EPSS >= 0.5 1.1% 3 of 27 11% (4 to 28) 9.8
EPSS >= 0.1 4.5% 4 of 27 15% (6 to 32) 3.3
EPSS >= 0.05 8.1% 5 of 27 19% (8 to 37) 2.3
EPSS >= 0.01 38.5% 9 of 27 33% (19 to 52) 0.9
CVSS >= 9.0 7.5% 9 of 27 33% (19 to 52) 4.5
CVSS >= 7.0 26.2% 20 of 27 74% (55 to 87) 2.8
EPSS >= 0.1 or CVSS >= 9.0 <=12.0% 11 of 27 41% (25 to 59)
EPSS on the start day for the 27 scored CVEs: {'under 0.01': 18, '0.01 to 0.1': 5, '0.1 or more': 4}
KEV additions that EPSS had no score for on the start day: 44 of 71
Highest CVSS base score of the CVEs EPSS had scored: {'9.0 or more': 9, '7.0 to 8.9': 11, 'under 7.0': 7, 'no score': 0}
Highest CVSS base score of the CVEs EPSS had not scored: {'9.0 or more': 22, '7.0 to 8.9': 19, 'under 7.0': 3, 'no score': 0}
Widest disagreement between sources among these CVEs
CVE-2023-22894: 4.9 (v3.1, [email protected]) to 7.2 (v3.1, 134c704f-9b21-4f2e-91b3-4a467353bcc0)
CVE-2025-39964: 5.5 (v3.1, [email protected]) to 7.8 (v3.1, 416baaa9-dc9f-4396-8d5f-8c081fb06d67)
CVE-2026-21589: 7.5 (v3.1, [email protected]) to 9.3 (v4.0, [email protected])
Read the output
- Most KEV additions were new CVEs. Of the 71 CVEs added over the two windows, 44 (62 percent) were not in EPSS’s file on the start day. In the NVD, 40 of them were published after the start day. A ranking built on a snapshot cannot see these, which is why the daily loop of step 6 matters. Half of them (22 of 44) now carry a Critical CVSS score. For a CVE that EPSS cannot score yet, CVSS is the signal most likely to be on hand.
- The CVEs EPSS had scored were mostly young. The median age was 214 days in the first window and 22 days in the second. Most had an EPSS under 0.01 on the start day (18 of 27), 5 were between 0.01 and 0.1 and only 4 were at 0.1 or more.
- Coverage is low for every single rule. Among the 27 scored CVEs, CVSS 9.0 or more caught 9 (33 percent) at an effort of 7.5 percent of all CVEs, which is a lift of 4.5. EPSS 0.1 or more caught 4 (15 percent) at 4.5 percent effort, a lift of 3.3. EPSS 0.5 or more caught 3 at a lift of 9.8, but with 3 hits the interval runs from 4 to 28 percent.
- The two signals found different CVEs. Together, “EPSS 0.1 or more or CVSS 9.0 or more” caught 11 of 27 (41 percent), while 4 and 9 alone would add up to 13. Only 2 CVEs were caught by both.
- Broad rules look good until you count the work. CVSS 7.0 or more caught 20 of 27 (74 percent) but flags 26.2 percent of all CVEs, roughly 108,000 of them. EPSS 0.01 or more flags 38.5 percent of all CVEs and has a lift of 0.9, no better than random.
- The windows disagree. EPSS 0.1 or more caught 4 of 14 in the first window and 0 of 13 in the second. With 27 CVEs the intervals overlap heavily, so this test cannot say which signal is better in general. It shows the method, and the size of the effects you should expect to have to measure.
- Sources disagree on CVSS, too. The widest gaps among these CVEs were 4.9 against 7.2, 5.5 against 7.8 and 7.5 against 9.3, each between the NVD’s own score and a CNA’s.
Three more warnings belong here. KEV is a conservative list of confirmed exploitation, not a list of everything attackers use, and FIRST describes EPSS as estimating whether a CVE will be exploited in the wild, not whether CISA will list it. Scoring EPSS against KEV alone can therefore make high scores look wrong when the exploitation never reached the catalog. The CVSS rows use today’s NVD data, because the NVD cannot be rewound, so they are a little generous to CVSS. And the 27-CVE sample is far too small for strong claims. Use these numbers to learn the method, then repeat it with more windows and your own thresholds.
Step 8: Test the rules and plant mistakes on purpose
Thresholds like “greater than or equal to” are where triage code quietly goes wrong. A single wrong comparison sends the wrong CVEs to the wrong bucket, and nothing crashes. So write tests that pin every rule, including the boundaries, and then check that the tests would actually notice a mistake.
Write the tests
Create test_triage.py. The first group tests decide(), one test per rule and per boundary. The second group tests the small parsers in sources.py with made-up records, so it needs no network.
# test_triage.py: tests for the decision rules and for the small parsers in sources.py
import gzip
import pytest
import sources
from triage import Signals, decide
def bucket(**signals):
return decide(Signals(cve="CVE-2026-0001", **signals)).bucket
def test_kev_listing_wins_over_weak_scores():
assert bucket(in_kev=True, epss=0.0001, cvss=3.1).startswith("P0")
def test_kev_listing_with_nothing_else_known_is_still_p0():
assert bucket(in_kev=True).startswith("P0")
def test_kev_reasons_carry_the_due_date_and_the_ransomware_flag():
d = decide(Signals(cve="CVE-2026-0001", in_kev=True, kev_due="2026-12-01", ransomware=True))
assert d.reasons == ("listed in CISA KEV", "CISA due date 2026-12-01", "used in ransomware campaigns")
def test_epss_at_the_cut_off_is_p1():
assert bucket(epss=0.10, cvss=4.0).startswith("P1")
def test_epss_just_below_the_cut_off_is_not_p1():
assert not bucket(epss=0.0999, cvss=4.0).startswith("P1")
def test_cvss_exactly_9_counts_as_critical():
assert bucket(epss=0.001, cvss=9.0).startswith("P2")
def test_critical_cvss_without_epss_says_that_epss_is_missing():
d = decide(Signals(cve="CVE-2026-0001", cvss=9.8))
assert d.bucket.startswith("P2") and "EPSS not published yet" in d.reasons
def test_raised_epss_and_high_cvss_together_are_p2():
assert bucket(epss=0.02, cvss=7.5).startswith("P2")
def test_raised_epss_with_a_middling_cvss_is_routine():
assert bucket(epss=0.02, cvss=6.9).startswith("P3")
def test_high_cvss_with_a_tiny_epss_is_routine():
assert bucket(epss=0.005, cvss=8.8).startswith("P3")
def test_a_missing_epss_is_not_a_zero():
assert bucket(epss=None, cvss=5.0).startswith("WAIT")
assert bucket(epss=0.0, cvss=5.0).startswith("P3")
def test_a_missing_cvss_waits():
assert bucket(epss=0.001, cvss=None).startswith("WAIT")
def test_nothing_known_waits_and_names_both_scores():
d = decide(Signals(cve="CVE-2026-0001"))
assert d.bucket.startswith("WAIT") and "EPSS and CVSS" in d.reasons[0]
def test_a_percentage_in_place_of_a_probability_is_refused():
with pytest.raises(ValueError):
Signals(cve="CVE-2026-0001", epss=10.0)
def test_a_score_on_a_hundred_point_scale_is_refused():
with pytest.raises(ValueError):
Signals(cve="CVE-2026-0001", cvss=98)
def metric(version, score, source="[email protected]"):
data = {"version": version, "baseScore": score, "baseSeverity": "HIGH", "vectorString": f"CVSS:{version}/AV:N"}
return {"source": source, "type": "Primary", "cvssData": data}
RECORD = {"metrics": {
"cvssMetricV40": [metric("4.0", 9.3, "[email protected]")],
"cvssMetricV31": [metric("3.1", 7.5)],
"cvssMetricV30": [metric("3.0", 8.8)],
"cvssMetricV2": [{"source": "[email protected]", "type": "Primary", "cvssData": {"version": "2.0", "baseScore": 10.0}}],
}}
def test_cvss_rows_read_v40_v31_and_v30_and_skip_v2():
rows = sources.cvss_rows(RECORD)
assert [(row["version"], row["score"]) for row in rows] == [("4.0", 9.3), ("3.1", 7.5), ("3.0", 8.8)]
def test_best_cvss_takes_the_highest_source():
assert sources.best_cvss(sources.cvss_rows(RECORD)) == 9.3
def test_best_cvss_of_an_unscored_cve_is_none():
assert sources.best_cvss(sources.cvss_rows({})) is None
def test_epss_api_gives_the_probability_first_and_the_percentile_second(monkeypatch):
class Reply:
def json(self):
return {"data": [{"cve": "CVE-2026-0001", "epss": "0.25000", "percentile": "0.90000"}]}
monkeypatch.setattr(sources, "get", lambda url, **kwargs: Reply())
assert sources.epss_api(["CVE-2026-0001"]) == {"CVE-2026-0001": (0.25, 0.9)}
def test_daily_file_is_parsed_with_its_header_line(tmp_path, monkeypatch):
monkeypatch.setattr(sources, "CACHE", tmp_path)
text = "#model_version:v1,score_date:2026-01-01T00:00:00Z\ncve,epss,percentile\nCVE-2026-0001,0.25,0.9\nCVE-2026-0002,0.001,0.1\n"
(tmp_path / "epss_2026-01-01.csv.gz").write_bytes(gzip.compress(text.encode()))
header, scores = sources.load_epss("2026-01-01")
assert header.startswith("model_version:v1")
assert scores == {"CVE-2026-0001": (0.25, 0.9), "CVE-2026-0002": (0.001, 0.1)}
python -m pytest -q
.................... [100%]
20 passed in 0.09s
Twenty tests pass. Passing tests prove little by themselves, though. The next script checks whether they can fail.
Plant 13 mistakes and see whether the tests notice
This is called mutation testing. mutants.py copies the lab, changes one thing in the copy, such as turning >= into > or taking the lowest score instead of the highest, and runs the tests. If the tests fail, the mistake was caught. If they pass, the mistake survived and your tests have a blind spot.
# mutants.py: plant one mistake at a time in a copy of the lab and check that the tests notice
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).parent
FILES = ("sources.py", "triage.py", "test_triage.py")
MUTANTS = [
("EPSS cut-off uses > instead of >=", "triage.py", "s.epss >= EPSS_FIX_WEEK", "s.epss > EPSS_FIX_WEEK"),
("Critical cut-off uses > instead of >=", "triage.py", "s.cvss >= CVSS_CRITICAL", "s.cvss > CVSS_CRITICAL"),
("KEV only counts when CVSS is high", "triage.py", "if s.in_kev:", "if s.in_kev and (s.cvss or 0) >= CVSS_HIGH:"),
("missing scores are not checked", "triage.py", "if s.epss is None or s.cvss is None:", "if False:"),
("EPSS watch level raised to 0.1", "triage.py", "EPSS_WATCH = 0.01", "EPSS_WATCH = 0.1"),
("CVSS High level raised to 8.0", "triage.py", "CVSS_HIGH = 7.0", "CVSS_HIGH = 8.0"),
("EPSS range check removed", "triage.py", "if self.epss is not None and not 0.0 <= self.epss <= 1.0:", "if False:"),
("ransomware reason dropped", "triage.py", "if s.ransomware:", "if False:"),
("raised pair uses or instead of and", "triage.py", "s.epss >= EPSS_WATCH and s.cvss >= CVSS_HIGH", "s.epss >= EPSS_WATCH or s.cvss >= CVSS_HIGH"),
("best_cvss takes the lowest score", "sources.py", 'max((row["score"] for row in rows), default=None)', 'min((row["score"] for row in rows), default=None)'),
("CVSS v4.0 rows ignored", "sources.py", '("cvssMetricV40", "cvssMetricV31", "cvssMetricV30")', '("cvssMetricV31", "cvssMetricV30")'),
("API answer swaps epss and percentile", "sources.py",
'(float(row["epss"]), float(row["percentile"])) for row in rows}', '(float(row["percentile"]), float(row["epss"])) for row in rows}'),
("daily file swaps epss and percentile", "sources.py",
'(float(row["epss"]), float(row["percentile"])) for row in csv.DictReader(io.StringIO(body))}',
'(float(row["percentile"]), float(row["epss"])) for row in csv.DictReader(io.StringIO(body))}'),
]
def passes(folder):
command = [sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:cacheprovider", "test_triage.py"]
return subprocess.run(command, cwd=folder, capture_output=True, text=True).returncode == 0
def fresh_copy(root, name):
folder = Path(root) / name
folder.mkdir()
for file in FILES:
shutil.copy(HERE / file, folder / file)
return folder
with tempfile.TemporaryDirectory() as root:
print("control, no mistake planted:", "tests pass" if passes(fresh_copy(root, "control")) else "TESTS FAIL")
caught = 0
for number, (label, file, old, new) in enumerate(MUTANTS, 1):
folder = fresh_copy(root, f"m{number}")
text = (folder / file).read_text(encoding="utf-8")
assert text.count(old) == 1, f"{label}: expected one match in {file}"
(folder / file).write_text(text.replace(old, new), encoding="utf-8")
failed = not passes(folder)
caught += failed
print(f" {number:>2}. {'caught ' if failed else 'SURVIVED'} {label}")
print(f"{caught} of {len(MUTANTS)} planted mistakes caught")
python mutants.py
control, no mistake planted: tests pass
1. caught EPSS cut-off uses > instead of >=
2. caught Critical cut-off uses > instead of >=
3. caught KEV only counts when CVSS is high
4. caught missing scores are not checked
5. caught EPSS watch level raised to 0.1
6. caught CVSS High level raised to 8.0
7. caught EPSS range check removed
8. caught ransomware reason dropped
9. caught raised pair uses or instead of and
10. caught best_cvss takes the lowest score
11. caught CVSS v4.0 rows ignored
12. caught API answer swaps epss and percentile
13. caught daily file swaps epss and percentile
13 of 13 planted mistakes caught
All 13 mistakes were caught, including the quiet ones: a changed boundary, a swapped EPSS and percentile column, and a missing-data check removed. Run this check again whenever you change a rule or add one.
Check that everything works end to end
Run these commands from the lab folder, with the virtual environment active. Each should end the way described.
python step01_kev.py CVE-2021-44228prints the catalog header and says that Log4Shell has been in KEV since 2021-12-10.python step02_epss.pyprints an EPSS file with 400,000 or more CVEs, and a line saying that about 38 percent of them score 0.01 or more.python step03_cvss.py CVE-2026-21589prints 9.8 Critical for the first vector and two NVD rows that both say “recomputed score matches.”python triage.py CVE-2021-44228 CVE-2026-114938prints a P0 line and a P1 line.python try_decide.pyprints six lines, ending with a WAIT.python fetch_nvd.pythenpython replay.pythenpython backtest.py 2026-09-15 2026-10-15print the tables of steps 6 and 7. Live numbers such as the EPSS values of step 5 drift from day to day, but the two backtest windows are pinned to past dates, so the 71 listings and the pooled table should match yours closely, unless CISA or the NVD has since edited records.python -m pytest -qprints20 passed, andpython mutants.pyends with13 of 13 planted mistakes caught.
Common mistakes and how to avoid them
- Reading a missing EPSS as zero. Brand-new CVEs have no score for a day or more. In the replay, 4 of the 53 public CVEs had no EPSS the day before, and 18 more were not public at all. The engine routes missing data to WAIT and asks again the next day.
- Confusing percentile with probability. A CVE at the 95th percentile has an EPSS of about 0.07, not 0.95.
- Using 0.01 as an urgency line. It flags 38 percent of all CVEs.
- Trusting one CVSS number. Sources and versions disagree, as in the 7.5 against 9.3 gap for CVE-2026-21589. Store the source with the score, and decide which one you will follow.
- Hammering the NVD. Without a key it allows 5 requests in a rolling 30 seconds. Cache every record and pause between calls.
- Judging a rule by hits alone. CVSS 7.0 or more caught the most CVEs and also created the most work. Always read effort and coverage together.
- Believing a small backtest. 27 CVEs, two windows that disagree, intervals that overlap. Treat it as an example of the method.
Where to go next
- Match the list to your own software. KEV entries carry
vendorProjectandproductfields. Compare them with an inventory of what you run, for example the SBOM from our pip-audit tutorial. - Add your environment. The environmental metrics of step 4 let you lower the score of a service that is not reachable from the internet. Keep the default for anything that is.
- Run it daily. Schedule the script, keep yesterday’s buckets in a file, and re-check every WAIT item the next morning.
- Look at a fourth signal. The NVD record you already download can carry a CISA SSVC block under
metrics, next to the CVSS entries. - Test longer. Add more start days to
backtest.py. The NVD documentation says a free API key, sent in a request header, raises the limit to 50 requests in 30 seconds, so with one you could add the header inget()and shortenNVD_PAUSE.








No Comment! Be the first one.