File size: 8,813 Bytes
27f6252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#!/usr/bin/env python3
"""
Compare CVE data from NVD zip (original) vs fkie-cad xz (GitHub release)
to understand exact structural differences.
"""
import json
from pathlib import Path

def compare_top_level_keys(nvd_data, fkie_data, year):
    """Compare top-level JSON keys."""
    print(f"\n{'='*70}")
    print(f"  YEAR: {year}")
    print(f"{'='*70}")
    
    nvd_keys = set(nvd_data.keys())
    fkie_keys = set(fkie_data.keys())
    
    print(f"\n[NVD zip]  Top-level keys: {sorted(nvd_keys)}")
    print(f"[fkie xz]  Top-level keys: {sorted(fkie_keys)}")
    
    only_nvd = nvd_keys - fkie_keys
    only_fkie = fkie_keys - nvd_keys
    common = nvd_keys & fkie_keys
    
    if only_nvd:
        print(f"  Keys ONLY in NVD:  {sorted(only_nvd)}")
    if only_fkie:
        print(f"  Keys ONLY in fkie: {sorted(only_fkie)}")
    if common:
        print(f"  Common keys:       {sorted(common)}")
    
    return nvd_keys, fkie_keys

def compare_cve_counts(nvd_data, fkie_data, year):
    """Compare CVE counts."""
    # NVD uses 'vulnerabilities'
    nvd_vulns = nvd_data.get('vulnerabilities', [])
    
    # fkie uses 'cve_items'
    fkie_vulns = fkie_data.get('cve_items', [])
    # also try 'vulnerabilities' in case fkie uses same key
    if not fkie_vulns:
        fkie_vulns = fkie_data.get('vulnerabilities', [])
    
    print(f"\n  CVE count NVD:  {len(nvd_vulns)}")
    print(f"  CVE count fkie: {len(fkie_vulns)}")
    
    return nvd_vulns, fkie_vulns

def compare_single_cve_structure(nvd_vulns, fkie_vulns, year):
    """Compare the structure of a single CVE entry."""
    if not nvd_vulns or not fkie_vulns:
        print("  [SKIP] No CVE entries to compare.")
        return
    
    nvd_first = nvd_vulns[0]
    fkie_first = fkie_vulns[0]
    
    print(f"\n  --- First CVE entry structure ---")
    print(f"  [NVD]  Type: {type(nvd_first).__name__}, Keys: {sorted(nvd_first.keys()) if isinstance(nvd_first, dict) else 'N/A'}")
    print(f"  [fkie] Type: {type(fkie_first).__name__}, Keys: {sorted(fkie_first.keys()) if isinstance(fkie_first, dict) else 'N/A'}")
    
    # NVD wraps in {"cve": {...}}, fkie might not
    nvd_cve = nvd_first.get('cve', nvd_first) if isinstance(nvd_first, dict) else nvd_first
    fkie_cve = fkie_first.get('cve', fkie_first) if isinstance(fkie_first, dict) else fkie_first
    
    if isinstance(nvd_cve, dict) and isinstance(fkie_cve, dict):
        print(f"\n  --- Inner CVE object keys ---")
        nvd_cve_keys = sorted(nvd_cve.keys())
        fkie_cve_keys = sorted(fkie_cve.keys())
        print(f"  [NVD]  CVE keys: {nvd_cve_keys}")
        print(f"  [fkie] CVE keys: {fkie_cve_keys}")
        
        nvd_id = nvd_cve.get('id', 'N/A')
        fkie_id = fkie_cve.get('id', 'N/A')
        print(f"\n  [NVD]  First CVE ID: {nvd_id}")
        print(f"  [fkie] First CVE ID: {fkie_id}")

def compare_cve_ids(nvd_vulns, fkie_vulns, year):
    """Compare CVE ID sets between sources."""
    nvd_ids = set()
    for v in nvd_vulns:
        cve = v.get('cve', v) if isinstance(v, dict) else {}
        cve_id = cve.get('id', '')
        if cve_id:
            nvd_ids.add(cve_id)
    
    fkie_ids = set()
    for v in fkie_vulns:
        cve = v.get('cve', v) if isinstance(v, dict) else {}
        cve_id = cve.get('id', '')
        if cve_id:
            fkie_ids.add(cve_id)
    
    only_nvd = nvd_ids - fkie_ids
    only_fkie = fkie_ids - nvd_ids
    common = nvd_ids & fkie_ids
    
    print(f"\n  --- CVE ID comparison ---")
    print(f"  Common CVEs:    {len(common)}")
    print(f"  Only in NVD:    {len(only_nvd)}")
    print(f"  Only in fkie:   {len(only_fkie)}")
    
    if only_nvd and len(only_nvd) <= 10:
        print(f"    NVD-only IDs: {sorted(only_nvd)}")
    if only_fkie and len(only_fkie) <= 10:
        print(f"    fkie-only IDs: {sorted(only_fkie)}")
    
    return common, only_nvd, only_fkie

def deep_compare_single_cve(nvd_vulns, fkie_vulns, common_ids):
    """Deep compare the actual field values for a shared CVE."""
    if not common_ids:
        print("  [SKIP] No common CVEs to compare fields.")
        return
    
    # Pick one CVE to compare in detail
    sample_id = sorted(common_ids)[0]
    
    nvd_cve = None
    for v in nvd_vulns:
        cve = v.get('cve', v)
        if cve.get('id') == sample_id:
            nvd_cve = cve
            break
    
    fkie_cve = None
    for v in fkie_vulns:
        cve = v.get('cve', v)
        if cve.get('id') == sample_id:
            fkie_cve = cve
            break
    
    if not nvd_cve or not fkie_cve:
        print(f"  [SKIP] Could not find {sample_id} in both sources.")
        return
    
    print(f"\n  --- Deep comparison for {sample_id} ---")
    
    all_keys = sorted(set(list(nvd_cve.keys()) + list(fkie_cve.keys())))
    
    diffs = []
    for key in all_keys:
        nvd_val = nvd_cve.get(key, '<MISSING>')
        fkie_val = fkie_cve.get(key, '<MISSING>')
        
        if nvd_val == fkie_val:
            status = "✓ SAME"
        elif nvd_val == '<MISSING>':
            status = "→ ONLY in fkie"
            diffs.append(key)
        elif fkie_val == '<MISSING>':
            status = "→ ONLY in NVD"
            diffs.append(key)
        else:
            status = "✗ DIFFERENT"
            diffs.append(key)
        
        # Truncate display
        nvd_display = str(nvd_val)[:80] if nvd_val != '<MISSING>' else '<MISSING>'
        fkie_display = str(fkie_val)[:80] if fkie_val != '<MISSING>' else '<MISSING>'
        
        print(f"    {status:20s} | {key}")
        if status.startswith("✗"):
            print(f"      NVD:  {nvd_display}")
            print(f"      fkie: {fkie_display}")
    
    if not diffs:
        print(f"\n  ✅ All fields are IDENTICAL for {sample_id}!")
    else:
        print(f"\n  ⚠️  {len(diffs)} field(s) differ: {diffs}")


def main():
    base = Path(__file__).resolve().parent.parent / "data" / "CVE"
    nvd_dir = base / "json_from_zip"
    fkie_dir = base / "json"
    
    # Auto-detect all years available in BOTH directories
    import re
    pattern = re.compile(r'nvdcve-2\.0-(\d{4})\.json')
    
    nvd_years = set()
    if nvd_dir.exists():
        for f in nvd_dir.iterdir():
            m = pattern.match(f.name)
            if m:
                nvd_years.add(m.group(1))
    
    fkie_years = set()
    if fkie_dir.exists():
        for f in fkie_dir.iterdir():
            m = pattern.match(f.name)
            if m:
                fkie_years.add(m.group(1))
    
    common_years = sorted(nvd_years & fkie_years)
    
    print(f"[INFO] NVD  years found: {sorted(nvd_years)}")
    print(f"[INFO] fkie years found: {sorted(fkie_years)}")
    print(f"[INFO] Overlapping years to compare: {common_years}")
    
    if not common_years:
        print("\n[ERROR] No overlapping years found between the two directories!")
        print(f"  NVD dir:  {nvd_dir}")
        print(f"  fkie dir: {fkie_dir}")
        return
    
    total_common = 0
    total_only_nvd = 0
    total_only_fkie = 0
    
    for year in common_years:
        nvd_file = nvd_dir / f"nvdcve-2.0-{year}.json"
        fkie_file = fkie_dir / f"nvdcve-2.0-{year}.json"
        
        if not nvd_file.exists():
            print(f"\n[SKIP] NVD file not found: {nvd_file.name}")
            continue
        if not fkie_file.exists():
            print(f"\n[SKIP] fkie file not found: {fkie_file.name}")
            continue
        
        print(f"\nLoading {nvd_file.name} ({nvd_file.stat().st_size / 1024 / 1024:.1f} MB)...")
        with open(nvd_file, 'r') as f:
            nvd_data = json.load(f)
        
        print(f"Loading fkie {fkie_file.name} ({fkie_file.stat().st_size / 1024 / 1024:.1f} MB)...")
        with open(fkie_file, 'r') as f:
            fkie_data = json.load(f)
        
        # 1. Compare top-level keys
        compare_top_level_keys(nvd_data, fkie_data, year)
        
        # 2. Compare CVE counts
        nvd_vulns, fkie_vulns = compare_cve_counts(nvd_data, fkie_data, year)
        
        # 3. Compare single CVE entry structure
        compare_single_cve_structure(nvd_vulns, fkie_vulns, year)
        
        # 4. Compare CVE ID sets
        common, only_nvd, only_fkie = compare_cve_ids(nvd_vulns, fkie_vulns, year)
        total_common += len(common)
        total_only_nvd += len(only_nvd)
        total_only_fkie += len(only_fkie)
        
        # 5. Deep compare a single shared CVE
        deep_compare_single_cve(nvd_vulns, fkie_vulns, common)
    
    print(f"\n{'='*70}")
    print(f"  SUMMARY ACROSS ALL YEARS")
    print(f"{'='*70}")
    print(f"  Total common CVEs:    {total_common}")
    print(f"  Total only in NVD:    {total_only_nvd}")
    print(f"  Total only in fkie:   {total_only_fkie}")

if __name__ == "__main__":
    main()