forked from splunk-soar-connectors/hyasinsight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hyasinsight_connector.py
836 lines (712 loc) · 32 KB
/
hyasinsight_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
# File: hyasinsight_connector.py
#
# Copyright (c) Hyas, 2022
#
# 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 re
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 hyasinsight_consts import *
class RetVal(tuple):
def __new__(cls, val1, val2=None):
return tuple.__new__(RetVal, (val1, val2))
class HyasInsightConnector(BaseConnector):
def __init__(self):
# Call the BaseConnectors init first
super(HyasInsightConnector, 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
def _process_empty_response(self, response, action_result):
if response.status_code == 200:
return RetVal(phantom.APP_SUCCESS, {})
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Empty response and no information in the header"
), None
)
def _process_html_response(self, response, action_result):
status_code = response.status_code
try:
soup = BeautifulSoup(response.text, "html.parser")
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:
error_text = "Cannot parse error details"
message = "Status Code: {0}. Data from server:\n{1}\n".format(
status_code, error_text)
message = message.replace(u'{', '{{').replace(u'}', '}}')
return RetVal(action_result.set_status(phantom.APP_ERROR, message),
None)
def _process_json_response(self, r, action_result):
# Try a json parse
try:
resp_json = r.json()
except Exception as e:
return RetVal(
action_result.set_status(
phantom.APP_ERROR,
"Unable to parse JSON response. Error: {0}".format(str(e))
), None
)
# Please specify the status codes here
if 200 <= r.status_code < 399:
return RetVal(phantom.APP_SUCCESS, resp_json)
# You should process the error returned in the json
message = "Error from server. Status Code: {0} Data from server: {1}". \
format(r.status_code,
r.text.replace(u'{', '{{').replace(u'}', '}}'))
return RetVal(action_result.set_status(phantom.APP_ERROR, message),
None)
def _process_response(self, r, action_result):
# store the r_text in debug data, it will get dumped in the logs if
# the action fails
if hasattr(action_result, 'add_debug_data'):
action_result.add_debug_data({'r_status_code': r.status_code})
action_result.add_debug_data({'r_text': r.text})
action_result.add_debug_data({'r_headers': r.headers})
# Process a json response
if 'json' in r.headers.get('Content-Type', ''):
return self._process_json_response(r, action_result)
if 'html' in r.headers.get('Content-Type', ''):
return self._process_html_response(r, action_result)
# it's not content-type that is to be parsed, handle an empty response
if not r.text:
return self._process_empty_response(r, action_result)
# everything else is actually an error at this point
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 flatten_json(self, response):
json_flatten = {}
def flatten(json_data, name=""):
# If the Nested key-value
# pair is of dict type
if isinstance(json_data, dict):
for json_data_in in json_data:
flatten(json_data[json_data_in], name + json_data_in + "_")
# If the Nested key-value
# pair is of list type
elif isinstance(json_data, list):
if len(json_data) > 0:
for json_data_in in json_data:
if isinstance(json_data_in, dict):
flatten(json_data_in, name)
else:
json_flatten[name[:-1]] = json_data
else:
flatten("", name)
else:
json_flatten[name[:-1]] = json_data
flatten(response)
return json_flatten
def get_flatten_json_response(self, raw_api_response, endpoint):
"""
:param raw_api_response: raw_api response from the API
:param endpoint: Endpoint
:return: Flatten Json response
"""
flatten_json_response = []
if raw_api_response:
for obj in raw_api_response:
if endpoint == OS_INDICATOR:
data = json.loads(obj.get("data", "{}"))
obj = {**obj, **data}
flatten_json_response.append(self.flatten_json(obj))
return flatten_json_response
def _get_error_message_from_exception(self, error):
"""This function is used to get appropriate error message from the
exception.
:param e: Exception object
:return: error message
"""
try:
if error.args:
if len(error.args) > 1:
error_code = error.args[0]
error_msg = error.args[1]
elif len(error.args) == 1:
error_code = HYAS_ERR_CODE_MSG
error_msg = error.args[0]
else:
error_code = HYAS_ERR_CODE_MSG
error_msg = HYAS_ERR_MSG_UNAVAILABLE
except:
error_code = HYAS_ERR_CODE_MSG
error_msg = HYAS_ERR_MSG_UNAVAILABLE
try:
if error_code in HYAS_ERR_CODE_MSG:
error_text = f"Error Message: {error_msg}"
else:
error_text = f"Error Code: {error_code}. Error Message: " \
f"{error_msg}"
except:
error_text = HYAS_PARSE_ERR_MSG
return error_text
def _make_rest_call(
self, endpoint, action_result, data=None, headers=None,
method="post"
):
try:
request_func = getattr(requests, method)
except AttributeError:
return RetVal(
action_result.set_status(
phantom.APP_ERROR, f"Unsupported method: {method}"
),
None,
)
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return RetVal(
action_result.set_status(
phantom.APP_ERROR, f"Handled exception: {error_message}"
),
None,
)
# Create a URL to connect to
if endpoint == CURRENT_WHOIS:
url = f"{CURRENT_WHOIS_BASE_URL}{endpoint}"
else:
url = f"{HYAS_BASE_URL}{endpoint}"
try:
response = request_func(url, data=data, headers=headers,
timeout=DEFAULT_REQUEST_TIMEOUT)
except Exception as e:
error_message = self._get_error_message_from_exception(e)
return RetVal(
action_result.set_status(
phantom.APP_ERROR, f"Error connecting: {error_message}"
),
None,
)
if response.status_code == 401:
return RetVal(
action_result.set_status(phantom.APP_ERROR,
HYAS_INVALID_APIKEY_ERROR),
None,
)
return self._process_response(response, action_result)
def validating_ioc(self, action_result, ioc, val):
"""
Function that checks given ioc and return IOC_NAME if ioc is valid
IP/Domain/Email/Phone/SHA256.
:param ioc: IP address/Email/Phone/SHA256/Domain
:return: status (success/failure)
"""
ioc_type = ioc
ioc_names_list = IOC_NAME
try:
if ioc_type in ioc_names_list.keys():
if ioc_type == "ip":
ip_dict = ioc_names_list[ioc_type]
for key, value in ip_dict.items():
regex = value
if (re.fullmatch(regex, val)):
ioc_name = key + "_regex"
return ioc_name
elif ioc_type == "hash":
hash_dict = ioc_names_list['hash']
for key, value in hash_dict.items():
regex = value
if (re.fullmatch(regex, val)):
ioc_name = key + "_regex"
return ioc_name
return None
else:
regex = ioc_names_list[ioc_type]
if (re.fullmatch(regex, val)):
ioc_name = ioc_type + "_regex"
return ioc_name
return RetVal(
action_result.set_status(
phantom.APP_ERROR, "Unable to locate ioc type."
),
None,
)
except:
return RetVal(
action_result.set_status(
phantom.APP_ERROR, "Error while Validating the ioc"
),
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
# 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.
payload = json.dumps(
{"applied_filters": {
HYAS_TEST_PAYLOAD_KEY: HYAS_TEST_PAYLOAD_VALUE}}
)
self.save_progress("Connecting to endpoint")
# make rest call
ret_val, response = self._make_rest_call(
HYAS_TEST_PASSIVEHASH_ENDPOINT,
action_result,
data=payload,
headers=self._headers,
)
if phantom.is_fail(ret_val):
self.save_progress(HYAS_TEST_CONN_FAILED)
return action_result.get_status()
self.save_progress(HYAS_TEST_CONN_PASSED)
return action_result.set_status(phantom.APP_SUCCESS)
def _handle_lookup_command_and_control_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = C2ATTRIBUTION
ioc_dict = C2ATTRIBUTION_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_command_and_control_email(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = EMAIL
endpoint = C2ATTRIBUTION
ioc_dict = C2ATTRIBUTION_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_command_and_control_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IP
endpoint = C2ATTRIBUTION
ioc_dict = C2ATTRIBUTION_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_whois_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = WHOIS
ioc_dict = WHOIS_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_whois_email(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = EMAIL
endpoint = WHOIS
ioc_dict = WHOIS_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_whois_phone(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = PHONE
endpoint = WHOIS
ioc_dict = WHOIS_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_dynamicdns_email(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = EMAIL
endpoint = DYNAMICDNS
ioc_dict = DYNAMIC_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_dynamicdns_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IP
endpoint = DYNAMICDNS
ioc_dict = DYNAMIC_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_dynamicdns_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = DYNAMICDNS
ioc_dict = DYNAMIC_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_sinkhole_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IPV4
endpoint = SINKHOLE
ioc_dict = SINKHOLE_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_passivehash_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IPV4
endpoint = PASSIVEHASH
ioc_dict = PASSIVEHASH_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_passivehash_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = PASSIVEHASH
ioc_dict = PASSIVEHASH_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_ssl_certificate_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IP
endpoint = SSL
ioc_dict = SSL_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_passivedns_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = PASSIVEDNS
ioc_dict = PASSIVE_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_current_whois_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = CURRENT_WHOIS
ioc_dict = WHOIS_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_passivedns_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IPV4
endpoint = PASSIVEDNS
ioc_dict = PASSIVE_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_mobile_geolocation_information_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IP
endpoint = DEVICEGEO
ioc_dict = DEVICE_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_malware_information_hash(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = HASH
endpoint = SAMPLE_INFORMATION
ioc_dict = SAMPLE_INFORMATION_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_malware_record_hash(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = HASH
endpoint = SAMPLE
ioc_dict = SAMPLE_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_malware_record_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = SAMPLE
ioc_dict = SAMPLE_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_malware_record_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IPV4
endpoint = SAMPLE
ioc_dict = SAMPLE_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_command_and_control_hash(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = HASH
endpoint = C2ATTRIBUTION
ioc_dict = C2ATTRIBUTION_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_os_indicator_hash(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = HASH
endpoint = OS_INDICATOR
ioc_dict = OS_INDICATOR_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_os_indicator_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = OS_INDICATOR
ioc_dict = OS_INDICATOR_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_os_indicator_ip(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = IP
endpoint = OS_INDICATOR
ioc_dict = OS_INDICATOR_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_ssl_certificate_hash(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = HASH
endpoint = SSL
ioc_dict = SSL_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def _handle_lookup_ssl_certificate_domain(self, param):
self.save_progress(
"In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
indicator_type = DOMAIN
endpoint = SSL
ioc_dict = SSL_IOC
self.save_progress("Checking the Indicator value")
self.handle_all_actions(indicator_type, action_result, ioc_dict,
endpoint, param)
def handle_all_actions(self, indicator_type, action_result, ioc_dict,
endpoint, param):
all_response = {}
indicator_value = param[indicator_type]
validated_ioc_name = self.validating_ioc(action_result, indicator_type,
indicator_value)
self.save_progress("Creating Payload")
if validated_ioc_name is not None:
if validated_ioc_name in ioc_dict.keys():
param_name = ioc_dict[validated_ioc_name]
if endpoint == CURRENT_WHOIS:
payload = json.dumps(
{
"applied_filters": {
param_name: indicator_value,
"current": True,
}
}
)
else:
payload = json.dumps(
{
"applied_filters": {
param_name: indicator_value
}
}
)
ret_val, response = self._make_rest_call(
endpoint,
action_result,
data=payload,
headers=self._headers,
)
if phantom.is_fail(ret_val):
return ret_val
try:
if endpoint != SSL and endpoint != CURRENT_WHOIS and \
endpoint != SAMPLE_INFORMATION:
all_response[endpoint] = self.get_flatten_json_response(
response, endpoint
)
elif endpoint == SSL:
response = response.get(SSL_CERTS)
all_response[endpoint] = self.get_flatten_json_response(
response, endpoint
)
elif endpoint == CURRENT_WHOIS:
response = response.get(ITEMS)
endpoint = CURRENT_WHOIS_NAME
all_response[endpoint] = self.get_flatten_json_response(
response, endpoint
)
elif endpoint == SAMPLE_INFORMATION:
response = response.get(SCAN_RESULT)
all_response[SAMPLE_INFORMATION_NAME] = \
self.get_flatten_json_response(response, endpoint)
self.save_progress("Saving Response")
action_result.add_data(all_response)
return action_result.set_status(phantom.APP_SUCCESS)
except:
return action_result.set_status(
phantom.APP_ERROR,
"unable to flatten json response.",
None,
)
return action_result.set_status(
phantom.APP_ERROR, HYAS_ERR_MSG_INVALID_INDICATOR_VALUE
)
def handle_action(self, param):
ret_val = phantom.APP_SUCCESS
# Get the action that we are supposed to execute for this App Run
action_id = self.get_action_identifier()
self.debug_print("action_id", self.get_action_identifier())
call_action = getattr(self, f'_handle_{action_id}')
ret_val = call_action(param)
return ret_val
def initialize(self):
# Load the state in initialize, use it to store data
# that needs to be accessed across actions
self._state = self.load_state()
# get the asset config
try:
config = self.get_config()
except Exception:
return phantom.APP_ERROR
"""
# Access values in asset config by the name
# Required values can be accessed directly
required_config_name = config['required_config_name']
# Optional values should use the .get() function
optional_config_name = config.get('optional_config_name')
"""
try:
self._apikey = config[HYAS_JSON_APIKEY]
except KeyError as ke:
return self._initialize_error(
HYAS_ERR_ASSET_API_KEY_,
Exception(f"KeyError: {ke}"),
)
self._headers = {
HYAS_JSON_APIKEY_HEADER: self._apikey,
"Content-Type": "application/json",
}
# self._base_url = config.get('base_url')
return phantom.APP_SUCCESS
def finalize(self):
# Save the state, this data is saved across actions and app upgrades
self.save_state(self._state)
return phantom.APP_SUCCESS
def main():
import argparse
import sys
argparser = argparse.ArgumentParser()
argparser.add_argument('input_test_json', help='Input Test JSON file')
argparser.add_argument('-u', '--username', help='username', required=False)
argparser.add_argument('-p', '--password', help='password', required=False)
args = argparser.parse_args()
session_id = None
username = args.username
password = args.password
if username is not None and password is None:
# User specified a username but not a password, so ask
import getpass
password = getpass.getpass("Password: ")
if username and password:
try:
login_url = HyasInsightConnector._get_phantom_base_url() + '/login'
print("Accessing the Login page")
r = requests.get(login_url, timeout=DEFAULT_REQUEST_TIMEOUT)
csrftoken = r.cookies['csrftoken']
data = dict()
data['username'] = username
data['password'] = password
data['csrfmiddlewaretoken'] = csrftoken
headers = dict()
headers['Cookie'] = 'csrftoken=' + csrftoken
headers['Referer'] = login_url
print("Logging into Platform to get the session id")
r2 = requests.post(login_url, data=data,
headers=headers, timeout=DEFAULT_REQUEST_TIMEOUT)
session_id = r2.cookies['sessionid']
except Exception as e:
print(
"Unable to get session id from the platform. Error: " + str(e))
sys.exit(1)
with open(args.input_test_json) as f:
in_json = f.read()
in_json = json.loads(in_json)
print(json.dumps(in_json, indent=4))
connector = HyasInsightConnector()
connector.print_progress_message = True
if session_id is not None:
in_json['user_session_token'] = session_id
connector._set_csrf_info(csrftoken, headers['Referer'])
ret_val = connector._handle_action(json.dumps(in_json), None)
print(json.dumps(json.loads(ret_val), indent=4))
sys.exit(0)
if __name__ == '__main__':
main()