forked from metron-labs/cybereason
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cybereason_connector.py
1168 lines (937 loc) · 48.2 KB
/
cybereason_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: cybereason_connector.py
#
# 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.
# Python 3 Compatibility imports
from __future__ import print_function, unicode_literals
import json
import traceback
import phantom.app as phantom
import requests
from bs4 import BeautifulSoup
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
# Usage of the consts file is recommended
from cybereason_consts import *
from cybereason_poller import CybereasonPoller
from cybereason_query_actions import CybereasonQueryActions
from cybereason_session import CybereasonSession
try:
from urllib import unquote
except:
from urllib.parse import unquote
class RetVal(tuple):
def __new__(cls, val1, val2=None):
return tuple.__new__(RetVal, (val1, val2))
class CybereasonConnector(BaseConnector):
def __init__(self):
# Call the BaseConnectors init first
super(CybereasonConnector, self).__init__()
self._state = {}
# 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
def _get_string_param(self, param):
return param
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", "title"]):
element.extract()
soup.prettify()
error_text = soup.get_text(separator="\n")
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:
error_text = "Cannot parse error details"
message = "Status Code: {0}. Data from server:\n{1}\n".format(status_code, error_text)
message = unquote(message)
message = message.replace('{', '{{').replace('}', '}}')
return RetVal(action_result.set_status(phantom.APP_ERROR, message), None)
def _process_response(self, r, action_result):
# Process an HTML response
if 'html' in r.headers.get('Content-Type', ''):
return self._process_html_response(r, action_result)
# everything else is actually an error at this point
message = "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, message), None)
def _get_error_message_from_exception(self, e):
""" This method is used to get appropriate error messages from the exception.
:param e: Exception object
:return: error message
"""
error_code = ERR_CODE_MSG
error_msg = ERR_MSG_UNAVAILABLE
try:
if 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:
pass
return "Error Code: {0}. Error Message: {1}".format(error_code, error_msg)
def _validate_integer(self, action_result, parameter, key):
if parameter is not None:
try:
if not float(parameter).is_integer():
return action_result.set_status(phantom.APP_ERROR, INVALID_INTEGER_ERR_MSG.format(key)), None
parameter = int(parameter)
except:
return action_result.set_status(phantom.APP_ERROR, INVALID_INTEGER_ERR_MSG.format(key)), None
if parameter < 0:
return action_result.set_status(phantom.APP_ERROR, INVALID_NON_NEGATIVE_INTEGER_ERR_MSG.format(key)), None
return phantom.APP_SUCCESS, parameter
def _handle_test_connectivity(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)))
# Set up a session by logging in to the Cybereason console.
cr_session = CybereasonSession(self)
cookies = cr_session.get_session_cookies()
if cookies.get("JSESSIONID"):
# We have a session id cookie, so the authentication succeeded
self.save_progress('Successfully connected to the Cybereason console and verified session cookie')
return action_result.set_status(
phantom.APP_SUCCESS,
'Successfully connected to the Cybereason console and verified session cookie'
)
else:
self.debug_print('Failure to verify session cookie.')
return action_result.set_status(
phantom.APP_ERROR,
'Connectivity failed. Unable to get session cookie from Cybereason console'
)
def _get_delete_registry_key_body(self, cr_session, malop_id, machine_name, action_result):
query = {
"queryPath": [
{
"requestedType": "MalopProcess",
"filters": [],
"guidList": [malop_id],
"connectionFeature": { "elementInstanceType": "MalopProcess", "featureName": "suspects" }
},
{
"requestedType": "Process",
"filter": [],
"isResult": True
}
],
"totalResultLimit": 100,
"perGroupLimit": 100,
"perFeatureLimit": 100,
"templateContext": "SPECIFIC",
"queryTimeout": 120000,
"customFields": [ "ownerMachine", "hasAutorunEvidence" ]
}
url = "{0}/rest/visualsearch/query/simple".format(self._base_url)
res = cr_session.post(url=url, json=query, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
return self._process_response(res, action_result)
results = res.json()
remediate_body = {
"malopId": malop_id,
"actionsByMachine": {},
"initiatorUserName": ""
}
target_ids_added = set()
for _, process_data in results["data"]["resultIdToElementDataMap"].items():
if process_data["elementValues"].get("hasAutorunEvidence"):
target_id = process_data["elementValues"]["hasAutorunEvidence"]["elementValues"][0]["guid"]
matching_machines = list(
filter(
lambda machine: machine["name"].lower(
) == machine_name, process_data["elementValues"]["ownerMachine"]["elementValues"]
)
)
if len(matching_machines) > 0:
machine_id = matching_machines[0]["guid"]
if not remediate_body["actionsByMachine"].get(machine_id):
remediate_body["actionsByMachine"][machine_id] = []
if target_id not in target_ids_added:
remediate_body["actionsByMachine"][machine_id].append({
"targetId": target_id,
"actionType": "DELETE_REGISTRY_KEY"
})
target_ids_added.add(target_id)
return RetVal(phantom.APP_SUCCESS, remediate_body)
def _handle_delete_registry_key(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)))
malop_id = self._get_string_param(param['malop_id'])
machine_name = param["machine_name"].lower()
# Get the remediation target
cr_session = CybereasonSession(self).get_session()
try:
ret_val, remediate_body = self._get_delete_registry_key_body(cr_session, malop_id, machine_name, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
# Make the call to remediate the action
res = cr_session.post("{0}/rest/remediate".format(self._base_url), json=remediate_body, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
result = res.json()
action_result.add_data({
"remediation_id": result["remediationId"],
"initiating_user": result["initiatingUser"]
})
except Exception as e:
err = self._get_error_message_from_exception(e)
self.debug_print("Error occurred: {}".format(err))
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_get_sensor_status(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)))
malop_id = self._get_string_param(param['malop_id'])
try:
# Set up a session by logging in to the Cybereason console.
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/visualsearch/query/simple".format(self._base_url)
post_data = {
"queryPath": [
{
"requestedType": "MalopProcess",
"filters": [],
"guidList": [
malop_id
],
"connectionFeature": {
"elementInstanceType": "MalopProcess",
"featureName": "suspects"
}
},
{
"requestedType": "Process",
"filters": [],
"connectionFeature": {
"elementInstanceType": "Process",
"featureName": "ownerMachine"
}
},
{
"requestedType": "Machine",
"filters": [],
"isResult": True
}
],
"totalResultLimit": 1000,
"perGroupLimit": 1200,
"perFeatureLimit": 1200,
"templateContext": "SPECIFIC",
"queryTimeout": 30,
"customFields": [
"isConnected",
"elementDisplayName"
]
}
res = cr_session.post(url=url, headers=self._headers, json=post_data)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
self.save_progress("Successfully fetched machine details from Cybereason console")
machines_dict = res.json()["data"]["resultIdToElementDataMap"]
for machine_id, machine_details in machines_dict.items():
action_result.add_data({
"machine_id": machine_id,
"machine_name": machine_details["simpleValues"]["elementDisplayName"]["values"][0],
"status": "Online" if machine_details["simpleValues"]["isConnected"]["values"][0] == "true" else "Offline"
})
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_add_malop_comment(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)))
malop_id = self._get_string_param(param['malop_id'])
self.save_progress("MALOP ID :{0}".format(malop_id))
comment = param.get('comment', "")
self.save_progress("COMMENT :{0}".format(comment))
try:
cr_session = CybereasonSession(self).get_session()
endpoint_url = "/rest/crimes/comment/"
url = "{0}{1}{2}".format(self._base_url, endpoint_url, str(malop_id))
self.save_progress("Add malop comment URL: {}".format(url))
res = cr_session.post(url, data=comment.encode('utf-8'), headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
except requests.exceptions.ConnectionError:
err = "Error Details: Connection refused from the server"
return action_result.set_status(phantom.APP_ERROR, err)
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS, "Add malop comment action executed successfully")
def _handle_update_malop_status(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)))
malop_id = self._get_string_param(param['malop_id'])
soar_status = param['status']
cybereason_status = SOAR_TO_CYBEREASON_STATUS.get(soar_status)
if not cybereason_status:
self.save_progress("Invalid status selected")
return action_result.set_status(
phantom.APP_ERROR,
"Invalid status. Please provide a valid value in the 'status' action parameter"
)
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/crimes/status".format(self._base_url)
self.save_progress("Update malop status URL: {}".format(url))
query = json.dumps({malop_id: cybereason_status})
res = cr_session.post(url, data=query, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS, "Update malop status action executed successfully")
def _handle_isolate_machine(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)))
malop_id = self._get_string_param(param['malop_id'])
ret_val, sensor_ids = self._get_malop_sensor_ids(malop_id, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/monitor/global/commands/isolate".format(self._base_url)
self.save_progress("Isolate machine URL: {}".format(url))
query = json.dumps({"pylumIds": sensor_ids, "malopId": malop_id})
res = cr_session.post(url, data=query, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_unisolate_machine(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)))
malop_id = self._get_string_param(param['malop_id'])
ret_val, sensor_ids = self._get_malop_sensor_ids(malop_id, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/monitor/global/commands/un-isolate".format(self._base_url)
self.save_progress("Unisolate machine URL: {}".format(url))
query = json.dumps({"pylumIds": sensor_ids, "malopId": malop_id})
res = cr_session.post(url, data=query, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_isolate_specific_machine(self, param):
"""
Isolate the machine with specified name or ip. The machine with the id provided as parameter will be
disconnected from the network
Parameters:
param: object containing either the machine name or ip
Returns:
Action results
"""
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)))
machine_name_or_ip = self._get_string_param(param['machine_name_or_ip'])
ret_val, sensor_ids = self._get_machine_sensor_ids(machine_name_or_ip, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/monitor/global/commands/isolate".format(self._base_url)
self.save_progress("Isolate specific machine URL: {}".format(url))
query = json.dumps({"pylumIds": sensor_ids})
res = cr_session.post(url, data=query, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
action_result.add_data({
"response_code_from_server": res.status_code,
"response_from_server": res.json()
})
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_unisolate_specific_machine(self, param):
"""
Un-isolate the machine with specified Name or IP. The machine with the id provided as parameter will be
connected to the network again.
Parameters:
param: object containing either the machine name or IP
Returns:
Action results
"""
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)))
machine_name_or_ip = self._get_string_param(param.get('machine_name_or_ip'))
ret_val, sensor_ids = self._get_machine_sensor_ids(machine_name_or_ip, action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/monitor/global/commands/un-isolate".format(self._base_url)
self.save_progress("Unisolate specific machine URL: {}".format(url))
query = json.dumps({"pylumIds": sensor_ids})
res = cr_session.post(url, data=query, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
action_result.add_data({
"response_code_from_server": res.status_code,
"response_from_server": res.json()
})
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_kill_process(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)))
malop_id = self._get_string_param(param["malop_id"])
machine_id = self._get_string_param(param["machine_id"])
remediation_user = param["remediation_user"]
process_id = self._get_string_param(param["process_id"])
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/remediate".format(self._base_url)
query = {
"malopId": malop_id,
"initiatorUserName": remediation_user,
"actionsByMachine": {
machine_id: [
{
"targetId": process_id,
"actionType": "KILL_PROCESS"
}
]
}
}
res = cr_session.post(url, json=query, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
result = res.json()
if len(result["statusLog"]) > 0:
action_result.add_data({
"remediation_id": result["remediationId"],
"remediation_status": result["statusLog"][0]["status"]
})
except Exception as e:
err = self._get_error_message_from_exception(e)
self.debug_print(err)
self.debug_print(traceback.format_exc())
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_get_remediation_status(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)))
malop_id = self._get_string_param(param["malop_id"])
remediation_user = param["remediation_user"]
remediation_id = param["remediation_id"]
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/remediate/progress/{1}/{2}/{3}".format(self._base_url, remediation_user, malop_id, remediation_id)
res = cr_session.get(url)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
result = res.json()
status_log_length = len(result["statusLog"])
error_obj = result["statusLog"][status_log_length - 1]["error"]
action_result.add_data({
"remediation_status": result["statusLog"][status_log_length - 1]["status"],
"remediation_message": error_obj.get("message", "Unknown error") if error_obj is not None else "No error message"
})
except requests.exceptions.ConnectionError:
err = "Error Details: Connection refused from the server"
return action_result.set_status(phantom.APP_ERROR, err)
except Exception as e:
err = self._get_error_message_from_exception(e)
self.debug_print(err)
self.debug_print(traceback.format_exc())
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_set_reputation(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)))
reputation_item = self._get_string_param(param.get('reputation_item_hash'))
custom_reputation = param.get('custom_reputation')
if custom_reputation not in CUSTOM_REPUTATION_LIST:
return action_result.set_status(
phantom.APP_ERROR,
"Please provide a valid value for the 'custom_reputation' action parameter"
)
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/classification/update".format(self._base_url)
self.save_progress("Set reputation URL: {}".format(url))
if custom_reputation == 'remove':
reputation = json.dumps([{"keys": [reputation_item], "maliciousType": None, "prevent": False, "remove": True}])
else:
reputation = json.dumps(
[{"keys": [reputation_item], "maliciousType": custom_reputation, "prevent": False, "remove": False}]
)
res = cr_session.post(url, data=reputation, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
self.save_progress("{0}ed...".format(custom_reputation))
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS, "Set reputation action executed successfully")
def _get_malop_sensor_ids(self, malop_id, action_result):
sensor_ids = []
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/visualsearch/query/simple".format(self._base_url)
self.save_progress("Get malop sensor IDs URL: {}".format(url))
query_path = {
"queryPath": [
{
"requestedType": "MalopProcess",
"filters": [],
"guidList": [
malop_id
],
"connectionFeature": {
"elementInstanceType": "MalopProcess",
"featureName": "suspects"
}
},
{
"requestedType": "Process",
"filters": [],
"connectionFeature": {
"elementInstanceType": "Process",
"featureName": "ownerMachine"
}
},
{
"requestedType": "Machine",
"filters": [],
"isResult": True
}
],
"totalResultLimit": 1000,
"perGroupLimit": 1200,
"perFeatureLimit": 1200,
"templateContext": "SPECIFIC",
"queryTimeout": None,
"customFields": [
"pylumId",
"elementDisplayName"
]
}
self.save_progress(str(query_path))
res = cr_session.post(url, json=query_path, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
return self._process_response(res, action_result)
self.save_progress("Got result from /rest/visualsearch/query/simple")
machines_dict = res.json()["data"]["resultIdToElementDataMap"]
for _, machine_details in machines_dict.items():
sensor_ids.append(str(machine_details['simpleValues']['pylumId']['values'][0]))
except Exception as e:
err = self._get_error_message_from_exception(e)
self.save_progress(err)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err)), None)
return RetVal(action_result.set_status(phantom.APP_SUCCESS), sensor_ids)
def _get_machine_sensor_ids(self, machine_name_or_ip, action_result):
sensor_ids = []
try:
ret_val, sensors_by_name = self._get_pylumid_by_machine_name(machine_name_or_ip, action_result)
if not (phantom.is_fail(ret_val) or len(sensors_by_name) == 0):
sensor_ids.extend(sensors_by_name)
ret_val, sensors_by_ip = self._get_pylumid_by_machine_ip(machine_name_or_ip, action_result)
if not (phantom.is_fail(ret_val) or len(sensors_by_ip) == 0):
sensor_ids.extend(sensors_by_ip)
action_result.add_data({
"sensor_ids_by_machine_ip": sensors_by_ip,
"sensor_ids_by_machine_name": sensors_by_name
})
except Exception as e:
err = self._get_error_message_from_exception(e)
self.save_progress(err)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err)), [])
return RetVal(action_result.set_status(phantom.APP_SUCCESS), sensor_ids)
def _get_pylumid_by_machine_name(self, machine_name, action_result):
sensor_ids = []
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/sensors/query".format(self._base_url)
self.save_progress("Sensors query URL: {}".format(url))
query_path = {
"limit": 1000,
"offset": 0,
"filters": [
{
"fieldName": "machineName",
"operator": "Equals",
"values": [machine_name]
}
]
}
self.save_progress("Calling {} with query {}".format(url, str(query_path)))
res = cr_session.post(url, json=query_path, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
return self._process_response(res, action_result)
self.save_progress("Got result from {}".format(url))
totalResults = res.json()["totalResults"]
if totalResults > 0:
sensors = res.json()["sensors"]
for sensor in sensors:
sensor_ids.append(sensor['pylumId'])
except Exception as e:
err = self._get_error_message_from_exception(e)
self.save_progress(err)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err)), [])
return RetVal(action_result.set_status(phantom.APP_SUCCESS), sensor_ids)
def _get_pylumid_by_machine_ip(self, machine_ip, action_result):
sensor_ids = []
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/sensors/query".format(self._base_url)
self.save_progress("Sensors query URL: {}".format(url))
query_path = {
"limit": 1000,
"offset": 0,
"filters": [
{
"fieldName": "externalIpAddress",
"operator": "Equals",
"values": [machine_ip]
}
]
}
self.save_progress("Calling {} with query {}".format(url, str(query_path)))
res = cr_session.post(url, json=query_path, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
return self._process_response(res, action_result)
self.save_progress("Got result from {}".format(url))
totalResults = res.json()["totalResults"]
if totalResults > 0:
sensors = res.json()["sensors"]
for sensor in sensors:
sensor_ids.append(sensor['pylumId'])
except Exception as e:
err = self._get_error_message_from_exception(e)
self.save_progress(err)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err)), [])
return RetVal(action_result.set_status(phantom.APP_SUCCESS), sensor_ids)
def _handle_upgrade_sensor(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 the parameters
pylum_id = self._get_string_param(param['pylumid'])
try:
# Create a session to call the rest APIs
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/sensors/action/upgrade".format(self._base_url)
self.save_progress("Upgrade sensor URL: {}".format(url))
pylum_ids = []
# Look for the multiple sensor ids
if "," in pylum_id:
filter_arr = pylum_id.strip().split(",")
filter_arr = [each_id.strip() for each_id in filter_arr]
pylum_ids.extend(filter_arr)
else:
pylum_ids.append(pylum_id)
query = json.dumps({
"filters": [
{
"fieldName": "pylumId",
"operator": "ContainsIgnoreCase",
"values": pylum_ids
}
]
})
res = cr_session.post(url, data=query, headers=self._headers)
if res.status_code == 204:
return action_result.set_status(
phantom.APP_ERROR,
"Status Code:204. The sensor names are incorrect or the filters are not valid"
)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
self.save_progress("Sensors Upgrade Requested")
json_res = res.json()
action_result.update_summary(json_res)
# Data will typically be the raw JSON if we need to use it in a playbook
action_result.add_data(json_res)
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS, "Successfully requested for sensor upgrade")
def _handle_restart_sensor(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 the parameters
pylum_id = self._get_string_param(param['pylumid'])
try:
# Create a session to call the rest APIs
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/sensors/action/restart".format(self._base_url)
self.save_progress("Restart sensor URL: {}".format(url))
pylum_ids = []
if "," in pylum_id:
filter_arr = pylum_id.strip().split(",")
filter_arr = [each_id.strip() for each_id in filter_arr]
pylum_ids.extend(filter_arr)
else:
pylum_ids.append(pylum_id)
query = json.dumps({
"filters": [
{
"fieldName": "pylumId",
"operator": "ContainsIgnoreCase",
"values": pylum_ids
}
]
})
res = cr_session.post(url, data=query, headers=self._headers)
if res.status_code == 204:
return action_result.set_status(
phantom.APP_ERROR,
"Status Code:204. The sensor names are incorrect or the filters are not valid"
)
if res.status_code < 200 or res.status_code >= 399:
self._process_response(res, action_result)
return action_result.get_status()
json_res = res.json()
self.save_progress("Sensors Restart Requested")
action_result.update_summary(json_res)
# Data will typically be the raw JSON if we need to use it in a playbook
action_result.add_data(json_res)
except Exception as e:
err = self._get_error_message_from_exception(e)
return action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err))
return action_result.set_status(phantom.APP_SUCCESS, "Successfully requested for sensor restart")
def _get_machine_name_by_machine_ip(self, machine_ip, action_result):
machine_names = []
try:
cr_session = CybereasonSession(self).get_session()
url = "{0}/rest/sensors/query".format(self._base_url)
self.save_progress("Sensors query URL: {}".format(url))
query_path = {
"limit": 1000,
"offset": 0,
"filters": [
{
"fieldName": "externalIpAddress",
"operator": "Equals",
"values": [machine_ip]
}
]
}
self.save_progress("Calling {} with query {}".format(url, str(query_path)))
res = cr_session.post(url, json=query_path, headers=self._headers)
if res.status_code < 200 or res.status_code >= 399:
return self._process_response(res, action_result)
self.save_progress("Got result from {}".format(url))
totalResults = res.json()["totalResults"]
if totalResults > 0:
sensors = res.json()["sensors"]
for sensor_details in sensors:
machine_names.append(str(sensor_details['machineName']))
except Exception as e:
err = self._get_error_message_from_exception(e)
self.save_progress(err)
return RetVal(action_result.set_status(phantom.APP_ERROR, "Error occurred. {}".format(err)), None)
return RetVal(action_result.set_status(phantom.APP_SUCCESS), machine_names)
def on_poll(self, param):
self.save_progress("Entered the on_poll function")
self.save_progress("processing")
poller = CybereasonPoller()
return poller.do_poll(self, param)
def _handle_query_processes(self, param):
self.save_progress("Entered the _handle_query_processes function")
self.save_progress("processing")
query_action = CybereasonQueryActions()
return query_action._handle_query_processes(self, param)
def _handle_query_machine(self, param):
self.save_progress("Entered the _handle_query_machine function")
self.save_progress("processing")
query_action = CybereasonQueryActions()
return query_action._handle_query_machine(self, param)
def _handle_query_machine_ip(self, param):
self.save_progress("Entered the _handle_query_machine_ip function")
self.save_progress("processing")
query_action = CybereasonQueryActions()
return query_action._handle_query_machine_ip(self, param)
def _handle_query_users(self, param):
self.save_progress("Entered the _handle_query_users function")
self.save_progress("processing")
query_action = CybereasonQueryActions()
return query_action._handle_query_users(self, param)
def _handle_query_files(self, param):
self.save_progress("Entered the _handle_query_files function")
self.save_progress("processing")
query_action = CybereasonQueryActions()
return query_action._handle_query_files(self, param)
def _handle_query_domain(self, param):
self.save_progress("Entered the _handle_query_domain function")
self.save_progress("processing")
query_action = CybereasonQueryActions()
return query_action._handle_query_domain(self, param)
def _handle_query_connections(self, param):
self.save_progress("Entered the _handle_query_connections function")
self.save_progress("processing")
query_action = CybereasonQueryActions()
return query_action._handle_query_connections(self, param)
def handle_action(self, param):
ret_val = phantom.APP_SUCCESS