Download scripts/ingest/fetch_nvd_recent.py from continuum-oss/ccrb: direct link, hf CLI and curl.
- Browser
- Download file 4.45 kB
-
https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/scripts/ingest/fetch_nvd_recent.py
- Command line
-
hf download hf://datasets/continuum-oss/ccrb/scripts/ingest/fetch_nvd_recent.py
-
curl -L -o fetch_nvd_recent.py https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/scripts/ingest/fetch_nvd_recent.py
4.45 kB
| """Fetch recent 2024-2026 NVD CVE JSON 2.0 slices using 120-day publication windows.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.parse | |
| import urllib.request | |
| from datetime import datetime, timedelta, timezone | |
| from pathlib import Path | |
| from typing import Any | |
| _REPO_ROOT = Path(__file__).resolve().parent.parent.parent | |
| if str(_REPO_ROOT) not in sys.path: | |
| sys.path.insert(0, str(_REPO_ROOT)) | |
| from scripts.ingest.fetch_raw import USER_AGENT, sha256_file | |
| def fetch_nvd_windows( | |
| raw_dir: Path, | |
| *, | |
| windows: list[tuple[str, str]], | |
| max_pages_per_window: int = 2, | |
| results_per_page: int = 2000, | |
| ) -> list[dict[str, Any]]: | |
| """Fetch NVD JSON 2.0 pages across explicit ISO date windows.""" | |
| nvd_dir = raw_dir / "nvd" | |
| nvd_dir.mkdir(parents=True, exist_ok=True) | |
| api_key = os.environ.get("NVD_API_KEY", "").strip() | |
| sleep_seconds = 0.8 if api_key else 6.3 | |
| saved_pages: list[dict[str, Any]] = [] | |
| page_counter = 0 | |
| for win_idx, (start_iso, end_iso) in enumerate(windows): | |
| start_index = 0 | |
| for sub_page in range(max_pages_per_window): | |
| out_path = nvd_dir / f"nvd_page_{page_counter:04d}.json" | |
| params = { | |
| "pubStartDate": start_iso, | |
| "pubEndDate": end_iso, | |
| "startIndex": str(start_index), | |
| "resultsPerPage": str(results_per_page), | |
| } | |
| url = "https://services.nvd.nist.gov/rest/json/cves/2.0?" + urllib.parse.urlencode(params) | |
| headers = {"User-Agent": USER_AGENT} | |
| if api_key: | |
| headers["apiKey"] = api_key | |
| print(f"[nvd] window {win_idx + 1}/{len(windows)} ({start_iso[:10]}..{end_iso[:10]}) startIndex={start_index}") | |
| req = urllib.request.Request(url, headers=headers) | |
| with urllib.request.urlopen(req, timeout=60) as resp: | |
| payload = json.loads(resp.read().decode("utf-8")) | |
| out_path.write_text(json.dumps(payload), encoding="utf-8") | |
| vulns = payload.get("vulnerabilities", []) | |
| total_results = int(payload.get("totalResults", 0)) | |
| saved_pages.append( | |
| { | |
| "file": str(out_path.relative_to(raw_dir)), | |
| "window": [start_iso, end_iso], | |
| "count": len(vulns), | |
| "total_results": total_results, | |
| "sha256": sha256_file(out_path), | |
| } | |
| ) | |
| print(f"[done] {out_path.name}: {len(vulns)} CVEs (window total={total_results})") | |
| page_counter += 1 | |
| start_index += len(vulns) | |
| if not vulns or start_index >= total_results: | |
| break | |
| time.sleep(sleep_seconds) | |
| time.sleep(sleep_seconds) | |
| manifest_path = nvd_dir / "nvd_manifest.json" | |
| manifest_path.write_text(json.dumps(saved_pages, indent=2) + "\n", encoding="utf-8") | |
| return saved_pages | |
| def build_default_windows(end_dt: datetime, num_windows: int = 8) -> list[tuple[str, str]]: | |
| """Build backwards 115-day NVD API windows ending at `end_dt`.""" | |
| windows: list[tuple[str, str]] = [] | |
| cur_end = end_dt | |
| for _ in range(num_windows): | |
| cur_start = cur_end - timedelta(days=115) | |
| windows.append( | |
| ( | |
| cur_start.strftime("%Y-%m-%dT00:00:00.000Z"), | |
| cur_end.strftime("%Y-%m-%dT23:59:59.000Z"), | |
| ) | |
| ) | |
| cur_end = cur_start - timedelta(seconds=1) | |
| return windows | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description="Fetch recent NVD CVE JSON 2.0 slices.") | |
| parser.add_argument("--raw-dir", type=Path, default=Path("data/raw")) | |
| parser.add_argument("--windows", type=int, default=6, help="Number of 115-day windows backwards from today.") | |
| parser.add_argument("--max-pages-per-window", type=int, default=2) | |
| args = parser.parse_args(argv) | |
| windows = build_default_windows(datetime.now(timezone.utc), num_windows=args.windows) | |
| try: | |
| fetch_nvd_windows( | |
| args.raw_dir, | |
| windows=windows, | |
| max_pages_per_window=args.max_pages_per_window, | |
| ) | |
| except urllib.error.URLError as exc: | |
| print(f"NVD fetch error: {exc}", file=sys.stderr) | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |