v0.3: phone check (iPhone, Android) as the Space front page, catalog 0.3 (74 checks), shared vulnerability rules, real-CVE training data
6ccf48e verified Download vulndb/build_bundle.py from Devseis/Arx: direct link, hf CLI and curl.
- Browser
- Download file 19.3 kB
-
https://huggingface.co/spaces/Devseis/Arx/resolve/main/vulndb/build_bundle.py
- Command line
-
hf download hf://spaces/Devseis/Arx/vulndb/build_bundle.py
-
curl -L -o build_bundle.py https://huggingface.co/spaces/Devseis/Arx/resolve/main/vulndb/build_bundle.py
19.3 kB
| #!/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"(?<!\\):", criteria) | |
| return parts[3], parts[4], parts[5] | |
| def build_nvd(products, stats): | |
| apps = [] | |
| for product in products: | |
| ranges = {} | |
| for cpe in product["cpe"]: | |
| vendor, name = cpe.split(":")[-2:] | |
| for item in nvd_query(cpe): | |
| cve = item["cve"] | |
| severity = nvd_severity(cve) | |
| for config in cve.get("configurations", []): | |
| for node in config.get("nodes", []): | |
| for match in node.get("cpeMatch", []): | |
| if not match.get("vulnerable"): | |
| continue | |
| m_vendor, m_product, version = cpe_parts(match["criteria"]) | |
| if (m_vendor, m_product.replace("\\", "")) != (vendor, name.replace("\\", "")): | |
| continue | |
| exact = "" if version in ("*", "-") else version.replace("\\", "") | |
| row = (cve["id"], severity, match.get("versionStartIncluding", ""), match.get("versionStartExcluding", ""), | |
| match.get("versionEndIncluding", ""), match.get("versionEndExcluding", ""), exact) | |
| if version == "-" or (not exact and not row[4] and not row[5]): | |
| continue # no upper bound ("all versions" or "from version X on"): cannot tell fixed from unfixed | |
| ranges[row] = True | |
| apps.append({"id": product["id"], "name": product["name"], "windows": product.get("windows", ""), "macos": product.get("macos", ""), "ios": product.get("ios", ""), | |
| "cves": sorted(list(r) for r in ranges)}) | |
| stats["nvd"][product["id"]] = len({r[0] for r in ranges}) | |
| if not ranges: | |
| log(f" warning: no NVD ranges for {product['id']} ({', '.join(product['cpe'])})") | |
| return apps | |
| # --- KEV and EPSS ---------------------------------------------------------------------------- | |
| def load_kev(): | |
| with open(os.path.join(CACHE, "kev.json"), encoding="utf-8") as handle: | |
| data = json.load(handle) | |
| return data.get("catalogVersion", ""), {v["cveID"] for v in data["vulnerabilities"]} | |
| def load_epss(): | |
| with gzip.open(os.path.join(CACHE, "epss.csv.gz"), "rt", encoding="utf-8") as handle: | |
| first = handle.readline() # "#model_version:...,score_date:..." | |
| scores = {row["cve"]: float(row["epss"]) for row in csv.DictReader(handle)} | |
| date = re.search(r"score_date:(\S+)", first) | |
| return (date.group(1)[:10] if date else ""), scores | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--refresh", action="store_true", help="download every source again") | |
| parser.add_argument("--only", choices=["nvd", "osv"], help="only refresh one source cache") | |
| args = parser.parse_args() | |
| os.makedirs(CACHE, exist_ok=True) | |
| with open(os.path.join(HERE, "products.json"), encoding="utf-8") as handle: | |
| products = json.load(handle)["products"] | |
| if args.refresh and args.only != "osv": | |
| for name in os.listdir(os.path.join(CACHE, "nvd")) if os.path.isdir(os.path.join(CACHE, "nvd")) else []: | |
| os.remove(os.path.join(CACHE, "nvd", name)) | |
| if args.only != "nvd": | |
| for eco in OSV_ECOSYSTEMS: | |
| log(f"download OSV {eco}") | |
| fetch(f"https://osv-vulnerabilities.storage.googleapis.com/{urllib.parse.quote(eco)}/all.zip", | |
| os.path.join(CACHE, f"osv-{eco.replace(' ', '_')}.zip"), args.refresh) | |
| fetch(KEV_URL, os.path.join(CACHE, "kev.json"), args.refresh) | |
| fetch(EPSS_URL, os.path.join(CACHE, "epss.csv.gz"), args.refresh) | |
| if args.only != "osv": | |
| log("NVD desktop applications") | |
| for product in products: | |
| for cpe in product["cpe"]: | |
| log(f" {cpe}: {len(nvd_query(cpe))} CVEs") | |
| if args.only: | |
| return | |
| stats = {"nvd": {}} | |
| log("OSV distributions") | |
| releases = build_osv(stats) | |
| log("NVD applications") | |
| apps = build_nvd(products, stats) | |
| kev_version, kev = load_kev() | |
| epss_date, epss_all = load_epss() | |
| used = set() | |
| for packages in releases.values(): | |
| for entries in packages.values(): | |
| for entry in entries: | |
| used.update(entry[0].split("|")) | |
| for app in apps: | |
| used.update(row[0] for row in app["cves"]) | |
| today = datetime.date.today().isoformat() | |
| bundle = { | |
| "format": BUNDLE_FORMAT, | |
| "built_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), | |
| "sources": { | |
| "osv": {"ecosystems": OSV_ECOSYSTEMS, "downloaded": today, "license": "CC-BY 4.0 (osv.dev)"}, | |
| "nvd": {"products": len(apps), "downloaded": today, "license": "Public domain (NIST NVD); not endorsed by NIST"}, | |
| "kev": {"catalog_version": kev_version, "license": "CC0 (CISA)"}, | |
| "epss": {"score_date": epss_date, "license": "FIRST.org EPSS, free with attribution"}, | |
| }, | |
| "notes": "Only vulnerabilities with a fixed version are included. Linux package names are source packages (Ubuntu, Debian) or binary RPM names (Red Hat family).", | |
| "releases": releases, | |
| "apps": apps, | |
| "kev": sorted(used & kev), | |
| "epss": {cve: round(epss_all[cve], 4) for cve in sorted(used) if cve in epss_all and epss_all[cve] >= 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()) | |