forked from mohlcyber/McAfee-MVISION-EDR-Integrations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvision_edr_search_process.py
304 lines (247 loc) · 12.3 KB
/
mvision_edr_search_process.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
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/env python3
# Written by mohlcyber v.1.0 (25.04.2022)
# based on a hash, script will automatically launch MVISION EDR query
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.mcafee-cloud.com/iam/v1.1'
if args.region == 'EU':
self.base_url = 'soc.eu-central-1.mcafee.com'
elif args.region == 'US-W':
self.base_url = 'soc.mcafee.com'
elif args.region == 'US-E':
self.base_url = 'soc.us-east-1.mcafee.com'
elif args.region == 'SY':
self.base_url = 'soc.ap-southeast-2.mcafee.com'
elif args.region == 'GOV':
self.base_url = 'soc.mcafee-gov.com'
self.logging()
self.session = requests.Session()
self.session.verify = True
creds = (args.client_id, args.client_secret)
self.auth(creds)
self.pname = args.process
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',
'audience': 'mcafee'
}
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)}
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 = {
"projections": [
{
"name": "HostInfo",
"outputs": ["hostname", "ip_address"]
}, {
"name": "Processes",
"outputs": ["name", "id", "parentimagepath", "started_at"]
}
],
"condition": {
"or": [{
"and": [{
"name": "Processes",
"output": "name",
"op": "CONTAINS",
"value": str(self.pname)
}]
}]
}
}
res = self.session.post('https://api.{0}/active-response/api/v1/searches'.format(self.base_url), json=payload)
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:
queryId = res.json()['id']
self.logger.info('MVISION EDR search got started successfully')
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://api.{0}/active-response/api/v1/searches/{1}/status'.format(self.base_url, str(queryId)))
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:
if res.json()['status'] == 'FINISHED':
status = True
else:
self.logger.info('Search still in process. Status: {}'.format(res.json()['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://api.{0}/active-response/api/v1/searches/{1}/results'.format(self.base_url, str(queryId)))
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:
try:
items = res.json()['totalItems']
react_summary = []
for item in res.json()['items']:
react_dict = {}
react_dict[item['id']] = item['output']['Processes|id']
react_summary.append(react_dict)
self.logger.debug(json.dumps(res.json()))
self.logger.info('MVISION EDR search got {} responses for this process 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 get_reactions(self):
try:
res = self.session.get('https://api.{0}/active-response/api/v1/catalog/reactions'.format(self.base_url))
if res.ok:
return res.json()
else:
self.logger.error('Error in edr.get_reactions(). 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, pid):
try:
payload = {
"action": "killProcess",
"searchResultsArguments": {
"searchId": int(queryId),
"rowsIds": [str(systemId)],
"arguments": {}
},
"provider": "AR",
"actionInputs": [
{
"name": "pid",
"value": str(pid)
}
]
}
res = self.session.post('https://api.{0}/remediation/api/v1/actions/search-results-actions'.format(self.base_url),
json=payload)
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:
rid = res.json()['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:
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 mvision_edr_search_process.py -C <CLIENT_ID> -S <CLIENT_SECRET> -PN <process name>"""
title = 'MVISION EDR Python API'
parser = ArgumentParser(description=title, usage=usage, formatter_class=RawTextHelpFormatter)
parser.add_argument('--region', '-R',
required=True, type=str,
help='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('--process', '-PN', required=True,
type=str, default='Process Name to search for')
parser.add_argument('--reaction', '-RE', required=False,
type=str, choices=['True', 'False'],
default='False', help='Kill Process')
parser.add_argument('--loglevel', '-L', 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()