forked from splunk-soar-connectors/recordedfuture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecordedfuture_connector.py
1751 lines (1462 loc) · 70.1 KB
/
recordedfuture_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: recordedfuture_connector.py
#
# Copyright (c) Recorded Future, Inc, 2019-2024
#
# This unpublished material is proprietary to Recorded Future. All
# rights reserved. The methods and techniques described herein are
# considered trade secrets and/or confidential. Reproduction or
# distribution, in whole or in part, is forbidden except by express
# written permission of Recorded Future.
#
# 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 App imports
import base64
# noinspection PyCompatibility
import ipaddress
import json
# Global imports
import os
import platform
import sys
import time
import uuid
from datetime import datetime
from html import escape
from math import ceil
from typing import Literal
# Phantom App imports
# noinspection PyUnresolvedReferences
import phantom.app as phantom
# noinspection PyUnresolvedReferences
import phantom.vault as vault
import requests
# noinspection PyUnresolvedReferences
from bs4 import BeautifulSoup, UnicodeDammit
# noinspection PyUnresolvedReferences
from phantom.action_result import ActionResult
# noinspection PyUnresolvedReferences
from phantom.base_connector import BaseConnector
from phantom_common import paths
# Usage of the consts file is recommended
from recordedfuture_consts import *
class RetVal(tuple):
def __new__(cls, val1, val2=None):
return tuple.__new__(RetVal, (val1, val2))
class RecordedfutureConnector(BaseConnector):
"""Implement a Connector towards Recorded Future's ConnectAPI."""
def __init__(self):
"""Initialize."""
# Call the BaseConnectors init first
super(RecordedfutureConnector, self).__init__()
self._state = None
# Variable to hold a base_url in case the app makes REST calls
# Do note that the app json defines the asset config, so please
# modify this as you deem fit.
self._base_url = None
@staticmethod
def _process_empty_response(response, action_result):
"""Process an empty result."""
if response.status_code == 200 or response.status_code == 204:
return RetVal(phantom.APP_SUCCESS, {})
return RetVal(
action_result.set_status(phantom.APP_ERROR, "Empty response and no information in the header"),
None,
)
@staticmethod
def _process_html_response(response, action_result):
"""Process an HTML result."""
# An html response, treat it like an error
status_code = response.status_code
try:
soup = BeautifulSoup(response.text, "html.parser")
# Remove the script, style, footer and navigation part from the HTML message
for element in soup(["script", "style", "footer", "nav"]):
element.extract()
error_text = soup.text
split_lines = error_text.split("\n")
split_lines = [x.strip() for x in split_lines if x.strip()]
error_text = "\n".join(split_lines)
except Exception as err:
error_text = "Cannot parse error details: {0}".format(err)
error_text = UnicodeDammit(error_text).unicode_markup
message = "Please check the app configuration parameters. Status Code: {0}. Data from server:\n{1}\n".format(status_code, error_text)
message = message.replace("{", "{{").replace("}", "}}")
return RetVal(action_result.set_status(phantom.APP_ERROR, message), None)
@staticmethod
def _create_empty_response(fields):
"""Create an empty response.
This is typically used when the API return 404 (not found). Rather
than to return this as an error an empty response is created.
Depending on which fields were used (reputation/intelligence)
the returned structure is more or less rich.
"""
resp_json = {
"data": {
"entity": {"name": "", "type": None, "id": None},
"timestamps": {"firstSeen": "never", "lastSeen": "never"},
"risk": {
"criticalityLabel": None,
"rules": None,
"evidenceDetails": [],
"riskSummary": "No information available.",
"criticality": None,
"riskString": "",
"score": None,
},
}
}
if "intelCard" in fields:
resp_json["data"]["intelCard"] = ""
if "threatLists" in fields:
resp_json["data"]["threatLists"] = []
if "relatedEntities" in fields:
resp_json["data"]["relatedEntities"] = []
if "location" in fields:
resp_json["data"]["location"] = {}
if "metrics" in fields:
resp_json["data"]["metrics"] = []
return resp_json
def _process_json_response(self, resp, action_result, **kwargs):
"""Process a JSON response."""
# Try a json parse
try:
resp_json = resp.json()
except Exception as err:
error_code, error_message = self._get_error_message_from_exception(err)
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Unable to parse JSON response. Error code: {0}. Error message: {1}".format(error_code, error_message),
),
None,
)
# Please specify the status codes here
if 200 <= resp.status_code < 399:
return RetVal(phantom.APP_SUCCESS, resp_json)
# If an IOC has no data in Recorded Future's API it returns 404.
# While this is correct in REST semantics it's not what our app
# needs. We will create an empty response instead.
self.debug_print("_process_json_response kwargs: ", kwargs)
if "fields" in kwargs.get("params", {}):
fields = kwargs["params"]["fields"].split(",")
self.debug_print("_process_json_response fields: ", fields)
if resp.status_code == 404:
resp_json = self._create_empty_response(fields)
return RetVal(phantom.APP_SUCCESS, resp_json)
msg = "No data found"
if resp_json.get("message"):
msg = resp_json.get("message")
if resp_json.get("error").get("message"):
if msg:
msg = "{} and {}".format(msg, resp_json.get("error").get("message"))
else:
msg = resp_json.get("error").get("message")
# You should process the error returned in the json
message = "Error from server. Status Code: {0} " "Data from server: {1}".format(resp.status_code, UnicodeDammit(msg).unicode_markup)
return RetVal(action_result.set_status(phantom.APP_ERROR, message), None)
def _process_response(self, resp, action_result, **kwargs):
"""Process the response.
The response handling is handled differently depending on whether
it's text, HTML or JSON.
"""
# store the r_text in debug data, it will get dumped in the logs if
# the action fails
if hasattr(action_result, "add_debug_data"):
action_result.add_debug_data({"r_status_code": resp.status_code})
action_result.add_debug_data({"r_text": resp.text})
action_result.add_debug_data({"r_headers": resp.headers})
# Process each 'Content-Type' of response separately
# Process a json response
if "json" in resp.headers.get("Content-Type", ""):
return self._process_json_response(resp, action_result, **kwargs)
# Process an HTML response, Do this no matter what the api talks.
# There is a high chance of a PROXY in between phantom and the rest of
# world, in case of errors, PROXY's return HTML, this function parses
# the error and adds it to the action_result.
if "html" in resp.headers.get("Content-Type", ""):
return self._process_html_response(resp, action_result)
# it's not content-type that is to be parsed, handle an empty response
if not resp.text:
return self._process_empty_response(resp, action_result)
# everything else is actually an error at this point
error_msg = UnicodeDammit((resp.text.replace("{", "{{").replace("}", "}}"))).unicode_markup
message = "Can't process response from server. Status Code: {0} " "Data from server: {1}".format(resp.status_code, error_msg)
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 message from the exception.
:param e: Exception object
:return: error message
"""
error_code = "Error code 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]
else:
error_msg = "Unknown error occurred. Please check the asset configuration and|or action parameters."
except Exception as err:
error_msg = "An error occurred. Cannot parse error details: {0}".format(err)
try:
error_msg = UnicodeDammit(error_msg).unicode_markup
except TypeError:
error_msg = "Error occurred while connecting to the server. Please check the asset configuration and|or the action parameters."
except Exception as err:
error_msg = "An error occurred. Cannot parse error details: {0}".format(err)
return error_code, error_msg
def _make_rest_call(self, endpoint, action_result, params=None, method="get", **kwargs):
"""Make a REST call to Recorded Future's ConnectAPI.
Parameters:
endpoint: the path_info (ex ip, alert/search)
action_result: the current action_result
method: whether to make a get or post call
Keywords:
fields: the list of fields to fetch (see ConnectAPI docs)
Return value:
a RetVal: see above.
"""
# **kwargs can be any additional parameters that requests.request
# accepts
config = self.get_config()
resp_json = None
try:
request_func = getattr(requests, method)
except AttributeError:
return RetVal(
action_result.set_status(phantom.APP_ERROR, "Invalid method: {0}".format(method)),
resp_json,
)
# Create a URL to connect to
base_url = UnicodeDammit(self._base_url).unicode_markup
url = "{}{}".format(base_url, endpoint)
# Create a HTTP_USER_AGENT header
# container_id is added to track actions associated with an event in
# order to improve the app
platform_id = "Phantom_%s" % self.get_product_version()
pdict = dict(
app_name=os.path.basename(__file__),
container_id=self.get_container_id(),
os_id=platform.platform(),
pkg_name="phantom",
pkg_version=version,
requests_id=requests.__version__,
platform_id=platform_id,
)
user_agent_tplt = "{app_name}/{container_id} ({os_id}) " "{pkg_name}/{pkg_version} " "python-requests/{requests_id} ({platform_id})"
user_agent = user_agent_tplt.format(**pdict)
# headers
api_key = config.get("recordedfuture_api_token")
my_headers = {"X-RFToken": api_key, "User-Agent": user_agent}
# Ensure we log some useful data:
# url: shows if the url to ConnectAPI has been changed
# kwargs: shows fields and other keywords
# fingerprint: can be used to verify that the correct API key is used
self.debug_print("_make_rest_call url: {}".format(url))
self.debug_print("_make_rest_call kwargs {}".format(kwargs))
# Make the call
try:
resp = request_func(
url,
headers=my_headers,
verify=config.get("recordedfuture_verify_ssl", False),
params=params,
timeout=timeout,
**kwargs,
)
except requests.exceptions.Timeout as e:
self.error_print("Timeout Exception", dump_object=e)
return RetVal(
action_result.set_status(phantom.APP_ERROR, "Timeout error when connecting to server"),
resp_json,
)
except Exception as err:
self.error_print("Request exception", dump_object=err)
error_code, error_message = self._get_error_message_from_exception(err)
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Error Connecting to server. Error code:{0}. Error message:{1}".format(error_code, error_message),
),
resp_json,
)
if resp.status_code in [200, 201]:
return self._process_response(resp, action_result, **kwargs)
elif resp.status_code == 401:
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Error Connecting to server. Details: Error code: 401 Unauthorised.",
),
None,
)
elif resp.status_code == 403:
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Error Connecting to server. Details: Error code: 403 Forbidden.",
),
None,
)
elif resp.status_code == 400:
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Error Connecting to server. Details: Error code: 400 Bad Request.",
),
None,
)
elif resp.status_code == 404:
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Error Connecting to server. Details: Error code: 404 Not Found.",
),
resp,
)
else:
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Error Connecting to server. Details: Error code: %s." % resp.status_code,
),
None,
)
def _handle_test_connectivity(self, param):
# Add an action result object to self (BaseConnector) to represent
# the action for this param
action_result = self.add_action_result(ActionResult(dict(param)))
# NOTE: test connectivity does _NOT_ take any parameters
# it will use the RF token to verify that it works in the second part
# i.e. the param dictionary passed to this handler will be empty.
# Also typically it does not add any data into an action_result either.
# The status and progress messages are more important.
params = {"output-format": "application/json"}
# make rest call - further info: https://docs.splunk.com/Documentation/Phantom/4.10/DevelopApps/Tutorial
my_ret_val, response = self._make_rest_call("/helo", action_result, params=params)
if phantom.is_fail(my_ret_val):
self.save_progress("Connectivity test failed. API endpoint not reachable")
return action_result.get_status()
self.save_progress("Successful connection to the API")
self.save_progress("Verifying Recorded Future API token")
my_ret_val, response = self._make_rest_call("/config/info", action_result)
# this is never run as we don't take care of a non-successful reply properly
if phantom.is_fail(my_ret_val):
self.save_progress("Test Credentials Failed")
return action_result.get_status()
# Return success
self.save_progress("Token is accepted by the API")
self.save_progress("Connectivity and credentials test passed. You may now close this window")
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_intelligence(self, param, ioc, entity_type):
"""Return intelligence for an entity."""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
# Params for the API call
params = {"entity_type": entity_type, "ioc": ioc}
# make rest call
my_ret_val, response = self._make_rest_call("/lookup/intelligence", action_result, json=params, method="post")
self.debug_print(
"_handle_intelligence",
{
"path_info": ("%s/%s", entity_type, ioc),
"action_result": action_result,
"params": params,
"my_ret_val": my_ret_val,
"response": response,
},
)
# Do not fail on 404. Give a message to user with success status.
if phantom.is_fail(my_ret_val) and response.status_code == 404:
action_result.set_status(
phantom.APP_SUCCESS,
status_message="Recorded Future does not have any information on this indicator.",
)
if phantom.is_fail(my_ret_val):
return action_result.get_status()
res = response.get("data", {})
action_result.add_data(res)
self.save_progress("Added data with keys {}", list(res.keys()))
# Update the summary
summary = action_result.get_summary()
if "risk" in res:
if "criticalityLabel" in res["risk"]:
summary["criticalityLabel"] = res["risk"]["criticalityLabel"]
if "riskSummary" in res["risk"]:
summary["riskSummary"] = res["risk"]["riskSummary"]
if res.get("timestamps", {}).get("lastSeen", ""):
summary["lastSeen"] = res["timestamps"]["lastSeen"]
action_result.set_summary(summary)
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_reputation(self, param, category, entity):
"""Return reputation information."""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
# Params for the API call
params = {category: entity}
# make rest call
my_ret_val, response = self._make_rest_call("/lookup/reputation", action_result, json=params, method="post")
self.debug_print(
"_handle_reputation",
{
"path_info": entity,
"endpoint": "/lookup/reputation",
"action_result": action_result,
"params": params,
"my_ret_val": my_ret_val,
"response": response,
},
)
if phantom.is_fail(my_ret_val):
return action_result.get_status()
# the BFI returns a list of entities. In future we may add the capability for
# to do a reputation lookup of more than one entity
entity = response.pop(0)
summary = action_result.get_summary()
if entity.get("id", ""):
summary["risk score"] = entity.get("riskscore", "")
summary["risk summary"] = "%s rules triggered of %s" % (
entity.get("rulecount", ""),
entity.get("maxrules", ""),
)
else:
summary = action_result.get_summary()
summary["riskscore"] = "No information available."
action_result.add_data(entity)
action_result.set_summary(summary)
self.save_progress("Added data with keys {}", list(entity.keys()))
# Return success, no need to set the message, only the status BaseConnector
# will create a textual message based off the summary dictionary
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_list_actions(self, param, action: str):
if action == "search":
return self._handle_list_search(param)
if action == "details":
return self._handle_list_details(param, info_type="info")
if action == "entities":
return self._handle_list_details(param, info_type="entities")
if action == "status":
return self._handle_list_details(param, info_type="status")
if action == "create":
return self._handle_list_create(param)
if action == "add-entity":
return self._handle_manage_list_entities(param, action="add")
if action == "remove-entity":
return self._handle_manage_list_entities(param, action="remove")
def _get_list_action_result(self, action_result, my_ret_val, response_obj):
if phantom.is_fail(my_ret_val):
return action_result.get_status()
summary = action_result.get_summary()
action_result.add_data(response_obj)
action_result.set_summary(summary)
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_list_search(self, param):
"""Find lists"""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
params = {"limit": param.get("limit", 25)}
entity_types = param.get("entity_types", "")
list_name = param.get("list_name", "")
if entity_types:
params["type"] = UnicodeDammit(escape(entity_types)).unicode_markup
if list_name:
params["name"] = UnicodeDammit(escape(list_name)).unicode_markup
my_ret_val, response = self._make_rest_call("/list/search", action_result, json=params, method="post")
self.debug_print(
"_handle_list_search",
{
"endpoint": "/list/search",
"action_result": action_result,
"param": param,
"params": params,
"my_ret_val": my_ret_val,
"response": response,
},
)
return self._get_list_action_result(
action_result=action_result,
my_ret_val=my_ret_val,
response_obj=response,
)
def _handle_list_create(self, param):
"""Create new list"""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
params = {
"name": UnicodeDammit(param["list_name"]).unicode_markup,
"type": UnicodeDammit(param["entity_types"]).unicode_markup,
}
my_ret_val, response = self._make_rest_call("/list/create", action_result, json=params, method="post")
self.debug_print(
"_handle_list_create",
{
"endpoint": "/list/create",
"action_result": action_result,
"params": params,
"my_ret_val": my_ret_val,
"response": response,
},
)
return self._get_list_action_result(
action_result=action_result,
my_ret_val=my_ret_val,
response_obj=response,
)
def _handle_list_details(self, param, info_type: Literal["info", "status", "entities"]):
"""Get list details"""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
list_id = UnicodeDammit(param["list_id"]).unicode_markup
my_ret_val, response = self._make_rest_call(f"/list/{list_id}/{info_type}", action_result, method="get")
self.debug_print(
"_handle_list_details",
{
"endpoint": f"/list/{list_id}/{info_type}",
"action_result": action_result,
"my_ret_val": my_ret_val,
"response": response,
},
)
return self._get_list_action_result(action_result=action_result, my_ret_val=my_ret_val, response_obj=response)
def _handle_manage_list_entities(self, param, action: Literal["add", "remove"]):
"""Add/remove entity to list"""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
list_id = UnicodeDammit(param["list_id"]).unicode_markup
entity_id = param.get("entity_id")
entity_name = param.get("entity_name")
entity_type = param.get("entity_type")
data = {
"name": (UnicodeDammit(escape(entity_name)).unicode_markup if entity_name else None),
"type": (UnicodeDammit(escape(entity_type)).unicode_markup if entity_type else None),
"id": (UnicodeDammit(escape(entity_id)).unicode_markup if entity_id else None),
}
my_ret_val, response = self._make_rest_call(f"/list/{list_id}/entity/{action}", action_result, json=data, method="post")
self.debug_print(
"_handle_manage_list_entities",
{
"endpoint": f"/list/{list_id}/entity/{action}",
"action_result": action_result,
"my_ret_val": my_ret_val,
"response": response,
"data": data,
},
)
return self._get_list_action_result(
action_result=action_result,
my_ret_val=my_ret_val,
response_obj=response,
)
def _handle_triage(self, param):
"""Return triage information."""
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
# Params for the API call
param_types = ["ip", "domain", "url", "hash"]
params = {}
for i in param.keys():
if i in param_types:
params[i] = [UnicodeDammit(entry.strip()).unicode_markup for entry in param.get(i).split(",") if entry != "None"]
self.save_progress("Params found to triage: %s" % params)
# make rest call
my_ret_val, response = self._make_rest_call(
"/lookup/triage/%s?%s"
% (
UnicodeDammit(param["threat_context"]).unicode_markup,
"&format=phantom",
),
action_result,
json=params,
method="post",
)
self.debug_print(
"_handle_triage",
{
"path_info": "triage",
"endpoint": "/lookup/triage",
"action_result": action_result,
"params": params,
"my_ret_val": my_ret_val,
"response": response,
},
)
self.save_progress("Obtained API response")
if phantom.is_fail(my_ret_val):
return action_result.get_status()
# there will always be a response with data, how best represent this?
summary = action_result.get_summary()
if response.get("verdict", ""):
summary["assessment"] = "Suspected to be malicious"
summary["riskscore"] = response.get("triage_riskscore", "")
elif not response.get("entities", []):
summary["assessment"] = "No information available"
else:
summary["assessment"] = "Not found to be malicious"
summary["riskscore"] = response.get("triage_riskscore", "")
action_result.add_data(response)
action_result.set_summary(summary)
self.save_progress("Added data with keys {}", response.keys())
# Return success, no need to set the message, only the status BaseConnector
# will create a textual message based off the summary dictionary
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_list_contexts(self, param):
"""List available contexts"""
action_result = self.add_action_result(ActionResult(dict(param)))
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
# make rest call
my_ret_val, response = self._make_rest_call("/config/triage/contexts", action_result)
self.debug_print(
"_handle_list_contexts",
{
"action_result": action_result,
"my_ret_val": my_ret_val,
"response": response,
},
)
if phantom.is_fail(my_ret_val):
self.save_progress("API call to retrieve triage contexts failed.")
return action_result.get_status()
if response:
self.save_progress("Added data with keys {}", list(response.keys()))
summary = action_result.get_summary()
summary_statement = ""
for triage_context in list(response.keys()):
# Assemble summary
if summary_statement == "":
summary_statement = triage_context
else:
summary_statement = summary_statement + ", " + triage_context
action_result.add_data(
{
"context": triage_context,
"name": response[triage_context].get("name"),
"datagroup": response[triage_context].get("datagroup"),
}
)
summary["contexts_available_for_threat_assessment"] = summary_statement
else:
self.save_progress("API call failed to retrieve any information.")
summary = "API call to retrieve triage contexts failed"
action_result.set_summary(summary)
# Return success, no need to set the message, only the status
# BaseConnector will create a textual message based off of the summary
# dictionary
return action_result.set_status(phantom.APP_SUCCESS)
def _write_file_to_vault(self, container, file_data, file_name):
if hasattr(vault.Vault, "get_vault_tmp_dir"):
file_path = os.path.join(vault.Vault.get_vault_tmp_dir(), file_name)
else:
file_path = os.path.join(os.path.join(paths.PHANTOM_VAULT, "/tmp"), file_name)
with open(file_path, "wb") as file:
file.write(file_data)
_, message, _ = vault.vault_add(
container=container,
file_location=file_path,
file_name=file_name,
metadata=None,
trace=True,
)
self.debug_print(f"Add file - {message} - {container}")
def _add_screenshots_to_container(self, container, screenshots):
for screenshot in screenshots:
file_name = f"{uuid.uuid4()}.png"
file_data = base64.b64decode(screenshot)
self._write_file_to_vault(container, file_data, file_name)
def _on_poll_playbook_alerts(self, param, config, action_result):
"""Polling for triggered playbook alerts"""
params = {}
# Return early if no playbook alert categories are specified.
if not config.get("on_poll_playbook_alert_type"):
self.save_progress("No Playbook Alert Categories have been specified for polling")
return []
if self.is_poll_now():
param["max_count"] = param.get("container_count", MAX_CONTAINERS)
params["from_date"] = None
else:
# Different number of max containers if first run
if self._state.get("first_run", True):
# set the config to _not_ first run hereafter
self._state["first_run"] = False
param["max_count"] = config.get("first_max_count", MAX_CONTAINERS)
self.save_progress("First time Ingestion detected.")
params["from_date"] = config.get("on_poll_playbook_alert_start_time")
else:
param["max_count"] = config.get("max_count", MAX_CONTAINERS)
# For all the runs after tge first one we get alerts filtered by update_data instead of create_date.
params["last_updated_date"] = self._state.get("last_playbook_alerts_fetch_time") or config.get(
"on_poll_playbook_alert_start_time"
)
# Asset Settings in Asset Configuration allows a negative number
if int(param["max_count"]) <= 0:
param["max_count"] = MAX_CONTAINERS
# Prepare the REST call to get all alerts within the timeframe and with status New
params["state"] = self._state
params["limit"] = param.get("max_count", 100)
params["categories"] = [el.strip() for el in config.get("on_poll_playbook_alert_type", "").split(",") if el.strip()]
params["statuses"] = [el.strip() for el in config.get("on_poll_playbook_alert_status", "").split(",") if el.strip()]
params["priorities"] = (
[el.strip() for el in config["on_poll_playbook_alert_priority"].split(",")]
if config.get("on_poll_playbook_alert_priority")
else None
)
# Make the rest call
my_ret_val, containers = self._make_rest_call(
"/playbook_alert/on_poll",
action_result,
json=params,
method="post",
)
# Something went wrong
if phantom.is_fail(my_ret_val):
return action_result.get_status()
return containers
def _on_poll(self, param):
"""Entry point for obtaining alerts and rules."""
# new containers and artifacts will be stored in containers[]
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
config = self.get_config()
self.save_progress("Polling Playbook Alerts")
containers = self._on_poll_playbook_alerts(param, config, action_result)
try:
for container in containers:
screenshots = container.pop("images", [])
ret_val, msg, cid = self.save_container(container)
self._add_screenshots_to_container(cid, screenshots)
if phantom.is_fail(ret_val):
self.save_progress("Error saving containers: {}".format(msg))
self.error_print("Error saving containers: {} -- CID: {}".format(msg, cid))
return action_result.set_status(phantom.APP_ERROR, "Error while trying to add the containers")
except TypeError:
if not containers:
self.save_progress("Error in API request, please see spawn.log for more details")
else:
self.save_progress("API response provided no new playbook alert containers to ingest")
action_result.set_status(phantom.APP_SUCCESS)
self._state["last_playbook_alerts_fetch_time"] = datetime.now().isoformat()
if not config.get("on_poll_alert_ruleids"):
return action_result.get_status()
self.save_progress("Polling Alerts")
containers = self._on_poll_alerts(param, config, action_result)
try:
for container in containers:
ret_val, msg, cid = self.save_container(container)
if phantom.is_fail(ret_val):
self.save_progress("Error saving containers: {}".format(msg))
self.debug_print("Error saving containers: {} -- CID: {}".format(msg, cid))
return action_result.set_status(phantom.APP_ERROR, "Error while trying to add the containers")
# Always update the alerts with new status to ensure that they are not left in limbo
# description has string in the format -> "Container created from alert {alert_id}"
# we get alert_id from it.
params = [{"id": container["description"].split(" ")[4], "status": "Pending"}]
my_ret_val, response = self._make_rest_call("/alert/update", action_result, json=params, method="post")
# Something went wrong
if phantom.is_fail(my_ret_val):
return action_result.get_status()
except TypeError:
if not containers:
self.save_progress("Error in API request, please see spawn.log for more details")
else:
self.save_progress("API response provided no new playbook alert containers to ingest")
return action_result.set_status(phantom.APP_SUCCESS)
def _on_poll_alerts(self, param, config, action_result):
"""Polling for triggered alerts given a list of rule IDs."""
start_time = time.time()
rollback_start_time = start_time
if "start_time" in self._state:
rollback_start_time = self._state["start_time"]
# obtain the list of rule ids to use to obtain alerts
list_of_rules = config.get("on_poll_alert_ruleids")
if not list_of_rules:
self.save_progress("No Alert Rule IDs have been specified for polling")
return action_result.set_status(phantom.APP_ERROR)
rule_list = [x.strip() for x in list_of_rules.split(",")]
if self.is_poll_now():
param["max_count"] = param.get("container_count", MAX_CONTAINERS)
timeframe = ""
else:
# Different number of max containers if first run
if self._state.get("first_run", True):
# set the config to _not_ first run hereafter
self._state["first_run"] = False
self._state["start_time"] = start_time
param["max_count"] = config.get("first_max_count", MAX_CONTAINERS)
self.save_progress("First time Ingestion detected.")
timeframe = ""
else:
param["max_count"] = config.get("max_count", MAX_CONTAINERS)
# calculate time since last fetch
interval = ceil((start_time - self._state.get("start_time", start_time)) / 3600) + 3
self._state["start_time"] = start_time
timeframe = f"-{interval}h to now"
# Asset Settings in Asset Configuration allows a negative number
if int(param["max_count"]) <= 0:
param["max_count"] = MAX_CONTAINERS
# Prepare the REST call to get all alerts within the timeframe and with status New
params = {
"triggered": timeframe,
"rules": rule_list,
"severity": config.get("on_poll_alert_severity"),
"limit": param.get("max_count", 100),
"limited_entity_scope": config.get("on_poll_alert_full_alert") != "All entities",
}
params["status"] = [el.strip() for el in config.get("on_poll_alert_status", "").split(",") if el.strip()]
# Make the rest call
my_ret_val, containers = self._make_rest_call(
"/alert/on_poll",
action_result,
json=params,
method="post",
)
# Something went wrong
if phantom.is_fail(my_ret_val):
status = action_result.get_status()
# make sure to revert to the old start time,
# so that next iteration will try again with a longer interval.
self._state["start_time"] = rollback_start_time
return status
# sort the containers to get the oldest first
containers.sort(key=lambda k: k["triggered"], reverse=False)
# if necessary truncate the list of containers TODO need to fix other issue first
# if len(containers) > param['max_count'] + 1:
# containers = containers[0:param['max_count'] + 1]
return containers
def _handle_alert_search(self, param):
"""Implement lookup of alerts issued for an alert rule."""
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)))
# Required values can be accessed directly
rule_id = UnicodeDammit(param["rule_id"]).unicode_markup