forked from DefectDojo/defectdojo_api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdojo_ci_cd.py
293 lines (258 loc) · 11.5 KB
/
dojo_ci_cd.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
"""
Example written by Aaron Weaver <[email protected]>
as part of the OWASP DefectDojo and OWASP AppSec Pipeline Security projects
Description: CI/CD example for DefectDojo
"""
from defectdojo_api import defectdojo
from datetime import datetime, timedelta
import os, sys
import argparse
import time
test_cases = []
def junit(toolName, file):
junit_xml = junit_xml_output.JunitXml(toolName, test_cases, total_tests=None, total_failures=None)
with open(file, 'w') as file:
print "Writing Junit test files"
file.write(junit_xml.dump())
def dojo_connection(host, api_key, user, proxy):
#Optionally, specify a proxy
proxies = None
if proxy:
proxies = {
'http': proxy,
'https': proxy,
}
# Instantiate the DefectDojo api wrapper
dd = defectdojo.DefectDojoAPI(host, api_key, user, proxies=proxies, verify_ssl=False, timeout=360, debug=False)
return dd
# Workflow as follows:
# 1. Scan tool is run against build
# 2. Reports is saved from scan tool
# 3. Call this script to load scan data, specifying scanner type
# 4. Script returns along with a pass or fail results: Example: 2 new critical vulns, 1 low out of 10 vulnerabilities
def return_engagement(dd, product_id, user, build_id=None):
#Specify the product id
product_id = product_id
engagement_id = None
"""
# Check for a CI/CD engagement_id
engagements = dd.list_engagements(product_in=product_id, status="In Progress")
if engagements.success:
for engagement in engagements.data["objects"]:
if "Recurring CI/CD Integration" == engagement['name']:
engagement_id = engagement['id']
if engagement_id == None:
"""
start_date = datetime.now()
end_date = start_date+timedelta(days=1)
users = dd.list_users(user)
user_id = None
if users.success:
user_id = users.data["objects"][0]["id"]
dojoTime = start_date.strftime("%H:%M:%S")
engagementText = "CI/CD Integration (" + dojoTime + ")"
if build_id is not None:
engagementText = engagementText + " - Build #" + build_id
engagement_id = dd.create_engagement(engagementText, product_id, str(user_id),
"In Progress", start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))
return engagement_id
def process_findings(dd, engagement_id, dir, build=None):
test_ids = []
for root, dirs, files in os.walk(dir):
for name in files:
file = os.path.join(os.getcwd(),root, name)
test_id = processFiles(dd, engagement_id, file)
if test_id is not None:
test_ids.append(str(test_id))
return ','.join(test_ids)
def processFiles(dd, engagement_id, file, scanner=None, build=None):
upload_scan = None
scannerName = None
path=os.path.dirname(file)
name = os.path.basename(file)
tool = os.path.basename(path)
tool = tool.lower()
test_id = None
date = datetime.now()
dojoDate = date.strftime("%Y-%m-%d")
#Tools without an importer in Dojo; attempted to import as generic
if "generic" in name:
scanner = "Generic Findings Import"
if tool == "nikto":
print "Uploading nikto scan: " + file
test_id = dd.upload_scan(engagement_id, scanner, file, "true", dojoDate, build)
elif tool == "bandit":
print "Uploading bandit scan: " + file
test_id = dd.upload_scan(engagement_id, scanner, file, "true", dojoDate, build)
else:
if tool == "burp":
scannerName = "Burp Scan"
elif tool == "nessus":
scannerName = "Nessus Scan"
elif tool == "nmap":
scannerName = "Nmap Scan"
elif tool == "nexpose":
scannerName = "Nexpose Scan"
elif tool == "veracode":
scannerName = "Veracode Scan"
elif tool == "checkmarx":
scannerName = "Checkmarx Scan"
elif tool == "zap":
scannerName = "ZAP Scan"
elif tool == "appspider":
scannerName = "AppSpider Scan"
elif tool == "Arachni Scan":
scannerName = "Arachni Scan"
elif tool == "vcg":
scannerName = "VCG Scan"
elif tool == "dependency":
scannerName = "Dependency Check Scan"
elif tool == "retirejs":
scannerName = "Retire.js Scan"
elif tool == "nodesecurity":
scannerName = "Node Security Platform Scan"
elif tool == "qualys":
scannerName = "Qualys Scan"
elif tool == "qualyswebapp":
scannerName = "Qualys Webapp Scan"
elif tool == "openvas":
scannerName = "OpenVAS CSV"
elif tool == "snyk":
scannerName = "Snyk Scan"
if scannerName is not None:
print "Uploading " + scannerName + " scan: " + file
test_id = dd.upload_scan(engagement_id, scannerName, file, "true", dojoDate, build)
if test_id.success == False:
print "Upload failed: Detailed error message: " + test_id.data
return test_id
def create_findings(dd, engagement_id, scanner, file, build=None):
# Upload the scanner export
if engagement_id > 0:
print "Uploading scanner data."
date = datetime.now()
upload_scan = dd.upload_scan(engagement_id, scanner, file, "true", date.strftime("%Y-%m-%d"), build=build)
if upload_scan.success:
test_id = upload_scan.id()
else:
print upload_scan.message
quit()
def summary(dd, engagement_id, test_ids, max_critical=0, max_high=0, max_medium=0):
findings = dd.list_findings(engagement_id_in=engagement_id, duplicate="false", active="true", verified="true")
print"=============================================="
print "Total Number of Vulnerabilities: " + str(findings.data["meta"]["total_count"])
print"=============================================="
print_findings(sum_severity(findings))
print
findings = dd.list_findings(test_id_in=test_ids, duplicate="true")
print"=============================================="
print "Total Number of Duplicate Findings: " + str(findings.data["meta"]["total_count"])
print"=============================================="
print_findings(sum_severity(findings))
print
#Delay while de-dupes
sys.stdout.write("Sleeping for 10 seconds for de-dupe celery process:")
sys.stdout.flush()
for i in range(5):
time.sleep(2)
sys.stdout.write(".")
sys.stdout.flush()
findings = dd.list_findings(test_id_in=test_ids, duplicate="false", limit=500)
if findings.count() > 0:
"""
for finding in findings.data["objects"]:
test_cases.append(junit_xml_output.TestCase(finding["title"] + " Severity: " + finding["severity"], finding["description"],"failure"))
if not os.path.exists("reports"):
os.mkdir("reports")
junit("DefectDojo", "reports/junit_dojo.xml")
"""
print"\n=============================================="
print "Total Number of New Findings: " + str(findings.data["meta"]["total_count"])
print"=============================================="
sum_new_findings = sum_severity(findings)
print_findings(sum_new_findings)
print
print"=============================================="
strFail = None
if max_critical is not None:
if sum_new_findings[4] > max_critical:
strFail = "Build Failed: Max Critical"
if max_high is not None:
if sum_new_findings[3] > max_high:
strFail = strFail + " Max High"
if max_medium is not None:
if sum_new_findings[2] > max_medium:
strFail = strFail + " Max Medium"
if strFail is None:
print "Build Passed!"
else:
print "Build Failed: " + strFail
print"=============================================="
def sum_severity(findings):
severity = [0,0,0,0,0]
for finding in findings.data["objects"]:
if finding["severity"] == "Critical":
severity[4] = severity[4] + 1
if finding["severity"] == "High":
severity[3] = severity[3] + 1
if finding["severity"] == "Medium":
severity[2] = severity[2] + 1
if finding["severity"] == "Low":
severity[1] = severity[1] + 1
if finding["severity"] == "Info":
severity[0] = severity[0] + 1
return severity
def print_findings(findings):
print "Critical: " + str(findings[4])
print "High: " + str(findings[3])
print "Medium: " + str(findings[2])
print "Low: " + str(findings[1])
print "Info: " + str(findings[0])
class Main:
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='CI/CD integration for DefectDojo')
parser.add_argument('--host', help="DefectDojo Hostname", required=True)
parser.add_argument('--proxy', help="Proxy ex:localhost:8080", required=False, default=None)
parser.add_argument('--api_key', help="API Key", required=True)
parser.add_argument('--build_id', help="Reference to external build id", required=False)
parser.add_argument('--user', help="User", required=True)
parser.add_argument('--product', help="DefectDojo Product ID", required=True)
parser.add_argument('--file', help="Scanner file", required=False)
parser.add_argument('--dir', help="Scanner directory, needs to have the scanner name with the scan file in the folder. Ex: reports/nmap/nmap.csv", required=False)
parser.add_argument('--scanner', help="Type of scanner", required=False)
parser.add_argument('--build', help="Build ID", required=False)
parser.add_argument('--engagement', help="Engagement ID (optional)", required=False)
parser.add_argument('--critical', help="Maximum new critical vulns to pass the build.", required=False)
parser.add_argument('--high', help="Maximum new high vulns to pass the build.", required=False)
parser.add_argument('--medium', help="Maximum new medium vulns to pass the build.", required=False)
#Parse out arguments
args = vars(parser.parse_args())
host = args["host"]
api_key = args["api_key"]
user = args["user"]
product_id = args["product"]
file = args["file"]
dir = args["dir"]
scanner = args["scanner"]
engagement_id = args["engagement"]
max_critical = args["critical"]
max_high = args["high"]
max_medium = args["medium"]
build = args["build"]
proxy = args["proxy"]
build_id = args["build_id"]
if dir is not None or file is not None:
dd = dojo_connection(host, api_key, user, proxy=proxy)
engagement_id = return_engagement(dd, product_id, user, build_id=build_id)
test_ids = None
if file is not None:
if scanner is not None:
test_ids = processFiles(dd, engagement_id, file, scanner=scanner)
else:
print "Scanner type must be specified for a file import. --scanner"
else:
test_ids = process_findings(dd, engagement_id, dir, build)
#Close the engagement_id
dd.close_engagement(engagement_id)
summary(dd, engagement_id, test_ids, max_critical, max_high, max_medium)
else:
print "No file or directory to scan specified."