forked from splunk-soar-connectors/trendmicrovisionone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrendmicrovisionone_connector.py
2160 lines (1778 loc) · 86.1 KB
/
trendmicrovisionone_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: trendmicrovisionone_connector.py
# Copyright (c) Trend Micro, 2022-2024
# 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 sys
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
import pytmv1
import requests
if TYPE_CHECKING:
from stubs import app as phantom
from stubs.action_result import ActionResult
from stubs.base_connector import BaseConnector
else:
from phantom import app as phantom
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
from phantom.vault import Vault
from phantom import vault
from pytmv1 import (
AccountTask,
AccountTaskResp,
BlockListTaskResp,
CollectFileTaskResp,
EmailMessageIdTask,
EmailMessageTaskResp,
EmailMessageUIdTask,
EndpointTask,
EndpointTaskResp,
ExceptionObject,
FileTask,
InvestigationStatus,
ObjectTask,
ObjectType,
ProcessTask,
ResultCode,
SaeAlert,
SuspiciousObject,
SuspiciousObjectTask,
TerminateProcessTaskResp,
TiAlert,
)
class RetVal(tuple):
def __new__(cls, val1, val2=None):
return tuple.__new__(RetVal, (val1, val2))
class TrendMicroVisionOneConnector(BaseConnector):
def __init__(self):
# Call the BaseConnectors init first
super(TrendMicroVisionOneConnector, self).__init__()
self._state: Dict[str, Any] = {}
self.config: Dict[str, Any] = {}
self.app = "Trend Vision One V3"
# 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: str = ""
self.supported_actions: Dict[str, Callable] = {
"on_poll": self._handle_on_poll,
"add_note": self._handle_add_note,
"status_check": self._handle_status_check,
"update_status": self._handle_update_status,
"enable_account": self._handle_enable_account,
"start_analysis": self._handle_start_analysis,
"disable_account": self._handle_disable_account,
"urls_to_sandbox": self._handle_urls_to_sandbox,
"sign_out_account": self._handle_sign_out_account,
"add_to_blocklist": self._handle_add_to_blocklist,
"add_to_exception": self._handle_add_to_exception,
"test_connectivity": self._handle_test_connectivity,
"get_endpoint_info": self._handle_get_endpoint_info,
"quarantine_device": self._handle_quarantine_device,
"terminate_process": self._handle_terminate_process,
"add_to_suspicious": self._handle_add_to_suspicious,
"get_alert_details": self._handle_get_alert_details,
"forensic_file_info": self._handle_forensic_file_info,
"get_exception_list": self._handle_get_exception_list,
"get_suspicious_list": self._handle_get_suspicious_list,
"unquarantine_device": self._handle_unquarantine_device,
"force_password_reset": self._handle_force_password_reset,
"delete_email_message": self._handle_delete_email_message,
"delete_from_exception": self._handle_delete_from_exception,
"remove_from_blocklist": self._handle_remove_from_blocklist,
"collect_forensic_file": self._handle_collect_forensic_file,
"restore_email_message": self._handle_restore_email_message,
"check_analysis_status": self._handle_check_analysis_status,
"delete_from_suspicious": self._handle_delete_from_suspicious,
"vault_sandbox_analysis": self._handle_vault_sandbox_analysis,
"sandbox_analysis_result": self._handle_sandbox_analysis_result,
"sandbox_suspicious_list": self._handle_sandbox_suspicious_list,
"download_analysis_report": self._handle_download_analysis_report,
"quarantine_email_message": self._handle_quarantine_email_message,
"sandbox_investigation_package": self._handle_sandbox_investigation_package,
}
def handle_exception(self, exception: BaseException):
error_result = ActionResult(self.get_current_param())
error_result.set_status(phantom.APP_ERROR)
error_result.add_exception_details(exception)
self.add_action_result(error_result)
def _get_client(self) -> pytmv1.Client:
return pytmv1.client(self.app, self.api_key, self._base_url)
@staticmethod
def _is_pytmv1_error(result_code: ResultCode) -> bool:
return result_code == ResultCode.ERROR
@staticmethod
def _get_ot_enum(obj_type: str) -> ObjectType:
if not obj_type.upper() in ObjectType.__members__:
raise RuntimeError(f"Please check object type: {obj_type}")
return ObjectType[obj_type.upper()]
@staticmethod
def get_task_type(action: str) -> Any:
task_dict: Dict[Any, List[str]] = {
AccountTaskResp: [
"enableAccount",
"disableAccount",
"forceSignOut",
"resetPassword",
],
BlockListTaskResp: ["block", "restoreBlock"],
EmailMessageTaskResp: [
"quarantineMessage",
"restoreMessage",
"deleteMessage",
],
EndpointTaskResp: ["isolate", "restoreIsolate"],
TerminateProcessTaskResp: ["terminateProcess"],
}
for key, values in task_dict.items():
if action in values:
return key
def _handle_test_connectivity(self, param):
"""
Makes a call to endpoint to check connectivity.
Args:
N/A
Returns:
str: Connectivity pass for fail.
"""
# Add an action result object to self (BaseConnector) to represent the action for this param
action_result = self.add_action_result(ActionResult(param))
# Initialize Pytmv1 client
client = self._get_client()
# Make rest call
response = client.check_connectivity()
if self._is_pytmv1_error(response.result_code):
self.debug_print("Please check your environment variables.")
self.save_progress("Test Connectivity Failed. Please check your environment variables.")
return action_result.get_status()
# Return success
self.save_progress("Test Connectivity Passed")
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_get_endpoint_info(self, param):
"""
Fetches information for an endpoint.
Args:
endpoint(str): endpoint to be queried
query_op(str): query operator ['and', 'or']
Returns:
List[Any]: Returns a list of objects containing information about an endpoint
"""
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(param))
# Required Params
endpoint = param["ip_hostname_mac"]
listify_endpoints = endpoint.split(",")
endpoint_list = [value.strip() for value in listify_endpoints]
query_op = param["query_op"]
# Initialize pytmv1
client = self._get_client()
# Choose QueryOp Enum based on user choice
if query_op.lower() == "or":
query_op = pytmv1.QueryOp.OR
elif query_op.lower() == "and":
query_op = pytmv1.QueryOp.AND
else:
raise RuntimeError(f"Please provide valid query operator: {query_op}")
new_endpoint_data: List[Any] = []
# Make rest call
try:
client.consume_endpoint_data(
lambda endpoint_data: new_endpoint_data.append(endpoint_data),
query_op,
*endpoint_list,
)
except Exception as e:
raise RuntimeError(f"Something went wrong while fetching endpoint data: {e}")
if len(new_endpoint_data) == 0:
self.save_progress(f"Endpoint lookup failed, please check endpoint name: {endpoint}")
return action_result.get_status()
# Load json objects to list
for endpoint in new_endpoint_data:
action_result.add_data(endpoint.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_quarantine_device(self, param):
"""
Action to isolate an endpoint.
Args:
endpoint_identifiers(List[Dict[str, str]]): Object containing Endpoint name and (optional) description.
Returns:
Dict[str, List[Any]]: Returns a list of objects containing task_id and HTTP status code
"""
# send progress messages back to the platform
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(param))
# Required Params
endpoint_identifiers: List[Dict[str, str]] = json.loads(param["endpoint_identifiers"])
# Initialize Pytmv1
client = self._get_client()
endpt_tasks: List[EndpointTask] = []
# Create endpoint task list
for endpt in endpoint_identifiers:
if endpt.get("endpoint"):
endpt_tasks.append(
EndpointTask(
endpoint_name=endpt["endpoint"],
description=endpt.get("description", "Quarantine Device"),
)
)
elif endpt.get("agent_guid"):
endpt_tasks.append(
EndpointTask(
agent_guid=endpt["agent_guid"],
description=endpt.get("description", "Quarantine Device"),
) # type: ignore
)
# Make rest call
response = client.isolate_endpoint(*endpt_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please check endpoint params.")
raise RuntimeError(f"Error quarantining endpoint: {response.errors}")
assert response.response is not None
# Add the response into the data section
for item in response.response.items:
action_result.add_data(item.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_unquarantine_device(self, param):
"""
Action to restore endpoint.
Args:
endpoint_identifiers(List[Dict[str, str]]): endpoint name and optional description.
Returns:
multi_resp(Dict[str,Any]): Object containing task_id and HTTP status code.
"""
# send progress messages back to the platform
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(param))
# Required Params
endpoint_identifiers: List[Dict[str, str]] = json.loads(param["endpoint_identifiers"])
# Initialize Pytmv1
client = self._get_client()
endpt_tasks: List[EndpointTask] = []
# Create endpoint task list
for endpt in endpoint_identifiers:
if endpt.get("endpoint"):
endpt_tasks.append(
EndpointTask(
endpoint_name=endpt["endpoint"],
description=endpt.get("description", "Unquarantine Device"),
)
)
elif endpt.get("agent_guid"):
endpt_tasks.append(
EndpointTask(
agent_guid=endpt["agent_guid"],
description=endpt.get("description", "Unquarantine Device"),
) # type: ignore
)
# Make rest call
response = client.restore_endpoint(*endpt_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please check endpoint params.")
raise RuntimeError(f"Error quarantining endpoint: {response.errors}")
assert response.response is not None
# Add the response into the data section
for item in response.response.items:
action_result.add_data(item.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _create_new_artifact_from_alert(self, container_id: int, alert: Union[SaeAlert, TiAlert]):
"""
Create a new artifact from alert.
Args:
container_id (int): ID that will be used to query for containers
alert (Union[SaeAlert, TiAlert]): SAEAlert or TiAlert object
Raises:
RuntimeError: Raise error if artifact creation encounters a problem
"""
# if artifacts doesn't already exist, make new artifact bundles
if self.artifact_exists(container_id, alert.id):
return
new_artifact = self._create_artifact_content(container_id, alert)
ret_val, msg, response = self.save_artifacts([new_artifact])
if phantom.is_fail(ret_val):
self.save_progress(f"Error saving artifacts: {msg}")
raise RuntimeError(f"Error saving artifacts: {[new_artifact]}")
@staticmethod
def create_artifact_identifier(alert_id: str) -> str:
"""
Returns string artifact identifier.
Args:
alert_id (str): Alert ID.
Returns:
str: Artifact identifier string.
"""
return f"TM-{alert_id}"
def _create_artifact_content(self, container_id: int, alert: Union[SaeAlert, TiAlert]):
"""
Gathers information and adds to artifact.
Args:
container_id (int): Container ID.
alert (Union[SaeAlert, TiAlert]): Type of alert (SaeAlert or TiAlert).
Returns:
dict[str, Any]: Artifact object.
"""
# Use pytmv1 mapper to populate artifact cef
art_cef = pytmv1.mapper.map_cef(alert)
return {
"name": alert.id,
"label": "ALERT",
"container_id": container_id,
"source_data_identifier": self.create_artifact_identifier(alert.id),
"type": alert.alert_provider,
"severity": alert.severity.value,
"start_time": alert.created_date_time,
"indicators": [ind.dict() for ind in alert.indicators],
"cef": art_cef,
}
def _update_container_metadata(self, container_id: int, alert: Union[SaeAlert, TiAlert]):
"""
Updates an Alert container.
Args:
container_id (int): ID for the container.
alert (Union[SaeAlert, TiAlert]): SaeAlert or TiAlert
Raises:
RuntimeError: Raise a runtime error if container update fails.
"""
# update old container
container_alert_metadata: Dict[str, Any] = {
"data": alert.dict(),
"description": "{}: {}".format(container_id, alert.alert_provider.value),
}
try:
requests.post(
f"{self.get_phantom_base_url()}rest/container/{container_id}",
data=json.dumps(container_alert_metadata),
verify=False,
timeout=30,
) # nosemgrep
except Exception as e:
raise RuntimeError("Encountered an error updateding container alert.") from e
def artifact_exists(self, container_id: int, alert_id: str):
"""
Makes a rest call to see if the artifact exists or not.
Args:
container_id (int): Container ID to filter.
alert_id (str): Alert ID.
Returns:
ID: Returns an ID or None if no ID exists.
"""
# Fetch the source data identifier
sdi = self.create_artifact_identifier(alert_id)
# check if a given artifact exists for in a container
url = f'{self.get_phantom_base_url()}rest/artifact?_filter_source_data_identifier="{sdi}"&_filter_container_id={container_id}'
# Make rest call
try:
self.debug_print(f"Making request on url: {url}")
response = requests.get(url, verify=False, timeout=30) # nosemgrep
except Exception:
return None
# return id or None
if response.json().get("data", None):
return response.json().get("data", None)[0].get("id", None)
else:
return None
def _get_existing_container_id_for_sdi(self, sdi: str) -> Optional[int]:
"""
Fetch container ID if it exists.
Args:
alert (Union[SaeAlert, TiAlert]): SaeAlert or TiAlert.
Raises:
RuntimeError: Raise an error if REST call fails.
Returns:
ID: Return the container ID.
"""
# check if TM workbenchID already exists in Splunk
url = f'{self.get_phantom_base_url()}rest/container?_filter_source_data_identifier="{sdi}"&_filter_asset={self.get_asset_id()}'
# Make rest call
try:
response = requests.get(url, verify=False, timeout=30) # nosemgrep
except Exception as e:
raise RuntimeError("Encountered an error getting the existing container ID from Phantom.") from e
# return id or None
container_data: dict[str, Any] = response.json()
if "data" not in container_data or len(container_data["data"]) == 0:
return None
# This direct access is okay because the values MUST exist otherwise the problem is out of scope.
return container_data["data"][0]["id"]
def _get_existing_container_id_for_alert(self, alert: Union[SaeAlert, TiAlert]) -> Optional[int]:
"""
Fetch container ID if it exists.
Args:
alert (Union[SaeAlert, TiAlert]): SaeAlert or TiAlert.
Raises:
RuntimeError: Raise an error if REST call fails.
Returns:
ID: Return the container ID.
"""
return self._get_existing_container_id_for_sdi(alert.id)
def _create_new_container_payload(self, alert: Union[SaeAlert, TiAlert]) -> Dict[str, Any]:
"""
Returns information for an Alert
Args:
alert (Union[SaeAlert, TiAlert]): SaeAlert or TiAlert object.
Returns:
Dict[str, Any]: All pertinent data used to create container from Alert.
"""
return {
"name": alert.model,
"source_data_identifier": alert.id,
"label": self.config.get("ingest", {}).get("container_label"),
"description": alert.description if isinstance(alert, SaeAlert) else "",
"type": alert.alert_provider,
"severity": alert.severity,
"start_time": alert.created_date_time,
}
def _create_or_update_container(self, alert: Union[SaeAlert, TiAlert]) -> int:
"""
Check if the container exists, if not then create a new container.
Args:
alert (Union[SaeAlert, TiAlert]): SaeAlert or TiAlert object.
Raises:
RuntimeError: Raise a runtime error if container creation fails.
Returns:
int: The ID for the created container.
"""
existing_container_id: Optional[int] = self._get_existing_container_id_for_alert(alert)
# If a container ID does not already exist, create a new one first, because the update operation
# runs regardless of whether the container is new or existing.
if existing_container_id is None:
# save new container to Splunk using the alert
ret_val, msg, cid = self.save_container(self._create_new_container_payload(alert))
if phantom.is_fail(ret_val):
self.save_progress("Error saving container: {}".format(msg))
raise RuntimeError("Error saving container: {} -- CID: {}".format(msg, cid))
existing_container_id = self._get_existing_container_id_for_alert(alert)
# Assertion made for type checking. At this point, the container ID will not be None if it was
# successfully created.
assert existing_container_id is not None
return existing_container_id
def _create_container_artifacts(self, container_id: int, alert: Union[SaeAlert, TiAlert]):
"""
Create an artifact for a container.
Args:
container_id (int): ID for the container.
alert (Union[SaeAlert, TiAlert]): SaeAlert or TiAlert object.
"""
# add new artifacts
self._create_new_artifact_from_alert(container_id, alert)
def _get_poll_interval(self, param) -> Tuple[str, str]:
"""
Helper function for *On Poll* action to get poll interval.
Args:
starttime(str): starttime string in ISO 8601 format (yyyy-MM-ddThh:mm:ssZ in UTC).
endtime(str): endtime string in ISO 8601 format (yyyy-MM-ddThh:mm:ssZ in UTC).
Returns:
Tuple[datetime, datetime]: start and end datetime.
"""
# standard time frame for poll interval
default_end_time = datetime.fromtimestamp(int(datetime.utcnow().timestamp())).isoformat() + "Z"
start_time: str = param.get("starttime", self._state.get("last_ingestion_time", "2020-06-15T10:00:00Z"))
end_time: str = param.get("endtime", default_end_time)
return start_time, end_time
def _handle_on_poll(self, param):
"""
Action to poll for Workbench Alerts.
Args:
start_time(str): starttime string in ISO 8601 format (yyyy-MM-ddThh:mm:ssZ in UTC).
end_time(str): endtime string in ISO 8601 format (yyyy-MM-ddThh:mm:ssZ in UTC).
Raises:
RuntimeError: Raise an error if fetching Alerts fails.
Returns:
List[Dict[str, Any]]: List containing Alert Objects.
"""
# Log current action
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
# Optional Params
start_time, end_time = self._get_poll_interval(param)
# Initialize Pytmv1
client = self._get_client()
new_alerts: List[Union[SaeAlert, TiAlert]] = []
# Make rest call
try:
client.consume_alert_list(
lambda alert: new_alerts.append(alert),
start_time=start_time,
end_time=end_time,
)
except Exception as e:
raise RuntimeError("Consume Alert List failed.") from e
# Get events from the TM Vision One and process them as Phantom containers
try:
for alert in new_alerts:
# Use the container ID to create or update an Alert container
container_id: int = self._create_or_update_container(alert)
# Update container metadata
self._update_container_metadata(container_id, alert)
# Create artifacts for Alert containers
self._create_container_artifacts(container_id, alert)
# Log results
serialized_alerts: List[Dict] = [item.dict() for item in new_alerts]
action_result.update_data(serialized_alerts)
action_result.set_summary({"Number of Events Found": len(serialized_alerts)})
self.save_progress("Phantom imported {0} events".format(len(serialized_alerts)))
# remember current timestamp for next run
self._state["last_ingestion_time"] = end_time
return action_result.set_status(phantom.APP_SUCCESS)
except Exception as e:
self.save_progress("Exception = {0}".format(str(e)))
raise e
def _handle_status_check(self, param):
"""
Action to check the status of a task based on task_id.
Args:
task_id(str): Unique numeric string that identifies a response task.
poll(str): If script should wait until the task is finished before returning the result (disabled by default)
Returns:
Dict[str, int]: object containing task_id and HTTP status code
"""
# send progress messages back to the platform
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(param))
# Required Params
task_id = param["task_id"]
# Optional Params
poll = param.get("poll", "true")
poll_time_sec = param.get("poll_time_sec", 30)
# Initialize Pytmv1
client = self._get_client()
# Make rest call
response = client.get_base_task_result(task_id, poll, poll_time_sec)
assert response.response is not None
response_dict = response.response.dict()
action = response_dict["action"]
action_type = self.get_task_type(action)
# Make task specific call using action_type
resp = client.get_task_result(
task_id=task_id,
class_=action_type,
poll=poll,
poll_time_sec=poll_time_sec,
)
if self._is_pytmv1_error(resp.result_code):
self.debug_print("Something went wrong, please check task_id.")
raise RuntimeError(f"Error fetching task status for task {task_id}. Result Code: {resp.error}")
assert resp.response is not None
action_result.add_data(resp.response.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_add_to_blocklist(self, param):
"""
Action to add item to block list.
Args:
block_objects(List[Dict[str, str]]): Object object made up of type, value and description.
Returns:
multi_resp: Object containing task_id and https status code.
"""
# send progress messages back to the platform
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(param))
# Required Params
block_objects: List[Dict[str, Any]] = json.loads(param["block_objects"])
# Initialize Pytmv1
client = self._get_client()
block_tasks: List[ObjectTask] = []
# Create block task list
for obj in block_objects:
block_tasks.append(
ObjectTask(
object_type=self._get_ot_enum(obj["object_type"]),
object_value=obj["object_value"],
description=obj.get("description", "Add To Blocklist"),
)
)
# Make rest call
response = client.add_to_block_list(*block_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please input params.")
raise RuntimeError(f"Error while adding to block list: {response.errors}")
assert response.response is not None
# Add the response into the data section
for item in response.response.items:
action_result.add_data(item.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_remove_from_blocklist(self, param):
"""
Remove an item from block list.
Args:
block_objects(List[Dict[str, str]]): Object containing type, value and (optional) description.
Returns:
multi_resp: Object containing task_id and https status code.
"""
# send progress messages back to the platform
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(param))
# Required Params
block_objects: List[Dict[str, str]] = json.loads(param["block_objects"])
# Initialize Pytmv1
client = self._get_client()
# Create unblock task list
unblock_tasks: List[ObjectTask] = []
for obj in block_objects:
unblock_tasks.append(
ObjectTask(
object_type=self._get_ot_enum(obj["object_type"]),
object_value=obj["object_value"],
description=obj.get("description", "Remove from Blocklist"),
)
)
# Make rest call
response = client.remove_from_block_list(*unblock_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please input params.")
raise RuntimeError(f"Error while removing items from block list: {response.errors}")
assert response.response is not None
# Add the response into the data section
for item in response.response.items:
action_result.add_data(item.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_quarantine_email_message(self, param):
"""
Action to quarantine an email using the mailBox and messageId or uniqueId
Args:
email_identifiers(List[Dict[str, str]]): Object containing mailBox/messageId and optional description
or uniqueId and optional description.
Returns:
multi_resp(List[Dict[str, Any]]): Object containing task_id and HTTP status code.
"""
# send progress messages back to the platform
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(param))
# Required Params
email_identifiers: List[Dict[str, str]] = json.loads(param["email_identifiers"])
# Initialize Pytmv1
client = self._get_client()
email_tasks: List[EmailMessageIdTask | EmailMessageUIdTask] = []
# Create email task list
for email in email_identifiers:
if email.get("message_id"):
email_tasks.append(
EmailMessageIdTask(
message_id=email["message_id"],
description=email.get("description", "Quarantine Email Message."),
mail_box=email.get("mailbox", ""),
)
)
elif email.get("unique_id"):
email_tasks.append(
EmailMessageUIdTask(
unique_id=email["unique_id"],
description=email.get("description", "Quarantine Email Message."),
)
)
# Make rest call
response = client.quarantine_email_message(*email_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please check email identifiers.")
raise RuntimeError(f"Error while quarantining email: {response.errors}")
assert response.response is not None
# Add the response into the data section
for item in response.response.items:
action_result.add_data(item.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_delete_email_message(self, param):
"""
Action to delete an email using the mailBox and messageId or uniqueId.
Args:
email_identifiers(List[Dict[str, str]]): Object containing mailBox/messageId and optional description
or uniqueId and optional description.
Returns:
multi_resp(Dict[str, List]): Object containing task_id and HTTP status code.
"""
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(param))
# Required Params
email_identifiers: List[Dict[str, str]] = json.loads(param["email_identifiers"])
# Initialize Pytmv1
client = self._get_client()
email_tasks: List[EmailMessageIdTask | EmailMessageUIdTask] = []
# Create email task list
for email in email_identifiers:
if email.get("message_id"):
email_tasks.append(
EmailMessageIdTask(
message_id=email["message_id"],
description=email.get("description", "Delete Email Message."),
mail_box=email.get("mailbox", ""),
)
)
elif email.get("unique_id"):
email_tasks.append(
EmailMessageUIdTask(
unique_id=email["unique_id"],
description=email.get("description", "Delete Email Message."),
)
)
# Make rest call
response = client.delete_email_message(*email_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please check email identifiers.")
raise RuntimeError(f"Error while deleting email: {response.errors}")
assert response.response is not None
# Add the response into the data section
for item in response.response.items:
action_result.add_data(item.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_terminate_process(self, param):
"""
Terminates a process that is running on one or more endpoints.
Note: You can specify either the computer name ("endpointName") or the GUID of the installed agent program ("agentGuid").
Args:
process_identifiers(List[Dict[str, str]]): Object containing mailBox/messageId and optional description
or uniqueId and optional description.
Returns:
multi_resp(Dict[str, List]): Object containing task_id and HTTP status code.
"""
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(param))
# Required Params
process_identifiers: List[Dict[str, str]] = json.loads(param["process_identifiers"])
# Initialize Pytmv1
client = self._get_client()
process_tasks: List[ProcessTask] = []
# Create process task list
for process in process_identifiers:
if process.get("endpoint"):
process_tasks.append(
ProcessTask(
endpoint_name=process["endpoint"],
file_sha1=process["file_sha1"],
description=process.get("description", "Terminate Process."),
file_name=process.get("filename", ""),
)
)
elif process.get("agent_guid"):
process_tasks.append(
ProcessTask(
agent_guid=process["agent_guid"],
file_sha1=process["file_sha1"],
description=process.get("description", "Terminate Process."),
file_name=process.get("filename", ""),
) # type: ignore
)
# Make rest call
response = client.terminate_process(*process_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please check process identifiers.")
raise RuntimeError(f"Error while terminating process: {response.errors}")
assert response.response is not None
# Add the response into the data section
for item in response.response.items:
action_result.add_data(item.dict())
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def get_exception_count(self) -> int:
"""Gets the count of objects present in exception list"""
# Initialize Pytmv1
client = self._get_client()
new_exceptions: List[ExceptionObject] = []
try:
client.consume_exception_list(lambda exception: new_exceptions.append(exception))
except Exception as e:
self.debug_print("Consume Exception List failed with following exception:")
raise RuntimeError("Error while adding to exception list.") from e
return len(new_exceptions)
def _handle_add_to_exception(self, param: Dict[str, Any]):
"""
Adds domains, file SHA-1, file SHA-256, IP addresses, sender addresses, or URLs to the Exception List.
Args:
block_objects(List[Dict[str, str]]): List of objects containing type, value and optional description.
Returns:
multi_resp(Dict[str, List]): Object containing task_id and HTTP status code.
"""
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(param))
# Required Params
block_objects: List[Dict[str, str]] = json.loads(param["block_objects"])
# Initialize Pytmv1
client = self._get_client()
excp_tasks: List[ObjectTask] = []
# Create exception task list
for obj in block_objects:
excp_tasks.append(
ObjectTask(
object_type=self._get_ot_enum(obj["object_type"]),
object_value=obj["object_value"],
description=obj.get("description", "Add To Exception List."),
)
)
# Make rest call
response = client.add_to_exception_list(*excp_tasks)
if self._is_pytmv1_error(response.result_code):
self.debug_print("Something went wrong, please check block objects.")
raise RuntimeError(f"Error while adding object to exception list: {response.errors}")
assert response.response is not None
# Get total exception list count
total_exception_count = self.get_exception_count()
# Add the response into the data section
action_result.add_data(
{
"multi_response": [item.dict() for item in response.response.items],
"total_count": total_exception_count,
}
)
# Return success
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_delete_from_exception(self, param):
"""
Deletes the specified objects from the Exception List.
Args:
block_objects(List[Dict[str, str]]): List of objects containing type, value and optional description.
Returns:
multi_resp(Dict[str, List]): Object containing task_id and HTTP status code.
"""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))