-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathscraper.py
312 lines (277 loc) · 11.7 KB
/
scraper.py
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
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
import os
import requests
import zipfile
from bs4 import BeautifulSoup
import platform
from circuitbreaker import circuit
import json
import xmltodict
import xml.etree.ElementTree as ET
import fnmatch
import subprocess
MAX_RETRIES = 5
def download_files_cve(import_path):
url = 'https://nvd.nist.gov/vuln/data-feeds'
root = 'https://nvd.nist.gov/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
all_hrfs = soup.find_all('a')
all_links = [
link.get('href') for link in all_hrfs
]
zip_files = [
dl for dl in all_links if dl and '.json.zip' in dl and 'nvdcve' in dl
]
download_folder = import_path + "nist/cve/"
extract_dir = import_path + "nist/cve/"
# Download and Unzip the files
print('\nUpdating the Database with the latest CVE Files...')
for zip_file in zip_files:
print("Zip file: ", zip_file)
full_url = root + zip_file
zip_file_name = os.path.basename(zip_file)
download_file_to_path(full_url, download_folder, zip_file_name)
unzip_files_to_directory(download_folder, extract_dir, zip_file_name)
transform_xml_files_to_json(extract_dir)
transform_big_json_files_to_multiple_json_files(extract_dir, 'cve','CVE_Items')
def download_files_cpe(import_path):
url = 'https://nvd.nist.gov/vuln/data-feeds'
root = 'https://nvd.nist.gov/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
all_hrfs = soup.find_all('a')
all_links = [
link.get('href') for link in all_hrfs
]
zip_files = [
dl for dl in all_links if dl and '.json.zip' in dl and 'nvdcpematch' in dl
]
download_folder = import_path + "nist/cpe/"
extract_dir = import_path + "nist/cpe/"
#
# Download and Unzip the files
print('\nUpdating the Database with the latest CVE Files...')
for zip_file in zip_files:
full_url = root + zip_file
zip_file_name = os.path.basename(zip_file)
# 5 attempts to download and unzip the file correctly
download_file_to_path(full_url, download_folder, zip_file_name)
unzip_files_to_directory(download_folder, extract_dir, zip_file_name)
#
transform_xml_files_to_json(extract_dir)
transform_big_json_files_to_multiple_json_files(extract_dir, 'cpe','matches')
def download_files_cwe(import_path):
url = 'https://cwe.mitre.org/data/archive.html'
root = 'https://cwe.mitre.org/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
all_hrfs = soup.find_all('a')
all_links = [
link.get('href') for link in all_hrfs
]
zip_files = [
dl for dl in all_links if dl and '.xml.zip' in dl
]
zip_file = zip_files[0]
download_folder = import_path + "mitre_cwe/"
extract_dir = import_path + "mitre_cwe/"
# Download and Unzip the files
print('\nUpdating the Database with the latest CWE Files...')
full_url = root + zip_file
zip_file_name = os.path.basename(zip_file)
# 5 attempts to download and unzip the file correctly
download_file_to_path(full_url, download_folder, zip_file_name)
unzip_files_to_directory(download_folder, extract_dir, zip_file_name)
transform_xml_files_to_json(extract_dir)
replace_unwanted_string_cwe(extract_dir)
transform_big_json_files_to_multiple_json_files(extract_dir, 'cwe_reference','Weakness_Catalog.External_References.External_Reference')
transform_big_json_files_to_multiple_json_files(extract_dir, 'cwe_weakness','Weakness_Catalog.Weaknesses.Weakness')
transform_big_json_files_to_multiple_json_files(extract_dir, 'cwe_category','Weakness_Catalog.Categories.Category')
transform_big_json_files_to_multiple_json_files(extract_dir, 'cwe_view','Weakness_Catalog.Views.View')
def download_files_capec(import_path):
url = 'https://capec.mitre.org/data/archive.html'
root = 'https://capec.mitre.org/'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
all_hrfs = soup.find_all('a')
all_links = [
link.get('href') for link in all_hrfs
]
xml_files = [
dl for dl in all_links if dl and '.xml' in dl
]
xml_file = xml_files[0]
download_folder = import_path + "mitre_capec/"
extract_dir = import_path + "mitre_capec/"
# Download xml file
print('\nUpdating the Database with the latest CAPEC Files...')
full_url = root + xml_file
zip_file_name = os.path.basename(xml_file)
download_file_to_path(full_url, download_folder, zip_file_name)
current_os = platform.system()
if (current_os == "Linux" or current_os == "Darwin"):
run_dos2unix(os.path.join(download_folder, zip_file_name))
transform_xml_files_to_json(download_folder)
replace_unwanted_string_capec(download_folder)
transform_big_json_files_to_multiple_json_files(extract_dir, 'capec_reference','Attack_Pattern_Catalog.External_References.External_Reference')
transform_big_json_files_to_multiple_json_files(extract_dir, 'capec_attack_pattern','Attack_Pattern_Catalog.Attack_Patterns.Attack_Pattern')
transform_big_json_files_to_multiple_json_files(extract_dir, 'capec_category','Attack_Pattern_Catalog.Categories.Category')
transform_big_json_files_to_multiple_json_files(extract_dir, 'capec_view','Attack_Pattern_Catalog.Views.View')
def download_datasets(import_path):
download_files_cve(import_path)
download_files_cpe(import_path)
download_files_cwe(import_path)
download_files_capec(import_path)
# Define the function that makes the HTTP request with retry
def make_http_request_with_retry(url, retries=0):
try:
# Call the function that makes the HTTP request, protected by the circuit breaker
return download_file_to_path(url)
except circuit.BreakerOpenError:
if retries < MAX_RETRIES:
print(f"Circuit is open. Retrying... Attempt {retries + 1}")
return make_http_request_with_retry(url, retries=retries + 1)
else:
raise RuntimeError("Circuit is open. Max retries reached.")
except Exception as e:
if retries < MAX_RETRIES:
print(f"Error occurred: {e}. Retrying... Attempt {retries + 1}")
return make_http_request_with_retry(url, retries=retries + 1)
else:
raise RuntimeError("Max retries reached. Last error: {}".format(e))
# Define the function that makes the HTTP request
@circuit(failure_threshold=10)
def download_file_to_path(url, download_path, file_name):
print("Download path: ", download_path)
if not os.path.exists(download_path):
os.makedirs(download_path, exist_ok=True)
r = requests.get(url)
dl_path = os.path.join(download_path, file_name)
with open(dl_path, 'wb') as file:
file.write(r.content)
def unzip_files_to_directory(zip_path, extract_path, zip_filename):
try:
if not os.path.exists(extract_path):
os.makedirs(extract_path, exist_ok=True)
z = zipfile.ZipFile(os.path.join(zip_path, zip_filename))
z.extractall(extract_path)
print(zip_filename + ' unzipped successfully')
print('---------')
z.close()
current_os = platform.system()
if (current_os == "Linux" or current_os == "Darwin"):
file_to_delete = f'{extract_path}' + f'/{zip_filename}'
elif current_os == "Windows":
file_to_delete = f'{extract_path}' + f'\\{zip_filename}'
os.remove(file_to_delete)
except zipfile.BadZipfile as e:
print("Error while unzipping data" + e)
def transform_xml_files_to_json(path):
directory_contents = os.listdir(path)
for item in directory_contents:
item_path = os.path.join(path, item)
if item_path.endswith(".xml") and os.path.isfile(item_path):
xml_file_to_json(item_path)
os.remove(item_path)
def transform_big_json_files_to_multiple_json_files(path, output_prefix, json_array_path):
directory_contents = os.listdir(path)
for item in directory_contents:
item_path = os.path.join(path, item)
if item_path.endswith(".json") and os.path.isfile(item_path):
slice_json_file(item_path, path, output_prefix, 200, json_array_path)
# Convert XML Files to JSON Files
def xml_file_to_json(xmlFile):
# parse the import folder for xml files
# open the input xml file and read
# data in form of python dictionary
# using xmltodict module
print(f"Transforming file {xmlFile}")
if xmlFile.endswith(".xml"):
with open(xmlFile, 'r', encoding='utf-8') as xml_file:
data_dict = xmltodict.parse(xml_file.read())
xml_file.close()
# generate the object using json.dumps()
# corresponding to json data
json_data = json.dumps(data_dict)
# Write the json data to output
# json file
xml_file.close()
jsonfile = f'{xmlFile}'
print(jsonfile)
jsonfile = jsonfile.replace(".xml", ".json")
print(jsonfile)
with open(jsonfile, "w") as json_file:
json_file.write(json_data)
json_file.close()
# Flatten CWE Dataset File
def replace_unwanted_string_cwe(path):
listOfFiles = os.listdir(path)
pattern = "*.json"
files = []
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
if entry.startswith("cwec"):
files.append(entry)
break
file = path + files[0]
fin = open(file, "rt")
flattened_cwe = path + "cwe.json"
fout = open(flattened_cwe, "wt")
for line in fin:
fout.write(line.replace('"@', '"'))
fin.close()
os.remove(file)
fout.close()
# Flatten CAPEC Dataset File
def replace_unwanted_string_capec(path):
listOfFiles = os.listdir(path)
pattern = "*.json"
files = []
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
if entry.startswith("capec"):
files.append(entry)
break
file = path + files[0]
fin = open(file, "rt")
flattened_cwe = path + "capec.json"
fout = open(flattened_cwe, "wt")
for line in fin:
fout.write(line.replace('"@', '"').replace('#text', 'text'))
fin.close()
fout.close()
os.remove(file)
def slice_json_file(input_file, output_path, output_prefix, batch_size, json_array_path):
with open(input_file, 'r') as f:
data = json.load(f)
data_array = select_nested_array_by_path(data, json_array_path)
length = len(data_array)
if not os.path.exists(os.path.join(output_path, "splitted")):
os.makedirs(os.path.join(output_path, "splitted"), exist_ok=True)
for i in range(0, length, batch_size):
batch = data_array[i:i+batch_size]
output_file = f"{output_path}/splitted/{output_prefix}_output_file_{i//batch_size + 1}.json"
with open(output_file, 'w') as f_out:
json.dump(batch, f_out, indent=4)
def select_nested_array_by_path(json_data, path):
parsed_json = json_data
keys = path.split('.')
for key in keys:
if key in parsed_json:
parsed_json = parsed_json[key]
else:
return None
return parsed_json
def run_dos2unix(file):
try:
dos2unix_command = f'dos2unix {file}'
print("Executing command:", dos2unix_command)
process = subprocess.run(['dos2unix', file], capture_output=True, text=True, check=True)
if process.returncode == 0:
print(f"File {file} transformed to unix format")
else:
raise RuntimeError(f"Error running dos2unix command: {process.stderr.strip()}")
except FileNotFoundError:
raise RuntimeError("dos2unix command not found. Make sure jq is installed on your system.")
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Error running dos2unix command. Make sure dos2unix is installed and check your file. Error: {e}")