-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_graph.py
More file actions
3245 lines (2830 loc) · 141 KB
/
create_graph.py
File metadata and controls
3245 lines (2830 loc) · 141 KB
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 requests
import math
import os
from mitreattack.stix20 import MitreAttackData
from dotenv import load_dotenv
from neo4j import GraphDatabase
import time
import csv
import re
import json
import sys
class CyberGraph:
def __init__(self, uri, user, password):
self.driver = GraphDatabase.driver(uri, auth=(user, password))
self.db="neo4j"
def close(self):
self.driver.close()
# ==============================================
# ============ INTERNAL UTILITIES ==============
# ==============================================
def printProgressBar(self, value, max, label):
n_bar = 40 # Size of progress bar
sup= value/max
sys.stdout.write('\r')
bar = '█' * int(n_bar * sup)
bar = bar + '-' * int(n_bar * (1-sup))
sys.stdout.write(f"{label.ljust(10)} | [{bar:{n_bar}s}] {int(100 * sup)}% ")
sys.stdout.flush()
# ==============================================
# ===== COMMON VARIABLES (Of: CWE, CAPEC) ======
# ==============================================
relationship = {
"ChildOf": { # (current)<--(related_cwe)
"relationship":"PARENT_OF",
"direction":"Left"
},
"CanPrecede":{ # (current)-->(related_cwe)
"relationship":"CAN_PRECEDE",
"direction":"Right"
},
"CanFollow":{ # (current)<--(related_cwe)
"relationship":"CAN_PRECEDE",
"direction":"Left"
},
"PeerOf":{ # (current)--(related_cwe) --> as default
"relationship":"PEER_OF",
"direction":"Right"
},
"CanAlsoBe":{ # (current)--(related_cwe) --> as default
"relationship":"CAN_ALSO_BE",
"direction":"Right"
},
"Requires":{ # (current)-->(related_cwe)
"relationship":"REQUIRES",
"direction":"Right"
}
}
# ==============================================
# =============== HANDLE CNA ===================
# ==============================================
@staticmethod
def _create_cna(tx, elements):
tx.run("MERGE (cna:CNA { name:$name, link:$link }) SET cna:"+ elements["label"],
name=elements["name"],
link=elements["link"])
@staticmethod
def _create_disclosure_policy(tx, elements):
tx.run("""
MATCH (cna:CNA { name:$cnaName })
MERGE (dp:DisclosurePolicy { link:$link, description:$description })
MERGE (cna)-[:HAS_DISCLOSURE_POLICY]->(dp)
""",
link=elements["link"],
description=elements["description"],
cnaName=elements["cnaName"])
@staticmethod
def _create_organization_type(tx, elements):
tx.run("""
MATCH (cna:CNA { name:$cnaName })
MERGE (ot:OrganizationType { type:$type })
MERGE (cna)-[:WORKS_IN_THE_FIELD_OF]->(ot)
""",
type=elements["type"],
cnaName=elements["cnaName"])
@staticmethod
def _create_security_advisory(tx, elements):
tx.run("""
MATCH (cna:CNA { name:$cnaName })
MERGE (sa:SecurityAdvisory { link:$link, description:$description })
MERGE (cna)-[:HAS_SECURITY_ADVISORY]->(sa)
""",
link=elements["link"],
description=elements["description"],
cnaName=elements["cnaName"])
@staticmethod
def _create_contact_info(tx, elements):
tx.run("""
MATCH (cna:CNA { name:$cnaName })
MERGE (contact:ContactInfo:"""+ elements["additionalLabel"] +""" { contact:$contact, description:$description })
MERGE (cna)-[:"""+ elements["relationship"] +"""]->(contact)
""",
contact=elements["contact"],
description=elements["description"],
cnaName=elements["cnaName"])
@staticmethod
def _create_country(tx, elements):
tx.run("""
MATCH (cna:CNA { name:$cnaName })
MERGE (country:Country { name:$name })
MERGE (cna)-[:BASED_IN]->(country)
""",
name=elements["name"],
cnaName=elements["cnaName"])
@staticmethod
def _create_scope(tx, elements):
tx.run("""
MATCH (cna:CNA { name:$cnaName })
MERGE (scope:Scope { description:$description })
MERGE (cna)-[:"""+ elements["relationship"] +"""]->(scope)
""",
description=elements["description"],
cnaName=elements["cnaName"])
@staticmethod
def _create_cna_parent(tx, elements):
tx.run("""
MATCH (cna:CNA { name:$cnaName })
MERGE (parentCNA:CNA { name:$cnaParentName, link:$cnaParentLink })
MERGE (cna)<-[:OWNS_ORGANIZATION]-(parentCNA)
""",
cnaParentName=elements["cnaParentName"],
cnaParentLink=elements["cnaParentLink"],
cnaName=elements["cnaName"])
def write_cna(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cna, elements)
def write_disclosure_policy(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_disclosure_policy, elements)
def write_organization_type(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_organization_type, elements)
def write_security_advisory(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_security_advisory, elements)
def write_contact_info(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_contact_info, elements)
def write_country(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_country, elements)
def write_scope(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_scope, elements)
def write_cna_parent(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cna_parent, elements)
def write_cna_index(self):
self.driver.execute_query("""CREATE INDEX cna_contact IF NOT EXISTS FOR (info:ContactInfo) ON (info.cnaEmail )""")
def handle_cna(self, source_filename):
with open(source_filename, mode='r') as file:
data = json.load(file)
cna_count = len(data["cnas"])
self.write_cna_index()
for idx,cna in enumerate(data["cnas"],1):
self.printProgressBar(idx,cna_count,"CNA")
label = ":".join(re.sub("\(.*\)","",role).replace(" ","").replace("-","") for role in cna["program_roles"])
self.write_cna({
"name":cna["name"],
"link":cna["link_more_info"],
"label":label
})
for policy in cna["disclosure_policies"]:
self.write_disclosure_policy({
"link":policy["link"],
"description":policy["name"],
"cnaName":cna["name"]
})
for org_type in cna["organization_types"]:
self.write_organization_type({
"type":org_type,
"cnaName":cna["name"]
})
for sec_advisory in cna["security_advisories"]:
self.write_security_advisory({
"link":sec_advisory["link"],
"description":sec_advisory["name"],
"cnaName":cna["name"]
})
for contact in cna["contacts"]:
self.write_contact_info({
"contact":contact["contact"],
"description":contact["name"],
"additionalLabel":contact["type"].capitalize(),
"relationship":"REACHABLE_BY_"+contact["type"].upper(),
"cnaName":cna["name"]
})
self.write_country({
"name":cna["country"],
"cnaName":cna["name"]
})
for scope in cna["scopes"]:
scope["type"] = scope["type"].replace("-","_").upper()
print(scope["type"])
self.write_scope({
"description":scope["description"],
"relationship":"HAS_"+scope["type"]+"_SCOPE",
"cnaName":cna["name"]
})
if "root" in cna:
self.write_cna_parent({
"cnaParentName":cna["root"]["name"],
"cnaParentLink":cna["root"]["link_more_info"],
"cnaName":cna["name"]
})
print("")
# ==============================================
# =============== HANDLE CWE ===================
# ==============================================
@staticmethod
def _create_cwe(tx, elements):
tx.run("""
MERGE (cwe:CWE { id:$id })
SET cwe += { name:$name, description:$description, link:$link, extendedDescription:$extendedDescription, backgroundDetails:$backgroundDetails }
""",
id=elements["id"],
name=elements["name"],
description=elements["description"],
link=elements["link"],
extendedDescription=elements["extendedDescription"],
backgroundDetails=elements["backgroundDetails"])
@staticmethod
def _create_cwe_status(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (status:Status { type:$type })
MERGE (cwe)-[:HAS_STATUS]->(status)
""",
type=elements["type"],
cweId=elements["cweId"])
@staticmethod
def _create_cwe_related_cwe(tx, elements):
relation = "{}-[:{}]-{}".format("<",elements["relationship"],"" if elements["direction"]=="Left" else "",elements["relationship"],">")
tx.run("""
MATCH (currentCwe:CWE { id:$cweId })
MERGE (relatedCwe:CWE { id:$relatedCweId })
MERGE (currentCwe)""" + relation + """(relatedCwe)
""",
relatedCweId=elements["relatedCweId"],
direction=elements["direction"],
cweId=elements["cweId"])
@staticmethod
def _create_weakness_ordinality(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (weaknessOrdinality:WeaknessOrdinality { type:$type, description:$description })
MERGE (cwe)-[r:HAS_WEAKNESS_ORDINALITY]->(weaknessOrdinality)
SET r.description = $customDescription
""",
type=elements["type"],
description=elements["description"],
customDescription=elements["customDescription"],
cweId=elements["cweId"])
@staticmethod
def _create_cwe_alternative_term(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (alternativeTerm:AlternativeTerm { name:$name })
SET alternativeTerm.description=$description
MERGE (cwe)-[:HAS_ALTERNATIVE_TERM]->(alternativeTerm)
""",
name=elements["name"],
description=elements["description"],
cweId=elements["cweId"])
@staticmethod
def _create_phase(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (phase:Phase { name:$name })
MERGE (cwe)-[r:CAN_BE_INTRODUCED_DURING]->(status)
SET r.description=$description
""",
name=elements["name"],
description=elements["description"],
cweId=elements["cweId"])
@staticmethod
def _create_security_property(tx, elements):
tx.run("""
MERGE (:SecurityProperty { name:$name })
""",
name=elements["name"])
@staticmethod
def _create_impact(tx, elements):
tx.run("""
MERGE (:Impact { name:$name })
""",
name=elements["name"])
@staticmethod
def _remove_cwe_consequences(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })-[:HAS_COMMON_CONSEQUENCE]->(consequence:Consequence)
DETACH DELETE consequence
""",
cweId=elements["cweId"])
@staticmethod
def _create_cwe_consequence(tx, elements):
tx.run( """
MATCH (cwe:CWE { id:$cweId })
CREATE (consequence:Consequence)
SET consequence.description=$description
MERGE (cwe)-[:HAS_COMMON_CONSEQUENCE]->(consequence)
FOREACH (sec_name in $securityProperties |
MERGE (sec:SecurityProperty { name:sec_name })
MERGE (consequence)-[:AFFECTS_SECURITY_PROPERTY]->(sec))
FOREACH (impact_name in $impacts |
MERGE (impact:Impact { name:impact_name })
MERGE (consequence)-[:HAS_IMPACT]->(impact))
""",
description=elements["description"],
securityProperties=elements["securityProperties"],
impacts=elements["impacts"],
cweId=elements["cweId"])
@staticmethod
def _create_detection_method(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (detectionMethod:DetectionMethod { name:$name })
MERGE (cwe)-[r:CAN_BE_DETECTED_BY]->(detectionMethod)
SET r += { effectiveness:$effectiveness, description:$description }
""",
name=elements["name"],
description=elements["description"],
effectiveness=elements["effectiveness"],
cweId=elements["cweId"])
@staticmethod
def _create_cwe_mitigation(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (mitigation:Mitigation { description:$description })
MERGE (cwe)-[r:CAN_BE_MITIGATED_BY]->(mitigation)
SET r.effectiveness=$effectiveness
""",
description=elements["description"],
effectiveness=elements["effectiveness"],
cweId=elements["cweId"])
if elements["phase"]:
tx.run("""
MATCH (mitigation:Mitigation { description:$description })
MERGE (phase:Phase { name:$phase })
MERGE (mitigation)-[:DURING_PHASE]->(phase)
""",
phase=elements["phase"],
description=elements["description"])
if elements["strategy"]:
tx.run("""
MATCH (mitigation:Mitigation { description:$description })
MERGE (strategy:Strategy { name:$strategy })
MERGE (mitigation)-[:HAVING_STRATEGY]->(strategy)
""",
strategy=elements["strategy"],
description=elements["description"])
@staticmethod
def _create_functional_area(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (functionalArea:FunctionalArea { name:$name })
MERGE (cwe)-[:MAY_OCCURS_IN_FUNCTIONAL_AREA]->(functionalArea)
""",
name=elements["name"],
cweId=elements["cweId"])
@staticmethod
def _create_affected_resource(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (resource:Resource { name:$name })
MERGE (cwe)-[:AFFECTS_RESOURCE]->(resource)
""",
name=elements["name"],
cweId=elements["cweId"])
@staticmethod
def _create_cwe_related_capec(tx, elements):
tx.run("""
MATCH (cwe:CWE { id:$cweId })
MERGE (capec:CAPEC { id:$capecId })
MERGE (cwe)-[:HAS_RELATED_ATTACK_PATTERN]->(capec)
""",
capecId=elements["capecId"],
cweId=elements["cweId"])
def write_cwe(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cwe, elements)
def write_cwe_status(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cwe_status, elements)
def write_cwe_related_cwe(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cwe_related_cwe, elements)
def write_weakness_ordinality(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_weakness_ordinality, elements)
def write_cwe_alternative_term(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cwe_alternative_term, elements)
def write_phase(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_phase, elements)
def write_security_property(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_security_property, elements)
def write_impact(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_impact, elements)
def write_cwe_consequence(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cwe_consequence, elements)
def delete_cwe_consequences(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._remove_cwe_consequences, elements)
def write_detection_method(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_detection_method, elements)
def write_cwe_mitigation(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cwe_mitigation, elements)
def write_functional_area(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_functional_area, elements)
def write_affected_resource(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_affected_resource, elements)
def write_cwe_related_capec(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_cwe_related_capec, elements)
def write_cwe_index(self):
self.driver.execute_query("""CREATE INDEX cwe_id IF NOT EXISTS FOR (cwe:CWE) ON (cwe.id )""")
def handle_cwe(self, source_filename):
ordinality_descriptions = {
"Primary":"Where the weakness exists independent of other weaknesses",
"Resultant":"Where the weakness is typically related to the presence of some other weaknesses",
"Indirect":"Where the weakness is a quality issue that might indirectly make it easier to introduce security-relevant weaknesses or make them more difficult to detect"
}
related_cwe_regex = re.compile("^NATURE:(.*?):CWE ID:(.*?):VIEW ID:(.*?)(?::ORDINAL:(.*))?$")
weakness_ordinality_regex = re.compile("^ORDINALITY:(.*?)(?::DESCRIPTION:(.*))?$")
alternative_term_regex = re.compile("^TERM:(.*?)(?::DESCRIPTION:(.*))?$")
phase_regex = re.compile("^PHASE:(.*?)(?::NOTE:(.*))?$")
consequence_regex = re.compile("^(?:SCOPE:(.*?))?(?::IMPACT:(.*?))?(?::NOTE:(.*))?$")
detection_method_regex = re.compile("^METHOD:(.*?):DESCRIPTION:(.*?)(?::EFFECTIVENESS:(.*))?$")
mitigation_regex = re.compile("^(?:PHASE:(.*?))?(?::STRATEGY:(.*?))?[:]*(?:DESCRIPTION:(.*?))?(?::EFFECTIVENESS:(.*))?$")
# Creating the indexes for the CWE nodes
self.write_cwe_index()
cwe_count = 0
with open(source_filename, mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
cwe_count = sum(1 for row in csv_reader) - 1
with open(source_filename, mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
for idx,cwe in enumerate(csv_reader,1):
self.printProgressBar(idx,cwe_count,"CWE")
self.write_cwe({
"id":cwe["CWE-ID"],
"name":cwe["Name"],
"description":cwe["Description"],
"link":"https://cwe.mitre.org/data/definitions/{}.html".format(cwe["CWE-ID"]),
"extendedDescription":cwe["Extended Description"] if cwe["Extended Description"] else None,
"backgroundDetails":cwe["Background Details"].replace("::","") if cwe["Background Details"] else None
})
if cwe["Status"]:
self.write_cwe_status({
"type":cwe["Status"],
"cweId":cwe["CWE-ID"]
})
if cwe["Related Weaknesses"]:
for related_cwe in [elem for elem in cwe["Related Weaknesses"].split("::") if elem]:
sup = related_cwe_regex.search(related_cwe)
if sup.group(3) == "1000":
self.write_cwe_related_cwe({
"relatedCweId":sup.group(2),
"relationship":self.relationship[sup.group(1)]["relationship"],
"direction":self.relationship[sup.group(1)]["direction"],
"cweId":cwe["CWE-ID"]
})
if cwe["Weakness Ordinalities"]:
for ordinality in [elem for elem in cwe["Weakness Ordinalities"].split("::") if elem]:
sup = weakness_ordinality_regex.search(ordinality)
self.write_weakness_ordinality({
"type":sup.group(1),
"description":ordinality_descriptions[sup.group(1)],
"customDescription":sup.group(2),
"cweId":cwe["CWE-ID"]
})
if cwe["Alternate Terms"]:
for term in [elem for elem in cwe["Alternate Terms"].split("::") if elem]:
sup = alternative_term_regex.search(term)
self.write_cwe_alternative_term({
"name":sup.group(1),
"description":sup.group(2),
"cweId":cwe["CWE-ID"]
})
if cwe["Modes Of Introduction"]:
for phase in [elem for elem in cwe["Modes Of Introduction"].split("::") if elem]:
sup = phase_regex.search(phase)
self.write_phase({
"name":sup.group(1),
"description":sup.group(2),
"cweId":cwe["CWE-ID"]
})
if cwe["Common Consequences"]:
# Deleting the previous "Consequence" nodes before recreating the new ones.
# This is necessary cause we are using the CREATE clause
self.delete_cwe_consequences({
"cweId":cwe["CWE-ID"]
})
for consequence in [elem for elem in cwe["Common Consequences"].split("::") if elem]:
sup = consequence_regex.search(consequence)
# for security_property in sup.group(1).split(":SCOPE:"):
# self.write_security_property({
# "name":security_property
# })
# for impact in sup.group(2).split(":IMPACT:"):
# self.write_impact({
# "name":impact
# })
self.write_cwe_consequence({
"description":sup.group(3),
"securityProperties":sup.group(1).split(":SCOPE:") if sup.group(1) else [],
"impacts":sup.group(2).split(":IMPACT:") if sup.group(2) else [],
"cweId":cwe["CWE-ID"]
})
if cwe["Detection Methods"]:
for detection_method in [elem for elem in cwe["Detection Methods"].split("::") if elem]:
sup = detection_method_regex.search(detection_method)
self.write_detection_method({
"name":sup.group(1),
"description":sup.group(2),
"effectiveness":sup.group(3),
"cweId":cwe["CWE-ID"]
})
if cwe["Potential Mitigations"]:
for mitigation in [elem for elem in cwe["Potential Mitigations"].split("::") if elem]:
if(sup := mitigation_regex.search(mitigation)) is not None:
self.write_cwe_mitigation({
"phase":sup.group(1),
"strategy":sup.group(2),
"description":sup.group(3),
"effectiveness":sup.group(4),
"cweId":cwe["CWE-ID"]
})
if cwe["Functional Areas"]:
for area in [elem for elem in cwe["Functional Areas"].split("::") if elem]:
self.write_functional_area({
"name":area,
"cweId":cwe["CWE-ID"]
})
if cwe["Affected Resources"]:
for resource in [elem for elem in cwe["Affected Resources"].split("::") if elem]:
self.write_affected_resource({
"name":resource,
"cweId":cwe["CWE-ID"]
})
if cwe["Related Attack Patterns"]:
for capec in [elem for elem in cwe["Related Attack Patterns"].split("::") if elem]:
self.write_cwe_related_capec({
"capecId":capec,
"cweId":cwe["CWE-ID"]
})
print("")
# ==============================================
# =============== HANDLE CAPEC =================
# ==============================================
@staticmethod
def _create_capec(tx, elements):
tx.run("""
MERGE (capec:CAPEC { id:$id })
SET capec += { name:$name, description:$description, link:$link }
""",
id=elements["id"],
name=elements["name"],
description=elements["description"],
link=elements["link"])
@staticmethod
def _create_capec_status(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (status:Status { type:$type })
MERGE (capec)-[:HAS_STATUS]->(status)
""",
type=elements["type"],
capecId=elements["capecId"])
@staticmethod
def _create_capec_alternative_term(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (alternativeTerm:AlternativeTerm { name:$name })
SET alternativeTerm.description=$description
MERGE (capec)-[:HAS_ALTERNATIVE_TERM]->(alternativeTerm)
""",
name=elements["name"],
description=elements["description"],
capecId=elements["capecId"])
@staticmethod
def _create_capec_scale_level(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (scaleLevel:ScaleLevel { level:$level })
MERGE (capec)-[:"""+ elements["relationship"] +"""]->(scaleLevel)
""",
level=elements["level"],
capecId=elements["capecId"])
@staticmethod
def _create_execution_flow(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (ef:ExecutionFlow:"""+ elements["additionalLabel"] +""" { description:$description })
SET ef.title=$title
MERGE (capec)-[r:"""+ elements["relationship"] +"""]->(ef)
SET r.flowStepNumber=$flowStepNumber
""",
title=elements["title"],
description=elements["description"],
flowStepNumber=elements["flowStepNumber"],
capecId=elements["capecId"])
@staticmethod
def _create_technique(tx, elements):
additionalProperties = "title:$executionFlowTitle, " if elements["executionFlowTitle"] else ""
tx.run("""
MATCH (ef:ExecutionFlow { """ + additionalProperties + """ description:$executionFlowDescription })
MERGE (technique:Technique { description:$description })
MERGE (ef)-[:HAS_TECHNIQUE]->(technique)
""",
executionFlowTitle=elements["executionFlowTitle"],
executionFlowDescription=elements["executionFlowDescription"],
description=elements["description"])
@staticmethod
def _create_prerequisite(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (prerequisite:Prerequisite { description:$description })
MERGE (capec)-[:HAS_PREREQUISITE]->(prerequisite)
""",
description=elements["description"],
capecId=elements["capecId"])
@staticmethod
def _create_skill(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (skill:Skill { description:$description })
MERGE (scaleLevel:ScaleLevel { level:$level })
MERGE (capec)-[:REQUIRES_SKILL]->(skill)-[:REQUIRES_EXPERTISE_LEVEL]->(scaleLevel)
""",
description=elements["description"],
level=elements["level"],
capecId=elements["capecId"])
@staticmethod
def _create_asset(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (asset:Asset { description:$description })
MERGE (capec)-[:REQUIRES_ASSET]->(asset)
""",
description=elements["description"],
capecId=elements["capecId"])
@staticmethod
def _create_indicator(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (indicator:AttackIndicator { description:$description })
MERGE (capec)-[:HAS_ATTACK_INDICATOR]->(indicator)
""",
description=elements["description"],
capecId=elements["capecId"])
@staticmethod
def _remove_capec_consequences(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })-[:HAS_COMMON_CONSEQUENCE]->(consequence:Consequence)
DETACH DELETE consequence
""",
capecId=elements["capecId"])
@staticmethod
def _create_capec_consequence(tx, elements):
tx.run( """
MATCH (capec:CAPEC { id:$capecId })
CREATE (consequence:Consequence)
SET consequence.description=$description
MERGE (capec)-[:HAS_COMMON_CONSEQUENCE]->(consequence)
FOREACH (sec_name in $securityProperties |
MERGE (sec:SecurityProperty { name:sec_name })
MERGE (consequence)-[:AFFECTS_SECURITY_PROPERTY]->(sec))
FOREACH (impact_name in $impacts |
MERGE (impact:Impact { name:impact_name })
MERGE (consequence)-[:HAS_IMPACT]->(impact))
""",
description=elements["description"],
securityProperties=elements["securityProperties"],
impacts=elements["impacts"],
capecId=elements["capecId"])
@staticmethod
def _create_capec_mitigation(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (mitigation:Mitigation { description:$description })
MERGE (capec)-[:CAN_BE_MITIGATED_BY]->(mitigation)
""",
description=elements["description"],
capecId=elements["capecId"])
@staticmethod
def _create_capec_example(tx, elements):
tx.run("""
MATCH (capec:CAPEC { id:$capecId })
MERGE (example:Example { description:$description })
MERGE (capec)-[:HAS_EXAMPLE]->(example)
""",
description=elements["description"],
capecId=elements["capecId"])
@staticmethod
def _create_capec_related_capec(tx, elements):
relation = "{}-[:{}]-{}".format("<",elements["relationship"],"" if elements["direction"]=="Left" else "",elements["relationship"],">")
tx.run("""
MATCH (currentCapec:CAPEC { id:$capecId })
MERGE (relatedCapec:CAPEC { id:$relatedCapecId })
MERGE (currentCapec)""" + relation + """(relatedCapec)
""",
relatedCapecId=elements["relatedCapecId"],
direction=elements["direction"],
capecId=elements["capecId"])
def write_capec(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec, elements)
def write_capec_status(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec_status, elements)
def write_capec_alternative_term(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec_alternative_term, elements)
def write_capec_scale_level(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec_scale_level, elements)
def write_execution_flow(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_execution_flow, elements)
def write_technique(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_technique, elements)
def write_prerequisite(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_prerequisite, elements)
def write_skill(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_skill, elements)
def write_asset(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_asset, elements)
def write_indicator(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_indicator, elements)
def delete_capec_consequences(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._remove_capec_consequences, elements)
def write_capec_consequence(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec_consequence, elements)
def write_capec_mitigation(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec_mitigation, elements)
def write_capec_example(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec_example, elements)
def write_capec_related_capec(self, elements):
with self.driver.session(database=self.db) as session:
res = session.execute_write(self._create_capec_related_capec, elements)
def create_capec_index(self):
self.driver.execute_query("""
CREATE INDEX capec_id IF NOT EXISTS FOR (capec:CAPEC) ON (capec.id)
""")
def handle_capec(self, source_filename):
alternative_term_regex = re.compile("^TERM:(.*?)(?::DESCRIPTION[:]*(.*))?$")
execution_flow_regex = re.compile("^STEP:(.*?)(?::PHASE:(.*?))?(?::DESCRIPTION:(?:\[(.*?)\] )?(.*?))?(?::TECHNIQUE:(.*))?$")
skill_regex = re.compile("^SKILL:(.*?)(?::LEVEL:(.*))?$")
capec_consequence_regex = re.compile("^(?:SCOPE:(.*?))?(?:TECHNICAL IMPACT:(.*?))?(?::NOTE:(.*))?$")
related_capec_regex = re.compile("^NATURE:(.*?):CAPEC ID:(.*)$")
# Creating the indexes for the CAPEC nodes
self.create_capec_index()
capec_count = 0
with open(source_filename, mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
capec_count = sum(1 for row in csv_reader) - 1
with open(source_filename, mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
for idx,capec in enumerate(csv_reader,1):
self.printProgressBar(idx,capec_count,"CAPEC")
self.write_capec({
"id":capec["'ID"],
"name":capec["Name"],
"description":capec["Description"] if capec["Description"] else None,
"link":"https://capec.mitre.org/data/definitions/{}.html".format(capec["'ID"])
})
if capec["Status"]:
self.write_capec_status({
"type":capec["Status"],
"capecId":capec["'ID"]
})
if capec["Alternate Terms"]:
for term in [elem for elem in capec["Alternate Terms"].replace(":::","::").split("::") if elem]:
sup = alternative_term_regex.search(term)
self.write_capec_alternative_term({
"name":sup.group(1),
"description":sup.group(2) if sup.group(2) else None,
"capecId":capec["'ID"]
})
if capec["Likelihood Of Attack"]:
self.write_capec_scale_level({
"level":capec["Likelihood Of Attack"],
"relationship":"HAS_ATTACK_LIKELIHOOD",
"capecId":capec["'ID"]
})
if capec["Typical Severity"]:
self.write_capec_scale_level({
"level":capec["Typical Severity"],
"relationship":"HAS_TYPICAL_SEVERITY",
"capecId":capec["'ID"]
})
if capec["Execution Flow"]:
count_step = 1
for flow in [elem for elem in capec["Execution Flow"].split("::") if elem]:
sup = execution_flow_regex.search(flow)
self.write_execution_flow({
"title":sup.group(3),
"description":sup.group(4),
"additionalLabel":sup.group(2).capitalize(),
"relationship":"HAS_{}_FLOW".format(sup.group(2).upper()),
"flowStepNumber":count_step,
"capecId":capec["'ID"]
})
if sup.group(5):
for technique in sup.group(5).split(":TECHNIQUE:"):
self.write_technique({
"executionFlowTitle":sup.group(3),
"executionFlowDescription":sup.group(4),
"description":technique
})
count_step += 1
if capec["Prerequisites"]:
for prerequisite in [elem for elem in capec["Prerequisites"].split("::") if elem]:
self.write_prerequisite({
"description":prerequisite,
"capecId":capec["'ID"]
})
if capec["Skills Required"]:
for skill in [elem for elem in capec["Skills Required"].split("::") if elem]:
sup = skill_regex.search(skill)
if sup:
self.write_skill({
"description":sup.group(1),
"level":sup.group(2),
"capecId":capec["'ID"]
})
if capec["Resources Required"]:
for resource in [elem for elem in capec["Resources Required"].split("::") if elem]:
self.write_asset({
"description":resource,
"capecId":capec["'ID"]
})
if capec["Indicators"]:
for indicator in [elem for elem in capec["Indicators"].split("::") if elem]:
self.write_indicator({
"description":indicator,
"capecId":capec["'ID"]
})
if capec["Consequences"]:
# Deleting the previous "Consequence" nodes before recreating the new ones.
# This is necessary cause we are using the CREATE clause
self.delete_capec_consequences({
"capecId":capec["'ID"]
})
for consequence in [elem for elem in capec["Consequences"].split("::") if elem]:
# Edge case. The easiest and fastest way is to hardcoded it.
if capec["'ID"] == "508":
consequence = consequence.split(":LIKELIHOOD:")[0]
sup = capec_consequence_regex.search(consequence)
self.write_capec_consequence({
"description":sup.group(3),