-
Notifications
You must be signed in to change notification settings - Fork 129
/
opencti_connector_helper.py
2059 lines (1871 loc) · 77.5 KB
/
opencti_connector_helper.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
import asyncio
import base64
import copy
import datetime
import json
import os
import queue
import sched
import signal
import ssl
import sys
import tempfile
import threading
import time
import uuid
from enum import Enum
from queue import Queue
from typing import Callable, Dict, List, Optional, Union
import pika
from filigran_sseclient import SSEClient
from pika.exceptions import NackError, UnroutableError
from pydantic import TypeAdapter
from pycti.api.opencti_api_client import OpenCTIApiClient
from pycti.connector.opencti_connector import OpenCTIConnector
from pycti.connector.opencti_metric_handler import OpenCTIMetricHandler
from pycti.utils.opencti_stix2_splitter import OpenCTIStix2Splitter
TRUTHY: List[str] = ["yes", "true", "True"]
FALSY: List[str] = ["no", "false", "False"]
def killProgramHook(etype, value, tb):
os.kill(os.getpid(), signal.SIGTERM)
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
def get_config_variable(
env_var: str,
yaml_path: List,
config: Dict = {},
isNumber: Optional[bool] = False,
default=None,
required=False,
) -> Union[bool, int, None, str]:
"""[summary]
:param env_var: environment variable name
:param yaml_path: path to yaml config
:param config: client config dict, defaults to {}
:param isNumber: specify if the variable is a number, defaults to False
:param default: default value
"""
if os.getenv(env_var) is not None:
result = os.getenv(env_var)
elif yaml_path is not None:
if yaml_path[0] in config and yaml_path[1] in config[yaml_path[0]]:
result = config[yaml_path[0]][yaml_path[1]]
else:
return default
else:
return default
if result in TRUTHY:
return True
if result in FALSY:
return False
if isNumber:
return int(result)
if (
required
and default is None
and (result is None or (isinstance(result, str) and len(result) == 0))
):
raise ValueError("The configuration " + env_var + " is required")
if isinstance(result, str) and len(result) == 0:
return default
return result
def is_memory_certificate(certificate):
return certificate.startswith("-----BEGIN")
def ssl_verify_locations(ssl_context, certdata):
if certdata is None:
return
if is_memory_certificate(certdata):
ssl_context.load_verify_locations(cadata=certdata)
else:
ssl_context.load_verify_locations(cafile=certdata)
# As cert must be written in files to be loaded in ssl context
# Creates a temporary file in the most secure manner possible
def data_to_temp_file(data):
# The file is readable and writable only by the creating user ID.
# If the operating system uses permission bits to indicate whether a
# file is executable, the file is executable by no one. The file
# descriptor is not inherited by children of this process.
file_descriptor, file_path = tempfile.mkstemp()
with os.fdopen(file_descriptor, "w") as open_file:
open_file.write(data)
open_file.close()
return file_path
def ssl_cert_chain(ssl_context, cert_data, key_data, passphrase):
if cert_data is None:
return
cert_file_path = None
key_file_path = None
# Cert loading
if cert_data is not None and is_memory_certificate(cert_data):
cert_file_path = data_to_temp_file(cert_data)
cert = cert_file_path if cert_file_path is not None else cert_data
# Key loading
if key_data is not None and is_memory_certificate(key_data):
key_file_path = data_to_temp_file(key_data)
key = key_file_path if key_file_path is not None else key_data
# Load cert
ssl_context.load_cert_chain(cert, key, passphrase)
# Remove temp files
if cert_file_path is not None:
os.unlink(cert_file_path)
if key_file_path is not None:
os.unlink(key_file_path)
def create_mq_ssl_context(config) -> ssl.SSLContext:
use_ssl_ca = get_config_variable("MQ_USE_SSL_CA", ["mq", "use_ssl_ca"], config)
use_ssl_cert = get_config_variable(
"MQ_USE_SSL_CERT", ["mq", "use_ssl_cert"], config
)
use_ssl_key = get_config_variable("MQ_USE_SSL_KEY", ["mq", "use_ssl_key"], config)
use_ssl_reject_unauthorized = get_config_variable(
"MQ_USE_SSL_REJECT_UNAUTHORIZED",
["mq", "use_ssl_reject_unauthorized"],
config,
False,
False,
)
use_ssl_passphrase = get_config_variable(
"MQ_USE_SSL_PASSPHRASE", ["mq", "use_ssl_passphrase"], config
)
ssl_context = ssl.create_default_context()
# If no rejection allowed, use private function to generate unverified context
if not use_ssl_reject_unauthorized:
# noinspection PyUnresolvedReferences,PyProtectedMember
ssl_context = ssl._create_unverified_context()
ssl_verify_locations(ssl_context, use_ssl_ca)
# Thanks to https://bugs.python.org/issue16487 is not possible today to easily use memory pem
# in SSL context. We need to write it to a temporary file before
ssl_cert_chain(ssl_context, use_ssl_cert, use_ssl_key, use_ssl_passphrase)
return ssl_context
class ListenQueue(threading.Thread):
"""Main class for the ListenQueue used in OpenCTIConnectorHelper
:param helper: instance of a `OpenCTIConnectorHelper` class
:type helper: OpenCTIConnectorHelper
:param config: dict containing client config
:type config: Dict
:param callback: callback function to process queue
:type callback: callable
"""
def __init__(
self,
helper,
config: Dict,
connector_config: Dict,
applicant_id,
callback,
) -> None:
threading.Thread.__init__(self)
self.pika_credentials = None
self.pika_parameters = None
self.pika_connection = None
self.channel = None
self.helper = helper
self.callback = callback
self.config = config
self.connector_applicant_id = applicant_id
self.host = connector_config["connection"]["host"]
self.vhost = connector_config["connection"]["vhost"]
self.use_ssl = connector_config["connection"]["use_ssl"]
self.port = connector_config["connection"]["port"]
self.user = connector_config["connection"]["user"]
self.password = connector_config["connection"]["pass"]
self.queue_name = connector_config["listen"]
self.exit_event = threading.Event()
self.thread = None
# noinspection PyUnusedLocal
def _process_message(self, channel, method, properties, body) -> None:
"""process a message from the rabbit queue
:param channel: channel instance
:type channel: callable
:param method: message methods
:type method: callable
:param properties: unused
:type properties: str
:param body: message body (data)
:type body: str or bytes or bytearray
"""
json_data = json.loads(body)
# Message should be ack before processing as we don't own the processing
# Not ACK the message here may lead to infinite re-deliver if the connector is broken
# Also ACK, will not have any impact on the blocking aspect of the following functions
channel.basic_ack(delivery_tag=method.delivery_tag)
self.helper.connector_logger.info("Message ack", {"tag": method.delivery_tag})
self.thread = threading.Thread(target=self._data_handler, args=[json_data])
self.thread.start()
five_minutes = 60 * 5
time_wait = 0
# Wait for end of execution of the _data_handler
while self.thread.is_alive(): # Loop while the thread is processing
self.pika_connection.sleep(0.05)
if (
self.helper.work_id is not None and time_wait > five_minutes
): # Ping every 5 minutes
self.helper.api.work.ping(self.helper.work_id)
time_wait = 0
else:
time_wait += 1
time.sleep(1)
self.helper.connector_logger.info(
"Message processed, thread terminated",
{"tag": method.delivery_tag},
)
def _data_handler(self, json_data) -> None:
# Execute the callback
try:
event_data = json_data["event"]
entity_id = event_data.get("entity_id")
entity_type = event_data.get("entity_type")
# Set the API headers
work_id = json_data["internal"]["work_id"]
self.helper.work_id = work_id
self.helper.playbook = None
self.helper.enrichment_shared_organizations = None
if self.helper.connect_type == "INTERNAL_ENRICHMENT":
# For enrichment connectors only, pre resolve the information
if entity_id is None:
raise ValueError(
"Internal enrichment must be based on a specific id"
)
do_read = self.helper.api.stix2.get_reader(
entity_type if entity_type is not None else "Stix-Core-Object"
)
opencti_entity = do_read(id=entity_id, withFiles=True)
if opencti_entity is None:
raise ValueError(
"Unable to read/access to the entity, please check that the connector permission"
)
event_data["enrichment_entity"] = opencti_entity
# Handle action vs playbook behavior
is_playbook = "playbook" in json_data["internal"]
# If playbook, compute object on data bundle
if is_playbook:
execution_start = self.helper.date_now()
event_id = json_data["internal"]["playbook"].get("event_id")
execution_id = json_data["internal"]["playbook"].get("execution_id")
playbook_id = json_data["internal"]["playbook"].get("playbook_id")
data_instance_id = json_data["internal"]["playbook"].get(
"data_instance_id"
)
previous_bundle = json.dumps((json_data["event"]["bundle"]))
step_id = json_data["internal"]["playbook"]["step_id"]
previous_step_id = json_data["internal"]["playbook"][
"previous_step_id"
]
playbook_data = {
"event_id": event_id,
"execution_id": execution_id,
"execution_start": execution_start,
"playbook_id": playbook_id,
"data_instance_id": data_instance_id,
"previous_step_id": previous_step_id,
"previous_bundle": previous_bundle,
"step_id": step_id,
}
self.helper.playbook = playbook_data
bundle = event_data["bundle"]
stix_objects = bundle["objects"]
event_data["stix_objects"] = stix_objects
stix_entity = [e for e in stix_objects if e["id"] == entity_id][0]
event_data["stix_entity"] = stix_entity
else:
# If not playbook but enrichment, compute object on enrichment_entity
opencti_entity = event_data["enrichment_entity"]
stix_objects = self.helper.api.stix2.prepare_export(
entity=self.helper.api.stix2.generate_export(
copy.copy(opencti_entity)
)
)
stix_entity = [
e
for e in stix_objects
if e["id"] == opencti_entity["standard_id"]
][0]
event_data["stix_objects"] = stix_objects
event_data["stix_entity"] = stix_entity
# Handle organization propagation
# Keep the sharing to be re-apply automatically at send_stix_bundle stage
if "x_opencti_granted_refs" in event_data["stix_entity"]:
self.helper.enrichment_shared_organizations = event_data[
"stix_entity"
]["x_opencti_granted_refs"]
else:
self.helper.enrichment_shared_organizations = (
self.helper.get_attribute_in_extension(
"granted_refs", event_data["stix_entity"]
)
)
# Handle applicant_id for in-personalization
self.helper.applicant_id = self.connector_applicant_id
self.helper.api_impersonate.set_applicant_id_header(
self.connector_applicant_id
)
applicant_id = json_data["internal"]["applicant_id"]
if applicant_id is not None:
self.helper.applicant_id = applicant_id
self.helper.api_impersonate.set_applicant_id_header(applicant_id)
if work_id:
self.helper.api.work.to_received(
work_id, "Connector ready to process the operation"
)
# Send the enriched to the callback
message = self.callback(event_data)
if work_id:
self.helper.api.work.to_processed(work_id, message)
except Exception as e: # pylint: disable=broad-except
self.helper.metric.inc("error_count")
self.helper.connector_logger.error(
"Error in message processing, reporting error to API"
)
if work_id:
try:
self.helper.api.work.to_processed(work_id, str(e), True)
except: # pylint: disable=bare-except
self.helper.metric.inc("error_count")
self.helper.connector_logger.error(
"Failing reporting the processing"
)
def run(self) -> None:
self.helper.connector_logger.info("Starting ListenQueue thread")
while not self.exit_event.is_set():
try:
self.helper.connector_logger.info("ListenQueue connecting to rabbitMq.")
# Connect the broker
self.pika_credentials = pika.PlainCredentials(self.user, self.password)
self.pika_parameters = pika.ConnectionParameters(
heartbeat=10,
blocked_connection_timeout=30,
host=self.host,
port=self.port,
virtual_host=self.vhost,
credentials=self.pika_credentials,
ssl_options=(
pika.SSLOptions(create_mq_ssl_context(self.config), self.host)
if self.use_ssl
else None
),
)
self.pika_connection = pika.BlockingConnection(self.pika_parameters)
self.channel = self.pika_connection.channel()
try:
# confirm_delivery is only for cluster mode rabbitMQ
# when not in cluster mode this line raise an exception
self.channel.confirm_delivery()
except Exception as err: # pylint: disable=broad-except
self.helper.connector_logger.debug(str(err))
self.channel.basic_qos(prefetch_count=1)
assert self.channel is not None
self.channel.basic_consume(
queue=self.queue_name, on_message_callback=self._process_message
)
self.channel.start_consuming()
except Exception as err: # pylint: disable=broad-except
try:
self.pika_connection.close()
except Exception as errInException:
self.helper.connector_logger.debug(
type(errInException).__name__, {"reason": str(errInException)}
)
self.helper.connector_logger.error(
type(err).__name__, {"reason": str(err)}
)
# Wait some time and then retry ListenQueue again.
time.sleep(10)
def stop(self):
self.helper.connector_logger.info("Preparing ListenQueue for clean shutdown")
self.exit_event.set()
self.pika_connection.close()
if self.thread:
self.thread.join()
class PingAlive(threading.Thread):
def __init__(
self,
connector_logger,
connector_id,
api,
get_state,
set_state,
metric,
connector_info,
) -> None:
threading.Thread.__init__(self, daemon=True)
self.connector_logger = connector_logger
self.connector_id = connector_id
self.in_error = False
self.api = api
self.get_state = get_state
self.set_state = set_state
self.exit_event = threading.Event()
self.metric = metric
self.connector_info = connector_info
def ping(self) -> None:
while not self.exit_event.is_set():
try:
self.connector_logger.debug("PingAlive running.")
initial_state = self.get_state()
connector_info = self.connector_info.all_details
self.connector_logger.debug(
"PingAlive ConnectorInfo", {"connector_info": connector_info}
)
result = self.api.connector.ping(
self.connector_id, initial_state, connector_info
)
remote_state = (
json.loads(result["connector_state"])
if result["connector_state"] is not None
and len(result["connector_state"]) > 0
else None
)
if initial_state != remote_state:
self.set_state(result["connector_state"])
self.connector_logger.info(
"Connector state has been remotely reset",
{"state": self.get_state()},
)
if self.in_error:
self.in_error = False
self.connector_logger.info("API Ping back to normal")
self.metric.inc("ping_api_count")
except Exception as e: # pylint: disable=broad-except
self.in_error = True
self.metric.inc("ping_api_error")
self.connector_logger.error("Error pinging the API", {"reason": str(e)})
self.exit_event.wait(40)
def run(self) -> None:
self.connector_logger.info("Starting PingAlive thread")
self.ping()
def stop(self) -> None:
self.connector_logger.info("Preparing PingAlive for clean shutdown")
self.exit_event.set()
class StreamAlive(threading.Thread):
def __init__(self, helper, q) -> None:
threading.Thread.__init__(self)
self.helper = helper
self.q = q
self.exit_event = threading.Event()
def run(self) -> None:
try:
self.helper.connector_logger.info("Starting StreamAlive thread")
time_since_last_heartbeat = 0
while not self.exit_event.is_set():
time.sleep(5)
self.helper.connector_logger.debug("StreamAlive running")
try:
self.q.get(block=False)
time_since_last_heartbeat = 0
except queue.Empty:
time_since_last_heartbeat = time_since_last_heartbeat + 5
if time_since_last_heartbeat > 45:
self.helper.connector_logger.error(
"Time since last heartbeat exceeded 45s, stopping the connector"
)
break
self.helper.connector_logger.info(
"Exit event in StreamAlive loop, stopping process."
)
sys.excepthook(*sys.exc_info())
except Exception as ex:
self.helper.connector_logger.error(
"Error in StreamAlive loop, stopping process.", {"reason": str(ex)}
)
sys.excepthook(*sys.exc_info())
def stop(self) -> None:
self.helper.connector_logger.info("Preparing StreamAlive for clean shutdown")
self.exit_event.set()
class ListenStream(threading.Thread):
def __init__(
self,
helper,
callback,
url,
token,
verify_ssl,
start_timestamp,
live_stream_id,
listen_delete,
no_dependencies,
recover_iso_date,
with_inferences,
) -> None:
threading.Thread.__init__(self)
self.helper = helper
self.callback = callback
self.url = url
self.token = token
self.verify_ssl = verify_ssl
self.start_timestamp = start_timestamp
self.live_stream_id = live_stream_id
self.listen_delete = listen_delete
self.no_dependencies = no_dependencies
self.recover_iso_date = recover_iso_date
self.with_inferences = with_inferences
self.exit_event = threading.Event()
def run(self) -> None: # pylint: disable=too-many-branches
try:
self.helper.connector_logger.info("Starting ListenStream thread")
current_state = self.helper.get_state()
start_from = self.start_timestamp
recover_until = self.recover_iso_date
if current_state is None:
# First run, if no timestamp in config, put "0-0"
if start_from is None:
start_from = "0-0"
# First run, if no recover iso date in config, put today
if recover_until is None:
recover_until = self.helper.date_now_z()
self.helper.set_state(
{"start_from": start_from, "recover_until": recover_until}
)
else:
# Get start_from from state
# Backward compat
if "connectorLastEventId" in current_state:
start_from = current_state["connectorLastEventId"]
# Current implem
else:
start_from = current_state["start_from"]
# Get recover_until from state
# Backward compat
if "connectorStartTime" in current_state:
recover_until = current_state["connectorStartTime"]
# Current implem
else:
recover_until = current_state["recover_until"]
# Start the stream alive watchdog
q = Queue(maxsize=1)
stream_alive = StreamAlive(self.helper, q)
stream_alive.start()
# Computing args building
live_stream_url = self.url
# In case no recover is explicitely set
if recover_until is not False and recover_until not in [
"no",
"none",
"No",
"None",
"false",
"False",
]:
live_stream_url = live_stream_url + "?recover=" + recover_until
listen_delete = str(self.listen_delete).lower()
no_dependencies = str(self.no_dependencies).lower()
with_inferences = str(self.with_inferences).lower()
self.helper.connector_logger.info(
"Starting to listen stream events",
{
"live_stream_url": live_stream_url,
"listen_delete": listen_delete,
"no_dependencies": no_dependencies,
"with_inferences": with_inferences,
},
)
messages = SSEClient(
live_stream_url,
start_from,
headers={
"authorization": "Bearer " + self.token,
"listen-delete": listen_delete,
"no-dependencies": no_dependencies,
"with-inferences": with_inferences,
},
verify=self.verify_ssl,
)
# Iter on stream messages
for msg in messages:
if self.exit_event.is_set():
stream_alive.stop()
break
if msg.id is not None:
try:
q.put(msg.event, block=False)
except queue.Full:
pass
if msg.event == "heartbeat" or msg.event == "connected":
state = self.helper.get_state()
# state can be None if reset from the UI
# In this case, default parameters will be used but SSE Client needs to be restarted
if state is None:
self.exit_event.set()
else:
state["start_from"] = str(msg.id)
self.helper.set_state(state)
else:
self.callback(msg)
state = self.helper.get_state()
# state can be None if reset from the UI
# In this case, default parameters will be used but SSE Client needs to be restarted
if state is None:
self.exit = True
state["start_from"] = str(msg.id)
self.helper.set_state(state)
except Exception as ex:
self.helper.connector_logger.error(
"Error in ListenStream loop, exit.", {"reason": str(ex)}
)
sys.excepthook(*sys.exc_info())
def stop(self):
self.helper.connector_logger.info("Preparing ListenStream for clean shutdown")
self.exit_event.set()
class ConnectorInfo:
def __init__(
self,
run_and_terminate: bool = False,
buffering: bool = False,
queue_threshold: float = 500.0,
queue_messages_size: float = 0.0,
next_run_datetime: datetime = None,
last_run_datetime: datetime = None,
):
self._run_and_terminate = run_and_terminate
self._buffering = buffering
self._queue_threshold = queue_threshold
self._queue_messages_size = queue_messages_size
self._next_run_datetime = next_run_datetime
self._last_run_datetime = last_run_datetime
@property
def all_details(self):
return {
"run_and_terminate": self._run_and_terminate,
"buffering": self._buffering,
"queue_threshold": self._queue_threshold,
"queue_messages_size": self._queue_messages_size,
"next_run_datetime": self._next_run_datetime,
"last_run_datetime": self._last_run_datetime,
}
@property
def run_and_terminate(self) -> bool:
return self._run_and_terminate
@run_and_terminate.setter
def run_and_terminate(self, value):
self._run_and_terminate = value
@property
def buffering(self) -> bool:
return self._buffering
@buffering.setter
def buffering(self, value):
self._buffering = value
@property
def queue_threshold(self) -> float:
return self._queue_threshold
@queue_threshold.setter
def queue_threshold(self, value):
self._queue_threshold = value
@property
def queue_messages_size(self) -> float:
return self._queue_messages_size
@queue_messages_size.setter
def queue_messages_size(self, value):
self._queue_messages_size = value
@property
def next_run_datetime(self) -> datetime:
return self._next_run_datetime
@next_run_datetime.setter
def next_run_datetime(self, value):
self._next_run_datetime = value
@property
def last_run_datetime(self) -> datetime:
return self._last_run_datetime
@last_run_datetime.setter
def last_run_datetime(self, value):
self._last_run_datetime = value
class OpenCTIConnectorHelper: # pylint: disable=too-many-public-methods
"""Python API for OpenCTI connector
:param config: dict standard config
:type config: Dict
"""
class TimeUnit(Enum):
SECONDS = 1
MINUTES = 60
HOURS = 3600
DAYS = 86400
WEEKS = 604800
YEARS = 31536000
def __init__(self, config: Dict, playbook_compatible=False) -> None:
sys.excepthook = killProgramHook
# Load API config
self.config = config
self.opencti_url = get_config_variable(
"OPENCTI_URL", ["opencti", "url"], config
)
self.opencti_token = get_config_variable(
"OPENCTI_TOKEN", ["opencti", "token"], config
)
self.opencti_ssl_verify = get_config_variable(
"OPENCTI_SSL_VERIFY", ["opencti", "ssl_verify"], config, False, False
)
self.opencti_json_logging = get_config_variable(
"OPENCTI_JSON_LOGGING", ["opencti", "json_logging"], config, False, True
)
# Load connector config
self.connect_id = get_config_variable(
"CONNECTOR_ID", ["connector", "id"], config
)
self.queue_protocol = get_config_variable(
"QUEUE_PROTOCOL", ["connector", "queue_protocol"], config, default="amqp"
)
self.connect_type = get_config_variable(
"CONNECTOR_TYPE", ["connector", "type"], config
)
self.connect_queue_threshold = get_config_variable(
"CONNECTOR_QUEUE_THRESHOLD",
["connector", "queue_threshold"],
config,
default=500, # Mo
)
self.connect_duration_period = get_config_variable(
"CONNECTOR_DURATION_PERIOD", ["connector", "duration_period"], config
)
self.connect_live_stream_id = get_config_variable(
"CONNECTOR_LIVE_STREAM_ID",
["connector", "live_stream_id"],
config,
False,
None,
)
self.connect_live_stream_listen_delete = get_config_variable(
"CONNECTOR_LIVE_STREAM_LISTEN_DELETE",
["connector", "live_stream_listen_delete"],
config,
False,
True,
)
self.connect_live_stream_no_dependencies = get_config_variable(
"CONNECTOR_LIVE_STREAM_NO_DEPENDENCIES",
["connector", "live_stream_no_dependencies"],
config,
False,
False,
)
self.connect_live_stream_with_inferences = get_config_variable(
"CONNECTOR_LIVE_STREAM_WITH_INFERENCES",
["connector", "live_stream_with_inferences"],
config,
False,
False,
)
self.connect_live_stream_recover_iso_date = get_config_variable(
"CONNECTOR_LIVE_STREAM_RECOVER_ISO_DATE",
["connector", "live_stream_recover_iso_date"],
config,
)
self.connect_live_stream_start_timestamp = get_config_variable(
"CONNECTOR_LIVE_STREAM_START_TIMESTAMP",
["connector", "live_stream_start_timestamp"],
config,
)
self.connect_name = get_config_variable(
"CONNECTOR_NAME", ["connector", "name"], config
)
self.connect_confidence_level = None # Deprecated since OpenCTI version >= 6.0
self.connect_scope = get_config_variable(
"CONNECTOR_SCOPE", ["connector", "scope"], config
)
self.connect_auto = get_config_variable(
"CONNECTOR_AUTO", ["connector", "auto"], config, False, False
)
self.bundle_send_to_queue = get_config_variable(
"CONNECTOR_SEND_TO_QUEUE",
["connector", "send_to_queue"],
config,
False,
True,
)
self.bundle_send_to_directory = get_config_variable(
"CONNECTOR_SEND_TO_DIRECTORY",
["connector", "send_to_directory"],
config,
False,
False,
)
self.bundle_send_to_directory_path = get_config_variable(
"CONNECTOR_SEND_TO_DIRECTORY_PATH",
["connector", "send_to_directory_path"],
config,
)
self.bundle_send_to_directory_retention = get_config_variable(
"CONNECTOR_SEND_TO_DIRECTORY_RETENTION",
["connector", "send_to_directory_retention"],
config,
True,
7,
)
self.connect_only_contextual = get_config_variable(
"CONNECTOR_ONLY_CONTEXTUAL",
["connector", "only_contextual"],
config,
False,
False,
)
self.log_level = get_config_variable(
"CONNECTOR_LOG_LEVEL", ["connector", "log_level"], config, default="INFO"
).upper()
self.connect_run_and_terminate = get_config_variable(
"CONNECTOR_RUN_AND_TERMINATE",
["connector", "run_and_terminate"],
config,
False,
False,
)
self.connect_validate_before_import = get_config_variable(
"CONNECTOR_VALIDATE_BEFORE_IMPORT",
["connector", "validate_before_import"],
config,
False,
False,
)
self.scheduler = sched.scheduler(time.time, time.sleep)
# Start up the server to expose the metrics.
expose_metrics = get_config_variable(
"CONNECTOR_EXPOSE_METRICS",
["connector", "expose_metrics"],
config,
False,
False,
)
metrics_port = get_config_variable(
"CONNECTOR_METRICS_PORT", ["connector", "metrics_port"], config, True, 9095
)
# Initialize ConnectorInfo instance
self.connector_info = ConnectorInfo()
# Initialize configuration
# - Classic API that will be directly attached to the connector rights
self.api = OpenCTIApiClient(
self.opencti_url,
self.opencti_token,
self.log_level,
self.opencti_ssl_verify,
json_logging=self.opencti_json_logging,
bundle_send_to_queue=self.bundle_send_to_queue,
)
# - Impersonate API that will use applicant id
# Behave like standard api if applicant not found
self.api_impersonate = OpenCTIApiClient(
self.opencti_url,
self.opencti_token,
self.log_level,
self.opencti_ssl_verify,
json_logging=self.opencti_json_logging,
bundle_send_to_queue=self.bundle_send_to_queue,
)
self.connector_logger = self.api.logger_class(self.connect_name)
# For retro compatibility
self.log_debug = self.connector_logger.debug
self.log_info = self.connector_logger.info
self.log_warning = self.connector_logger.warning
self.log_error = self.connector_logger.error
# For retro compatibility
self.metric = OpenCTIMetricHandler(
self.connector_logger, expose_metrics, metrics_port
)
# Register the connector in OpenCTI
self.connector = OpenCTIConnector(
self.connect_id,
self.connect_name,
self.connect_type,
self.connect_scope,
self.connect_auto,
self.connect_only_contextual,
playbook_compatible,
)
connector_configuration = self.api.connector.register(self.connector)
self.connector_logger.info(
"Connector registered with ID", {"id": self.connect_id}
)
self.work_id = None
self.playbook = None
self.enrichment_shared_organizations = None
self.connector_id = connector_configuration["id"]
self.applicant_id = connector_configuration["connector_user_id"]
self.connector_state = connector_configuration["connector_state"]
self.connector_config = connector_configuration["config"]
# Overwrite connector config for RabbitMQ if given manually / in conf
self.connector_config["connection"]["host"] = get_config_variable(
"MQ_HOST",
["mq", "host"],
config,
default=self.connector_config["connection"]["host"],
)
self.connector_config["connection"]["port"] = get_config_variable(
"MQ_PORT",
["mq", "port"],
config,
isNumber=True,
default=self.connector_config["connection"]["port"],
)
self.connector_config["connection"]["vhost"] = get_config_variable(
"MQ_VHOST",
["mq", "vhost"],
config,
default=self.connector_config["connection"]["vhost"],
)
self.connector_config["connection"]["use_ssl"] = get_config_variable(
"MQ_USE_SSL",
["mq", "use_ssl"],
config,
default=self.connector_config["connection"]["use_ssl"],
)
self.connector_config["connection"]["user"] = get_config_variable(
"MQ_USER",
["mq", "user"],
config,
default=self.connector_config["connection"]["user"],
)
self.connector_config["connection"]["pass"] = get_config_variable(
"MQ_PASS",
["mq", "pass"],
config,
default=self.connector_config["connection"]["pass"],
)