-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtry_refactor.py
2141 lines (1912 loc) · 84.1 KB
/
try_refactor.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 json
import os
import datetime
import csv
from typing import Dict
#import dateutil.parser
#from dateutil.parser import *
from stixorm.module.typedb import TypeDBSink, TypeDBSource
from typedb.driver import *
from stixorm.module.orm.import_objects import raw_stix2_to_typeql
from stixorm.module.orm.delete_object import delete_stix_object
from stixorm.module.orm.export_object import convert_ans_to_stix
from stixorm.module.authorise import authorised_mappings, import_type_factory
from stixorm.module.parsing.parse_objects import parse
from stixorm.module.parsing.conversion_decisions import get_embedded_match
#from stixorm.module.generate_docs import configure_overview_table_docs, object_tables
from stixorm.module.initialise import sort_layers, load_typeql_data
from stixorm.module.definitions.stix21 import ObservedData, IPv4Address
from stixorm.module.definitions.os_threat import Feed, ThreatSubObject
from stixorm.module.orm.import_utilities import val_tql
from stixorm.module.typedb_lib.factories.definition_factory import get_definition_factory_instance
from stixorm.module.typedb_lib.model.definitions import DefinitionName
stix_models = get_definition_factory_instance().lookup_definition(DefinitionName.STIX_21)
attack_models = get_definition_factory_instance().lookup_definition(DefinitionName.ATTACK)
os_threat_models = get_definition_factory_instance().lookup_definition(DefinitionName.OS_THREAT)
import copy
import logging
from timeit import default_timer as timer
#from stix.module.typedb_lib.import_type_factory import AttackDomains, AttackVersions
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s')
logger = logging.getLogger(__name__)
#logger.addHandler(logging.StreamHandler())
# define the database data and import details
connection = {
"uri": "localhost",
"port": "1729",
"database": "stix",
"user": None,
"password": None
}
import_type = import_type_factory.get_all_imports()
all_imports = import_type_factory.get_all_imports()
marking =["marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
"marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da",
"marking-definition--f88d31f6-486f-44da-b317-01333bde0b82",
"marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed"]
get_ids = 'match $stix-id isa stix-id; get $stix-id;'
test_id = "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff"
marking_id = "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da"
file_id = 'file--364fe3e5-b1f4-5ba3-b951-ee5983b3538d'
test_ident = {
"type": "identity",
"spec_version": "2.1",
"id": "identity--b349b84d-c237-4959-a658-d431e502b4b0",
"created": "2024-01-27T08:17:42.861Z",
"modified": "2024-01-27T08:17:42.861Z",
"name": "Whooping",
"description": "A Whooping Individual",
"roles": [
"user",
"sales"
],
"identity_class": "individual",
"sectors": [
"technology"
],
"extensions": {
"extension-definition--66e2492a-bbd3-4be6-88f5-cc91a017a498": {
"extension_type": "property-extension",
"first_name": "Whooping",
"last_name": "Whilly",
"middle_name": "Wee",
"prefix": "Mr",
"team": "Sales"
}
}
}
def test_generate_docs():
print("================================================================================")
print("------------------------ Test Doc Generation ---------------------------------------------")
#configure_overview_table_docs(object_tables)
def backdoor_get(stix_id, _composite_filters=None):
"""Retrieve STIX object from file directory via STIX ID.
Args:
stix_id (str): The STIX ID of the STIX object to be retrieved.
_composite_filters (FilterSet): collection of filters passed from the parent
CompositeDataSource, not user supplied
Returns:
(STIX object): STIX object that has the supplied STIX ID.
The STIX object is loaded from its json file, parsed into
a python STIX object and then returned
"""
try:
obj_var, type_ql = get_embedded_match(stix_id, import_type)
match = 'match ' + type_ql + "get;"
#logger.debug(f' typeql -->: {match}')
g_uri = connection["uri"] + ':' + connection["port"]
with TypeDB. core_driver(g_uri) as client:
with client.session(connection["database"], SessionType.DATA) as session:
with session.transaction(TransactionType.READ) as read_transaction:
answer_iterator = read_transaction.query.get(match)
#logger.debug((f'have read the query -> {answer_iterator}'))
stix_dict = convert_ans_to_stix(match, answer_iterator, read_transaction, import_type)
stix_obj = parse(stix_dict, import_type=import_type)
#logger.debug(f'stix_obj -> {stix_obj}')
with open("export_final.json", "w") as outfile:
json.dump(stix_dict, outfile)
except Exception as e:
logger.error(f'Stix Object Retrieval Error: {e}')
stix_obj = None
return stix_obj
def dict_to_typeql(stix_dict, import_type):
""" From the old code base,
- convert a stix dict into a Python object, based on import_type
- convert the object into TypeQL, with a dpendency object
"""
#logger.debug(f"im about to parse \n")
stix_obj = parse(stix_dict, False, import_type)
logger.debug(f' i have parsed {stix_dict}\n')
logger.debug(f"\n object type -> {type(stix_obj)} -> {stix_obj}")
dep_match, dep_insert, indep_ql, core_ql, dep_obj = raw_stix2_to_typeql(stix_obj, import_type)
logger.debug(f'\ndep_match {dep_match} \ndep_insert {dep_insert} \nindep_ql {indep_ql} \ncore_ql {core_ql}')
dep_obj["dep_match"] = dep_match
dep_obj["dep_insert"] = dep_insert
dep_obj["indep_ql"] = indep_ql
dep_obj["core_ql"] = core_ql
return dep_obj
def test_insert_statements(pahhway, stid):
with open(pahhway, mode="r", encoding="utf-8") as f:
json_text = json.load(f)
json_text = json_text["objects"]
for stix_dict in json_text:
if stix_dict['id'] == stid:
dep_obj = dict_to_typeql(stix_dict, import_type)
logger.debug(f'\ndep_match {dep_obj["dep_match"]} \ndep_insert {dep_obj["dep_insert"]} \nindep_ql {dep_obj["indep_ql"]} \ncore_ql {dep_obj["core_ql"]}')
def update_layers(layers, indexes, missing, dep_obj, cyclical):
""" From the old codebase takes a layer and updates it, handling the layer zero case
"""
if len(layers) == 0:
# 4a. For the first record to order
missing = dep_obj['dep_list']
indexes.append(dep_obj['id'])
layers.append(dep_obj)
else:
# 4b. Add up and return the layers, indexes, missing and cyclical lists
add = 'add'
layers, indexes, missing, cyclical = sort_layers(layers, cyclical, indexes, missing, dep_obj, add)
return layers, indexes, missing, cyclical
def backdoor_add_dir(dirpath):
""" Test the database initialisation function
"""
layers = []
indexes = []
missing = []
cyclical = []
type_ql_list = []
id_list = []
obj_list = []
dirFiles = os.listdir(dirpath)
sorted_files = sorted(dirFiles)
typedb_sink = TypeDBSink(connection, True, import_type)
typedb_source = TypeDBSource(connection, import_type)
logger.debug(sorted_files)
for s_file in sorted_files:
if os.path.isdir(os.path.join(dirpath, s_file)):
continue
else:
with open(os.path.join(dirpath, s_file), mode="r", encoding="utf-8") as f:
json_text = json.load(f)
json_text = json_text["objects"]
length = len(json_text)
i=0
for element in json_text:
i += 1
logger.debug(f' processing {i} of {length}')
logger.debug(f'**********{type(element)}==={element}')
obj_list.append(element)
temp_id = element.get('id', False)
if temp_id:
id_list.append(temp_id)
dep_obj = dict_to_typeql(element, import_type)
# logger.debug('----------------------------------------------------------------------------------------------------')
# myobj1 = parse(element, False, import_type)
# logger.debug(myobj1.serialize(pretty=True))
# logger.debug(f'\n================\n{dep_obj["dep_list"]}')
# logger.debug(f'\ndep_match {dep_obj["dep_match"]} \ndep_insert {dep_obj["dep_insert"]} \nindep_ql {dep_obj["indep_ql"]} \ncore_ql {dep_obj["core_ql"]}')
# logger.debug('----------------------------------------------------------------------------------------------------')
layers, indexes, missing, cyclical = update_layers(layers, indexes, missing, dep_obj, cyclical)
logger.debug(f'missing {missing}, cyclical {cyclical}')
newlist = []
duplist = []
missing2 = []
if missing != []:
missing2 = [x for x in missing if x not in id_list]
print(f'\n\n-----------------')
print(f'missing ->{missing}')
print(f'missing2 -> {missing2}')
if missing2 == [] and cyclical == []:
# add the layers into a list of strings
for layer in layers:
stid = layer["id"]
if stid not in newlist:
newlist.append(stid)
dep_match = layer["dep_match"]
dep_insert = layer["dep_insert"]
indep_ql = layer["indep_ql"]
core_ql = layer["core_ql"]
print("\n&&&&&&&&&&&&&&&&&&&&&&&&&")
print(f'{layer["id"]} -> {layer["dep_list"]}')
#print(f'\ndep_match {dep_match} \ndep_insert {dep_insert} \nindep_ql {indep_ql} \ncore_ql {core_ql}')
prestring = ""
if dep_match != "":
prestring = "match " + dep_match
upload_string = prestring + " insert " + indep_ql + dep_insert
print(" ")
print(upload_string)
type_ql_list.append(upload_string)
else:
duplist.append(stid)
# add list of strings to typedb
load_typeql_data(type_ql_list, connection)
id_set = set(id_list)
id_typedb = set(get_stix_ids())
len_files = len(id_set)
len_typedb = len(id_typedb)
id_diff = id_set - id_typedb
sorted_diff = sorted(list(id_diff))
print(f'\n\n\n===========================\nduplist -> {duplist}')
print(f'\n\n\n===========================\ninput len -> {len_files}, typedn len ->{len_typedb}')
print(f'difference -> ')
for id_d in sorted_diff:
print(id_d)
def backdoor_add(pahhway):
""" Test the database initialisation function
"""
typedb = TypeDBSink(connection, True, import_type)
layers = []
indexes = []
missing = []
cyclical = []
type_ql_list = []
id_list = []
with open(pahhway, mode="r", encoding="utf-8") as f:
json_text = json.load(f)
for stix_dict in json_text:
dep_obj = dict_to_typeql(stix_dict, import_type)
layers, indexes, missing, cyclical = update_layers(layers, indexes, missing, dep_obj, cyclical)
print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
print(f"layers -> {layers}")
print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
print(f'missing {missing}, cyclical {cyclical}')
if missing == [] and cyclical == []:
# add the layers into a list of strings
for layer in layers:
stid = layer["id"]
id_list.append(stid)
dep_match = dep_obj["dep_match"]
dep_insert = dep_obj["dep_insert"]
indep_ql = dep_obj["indep_ql"]
core_ql = dep_obj["core_ql"]
#print(f'\ndep_match {dep_match} \ndep_insert {dep_insert} \nindep_ql {indep_ql} \ncore_ql {core_ql}')
prestring = ""
if dep_match != "":
prestring = "match " + dep_match
upload_string = prestring + " insert " + indep_ql + dep_insert
type_ql_list.append(upload_string)
# add list of strings to typedb
load_typeql_data(type_ql_list, connection)
id_set = set(id_list)
id_typedb = set(get_stix_ids())
len_files = len(id_set)
len_typedb = len(id_typedb)
id_diff = id_set - id_typedb
print(f'\n\n\n===========================\ninput len -> {len_files}, typedn len ->{len_typedb}')
print(f'difference -> {id_diff}')
def test_initialise():
""" Test the database initialisation function
"""
typedb = TypeDBSink(connection, True, all_imports)
def load_file_list(path1, file_list):
""" Load a list of files from a path, number of files can be restricted
Args:
path1 (): path
file_list (): list of files
"""
obj_list = []
logger.debug(f' connection {connection}')
typedb = TypeDBSink(connection, True, import_type)
#print(f'files {file_list}')
for i, f in enumerate(file_list):
logger.debug(f'i have entered the file loop, time {i}')
if i > 100:
break
else:
with open((path1+f), mode="r", encoding="utf-8") as df:
#print(f'I am about to history {f}')
json_text = json.load(df)
obj_list.extend(json_text)
typedb.add(obj_list)
def load_file(fullname):
""" Add a json file to typeDB
Args:
fullname (): path and filename
"""
evidence_list = []
logger.debug(f'inside history file {fullname}')
typedb = TypeDBSink(connection, True, import_type)
input_id_list=[]
with open(fullname, mode="r", encoding="utf-8") as f:
json_text = json.load(f)
#print(json_text["objects"])
for stix_dict in json_text["objects"]:
input_id_list.append(stix_dict.get("id", False))
result = typedb.add(json_text)
id_set = set(input_id_list)
id_typedb = set(get_stix_ids())
len_files = len(id_set)
len_typedb = len(id_typedb)
id_diff = id_set - id_typedb
print(f'\n\n\n===========================\ninput len -> {len_files}, typedn len ->{len_typedb}')
print(f'difference -> {id_diff}')
print(f'\n\n\n===========================\ninput len -> {len_files}, typedn len ->{len_typedb}')
for item in result:
print(item.id + " " + str(item.status) + " " + str(item.message))
def check_object(fullname):
logger.debug(f'inside history file {fullname}')
with open(fullname, mode="r", encoding="utf-8") as f:
json_text = json.load(f)
typedb = TypeDBSink(connection, True, import_type)
# first find identity
for jt in json_text:
if jt["type"] == "relationship":
relationship = jt
elif jt["type"] == "x-mitre-tactic":
tactic =jt
elif jt["type"] == "attack-pattern":
if jt["x_mitre_is_subtechnique"] == True:
subtechnique = jt
else:
technique = jt
# try to make an object out of identity
templist=[]
templist.append(relationship)
typedb.add(templist)
# myobj1 = parse(subtechnique, False, import_type)
# print(f'\n\n============> my subtechnique = {myobj1}<==================\n\n')
# myobj2 = parse(technique, False, import_type)
# print(f'\n\n============> my technique = {myobj2}<==================\n\n')
# myobj3 = parse(relationship, False, import_type)
# print(f'\n\n============> my relationship = {myobj3}<==================\n\n')
# myobj4 = parse(tactic, False, import_type)
# print(f'\n\n============> my tactic = {myobj4} <==================\n\n')
def test_get_del_dir_statements(dirpath):
dirFiles = os.listdir(dirpath)
sorted_files = sorted(dirFiles)
for i, s_file in enumerate(sorted_files):
if os.path.isdir(os.path.join(dirpath, s_file)) or i<0:
continue
else:
file_list.append(s_file)
#print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
#print(f'==================== {s_file} ===================================')
with open(os.path.join(dirpath, s_file), mode="r", encoding="utf-8") as f:
json_text = json.load(f)
for jt in json_text:
stid = jt["id"]
query_id(stid)
def test_get_delete(fullname):
#load_file(fullname)
id_list = get_stix_ids()
print(f"\n\n=============\n------{id_list}-------\n$$$$$$$$$$$$$$$$$$$$$\n")
for inc, obj_id in enumerate(id_list):
print(f'\n==========\n---------- {inc + 1} of {len(id_list)} -------\n===========')
query_id(obj_id)
print(f'id list -> {id_list}')
def query_id(stixid):
""" Print out the match/insert and match/delete statements for any stix-id
Args:
stixid ():
"""
typedb = TypeDBSource(connection, import_type)
print(f'stixid -> {stixid}')
#stix_dict = typedb.get(stixid)
stix_dict = backdoor_get(stixid)
stix_obj = stix_dict #parse(stix_dict)
print(' ---------------------------Query Object----------------------')
print(stix_obj.serialize(pretty=True))
dep_match, dep_insert, indep_ql, core_ql, dep_obj = raw_stix2_to_typeql(stix_obj, import_type)
print(' ---------------------------Insert Object----------------------')
print(f'dep_match -> {dep_match}')
print(f'dep_insert -> {dep_insert}')
print(f'indep_ql -> {indep_ql}')
print(f'core_ql -> {core_ql}')
print("=========================== delete typeql below ====================================")
del_match, del_tql = delete_stix_object(stix_obj, dep_match, dep_insert, indep_ql, core_ql, import_type)
print(f'del_match -> {del_match}')
print(f'del_tql -> {del_tql}')
def get_stix_ids(get_id_query = get_ids):
""" Get all the stix-ids in a database, should be moved to typedb_lib file
Returns:
id_list : list of the stix-ids in the database
"""
query = get_id_query
g_uri = connection["uri"] + ':' + connection["port"]
id_list = []
with TypeDB. core_driver(g_uri) as client:
with client.session(connection["database"], SessionType.DATA) as session:
with session.transaction(TransactionType.READ) as read_transaction:
logger.debug(f"\n\n query is -> {query}")
answer_iterator = read_transaction.query.get(query)
ids = [ans.get("stix-id") for ans in answer_iterator]
for sid_obj in ids:
sid = sid_obj.as_attribute().as_attribute().get_value()
if sid in marking:
continue
else:
id_list.append(sid)
return id_list
def clean_db():
""" Get all stix-ids and delete them
"""
local_list = get_stix_ids()
print(f'list -> {local_list}')
for stid in local_list:
print(f"\nid is -> {stid}\n")
query_id(stid)
typedb = TypeDBSink(connection, False, import_type)
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$ Ready for Delete $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
typedb.delete(local_list)
print(f"len db ids before delete -> {len(local_list)}")
print(f"db ids after delete -> {len(get_stix_ids())}")
def test_delete_dir(dirpath):
""" Load an entire directory and delete all files except marking objects
Args:
dirpath (): path to directory to delete
"""
dirFiles = os.listdir(dirpath)
sorted_files = sorted(dirFiles)
typedb_sink = TypeDBSink(connection, True, import_type)
print(sorted_files)
layers = []
indexes = []
missing = []
cyclical = []
obj_list = []
input_id_list = []
file_list = []
for i, s_file in enumerate(sorted_files):
if os.path.isdir(os.path.join(dirpath, s_file)) or i<0:
continue
else:
file_list.append(s_file)
#print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
#print(f'==================== {s_file} ===================================')
with open(os.path.join(dirpath, s_file), mode="r", encoding="utf-8") as f:
json_text = json.load(f)
for stix_dict in json_text:
input_id_list.append(stix_dict.get("id", False))
obj_list.append(stix_dict)
# dep_obj = dict_to_typeql(stix_dict, import_type)
# layers, indexes, missing, cyclical = update_layers(layers, indexes, missing, dep_obj, cyclical)
#typedb_sink.add(json_text)
#print(json.dumps(json_text, indent=4))
#print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
# print(f'missing {missing}, cyclical {cyclical}')
# if missing == [] and cyclical == []:
# # add the layers into a list of strings
# for layer in layers:
# dep_match = dep_obj["dep_match"]
# dep_insert = dep_obj["dep_insert"]
# indep_ql = dep_obj["indep_ql"]
# core_ql = dep_obj["core_ql"]
# print(f'\ndep_match {dep_match} \ndep_insert {dep_insert} \nindep_ql {indep_ql} \ncore_ql {core_ql}')
# prestring = ""
# if dep_match != "":
# prestring = "match " + dep_match
# upload_string = prestring + " insert " + indep_ql + dep_insert
# type_ql_list.append(upload_string)
#
# # add list of strings to typedb
# load_typeql_data(type_ql_list, connection)
typedb_sink.add(obj_list)
print("**********************************************************************************")
print("----------------------------------------------------------------------------------")
print("============= Add is complete =====================================================")
print("**********************************************************************************")
stix_id_list = set(get_stix_ids())
for stid in stix_id_list:
print(f"\nid is -> {stid}\n")
query_id(stid)
print("**********************************************************************************")
print("----------------------------------------------------------------------------------")
print("============= Get is complete =====================================================")
print("**********************************************************************************")
typedb_sink.delete(stix_id_list)
#clean_db()
#print(f' files-> {file_list}')
print(f"\n\nlen input ids -> {len(set(input_id_list))} ")
print(f"len db ids before delete -> {len(stix_id_list)}")
print(f"db ids after delete -> {len(get_stix_ids())}")
def test_delete(path):
""" Load a single file and delete it
Args:
path (): the path and file name
"""
obj_ids = []
typedb = TypeDBSink(connection, True, import_type)
with open(path, mode="r", encoding="utf-8") as f:
json_text = json.load(f)
typedb.add(json_text)
local_list = get_stix_ids()
typedb.delete(local_list)
def check_dir_ids(dirpath):
""" Open a directory and history all the files,
one at a time to the database and then check the ids
Args:
dirpath ():
"""
id_list = []
dirFiles = os.listdir(dirpath)
sorted_files = sorted(dirFiles)
print(sorted_files)
typedb_sink = TypeDBSink(connection, True, import_type)
typedb_source = TypeDBSource(connection, import_type)
for s_file in sorted_files:
if os.path.isdir(os.path.join(dirpath, s_file)):
continue
else:
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
print(f'==================== {s_file} ===================================')
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
with open(os.path.join(dirpath, s_file), mode="r", encoding="utf-8") as f:
json_text = json.load(f)
for element in json_text:
print(f'**********==={element}')
temp_id = element.get('id', False)
if temp_id:
id_list.append(temp_id)
typedb_sink.add(json_text)
id_set = set(id_list)
id_typedb = set(get_stix_ids())
len_files = len(id_set)
len_typedb = len(id_typedb)
id_diff = id_set - id_typedb
print(f'\n\n\n===========================\ninput len -> {len_files}, typedn len ->{len_typedb}')
print(f'difference -> {id_diff}')
def check_dir_ids2(dirpath):
""" Open a directory and history all the files,
creating a list of objects first and then adding them to the db
Args:
dirpath ():
"""
id_list = []
obj_list = []
dirFiles = os.listdir(dirpath)
sorted_files = sorted(dirFiles)
#print(sorted_files)
typedb_sink = TypeDBSink(connection, True, import_type)
typedb_source = TypeDBSource(connection, import_type)
for s_file in sorted_files:
if os.path.isdir(os.path.join(dirpath, s_file)):
continue
else:
# print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
# print(f'==================== {s_file} ===================================')
# print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
with open(os.path.join(dirpath, s_file), mode="r", encoding="utf-8") as f:
json_text = json.load(f)
for element in json_text:
#print(f'**********==={element}')
obj_list.append(element)
temp_id = element.get('id', False)
if temp_id:
id_list.append(temp_id)
typedb_sink.add(obj_list)
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
print(f'==================== Add is Complete ===================================')
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
id_set = set(id_list)
id_typedb = set(get_stix_ids())
len_files = len(id_set)
len_typedb = len(id_typedb)
id_diff = id_set - id_typedb
print(f'\n\n\n===========================\ninput len -> {len_files}, typedn len ->{len_typedb}')
print(f'difference -> {id_diff}')
def check_dir(dirpath):
""" Open a directory and history all the files, optionally printing them
Args:
dirpath ():
"""
id_list = []
dirFiles = os.listdir(dirpath)
list_of_objects = []
sorted_files = sorted(dirFiles)
print(sorted_files)
typedb_sink = TypeDBSink(connection, True, import_type)
typedb_source = TypeDBSource(connection, import_type)
for s_file in sorted_files:
if os.path.isdir(os.path.join(dirpath, s_file)):
continue
else:
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
print(f'==================== {s_file} ===================================')
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
with open(os.path.join(dirpath, s_file), mode="r", encoding="utf-8") as f:
testtime = datetime.now()
print(f"I am opening the file {testtime}")
json_list = json.load(f)
#json_list = json_list["objects"]
for element in json_list:
#print(f'element is {element}')
temp_id = element.get('id', False)
if temp_id:
id_list.append(temp_id)
list_of_objects = list_of_objects + json_list
print(f'9999999999999999999999999 Add {len(list_of_objects)} 99999999999999999999999999999999999999999999')
typedb_sink.add(list_of_objects)
print(f'==================== List is added ===================================')
id_set = set(id_list)
id_typedb = set(get_stix_ids())
len_files = len(id_set)
len_typedb = len(id_typedb)
id_diff = id_set - id_typedb
print(f'\n\n\n===========================\ninput len -> {len_files}, typedn len ->{len_typedb}')
sorted_diff = sorted(list(id_diff))
print(f'difference -> ')
for id_d in sorted_diff:
print(id_d)
def cert_dict(cert_root, certs):
for cert in certs:
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
print(f'==================== {cert} ===================================')
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
cert_test(cert_root + cert)
def cert_test(dirpath):
dirs = [
"consumer_example/",
"consumer_test/",
"producer_example/",
"producer_test/"
]
for d in dirs:
#print(f'############## {dirpath+d} #################')
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
#print(f'handler {logger.handlers}')
print('----------------------------------------')
dirFiles = os.listdir(dirpath+d)
for s_file in dirFiles:
if os.path.isdir(os.path.join((dirpath+d), s_file)):
continue
else:
local_list1 = []
print(f's-file {s_file}')
with open(os.path.join(dirpath+d, s_file), mode="r", encoding="utf-8") as f:
json_text = json.load(f)
for l in json_text:
local_list1.append(l["id"])
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
print(f'==================== {dirpath+d+s_file} ===================================')
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
load_file(dirpath+d+s_file)
local_list = get_stix_ids()
print(f'my id list -> {local_list}')
print('========================= I am starting deletion ===========================================')
typedb = TypeDBSink(connection, False, import_type)
typedb.delete(local_list)
local_list2 = get_stix_ids()
print("******************************************")
print(f'\n\nmy initial list is -> {local_list1}')
print(f'\n\nmy returned list is -> {local_list}')
print(f'\n\nmy final list is -> {local_list2}')
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
def test_get_ids(connection, import_type):
typedb_sink = TypeDBSink(connection, False, import_type)
my_id_list = typedb_sink.get_stix_ids()
print(f'myidlist {my_id_list}')
def test_get(stixid):
typedb_source = TypeDBSource(connection, import_type)
stix_obj = typedb_source.get(stixid, None)
return stix_obj
def test_get_file(fullname):
load_file(fullname)
typedb_sink = TypeDBSink(connection, False, import_type)
stid_list = typedb_sink.get_stix_ids()
for stid in stid_list:
stix_obj = test_get(stid)
def test_json(fullname):
with open(fullname, mode="r", encoding="utf-8") as f:
json_text = json.load(f)
for jt in json_text:
print("===========================================")
print(jt)
def test_auth():
# import_type = import_type_factory.create_import(stix_21=True,
# os_hunt=True,
# os_intel=True,
# cacao=True,
# attack_domains=[AttackDomains.ENTERPRISE_ATTACK, AttackDomains.ICS_ATTACK, AttackDomains.MOBILE_ATTACK],
# attack_versions=[AttackVersions.V12_1])
auth = authorised_mappings(import_type)
print("===========================================")
print(auth)
# ObservedData, IPv4Address, Feed, ThreatSubObject
###################################################################################
#
# Setup Feeds import and update code
#
##################################################################################
def test_feeds():
osthreat = "data/os-threat/feed-example/example.json"
# # datetime1 = dateutil.parser.isoparse("2020-10-19T01:01:01.000Z")
# # datetime2 = dateutil.parser.isoparse("2020-10-20T01:01:01.000Z")
# # datetime3 = dateutil.parser.isoparse("2020-10-21T01:01:01.000Z")
# typedb_source = TypeDBSource(connection, import_type)
# typedb_sink = TypeDBSink(connection, True, import_type)
# with open(osthreat, mode="r", encoding="utf-8") as f:
# json_text = json.load(f)
# # first lets create the feed
# feed_id = create_feed(json_text[0], typedb_sink, datetime1)
# print(f'feed id -> {feed_id}')
# update_feed(feed_id, json_text[1], datetime2, typedb_source, typedb_sink)
def update_feed(feed_id, local_list, loc_datetime, typedb_source, typedb_sink):
# get the feed
sco_map = {}
sco_loaded_list = []
feed_obj = typedb_source.get(feed_id, None)
# get the observed data objects
loc_contents = feed_obj["contents"]
for loc_content in loc_contents:
observed_id = loc_content["object_ref"] # get the observed data id
observed_obj = typedb_source.get(observed_id, None)
sco_list = observed_obj["object_refs"]
# we make the assumption there is only one sco for every observed-data object
for sco in sco_list:
sco_obj = typedb_source.get(sco, None)
sco_map[sco_obj["value"]] = observed_obj
# build the list of scos that are laoded already
sco_loaded_list = list(sco_map.keys())
set_sco_loaded = set(sco_loaded_list)
set_new_sco = set(local_list)
update_date_list = list(set_sco_loaded & set_new_sco)
revoke_list = list(set_sco_loaded - set_new_sco)
insert_list = list(set_new_sco - set_sco_loaded)
# plus new ips
print(f'\n==== revoke =====\n{revoke_list}')
revoke_observed(feed_id, revoke_list, sco_map)
print(f"\n==== update =====\n{update_date_list}")
update_observed_and_feed_dates(feed_id, update_date_list, sco_map, loc_datetime)
print(f'\n==== insert =====\n{insert_list}')
insert_observed(feed_id, insert_list, loc_datetime, typedb_sink)
print("===============================================")
def insert_observed(feed_id, insert_list, loc_datetime, typedb_sink):
ips = []
observed = []
obs_ids = []
insert_tql_list = []
for ipaddr in insert_list:
ip = IPv4Address(value=ipaddr)
ips.append(ip)
obs = ObservedData(
first_observed=loc_datetime,
last_observed=loc_datetime,
number_observed=1,
object_refs =[ip.id]
)
observed.append(obs)
obs_ids.append(obs.id)
add_list = ips + observed
typedb_sink.add(add_list)
for obs_id in obs_ids:
insert_tql = 'match $obs isa observed-data, has stix-id "' + obs_id + '";'
insert_tql += '$feed isa feed, has stix-id "' + feed_id + '";' # get the feed
insert_tql += 'insert $sub isa threat-sub-object, has created ' + val_tql(loc_datetime) + ','
insert_tql += 'has modified ' + val_tql(loc_datetime) + ';'
insert_tql += '$objref (container:$sub,content:$obs) isa obj-ref;'
insert_tql += '$content (content:$sub, feed-owner:$feed) isa feed-content;'
insert_tql_list.append(insert_tql)
insert_typeql_data(insert_tql_list, connection)
def revoke_observed(feed_id, revoke_list, sco_map):
insert_tql_list = []
update_tql_list = []
for rev in revoke_list:
observed_obj = sco_map[rev]
if not getattr(observed_obj, "revoked", False):
# revoke the observed data object, but the revoke property is there and is false, so update to make it true
revoke_tql = 'match $x isa observed-data, has stix-id "' + observed_obj['id'] + '";'
revoke_tql += 'insert $x has revoked true;'
insert_tql_list.append(revoke_tql)
#update_typeql_data(update_tql_list, connection)
insert_typeql_data(insert_tql_list, connection)
def update_observed_and_feed_dates(feed_id, update_date_list, sco_map, loc_datetime):
update_tql_list = []
obs_id_list = []
feed_update_list = []
# update the observed data objects
for up in update_date_list:
observed_obj = sco_map[up]
obs_id_list.append(observed_obj["id"])
# update the observed data object, modified, and last observed and feed modified
update_obs_tql = 'match $obs isa observed-data, has stix-id "' + observed_obj['id'] + '",'
update_obs_tql += 'has last-observed $last_obs, has modified $mod, has number-observed $num_obs;'
update_obs_tql += 'delete $obs has $last_obs; $obs has $mod; $obs has $num_obs;'
update_obs_tql += 'insert $obs has last-observed ' + val_tql(loc_datetime) + ';'
update_obs_tql += '$obs has modified ' + val_tql(loc_datetime) + ';' # this is the observed data object
update_obs_tql += '$obs has number-observed ' + str(observed_obj['number_observed'] + 1) + ';'
update_tql_list.append(update_obs_tql)
# update the threat sub object
for obs_id in obs_id_list:
update_threat_tql = 'match $feed isa feed, has stix-id "' + feed_id + '";'
update_threat_tql += '$obs isa observed-data, has stix-id "' + obs_id + '";'
update_threat_tql += '$threat isa threat-sub-object, has modified $mod;'
update_threat_tql += '$objref (container:$threat,content:$obs) isa obj-ref;'
update_threat_tql += '$content (content:$threat, feed-owner:$feed) isa feed-content;'
update_threat_tql += 'delete $threat has $mod;'
update_threat_tql += 'insert $threat has modified ' + val_tql(loc_datetime) + ';'
feed_update_list.append(update_threat_tql)
# update the feed object modified date
update_feed_tql = 'match $feed isa feed, has stix-id "' + feed_id + '";'
update_feed_tql += '$feed has modified $mod;'
update_feed_tql += 'delete $feed has $mod;'
update_feed_tql += 'insert $feed has modified ' + val_tql(loc_datetime) + ';' # this is the feed object
feed_update_list.append(update_feed_tql)
# update the typeql
update_typeql_data(update_tql_list, connection)
update_typeql_data(feed_update_list, connection)
def create_feed(local_list, typedb_sink, loc_datetime):
ips = []
observed = []
threatsubobj = []
for ipaddr in local_list:
ip = IPv4Address(value=ipaddr)
ips.append(ip)
obs = ObservedData(
first_observed=loc_datetime,
last_observed=loc_datetime,
number_observed=1,
object_refs =[ip.id]
)
observed.append(obs)
sub = ThreatSubObject(
object_ref=obs.id,
created=loc_datetime,
modified=loc_datetime
)
threatsubobj.append(sub)
feed = Feed(
name="OS Threat Feed",
description="OS Threat Test Feed",
created=loc_datetime,
contents=[
threatsubobj[0],
threatsubobj[1],
threatsubobj[2],
threatsubobj[3]
]
)
add_list = ips + observed + [feed]
typedb_sink.add(add_list)
return feed.id
def update_typeql_data(data_list, stix_connection: Dict[str, str]):
url = stix_connection["uri"] + ":" + stix_connection["port"]
with TypeDB. core_driver(url) as client:
# Update the data in the database
with client.session(stix_connection["database"], SessionType.DATA) as session:
with session.transaction(TransactionType.WRITE) as update_transaction:
logger.debug(f'==================== updating feed concepts =======================')
for data in data_list:
logger.debug(f'\n\n{data}\n\n')
insert_iterator = update_transaction.query.update(data)
logger.debug(f'insert_iterator response ->\n{insert_iterator}')
for result in insert_iterator:
logger.info(f'typedb response ->\n{result}')
update_transaction.commit()
def insert_typeql_data(data_list, stix_connection: Dict[str, str]):
url = stix_connection["uri"] + ":" + stix_connection["port"]
with TypeDB. core_driver(url) as client:
# Update the data in the database
with client.session(stix_connection["database"], SessionType.DATA) as session: