-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathMSDefenderEndpoints.py
More file actions
executable file
·337 lines (292 loc) · 15.4 KB
/
MSDefenderEndpoints.py
File metadata and controls
executable file
·337 lines (292 loc) · 15.4 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env python3
from cortexutils.responder import Responder
import requests
import urllib
import urllib.error
import json
import datetime
class MSDefenderEndpoints(Responder):
def __init__(self):
Responder.__init__(self)
self.msdefenderTenantId = self.get_param('config.tenantId', None, 'TenantId missing!')
self.msdefenderAppId = self.get_param('config.appId', None, 'AppId missing!')
self.msdefenderSecret = self.get_param('config.appSecret', None, 'AppSecret missing!')
self.msdefenderResourceAppIdUri = self.get_param('config.resourceAppIdUri', None, 'resourceAppIdUri missing!')
self.msdefenderOAuthUri = self.get_param('config.oAuthUri', None, 'oAuthUri missing!')
self.msdefenderApiBaseUrl = self.msdefenderResourceAppIdUri.rstrip('/') + "/api/v1.0"
self.observable = self.get_param('data.data', None, "Data is empty")
self.observableType = self.get_param('data.dataType', None, "Data type is empty")
self.caseId = self.get_param("data.case.caseId", None, "caseId is missing")
self.caseTitle = self.get_param('data.case.title', None, 'Case title is missing').encode("utf-8")
self.service = self.get_param("config.service", None, "Service Missing")
self.msdefenderSession = requests.Session()
self.msdefenderSession.headers.update(
{
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
)
def run(self):
Responder.run(self)
url = "{}/{}/oauth2/token".format(
self.msdefenderOAuthUri,self.msdefenderTenantId
)
body = {
'resource' : self.msdefenderResourceAppIdUri,
'client_id' : self.msdefenderAppId,
'client_secret' : self.msdefenderSecret,
'grant_type' : 'client_credentials'
}
data = urllib.parse.urlencode(body).encode("utf-8")
req = urllib.request.Request(url, data)
try:
response = urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
#print("message: HTTP ErrorCode {}. Reason: {}".format(e.code,e.reason))
self.error("HTTP ErrorCode {}. Reason: {}".format(e.code,e.reason))
except urllib.error.URLError as e:
#print("message: URL Error: {}".format(e.reason))
self.error("URL Error: {}".format(e.reason))
jsonResponse = json.loads(response.read())
token = jsonResponse["access_token"]
self.msdefenderSession.headers.update(
{
'Authorization' : 'Bearer {0}'.format(token)
}
)
def getMachineId(id):
time = datetime.datetime.now() - datetime.timedelta(minutes=60)
time = time.strftime("%Y-%m-%dT%H:%M:%SZ")
if self.observableType == "ip":
url = "{}/machines/findbyip(ip='{}',timestamp={})".format(self.msdefenderApiBaseUrl, id, time)
else:
url = "{}/machines?$filter=computerDnsName+eq+'{}'".format(self.msdefenderApiBaseUrl, id)
try:
response = self.msdefenderSession.get(url=url)
if response.status_code == 200:
jsonResponse = response.json()
if len(response.content) > 100:
if jsonResponse["value"][0]["aadDeviceId"] is None:
return jsonResponse["value"][0]["id"]
return jsonResponse["value"][0]["aadDeviceId"]
else:
self.error("Can't get hostname from Microsoft API")
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
def isolateMachine(machineId):
'''
example
POST https://api.security.microsoft.com/api/v1.0/machines/{id}/isolate
'''
url = '{}/machines/{}/isolate'.format(self.msdefenderApiBaseUrl, machineId)
body = {
'Comment': 'Isolate machine due to TheHive case {}'.format(self.caseId),
'IsolationType': 'Full'
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 201:
self.report({'message': "Isolated machine: " + self.observable })
elif response.status_code == 400 and "ActiveRequestAlreadyExists" in response.content.decode("utf-8"):
self.report({'message': "Error isolating machine: ActiveRequestAlreadyExists"})
else:
self.error("Can't isolate machine")
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
self.report({'message': "Isolated machine: " + self.observable })
def runFullVirusScan(machineId):
'''
example
POST https://api.security.microsoft.com/api/v1.0/machines/{id}/runAntiVirusScan
'''
url = '{}/machines/{}/runAntiVirusScan'.format(self.msdefenderApiBaseUrl, machineId)
body = {
'Comment': 'Full scan to machine due to TheHive case {}'.format(self.caseId),
'ScanType': 'Full'
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 201:
self.report({'message': "Started full VirusScan on machine: " + self.observable })
elif response.status_code == 400 and "ActiveRequestAlreadyExists" in response.content.decode("utf-8"):
self.report({'message': "Error full VirusScan on machine: ActiveRequestAlreadyExists"})
else:
self.error("Error full VirusScan on machine")
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
def unisolateMachine(machineId):
'''
example
POST https://api.security.microsoft.com/api/v1.0/machines/{id}/unisolate
'''
url = '{}/machines/{}/unisolate'.format(self.msdefenderApiBaseUrl, machineId)
body = {
'Comment': 'Unisolate machine due to TheHive case {}'.format(self.caseId)
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 201:
self.report({'message': "Unisolated machine: " + self.observable })
elif response.status_code == 400 and "ActiveRequestAlreadyExists" in response.content.decode("utf-8"):
self.report({'message': "Error unisolating machine: ActiveRequestAlreadyExists"})
else:
self.error("Can't unisolate machine")
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
def restrictAppExecution(machineId):
'''
example
POST https://api.security.microsoft.com/api/v1.0/machines/{id}/restrictCodeExecution
'''
url = '{}/machines/{}/restrictCodeExecution'.format(self.msdefenderApiBaseUrl, machineId)
body = {
'Comment': 'Restrict code execution due to TheHive case {}'.format(self.caseId)
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 201:
self.report({'message': "Restricted app execution on machine: " + self.observable })
elif response.status_code == 400 and "ActiveRequestAlreadyExists" in response.content.decode("utf-8"):
self.report({'message': "Error restricting app execution on machine: ActiveRequestAlreadyExists"})
else:
self.error("Can't restrict app execution")
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
def unrestrictAppExecution(machineId):
'''
example
POST https://api.security.microsoft.com/api/v1.0/machines/{id}/unrestrictCodeExecution
'''
url = '{}/machines/{}/unrestrictCodeExecution'.format(self.msdefenderApiBaseUrl, machineId)
body = {
'Comment': '"Remove code execution restriction since machine was cleaned and validated due to TheHive case {}'.format(self.caseId)
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 201:
self.report({'message': "Removed app execution restriction on machine: " + self.observable })
elif response.status_code == 400 and "ActiveRequestAlreadyExists" in response.content.decode("utf-8"):
self.report({'message': "Error removing app execution restriction on machine: ActiveRequestAlreadyExists"})
else:
self.error("Can't unrestrict app execution")
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
def startAutoInvestigation(machineId):
'''
example
POST https://api.security.microsoft.com/api/v1.0/machines/{id}/startInvestigation
'''
url = '{}/machines/{}/startInvestigation'.format(self.msdefenderApiBaseUrl, machineId)
body = {
'Comment': 'Start investigation due to TheHive case {}'.format(self.caseId)
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 201:
self.report({'message': "Started Auto Investigation on : " + self.observable })
elif response.status_code == 400 and "ActiveRequestAlreadyExists" in response.content.decode("utf-8"):
self.report({'message': "Error lauching auto investigation on machine: ActiveRequestAlreadyExists"})
else:
self.error("Error auto investigation on machine")
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
def pushCustomIocAlert(observable):
if self.observableType == 'ip':
indicatorType = 'IpAddress'
elif self.observableType == 'url':
indicatorType = 'Url'
elif self.observableType == 'domain':
indicatorType = 'DomainName'
elif self.observableType == 'hash':
if len(observable) == 32:
indicatorType = 'FileMd5'
elif len(observable) == 40:
indicatorType = 'FileSha1'
elif len(observable) == 64:
indicatorType = 'FileSha256'
else:
self.report({'message':"Observable is not a valid hash"})
else:
self.error("Observable type must be ip, url, domain or hash")
url = '{}/indicators'.format(self.msdefenderApiBaseUrl)
body = {
'indicatorValue': observable,
'indicatorType': indicatorType,
'action': 'Alert',
'title': "TheHive IOC: {}".format(self.caseTitle),
'severity': 'High',
'description': "TheHive case: {} - caseId {}".format(self.caseTitle,self.caseId),
'recommendedActions': 'N/A'
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 200:
self.report({'message': "Added IOC to Defender with Alert mode: " + self.observable })
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
def pushCustomIocBlock(observable):
if self.observableType == 'ip':
indicatorType = 'IpAddress'
elif self.observableType == 'url':
indicatorType = 'Url'
elif self.observableType == 'domain':
indicatorType = 'DomainName'
elif self.observableType == 'hash':
if len(observable) == 32:
indicatorType = 'FileMd5'
elif len(observable) == 40:
indicatorType = 'FileSha1'
elif len(observable) == 64:
indicatorType = 'FileSha256'
else:
self.report({'message':"Observable is not a valid hash"})
else:
self.error("Observable type must be ip, url, domain or hash")
url = '{}/indicators'.format(self.msdefenderApiBaseUrl)
body = {
'indicatorValue' : observable,
'indicatorType' : indicatorType,
'action' : 'AlertAndBlock',
'title' : "TheHive IOC: {}".format(self.caseTitle),
'severity' : 'High',
'description' : "TheHive case: {} - caseId {}".format(self.caseTitle,self.caseId),
'recommendedActions' : 'N/A'
}
try:
response = self.msdefenderSession.post(url=url, json=body)
if response.status_code == 200:
self.report({'message': "Added IOC to Defender with Alert and Block mode: " + self.observable })
except requests.exceptions.RequestException as e:
self.error("Error: {}".format(str(e)))
if self.service == "isolateMachine":
isolateMachine(getMachineId(self.observable))
elif self.service == "unisolateMachine":
unisolateMachine(getMachineId(self.observable))
elif self.service == "runFullVirusScan":
runFullVirusScan(getMachineId(self.observable))
elif self.service == "restrictAppExecution":
restrictAppExecution(getMachineId(self.observable))
elif self.service == "unrestrictAppExecution":
unrestrictAppExecution(getMachineId(self.observable))
elif self.service == "startAutoInvestigation":
startAutoInvestigation(getMachineId(self.observable))
elif self.service == "pushIOCBlock":
pushCustomIocBlock(self.observable)
elif self.service == "pushIOCAlert":
pushCustomIocAlert(self.observable)
else:
self.error("Unidentified service")
def operations(self, raw):
self.build_operation('AddTagToCase', tag='MSDefenderResponder:run')
if self.service == "isolateMachine":
return [self.build_operation("AddTagToArtifact", tag="MsDefender:isolated")]
elif self.service == "runFullVirusScan":
return [self.build_operation("AddTagToArtifact", tag="MsDefender:fullVirusScan")]
elif self.service == "unisolateMachine":
return [self.build_operation("AddTagToArtifact", tag="MsDefender:unIsolated")]
elif self.service == "restrictAppExecution":
return [self.build_operation("AddTagToArtifact", tag="MsDefender:restrictedAppExec")]
elif self.service == "unrestrictAppExecution":
return [self.build_operation("AddTagToArtifact", tag="MsDefender:unrestrictedAppExec")]
if __name__ == '__main__':
MSDefenderEndpoints().run()