forked from splunk-soar-connectors/crowdstrikeoauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrowdstrikeoauthapi_connector.py
3439 lines (2558 loc) · 144 KB
/
crowdstrikeoauthapi_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: crowdstrikeoauthapi_connector.py
#
# Copyright (c) 2019-2022 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.
#
#
# Phantom imports
import ipaddress
import os
import time
import traceback
import uuid
from datetime import datetime, timedelta
import phantom.app as phantom
import phantom.rules as phantom_rules
import phantom.utils as util
import pytz
import requests
import simplejson as json
from _collections import defaultdict
from bs4 import BeautifulSoup, UnicodeDammit
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
from phantom.vault import Vault
from requests_toolbelt.multipart.encoder import MultipartEncoder
import parse_cs_events as events_parser
# THIS Connector imports
from crowdstrikeoauthapi_consts import *
class RetVal(tuple):
def __new__(cls, val1, val2):
return tuple.__new__(RetVal, (val1, val2))
class CrowdstrikeConnector(BaseConnector):
def __init__(self):
# Call the BaseConnectors init first
super(CrowdstrikeConnector, self).__init__()
self._state = {}
self._events = []
self._base_url_oauth = None
self._client_id = None
self._client_secret = None
self._oauth_access_token = None
self._poll_interval = None
self._required_detonation = False
self._stream_file_data = False
def initialize(self):
""" Automatically called by the BaseConnector before the calls to the handle_action function"""
config = self.get_config()
# The headers, initialize them here once and use them for all other REST calls
self._headers = {'Content-Type': 'application/json'}
self.set_validator('ipv6', self._is_ip)
# Base URL
self._client_id = config[CROWDSTRIKE_CLIENT_ID]
self._client_secret = config[CROWDSTRIKE_CLIENT_SECRET]
self._base_url_oauth = config[CROWDSTRIKE_JSON_URL_OAuth]
self._required_detonation = False
self._poll_interval = self._validate_integers(self, config.get(CROWDSTRIKE_POLL_INTERVAL, 15), CROWDSTRIKE_POLL_INTERVAL)
if self._poll_interval is None:
return self.get_status()
self._base_url_oauth = self._base_url_oauth.replace('\\', '/')
if self._base_url_oauth[-1] == '/':
self._base_url_oauth = self._base_url_oauth[:-1]
app_id = config.get('app_id', self.get_asset_id().replace('-', ''))
self._parameters = {'appId': app_id.replace('-', '')}
self._state = self.load_state()
if not isinstance(self._state, dict):
self.debug_print("Resetting the state file with the default format")
self._state = {"app_version": self.get_app_json().get("app_version")}
return self.set_status(phantom.APP_ERROR, CROWDSTRIKE_STATE_FILE_CORRUPT_ERR)
self._oauth_access_token = self._state.get(CROWDSTRIKE_OAUTH_TOKEN_STRING, {}).get(CROWDSTRIKE_OAUTH_ACCESS_TOKEN_STRING)
ret = self._handle_preprocess_scripts()
if phantom.is_fail(ret):
return ret
return phantom.APP_SUCCESS
def finalize(self):
self.save_state(self._state)
return phantom.APP_SUCCESS
def _is_ip(self, input_ip_address):
"""
Function that checks given address and return True if address is valid IPv4 or IPV6 address.
:param input_ip_address: IP address
:return: status (success/failure)
"""
try:
ipaddress.ip_address(input_ip_address)
except Exception:
return False
return True
def _handle_preprocess_scripts(self):
config = self.get_config()
script = config.get('preprocess_script')
self._preprocess_container = lambda x: x
if script:
try: # Try to laod in script to preprocess artifacts
import importlib.util
preprocess_methods = importlib.util.spec_from_loader('preprocess_methods', loader=None)
self._script_module = importlib.util.module_from_spec(preprocess_methods)
exec(script, self._script_module.__dict__)
except Exception as e:
self.save_progress("Error loading custom script. Error: {}".format(str(e)))
return phantom.APP_ERROR
try:
self._preprocess_container = self._script_module.preprocess_container
except Exception:
self.save_progress("Error loading custom script. Does not contain preprocess_container function")
return phantom.APP_ERROR
return phantom.APP_SUCCESS
def _get_error_message_from_exception(self, e):
""" This method is used to get appropriate error message from the exception.
:param e: Exception object
:return: error message
"""
error_code = None
error_msg = CROWDSTRIKE_ERR_MSG_UNAVAILABLE
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)
return error_text
def _check_for_existing_container(self, container, time_interval, collate):
# Even if the collate parameter is selected, the time mentioned in the merge_time_interval
# config parameter will be considered for the creation of the new container for a given category of DetectionSummaryEvent
gt_date = datetime.utcnow() - timedelta(seconds=int(time_interval))
# Cutoff Timestamp From String
common_str = ' '.join(container['name'].split()[:-1])
request_str = CROWDSTRIKE_FILTER_REQUEST_STR.format(
self.get_phantom_base_url(), self.get_asset_id(), common_str, gt_date.strftime('%Y-%m-%dT%H:%M:%SZ'))
try:
r = requests.get(request_str, verify=False) # nosemgrep
except Exception as e:
self.debug_print("Error making local rest call: {0}".format(self._get_error_message_from_exception(e)))
self.debug_print('DB QUERY: {}'.format(request_str))
return phantom.APP_ERROR, None
try:
resp_json = r.json()
except Exception as e:
self.debug_print('Exception caught: {0}'.format(self._get_error_message_from_exception(e)))
return phantom.APP_ERROR, None
count = resp_json.get('count', 0)
if count:
try:
most_recent = gt_date
most_recent_id = None
for container in resp_json['data']:
if container.get('parent_container'):
# container created through aggregation, skip this
continue
cur_start_time = datetime.strptime(container['start_time'], '%Y-%m-%dT%H:%M:%S.%fZ')
if most_recent <= cur_start_time:
most_recent_id = container['id']
most_recent = cur_start_time
if most_recent_id is not None:
return phantom.APP_SUCCESS, most_recent_id
except Exception as e:
self.debug_print("Caught Exception in parsing containers: {0}".format(self._get_error_message_from_exception(e)))
return phantom.APP_ERROR, None
return phantom.APP_ERROR, None
def _get_hash_type(self, hash_value, action_result):
if util.is_md5(hash_value):
return (phantom.APP_SUCCESS, "md5")
if util.is_sha1(hash_value):
return (phantom.APP_SUCCESS, "sha1")
if util.is_sha256(hash_value):
return (phantom.APP_SUCCESS, "sha256")
return (action_result.set_status(phantom.APP_ERROR, CROWDSTRIKE_ERR_UNSUPPORTED_HASH_TYPE), None)
def _get_ioc_type(self, ioc, action_result):
if util.is_ip(ioc):
return (phantom.APP_SUCCESS, "ipv4")
ip = UnicodeDammit(ioc).unicode_markup.encode('UTF-8').decode('UTF-8')
try:
ipv6_type = None
ipv6_type = ipaddress.IPv6Address(ip)
if ipv6_type:
return (phantom.APP_SUCCESS, "ipv6")
except Exception:
pass
if util.is_hash(ioc):
return self._get_hash_type(ioc, action_result)
if util.is_domain(ioc):
return (phantom.APP_SUCCESS, "domain")
return action_result.set_status(phantom.APP_ERROR, "Failed to detect the IOC type")
def _check_data(self, action_result, param, max_limit=None, sort_data=None):
limit = self._validate_integers(action_result, param.get('limit', 50), 'limit')
if limit is None:
return action_result.get_status()
if max_limit is not None:
if limit > max_limit:
limit = max_limit
param['limit'] = limit
if param.get('sort') == "--":
param['sort'] = None
if sort_data is not None:
if param.get('sort') and param.get('sort') != "--":
if param.get('sort') not in sort_data:
return action_result.set_status(phantom.APP_ERROR, "Please provide a valid value in the 'sort' parameter")
return action_result.set_status(phantom.APP_SUCCESS)
def _save_results(self, results, param):
reused_containers = 0
containers_processed = 0
for i, result in enumerate(results):
self.send_progress("Adding event artifact # {0}".format(i))
# result is a dictionary of a single container and artifacts
if 'container' not in result:
self.debug_print("Skipping empty container # {0}".format(i))
continue
if 'artifacts' not in result:
# ignore containers without artifacts
self.debug_print("Skipping container # {0} without artifacts".format(i))
continue
if len(result['artifacts']) == 0:
# ignore containers without artifacts
self.debug_print("Skipping container # {0} with 0 artifacts".format(i))
continue
config = self.get_config()
time_interval = config.get('merge_time_interval', 0)
if 'artifacts' not in result:
continue
artifacts = result['artifacts']
container = result['container']
container['artifacts'] = artifacts
if hasattr(self, '_preprocess_container'):
try:
container = self._preprocess_container(container)
except Exception as e:
self.debug_print('Preprocess error: {}'.format(self._get_error_message_from_exception(e)))
artifacts = container.pop('artifacts', [])
ret_val, container_id = self._check_for_existing_container(
container, time_interval, config.get('collate')
)
if not container_id:
ret_val, response, container_id = self.save_container(container)
self.debug_print("save_container returns, value: {0}, reason: {1}, id: {2}".format(ret_val, response, container_id))
if phantom.is_fail(ret_val):
self.debug_print("Error occurred while creating a new container")
continue
else:
reused_containers += 1
# get the length of the artifact, we might have trimmed it or not
len_artifacts = len(artifacts)
# Always set the very first artifact to run_automation = True to never have duplicate conflicts
if len_artifacts >= 1:
artifacts[0]['run_automation'] = True
# Useful for spawn.log file analysis
for artifact in artifacts:
artifact['container_id'] = container_id
ret_val, status_string, artifact_ids = self.save_artifacts(artifacts)
self.debug_print("save_artifacts returns, value: {0}, reason: {1}".format(ret_val, status_string))
self.debug_print("Container with id: {0}".format(container_id))
if phantom.is_fail(ret_val):
self.debug_print("Error occurred while adding {} artifacts to container: {}".format(len_artifacts, container_id))
containers_processed += 1
if reused_containers and config.get('collate'):
self.save_progress("Some containers were re-used due to collate set to True")
return containers_processed
def _paginator(self, action_result, endpoint, param):
"""
This action is used to create an iterator that will paginate through responses from called methods.
:param method_name: Name of method whose response is to be paginated
:param action_result: Object of ActionResult class
:param **kwargs: Dictionary of Input parameters
"""
list_ids = list()
limit = None
if param.get('limit'):
limit = int(param.pop('limit'))
offset = param.get('offset', 0)
while True:
param.update({"offset": offset})
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, params=param)
if phantom.is_fail(ret_val):
return None
prev_offset = offset
offset = response.get('meta', {}).get("pagination", {}).get("offset")
if offset == prev_offset:
offset += len(response.get('resources', []))
# Fetching total from the response
total = response.get('meta', {}).get("pagination", {}).get("total")
if len(response.get('errors', [])):
error = response.get('errors')[0]
action_result.set_status(
phantom.APP_ERROR, "Error occurred in results:\r\nCode: {}\r\nMessage: {}".format(error.get('code'), error.get('message')))
return None
if offset is None or total is None:
action_result.set_status(
phantom.APP_ERROR, "Error occurred in fetching 'offset' and 'total' key-values while fetching paginated results")
return None
if response.get("resources"):
list_ids.extend(response.get("resources"))
if limit and len(list_ids) >= int(limit):
return list_ids[:int(limit)]
if self.get_action_identifier() in ['detonate_file', 'detonate_url']:
if total == 0:
self._required_detonation = True
if offset >= total:
return list_ids
return list_ids
def _hunt_paginator(self, action_result, endpoint, params):
list_ids = list()
offset = ''
limit = None
if params.get('limit'):
limit = params.pop('limit')
while True:
params.update({"offset": offset})
params.update({"limit": 100})
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, params=params)
if phantom.is_fail(ret_val):
if CROWDSTRIKE_STATUS_CODE_CHECK_MESSAGE in action_result.get_message():
return []
return None
offset = response.get('meta', {}).get('pagination', {}).get('offset')
if len(response.get('errors', [])):
error = response.get('errors')[0]
action_result.set_status(
phantom.APP_ERROR, "Error occurred in results:\r\nCode: {}\r\nMessage: {}".format(error.get('code'), error.get('message')))
return None
if response.get("resources"):
list_ids.extend(response.get("resources"))
if limit and len(list_ids) >= limit:
return list_ids[:limit]
if (not offset) and (not response.get('meta', {}).get("pagination", {}).get("next_page")):
return list_ids
def _handle_test_connectivity(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
# initially set the token for first time
ret_val = self._get_token(action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
if not param:
param = {}
param.update({'limit': 1})
ret_val, resp_json = self._make_rest_call_helper_oauth2(action_result, CROWDSTRIKE_GET_DEVICE_ID_ENDPOINT, params=param)
if phantom.is_fail(ret_val):
self.save_progress(CROWDSTRIKE_ERR_CONNECTIVITY_TEST)
return phantom.APP_ERROR
self.save_progress("Test connectivity passed")
return action_result.set_status(phantom.APP_SUCCESS, CROWDSTRIKE_SUCC_CONNECTIVITY_TEST)
def _get_ids(self, action_result, endpoint, param, is_str=True):
id_list = self._paginator(action_result, endpoint, param)
if id_list is None:
return id_list
if is_str:
id_list = list(map(str, id_list))
return id_list
def _get_details(self, action_result, endpoint, param, method='get'):
list_ids = param.get("ids")
list_ids_details = list()
while list_ids:
param = {"ids": list_ids[:min(100, len(list_ids))]}
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, json=param, method=method)
if phantom.is_fail(ret_val):
return None
if response.get("resources"):
list_ids_details.extend(response.get("resources"))
del list_ids[:min(100, len(list_ids))]
return list_ids_details
def _get_devices_ran_on(self, ioc, ioc_type, param, action_result):
api_data = {
"type": ioc_type,
"value": ioc
}
limit = self._validate_integers(action_result, param.get('limit', 100), 'limit')
if limit is None:
return action_result.get_status()
api_data['limit'] = limit
count_only = param.get(CROWDSTRIKE_JSON_COUNT_ONLY, False)
response = self._hunt_paginator(action_result, CROWDSTRIKE_GET_DEVICES_RAN_ON_APIPATH, params=api_data)
if response is None:
return action_result.get_status()
if count_only:
action_result.update_summary({'device_count': len(response)})
return action_result.set_status(phantom.APP_SUCCESS)
# successful request / "none found"
for device_id in response:
action_result.add_data({"device_id": device_id})
action_result.set_summary({"device_count": len(response)})
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_resolve_detection(self, param):
# Add an action result to the App Run
action_result = self.add_action_result(ActionResult(dict(param)))
detection_id = param[CROWDSTRIKE_JSON_ID]
to_state = param[CROWDSTRIKE_RESOLVE_DETECTION_TO_STATE]
detection_id = [x.strip() for x in detection_id.split(',')]
detection_id = list(filter(None, detection_id))
api_data = {
"ids": detection_id,
"status": to_state
}
ret_val, response = self._make_rest_call_helper_oauth2(
action_result, CROWDSTRIKE_RESOLVE_DETECTION_APIPATH, json=api_data, method="patch")
if phantom.is_fail(ret_val):
return action_result.get_status()
return action_result.set_status(phantom.APP_SUCCESS, "Status set successfully")
def _paginate_get_endpoint(self, action_result, resource_id_list, endpoint, check_message=None, resource_data=None):
id_list = list()
id_list.extend(resource_id_list)
resource_details_list = list()
while id_list:
# Endpoint creation
ids = id_list[:min(100, len(id_list))]
endpoint_param = ''
for resource in ids:
endpoint_param += "ids={}&".format(resource)
endpoint_param = endpoint_param.strip("&")
endpoint = "{}?{}".format(endpoint, endpoint_param)
# Make REST call
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint)
if phantom.is_fail(ret_val) and check_message not in action_result.get_message():
self.debug_print('Error response returned from the API : {}'.format(endpoint))
return action_result.get_status()
if ret_val and response.get("resources"):
resource_details_list.extend(response.get("resources"))
del id_list[:min(100, len(id_list))]
if not resource_details_list:
return action_result.set_status(phantom.APP_SUCCESS, 'No data found')
resource_details_list = [i for n, i in enumerate(resource_details_list) if i not in resource_details_list[n + 1:]]
for item in resource_details_list:
action_result.add_data(item)
return action_result.set_status(phantom.APP_SUCCESS, "{} fetched successfully".format(resource_data))
def _handle_get_zta_data(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
agent_ids = param['agent_id']
agent_ids = [x.strip() for x in agent_ids.split(',')]
agent_ids = list(filter(None, agent_ids))
return self._paginate_get_endpoint(action_result, agent_ids, CROWDSTRIKE_GET_ZERO_TRUST_ASSESSMENT_ENDPOINT,
CROWDSTRIKE_STATUS_CODE_CHECK_MESSAGE, "Zero Trust Assessment data")
def _handle_hunt_file(self, param):
file_hash = param[phantom.APP_JSON_HASH]
action_result = self.add_action_result(ActionResult(dict(param)))
ret_val, ioc_type = self._get_hash_type(file_hash, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
return self._get_devices_ran_on(file_hash, ioc_type, param, action_result)
def _handle_hunt_domain(self, param):
domain = param[phantom.APP_JSON_DOMAIN]
action_result = self.add_action_result(ActionResult(dict(param)))
return self._get_devices_ran_on(domain, "domain", param, action_result)
def _handle_get_device_detail(self, param):
# Add an action result to the App Run
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
fdid = param[CROWDSTRIKE_GET_DEVICE_DETAIL_DEVICE_ID]
api_data = {
"ids": fdid
}
ret_val, response = self._make_rest_call_helper_oauth2(action_result, CROWDSTRIKE_GET_DEVICE_DETAILS_ENDPOINT, params=api_data)
if phantom.is_fail(ret_val) and CROWDSTRIKE_STATUS_CODE_CHECK_MESSAGE in action_result.get_message():
return action_result.set_status(phantom.APP_SUCCESS, CROWDSTRIKE_NO_DATA_MESSAGE)
if phantom.is_fail(ret_val):
return action_result.get_status()
# successful request
try:
data = dict(response["resources"][0])
except Exception:
return action_result.set_status(
phantom.APP_ERROR, "Error occurred while parsing response of 'get_system_info' action. Unknown response retrieved")
action_result.add_data(data)
summary = action_result.update_summary({})
try:
summary['hostname'] = response["resources"][0]['hostname']
except Exception:
pass
return action_result.set_status(phantom.APP_SUCCESS, "Device details fetched successfully")
def _handle_get_device_scroll(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
data = {
'offset': param.get('offset', None),
'limit': param.get('limit', None),
'sort': param.get('sort', None),
'filter': param.get('filter', None),
}
# More info on the endpoint at https://assets.falcon.crowdstrike.com/support/api/swagger.html#/hosts/QueryDevicesByFilterScroll
ret_val, response = self._make_rest_call_helper_oauth2(
action_result, CROWDSTRIKE_GET_DEVICE_SCROLL_ENDPOINT, params=data)
if phantom.is_fail(ret_val):
return action_result.set_status(phantom.APP_ERROR, "Failed to fetch device scroll", response)
action_result.add_data(response)
self.debug_print('Successfully fetched device scroll with response {0}'.format(response))
return action_result.set_status(phantom.APP_SUCCESS, "Device scroll fetched successfully")
def _handle_get_process_detail(self, param):
# Add an action result to the App Run
action_result = self.add_action_result(ActionResult(dict(param)))
fpid = param.get(CROWDSTRIKE_GET_PROCESS_DETAIL_FALCON_PROCESS_ID, '')
api_data = {
"ids": fpid
}
ret_val, response = self._make_rest_call_helper_oauth2(action_result, CROWDSTRIKE_GET_PROCESS_DETAIL_APIPATH, params=api_data)
if phantom.is_fail(ret_val):
return action_result.get_status()
try:
data = dict(response["resources"][0])
except Exception:
return action_result.set_status(
phantom.APP_ERROR, "Error occurred while parsing response of 'get_process_detail' action. Unknown response retrieved")
action_result.add_data(data)
return action_result.set_status(phantom.APP_SUCCESS, "Process details fetched successfully")
def _handle_list_incidents(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
max_limit = None
sort_data = ["assigned_to.asc", "assigned_to.desc", "assigned_to_name.asc", "assigned_to_name.desc", "end.asc", "end.desc",
"modified_timestamp.asc", "modified_timestamp.desc", "name.asc", "name.desc", "sort_score.asc", "sort_score.desc",
"start.asc", "start.desc", "state.asc", "state.desc", "status.asc", "status.desc"]
resp = self._check_data(action_result, param, max_limit, sort_data)
if phantom.is_fail(resp):
return action_result.get_status()
endpoint = CROWDSTRIKE_LIST_INCIDENTS_ENDPOINT
id_list = self._get_ids(action_result, endpoint, param)
if id_list is None:
return action_result.get_status()
# Add the response into the data section
for id in id_list:
action_result.add_data(id)
summary = action_result.update_summary({})
summary['total_incidents'] = action_result.get_data_size()
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_list_incident_behaviors(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
max_limit = None
sort_data = ["--", "timestamp.asc", "timestamp.desc"]
resp = self._check_data(action_result, param, max_limit, sort_data)
if phantom.is_fail(resp):
return action_result.get_status()
endpoint = CROWDSTRIKE_LIST_BEHAVIORS_ENDPOINT
id_list = self._get_ids(action_result, endpoint, param)
if id_list is None:
return action_result.get_status()
# Add the response into the data section
for id in id_list:
action_result.add_data(id)
summary = action_result.update_summary({})
summary['total_incident_behaviors'] = action_result.get_data_size()
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_get_incident_details(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
ids = param.get("ids")
ids = [x.strip() for x in ids.split(',')]
ids = list(filter(None, ids))
data = {"ids": ids}
endpoint = CROWDSTRIKE_GET_INCIDENT_DETAILS_ID_ENDPOINT
details_list = self._get_details(action_result, endpoint, data, method='post')
if details_list is None:
return action_result.get_status()
for incident in details_list:
action_result.add_data(incident)
summary = action_result.update_summary({})
summary['total_incidents'] = action_result.get_data_size()
return action_result.set_status(phantom.APP_SUCCESS, "Incidents fetched: {}".format(len(details_list)))
def _handle_get_incident_behaviors(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
ids = param.get("ids")
ids = [x.strip() for x in ids.split(',')]
ids = list(filter(None, ids))
data = {"ids": ids}
endpoint = CROWDSTRIKE_GET_INCIDENT_BEHAVIORS_ID_ENDPOINT
details_list = self._get_details(action_result, endpoint, data, 'post')
if details_list is None:
return action_result.get_status()
# Add the response into the data section
for incident_behavior in details_list:
action_result.add_data(incident_behavior)
return action_result.set_status(phantom.APP_SUCCESS, "Incident behavior fetched successfully")
def _handle_list_crowdscores(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
max_limit = None
sort_data = ["--", "score.asc", "score.desc", "timestamp.asc", "timestamp.desc"]
resp = self._check_data(action_result, param, max_limit, sort_data)
if phantom.is_fail(resp):
return action_result.get_status()
endpoint = CROWDSTRIKE_LIST_CROWDSCORES_ENDPOINT
id_list = self._get_ids(action_result, endpoint, param, is_str=False)
if id_list is None:
return action_result.get_status()
# Add the response into the data section
for crowdscore in id_list:
action_result.add_data(crowdscore)
summary = action_result.update_summary({})
summary['total_crowdscores'] = action_result.get_data_size()
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_update_incident(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
# Hold the values for the status
statuses = {"new": 20, "reopened": 25, "in progress": 30, "closed": 40}
ids = param.get("ids")
ids = [x.strip() for x in ids.split(',')]
ids = list(filter(None, ids))
# Default data we will send
data = {"action_parameters": [], "ids": ids}
if param.get("add_tag"):
add_tags = param.get("add_tag")
add_tags = [x.strip() for x in add_tags.split(',')]
add_tags = list(filter(None, add_tags))
for tag in add_tags:
data["action_parameters"].append({"name": "add_tag", "value": tag})
if param.get("delete_tag"):
delete_tags = param.get("delete_tag")
delete_tags = [x.strip() for x in delete_tags.split(',')]
delete_tags = list(filter(None, delete_tags))
for tag in delete_tags:
data["action_parameters"].append({"name": "delete_tag", "value": tag})
if param.get("update_name"):
name = param.get("update_name")
data["action_parameters"].append({"name": "update_name", "value": name})
if param.get("update_description"):
description = param.get("update_description")
data["action_parameters"].append({"name": "update_description", "value": description})
data_list = ["New", "Reopened", "In Progress", "Closed"]
if param.get('update_status'):
if param.get('update_status') not in data_list:
return action_result.set_status(phantom.APP_ERROR, "Please provide a valid value in the 'update_status' parameter")
status = param.get("update_status").lower()
data["action_parameters"].append({"name": "update_status", "value": str(statuses[status])})
if param.get("add_comment"):
comment = param.get("add_comment")
data["action_parameters"].append({"name": "add_comment", "value": comment})
endpoint = CROWDSTRIKE_UPDATE_INCIDENT_ENDPOINT
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, json=data, method="post")
if phantom.is_fail(ret_val):
return action_result.get_status()
# Add the response into the data section
action_result.add_data(response)
return action_result.set_status(phantom.APP_SUCCESS, "Incident updated successfully")
def _handle_list_users(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
# Get all the UIDS from your Customer ID
endpoint = CROWDSTRIKE_LIST_USERS_UIDS_ENDPOINT
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint)
if phantom.is_fail(ret_val):
return action_result.get_status()
if not response.get('resources', []):
return action_result.set_status(phantom.APP_SUCCESS, "No data found for user resources")
params = {'ids': response.get('resources', [])}
endpoint = CROWDSTRIKE_GET_USER_INFO_ENDPOINT
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, params=params)
if phantom.is_fail(ret_val):
return action_result.get_status()
# Add the response into the data section
action_result.add_data(response)
return action_result.set_status(phantom.APP_SUCCESS, "Users listed successfully")
def _handle_get_user_roles(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
params = {"user_uuid": param["user_uuid"]}
endpoint = CROWDSTRIKE_GET_USER_ROLES_ENDPOINT
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint, params=params)
if phantom.is_fail(ret_val):
return action_result.get_status()
# Add the response into the data section
action_result.add_data(response)
return action_result.set_status(phantom.APP_SUCCESS, "User roles fetched successfully")
def _handle_get_role(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
list_ids = param.get("role_id")
list_ids = [x.strip() for x in list_ids.split(',')]
list_ids = list(filter(None, list_ids))
return self._paginate_get_endpoint(action_result, list_ids, CROWDSTRIKE_GET_ROLE_ENDPOINT, CROWDSTRIKE_STATUS_CODE_MESSAGE, "Role")
def _handle_list_roles(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
# Get all the Roles from your Customer ID
endpoint = CROWDSTRIKE_LIST_USER_ROLES_ENDPOINT
ret_val, response = self._make_rest_call_helper_oauth2(action_result, endpoint)
if phantom.is_fail(ret_val):
return action_result.get_status()
# Create the param variable to send
params = {'ids': response['resources']}