-
Notifications
You must be signed in to change notification settings - Fork 65
/
Screener.py
272 lines (207 loc) · 9.13 KB
/
Screener.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
import importlib.util
import json
import os
import botocore
import traceback
import time
from utils.Config import Config
from services.Cloudwatch import Cloudwatch
from services.Reporter import Reporter
from services.PageBuilder import PageBuilder
from services.dashboard.DashboardPageBuilder import DashboardPageBuilder
from utils.CustomPage.CustomPage import CustomPage
from utils.Tools import _warn, _info
from frameworks.FrameworkPageBuilder import FrameworkPageBuilder
from utils.ExcelBuilder import ExcelBuilder
import shutil
# import zlib
import constants as _C
class Screener:
def __init__(self):
pass
@staticmethod
def scanByService(service, regions, filters):
_cli_options = Config.get('_SS_PARAMS', {})
_zeroCount = {
'resources': 0,
'rules': 0,
'exceptions': 0,
'timespent': 0
}
contexts = {}
charts = {}
time_start = time.time()
tempCount = 0
service = service.split('::')
_regions = ['GLOBAL'] if service[0] in Config.GLOBAL_SERVICES else regions
scannedKey = 'scanned_'+service[0]
globalKey = 'GLOBALRESOURCES_'+service[0]
Config.set(scannedKey, _zeroCount)
## CustomPage Enhancement
cp = CustomPage()
cp.resetOutput(service[0])
for region in _regions:
reg = region
if region == 'GLOBAL':
reg = 'us-east-1'
# reg = regions[0]
CURRENT_REGION = reg
cw = Cloudwatch(reg)
ServiceClass = Screener.getServiceModuleDynamically(service[0])
serv = ServiceClass(reg)
## Support --filters
if filters != []:
serv.setTags(filters)
if len(service) > 1 and service[1] != []:
serv.setRules(service[1])
if not service[0] in contexts:
contexts[service[0]] = {}
if not service[0] in charts:
charts[service[0]] = {}
Config.set('CWClient', cw.getClient())
try:
## Enhancement 20240117 - Capture all scanned resources
classPrefix = Config.getDriversClassPrefix(service[0])
Config.set(classPrefix, reg)
resp = serv.advise()
arr = {}
info = {}
for identifier, obj in resp.items():
arr[identifier] = obj['results']
info[identifier] = obj['info']
contexts[service[0]][region] = arr
charts[service[0]][region] = serv.getChart()
except botocore.exceptions.ClientError as e:
contexts[service[0]][region] = {}
eCode = e.response['Error']['Code']
eMsg = e.response['Error']['Message']
print("Screener.py error: {}, {}".format(eCode, eMsg))
print("Screener.py isCrossAccounts: {}".format(_cli_options['crossAccounts']))
if eCode == 'InvalidClientTokenId' and _cli_options['crossAccounts'] == True:
_warn('Impacted Region: [{}], Services: {}... Cross Account limitation, encounted errors: {}'.format(reg, service[0], e))
except botocore.exceptions.EndpointConnectionError as e:
contexts[service[0]][region] = {}
_warn("(Not showstopper: Service <{}> not available: {}".format(service[0], e))
tempCount += len(contexts[service[0]][region])
del serv
Config.set(classPrefix, None)
GLOBALRESOURCES = Config.get(globalKey, [])
if len(GLOBALRESOURCES) > 0:
garr = {}
ginfo = {}
for identifier, obj in GLOBALRESOURCES.items():
garr[identifier] = obj['results']
ginfo[identifier] = obj['info']
contexts[service[0]]['GLOBAL'] = arr
time_end = time.time()
scanned = Config.get(scannedKey)
# print(scannedKey)
scanned['timespent'] = time_end - time_start
with open(_C.FORK_DIR + '/' + service[0] + '.json', 'w') as f:
json.dump(contexts[service[0]], f)
with open(_C.FORK_DIR + '/' + service[0] + '.stat.json', 'w') as f:
json.dump(scanned, f)
## write the charts data per region
with open(_C.FORK_DIR + '/' + service[0] + '.charts.json', 'w') as f:
json.dump(charts[service[0]], f)
cp.writeOutput(service[0].lower())
@staticmethod
def getServiceModuleDynamically(service):
# .title() captilise the first character
# e.g: services.iam.Iam
folder = service
if service in Config.KEYWORD_SERVICES:
folder = service + '_'
className = service.title()
module = 'services.' + folder + '.' + className
ServiceClass = getattr(importlib.import_module(module), className)
return ServiceClass
@staticmethod
def getServicePagebuilderDynamically(service):
# ServiceClass = getattr(importlib.import_module('services.guardduty.GuarddutypageBuilder'), 'GuarddutypageBuilder')
# return ServiceClass
ServiceClass = getattr(importlib.import_module('services.PageBuilder'), 'PageBuilder')
folder = service
if service in Config.KEYWORD_SERVICES:
folder = service + '_'
className = service.title() + 'pageBuilder'
module = 'services.' + folder + '.' + className
try:
ServiceClass = getattr(importlib.import_module(module), className)
except:
print(className + ' class not found, using default pageBuilder')
# print(module, className)
# print(ServiceClass)
return ServiceClass
@staticmethod
def generateScreenerOutput(contexts, hasGlobal, regions, uploadToS3):
htmlFolder = Config.get('HTML_ACCOUNT_FOLDER_FULLPATH')
if not os.path.exists(htmlFolder):
os.makedirs(htmlFolder)
stsInfo = Config.get('stsInfo')
# generate raw findings json file
with open(htmlFolder + '/api-raw.json', 'w') as f:
json.dump(contexts, f)
cp = CustomPage()
pages = cp.getRegistrar()
Config.set("CustomPage::Pages", pages)
apiResultArray = {}
if hasGlobal:
regions.append('GLOBAL')
params = []
for key, val in Config.get('_SS_PARAMS').items():
if val != '':
tmp = '--' + key + ' ' + str(val)
params.append(tmp)
summary = Config.get("SCREENER-SUMMARY")
excelObj = ExcelBuilder(stsInfo["Account"], " ".join(params))
for service, dataSets in contexts.items():
resultSets = dataSets['results']
chartSets = dataSets['charts']
reporter = Reporter(service)
reporter.process(resultSets).processCharts(chartSets).getSummary().getDetails()
## <TODO> -- verification
## Maybe need to import module, to validate later
pageBuilderClass = Screener.getServicePagebuilderDynamically(service)
pb = pageBuilderClass(service, reporter)
pb.buildPage()
## <TODO>
if service not in ['guardduty']:
excelObj.generateWorkSheet(service, reporter.cardSummary)
if not service in apiResultArray:
apiResultArray[service] = {'summary': {}, 'detail': {}}
apiResultArray[service]['summary'] = reporter.getCard()
apiResultArray[service]['detail'] = reporter.getDetail()
# serviceStat = Config.get('cli_services')
# print(serviceStat)
dashPB = DashboardPageBuilder('index', [])
dashPB.buildPage()
# <TODO>
## dashPB will gather summary info, hence rearrange the sequences
excelObj.buildSummaryPage(summary)
excelObj._save()
## Enhancement - Framework
frameworks = Config.get('cli_frameworks')
if len(frameworks) > 0:
for framework in frameworks:
o = FrameworkPageBuilder(framework, apiResultArray)
if o.getGateCheckStatus() == True:
p = o.buildPage()
else:
print(framework + " GATECHECK==FALSE")
emsg = []
try:
cp.buildPage()
except Exception:
print(traceback.format_exc())
emsg.append(traceback.format_exc())
if emsg:
with open(_C.FORK_DIR + '/error.txt', 'a+') as f:
f.write('\n\n'.join(emsg))
f.close()
reporter.resetDashboard()
cp.resetPages()
del cp
# generate the full results in JSON format
with open(htmlFolder + "/api-full.json", "w") as f:
json.dump(apiResultArray, f)