File size: 11,500 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# data_collection/get_data.py

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
from config import Config
import logging
import requests
import logging
import requests
import re
import os
import shutil
import subprocess
import json
import xml.etree.ElementTree as ET
from pathlib import Path
import pandas as pd

config = Config()
PATHS = config.PATHS
API_ENDPOINTS = config.api_endpoints

DATA_SOURCE_DIR = config.cti_data_dir
SYSTEM_DATA_DIR = config.system_data_dir
SCRAPY_DIR = DATA_SOURCE_DIR / "scrapyCWE" / "cwecrawler"
LOGS_DIR = config.logs_dir

LOGS_DIR.mkdir(parents=True, exist_ok=True)

logging.basicConfig(
    level=logging.INFO,
    filename=LOGS_DIR / "get_data.log",
    format='%(asctime)s - %(levelname)s - %(message)s'
)


def clean_canfollow_json(file_path: Path):
    """Clean up the canfollow.json file generated by Scrapy crawler."""
    logging.info(f"Cleaning up {file_path}...")
    try:
        with open(file_path, 'r', encoding="utf-8") as f:
            data = json.load(f)
        cleaned_data = []
        for item in data:
            cleaned_item = {
                "cwe_id": item.get("cwe_id", "").strip(),
                "cwe_refs": []
            }
            for ref_id in item.get("cwe_refs", []):
                if ref_id:
                    ref_id = ref_id.strip()
                    match = re.search(r'\d+', ref_id)
                    if match:
                        cwe_num = match.group(0)
                        cleaned_item["cwe_refs"].append(f"CWE-{cwe_num}")
            cleaned_data.append(cleaned_item)
        with open(file_path, 'w', encoding="utf-8") as f:
            json.dump(cleaned_data, f, indent=2)
        logging.info(f"Successfully cleaned {file_path}")
        return True
    except Exception as e:
        logging.error(f"Error cleaning canfollow.json: {e}")
        return False


def generate_cwe_capec_mitre_mapping(cwe_file: Path, capec_file: Path, output_file: Path):
    """Generate mapping between CWE, CAPEC, and MITRE ATT&CK techniques."""
    logging.info("Generating CWE-CAPEC-MITRE mapping...")
    try:
        mapping = {}
        # Parse CWE XML
        cwe_tree = ET.parse(cwe_file)
        cwe_root = cwe_tree.getroot()
        ns = '{' + cwe_root.tag.split('}')[0].strip('{') + '}' if '}' in cwe_root.tag else ''
        for weakness in cwe_root.findall(f'.//{ns}Weakness'):
            cwe_id = f"CWE-{weakness.get('ID')}"
            capec_ids = [
                f"CAPEC-{pattern.get('CAPEC_ID')}"
                for pattern in weakness.findall(f'.//{ns}Related_Attack_Patterns/{ns}Related_Attack_Pattern')
                if pattern.get('CAPEC_ID')
            ]
            mapping[cwe_id] = {"capecs": capec_ids, "mitre_techniques": []}

        # Parse CAPEC XML
        capec_tree = ET.parse(capec_file)
        capec_root = capec_tree.getroot()
        ns = '{' + capec_root.tag.split('}')[0].strip('{') + '}' if '}' in capec_root.tag else ''
        capec_to_mitre = {}
        for attack_pattern in capec_root.findall(f'.//{ns}Attack_Pattern'):
            capec_id = f"CAPEC-{attack_pattern.get('ID')}"
            mitre_techniques = [
                f"T{mapping_elem.find(f'.//{ns}Entry_ID').text.strip()}"
                for mapping_elem in attack_pattern.findall(f'.//{ns}Taxonomy_Mappings/{ns}Taxonomy_Mapping')
                if mapping_elem.get('Taxonomy_Name') == 'ATTACK' and mapping_elem.find(f'.//{ns}Entry_ID') is not None
            ]
            capec_to_mitre[capec_id] = mitre_techniques

        # Connect CWE to MITRE
        for cwe_id, cwe_data in mapping.items():
            for capec_id in cwe_data["capecs"]:
                cwe_data["mitre_techniques"].extend(capec_to_mitre.get(capec_id, []))
            cwe_data["mitre_techniques"] = list(set(cwe_data["mitre_techniques"]))

        # Fetch MITRE ATT&CK data
        try:
            response = requests.get(API_ENDPOINTS["mitre_attack"])
            if response.status_code == 200:
                mitre_data = response.json()
                for obj in mitre_data.get("objects", []):
                    if obj["type"] == "attack-pattern":
                        technique_id = obj["external_references"][0].get("external_id", "")
                        if technique_id.startswith("T"):
                            for cwe_id, cwe_data in mapping.items():
                                if technique_id in cwe_data["mitre_techniques"]:
                                    cwe_data["mitre_description"] = obj.get("description", "")
        except Exception as e:
            logging.warning(f"Failed to fetch MITRE ATT&CK data: {e}")

        with open(output_file, 'w', encoding="utf-8") as f:
            json.dump(mapping, f, indent=2)
        logging.info(f"Mapping saved to {output_file}")
    except Exception as e:
        logging.error(f"Error generating mapping: {e}")


def get_data_file():
    """Download and prepare CTI data files."""
    DATA_SOURCE_DIR.mkdir(parents=True, exist_ok=True)

    # Download CWE data
    cwe_xml_path = DATA_SOURCE_DIR / 'cwe_latest.xml'
    try:
        cwe_url = "https://cwe.mitre.org/data/xml/cwec_latest.xml.zip"
        logging.info(f"Downloading CWE from {cwe_url}")
        response = requests.get(cwe_url, stream=True)
        zip_path = DATA_SOURCE_DIR / 'cwe_latest.xml.zip'
        with open(zip_path, 'wb') as f:
            for chunk in response:
                f.write(chunk)
        shutil.unpack_archive(zip_path, DATA_SOURCE_DIR)
        zip_path.unlink()
        cwe_files = [f for f in DATA_SOURCE_DIR.glob("cwec_*.xml")]
        if cwe_files:
            shutil.move(cwe_files[0], cwe_xml_path)
        logging.info("Downloaded and extracted CWE XML")
    except Exception as e:
        logging.error(f"Error downloading CWE data: {e}")

    # Download CAPEC data
    capec_xml_path = DATA_SOURCE_DIR / 'capec_latest.xml'
    try:
        capec_url = "https://capec.mitre.org/data/xml/capec_latest.xml"
        logging.info(f"Downloading CAPEC from {capec_url}")
        response = requests.get(capec_url, stream=True)
        with open(capec_xml_path, 'wb') as f:
            for chunk in response:
                f.write(chunk)
        logging.info("Downloaded CAPEC XML")
    except Exception as e:
        logging.error(f"Error downloading CAPEC data: {e}")

    # Download ExploitDB data
    exploit_db_path = DATA_SOURCE_DIR / 'files_exploits.csv'
    try:
        logging.info("Downloading ExploitDB data...")
        response = requests.get(
            'https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv?ref_type=heads',
            stream=True
        )
        with open(exploit_db_path, 'wb') as f:
            for chunk in response:
                f.write(chunk)
        logging.info("Downloaded ExploitDB CSV")
    except Exception as e:
        logging.error(f"Error downloading ExploitDB data: {e}")

    # Download MITRE ATT&CK Excel files (tactics and techniques)
    try:
        attk_r = requests.get('https://attack.mitre.org/resources/attack-data-and-tools/')
        # Download tactics Excel
        tactics_links = re.findall(r'href="([^"]*enterprise-attack-v[0-9.]*-tactics\.xlsx)"', attk_r.text)
        if tactics_links:
            url_filename = f"https://attack.mitre.org{tactics_links[0]}"
            filename = url_filename.split('/')[-1]
            logging.info(f"Downloading: {filename}")
            r_file = requests.get(url_filename, stream=True)
            out_path = DATA_SOURCE_DIR / filename
            with open(out_path, 'wb') as f:
                for chunk in r_file.iter_content(chunk_size=8192):
                    f.write(chunk)
            logging.info(f"Downloaded MITRE ATT&CK tactics Excel: {out_path}")
        # Download techniques Excel
        techniques_links = re.findall(r'href="([^"]*enterprise-attack-v[0-9.]*-techniques\.xlsx)"', attk_r.text)
        if techniques_links:
            url_filename = f"https://attack.mitre.org{techniques_links[0]}"
            filename = url_filename.split('/')[-1]
            logging.info(f"Downloading: {filename}")
            r_file = requests.get(url_filename, stream=True)
            out_path = DATA_SOURCE_DIR / filename
            with open(out_path, 'wb') as f:
                for chunk in r_file.iter_content(chunk_size=8192):
                    f.write(chunk)
            logging.info(f"Downloaded MITRE ATT&CK techniques Excel: {out_path}")
    except Exception as e:
        logging.error(f"Error downloading MITRE ATT&CK Excel files: {e}")

    # Generate CWE-CAPEC-MITRE mapping
    if cwe_xml_path.exists() and capec_xml_path.exists():
        mapping_file = DATA_SOURCE_DIR / 'cwe_capec_mitre_mapping.json'
        generate_cwe_capec_mitre_mapping(cwe_xml_path, capec_xml_path, mapping_file)

    # Extract CWEs from system data
    cwe_ids = set()
    for file_name in ['ICS.json', 'ES.json']:
        file_path = SYSTEM_DATA_DIR / file_name
        if file_path.exists():
            try:
                with open(file_path, 'r', encoding="utf-8") as f:
                    data = json.load(f)
                for asset in data.get("Assets", []):
                    for component in asset.get("components", []):
                        for vuln in component.get("vulnerabilities", []):
                            cwe_id = vuln.get("cwe_id")
                            if isinstance(cwe_id, str) and cwe_id.startswith("CWE-"):
                                cwe_ids.add(cwe_id.replace("CWE-", ""))
                            elif isinstance(cwe_id, list):
                                for single_cwe in cwe_id:
                                    if single_cwe.startswith("CWE-"):
                                        cwe_ids.add(single_cwe.replace("CWE-", ""))
                logging.info(f"Found {len(cwe_ids)} CWEs in {file_name}")
            except Exception as e:
                logging.error(f"Error processing {file_name}: {e}")

    # Generate CWE URLs for Scrapy
    if cwe_ids:
        SCRAPY_DIR.mkdir(parents=True, exist_ok=True)
        websites_file = SCRAPY_DIR / "websites.txt"
        with open(websites_file, "w", encoding="utf-8") as f:
            for cwe_num in cwe_ids:
                f.write(f"https://cwe.mitre.org/data/definitions/{cwe_num}.html\n")
        logging.info(f"Wrote {len(cwe_ids)} CWE URLs to {websites_file}")

        # Run Scrapy spider
        output_file = SCRAPY_DIR / "canfollow.json"
        try:
            original_cwd = os.getcwd()
            os.chdir(SCRAPY_DIR)
            if output_file.exists():
                output_file.unlink()
            result = subprocess.run(
                'scrapy crawl cwe_spider -o canfollow.json',
                shell=True,
                capture_output=True,
                text=True
            )
            if result.returncode == 0 and output_file.exists():
                clean_canfollow_json(output_file)
                shutil.copy(output_file, DATA_SOURCE_DIR / 'canfollow.json')
                logging.info(f"Copied cleaned canfollow.json to {DATA_SOURCE_DIR}")
            else:
                logging.error(f"Scrapy spider failed: {result.stderr}")
        except Exception as e:
            logging.error(f"Failed to run Scrapy spider: {e}")
        finally:
            os.chdir(original_cwd)
    else:
        logging.warning("No CWEs found in system data files")


if __name__ == '__main__':
    get_data_file()