-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinitialize.py
1494 lines (1222 loc) · 58.9 KB
/
initialize.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
from copy import Error
import pymisp as pm
from pymisp import api
import malpedia_client as mp_Client
import mitre_functions as mf
import sanitizitation_functions as sf
import globals as gv
import misp_event_functions as mef
import database_actions as db
import os
import sys
import json
import time
import math
import glob
import datetime
import uuid
import misp_galaxy_functions as mgf
# import git_actions
import yaml
# import threading
import concurrent.futures as cf
from globals import _EXECUTOR as executor
# AUTHENTICATE TO MALPEDIA
def Authenticate():
try:
retClient = mp_Client.Client(apitoken=gv._MALPEDIA_KEY)
return retClient
except Exception as e:
print("f(x) Authenticate Error: {}".format(e))
sys.exit(e)
# CHECK IF IS A VALID DATE
def valid_date(datestring):
try:
datetime.datetime.strptime(datestring, '%Y-%m-%d')
return True
except ValueError:
return False
# FIX MALFORMED JSON
def fix_json(iJSON):
try:
yamlData = yaml.safe_load(iJSON)
jsonData = json.dumps(yamlData)
return jsonData
except:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) fix_json: ERROR: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
# READ SPECIMEN DATA FROM JSON FILE
def getSpecimenData(iFamilyName, iSha256):
# if not gv._DEBUG:
# print("{}:{}".format(iFamilyName, iSha256))
specimen_dict = {}
status = ""
version = ""
sha256 = ""
with open(gv._MALPEDIA_OUTPUT + "malware/" + iFamilyName + ".json", 'r') as jsonIn:
specimen_dict = json.loads(fix_json(jsonIn))
jsonIn.close()
for specimen in specimen_dict:
sha256 = specimen["sha256"]
if sha256 == iSha256:
status = specimen["status"]
version = specimen["version"]
break
return status, version, sha256
def stageMalwareSpecimens():
dirList = []
for path in gv._DIR_MALPEDIA_GIT_LIST:
listPath = path.split("/")
if len(listPath) > (gv._FAMILY_SPLIT_DEPTH + 1):
family = path.split("/")[gv._FAMILY_SPLIT_DEPTH]
dirList.append(family)
dirList.sort()
gv._MALWARE_FAMILY_SET = set(dirList)
try:
# DOWNLOAD MALWARE SPECIMENT LISTS AND WRITE THEM TO JSON
# THROTTLE SO IT DOESN'T LOCK API KEY
max_requests_per_minute = 40 #60 requests per minute is the max
current_request_count = 1
completed_malware_list = []
# MAKE THE COMPLETED FILE IF IT DOESN'T EXIST
completed_malware_file_path = gv._MALPEDIA_OUTPUT + "malware/" + "001.completed.maware.json"
if os.path.isfile(completed_malware_file_path):
completed_malware_file = open(completed_malware_file_path, 'r')
completed_malware_list = json.loads(fix_json(completed_malware_file.read()))
completed_malware_file.close()
else:
completed_malware_file = open(completed_malware_file_path, 'w')
completed_malware_file.write(json.dumps("[]"))
completed_malware_file.close
tStart = time.time()
tNow = None
tDiff = 0
iWait = 140
for malware in gv._MALWARE_FAMILY_SET:
if malware in completed_malware_list:
continue
with open(gv._MALPEDIA_OUTPUT + "malware/" + malware + ".json", 'w') as jsonOut:
print("f(x) stageMalwareSpecimens: PULLING DATA FOR MALWARE: {}".format(malware))
mpClient = Authenticate()
gv._CURRENT_FAMILY_CURRENT_SPECIMEN_DICT = mpClient.list_samples(malware)
jsonOut.write(json.dumps(gv._CURRENT_FAMILY_CURRENT_SPECIMEN_DICT))
jsonOut.close()
tNow = time.time()
tDiff = tNow - tStart
if ((current_request_count == max_requests_per_minute) and (tDiff <= iWait )):
tNow = time.time()
tDiff = tNow - tStart
print("f(x) stageMalwareSpecimens: API PULL THRESHHOLD REACHED.")
while (tDiff <= iWait):
time.sleep(1)
tNow = time.time()
tDiff = (tNow - tStart)
print("f(x) stageMalwareSpecimens: WAITING {} SECONDS.".format(math.ceil(iWait - tDiff)))
tStart = time.time()
current_request_count = 1
print("f(x) stageMalwareSpecimens: RESUMING PULLS")
else:
completed_malware_list.append(malware)
completed_malware_file = open(completed_malware_file_path, 'w')
completed_malware_file.write(json.dumps(completed_malware_list))
completed_malware_file.close
current_request_count += 1
# DEBUG SEQ
if gv._DEBUG:
print("f(x) stageMalwareSpecimens: {}: ADDED TO COMPLETED MALWARE.".format(malware))
# os.remove(completed_malware_file_path)
print("f(x) stageMalwareSpecimens: COMPLETED DOWNLOAD OF MALWARE SPECIMEN INFO")
except Exception as e:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) stageMalwareSpecimens: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
sys.exit(e)
def build_actor_malware_tree(threat_actor):
print("f(x) build_actor_malware_tree: STAGING DATA FOR {}".format(threat_actor.upper()))
lastupdated = datetime.date.today()
path_to_json = gv._MALPEDIA_OUTPUT + "actors/" + threat_actor + ".json"
# READ THE THREAT ACTOR JSON FILE
gv._CURRENT_ACTOR_MITRE_GROUP_CODE = "NONE"
gv._CURRENT_ACTOR_MITRE_TECHNIQUE_IDS = []
gv._CURRENT_ACTOR_TECHNIQUE_TAGS = []
with open(path_to_json, 'r') as jsonIn:
try:
gv._CURRENT_ACTOR_INFO_DICT = json.loads(fix_json(jsonIn))
jsonIn.close()
except:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) build_actor_malware_tree: BUILD THREAT ACTOR JSON FILE ERROR: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
#-----------------------------------------------------------------------------------------------------------------
# TOP LEVEL VALUES------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------
if gv._DEBUG:
print("f(x) build_actor_malware_tree: TOP LEVEL")
print("+" * 75)
# STRING NAME OF ACTOR WITH FIRST CHARACTER CAPITALIZED
try:
gv._CURRENT_ACTOR_NAME_STR = gv._CURRENT_ACTOR_INFO_DICT["value"].strip()
except:
gv._CURRENT_ACTOR_NAME_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR NAME: {}".format(gv._CURRENT_ACTOR_NAME_STR))
# STRING OF ACTOR DESCRIPTION
try:
gv._CURRENT_ACTOR_DESCRIPTION_STR = gv._CURRENT_ACTOR_INFO_DICT["description"].strip()
except:
gv._CURRENT_ACTOR_DESCRIPTION_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR DESCRIPTION: {}".format(gv._CURRENT_ACTOR_DESCRIPTION_STR))
# STRING OF UUID
try:
gv._CURRENT_ACTOR_UUID_STR = gv._CURRENT_ACTOR_INFO_DICT["uuid"].strip()
gv._ACTOR_UUID_DICT.update({gv._CURRENT_ACTOR_NAME_STR : gv._CURRENT_ACTOR_UUID_STR})
except:
gv._CURRENT_ACTOR_UUID_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR UUID: {}".format(gv._CURRENT_ACTOR_UUID_STR))
print("+" * 75)
#-----------------------------------------------------------------------------------------------------------------
# ACTOR META SECTION----------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------
# GET META SECTION
try:
gv._CURRENT_ACTOR_META_DICT = gv._CURRENT_ACTOR_INFO_DICT["meta"]
except:
gv._CURRENT_ACTOR_META_DICT = {}
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR META")
print("+" * 75)
# LIST OF STRINGS OF COUNTRY NAMES
try:
gv._CURRENT_ACTOR_META_CFR_SUSPECTED_VICTIMS_LIST = gv._CURRENT_ACTOR_META_DICT["cfr-suspected-victims"]
except:
gv._CURRENT_ACTOR_META_CFR_SUSPECTED_VICTIMS_LIST = []
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR SUSPECTED VICTIMS")
print(*gv._CURRENT_ACTOR_META_CFR_SUSPECTED_VICTIMS_LIST, sep = "\n")
# STRING OF TWO DIGIT COUNTRY CODE
try:
gv._CURRENT_ACTOR_META_COUNTRY_STR = gv._CURRENT_ACTOR_META_DICT["country"].strip()
except:
gv._CURRENT_ACTOR_META_COUNTRY_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR COUNTRY: {}".format(gv._CURRENT_ACTOR_META_COUNTRY_STR))
# print("*" * 50)
# LIST OF STRINGS OF LINKS TO ARTICLES
try:
gv._CURRENT_ACTOR_META_REFS_LIST = gv._CURRENT_ACTOR_META_DICT["refs"]
except:
gv._CURRENT_ACTOR_META_REFS_LIST = []
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR REFERENCES")
print(*gv._CURRENT_ACTOR_META_REFS_LIST, sep = "\n")
# LIST OF STRINGS OF TYPE OF ACTOR
try:
gv._CURRENT_ACTOR_META_CFR_TARGET_CATEGORY_LIST = gv._CURRENT_ACTOR_META_DICT["cfr-target-category"]
except:
gv._CURRENT_ACTOR_META_CFR_TARGET_CATEGORY_LIST = []
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: TYPE OF ACTOR")
print(*gv._CURRENT_ACTOR_META_CFR_TARGET_CATEGORY_LIST, sep = "\n")
# STRING OF TYPE OF INCIDENT
try:
gv._CURRENT_ACTOR_META_CFR_TYPE_OF_INCIDENT_STR = gv._CURRENT_ACTOR_META_DICT["cfr-type-of-incident"].strip()
except:
gv._CURRENT_ACTOR_META_CFR_TYPE_OF_INCIDENT_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR INCIDENT TYPE: {}".format(gv._CURRENT_ACTOR_META_CFR_TYPE_OF_INCIDENT_STR))
# print("*" * 50)
# LIST OF STRINGS OF SYNONYMS
try:
gv._CURRENT_ACTOR_META_SYNONYMS_LIST = gv._CURRENT_ACTOR_META_DICT["synonyms"]
except:
gv._CURRENT_ACTOR_META_SYNONYMS_LIST = []
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR SYNONYMS")
print(*gv._CURRENT_ACTOR_META_SYNONYMS_LIST, sep = "\n")
# STRING OF STATE SPONSOR
try:
gv._CURRENT_ACTOR_META_CFR_STATE_SPONSOR_STR = gv._CURRENT_ACTOR_META_DICT["cfr-suspected-state-sponsor"].strip()
except:
gv._CURRENT_ACTOR_META_CFR_STATE_SPONSOR_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR STATE SPONSOR: {}".format(gv._CURRENT_ACTOR_META_CFR_STATE_SPONSOR_STR))
# print("*" * 50)
# STRING OF VICTIMOLOGY
try:
gv._CURRENT_ACTOR_META_VICTIMOLOGY_STR = gv._CURRENT_ACTOR_META_DICT["victimology"].strip()
except:
gv._CURRENT_ACTOR_META_VICTIMOLOGY_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR VICTIMOLOGY: {}".format(gv._CURRENT_ACTOR_META_VICTIMOLOGY_STR))
# print("*" * 50)
# STRING OF SINCE
try:
gv._CURRENT_ACTOR_META_SINCE_STR = gv._CURRENT_ACTOR_META_DICT["since"].strip()
except:
gv._CURRENT_ACTOR_META_SINCE_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR SINCE: {}".format(gv._CURRENT_ACTOR_META_SINCE_STR))
# print("*" * 50)
# STRING OF MODE OF OPERATION
try:
gv._CURRENT_ACTOR_META_MODEOFOPERATIONS_STR = gv._CURRENT_ACTOR_META_DICT["mode-of-operation"].strip()
except:
gv._CURRENT_ACTOR_META_MODEOFOPERATIONS_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR MODE OF OPERATION: {}".format(gv._CURRENT_ACTOR_META_MODEOFOPERATIONS_STR))
# print("*" * 50)
# STRING OF CAPABILITIES
try:
gv._CURRENT_ACTOR_META_CAPABILITIES_STR = gv._CURRENT_ACTOR_META_DICT["capabilities"].strip()
except:
gv._CURRENT_ACTOR_META_CAPABILITIES_STR = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ACTOR CAPABILITIES: {}".format(gv._CURRENT_ACTOR_META_CAPABILITIES_STR))
# print("*" * 50)
# ---------------------------------------------------------------------
# BEGIN ACTOR META DATA DB INSERT
# ---------------------------------------------------------------------
# TAG FOR ACTOR
# ---------------------------------------------------------------------
# COMMON NAME
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: ACTOR COMMON NAME: {}".format(gv._CURRENT_ACTOR_NAME_STR))
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", gv._CURRENT_ACTOR_NAME_STR, "ACTOR")
# GET / INSERT MITRE GROUP DATA
knownGroupCodes = set()
group_code = ""
if gv._CURRENT_ACTOR_MITRE_GROUP_CODE == "NONE":
try:
gv._CURRENT_ACTOR_MITRE_GROUP_CODE = mf.get_group_code(gv._CURRENT_ACTOR_NAME_STR)
except:
gv._CURRENT_ACTOR_MITRE_GROUP_CODE = "NONE"
group_code = gv._CURRENT_ACTOR_MITRE_GROUP_CODE
if group_code != "NONE":
knownGroupCodes.add(group_code)
# GET MITRE GALAXY TAG:
mitre_tag = []
try:
mitre_tag = db.get_galaxy_specific_tags(group_code, "mitre-intrusion-set")
except Exception as e:
print(e)
mitre_tag = []
for tag in mitre_tag:
iGalaxy = tag["galaxy"]
iTag = tag["tag"]
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, iGalaxy, iTag, "GALAXY")
# GET ACTOR MITRE DATA TECHNIQUES
groupMitreTechniques = []
if len(gv._CURRENT_ACTOR_MITRE_TECHNIQUE_IDS) == 0:
gv._CURRENT_ACTOR_MITRE_TECHNIQUE_IDS = mf.get_group_technique_ids(gv._CURRENT_ACTOR_FAMILIES_CURRENT_FAMILY_STR)
else:
groupMitreTechniques = gv._CURRENT_ACTOR_MITRE_TECHNIQUE_IDS
groupMitreTags = []
if len(gv._CURRENT_ACTOR_TECHNIQUE_TAGS) == 0:
for tID in groupMitreTechniques:
retTags = db.get_galaxy_specific_tags(tID)
gv._CURRENT_ACTOR_TECHNIQUE_TAGS.append(retTags)
else:
groupMitreTags= gv._CURRENT_ACTOR_TECHNIQUE_TAGS
for tag in groupMitreTags:
for sub in tag:
iGalaxy = sub["galaxy"]
iTag = sub["tag"]
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, iGalaxy, iTag, "GALAXY")
# SHORT NAME
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: ACTOR SHORT NAME: {}".format(threat_actor))
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", threat_actor, "ACTOR")
# COUNTRY SPONSOR
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: ACTOR COUNTRY SPONSOR: {}".format(gv._CURRENT_ACTOR_META_CFR_STATE_SPONSOR_STR))
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", gv._CURRENT_ACTOR_META_CFR_STATE_SPONSOR_STR, "COUNTRY_SPONSOR")
# TYPES OF INCIDENTS
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: TYPES OF INCIDENTS: {}".format(gv._CURRENT_ACTOR_META_CFR_TYPE_OF_INCIDENT_STR))
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", gv._CURRENT_ACTOR_META_CFR_TYPE_OF_INCIDENT_STR, "TYPE_OF_INCIDENT")
# ISO COUNTRY (2 CHARACTER)
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: ISO COUNTRY (2 CHARACTER): {}".format(gv._CURRENT_ACTOR_META_COUNTRY_STR))
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", gv._CURRENT_ACTOR_META_COUNTRY_STR, "ISO_COUNTRY")
altActorTechniqueIDs = []
altActorTechniqueTags = set()
currentActorMetaSynonyms = set(gv._CURRENT_ACTOR_META_SYNONYMS_LIST)
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: ALT NAMES FOR THREAT ACTOR")
print(*currentActorMetaSynonyms, sep = "\n")
for value in currentActorMetaSynonyms:
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", value, "ACTOR")
# GET / INSERT MITRE GROUP DATA
group_code = ""
if gv._DEBUG:
print("f(x) build_actor_malware_tree: GETTING MITRE GROUP DATA")
try:
group_code = mf.get_group_code(value)
except:
group_code = gv._CURRENT_ACTOR_MITRE_GROUP_CODE
# IF IT IS NOT ONE WE ALREADY HAVE
if group_code != "NONE" and gv._CURRENT_ACTOR_MITRE_GROUP_CODE != "NONE" and group_code not in knownGroupCodes:
knownGroupCodes.add(group_code)
if gv._DEBUG:
print("f(x) build_actor_malware_tree: ADDING GROUP CODE: {}".format(group_code))
# GET MITRE GALAXY TAG:
mitre_tag = []
try:
mitre_tag = db.get_galaxy_specific_tags(group_code, "mitre-intrusion-set")
except Exception as e:
print("f(x) build_actor_malware_tree: {}".format(e))
mitre_tag = []
for tag in mitre_tag:
iGalaxy = tag["galaxy"]
iTag = tag["tag"]
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, iGalaxy, iTag, "GALAXY")
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT GALAXY: {} TAG: {}".format(iGalaxy, iTag))
altActorTechniqueIDs = mf.get_group_technique_ids(value)
for tID in altActorTechniqueIDs:
retTags = db.get_galaxy_specific_tags(tID)
# INSERT NEWLY DISCOVERED TAGS INTO DATABASE
for sub in retTags:
if sub["uuid"] not in altActorTechniqueTags:
altActorTechniqueTags.add(sub["uuid"])
iGalaxy = sub["galaxy"]
iTag = sub["tag"]
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, iGalaxy, iTag, "GALAXY")
if gv._DEBUG:
print("f(x) build_actor_malware_tree: CORRELATING TAG FROM ALT NAME: {} GALAXY: {} TAG: {}".format(value, iGalaxy, iTag))
else:
if gv._DEBUG:
print("f(x) build_actor_malware_tree: DUPLICATE GROUP CODE SKIPPED")
# VICTIMS
for value in gv._CURRENT_ACTOR_META_CFR_SUSPECTED_VICTIMS_LIST:
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: ACTOR VICTIMS: {}".format(value))
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", value, "VICTIMS")
# TARGETS
for value in gv._CURRENT_ACTOR_META_CFR_TARGET_CATEGORY_LIST:
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: ACTOR: TARGET: {}".format(value))
db.insert_tag(gv._CURRENT_ACTOR_UUID_STR, "", value, "TARGETS")
db.insert_actor(gv._CURRENT_ACTOR_UUID_STR, \
threat_actor, \
gv._CURRENT_ACTOR_NAME_STR, \
gv._CURRENT_ACTOR_META_COUNTRY_STR, \
gv._CURRENT_ACTOR_META_VICTIMOLOGY_STR, \
gv._CURRENT_ACTOR_META_CFR_TYPE_OF_INCIDENT_STR, \
gv._CURRENT_ACTOR_META_CFR_STATE_SPONSOR_STR, \
gv._CURRENT_ACTOR_META_SINCE_STR, \
gv._CURRENT_ACTOR_META_MODEOFOPERATIONS_STR, \
gv._CURRENT_ACTOR_META_CAPABILITIES_STR, \
lastupdated, \
gv._CURRENT_ACTOR_DESCRIPTION_STR )
# ---------------------------------------------------------------------
# ACTOR_CFRSUSPECTEDVICTIMS
for victim in gv._CURRENT_ACTOR_META_CFR_SUSPECTED_VICTIMS_LIST:
if gv._DEBUG:
print("f(x) build_actor_malware_tree: INSERT TAG: VICTIM: VICTIM: {}".format(victim))
db.insert_victims(gv._CURRENT_ACTOR_UUID_STR, victim)
# ---------------------------------------------------------------------
# REFERENCES
for reference in gv._CURRENT_ACTOR_META_REFS_LIST:
if gv._DEBUG:
print ("f(x) build_actor_malware_tree: INSERT REFERENCE: {}".format(reference))
db.insert_reference(gv._CURRENT_ACTOR_UUID_STR, reference)
# ---------------------------------------------------------------------
# ACTOR_CFRTARGETCATEGORY
for targetcategory in gv._CURRENT_ACTOR_META_CFR_TARGET_CATEGORY_LIST:
if gv._DEBUG:
print ("f(x) build_actor_malware_tree: INSERT TARGET CATEGORY: {}".format(targetcategory))
db.insert_target(gv._CURRENT_ACTOR_UUID_STR,targetcategory)
# ---------------------------------------------------------------------
# ACTOR SYNONYMS
for synonym in gv._CURRENT_ACTOR_META_SYNONYMS_LIST:
if gv._DEBUG:
print ("f(x) build_actor_malware_tree: INSERT ACTOR SYNONYM: {}".format(synonym))
db.insert_synonym(gv._CURRENT_ACTOR_UUID_STR, synonym, "ACTOR")
# ---------------------------------------------------------------------
# END ACTOR META DATA DB INSERT
# ---------------------------------------------------------------------
db.insert_parent_child(gv._CURRENT_ACTOR_UUID_STR, \
"", \
threat_actor,
"", \
False, \
"", \
"", \
"", \
"ACTOR", \
"NONE")
def stageActorMalwareMeta():
# BEGIN DOWNLOADING ALL ACTORS
print("f(x) stageActorMalwareMeta: GETTING A LIST OF THREAT ACTORS FROM MALPEDIA")
mpClient = Authenticate()
gv._ACTORS_LIST = mpClient.list_actors()
print("f(x) stageActorMalwareMeta: RETRIEVED LIST OF THREAT ACTORS FROM MALPEDIA")
# WRITE OUT OUTPUT
with open(gv._MALPEDIA_OUTPUT + "actors/" + "001.actors.json", 'w') as jsonOut:
jsonOut.write(json.dumps(gv._ACTORS_LIST))
jsonOut.close()
#BEGIN ACTOR/MALWARE METADATA SECTION
try:
# DOWNLOAD ACTOR PROFILES AND WRITE THEM TO JSON
# THROTTLE SO IT DOESN'T LOCK API KEY
max_requests_per_minute = 40 #60 requests per minute is the max
current_request_count = 1
completed_actors_list = []
# MAKE THE COMPLETED FILE IF IT DOESN'T EXIST
completed_actors_file_path = gv._MALPEDIA_OUTPUT + "actors/" + "001.completed.actors.json"
if os.path.isfile(completed_actors_file_path):
with open(completed_actors_file_path, 'r') as jsonIn:
completed_actors_list = json.loads(fix_json(jsonIn.read()))
jsonIn.close()
else:
with open(completed_actors_file_path, 'w') as jsonOut:
jsonOut.write(json.dumps(" "))
jsonOut.close
tStart = time.time()
tNow = None
tDiff = 0
iWait = 140
for actor_id in gv._ACTORS_LIST:
if actor_id in completed_actors_list:
continue
with open(gv._MALPEDIA_OUTPUT + "actors/" + actor_id + ".json", 'w') as jsonOut:
print("f(x) stageActorMalwareMeta: PULLING DATA FOR ACTOR: {}".format(actor_id))
mpClient = Authenticate()
gv._CURRENT_ACTOR_INFO_DICT = mpClient.get_actor(actor_id)
jsonOut.write(json.dumps(gv._CURRENT_ACTOR_INFO_DICT))
jsonOut.close()
tNow = time.time()
tDiff = tNow - tStart
if ((current_request_count == max_requests_per_minute) and (tDiff <= iWait )):
tNow = time.time()
tDiff = tNow - tStart
print("f(x) stageActorMalwareMeta: API PULL THRESHHOLD REACHED.")
while (tDiff <= iWait):
time.sleep(1)
tNow = time.time()
tDiff = (tNow - tStart)
print("f(x) stageActorMalwareMeta: WAITING {} SECONDS.".format(math.ceil(iWait - tDiff)))
tStart = time.time()
current_request_count = 1
print("f(x) stageActorMalwareMeta: RESUMING PULLS")
else:
completed_actors_list.append(actor_id)
completed_actors_file = open(completed_actors_file_path, 'w')
completed_actors_file.write(json.dumps(completed_actors_list))
completed_actors_file.close
current_request_count += 1
# DEBUG SEQ
if gv._DEBUG:
print("f(x) stageActorMalwareMeta: {}: ADDED TO COMPLETED ACTORS.".format(actor_id))
# os.remove(completed_actors_file_path)
print("f(x) stageActorMalwareMeta: COMPLETED DOWNLOAD OF ACTOR META INFO")
except Exception as e:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) stageActorMalwareMeta ERROR: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
sys.exit(e)
def initGlobals():
if os.getenv('MISP_KEY') and os.getenv("MISP_URL") and os.getenv("MALPEDIA_KEY"):
gv._MISP_KEY = os.getenv('MISP_KEY').replace("\'", "").replace("\"", "")
gv._MISP_URL = os.getenv('MISP_URL').replace("\'", "").replace("\"", "")
gv._MALPEDIA_KEY = os.getenv('MALPEDIA_KEY').replace("\'", "").replace("\"", "")
print("f(x) initGlobals: KEYS SET:\n\tMISP KEY: {}\n\tMISP URL: {}\n\tMALPEDIA KEY: {}".format(gv._MISP_KEY, gv._MISP_URL, gv._MALPEDIA_KEY))
else:
print("f(x) initGlobals: INVALID MISP_KEY, MISP_URL, AND/OR MALPEDIA KEY. EXITING")
return(1)
print("f(x) initGlobals: TESTING CONNECTIVITY TO MISP:", end=' ')
try:
# retVal = 0
mispDB = pm.ExpandedPyMISP(url=gv._MISP_URL, key=gv._MISP_KEY, ssl=gv._MISP_VERIFYCERT, debug=gv._DEBUG)
result = mispDB.get_user()
if result:
print("PASSED")
except Exception as e:
print ("FAILED")
return(1)
print("f(x) initGlobals: TESTING CONNECTIVITY TO MALPEDIA:", end=' ')
try:
mpClient = Authenticate()
result = mpClient.list_samples("win.sslmm")
if result:
print("PASSED")
except Exception as e:
print ("FAILED")
return(1)
# ADD MANUAL TAGS
print("f(x) initGlobals: INSERTING MANUAL TAGS")
db.insert_manual_tags()
# # PULL LATEST MISP GALAXIES
# print("f(x) initGlobals: CLONING MISP GALAXY REPO")
# if os.path.exists(gv._MISP_GALAXY_GIT):
# print("f(x) initGlobals: FOUND OLD MISP GALAXY DIRECTORY. SKIPPING")
# #shutil.rmtree(gv._MISP_GALAXY_GIT)
# else:
# git_actions.clone_misp_galaxy()
# print("f(x) initGlobals: CLONED MISP GALAXY REPO")
# PULL LATEST MALPEDIA
# print("f(x) initGlobals: PULLING MALPEDIA GITHUB")
# git_actions.pull_malpedia_git()
# print("f(x) initGlobals: PULLED MALPEDIA GITHUB")
# # CLONE MITRE REPO
# print("f(x) initGlobals: CLONING MITRE REPO")
# if os.path.exists(gv._MITRE_GIT):
# print("f(x) initGlobals: FOUND OLD MITRE DIRECTORY. SKIPPING")
# #shutil.rmtree(gv._MISP_GALAXY_GIT)
# else:
# git_actions.clone_mitre_git()
# print("f(x) initGlobals: CLONED MITRE REPO")
# LOAD MITRE SOFTWARE
print("f(x) initGlobals: LOADING MITRE SOFTWARE ALIASES INTO DB")
mf.load_mitre_software()
print("f(x) initGlobals: LOADED MITRE SOFTWARE ALIASES INTO DB")
# CREATE OUTPUT DIRECTORIES IF THEY DON'T EXIST
if not os.path.exists(gv._MALPEDIA_OUTPUT):
os.makedirs(gv._MALPEDIA_OUTPUT)
if not os.path.exists(gv._MALPEDIA_OUTPUT + "actors"):
os.makedirs(gv._MALPEDIA_OUTPUT + "actors")
if not os.path.exists(gv._MALPEDIA_OUTPUT + "malware"):
os.makedirs(gv._MALPEDIA_OUTPUT + "malware")
# GET NAME OF MALWARE FAMILIES FROM DIRECTORY LISTING
for name in glob.glob(gv._MALPEDIA_REPOSITORY + "**", recursive=True):
if "yara" not in name and ".json" not in name:
gv._DIR_MALPEDIA_GIT_LIST.append(name)
gv._DIR_MALPEDIA_GIT_LIST.sort()
if gv._DEBUG:
print(*gv._DIR_MALPEDIA_GIT_LIST, sep = "\n")
print("f(x) initGlobals: STAGED ENVIRONMENT")
def stageThreatActors():
for actor in gv._ACTORS_LIST:
if gv._DEBUG:
print("INGESTING ACTOR INTO DATABASE: {}".format(actor))
build_actor_malware_tree(actor)
def removeDuplicates(iUUID, x, lenList):
try:
countUUID = mef.uuidSearch(iUUID)
if countUUID == 0:
print("f(x) removeDuplicates: FOUND UNIQUE UUID {}/{}: {}".format(x, lenList, iUUID))
gv._UUIDS.append(iUUID)
else:
print("f(x) removeDuplicates: REMOVED DUPLICATE UUID {}/{}: {}".format(x, lenList, iUUID))
return True
except Exception as e:
print("f(x) removeDuplicates: ERROR: {}".format(e))
sys.exit(e)
def pushNewEventsIntoMisp(iUUIDS, update=False):
try:
gv._UUIDS = []
oUUIDs = []
# ATTEMPT TO TRIM DOWN LIST IF THIS IS NOT AN UPDATE EVENT
x = 0
lenIUUIDS = len(iUUIDS)
if update == False:
print("f(x) pushNewEventsIntoMisp: CHECKING AND REMOVING DUPLICATES.")
for oUUID in iUUIDS:
x += 1
# removeDuplicates(oUUID["uuid"])
gv._THREAD_LIST.append(executor.submit(removeDuplicates, oUUID["uuid"], x, lenIUUIDS))
# print("f(x) pushNewEventsIntoMisp {}/{}: CHECKING: {}".format(x , lenIUUIDS, oUUID["uuid"]))
oUUIDs = gv._UUIDS
else:
x = 0
for oUUID in iUUIDS:
x += 1
gv._UUIDS.append(oUUID["uuid"])
print("f(x) pushNewEventsIntoMisp: UNIQUE UUID ADDED {}/{}: {}".format(x, x, oUUID["uuid"]))
cf.wait(gv._THREAD_LIST)
gv._THREAD_LIST = []
oUUIDs = gv._UUIDS
gv._UUIDS = []
x = 0
lengvUUIDS = len(oUUIDs)
print("f(x) pushNewEventsIntoMisp: PROCESSING {} EVENTS".format(lengvUUIDS))
for oUUID in oUUIDs:
x += 1
# HAVE TO GET COUNT IN CASE THIS IS AN UPDATE EVENT TO DETERMINE IF YOU NEED TO UPDATE OR INSERT
countUUID = mef.uuidSearch(oUUID)
# UUID NOT FOUND SO CREATE IT
if countUUID == 0:
if gv._DEBUG:
print("f(x) pushNewEventsIntoMisp {}/{}: CREATING MISP EVENT FOR UUID: {}".format(x, lengvUUIDS, oUUID))
# CREATE A MISP EVENT
mef.createIncident(oUUID, False)
# threads.append(eventThread)
# UUID IS FOUND SO SKIP IT SINCE THIS IS THE FIRST RUN
else:
if update == True:
if gv._DEBUG:
print("f(x) pushNewEventsIntoMisp {}/{}: UPDATING MISP EVENT FOR UUID: {}".format(x, lengvUUIDS, oUUID))
mef.createIncident(oUUID, True)
else:
print("f(x) pushNewEventsIntoMisp {}/{}: DUPLICATE EVENT DETECTED. UUID: {}".format(x, lengvUUIDS,oUUID))
except Exception as e:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) pushNewEventsIntoMisp: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
sys.exit(e)
def stageUnattributedActor():
try:
# CREATE UNATTRIBUTED ACTOR
myName = "UNATTRIBUTED"
if gv._DEBUG:
print("f(x) stageUnattributedActor: INITIALIZING DATA FOR: {}".format(myName))
myUUID = str(uuid.uuid4())
parentUUID = ""
myType = "ACTOR"
parentName = "NONE"
myPath = ""
myVersion = ""
myDate = ""
parentType = "NONE"
db.insert_actor(myUUID, "UNATTRIBUTED", "UNATTRIBUTED", "", "", "", "","","","",datetime.date.today(),"UNATTRIBUTED")
db.insert_parent_child(myUUID, parentUUID, myName, parentName, 0, myPath, myVersion, myDate, myType, parentType)
# CREATE ERROR ACTOR
myName = "ERROR"
if gv._DEBUG:
print("f(x) stageUnattributedActor: INITIALIZING DATA FOR: {}".format(myName))
myUUID = str(uuid.uuid4())
parentUUID = ""
myType = "ACTOR"
parentName = "NONE"
myPath = ""
myVersion = ""
myDate = ""
parentType = "NONE"
db.insert_actor(myUUID, "ERROR", "ERROR", "", "", "", "","","","",datetime.date.today(),"ERROR")
db.insert_parent_child(myUUID, parentUUID, myName, parentName, 0, myPath, myVersion, myDate, myType, parentType)
except Exception as e:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) stageUnattributedActor: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
sys.exit(e)
def stageMalwareFamilies():
try:
malwareFamilySet = set()
checkedSet = set()
# GO THROUGH PATH
for path in gv._DIR_MALPEDIA_GIT_LIST:
lstPath = path.split("/")
pathLen = len(lstPath)
# LEVEL OF THE SHORT NAMES OF MALWARE
currDirDepth = gv._CURRENT_DIR_DEPTH
if pathLen > currDirDepth:
myName = lstPath[currDirDepth-1]
if myName not in malwareFamilySet and myName not in checkedSet:
checkedSet.add(myName)
stored_data = db.get_parent_child_data(iValue=myName)
# IF NONE, WE DONT HAVE THIS FAMILY
if not stored_data:
malwareFamilySet.add(myName)
if gv._DEBUG:
print("f(x) stageMalwareFamilies(): FOUND FAMILY IN PATH: {}".format(myName))
for family in malwareFamilySet:
print("f(x) stageMalwareFamilies(): STAGING DATA FOR FAMILY: {}".format(family))
insertFamilyIntoDB(family)
except Exception as e:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) stageMalwareFamilies(): {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
sys.exit(e)
def getFamilyInformation(iFamilyName):
try:
# GET THE FAMILY JSON FILE
malware_family_json = gv._MALPEDIA_REPOSITORY + iFamilyName + "/" + iFamilyName + ".json"
isFile = os.path.isfile(malware_family_json)
if gv._DEBUG:
print("f(x) getFamilyInformation(): GETTING FAMILY INFORMATION FOR:\nFAMILY: {}\nPATH: {}".format(iFamilyName, malware_family_json))
if isFile:
with open(malware_family_json, 'r') as jsonIn:
# # IN ORDER TO 'FIX' ERRONEOUSLY FORMATTED JSON, YOU HAVE TO FIRST IMPORT THE FILE INTO YAML, THEN INTO JSON
# yamlData = yaml.safe_load(jsonIn)
# jsonData = json.dumps(yamlData)
# fix_json(jsonIn)
if gv._DEBUG:
print("f(x) getFamilyInformation() JSON DATA: {}".format(jsonIn))
malware_family_data = json.loads(fix_json(jsonIn))
jsonIn.close()
else:
return "NONE"
return malware_family_data
except Exception as e:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) getFamilyInformation ERROR: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
sys.exit(e)
def insertFamilyIntoDB(iFamilyName):
threat_actor = ""
threat_actor_UUID = ""
try:
malwareFamilyDict = getFamilyInformation(iFamilyName)
malwareFamilyMitreSoftwareTags = []
malwareFamilyMitreSoftwareTechniqueTags = []
malwareFamilyAltNamesMitreSpecificTags = []
actor_data = ""
# STRING OF COMMON NAME OF THIS MALWARE FAMILY
try:
commonName = malwareFamilyDict["common_name"].strip()
print("f(x) insertFamilyIntoDB: IMPORTING MALWARE: {}".format(commonName.upper()))
except:
commonName = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) insertFamilyIntoDB: FAMILY COMMON NAME: {}".format(commonName))
# LIST OF THE ALT NAMES ASSOCIATED WITH THIS MALWARE FAMILY
try:
altNames = malwareFamilyDict["alt_names"]
except:
altNames = []
# DEBUG SEQ
if gv._DEBUG:
print("f(x) insertFamilyIntoDB: FAMILY ALT NAMES:")
print(*altNames, sep = "\n")
# STRING OF ATTRIBUTION OF THIS MALWARE FAMILY
try:
attribution = malwareFamilyDict["attribution"]
except:
attribution = []
# IF NO ATTRIBUTION SET IT TO BE ATTRIBUTED TO BE UNATTRIBUTED
if len(attribution) == 0:
attribution = ["UNATTRIBUTED"]
threat_actor = "UNATTRIBUTED"
for attributed in attribution:
actor_data = db.get_actor_meta(iCommonName=attributed)
# ONLY GET THE FIRST ONE
try:
threat_actor = actor_data["shortname"]
threat_actor_UUID = actor_data["uuid"]
except:
actor_data = db.get_actor_meta(iCommonName="ERROR")
threat_actor = actor_data["shortname"]
threat_actor_UUID = actor_data["uuid"]
finally:
break
if gv._DEBUG:
print("f(x) stageMalwareFamilies(): LOOKING FOR THREAT ACTOR: [{}]: UUID: [{}]".format(threat_actor, threat_actor_UUID))
# STRING OF DESCRIPTION OF THIS MALWARE FAMILY
try:
malwareDescription = malwareFamilyDict["description"].strip()
except:
malwareDescription = ""
# DEBUG SEQ
if gv._DEBUG:
print("f(x) insertFamilyIntoDB: FAMILY DESCRIPTION: {}".format(malwareDescription))
#STRING OF UUID OF CURRENT MALWARE FAMILY
try:
malwareUUID = malwareFamilyDict["uuid"].strip()
except Exception as e:
exc_type, _, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("f(x) insertFamilyIntoDB: {}: {}: {}".format(exc_type, fname, exc_tb.tb_lineno))
malwareUUID = ""