-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathoffice365_connector.py
3640 lines (2820 loc) · 143 KB
/
office365_connector.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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File: office365_connector.py
#
# Copyright (c) 2017-2024 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions
# and limitations under the License.
#
import base64
import grp
import json
import os
import pathlib
import pwd
import re
import sys
import tempfile
import time
from copy import deepcopy
from datetime import datetime
import encryption_helper
import msal
import phantom.app as phantom
import phantom.rules as ph_rules
import phantom.utils as util
import phantom.vault as phantom_vault
import requests
from bs4 import BeautifulSoup, UnicodeDammit
from django.http import HttpResponse
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
from phantom.vault import Vault
from office365_consts import *
from process_email import ProcessEmail
TC_FILE = "oauth_task.out"
SERVER_TOKEN_URL = "https://login.microsoftonline.com/{0}/oauth2/v2.0/token"
MSGOFFICE365_AUTHORITY_URL = "https://login.microsoftonline.com/{tenant}"
MSGRAPH_API_URL = "https://graph.microsoft.com"
MAX_END_OFFSET_VAL = 2147483646
MSGOFFICE365_DEFAULT_SCOPE = "https://graph.microsoft.com/.default"
class ReturnException(Exception):
pass
class RetVal(tuple):
def __new__(cls, val1, val2):
return tuple.__new__(RetVal, (val1, val2))
def _load_app_state(asset_id, app_connector=None):
"""This function is used to load the current state file.
:param asset_id: asset_id
:param app_connector: Object of app_connector class
:return: state: Current state file as a dictionary
"""
asset_id = str(asset_id)
if not asset_id or not asset_id.isalnum():
if app_connector:
app_connector.debug_print("In _load_app_state: Invalid asset_id")
return {}
app_dir = os.path.dirname(os.path.abspath(__file__))
state_file = "{0}/{1}_state.json".format(app_dir, asset_id)
real_state_file_path = os.path.abspath(state_file)
if not os.path.dirname(real_state_file_path) == app_dir:
if app_connector:
app_connector.debug_print("In _load_app_state: Invalid asset_id")
return {}
state = {}
try:
with open(real_state_file_path, "r") as state_file_obj:
state_file_data = state_file_obj.read()
state = json.loads(state_file_data)
except Exception as e:
if app_connector:
error_msg = _get_error_msg_from_exception(e, app_connector)
app_connector.debug_print("In _load_app_state: {0}".format(error_msg))
if app_connector:
app_connector.debug_print("Loaded state: ", state)
try:
if "code" in state:
state["code"] = encryption_helper.decrypt(state["code"], asset_id)
except Exception as e:
if app_connector:
error_msg = _get_error_msg_from_exception(e, app_connector)
app_connector.debug_print("{}: {}".format(MSGOFFICE365_DECRYPTION_ERROR, error_msg))
state = {}
return state
def _save_app_state(state, asset_id, app_connector=None):
"""This function is used to save current state in file.
:param state: Dictionary which contains data to write in state file
:param asset_id: asset_id
:param app_connector: Object of app_connector class
:return: status: phantom.APP_SUCCESS
"""
asset_id = str(asset_id)
if not asset_id or not asset_id.isalnum():
if app_connector:
app_connector.debug_print("In _save_app_state: Invalid asset_id")
return {}
app_dir = os.path.split(__file__)[0]
state_file = "{0}/{1}_state.json".format(app_dir, asset_id)
real_state_file_path = os.path.abspath(state_file)
if not os.path.dirname(real_state_file_path) == app_dir:
if app_connector:
app_connector.debug_print("In _save_app_state: Invalid asset_id")
return {}
try:
if "code" in state:
state["code"] = encryption_helper.encrypt(state["code"], asset_id)
except Exception as e:
if app_connector:
error_msg = _get_error_msg_from_exception(e, app_connector)
app_connector.debug_print("{}: {}".format(MSGOFFICE365_ENCRYPTION_ERROR, error_msg))
if app_connector:
app_connector.debug_print("Saving state: ", state)
try:
with open(real_state_file_path, "w+") as state_file_obj:
state_file_obj.write(json.dumps(state))
except Exception as e:
error_msg = _get_error_msg_from_exception(e, app_connector)
if app_connector:
app_connector.debug_print("Unable to save state file: {0}".format(error_msg))
print("Unable to save state file: {0}".format(error_msg))
return phantom.APP_ERROR
return phantom.APP_SUCCESS
def _get_error_msg_from_exception(e, app_connector=None):
"""
Get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
error_code = None
error_msg = MSGOFFICE365_ERROR_MSG_UNAVAILABLE
if app_connector:
app_connector.error_print("Error occurred.", dump_object=e)
try:
if hasattr(e, "args"):
if len(e.args) > 1:
error_code = e.args[0]
error_msg = e.args[1]
elif len(e.args) == 1:
error_msg = e.args[0]
except Exception:
pass
if not error_code:
error_text = "Error Message: {}".format(error_msg)
else:
error_text = "Error Code: {}. Error Message: {}".format(error_code, error_msg)
if app_connector:
app_connector.error_print("{}".format(error_text))
return error_text
def _validate_integer(action_result, parameter, key, allow_zero=False):
"""
Validate an integer.
:param action_result: Action result or BaseConnector object
:param parameter: input parameter
:param key: input parameter message key
:allow_zero: whether zero should be considered as valid value or not
:return: status phantom.APP_ERROR/phantom.APP_SUCCESS, integer value of the parameter or None in case of failure
"""
if parameter is not None:
try:
if not float(parameter).is_integer():
return (
action_result.set_status(phantom.APP_ERROR, MSGOFFICE365_VALID_INT_MSG.format(param=key)),
None,
)
parameter = int(parameter)
except Exception:
return (
action_result.set_status(phantom.APP_ERROR, MSGOFFICE365_VALID_INT_MSG.format(param=key)),
None,
)
if parameter < 0:
return action_result.set_status(phantom.APP_ERROR, MSGOFFICE365_NON_NEG_NON_ZERO_INT_MSG.format(param=key)), None
if not allow_zero and parameter == 0:
return (
action_result.set_status(
phantom.APP_ERROR,
MSGOFFICE365_NON_NEG_NON_ZERO_INT_MSG.format(param=key),
),
None,
)
return phantom.APP_SUCCESS, parameter
def _handle_oauth_result(request, path_parts):
"""
<base_url>?admin_consent=True&tenant=a417c578-c7ee-480d-a225-d48057e74df5&state=13
"""
asset_id = request.GET.get("state")
if not asset_id:
return HttpResponse(
"ERROR: Asset ID not found in URL\n{0}".format(json.dumps(request.GET)),
content_type="text/plain",
status=400,
)
# first check for error info
error = request.GET.get("error")
error_description = request.GET.get("error_description")
if error:
msg = "Error: {0}".format(error)
if error_description:
msg += " Details: {0}".format(error_description)
return HttpResponse("Server returned {0}".format(msg), content_type="text/plain", status=400)
admin_consent = request.GET.get("admin_consent")
code = request.GET.get("code")
if not admin_consent and not code:
return HttpResponse(
"ERROR: admin_consent or authorization code not found in URL\n{0}".format(json.dumps(request.GET)),
content_type="text/plain",
status=400,
)
# Load the data
state = _load_app_state(asset_id)
if admin_consent:
if admin_consent == "True":
admin_consent = True
else:
admin_consent = False
state["admin_consent"] = admin_consent
_save_app_state(state, asset_id)
# If admin_consent is True
if admin_consent:
return HttpResponse(
"Admin Consent received. Please close this window.",
content_type="text/plain",
)
return HttpResponse(
"Admin Consent declined. Please close this window and try again later.",
content_type="text/plain",
status=400,
)
# If value of admin_consent is not available, value of code is available
state["code"] = code
_save_app_state(state, asset_id)
return HttpResponse(
"Code received. Please close this window, the action will continue to get new token.",
content_type="text/plain",
)
def _handle_oauth_start(request, path_parts):
# get the asset id, the state file is created for each asset
asset_id = request.GET.get("asset_id")
if not asset_id:
return HttpResponse("ERROR: Asset ID not found in URL", content_type="text/plain", status=404)
# Load the state that was created for the asset
state = _load_app_state(asset_id)
if not state:
return HttpResponse(
"ERROR: The asset ID is invalid or an error occurred while reading the state file",
content_type="text/plain",
status=400,
)
# get the url to point to the authorize url of OAuth
admin_consent_url = state.get("admin_consent_url")
if not admin_consent_url:
return HttpResponse(
"App state is invalid, admin_consent_url key not found",
content_type="text/plain",
status=400,
)
# Redirect to this link, the user will then require to enter credentials interactively
response = HttpResponse(status=302)
response["Location"] = admin_consent_url
return response
def handle_request(request, path_parts):
"""
request contains the data posted to the rest endpoint, it is the django http request object
path_parts is a list of the URL tokenized
"""
# get the type of data requested, it's the last part of the URL used to post to the REST endpoint
if len(path_parts) < 2:
return HttpResponse(
"error: True, message: Invalid REST endpoint request",
content_type="text/plain",
status=404,
)
call_type = path_parts[1]
if call_type == "start_oauth":
# start the authentication process
return _handle_oauth_start(request, path_parts)
if call_type == "result":
# process the 'code'
ret_val = _handle_oauth_result(request, path_parts)
asset_id = request.GET.get("state") # nosemgrep
if asset_id and asset_id.isalnum():
app_dir = os.path.dirname(os.path.abspath(__file__))
auth_status_file_path = "{0}/{1}_{2}".format(app_dir, asset_id, TC_FILE)
real_auth_status_file_path = os.path.abspath(auth_status_file_path)
if not os.path.dirname(real_auth_status_file_path) == app_dir:
return HttpResponse("Error: Invalid asset_id", content_type="text/plain", status=400)
open(auth_status_file_path, "w").close()
try:
uid = pwd.getpwnam("apache").pw_uid
gid = grp.getgrnam("phantom").gr_gid
os.chown(auth_status_file_path, uid, gid)
os.chmod(auth_status_file_path, "0664")
except Exception:
pass
return ret_val
return HttpResponse("error: Invalid endpoint", content_type="text/plain", status=404)
def _get_dir_name_from_app_name(app_name):
app_name = "".join([x for x in app_name if x.isalnum()])
app_name = app_name.lower()
if not app_name:
# hardcode it
app_name = "app_for_phantom"
return app_name
class Office365Connector(BaseConnector):
def __init__(self):
# Call the BaseConnectors init first
super(Office365Connector, self).__init__()
self._state = None
# Variable to hold a base_url in case the app makes REST calls
# Do note that the app json defines the asset config, so please
# modify this as you deem fit.
self._base_url = None
self._tenant = None
self._client_id = None
self._auth_type = None
self._client_secret = None
self._admin_access = None
self._scope = None
self._access_token = None
self._refresh_token = None
self._REPLACE_CONST = "C53CEA8298BD401BA695F247633D0542" # pragma: allowlist secret
self._duplicate_count = 0
self._asset_id = None
self._cba_auth = None
self._private_key = None
self._certificate_private_key = None
def load_state(self):
"""
Load the contents of the state file to the state dictionary and decrypt it.
:return: loaded state
"""
state = super().load_state()
if not isinstance(state, dict):
self.debug_print("Resetting the state file with the default format")
state = {"app_version": self.get_app_json().get("app_version")}
return state
return self._decrypt_state(state)
def save_state(self, state):
"""
Encrypt and save the current state dictionary to the state file.
:param state: state dictionary
:return: status
"""
return super().save_state(self._encrypt_state(state))
def update_state_fields(self, value, helper_function, error_message):
try:
return helper_function(value, self._asset_id)
except Exception as ex:
self.debug_print("{}: {}".format(error_message, _get_error_msg_from_exception(ex, self)))
return None
def check_state_fields(self, state, helper_function, error_message):
access_token = state.get("non_admin_auth", {}).get("access_token")
if access_token:
state["non_admin_auth"]["access_token"] = self.update_state_fields(access_token, helper_function, error_message)
refresh_token = state.get("non_admin_auth", {}).get("refresh_token")
if refresh_token:
state["non_admin_auth"]["refresh_token"] = self.update_state_fields(refresh_token, helper_function, error_message)
access_token = state.get("admin_auth", {}).get("access_token")
if access_token:
state["admin_auth"]["access_token"] = self.update_state_fields(access_token, helper_function, error_message)
return state
def _decrypt_state(self, state):
"""
Decrypts the state.
:param state: state dictionary
:return: decrypted state
"""
if not state.get("is_encrypted"):
return state
return self.check_state_fields(state, encryption_helper.decrypt, MSGOFFICE365_DECRYPTION_ERROR)
def _encrypt_state(self, state):
"""
Encrypts the state.
:param state: state dictionary
:return: encrypted state
"""
state = self.check_state_fields(state, encryption_helper.encrypt, MSGOFFICE365_ENCRYPTION_ERROR)
state["is_encrypted"] = True
return state
def _dump_error_log(self, error, msg="Exception occurred."):
self.error_print(msg, dump_object=error)
def _process_empty_response(self, response, action_result):
if response.status_code == 200:
return RetVal(phantom.APP_SUCCESS, {})
return RetVal(action_result.set_status(phantom.APP_ERROR, MSGOFFICE365_ERROR_EMPTY_RESPONSE.format(code=response.status_code)), None)
def _process_html_response(self, response, action_result):
# An html response, treat it like an error
status_code = response.status_code
try:
soup = BeautifulSoup(response.text, "html.parser")
# Remove the script, style, footer and navigation part from the HTML message
for element in soup(["script", "style", "footer", "nav"]):
element.extract()
error_text = soup.text
split_lines = error_text.split("\n")
split_lines = [x.strip() for x in split_lines if x.strip()]
error_text = "\n".join(split_lines)
except Exception:
error_text = "Cannot parse error details"
msg = "Status Code: {0}. Data from server:\n{1}\n".format(status_code, error_text)
msg = msg.replace("{", "{{").replace("}", "}}")
return RetVal(action_result.set_status(phantom.APP_ERROR, msg), None)
def _process_json_response(self, r, action_result):
# Try a json parse
try:
resp_json = r.json()
except Exception as e:
error_msg = _get_error_msg_from_exception(e, self)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Unable to parse JSON response. {0}".format(error_msg)), None)
# Please specify the status codes here
if 200 <= r.status_code < 399:
return RetVal(phantom.APP_SUCCESS, resp_json)
try:
error_code = ""
error_text = ""
error_msg = ""
error = resp_json.get("error", "")
error_desc = resp_json.get("error_description", "")
if isinstance(error, dict):
error_code = error.get("code")
error_msg = error.get("message")
if error_msg:
try:
soup = BeautifulSoup(resp_json.get("error", {}).get("message"), "html.parser")
# Remove the script, style, footer and navigation part from the HTML message
for element in soup(["script", "style", "footer", "nav"]):
element.extract()
error_text = soup.text
split_lines = error_text.split("\n")
split_lines = [x.strip() for x in split_lines if x.strip()]
error_text = "\n".join(split_lines)
if len(error_text) > 500:
error_text = "Error while connecting to a server (Please check input parameters or asset configuration parameters)"
except Exception:
error_text = "Cannot parse error details"
if error_code:
error_text = "{}. {}".format(error_code, error_text)
if error_desc:
error_text = "{}. {}".format(error_desc, error_text)
if not error_text:
error_text = r.text.replace("{", "{{").replace("}", "}}")
except Exception:
error_text = r.text.replace("{", "{{").replace("}", "}}")
# You should process the error returned in the json
msg = "Error: Status Code: {0} Data from server: {1}".format(r.status_code, error_text)
return RetVal(action_result.set_status(phantom.APP_ERROR, msg), None)
def _process_response(self, r, action_result):
# store the r_text in debug data, it will get dumped in the logs if the action fails
if hasattr(action_result, "add_debug_data"):
action_result.add_debug_data({"r_status_code": r.status_code})
action_result.add_debug_data({"r_text": r.text})
action_result.add_debug_data({"r_headers": r.headers})
# Process each 'Content-Type' of response separately
# Process a json response
content_type = r.headers.get("Content-Type", "")
if "json" in content_type or "javascript" in content_type:
return self._process_json_response(r, action_result)
# Process an HTML response, Do this no matter what the api talks.
# There is a high chance of a PROXY in between Splunk SOAR and the rest of
# world, in case of errors, PROXY's return HTML, this function parses
# the error and adds it to the action_result.
if "html" in r.headers.get("Content-Type", ""):
return self._process_html_response(r, action_result)
if r.status_code == 404:
return RetVal(action_result.set_status(phantom.APP_ERROR, "Email not found"), None)
if 200 <= r.status_code <= 204:
return RetVal(phantom.APP_SUCCESS, None)
# it's not content-type that is to be parsed, handle an empty response
if not r.text:
return self._process_empty_response(r, action_result)
# everything else is actually an error at this point
msg = "Can't process response from server. Status Code: {0} Data from server: {1}".format(
r.status_code, r.text.replace("{", "{{").replace("}", "}}")
)
return RetVal(action_result.set_status(phantom.APP_ERROR, msg), None)
def _make_rest_call(
self,
action_result,
url,
verify=True,
headers={},
params=None,
data=None,
method="get",
download=False,
):
resp_json = None
try:
request_func = getattr(requests, method)
except AttributeError:
return RetVal(
action_result.set_status(phantom.APP_ERROR, "Invalid method: {0}".format(method)),
resp_json,
)
for _ in range(self._number_of_retries):
try:
r = request_func(
url,
data=data,
headers=headers,
verify=verify,
params=params,
timeout=MSGOFFICE365_DEFAULT_REQUEST_TIMEOUT,
)
except Exception as e:
error_msg = _get_error_msg_from_exception(e, self)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Error connecting to server. {0}".format(error_msg)), resp_json)
if r.status_code != 502:
break
self.debug_print("Received 502 status code from the server")
time.sleep(self._retry_wait_time)
if download:
if 200 <= r.status_code < 399:
return RetVal(phantom.APP_SUCCESS, r.text)
self.debug_print("Error while downloading a file content")
return RetVal(phantom.APP_ERROR, None)
return self._process_response(r, action_result)
def _get_asset_name(self, action_result):
rest_endpoint = SPLUNK_SOAR_ASSET_INFO_URL.format(url=self.get_phantom_base_url(), asset_id=self._asset_id)
ret_val, resp_json = self._make_rest_call(action_result, rest_endpoint, False)
if phantom.is_fail(ret_val):
return (ret_val, None)
asset_name = resp_json.get("name")
if not asset_name:
return action_result.set_status(
phantom.APP_ERROR,
"Asset Name for ID: {0} not found".format(self._asset_id),
None,
)
return (phantom.APP_SUCCESS, asset_name)
def _update_container(self, action_result, container_id, container):
"""
Update container.
:param action_result: Action result or BaseConnector object
:param container_id: container ID
:param container: container's payload to update
:return: status phantom.APP_ERROR/phantom.APP_SUCCESS with status message
"""
rest_endpoint = SPLUNK_SOAR_CONTAINER_INFO_URL.format(url=self.get_phantom_base_url(), container_id=container_id)
try:
data = json.dumps(container)
except Exception as e:
error_msg = _get_error_msg_from_exception(e, self)
msg = (
"json.dumps failed while updating the container: {}. "
"Possibly a value in the container dictionary is not encoded properly."
"Exception: {}"
).format(container_id, error_msg)
return action_result.set_status(phantom.APP_ERROR, msg)
ret_val, _ = self._make_rest_call(action_result, rest_endpoint, False, data=data, method="post")
if phantom.is_fail(ret_val):
return action_result.get_status()
return phantom.APP_SUCCESS
def _get_phantom_base_url(self, action_result):
ret_val, resp_json = self._make_rest_call(
action_result,
SPLUNK_SOAR_SYS_INFO_URL.format(url=self.get_phantom_base_url()),
False,
)
if phantom.is_fail(ret_val):
return (ret_val, None)
phantom_base_url = resp_json.get("base_url").rstrip("/")
if not phantom_base_url:
return (
action_result.set_status(
phantom.APP_ERROR,
"Splunk SOAR Base URL not found in System Settings. Please specify this value in System Settings",
),
None,
)
return (phantom.APP_SUCCESS, phantom_base_url)
def _get_url_to_app_rest(self, action_result=None):
if not action_result:
action_result = ActionResult()
# get the Splunk SOAR ip to redirect to
ret_val, phantom_base_url = self._get_phantom_base_url(action_result)
if phantom.is_fail(ret_val):
return (action_result.get_status(), None)
# get the asset name
ret_val, asset_name = self._get_asset_name(action_result)
if phantom.is_fail(ret_val):
return (action_result.get_status(), None)
self.save_progress("Using Splunk SOAR base URL as: {0}".format(phantom_base_url))
app_json = self.get_app_json()
app_name = app_json["name"]
app_dir_name = _get_dir_name_from_app_name(app_name)
url_to_app_rest = "{0}/rest/handler/{1}_{2}/{3}".format(phantom_base_url, app_dir_name, app_json["appid"], asset_name)
return (phantom.APP_SUCCESS, url_to_app_rest)
def _make_rest_call_helper(
self,
action_result,
endpoint,
verify=True,
headers=None,
params=None,
data=None,
method="get",
nextLink=None,
download=False,
beta=False,
):
if nextLink:
url = nextLink
else:
if not beta:
url = f"{MSGRAPH_API_URL}/v1.0{endpoint}"
else:
url = f"{MSGRAPH_API_URL}/beta{endpoint}"
if headers is None:
headers = {}
headers.update(
{"Authorization": "Bearer {0}".format(self._access_token), "Accept": "application/json", "Content-Type": "application/json"}
)
ret_val, resp_json = self._make_rest_call(action_result, url, verify, headers, params, data, method, download=download)
# If token is expired, generate a new token
msg = action_result.get_message()
if msg and (("token" in msg and "expired" in msg) or any(failure_msg in msg for failure_msg in MSGOFFICE365_AUTH_FAILURE_MSG)):
self.debug_print("MSGRAPH", f"Error '{msg}' found in API response. Requesting new access token using refresh token")
ret_val = self._get_token(action_result)
if phantom.is_fail(ret_val):
return action_result.get_status(), None
headers.update({"Authorization": "Bearer {0}".format(self._access_token)})
ret_val, resp_json = self._make_rest_call(
action_result,
url,
verify,
headers,
params,
data,
method,
download=download,
)
if phantom.is_fail(ret_val):
return action_result.get_status(), None
return phantom.APP_SUCCESS, resp_json
def _sanitize_file_name(self, file_name):
return re.sub("[,\"']", "", file_name)
def _add_attachment_to_vault(self, attachment, container_id, file_data):
fd, tmp_file_path = tempfile.mkstemp(dir=Vault.get_vault_tmp_dir())
os.close(fd)
file_mode = "wb" if isinstance(file_data, bytes) else "w"
with open(tmp_file_path, file_mode) as f:
f.write(file_data)
file_name = self._sanitize_file_name(attachment["name"])
success, msg, vault_id = ph_rules.vault_add(
container=container_id,
file_location=tmp_file_path,
file_name=file_name,
)
if not success:
self.debug_print("Error adding file to vault: {}".format(msg))
return RetVal(phantom.APP_ERROR, None)
else:
return RetVal(phantom.APP_SUCCESS, vault_id)
def _handle_attachment(self, attachment, container_id, artifact_json=None):
vault_id = None
try:
if "contentBytes" in attachment: # Check whether the attachment contains the data
file_data = base64.b64decode(attachment.pop("contentBytes"))
ret_val, vault_id = self._add_attachment_to_vault(attachment, container_id, file_data)
if phantom.is_fail(ret_val):
return phantom.APP_ERROR
else:
self.debug_print("No content found in the attachment. Hence, skipping the vault file creation.")
except Exception as e:
error_msg = _get_error_msg_from_exception(e, self)
self.debug_print("Error saving file to vault: {0}".format(error_msg))
return phantom.APP_ERROR
if artifact_json is None:
attachment["vaultId"] = vault_id
return phantom.APP_SUCCESS
artifact_json["name"] = "Vault Artifact"
artifact_json["label"] = "attachment"
artifact_json["container_id"] = container_id
artifact_json["source_data_identifier"] = attachment["id"]
artifact_cef = {}
artifact_cef["size"] = attachment["size"]
artifact_cef["lastModified"] = attachment["lastModifiedDateTime"]
artifact_cef["filename"] = attachment["name"]
artifact_cef["mimeType"] = attachment["contentType"]
if vault_id:
artifact_cef["vault_id"] = vault_id
artifact_json["cef"] = artifact_cef
return phantom.APP_SUCCESS
def _handle_item_attachment(self, attachment, container_id, endpoint, action_result):
vault_id = None
try:
attach_endpoint = "{}/{}/$value".format(endpoint, attachment["id"])
ret_val, rfc822_email = self._make_rest_call_helper(action_result, attach_endpoint, download=True)
if phantom.is_fail(ret_val):
self.debug_print("Error while downloading the file content, for attachment id: {}".format(attachment["id"]))
return phantom.APP_ERROR
attachment["name"] = "{}.eml".format(attachment["name"])
if rfc822_email: # Check whether the API returned any data
ret_val, vault_id = self._add_attachment_to_vault(attachment, container_id, rfc822_email)
if phantom.is_fail(ret_val):
return phantom.APP_ERROR
else:
self.debug_print("No content found for the item attachment. Hence, skipping the vault file creation.")
except Exception as e:
error_msg = _get_error_msg_from_exception(e, self)
self.debug_print("Error saving file to vault: {0}".format(error_msg))
return phantom.APP_ERROR
attachment["vaultId"] = vault_id
return phantom.APP_SUCCESS
def _create_reference_attachment_artifact(self, container_id, attachment, artifact_json):
"""
Create reference attachment artifact.
:param container_id: container ID
:param attachment: attachment dict
:param artifact_json: artifact dict to add the data
:return: phantom.APP_SUCCESS
"""
artifact_json["name"] = "Reference Attachment Artifact"
artifact_json["container_id"] = container_id
artifact_json["source_data_identifier"] = attachment["id"]
artifact_cef = {}
artifact_cef["size"] = attachment.get("size")
artifact_cef["lastModified"] = attachment.get("lastModifiedDateTime")
artifact_cef["filename"] = attachment.get("name")
artifact_cef["mimeType"] = attachment.get("contentType")
artifact_json["cef"] = artifact_cef
return phantom.APP_SUCCESS
def _create_email_artifacts(self, container_id, email, artifact_id=None, create_iocs=True):
"""
Create email artifacts.
:param container_id: container ID
:param email: email content
:param artifact_id: artifact ID
:return: extracted artifacts list
"""
artifacts = []
email_artifact = {}
email_artifact["label"] = "email"
email_artifact["name"] = "Email Artifact"
email_artifact["container_id"] = container_id
if email.get("id"):
artifact_id = email["id"]
# Set email ID contains
self._process_email._set_email_id_contains(email["id"])
email_artifact["cef_types"] = {"messageId": self._process_email._email_id_contains}
email_artifact["source_data_identifier"] = artifact_id
cef = {}
email_artifact["cef"] = cef
for k, v in email.items():
if v is not None:
if k == "from":
from_obj = v.get("emailAddress", {})
cef[k] = from_obj
cef["fromEmail"] = from_obj.get("address", "")
elif k == "toRecipients":
cef[k] = v
# add first email to To
recipients = v
if len(recipients):
cef["toEmail"] = recipients[0].get("emailAddress", {}).get("address", "")
elif k == "id":
cef["messageId"] = v
elif k == "internetMessageHeaders":
cef["internetMessageHeaders"] = {}
if isinstance(v, list):
for header in v:
key_name = header.get("name")
key_value = header.get("value")
if key_name and key_value:
cef["internetMessageHeaders"][key_name] = key_value
elif k == "attachments":
continue
else:
cef[k] = v
if cef.get("body", {}).get("content") and (cef.get("body", {}).get("contentType") == "html"):
html_body = cef["body"]["content"]
try:
soup = BeautifulSoup(html_body, "html.parser")
# Remove the script, style, footer, title and navigation part from the HTML message
for element in soup(["script", "style", "footer", "title", "nav"]):
element.extract()
body_text = soup.get_text(separator=" ")
split_lines = body_text.split("\n")
split_lines = [x.strip() for x in split_lines if x.strip()]
body_text = "\n".join(split_lines)
if body_text:
cef["bodyText"] = body_text
except Exception:
self.debug_print("Cannot parse email body text details")
if not create_iocs:
return [email_artifact]