File size: 7,436 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 | 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()
# Handle CWE-XXX format
if cwe_str.upper().startswith("CWE-"):
return cwe_str.upper()
# Handle just the number
if cwe_str.isdigit():
return f"CWE-{cwe_str}"
# Handle NVD format like "CWE-79" in various cases
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()
# Check direct cwe_ids field
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)
# Check NVD v2 weaknesses format
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)
# Check NVD v1 problemtype format
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": []
}
# Extract CWE IDs from CVE data
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)
} |