File size: 4,451 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""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())