-
Notifications
You must be signed in to change notification settings - Fork 5
/
trellix_edr_search_filename.py
272 lines (216 loc) · 11.2 KB
/
trellix_edr_search_filename.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
#!/usr/bin/env python3
# based on a hash, script will automatically launch MVISION EDR query
# This is a script intended to be a guideline and not supported by Trellix , if you help integrating scripts with EDR reach out to Trellix Professional services
import sys
import getpass
import time
import requests
import logging
import json
from argparse import ArgumentParser, RawTextHelpFormatter
class EDR():
def __init__(self):
self.iam_url = 'iam.cloud.trellix.com/iam/v1.0'
self.base_url='api.manage.trellix.com'
self.logging()
self.session = requests.Session()
self.session.verify = True
creds = (args.client_id, args.client_secret)
self.auth(creds)
self.fname = args.file
def logging(self):
self.logger = logging.getLogger('logs')
self.logger.setLevel(args.loglevel.upper())
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def auth(self, creds):
try:
payload = {
'scope': 'mi.user.investigate soc.act.tg soc.hts.c soc.hts.r soc.rts.c soc.rts.r soc.qry.pr',
'grant_type': 'client_credentials'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
res = self.session.post('https://{0}/token'.format(self.iam_url), headers=headers, data=payload, auth=creds)
self.logger.debug('request url: {}'.format(res.url))
self.logger.debug('request headers: {}'.format(res.request.headers))
self.logger.debug('request body: {}'.format(res.request.body))
if res.ok:
token = res.json()['access_token']
self.session.headers = {
'Authorization': 'Bearer {}'.format(token),
'Content-Type':'application/vnd.api+json',
'x-api-key': args.x_api_key
}
self.logger.debug('AUTHENTICATION: Successfully authenticated.')
else:
self.logger.error('Error in edr.auth(). Error: {0} - {1}'
.format(str(res.status_code), res.text))
exit()
except Exception as error:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.logger.error("Error in {location}.{funct_name}() - line {line_no} : {error}"
.format(location=__name__, funct_name=sys._getframe().f_code.co_name,
line_no=exc_tb.tb_lineno, error=str(error)))
def search(self):
try:
queryId = None
payload = {
"data": {
"type": "realTimeSearches",
"attributes": {
"query": "HostInfo hostname, ip_address and Files name, status, full_name where Files name contains "+str(self.fname)
}
}
}
res = self.session.post('https://{0}/edr/v2/searches/realtime'.format(self.base_url), json=payload)
self.logger.debug('request url: {}'.format(res.url))
self.logger.debug('request body: {}'.format(res.request.body))
if res.ok:
queryId = res.json()['data']['id']
self.logger.info('MVISION EDR search got started successfully {}'.format(queryId))
else:
self.logger.error('Error in edr.search(). Error {} - {}'.format(str(res.status_code), res.text))
exit()
return queryId
except Exception as error:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.logger.error("Error in {location}.{funct_name}() - line {line_no} : {error}"
.format(location=__name__, funct_name=sys._getframe().f_code.co_name,
line_no=exc_tb.tb_lineno, error=str(error)))
def search_status(self, queryId):
try:
status = False
res = self.session.get('https://{0}/edr/v2/searches/queue-jobs/{1}'.format(self.base_url, str(queryId)), allow_redirects=False)
self.logger.debug('request url: {}'.format(res.url))
self.logger.debug('request body: {}'.format(res.request.body))
if res.status_code == 303:
status = True
else:
self.logger.info('Search still in process. Status: {}'.format(res.json()['data']['attributes']['status']))
return status
except Exception as error:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.logger.error("Error in {location}.{funct_name}() - line {line_no} : {error}"
.format(location=__name__, funct_name=sys._getframe().f_code.co_name,
line_no=exc_tb.tb_lineno, error=str(error)))
def search_result(self, queryId):
try:
res = self.session.get('https://{0}/edr/v2/searches/realtime/{1}/results'.format(self.base_url, str(queryId)))
self.logger.debug('request url: {}'.format(res.url))
self.logger.debug('request body: {}'.format(res.request.body))
if res.ok:
try:
items = res.json()['meta']['totalResourceCount']
react_summary = []
for item in res.json()['data']:
if item['attributes']['Files.status'] != 'deleted':
react_dict = {}
react_dict[item['id']] = item['attributes']['Files.full_name']
react_summary.append(react_dict)
self.logger.debug(json.dumps(res.json()))
self.logger.info('MVISION EDR search got {} responses for this file name. {}'
.format(items, len(react_summary)))
return react_summary
except Exception as e:
self.logger.error('Something went wrong to retrieve the results. Error: {}'.format(e))
exit()
else:
self.logger.error('Error in edr.search_result(). Error {} - {}'.format(str(res.status_code), res.text))
exit()
except Exception as error:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.logger.error("Error in {location}.{funct_name}() - line {line_no} : {error}"
.format(location=__name__, funct_name=sys._getframe().f_code.co_name,
line_no=exc_tb.tb_lineno, error=str(error)))
def reaction_execution(self, queryId, systemId, filePath):
try:
payload = {
"data": {
"type": "searchRemediation",
"attributes": {
"action": "removeFile",
"searchId": queryId,
"rowIds": [str(systemId)],
"actionInputs": [
{
"name": "full_name",
"value": str(filePath)
}
]
}
}
}
res = self.session.post('https://{0}/edr/v2/remediation/search'.format(self.base_url),
json=payload)
self.logger.debug('request url: {}'.format(res.url))
self.logger.debug('request body: {}'.format(res.request.body))
if res.ok:
rid = res.json()['data']['id']
self.logger.info('MVISION EDR reaction got executed successfully')
return rid
else:
self.logger.error('Error in edr.reaction_execution(). Error {} - {}'.format(str(res.status_code), res.text))
exit()
except Exception as error:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.logger.error("Error in {location}.{funct_name}() - line {line_no} : {error}"
.format(location=__name__, funct_name=sys._getframe().f_code.co_name,
line_no=exc_tb.tb_lineno, error=str(error)))
def main(self):
try:
# Retrieve all reactions
# reactions = self.get_reactions()
# self.logger.info(json.dumps(reactions))
# sys.exit()
queryId = self.search()
if queryId is None:
exit()
while self.search_status(queryId) is False:
time.sleep(30)
results = self.search_result(queryId)
if len(results) == 0:
self.logger.info('All Files deleted on Systems')
exit()
if args.reaction == 'True':
for result in results:
for systemId, filePath in result.items():
reaction_id = self.reaction_execution(queryId, systemId, filePath)
if reaction_id is None:
self.logger.error('Could not create new MVISION EDR reaction')
except Exception as error:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.logger.error("Error in {location}.{funct_name}() - line {line_no} : {error}"
.format(location=__name__, funct_name=sys._getframe().f_code.co_name,
line_no=exc_tb.tb_lineno, error=str(error)))
if __name__ == '__main__':
usage = """Usage: python trellix_edr_search_filename.py -C <CLIENT_ID> -S <CLIENT_SECRET> -K <X_API_KEY> -F <FILE>"""
title = 'MVISION EDR Python API'
parser = ArgumentParser(description=title, usage=usage, formatter_class=RawTextHelpFormatter)
parser.add_argument('--region', '-R',
required=False, type=str,
help=' [Deprecated] MVISION EDR Tenant Location', choices=['EU', 'US-W', 'US-E', 'SY', 'GOV'])
parser.add_argument('--client_id', '-C',
required=True, type=str,
help='MVISION EDR Client ID')
parser.add_argument('--client_secret', '-S',
required=False, type=str,
help='MVISION EDR Client Secret')
parser.add_argument('--x_api_key', '-K',
required=True, type=str,
help='MVISION API Key')
parser.add_argument('--file', '-F', required=True,
type=str, default='Filename to search for / string filename contains.')
parser.add_argument('--reaction', '-RE', required=False,
type=str, choices=['True', 'False'],
default='False', help='Delete Files that got identified.')
parser.add_argument('--loglevel', '-LL', required=False,
type=str, choices=['INFO', 'DEBUG'],
default='INFO', help='Specify log level.')
args = parser.parse_args()
if not args.client_secret:
args.client_secret = getpass.getpass(prompt='MVISION EDR Client Secret: ')
EDR().main()