| import json
|
| import logging
|
| from pathlib import Path
|
| from typing import Dict, List, Set, Tuple
|
|
|
| logger = logging.getLogger(__name__)
|
|
|
|
|
| class CVEtoCWEtoTTPMapper:
|
| """Maps CVEs to TTPs through CWE relationships.
|
|
|
| This implements the direct mapping approach:
|
| CVE -> CWE -> CAPEC -> TTP
|
|
|
| Uses the existing CWE-CAPEC-MITRE mapping generated by
|
| generate_cwe_capec_mitre_mapping() in get_data.py
|
| """
|
|
|
| def __init__(self, cwe_capec_mitre_mapping_path: Path):
|
| """Initialize the mapper with existing CWE-CAPEC-MITRE mappings.
|
|
|
| Args:
|
| cwe_capec_mitre_mapping_path: Path to the JSON file containing CWE-CAPEC-MITRE mappings
|
| """
|
| self.cwe_capec_mitre_mapping_path = cwe_capec_mitre_mapping_path
|
| self.cwe_to_ttp_mapping = {}
|
| self._load_mappings()
|
|
|
| def _load_mappings(self):
|
| """Load the CWE-CAPEC-MITRE mapping data."""
|
| try:
|
| with open(self.cwe_capec_mitre_mapping_path, 'r', encoding='utf-8') as f:
|
| self.cwe_to_ttp_mapping = json.load(f)
|
| logger.info(f"Loaded {len(self.cwe_to_ttp_mapping)} CWE-to-TTP mappings")
|
| except Exception as e:
|
| logger.error(f"Failed to load CWE-CAPEC-MITRE mappings: {e}")
|
| self.cwe_to_ttp_mapping = {}
|
|
|
| def normalize_cwe_id(self, cwe_id: str) -> str:
|
| """Normalize CWE ID to standard format (CWE-XXX)."""
|
| if not cwe_id:
|
| return ""
|
|
|
| cwe_str = str(cwe_id).strip()
|
|
|
|
|
| if cwe_str.upper().startswith("CWE-"):
|
| return cwe_str.upper()
|
|
|
|
|
| if cwe_str.isdigit():
|
| return f"CWE-{cwe_str}"
|
|
|
|
|
| if "cwe" in cwe_str.lower():
|
| import re
|
| match = re.search(r'cwe[- ]?(\d+)', cwe_str, re.IGNORECASE)
|
| if match:
|
| return f"CWE-{match.group(1)}"
|
|
|
| return ""
|
|
|
| def extract_cwes_from_cve_data(self, cve_data: Dict) -> List[str]:
|
| """Extract CWE IDs from various CVE data formats.
|
|
|
| Handles multiple formats:
|
| - Direct: {"cwe_ids": ["CWE-79", "CWE-80"]}
|
| - NVD v1: {"problemtype": {"problemtype_data": [{"description": [{"value": "CWE-79"}]}]}}
|
| - NVD v2: {"weaknesses": [{"description": [{"value": "CWE-79"}]}]}
|
| """
|
| cwe_ids = set()
|
|
|
|
|
| if "cwe_ids" in cve_data:
|
| cwes = cve_data["cwe_ids"]
|
| if isinstance(cwes, str):
|
| cwes = [cwes]
|
| for cwe in cwes:
|
| normalized = self.normalize_cwe_id(cwe)
|
| if normalized:
|
| cwe_ids.add(normalized)
|
|
|
|
|
| if "weaknesses" in cve_data:
|
| for weakness in cve_data["weaknesses"]:
|
| if isinstance(weakness, dict) and "description" in weakness:
|
| for desc in weakness["description"]:
|
| if isinstance(desc, dict) and "value" in desc:
|
| normalized = self.normalize_cwe_id(desc["value"])
|
| if normalized:
|
| cwe_ids.add(normalized)
|
|
|
|
|
| if "problemtype" in cve_data:
|
| problemtype = cve_data["problemtype"]
|
| if isinstance(problemtype, dict) and "problemtype_data" in problemtype:
|
| for problem in problemtype["problemtype_data"]:
|
| if isinstance(problem, dict) and "description" in problem:
|
| for desc in problem["description"]:
|
| if isinstance(desc, dict) and "value" in desc:
|
| normalized = self.normalize_cwe_id(desc["value"])
|
| if normalized:
|
| cwe_ids.add(normalized)
|
|
|
| return list(cwe_ids)
|
|
|
| def get_ttps_from_cwe(self, cwe_id: str) -> List[str]:
|
| """Get TTPs associated with a CWE ID.
|
|
|
| Args:
|
| cwe_id: CWE identifier (e.g., "CWE-79", "CWE-119")
|
|
|
| Returns:
|
| List of TTP identifiers (e.g., ["T1203", "T1059"])
|
| """
|
| normalized_cwe = self.normalize_cwe_id(cwe_id)
|
|
|
| if normalized_cwe in self.cwe_to_ttp_mapping:
|
| return self.cwe_to_ttp_mapping[normalized_cwe].get("mitre_techniques", [])
|
| return []
|
|
|
| def get_capecs_from_cwe(self, cwe_id: str) -> List[str]:
|
| """Get CAPEC patterns associated with a CWE ID.
|
|
|
| Args:
|
| cwe_id: CWE identifier
|
|
|
| Returns:
|
| List of CAPEC identifiers
|
| """
|
| normalized_cwe = self.normalize_cwe_id(cwe_id)
|
|
|
| if normalized_cwe in self.cwe_to_ttp_mapping:
|
| return self.cwe_to_ttp_mapping[normalized_cwe].get("capecs", [])
|
| return []
|
|
|
| def map_cve_to_ttps(self, cve_data: Dict) -> Tuple[List[str], Dict]:
|
| """Map a CVE to TTPs through its CWE associations.
|
|
|
| Args:
|
| cve_data: Dictionary containing CVE information
|
|
|
| Returns:
|
| Tuple of (list of TTP IDs, mapping details dictionary)
|
| """
|
| ttps = set()
|
| mapping_details = {
|
| "method": "CWE-to-CAPEC-to-TTP",
|
| "mappings": []
|
| }
|
|
|
|
|
| cwe_ids = self.extract_cwes_from_cve_data(cve_data)
|
|
|
| if not cwe_ids:
|
| logger.debug(f"No CWEs found for CVE {cve_data.get('id', 'unknown')}")
|
|
|
| for cwe_id in cwe_ids:
|
| ttp_list = self.get_ttps_from_cwe(cwe_id)
|
| capec_list = self.get_capecs_from_cwe(cwe_id)
|
|
|
| if ttp_list:
|
| ttps.update(ttp_list)
|
| mapping_details["mappings"].append({
|
| "cwe": cwe_id,
|
| "capecs": capec_list,
|
| "ttps": ttp_list
|
| })
|
| logger.debug(f"CVE {cve_data.get('id', 'unknown')} -> {cwe_id} -> {ttp_list}")
|
|
|
| return list(ttps), mapping_details
|
|
|
| def get_mapping_statistics(self) -> Dict:
|
| """Get statistics about the loaded mappings."""
|
| total_cwes = len(self.cwe_to_ttp_mapping)
|
| cwes_with_ttps = len([c for c in self.cwe_to_ttp_mapping.values()
|
| if c.get("mitre_techniques")])
|
| cwes_with_capecs = len([c for c in self.cwe_to_ttp_mapping.values()
|
| if c.get("capecs")])
|
|
|
| all_ttps = set()
|
| all_capecs = set()
|
| for cwe_data in self.cwe_to_ttp_mapping.values():
|
| all_ttps.update(cwe_data.get("mitre_techniques", []))
|
| all_capecs.update(cwe_data.get("capecs", []))
|
|
|
| return {
|
| "total_cwes": total_cwes,
|
| "cwes_with_ttps": cwes_with_ttps,
|
| "cwes_with_capecs": cwes_with_capecs,
|
| "unique_ttps": len(all_ttps),
|
| "unique_capecs": len(all_capecs)
|
| } |