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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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#!/usr/bin/env python3
"""

Knowledge Graph Builder Without Neo4j



This script builds a comprehensive knowledge graph from processed CVE data and CPE extraction results

without requiring Neo4j. It creates a structured representation that can be used for RAG systems

and other graph-based analysis.



Usage:

    python kg_builder_without_neo4j.py

"""

import json
import sys
from datetime import datetime
from typing import Dict, List, Any, Set
from pathlib import Path
from collections import defaultdict, Counter
import logging

# Add the project root to Python path for imports
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from config import Config

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class KnowledgeGraphBuilder:
    def __init__(self):
        self.config = Config()
        self.knowledge_base_dir = self.config.knowledge_base_dir
        self.output_dir = self.knowledge_base_dir / 'knowledge_graph'
        self.output_dir.mkdir(exist_ok=True)
        
        # Graph structure
        self.nodes = {
            'cves': {},
            'products': {},
            'vendors': {},
            'cwes': {},
            'capecs': {},
            'mitre_techniques': {},
            'mitre_tactics': {}
        }
        
        self.relationships = {
            'cve_product': [],
            'cve_cwe': [],
            'cve_capec': [],
            'cve_mitre_technique': [],
            'cve_mitre_tactic': [],
            'product_vendor': [],
            'product_version': []
        }
        
        self.statistics = {}
    
    def load_all_cve_data(self) -> List[Dict[str, Any]]:
        """Load all CVE data from year-based files"""
        all_cves = []
        
        # Find all year-based CVE files
        cve_files = list(self.knowledge_base_dir.glob("enhanced_documents_cve_*.json"))
        cve_files.sort()
        
        logger.info(f"Found {len(cve_files)} year-based CVE files")
        
        for file in cve_files:
            logger.info(f"Loading CVEs from {file.name}...")
            try:
                with open(file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # Filter for CVE documents only
                cve_docs = [doc for doc in data if doc.get('document_type') == 'CVE']
                all_cves.extend(cve_docs)
                logger.info(f"  Loaded {len(cve_docs)} CVEs from {file.name}")
                
            except Exception as e:
                logger.error(f"Error loading {file.name}: {e}")
                continue
        
        logger.info(f"Total CVEs loaded: {len(all_cves)}")
        return all_cves
    
    def load_cpe_data(self) -> Dict[str, Any]:
        """Load CPE parsing results"""
        cpe_file = self.knowledge_base_dir / 'cpe_parsing_results_full.json'
        
        if not cpe_file.exists():
            logger.warning(f"CPE file not found: {cpe_file}")
            return {}
        
        try:
            with open(cpe_file, 'r', encoding='utf-8') as f:
                cpe_data = json.load(f)
            logger.info(f"Loaded CPE data for {len(cpe_data.get('products', {}))} products")
            return cpe_data
        except Exception as e:
            logger.error(f"Error loading CPE data: {e}")
            return {}
    
    def build_cve_nodes(self, cve_data: List[Dict[str, Any]]):
        """Build CVE nodes from CVE data"""
        logger.info("Building CVE nodes...")
        
        for cve in cve_data:
            cve_id = cve['id']
            
            # Create CVE node
            cve_node = {
                'id': cve_id,
                'title': cve.get('title', ''),
                'description': cve.get('content', ''),
                'source': cve.get('source', ''),
                'published_date': cve.get('published_date', ''),
                'last_modified_date': cve.get('last_modified_date', ''),
                'cvss_v3': cve.get('cvss_v3', {}),
                'cvss_v2': cve.get('cvss_v2', {}),
                'affected_products': cve.get('affected_products', []),
                'is_in_kev': cve.get('is_in_kev', False),
                'tags': cve.get('tags', []),
                'vulnerability_count': 1  # Each CVE represents one vulnerability
            }
            
            self.nodes['cves'][cve_id] = cve_node
            
            # Create relationships
            self._create_cve_relationships(cve_id, cve)
    
    def _create_cve_relationships(self, cve_id: str, cve: Dict[str, Any]):
        """Create relationships for a CVE"""
        # CVE -> Product relationships
        affected_products = cve.get('affected_products', [])
        for product_name in affected_products:
            self.relationships['cve_product'].append({
                'cve_id': cve_id,
                'product_name': product_name,
                'relationship_type': 'AFFECTS'
            })
        
        # CVE -> CWE relationships
        cwe_refs = cve.get('cwe_refs', [])
        for cwe_id in cwe_refs:
            self.relationships['cve_cwe'].append({
                'cve_id': cve_id,
                'cwe_id': cwe_id,
                'relationship_type': 'HAS_WEAKNESS'
            })
        
        # CVE -> CAPEC relationships
        capec_entries = cve.get('capec_entries', [])
        for capec_id in capec_entries:
            self.relationships['cve_capec'].append({
                'cve_id': cve_id,
                'capec_id': capec_id,
                'relationship_type': 'USES_PATTERN'
            })
        
        # CVE -> MITRE Technique relationships
        mitre_techniques = cve.get('mitre_techniques', [])
        for technique_id in mitre_techniques:
            self.relationships['cve_mitre_technique'].append({
                'cve_id': cve_id,
                'technique_id': technique_id,
                'relationship_type': 'IMPLEMENTS_TECHNIQUE'
            })
        
        # CVE -> MITRE Tactic relationships
        mitre_tactics = cve.get('mitre_tactics', [])
        for tactic_id in mitre_tactics:
            self.relationships['cve_mitre_tactic'].append({
                'cve_id': cve_id,
                'tactic_id': tactic_id,
                'relationship_type': 'MAPPED_TO_TACTIC'
            })
    
    def build_cwe_nodes(self):
        """Build CWE nodes from CVE relationships"""
        logger.info("Building CWE nodes...")
        
        cwe_counter = Counter()
        for rel in self.relationships['cve_cwe']:
            cwe_counter[rel['cwe_id']] += 1
        
        for cwe_id, count in cwe_counter.items():
            self.nodes['cwes'][cwe_id] = {
                'id': cwe_id,
                'name': f"Common Weakness Enumeration {cwe_id}",
                'vulnerability_count': count,
                'node_type': 'CWE'
            }
    
    def build_capec_nodes(self):
        """Build CAPEC nodes from CVE relationships"""
        logger.info("Building CAPEC nodes...")
        
        capec_counter = Counter()
        for rel in self.relationships['cve_capec']:
            capec_counter[rel['capec_id']] += 1
        
        for capec_id, count in capec_counter.items():
            self.nodes['capecs'][capec_id] = {
                'id': capec_id,
                'name': f"Common Attack Pattern {capec_id}",
                'vulnerability_count': count,
                'node_type': 'CAPEC'
            }
    
    def build_mitre_nodes(self):
        """Build MITRE ATT&CK nodes from CVE relationships"""
        logger.info("Building MITRE ATT&CK nodes...")
        
        # Techniques
        technique_counter = Counter()
        for rel in self.relationships['cve_mitre_technique']:
            technique_counter[rel['technique_id']] += 1
        
        for technique_id, count in technique_counter.items():
            self.nodes['mitre_techniques'][technique_id] = {
                'id': technique_id,
                'name': f"MITRE ATT&CK Technique {technique_id}",
                'vulnerability_count': count,
                'node_type': 'MITRE_TECHNIQUE'
            }
        
        # Tactics
        tactic_counter = Counter()
        for rel in self.relationships['cve_mitre_tactic']:
            tactic_counter[rel['tactic_id']] += 1
        
        for tactic_id, count in tactic_counter.items():
            self.nodes['mitre_tactics'][tactic_id] = {
                'id': tactic_id,
                'name': f"MITRE ATT&CK Tactic {tactic_id}",
                'vulnerability_count': count,
                'node_type': 'MITRE_TACTIC'
            }
    
    def build_product_vendor_nodes(self, cpe_data: Dict[str, Any]):
        """Build Product and Vendor nodes from CPE data"""
        logger.info("Building Product and Vendor nodes...")
        
        # Build vendor nodes first
        vendor_counter = Counter()
        for product_key, product_data in cpe_data.get('products', {}).items():
            vendor_name = product_data.get('vendor', '')
            if vendor_name:
                vendor_counter[vendor_name] += product_data.get('vulnerability_count', 0)
        
        for vendor_name, total_vulns in vendor_counter.items():
            self.nodes['vendors'][vendor_name] = {
                'name': vendor_name,
                'display_name': vendor_name.title(),
                'vulnerability_count': total_vulns,
                'product_count': 0,  # Will be updated below
                'node_type': 'VENDOR'
            }
        
        # Build product nodes
        for product_key, product_data in cpe_data.get('products', {}).items():
            vendor_name = product_data.get('vendor', '')
            
            # Create product node
            product_node = {
                'name': product_data.get('product', ''),
                'vendor': vendor_name,
                'display_name': product_data.get('display_name', ''),
                'category': product_data.get('category', ''),
                'family': product_data.get('family', ''),
                'criticality_score': product_data.get('criticality_score', 0.0),
                'aliases': product_data.get('aliases', []),
                'vulnerability_count': product_data.get('vulnerability_count', 0),
                'versions': list(product_data.get('versions', {}).keys()),
                'node_type': 'PRODUCT'
            }
            
            self.nodes['products'][product_key] = product_node
            
            # Create product-vendor relationship
            if vendor_name:
                self.relationships['product_vendor'].append({
                    'product_key': product_key,
                    'vendor_name': vendor_name,
                    'relationship_type': 'MANUFACTURED_BY'
                })
                
                # Update vendor product count
                if vendor_name in self.nodes['vendors']:
                    self.nodes['vendors'][vendor_name]['product_count'] += 1
    
    def calculate_statistics(self):
        """Calculate comprehensive statistics about the knowledge graph"""
        logger.info("Calculating knowledge graph statistics...")
        
        stats = {
            'build_timestamp': datetime.now().isoformat(),
            'node_counts': {
                'cves': len(self.nodes['cves']),
                'products': len(self.nodes['products']),
                'vendors': len(self.nodes['vendors']),
                'cwes': len(self.nodes['cwes']),
                'capecs': len(self.nodes['capecs']),
                'mitre_techniques': len(self.nodes['mitre_techniques']),
                'mitre_tactics': len(self.nodes['mitre_tactics'])
            },
            'relationship_counts': {
                'cve_product': len(self.relationships['cve_product']),
                'cve_cwe': len(self.relationships['cve_cwe']),
                'cve_capec': len(self.relationships['cve_capec']),
                'cve_mitre_technique': len(self.relationships['cve_mitre_technique']),
                'cve_mitre_tactic': len(self.relationships['cve_mitre_tactic']),
                'product_vendor': len(self.relationships['product_vendor'])
            },
            'cve_statistics': {
                'total_cves': len(self.nodes['cves']),
                'cves_in_kev': sum(1 for cve in self.nodes['cves'].values() if cve.get('is_in_kev', False)),
                'cves_with_cvss_v3': sum(1 for cve in self.nodes['cves'].values() if cve.get('cvss_v3', {}).get('base_score')),
                'cves_with_cvss_v2': sum(1 for cve in self.nodes['cves'].values() if cve.get('cvss_v2', {}).get('base_score'))
            },
            'severity_distribution': self._calculate_severity_distribution(),
            'top_vendors': self._get_top_vendors(10),
            'top_products': self._get_top_products(10),
            'top_cwes': self._get_top_cwes(10),
            'top_capecs': self._get_top_capecs(10)
        }
        
        self.statistics = stats
        return stats
    
    def _calculate_severity_distribution(self) -> Dict[str, int]:
        """Calculate CVSS severity distribution"""
        severity_counts = Counter()
        for cve in self.nodes['cves'].values():
            severity = cve.get('cvss_v3', {}).get('base_severity', 'UNKNOWN')
            severity_counts[severity] += 1
        return dict(severity_counts)
    
    def _get_top_vendors(self, limit: int) -> List[Dict[str, Any]]:
        """Get top vendors by vulnerability count"""
        vendors = list(self.nodes['vendors'].values())
        vendors.sort(key=lambda x: x.get('vulnerability_count', 0), reverse=True)
        return vendors[:limit]
    
    def _get_top_products(self, limit: int) -> List[Dict[str, Any]]:
        """Get top products by vulnerability count"""
        products = list(self.nodes['products'].values())
        products.sort(key=lambda x: x.get('vulnerability_count', 0), reverse=True)
        return products[:limit]
    
    def _get_top_cwes(self, limit: int) -> List[Dict[str, Any]]:
        """Get top CWEs by vulnerability count"""
        cwes = list(self.nodes['cwes'].values())
        cwes.sort(key=lambda x: x.get('vulnerability_count', 0), reverse=True)
        return cwes[:limit]
    
    def _get_top_capecs(self, limit: int) -> List[Dict[str, Any]]:
        """Get top CAPECs by vulnerability count"""
        capecs = list(self.nodes['capecs'].values())
        capecs.sort(key=lambda x: x.get('vulnerability_count', 0), reverse=True)
        return capecs[:limit]
    
    def save_knowledge_graph(self):
        """Save the complete knowledge graph to files"""
        logger.info("Saving knowledge graph...")
        
        # Save nodes
        for node_type, nodes in self.nodes.items():
            output_file = self.output_dir / f"{node_type}_nodes.json"
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(nodes, f, indent=2, ensure_ascii=False)
            logger.info(f"Saved {len(nodes)} {node_type} nodes to {output_file}")
        
        # Save relationships
        for rel_type, relationships in self.relationships.items():
            output_file = self.output_dir / f"{rel_type}_relationships.json"
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(relationships, f, indent=2, ensure_ascii=False)
            logger.info(f"Saved {len(relationships)} {rel_type} relationships to {output_file}")
        
        # Save statistics
        stats_file = self.output_dir / "knowledge_graph_statistics.json"
        with open(stats_file, 'w', encoding='utf-8') as f:
            json.dump(self.statistics, f, indent=2, ensure_ascii=False)
        logger.info(f"Saved statistics to {stats_file}")
        
        # Save complete graph structure
        complete_graph = {
            'metadata': {
                'build_timestamp': datetime.now().isoformat(),
                'version': '1.0',
                'description': 'CVE Knowledge Graph built without Neo4j'
            },
            'nodes': self.nodes,
            'relationships': self.relationships,
            'statistics': self.statistics
        }
        
        graph_file = self.output_dir / "complete_knowledge_graph.json"
        with open(graph_file, 'w', encoding='utf-8') as f:
            json.dump(complete_graph, f, indent=2, ensure_ascii=False)
        logger.info(f"Saved complete knowledge graph to {graph_file}")
    
    def print_statistics(self):
        """Print a summary of the knowledge graph statistics"""
        if not self.statistics:
            self.calculate_statistics()
        
        stats = self.statistics
        
        print("\n📊 Knowledge Graph Statistics:")
        print("=" * 60)
        print(f"📈 Nodes:")
        for node_type, count in stats['node_counts'].items():
            print(f"  {node_type.upper()}: {count:,}")
        
        print(f"\n🔗 Relationships:")
        for rel_type, count in stats['relationship_counts'].items():
            print(f"  {rel_type.upper()}: {count:,}")
        
        print(f"\n🛡️ CVE Statistics:")
        cve_stats = stats['cve_statistics']
        print(f"  Total CVEs: {cve_stats['total_cves']:,}")
        print(f"  In KEV: {cve_stats['cves_in_kev']:,}")
        print(f"  With CVSS v3: {cve_stats['cves_with_cvss_v3']:,}")
        print(f"  With CVSS v2: {cve_stats['cves_with_cvss_v2']:,}")
        
        print(f"\n⚠️ Severity Distribution:")
        for severity, count in stats['severity_distribution'].items():
            print(f"  {severity}: {count:,}")
        
        print(f"\n🏭 Top 5 Vendors:")
        for i, vendor in enumerate(stats['top_vendors'][:5], 1):
            print(f"  {i}. {vendor['display_name']}: {vendor['vulnerability_count']:,} vulns")
        
        print(f"\n📦 Top 5 Products:")
        for i, product in enumerate(stats['top_products'][:5], 1):
            print(f"  {i}. {product['display_name']}: {product['vulnerability_count']:,} vulns")
    
    def build_knowledge_graph(self):
        """Build the complete knowledge graph"""
        logger.info("Starting knowledge graph construction...")
        
        # Load data
        cve_data = self.load_all_cve_data()
        cpe_data = self.load_cpe_data()
        
        if not cve_data:
            logger.error("No CVE data found! Please run the CVE processor first.")
            return
        
        # Build nodes and relationships
        self.build_cve_nodes(cve_data)
        self.build_cwe_nodes()
        self.build_capec_nodes()
        self.build_mitre_nodes()
        self.build_product_vendor_nodes(cpe_data)
        
        # Calculate statistics
        self.calculate_statistics()
        
        # Save everything
        self.save_knowledge_graph()
        
        # Print summary
        self.print_statistics()
        
        logger.info("✅ Knowledge graph construction complete!")
        logger.info(f"📁 Output directory: {self.output_dir}")

def main():
    builder = KnowledgeGraphBuilder()
    builder.build_knowledge_graph()

if __name__ == "__main__":
    main()