#!/usr/bin/env python3 """Build the offline vulnerability bundle the Devseis app matches installed software against. Runs on the Devseis side (needs internet); clients only download the finished bundle. Sources (all public): OSV.dev Ubuntu, Debian, Red Hat, AlmaLinux, Rocky Linux package advisories (CC-BY 4.0) NVD CVEs for the desktop applications in products.json (public domain) CISA KEV known exploited vulnerabilities (CC0) EPSS exploit prediction scores (FIRST.org, free with attribution) Only actionable data is kept: vulnerabilities with a fixed version, for releases still in use. Usage: python3 vulndb/build_bundle.py # download what is missing, build vulndb/out/ python3 vulndb/build_bundle.py --refresh # download everything again python3 vulndb/build_bundle.py --only nvd # just refresh the NVD cache Standard library only. """ import argparse import csv import datetime import gzip import hashlib import io import json import math import os import re import sys import time import urllib.parse import urllib.request import zipfile HERE = os.path.dirname(os.path.abspath(__file__)) CACHE = os.path.join(HERE, "cache") OUT = os.path.join(HERE, "out") BUNDLE_FORMAT = 1 USER_AGENT = "Devseis-Endpoint-Auditor-vulndb/0.1" OSV_ECOSYSTEMS = ["Ubuntu", "Debian", "Red Hat", "AlmaLinux", "Rocky Linux"] KEV_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json" EPSS_URL = "https://epss.empiricalsecurity.com/epss_scores-current.csv.gz" NVD_URL = "https://services.nvd.nist.gov/rest/json/cves/2.0" NVD_PAUSE = 6.5 # public API: 5 requests per 30 seconds without a key # Releases kept in the bundle (older ones are out of support and flagged by gdpr.os_supported). KEEP = { "ubuntu": lambda v: v >= (22, 4), "debian": lambda v: v >= (11,), "rhel": lambda v: v >= (8,), "almalinux": lambda v: v >= (8,), "rocky": lambda v: v >= (8,), } SEVERITIES = ["critical", "high", "medium", "low", "unknown"] def log(msg): print(msg, flush=True) def fetch(url, path, refresh=False): if os.path.exists(path) and not refresh: return path tmp = path + ".part" req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(req, timeout=600) as resp, open(tmp, "wb") as handle: while True: chunk = resp.read(1 << 20) if not chunk: break handle.write(chunk) os.replace(tmp, path) return path def vtuple(text): return tuple(int(x) for x in re.findall(r"\d+", text)) # --- severity --------------------------------------------------------------------------- def cvss3_score(vector): """Base score from a CVSS v3.x vector (FIRST specification).""" try: m = dict(part.split(":") for part in vector.split("/")[1:]) av = {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2}[m["AV"]] ac = {"L": 0.77, "H": 0.44}[m["AC"]] changed = m["S"] == "C" pr = {"N": 0.85, "L": 0.68 if changed else 0.62, "H": 0.5 if changed else 0.27}[m["PR"]] ui = {"N": 0.85, "R": 0.62}[m["UI"]] cia = [{"H": 0.56, "L": 0.22, "N": 0.0}[m[k]] for k in ("C", "I", "A")] except (KeyError, ValueError): return None iss = 1 - (1 - cia[0]) * (1 - cia[1]) * (1 - cia[2]) impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if changed else 6.42 * iss if impact <= 0: return 0.0 exploit = 8.22 * av * ac * pr * ui raw = min(1.08 * (impact + exploit), 10) if changed else min(impact + exploit, 10) return math.ceil(raw * 10 - 1e-9) / 10 def severity_from_score(score): if score is None: return "unknown" return "critical" if score >= 9 else "high" if score >= 7 else "medium" if score >= 4 else "low" if score > 0 else "unknown" def osv_severity(record): """Distribution rating if present, else computed from a CVSS v3 vector.""" for sev in record.get("severity", []): if sev.get("type") == "Ubuntu": return {"negligible": "low"}.get(sev["score"].lower(), sev["score"].lower()) for source in (record.get("database_specific") or {}, *(a.get("ecosystem_specific") or {} for a in record.get("affected", []))): rating = str(source.get("severity", "")).lower() if rating in ("critical", "important", "high", "moderate", "medium", "low"): return {"important": "high", "moderate": "medium"}.get(rating, rating) for sev in record.get("severity", []): if sev.get("type", "").startswith("CVSS_V3"): return severity_from_score(cvss3_score(sev["score"])) return "unknown" # --- OSV (Linux distributions) ------------------------------------------------------------ def release_key(ecosystem): """'Ubuntu:24.04:LTS' -> 'ubuntu:24.04'; None for releases or streams we do not keep.""" parts = ecosystem.split(":") name = parts[0] if name == "Ubuntu": if len(parts) < 2 or parts[1] == "Pro" or not re.match(r"^\d+\.\d+$", parts[1]): return None family, version = "ubuntu", parts[1] elif name == "Debian": if len(parts) < 2 or not parts[1].isdigit(): return None family, version = "debian", parts[1] elif name == "Red Hat": # Red Hat:enterprise_linux:9::baseos (EUS, SAP and other streams are skipped) if len(parts) < 3 or parts[1] != "enterprise_linux" or not re.match(r"^\d+$", parts[2]): return None family, version = "rhel", parts[2] elif name in ("AlmaLinux", "Rocky Linux"): if len(parts) < 2 or not re.match(r"^\d+$", parts[1]): return None family, version = ("almalinux" if name == "AlmaLinux" else "rocky"), parts[1] else: return None return f"{family}:{version}" if KEEP[family](vtuple(version)) else None def cve_ids(record): ids = {i for i in [record["id"], *record.get("aliases", []), *record.get("upstream", []), *record.get("related", [])] if i.startswith("CVE-")} return sorted(ids) def build_osv(stats): releases = {} rating = {} # CVE -> best known rating from any distribution for eco in OSV_ECOSYSTEMS: path = os.path.join(CACHE, f"osv-{eco.replace(' ', '_')}.zip") if not os.path.exists(path): log(f" {eco}: not downloaded, skipped") continue kept = 0 with zipfile.ZipFile(path) as archive: names = archive.namelist() for name in names: record = json.loads(archive.read(name)) if record.get("withdrawn"): continue # Debian publishes DSA/DLA advisories and per-CVE records; the per-CVE ones carry the fixed versions. if eco == "Debian" and not record["id"].startswith("DEBIAN-CVE-"): continue cves = cve_ids(record) if not cves: continue # bug-fix / enhancement advisories advisory = record["id"] if not record["id"].startswith(("UBUNTU-CVE-", "DEBIAN-CVE-")) else "" severity = osv_severity(record) if severity != "unknown": for cve in cves: rating.setdefault(cve, severity) for affected in record.get("affected", []): key = release_key(affected["package"]["ecosystem"]) if not key or "-sig-" in affected["package"].get("purl", ""): # special-interest builds (e.g. cloud kernels) continue for rng in affected.get("ranges", []): if rng.get("type") != "ECOSYSTEM": continue for event in rng.get("events", []): if "fixed" not in event: continue entry = ["|".join(cves) or record["id"], advisory, event["fixed"], severity] releases.setdefault(key, {}).setdefault(affected["package"]["name"], []).append(entry) kept += 1 log(f" {eco}: {len(names)} records, {kept} fixed-version entries kept") # Some records carry no rating (AlmaLinux, some Debian): borrow another distribution's rating for the same CVE. borrowed = 0 for key, packages in releases.items(): for entries in packages.values(): unique = {} for entry in entries: if entry[3] == "unknown": for cve in entry[0].split("|"): if cve in rating: entry[3] = rating[cve] borrowed += 1 break unique[(entry[0], entry[1], entry[2])] = entry entries[:] = sorted(unique.values()) stats["osv"] = {key: sum(len(v) for v in pkgs.values()) for key, pkgs in sorted(releases.items())} stats["osv_ratings_borrowed"] = borrowed return releases # --- NVD (desktop applications) ---------------------------------------------------------------- def nvd_query(cpe): """All CVEs for vendor:product, cached as raw pages.""" part, vendor, product = cpe.split(":", 2) if cpe.count(":") >= 2 and cpe[1] == ":" else ("a", *cpe.split(":", 1)) path = os.path.join(CACHE, "nvd", re.sub(r"[^A-Za-z0-9_.-]", "_", cpe) + ".json") if os.path.exists(path): with open(path, encoding="utf-8") as handle: return json.load(handle) os.makedirs(os.path.dirname(path), exist_ok=True) items, start = [], 0 while True: params = urllib.parse.urlencode({"virtualMatchString": f"cpe:2.3:{part}:{vendor}:{product}", "startIndex": start, "noRejected": ""}) url = f"{NVD_URL}?{params}".replace("noRejected=", "noRejected") for attempt in range(5): try: req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) if os.environ.get("NVD_API_KEY"): req.add_header("apiKey", os.environ["NVD_API_KEY"]) with urllib.request.urlopen(req, timeout=120) as resp: page = json.load(resp) break except Exception as exc: # rate limit or transient error: wait and retry log(f" {cpe} page {start}: {exc}; retrying") time.sleep(30 * (attempt + 1)) else: raise RuntimeError(f"NVD query failed for {cpe}") items.extend(page.get("vulnerabilities", [])) start += page.get("resultsPerPage", 0) time.sleep(NVD_PAUSE) if start >= page.get("totalResults", 0) or not page.get("resultsPerPage"): break with open(path, "w", encoding="utf-8") as handle: json.dump(items, handle) return items def nvd_severity(cve): metrics = cve.get("metrics", {}) for key in ("cvssMetricV31", "cvssMetricV30", "cvssMetricV40", "cvssMetricV2"): rows = metrics.get(key) or [] rows = sorted(rows, key=lambda r: r.get("type") != "Primary") for row in rows: rating = (row.get("cvssData", {}).get("baseSeverity") or row.get("baseSeverity") or "").lower() if rating in SEVERITIES: return rating if row.get("cvssData", {}).get("baseScore") is not None: return severity_from_score(row["cvssData"]["baseScore"]) return "unknown" def cpe_parts(criteria): # cpe:2.3:a:vendor:product:version:... (escaped colons are not used by the products we track) parts = re.split(r"(?= 0.01}, } os.makedirs(OUT, exist_ok=True) name = f"devseis-vulndb-{today}.json.gz" raw = json.dumps(bundle, separators=(",", ":")).encode("utf-8") data = gzip.compress(raw, 9, mtime=0) with open(os.path.join(OUT, name), "wb") as handle: handle.write(data) manifest = { "format": BUNDLE_FORMAT, "file": name, "built_at": bundle["built_at"], "size": len(data), "sha256": hashlib.sha256(data).hexdigest(), "sources": bundle["sources"], "counts": {"releases": stats["osv"], "apps": stats["nvd"], "kev": len(bundle["kev"]), "epss": len(bundle["epss"])}, "signature": None, } # Small bundle for the phone web check: mobile OS records only. mobile_apps = [a for a in apps if a.get("ios")] mobile_cves = {row[0] for a in mobile_apps for row in a["cves"]} mobile = {**{k: bundle[k] for k in ("format", "built_at", "sources")}, "notes": "Phone web check subset: iOS and iPadOS NVD records.", "releases": {}, "apps": mobile_apps, "kev": sorted(mobile_cves & kev), "epss": {cve: score for cve, score in bundle["epss"].items() if cve in mobile_cves}} mobile_name = f"devseis-vulndb-mobile-{today}.json.gz" mobile_data = gzip.compress(json.dumps(mobile, separators=(",", ":")).encode("utf-8"), 9, mtime=0) with open(os.path.join(OUT, mobile_name), "wb") as handle: handle.write(mobile_data) manifest["mobile"] = {"file": mobile_name, "size": len(mobile_data), "sha256": hashlib.sha256(mobile_data).hexdigest(), "signature": None} for old in os.listdir(OUT): if old.startswith("devseis-vulndb-") and old not in (name, mobile_name): os.remove(os.path.join(OUT, old)) with open(os.path.join(OUT, "manifest.json"), "w", encoding="utf-8") as handle: json.dump(manifest, handle, indent=2) log(f"\nWrote vulndb/out/{name}: {len(data) / 1048576:.1f} MB compressed ({len(raw) / 1048576:.1f} MB raw)") log(json.dumps(manifest["counts"], indent=1)) log("Next: node vulndb/sign-bundle.mjs (adds the Ed25519 signature to manifest.json)") if __name__ == "__main__": sys.exit(main())