Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
397 lines (344 loc) · 14.1 KB
/
Copy pathparser.py
File metadata and controls
397 lines (344 loc) · 14.1 KB
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
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
import datetime
import logging
import html2text
from cvss import CVSS3
from defusedxml import ElementTree
from django.conf import settings
from dojo.location.feature import locations_enabled
from dojo.models import Endpoint, Finding
from dojo.tools.locations import LocationData
from dojo.tools.qualys import csv_parser
from dojo.utils import parse_cvss_data
logger = logging.getLogger(__name__)
class QualysParser:
def get_fields(self) -> list[str]:
"""
Return the list of fields used in the Qualys Parser.
Fields:
- title: Set to gid and vulnerability name from Qualys Scanner
- mitigation: Set to solution from Qualys Scanner
- description: Custom description made from: description, category, QID, port, result evidence, first found, last found, and times found.
- severity: Set to severity from Qualys Scanner translated into DefectDojo formant.
- impact: Set to impact from Qualys Scanner.
- date: Set to datetime from Qualys Scanner.
- vuln_id_from_tool: Set to gid from Qualys Scanner.
- mitigated: Set to the mitigation_date from Qualys Scanner
- is_mitigated: Set to true or false based on pressence of "mitigated" in Qualys Scanner output.
- active: Set to true if status equals active, re-opened, or new; else set to false.
- cvssv3: Set to CVSS_vector if not null.
- verified: Set to true.
Return the list of fields used in the Qualys CSV Parser.
Fields:
- title: Set to gid and vulnerability name from Qualys Scanner
- mitigation: Set to solution from Qualys Scanner
- description: Custom description made from: description, category, QID, port, result evidence, first found, last found, and times found.
- severity: Set to severity from Qualys Scanner translated into DefectDojo formant.
- impact: Set to impact from Qualys Scanner.
- date: Set to datetime from Qualys Scanner.
- vuln_id_from_tool: Set to gid from Qualys Scanner.
- mitigated: Set to the mitigation_date from Qualys Scanner
- is_mitigated: Set to true or false based on pressence of "mitigated" in Qualys Scanner output.
- active: Set to true if status equals active, re-opened, or new; else set to false.
- cvssv3: Set to CVSS_vector if not null.
- verified: Set to true.
"""
return [
"title",
"mitigation",
"description",
"severity",
"impact",
"date",
"vuln_id_from_tool",
"mitigated",
"is_mitigated",
"active",
"cvssv3",
"verified",
]
def get_dedupe_fields(self) -> list[str]:
"""
Return the list of fields used for deduplication in the Qualys and Qualys CSV Parser.
Fields:
- title: Set to gid and vulnerability name from Qualys Scanner
- severity: Set to severity from Qualys Scanner translated into DefectDojo formant.
#NOTE: endpoints is not provided by parser
"""
return [
"title",
"severity",
]
def get_scan_types(self):
return ["Qualys Scan"]
def get_label_for_scan_types(self, scan_type):
return "Qualys Scan"
def get_description_for_scan_types(self, scan_type):
return "Qualys WebGUI output files can be imported in XML format."
def get_findings(self, file, test):
if file.name.lower().endswith(".csv"):
return csv_parser.parse_csv(file)
return qualys_parser(file)
CUSTOM_HEADERS = {
"CVSS_score": "CVSS Score",
"ip_address": "IP Address",
"fqdn": "FQDN",
"os": "OS",
"port_status": "Port",
"vuln_name": "Vulnerability",
"vuln_description": "Description",
"solution": "Solution",
"links": "Links",
"cve": "CVE",
"vuln_severity": "Severity",
"QID": "QID",
"first_found": "First Found",
"last_found": "Last Found",
"found_times": "Found Times",
"category": "Category",
}
REPORT_HEADERS = [
"CVSS_score",
"ip_address",
"fqdn",
"os",
"port_status",
"vuln_name",
"vuln_description",
"solution",
"links",
"cve",
"Severity",
"QID",
"first_found",
"last_found",
"found_times",
"category",
]
TYPE_MAP = {
"Ig": "INFORMATION GATHERED",
"Practice": "POTENTIAL",
"Vuln": "CONFIRMED",
}
# Severity mapping taken from
# https://qualysguard.qg2.apps.qualys.com/portal-help/en/malware/knowledgebase/severity_levels.htm
LEGACY_SEVERITY_LOOKUP = {
1: "Info",
2: "Low",
3: "Medium",
4: "High",
5: "Critical",
}
NON_LEGACY_SEVERITY_LOOKUP = {
"Info": "Low",
"Low": "Low",
"Medium": "Medium",
"High": "High",
"Critical": "High",
}
def get_severity(severity_value_str: str | None) -> str:
severity_value: int = int(severity_value_str or -1)
sev: str = LEGACY_SEVERITY_LOOKUP.get(severity_value, "Unknown")
# Non legacy severity is a subset of legacy severity, retrieve it from lookup
if not settings.USE_QUALYS_LEGACY_SEVERITY_PARSING:
sev: str = NON_LEGACY_SEVERITY_LOOKUP.get(sev, "Unknown")
# If we still don't have a severity, default to Informational
if sev == "Unknown":
logger.warning(
"Could not determine severity from severity_value_str: %s",
severity_value_str,
)
sev = "Info"
return sev
def htmltext(blob):
h = html2text.HTML2Text()
h.ignore_links = False
return h.handle(blob)
def split_cvss(value, _temp):
# Check if CVSS field contains the CVSS vector
if value is None or len(value) == 0 or value == "-":
return
if len(value) > 4:
split = value.split(" (")
if _temp.get("CVSS_value") is None:
_temp["CVSS_value"] = float(split[0])
# remove ")" at the end
if _temp.get("CVSS_vector") is None:
_temp["CVSS_vector"] = CVSS3(
"CVSS:3.0/" + split[1][:-1],
).clean_vector()
elif _temp.get("CVSS_value") is None:
_temp["CVSS_value"] = float(value)
def parse_finding(host, glossary):
ret_rows = []
issue_row = {}
# IP ADDRESS
issue_row["ip_address"] = host.findtext("IP")
# FQDN
issue_row["fqdn"] = host.findtext("DNS")
# OS NAME
issue_row["os"] = host.findtext("OPERATING_SYSTEM")
# Scan details
for vuln_details in host.iterfind("VULN_INFO_LIST/VULN_INFO"):
temp = issue_row.copy()
# Port
gid = vuln_details.find("QID").attrib["id"]
port = vuln_details.findtext("PORT")
temp["port_status"] = port
category = str(vuln_details.findtext("CATEGORY"))
result = str(vuln_details.findtext("RESULT"))
first_found = str(vuln_details.findtext("FIRST_FOUND"))
last_found = str(vuln_details.findtext("LAST_FOUND"))
times_found = str(vuln_details.findtext("TIMES_FOUND"))
# Get the date based on the first_seen setting
try:
if settings.USE_FIRST_SEEN:
if date := vuln_details.findtext("FIRST_FOUND"):
temp["date"] = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%SZ").date()
elif date := vuln_details.findtext("LAST_FOUND"):
temp["date"] = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%SZ").date()
except Exception:
temp["date"] = None
# Vuln_status
status = vuln_details.findtext("VULN_STATUS")
if status in {"Active", "Re-Opened", "New"}:
temp["active"] = True
temp["mitigated"] = False
temp["mitigation_date"] = None
else:
temp["active"] = False
temp["mitigated"] = True
last_fixed = vuln_details.findtext("LAST_FIXED")
if last_fixed is not None:
temp["mitigation_date"] = datetime.datetime.strptime(
last_fixed, "%Y-%m-%dT%H:%M:%SZ",
)
else:
temp["mitigation_date"] = None
# read cvss value if present
cvss3 = vuln_details.findtext("CVSS3_FINAL")
if cvss3 is not None and cvss3 != "-":
split_cvss(cvss3, temp)
else:
cvss2 = vuln_details.findtext("CVSS_FINAL")
if cvss2 is not None and cvss2 != "-":
split_cvss(cvss2, temp)
# DefectDojo does not support cvssv2
temp["CVSS_vector"] = None
vuln_item = glossary.get(gid)
if vuln_item is None:
# A finding whose QID has no GLOSSARY entry has neither severity nor title to
# import, so skip it with a warning instead of aborting the whole import.
logger.warning("Qualys report has no GLOSSARY entry for QID %s, skipping its finding", gid)
continue
if vuln_item is not None:
finding = Finding()
# Vuln name
temp["vuln_name"] = vuln_item.findtext("TITLE")
# Vuln Description
description = str(vuln_item.findtext("THREAT"))
# Solution Strips Heading Workaround(s)
# _temp['solution'] = re.sub('Workaround(s)?:.+\n', '', htmltext(vuln_item.findtext('SOLUTION')))
temp["solution"] = htmltext(vuln_item.findtext("SOLUTION"))
# type
vul_type = TYPE_MAP.get(vuln_details.findtext("TYPE"), "Unknown")
# Vuln_description
temp["vuln_description"] = "\n".join(
[
htmltext(description),
htmltext("Type: " + vul_type),
htmltext("Category: " + category),
htmltext("QID: " + str(gid)),
htmltext("Port: " + str(port)),
htmltext("Result Evidence: " + result),
htmltext("First Found: " + first_found),
htmltext("Last Found: " + last_found),
htmltext("Times Found: " + times_found),
],
)
# Impact description
temp["IMPACT"] = htmltext(vuln_item.findtext("IMPACT"))
# read cvss value if present and not already read from vuln
if temp.get("CVSS_value") is None:
cvss3 = vuln_item.findtext("CVSS3_SCORE/CVSS3_BASE")
cvss2 = vuln_item.findtext("CVSS_SCORE/CVSS_BASE")
if cvss3 is not None and cvss3 != "-":
split_cvss(cvss3, temp)
else:
cvss2 = vuln_item.findtext("CVSS_FINAL")
if cvss2 is not None and cvss2 != "-":
split_cvss(cvss2, temp)
# DefectDojo does not support cvssv2
temp["CVSS_vector"] = None
# CVE and LINKS
temp_cve_details = [(cve.findtext("ID"), cve.findtext("URL")) for cve in vuln_item.iterfind("CVE_ID_LIST/CVE_ID")]
temp["cve_list"] = [cve_id for cve_id, _ in temp_cve_details if cve_id]
temp["links"] = [url for _, url in temp_cve_details if url]
# Generate severity from number in XML's 'SEVERITY' field, if not present default to 'Informational'
sev = get_severity(vuln_item.findtext("SEVERITY"))
finding = None
if temp_cve_details:
refs = temp.get("links", "")
finding = Finding(
title="QID-" + gid[4:] + " | " + temp["vuln_name"],
mitigation=temp["solution"],
description=temp["vuln_description"],
severity=sev,
references=refs,
impact=temp["IMPACT"],
date=temp["date"],
vuln_id_from_tool=gid,
)
else:
finding = Finding(
title="QID-" + gid[4:] + " | " + temp["vuln_name"],
mitigation=temp["solution"],
description=temp["vuln_description"],
severity=sev,
references=gid,
impact=temp["IMPACT"],
date=temp["date"],
vuln_id_from_tool=gid,
)
finding.mitigated = temp["mitigation_date"]
finding.is_mitigated = temp["mitigated"]
finding.active = temp["active"]
if temp.get("CVSS_vector") is not None:
cvss_data = parse_cvss_data(temp.get("CVSS_vector"))
if cvss_data:
finding.cvssv3 = cvss_data.get("cvssv3")
finding.cvssv3_score = cvss_data.get("cvssv3_score")
if temp.get("CVSS_value") is not None:
finding.cvssv3_score = temp.get("CVSS_value")
finding.verified = True
# manage endpoint/location
if locations_enabled():
location = LocationData.url(host=issue_row["fqdn"]) if issue_row["fqdn"] else LocationData.url(host=issue_row["ip_address"])
finding.unsaved_locations = [location]
else:
# TODO: Delete this after the move to Locations
location = Endpoint(host=issue_row["fqdn"]) if issue_row["fqdn"] else Endpoint(host=issue_row["ip_address"])
finding.unsaved_endpoints = [location]
finding.unsaved_vulnerability_ids = temp.get("cve_list", [])
ret_rows.append(finding)
return ret_rows
def qualys_parser(qualys_xml_file):
parser = ElementTree.XMLParser()
tree = ElementTree.parse(qualys_xml_file, parser)
host_list = tree.find("HOST_LIST")
finding_list = []
if host_list is not None:
glossary = vuln_details_by_id(tree)
for host in host_list:
finding_list += parse_finding(host, glossary)
return finding_list
def vuln_details_by_id(tree):
"""
The report's glossary entries by QID, read once per report.
Looking a QID up with a search from the document root walks every host before it reaches the
glossary, so doing that for each finding made a parse cost findings x report size. The first
entry for an id wins, as that search returned it.
"""
glossary = {}
for vuln_item in tree.iterfind(".//GLOSSARY/VULN_DETAILS_LIST/VULN_DETAILS"):
glossary.setdefault(vuln_item.get("id"), vuln_item)
return glossary