forked from OpenCTI-Platform/client-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopencti_stix2.py
2662 lines (2537 loc) · 114 KB
/
opencti_stix2.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
# coding: utf-8
import base64
import datetime
import json
import os
import random
import time
import traceback
import uuid
from typing import Any, Dict, List, Optional, Union
import datefinder
import dateutil.parser
import pytz
from cachetools import LRUCache
from opentelemetry import metrics
from requests import RequestException, Timeout
from pycti.entities.opencti_identity import Identity
from pycti.utils.constants import (
IdentityTypes,
LocationTypes,
MultipleRefRelationship,
StixCyberObservableTypes,
ThreatActorTypes,
)
from pycti.utils.opencti_stix2_splitter import OpenCTIStix2Splitter
from pycti.utils.opencti_stix2_update import OpenCTIStix2Update
from pycti.utils.opencti_stix2_utils import (
OBSERVABLES_VALUE_INT,
STIX_CYBER_OBSERVABLE_MAPPING,
)
datefinder.ValueError = ValueError, OverflowError
utc = pytz.UTC
# Spec version
SPEC_VERSION = "2.1"
ERROR_TYPE_LOCK = "LOCK_ERROR"
ERROR_TYPE_MISSING_REFERENCE = "MISSING_REFERENCE_ERROR"
ERROR_TYPE_BAD_GATEWAY = "Bad Gateway"
ERROR_TYPE_TIMEOUT = "Request timed out"
# Extensions
STIX_EXT_OCTI = "extension-definition--ea279b3e-5c71-4632-ac08-831c66a786ba"
STIX_EXT_OCTI_SCO = "extension-definition--f93e2c80-4231-4f9a-af8b-95c9bd566a82"
STIX_EXT_MITRE = "extension-definition--322b8f77-262a-4cb8-a915-1e441e00329b"
PROCESSING_COUNT: int = 4
meter = metrics.get_meter(__name__)
bundles_timeout_error_counter = meter.create_counter(
name="opencti_bundles_timeout_error_counter",
description="number of bundles in timeout error",
)
bundles_lock_error_counter = meter.create_counter(
name="opencti_bundles_lock_error_counter",
description="number of bundles in lock error",
)
bundles_missing_reference_error_counter = meter.create_counter(
name="opencti_bundles_missing_reference_error_counter",
description="number of bundles in missing reference error",
)
bundles_bad_gateway_error_counter = meter.create_counter(
name="opencti_bundles_bad_gateway_error_counter",
description="number of bundles in bad gateway error",
)
bundles_timed_out_error_counter = meter.create_counter(
name="opencti_bundles_timed_out_error_counter",
description="number of bundles in timed out error",
)
bundles_technical_error_counter = meter.create_counter(
name="opencti_bundles_technical_error_counter",
description="number of bundles in technical error",
)
bundles_success_counter = meter.create_counter(
name="opencti_bundles_success_counter",
description="number of bundles successfully processed",
)
class OpenCTIStix2:
"""Python API for Stix2 in OpenCTI
:param opencti: OpenCTI instance
"""
def __init__(self, opencti):
self.opencti = opencti
self.stix2_update = OpenCTIStix2Update(opencti)
self.mapping_cache = LRUCache(maxsize=50000)
self.mapping_cache_permanent = {}
######### UTILS
# region utils
def unknown_type(self, stix_object: Dict) -> None:
self.opencti.app_logger.error(
"Unknown object type, doing nothing...", {"type": stix_object["type"]}
)
def convert_markdown(self, text: str) -> str:
"""converts input text to markdown style code annotation
:param text: input text
:type text: str
:return: sanitized text with markdown style code annotation
:rtype: str
"""
if text is not None:
return text.replace("<code>", "`").replace("</code>", "`")
else:
return None
def format_date(self, date: Any = None) -> str:
"""converts multiple input date formats to OpenCTI style dates
:param date: input date
:type date: Any [datetime, date, str or none]
:return: OpenCTI style date
:rtype: string
"""
if isinstance(date, datetime.datetime):
date_value = date
elif isinstance(date, datetime.date):
date_value = datetime.datetime.combine(date, datetime.datetime.min.time())
elif isinstance(date, str):
try:
date_value = dateutil.parser.parse(date)
except (dateutil.parser.ParserError, TypeError, OverflowError) as e:
raise ValueError(f"{e}: {date} does not contain a valid date string")
else:
date_value = datetime.datetime.utcnow()
if not date_value.tzinfo:
self.opencti.app_logger.info("No timezone found. Setting to UTC")
date_value = date_value.replace(tzinfo=datetime.timezone.utc)
return date_value.isoformat(timespec="milliseconds").replace("+00:00", "Z")
def filter_objects(self, uuids: List, objects: List) -> List:
"""filters objects based on UUIDs
:param uuids: list of UUIDs
:type uuids: list
:param objects: list of objects to filter
:type objects: list
:return: list of filtered objects
:rtype: list
"""
result = []
if objects is not None:
for item in objects:
if "id" in item and item["id"] not in uuids:
result.append(item)
return result
def pick_aliases(self, stix_object: Dict) -> Optional[List]:
"""check stix2 object for multiple aliases and return a list
:param stix_object: valid stix2 object
:type stix_object:
:return: list of aliases
:rtype: list
"""
# Add aliases
if "x_opencti_aliases" in stix_object:
return stix_object["x_opencti_aliases"]
elif "x_mitre_aliases" in stix_object:
return stix_object["x_mitre_aliases"]
elif "x_amitt_aliases" in stix_object:
return stix_object["x_amitt_aliases"]
elif "aliases" in stix_object:
return stix_object["aliases"]
return None
def import_bundle_from_file(
self, file_path: str, update: bool = False, types: List = None
) -> Optional[List]:
"""import a stix2 bundle from a file
:param file_path: valid path to the file
:type file_path: str
:param update: whether to updated data in the database, defaults to False
:type update: bool, optional
:param types: list of stix2 types, defaults to None
:type types: list, optional
:return: list of imported stix2 objects
:rtype: List
"""
if not os.path.isfile(file_path):
self.opencti.app_logger.error("The bundle file does not exists")
return None
with open(os.path.join(file_path), encoding="utf-8") as file:
data = json.load(file)
return self.import_bundle(data, update, types)
def import_bundle_from_json(
self,
json_data: Union[str, bytes],
update: bool = False,
types: List = None,
work_id: str = None,
) -> List:
"""import a stix2 bundle from JSON data
:param json_data: JSON data
:type json_data:
:param update: whether to updated data in the database, defaults to False
:type update: bool, optional
:param types: list of stix2 types, defaults to None
:type types: list, optional
:param work_id work_id: str, optional
:return: list of imported stix2 objects
:rtype: List
"""
data = json.loads(json_data)
return self.import_bundle(data, update, types, work_id)
def resolve_author(self, title: str) -> Optional[Identity]:
if "fireeye" in title.lower() or "mandiant" in title.lower():
return self.get_author("FireEye")
if "eset" in title.lower():
return self.get_author("ESET")
if "dragos" in title.lower():
return self.get_author("Dragos")
if "us-cert" in title.lower():
return self.get_author("US-CERT")
if (
"unit 42" in title.lower()
or "unit42" in title.lower()
or "palo alto" in title.lower()
):
return self.get_author("Palo Alto Networks")
if "accenture" in title.lower():
return self.get_author("Accenture")
if "symantec" in title.lower():
return self.get_author("Symantec")
if "trendmicro" in title.lower() or "trend micro" in title.lower():
return self.get_author("Trend Micro")
if "mcafee" in title.lower():
return self.get_author("McAfee")
if "crowdstrike" in title.lower():
return self.get_author("CrowdStrike")
if "securelist" in title.lower() or "kaspersky" in title.lower():
return self.get_author("Kaspersky")
if "f-secure" in title.lower():
return self.get_author("F-Secure")
if "checkpoint" in title.lower():
return self.get_author("CheckPoint")
if "talos" in title.lower():
return self.get_author("Cisco Talos")
if "secureworks" in title.lower():
return self.get_author("Dell SecureWorks")
if "microsoft" in title.lower():
return self.get_author("Microsoft")
if "mitre att&ck" in title.lower():
return self.get_author("The MITRE Corporation")
return None
def get_author(self, name: str) -> Identity:
if name in self.mapping_cache:
return self.mapping_cache[name]
else:
author = self.opencti.identity.create(
type="Organization",
name=name,
description="",
)
self.mapping_cache[name] = author
return author
def extract_embedded_relationships(
self, stix_object: Dict, types: List = None
) -> Dict:
"""extracts embedded relationship objects from a stix2 entity
:param stix_object: valid stix2 object
:type stix_object:
:param types: list of stix2 types, defaults to None
:type types: list, optional
:return: embedded relationships as dict
:rtype: dict
"""
# Created By Ref
created_by_id = None
if "created_by_ref" in stix_object:
created_by_id = stix_object["created_by_ref"]
elif "x_opencti_created_by_ref" in stix_object:
created_by_id = stix_object["x_opencti_created_by_ref"]
elif (
self.opencti.get_attribute_in_extension("created_by_ref", stix_object)
is not None
):
created_by_id = self.opencti.get_attribute_in_extension(
"created_by_ref", stix_object
)
# Object Marking Refs
object_marking_ids = (
stix_object["object_marking_refs"]
if "object_marking_refs" in stix_object
else []
)
# Open vocabularies
object_open_vocabularies = {}
if self.mapping_cache_permanent.get("vocabularies_definition_fields") is None:
self.mapping_cache_permanent["vocabularies_definition_fields"] = []
query = """
query getVocabCategories {
vocabularyCategories {
key
fields{
key
required
}
}
}
"""
result = self.opencti.query(query)
for category in result["data"]["vocabularyCategories"]:
for field in category["fields"]:
self.mapping_cache_permanent[
"vocabularies_definition_fields"
].append(field)
self.mapping_cache_permanent["category_" + field["key"]] = category[
"key"
]
if any(
field["key"] in stix_object
for field in self.mapping_cache_permanent["vocabularies_definition_fields"]
):
for f in self.mapping_cache_permanent["vocabularies_definition_fields"]:
if (
stix_object.get(f["key"]) is None
or len(stix_object.get(f["key"])) == 0
):
continue
if isinstance(stix_object.get(f["key"]), list):
object_open_vocabularies[f["key"]] = []
for vocab in stix_object[f["key"]]:
object_open_vocabularies[f["key"]].append(
self.opencti.vocabulary.handle_vocab(
vocab, self.mapping_cache_permanent, field=f
)["name"]
)
else:
object_open_vocabularies[f["key"]] = (
self.opencti.vocabulary.handle_vocab(
stix_object[f["key"]], self.mapping_cache_permanent, field=f
)["name"]
)
# Object Labels
object_label_ids = []
if (
"labels" not in stix_object
and self.opencti.get_attribute_in_extension("labels", stix_object)
is not None
):
stix_object["labels"] = self.opencti.get_attribute_in_extension(
"labels", stix_object
)
if "labels" in stix_object:
for label in stix_object["labels"]:
if "label_" + label in self.mapping_cache:
label_data = self.mapping_cache["label_" + label]
else:
# Fail in label creation is allowed
label_data = self.opencti.label.read_or_create_unchecked(
value=label
)
if label_data is not None:
self.mapping_cache["label_" + label] = label_data
object_label_ids.append(label_data["id"])
elif "x_opencti_labels" in stix_object:
for label in stix_object["x_opencti_labels"]:
if "label_" + label in self.mapping_cache:
label_data = self.mapping_cache["label_" + label]
else:
# Fail in label creation is allowed
label_data = self.opencti.label.read_or_create_unchecked(
value=label
)
if label_data is not None:
self.mapping_cache["label_" + label] = label_data
object_label_ids.append(label_data["id"])
elif "x_opencti_tags" in stix_object:
for tag in stix_object["x_opencti_tags"]:
label = tag["value"]
color = tag["color"] if "color" in tag else None
if "label_" + label in self.mapping_cache:
label_data = self.mapping_cache["label_" + label]
else:
# Fail in label creation is allowed
label_data = self.opencti.label.read_or_create_unchecked(
value=label, color=color
)
if label_data is not None:
self.mapping_cache["label_" + label] = label_data
object_label_ids.append(label_data["id"])
# Kill Chain Phases
kill_chain_phases_ids = []
if (
"kill_chain_phases" not in stix_object
and self.opencti.get_attribute_in_extension(
"kill_chain_phases", stix_object
)
is not None
):
stix_object["kill_chain_phases"] = self.opencti.get_attribute_in_extension(
"kill_chain_phases", stix_object
)
if "kill_chain_phases" in stix_object:
for kill_chain_phase in stix_object["kill_chain_phases"]:
if (
kill_chain_phase["kill_chain_name"] + kill_chain_phase["phase_name"]
in self.mapping_cache
):
kill_chain_phase = self.mapping_cache[
kill_chain_phase["kill_chain_name"]
+ kill_chain_phase["phase_name"]
]
else:
if (
"x_opencti_order" not in kill_chain_phase
and self.opencti.get_attribute_in_extension(
"order", kill_chain_phase
)
is not None
):
kill_chain_phase["x_opencti_order"] = (
self.opencti.get_attribute_in_extension(
"order", kill_chain_phase
)
)
kill_chain_phase = self.opencti.kill_chain_phase.create(
kill_chain_name=kill_chain_phase["kill_chain_name"],
phase_name=kill_chain_phase["phase_name"],
x_opencti_order=(
kill_chain_phase["x_opencti_order"]
if "x_opencti_order" in kill_chain_phase
else 0
),
stix_id=(
kill_chain_phase["id"] if "id" in kill_chain_phase else None
),
)
self.mapping_cache[
kill_chain_phase["kill_chain_name"]
+ kill_chain_phase["phase_name"]
] = {
"id": kill_chain_phase["id"],
"type": kill_chain_phase["entity_type"],
}
kill_chain_phases_ids.append(kill_chain_phase["id"])
elif "x_opencti_kill_chain_phases" in stix_object:
for kill_chain_phase in stix_object["x_opencti_kill_chain_phases"]:
if (
kill_chain_phase["kill_chain_name"] + kill_chain_phase["phase_name"]
in self.mapping_cache
):
kill_chain_phase = self.mapping_cache[
kill_chain_phase["kill_chain_name"]
+ kill_chain_phase["phase_name"]
]
else:
if (
"x_opencti_order" not in kill_chain_phase
and self.opencti.get_attribute_in_extension(
"order", kill_chain_phase
)
is not None
):
kill_chain_phase["x_opencti_order"] = (
self.opencti.get_attribute_in_extension(
"order", kill_chain_phase
)
)
kill_chain_phase = self.opencti.kill_chain_phase.create(
kill_chain_name=kill_chain_phase["kill_chain_name"],
phase_name=kill_chain_phase["phase_name"],
x_opencti_order=(
kill_chain_phase["x_opencti_order"]
if "x_opencti_order" in kill_chain_phase
else 0
),
stix_id=(
kill_chain_phase["id"] if "id" in kill_chain_phase else None
),
)
self.mapping_cache[
kill_chain_phase["kill_chain_name"]
+ kill_chain_phase["phase_name"]
] = {
"id": kill_chain_phase["id"],
"type": kill_chain_phase["entity_type"],
}
kill_chain_phases_ids.append(kill_chain_phase["id"])
# Object refs
object_refs_ids = (
stix_object["object_refs"] if "object_refs" in stix_object else []
)
# External References
reports = {}
external_references_ids = []
if (
"external_references" not in stix_object
and self.opencti.get_attribute_in_extension(
"external_references", stix_object
)
is not None
):
stix_object["external_references"] = (
self.opencti.get_attribute_in_extension(
"external_references", stix_object
)
)
if "external_references" in stix_object:
for external_reference in stix_object["external_references"]:
try:
url = (
external_reference["url"]
if "url" in external_reference
else None
)
source_name = (
external_reference["source_name"]
if "source_name" in external_reference
else None
)
external_id = (
external_reference["external_id"]
if "external_id" in external_reference
else None
)
generated_ref_id = self.opencti.external_reference.generate_id(
url, source_name, external_id
)
if generated_ref_id is None:
continue
else:
external_reference_id = self.opencti.external_reference.create(
source_name=source_name,
url=url,
external_id=external_id,
description=(
external_reference["description"]
if "description" in external_reference
else None
),
)["id"]
if "x_opencti_files" in external_reference:
for file in external_reference["x_opencti_files"]:
if "data" in file:
self.opencti.external_reference.add_file(
id=external_reference_id,
file_name=file["name"],
version=file.get("version", None),
data=base64.b64decode(file["data"]),
mime_type=file["mime_type"],
no_trigger_import=file.get(
"no_trigger_import", False
),
)
if (
self.opencti.get_attribute_in_extension(
"files", external_reference
)
is not None
):
for file in self.opencti.get_attribute_in_extension(
"files", external_reference
):
if "data" in file:
self.opencti.external_reference.add_file(
id=external_reference_id,
file_name=file["name"],
version=file.get("version", None),
data=base64.b64decode(file["data"]),
mime_type=file["mime_type"],
no_trigger_import=file.get(
"no_trigger_import", False
),
)
external_references_ids.append(external_reference_id)
if stix_object["type"] in [
"threat-actor",
"intrusion-set",
"campaign",
"incident",
"malware",
"relationship",
] and (
types is not None and "external-reference-as-report" in types
):
# Add a corresponding report
# Extract date
try:
if "description" in external_reference:
matches = datefinder.find_dates(
external_reference["description"],
base_date=datetime.datetime.fromtimestamp(0),
)
else:
matches = datefinder.find_dates(
source_name,
base_date=datetime.datetime.fromtimestamp(0),
)
except:
matches = None
published = None
yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
default_date = datetime.datetime.fromtimestamp(1)
if matches is not None:
try:
for match in matches:
if (
match.timestamp() < yesterday.timestamp()
and len(str(match.year)) == 4
):
published = match.strftime("%Y-%m-%dT%H:%M:%SZ")
break
except:
pass
if published is None:
published = default_date.strftime("%Y-%m-%dT%H:%M:%SZ")
if "mitre" in source_name and "name" in stix_object:
title = "[MITRE ATT&CK] " + stix_object["name"]
if "modified" in stix_object:
published = stix_object["modified"]
elif "amitt" in source_name and "name" in stix_object:
title = "[AM!TT] " + stix_object["name"]
if "modified" in stix_object:
published = stix_object["modified"]
else:
title = source_name
if "external_id" in external_reference:
title = (
title
+ " ("
+ str(external_reference["external_id"])
+ ")"
)
if "marking_tlpclear" in self.mapping_cache:
object_marking_ref_result = self.mapping_cache[
"marking_tlpclear"
]
else:
object_marking_ref_result = (
self.opencti.marking_definition.read(
filters={
"mode": "and",
"filters": [
{
"key": "definition_type",
"values": ["TLP"],
},
{
"key": "definition",
"values": ["TLP:CLEAR"],
},
],
"filterGroups": [],
}
)
)
self.mapping_cache["marking_tlpclear"] = {
"id": object_marking_ref_result["id"]
}
author = self.resolve_author(title)
report = self.opencti.report.create(
id=self.opencti.report.generate_fixed_fake_id(
title, published
),
name=title,
createdBy=author["id"] if author is not None else None,
objectMarking=[object_marking_ref_result["id"]],
externalReferences=[external_reference_id],
description=(
external_reference["description"]
if "description" in external_reference
else ""
),
report_types="threat-report",
published=published,
update=True,
)
reports[external_reference_id] = report
except:
self.opencti.app_logger.warning(
"Cannot generate external reference"
)
elif "x_opencti_external_references" in stix_object:
for external_reference in stix_object["x_opencti_external_references"]:
url = external_reference["url"] if "url" in external_reference else None
source_name = (
external_reference["source_name"]
if "source_name" in external_reference
else None
)
external_id = (
external_reference["external_id"]
if "external_id" in external_reference
else None
)
generated_ref_id = self.opencti.external_reference.generate_id(
url, source_name, external_id
)
if generated_ref_id is None:
continue
else:
external_reference_id = self.opencti.external_reference.create(
source_name=source_name,
url=url,
external_id=external_id,
description=(
external_reference["description"]
if "description" in external_reference
else None
),
)["id"]
if "x_opencti_files" in external_reference:
for file in external_reference["x_opencti_files"]:
if "data" in file:
self.opencti.external_reference.add_file(
id=external_reference_id,
file_name=file["name"],
version=file.get("version", None),
data=base64.b64decode(file["data"]),
mime_type=file["mime_type"],
no_trigger_import=file.get("no_trigger_import", False),
)
if (
self.opencti.get_attribute_in_extension("files", external_reference)
is not None
):
for file in self.opencti.get_attribute_in_extension(
"files", external_reference
):
if "data" in file:
self.opencti.external_reference.add_file(
id=external_reference_id,
file_name=file["name"],
version=file.get("version", None),
data=base64.b64decode(file["data"]),
mime_type=file["mime_type"],
no_trigger_import=file.get("no_trigger_import", False),
)
external_references_ids.append(external_reference_id)
# Granted refs
granted_refs_ids = []
if (
"x_opencti_granted_refs" not in stix_object
and self.opencti.get_attribute_in_extension("granted_refs", stix_object)
is not None
):
granted_refs_ids = self.opencti.get_attribute_in_extension(
"granted_refs", stix_object
)
elif "x_opencti_granted_refs" in stix_object:
granted_refs_ids = stix_object["x_opencti_granted_refs"]
# Sample refs
sample_refs_ids = (
stix_object["sample_refs"] if "sample_refs" in stix_object else []
)
return {
"created_by": created_by_id,
"object_marking": object_marking_ids,
"object_label": object_label_ids,
"open_vocabs": object_open_vocabularies,
"kill_chain_phases": kill_chain_phases_ids,
"object_refs": object_refs_ids,
"granted_refs": granted_refs_ids,
"sample_refs": sample_refs_ids,
"external_references": external_references_ids,
"reports": reports,
}
# Please use get_reader instead of this definition
def get_readers(self):
return {
"Attack-Pattern": self.opencti.attack_pattern.read,
"Campaign": self.opencti.campaign.read,
"Case-Incident": self.opencti.case_incident.read,
"Case-Rfi": self.opencti.case_rfi.read,
"Case-Rft": self.opencti.case_rft.read,
"Channel": self.opencti.channel.read,
"Course-Of-Action": self.opencti.course_of_action.read,
"Data-Component": self.opencti.data_component.read,
"Data-Source": self.opencti.data_source.read,
"Event": self.opencti.event.read,
"External-Reference": self.opencti.external_reference.read,
"Feedback": self.opencti.feedback.read,
"Grouping": self.opencti.grouping.read,
"Incident": self.opencti.incident.read,
"Identity": self.opencti.identity.read,
"Indicator": self.opencti.indicator.read,
"Infrastructure": self.opencti.infrastructure.read,
"Intrusion-Set": self.opencti.intrusion_set.read,
"Kill-Chain-Phase": self.opencti.kill_chain_phase.read,
"Label": self.opencti.label.read,
"Location": self.opencti.location.read,
"Language": self.opencti.language.read,
"Malware": self.opencti.malware.read,
"Malware-Analysis": self.opencti.malware_analysis.read,
"Marking-Definition": self.opencti.marking_definition.read,
"Narrative": self.opencti.narrative.read,
"Note": self.opencti.note.read,
"Observed-Data": self.opencti.observed_data.read,
"Opinion": self.opencti.opinion.read,
"Report": self.opencti.report.read,
"Stix-Core-Object": self.opencti.stix_core_object.read,
"Stix-Cyber-Observable": self.opencti.stix_cyber_observable.read,
"Stix-Domain-Object": self.opencti.stix_domain_object.read,
"stix-core-relationship": self.opencti.stix_core_relationship.read,
"stix-sighting-relationship": self.opencti.stix_sighting_relationship.read,
"stix-nested-relationship": self.opencti.stix_nested_ref_relationship.read,
"Task": self.opencti.task.read,
"Threat-Actor": self.opencti.threat_actor.read,
"Threat-Actor-Group": self.opencti.threat_actor_group.read,
"Threat-Actor-Individual": self.opencti.threat_actor_individual.read,
"Tool": self.opencti.tool.read,
"Vocabulary": self.opencti.vocabulary.read,
"Vulnerability": self.opencti.vulnerability.read,
}
def get_reader(self, entity_type: str):
# Map types
if entity_type == "StixFile":
entity_type = "File"
if IdentityTypes.has_value(entity_type):
entity_type = "Identity"
if LocationTypes.has_value(entity_type):
entity_type = "Location"
if entity_type == "Container":
entity_type = "Stix-Domain-Object"
if StixCyberObservableTypes.has_value(entity_type):
entity_type = "Stix-Cyber-Observable"
readers = self.get_readers()
return readers.get(
entity_type, lambda **kwargs: self.unknown_type({"type": entity_type})
)
# endregion
# region import
def import_object(
self, stix_object: Dict, update: bool = False, types: List = None
) -> Optional[List]:
"""import a stix2 object
:param stix_object: valid stix2 object
:type stix_object:
:param update: whether to updated data in the database, defaults to False
:type update: bool, optional
:param types: list of stix2 types, defaults to None
:type types: list, optional
:return: list of imported stix2 objects
:rtype: list
"""
self.opencti.app_logger.info(
"Importing an object",
{"type": stix_object["type"], "id": stix_object["id"]},
)
# Extract
embedded_relationships = self.extract_embedded_relationships(stix_object, types)
created_by_id = embedded_relationships["created_by"]
object_marking_ids = embedded_relationships["object_marking"]
object_label_ids = embedded_relationships["object_label"]
open_vocabs = embedded_relationships["open_vocabs"]
kill_chain_phases_ids = embedded_relationships["kill_chain_phases"]
object_refs_ids = embedded_relationships["object_refs"]
external_references_ids = embedded_relationships["external_references"]
reports = embedded_relationships["reports"]
sample_refs_ids = embedded_relationships["sample_refs"]
# Extra
extras = {
"created_by_id": created_by_id,
"object_marking_ids": object_marking_ids,
"object_label_ids": object_label_ids,
"open_vocabs": open_vocabs,
"kill_chain_phases_ids": kill_chain_phases_ids,
"object_ids": object_refs_ids,
"external_references_ids": external_references_ids,
"reports": reports,
"sample_ids": sample_refs_ids,
}
# Import
importer = {
"marking-definition": self.opencti.marking_definition.import_from_stix2,
"attack-pattern": self.opencti.attack_pattern.import_from_stix2,
"campaign": self.opencti.campaign.import_from_stix2,
"channel": self.opencti.channel.import_from_stix2,
"event": self.opencti.event.import_from_stix2,
"note": self.opencti.note.import_from_stix2,
"observed-data": self.opencti.observed_data.import_from_stix2,
"opinion": self.opencti.opinion.import_from_stix2,
"report": self.opencti.report.import_from_stix2,
"grouping": self.opencti.grouping.import_from_stix2,
"case-rfi": self.opencti.case_rfi.import_from_stix2,
"x-opencti-case-rfi": self.opencti.case_rfi.import_from_stix2,
"case-rft": self.opencti.case_rft.import_from_stix2,
"x-opencti-case-rft": self.opencti.case_rft.import_from_stix2,
"task": self.opencti.task.import_from_stix2,
"x-opencti-task": self.opencti.task.import_from_stix2,
"case-incident": self.opencti.case_incident.import_from_stix2,
"x-opencti-case-incident": self.opencti.case_incident.import_from_stix2,
"feedback": self.opencti.feedback.import_from_stix2,
"x-opencti-feedback": self.opencti.feedback.import_from_stix2,
"course-of-action": self.opencti.course_of_action.import_from_stix2,
"data-component": self.opencti.data_component.import_from_stix2,
"x-mitre-data-component": self.opencti.data_component.import_from_stix2,
"data-source": self.opencti.data_source.import_from_stix2,
"x-mitre-data-source": self.opencti.data_source.import_from_stix2,
"identity": self.opencti.identity.import_from_stix2,
"indicator": self.opencti.indicator.import_from_stix2,
"infrastructure": self.opencti.infrastructure.import_from_stix2,
"intrusion-set": self.opencti.intrusion_set.import_from_stix2,
"location": self.opencti.location.import_from_stix2,
"malware": self.opencti.malware.import_from_stix2,
"malware-analysis": self.opencti.malware_analysis.import_from_stix2,
"threat-actor": self.opencti.threat_actor.import_from_stix2,
"tool": self.opencti.tool.import_from_stix2,
"narrative": self.opencti.narrative.import_from_stix2,
"vulnerability": self.opencti.vulnerability.import_from_stix2,
"incident": self.opencti.incident.import_from_stix2,
}
do_import = importer.get(
stix_object["type"],
lambda **kwargs: self.unknown_type(stix_object),
)
stix_object_results = do_import(
stixObject=stix_object, extras=extras, update=update
)
if stix_object_results is None:
return None
if not isinstance(stix_object_results, list):
stix_object_results = [stix_object_results]
for stix_object_result in stix_object_results:
self.mapping_cache[stix_object["id"]] = {
"id": stix_object_result["id"],
"type": stix_object_result["entity_type"],
"observables": (
stix_object_result["observables"]
if "observables" in stix_object_result
else []
),
}
self.mapping_cache[stix_object_result["id"]] = {
"id": stix_object_result["id"],
"type": stix_object_result["entity_type"],
"observables": (
stix_object_result["observables"]
if "observables" in stix_object_result
else []
),
}
# Add reports from external references
for external_reference_id in external_references_ids:
if external_reference_id in reports:
self.opencti.report.add_stix_object_or_stix_relationship(
id=reports[external_reference_id]["id"],
stixObjectOrStixRelationshipId=stix_object_result["id"],
)
# Add files
if "x_opencti_files" in stix_object:
for file in stix_object["x_opencti_files"]:
if "data" in file:
self.opencti.stix_domain_object.add_file(
id=stix_object_result["id"],
file_name=file["name"],
version=file.get("version", None),
data=base64.b64decode(file["data"]),
mime_type=file["mime_type"],
no_trigger_import=file.get("no_trigger_import", False),
)
if (
self.opencti.get_attribute_in_extension("files", stix_object)
is not None
):
for file in self.opencti.get_attribute_in_extension(
"files", stix_object
):
if "data" in file: