-
Notifications
You must be signed in to change notification settings - Fork 1
/
vcmitreject.py
229 lines (182 loc) · 8.82 KB
/
vcmitreject.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
import argparse
import logging
import datetime
from uuid import UUID
import anticrlf
from beautifultable import BeautifulTable
from veracode_api_py import VeracodeAPI as vapi, Applications, Findings
debugmode = False
log = logging.getLogger(__name__)
app_names = list()
def setup_logger():
handler = logging.FileHandler('vcmitreject.log', encoding='utf8')
handler.setFormatter(anticrlf.LogFormatter('%(asctime)s - %(levelname)s - %(funcName)s - %(message)s'))
logger = logging.getLogger(__name__)
logger.addHandler(handler)
if debugmode:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
def creds_expire_days_warning():
creds = vapi().get_creds()
exp = datetime.datetime.strptime(creds['expiration_ts'], "%Y-%m-%dT%H:%M:%S.%f%z")
delta = exp - datetime.datetime.now().astimezone()
if (delta.days < 7):
print('These API credentials expire ', creds['expiration_ts'])
def is_valid_datetime(string_to_test):
try:
datetime.datetime.strptime(string_to_test,'%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
return True
def is_valid_uuid(uuid_to_test, version=4):
try:
uuid_obj = UUID(uuid_to_test, version=version)
except ValueError:
return False
return str(uuid_obj) == uuid_to_test
def prompt_for_app(prompt_text):
appguid = ""
app_name_search = input(prompt_text)
app_candidates = vapi().get_app_by_name(app_name_search)
if len(app_candidates) == 0:
print("No matches were found!")
elif len(app_candidates) > 1:
print("Please choose an application:")
for idx, appitem in enumerate(app_candidates,start=1):
print("{}) {}".format(idx, appitem["profile"]["name"]))
i = input("Enter number: ")
try:
if 0 < int(i) <= len(app_candidates):
appguid = app_candidates[int(i)-1].get('guid')
except ValueError:
appguid = ""
else:
appguid = app_candidates[0].get('guid')
return appguid
def get_apps_list(appguid: UUID=None,new_since=None):
the_apps=[]
# only look at new_since if appguid not specified
if appguid:
the_apps.append(appguid)
elif new_since:
matching_apps = Applications().get_all(policy_check_after=new_since)
matching_app_guids = [ma['guid'] for ma in matching_apps]
the_apps.extend(matching_app_guids)
return the_apps
def get_all_app_findings(the_apps):
the_findings=[]
for count, app in enumerate(the_apps):
if debugmode:
status = "{} - Checking findings for app {}".format(count, app)
print(status)
log.debug(status)
request_params = { 'mitigated_after': '2006-04-01', 'violates_policy': True, 'size': 100 } # only mitigated flaws; only policy violating flaws matter for mitigations; increase page size for perf
these_findings = Findings().get_findings(app=app, scantype='ALL', annot=True, request_params=request_params)
these_mitigated_findings = get_self_mitigated_findings(these_findings)
status = "Found {} mitigated out of {} total findings for application {}".format(len(these_mitigated_findings),len(these_findings),app)
print(status)
log.info(status)
# these_findings find the findings that have .action = 'APPROVED' and .action != APPROVED, COMMENT, REJECTED with same user
the_findings.extend(these_mitigated_findings)
return the_findings
def find_approver(the_finding):
return next((annot['user_name'] for annot in the_finding['annotations'] if annot['action'] == 'APPROVED'),"")
def find_proposer(the_finding):
return next((annot['user_name'] for annot in the_finding['annotations'] if annot['action'] in ('APPDESIGN','FP','NETENV','OSENV','LIBRARY','ACCEPTRISK')),"")
def get_self_mitigated_findings(all_findings):
# start by getting all mitigated findings
mitigated_findings = list(filter(lambda finding: finding['finding_status']['resolution_status'] == 'APPROVED', all_findings))
self_mitigated_findings=[]
for each_finding in mitigated_findings: # ideally we want to do this with list comprehension, but looping through as a first pass
approver = find_approver(each_finding)
proposer = find_proposer(each_finding)
if proposer == approver and approver != "":
self_mitigated_findings.append(each_finding)
return self_mitigated_findings
def get_app_name(app_guid: UUID):
app_name = next((app['name'] for app in app_names if app['guid'] == app_guid),"")
if app_name == "":
the_app = Applications().get(guid=app_guid)
app_name = the_app['profile']['name']
app_names.append({'guid':app_guid,'name':app_name})
return app_name
def build_report(the_findings, csv=False):
table = BeautifulTable(maxwidth=100)
for each_finding in the_findings:
this_guid = each_finding['context_guid']
app_name = get_app_name(app_guid=this_guid)
table.rows.append([each_finding['issue_id'],app_name,this_guid,each_finding['scan_type'],each_finding['finding_details']['cwe']['id'],find_approver(each_finding)])
table.columns.header = ['Flaw ID','App Name','App GUID','Scan Type','CWE ID','Approver']
table.columns.header.alignment = BeautifulTable.ALIGN_CENTER
table.columns.alignment['App Name'] = BeautifulTable.ALIGN_LEFT
table.columns.alignment['App GUID'] = BeautifulTable.ALIGN_LEFT
table.columns.alignment['Approver'] = BeautifulTable.ALIGN_LEFT
table.set_style(BeautifulTable.STYLE_COMPACT)
print()
print(table)
#format findings list
if csv:
the_time = datetime.datetime.now()
filename = 'vcmitreject-{}.csv'.format(the_time)
table.to_csv(file_name = filename)
def reject_self_mitigated_findings(the_findings):
rejection_comment = 'Automatically rejecting self-approved mitigation.'
for each_finding in the_findings:
issue_id = each_finding['issue_id']
app_guid = each_finding['context_guid']
Findings().add_annotation(app=app_guid, issue_list=[issue_id],comment=rejection_comment,action='REJECTED')
log.info('Rejected mitigation for issue {} on app guid {}'.format(issue_id,app_guid))
def main():
parser = argparse.ArgumentParser(
description='This script identifies and, optionally, rejects self-approved mitigations.')
parser.add_argument('-a', '--app_id', help='Applications guid to check for self-approved mitigations.')
parser.add_argument('-p', '--prompt', action='store_true', help='Prompt for application using partial match search.')
parser.add_argument('-n', '--new_since', help='Check for new self-approved mitigations after the date-time provided.')
parser.add_argument('-r', '--reject', action='store_true', help='Attempt to automatically reject self-approved mitigations.')
parser.add_argument('-c', '--csv', action='store_true', help='Set to save the output as a CSV file.')
parser.add_argument('-d', '--debug', action='store_true', help='Set to print additional debug information to console and log.')
args = parser.parse_args()
appguid = args.app_id
new_since = args.new_since
reject = args.reject
prompt = args.prompt
csv = args.csv
global debugmode
debugmode = args.debug
setup_logger()
# CHECK FOR CREDENTIALS EXPIRATION
creds_expire_days_warning()
# validate inputs
if not(new_since) and not(prompt) and not (appguid):
print('Searching across all applications in your account. This may take some time…')
if new_since:
if not(is_valid_datetime(new_since)):
print('{} is an invalid datetime value. Please provide the date in YYYY-MM-DDTHH:MM:SS.OOOZ format'.format(new_since))
return
else:
new_since = '2006-04-01' #fetch data for all time
if prompt:
appguid = prompt_for_app('Enter the application name for which to reject self-approved mitigations: ')
if appguid and not(is_valid_uuid(appguid)):
print('{} is an invalid application guid. Please supply a valid UUID.'.format(appguid))
return
# get apps to test
apps = []
apps = get_apps_list(appguid, new_since)
if len(apps) == 0:
print("No applications found that match the specified parameters.")
return 0
print('Checking {} applications for self mitigated findings.'.format(len(apps)))
# get findings for apps
all_findings = get_all_app_findings(apps)
print()
print('{} self-mitigated findings found within the criteria provided.'.format(len(all_findings)))
# construct report
build_report(all_findings, csv)
# reject self-approved mitigations
if reject:
reject_self_mitigated_findings(all_findings)
print('Rejected {} self-mitigated findings'.format(len(all_findings)))
if __name__ == '__main__':
main()