-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport.py
1481 lines (1166 loc) · 51.5 KB
/
report.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 os
from matplotlib.axis import Axis
from matplotlib.lines import Line2D
import pandas as pd
from owlready2 import *
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
def main():
owlready2.JAVA_EXE = "/Users/myuser/PoliTO/Protege-5.6.1/Protégé.app/Contents/jre/bin/java"
CWD = os.getcwd()
# Load your ontology
onto = get_ontology(CWD + "/popolatav11.owl").load()
# Sync reasoner
sync_reasoner_pellet(infer_property_values = True)
# report_resources(onto)
# va_per_resource_detailed_report(onto)
# risk_assessment_overview(onto)
# threat_model_report(onto)
# risk_assessment_detailed_report(onto)
# risk_assessment_overview_bar_chart(onto)
# vulnerability_assessment_overview_bar_chart(onto)
va_detailed_report(onto)
# Set highlighting rules
def highlight_row(row):
bg_colors_map = {
'Very Low': '#E0FFF3',
'Low': '#C7EFCE',
'Medium': '#FFEC9C',
'High': '#FF897A',
'Very High': '#E14D4F'
}
text_colors_map = {
'Very Low': '#009051',
'Low': '#009051',
'Medium': '#974706',
'High': '#7A0306',
'Very High': '#6F0307'
}
risk = row['Risk Level']
background_color = bg_colors_map.get(risk, '#974706')
text_color = text_colors_map.get(risk, '#006100')
style = f"background-color: {background_color}; color: {text_color};"
return [style] * len(row)
def highlight_vuln_row(row):
bg_colors_map = {
'Very Low': '#E0FFF3',
'LOW': '#C7EFCE',
'MEDIUM': '#FFEC9C',
'HIGH': '#FF897A',
'CRITICAL': '#E14D4F'
}
text_colors_map = {
'Very Low': '#009051',
'LOW': '#009051',
'MEDIUM': '#974706',
'HIGH': '#7A0306',
'CRITICAL': '#6F0307'
}
risk = row['Severity Level']
print(risk)
background_color = bg_colors_map.get(risk, '#974706')
text_color = text_colors_map.get(risk, '#006100')
style = f"background-color: {background_color}; color: {text_color};"
return [style] * len(row)
def top_10_resouces_at_risk(report):
# Make a pretty ranking table in HTML
# Compute the average risk for each resource (i.e. sum all the risks for a resource name and divide by the number of risks for that resource)
avg_risk = report.groupby('Resource')['Risk'].mean()
# Sort the resources by average risk
avg_risk = avg_risk.sort_values(ascending=False)
# Get the top 10 resources at risk
top_10 = avg_risk.head(10)
# Create a dataframe with the top 10 resources at risk
top_10_df = pd.DataFrame({
'Resource': top_10.index,
'Average Risk': top_10.values
})
# Save the dataframe to HTML
top_10_html_path = 'top_10_resources_at_risk.html'
top_10_df.to_html(top_10_html_path, index=False)
def pie_with_legend(report):
# Calculate the overall percentage of each risk
overall_percentage = report.groupby('QRisk').size() / len(report) * 100
# Get the counts of each risk
risk_counts = report['QRisk'].value_counts()
# Define custom colors
risk_colors = {
'Very Low': '#E0FFF3',
'Low': '#C7EFCE',
'Medium': '#FFEC9C',
'High': '#FF897A',
'Very High': '#E14D4F'
}
# Set a light background color
plt.figure(figsize=(8, 8))
plt.gca().set_facecolor('#F5F5F5')
# Plot the pie chart with custom colors
wedges, texts, autotexts = plt.pie(
overall_percentage,
labels=overall_percentage.index,
autopct=lambda p: f'{p:.1f}%\n{int(p * len(report) / 100)}', # Include both percentage and count
colors=[risk_colors.get(r, 'blue') for r in overall_percentage.index],
wedgeprops=dict(width=0.4, edgecolor='w')
)
# Add title with a larger font size
plt.title('Overall Percentage of Risk', fontsize=16)
# Equal aspect ratio ensures that pie is drawn as a circle.
plt.axis('equal')
# Add legend with risk counts
legend_labels = [f'{risk} ({count})' for risk, count in zip(overall_percentage.index, risk_counts)]
plt.legend(wedges, legend_labels, title='Risk Counts', loc='center left', bbox_to_anchor=(1, 0.5))
# # Show the plot
# plt.show()
# Save the plot to a png file, with high resolution (300 dpi)
plt.savefig('risk_pie_chart_1.png', dpi=300, bbox_inches='tight')
def generate_summary(report):
# Create a summary dataframe
summary_df = pd.DataFrame({
'Total Risks': [len(report)],
'Number of Very High Risks': [report[report['QRisk'] == 'Very High'].shape[0]],
'Average Risk Percentage': [report.groupby('QRisk').size().mean()],
'Most Common Risk Level': [report['QRisk'].mode().iloc[0]],
'Resource Types with Most Risks': [report['Resource Type'].mode().iloc[0]],
'Unique Resource Types': [report['Resource Type'].nunique()],
'Unique Risk Levels': [report['QRisk'].nunique()],
# Add more summary information as needed
})
# Save the summary dataframe to HTML
summary_html_path = 'risk_summary_table.html'
summary_df.to_html(summary_html_path, index=False)
# Copy of the risk_pie_chart function, but with a different name fake_risk_pie_chart
def fake_risk_pie_chart(report):
# Get the counts of each risk
risk_counts = {'Very High': 3,'High': 5, 'Medium': 8, 'Low': 5, 'Very Low': 0}
# Compute percentages
overall_percentage = {k: v / len(report) * 100 for k, v in risk_counts.items()}
# Define custom colors for each risk category
colors = {
'Very Low': '#E0FFF3',
'Low': '#C7EFCE',
'Medium': '#FFEC9C',
'High': '#FF897A',
'Very High': '#E14D4F'
}
# Set the font size
plt.rcParams['font.size'] = 15
# Plot the pie chart with custom colors
plt.figure(figsize=(8, 8))
plt.pie(overall_percentage.values(), labels=overall_percentage.keys(), autopct='%1.1f%%', colors=[colors.get(r, 'blue') for r in overall_percentage.keys()])
# Add a more descriptive title
plt.title('Risk Distribution')
# Equal aspect ratio ensures that pie is drawn as a circle.
plt.axis('equal')
# Add legend with risk counts
legend_labels = [f'{risk}: {count}' for risk, count in zip(overall_percentage.keys(), risk_counts.values())]
plt.legend(legend_labels, title='Threats per Risk Level', loc='upper right')
# Save the plot to an SVG file
plt.savefig('risk_pie_chart_fake_1.svg', bbox_inches='tight')
def risk_pie_chart(report):
# Calculate the overall percentage of each risk
overall_percentage = report.groupby('QRisk').size() / len(report) * 100
# Get the counts of each risk
risk_counts = report['QRisk'].value_counts()
# Define custom colors for each risk category
colors = {
'Very Low': '#E0FFF3',
'Low': '#C7EFCE',
'Medium': '#FFEC9C',
'High': '#FF897A',
'Very High': '#E14D4F'
}
# Plot the pie chart with custom colors
plt.figure(figsize=(8, 8))
plt.pie(overall_percentage, labels=overall_percentage.index, autopct='%1.1f%%', colors=[colors.get(r, 'blue') for r in overall_percentage.index])
# Add a more descriptive title
plt.title('Risk Distribution')
# Equal aspect ratio ensures that pie is drawn as a circle.
plt.axis('equal')
# Add legend with risk counts
legend_labels = [f'{risk}: {count}' for risk, count in zip(overall_percentage.index, risk_counts)]
plt.legend(legend_labels, title='Threats per Risk Level', loc='upper right')
# # Show the plot
# plt.show()
# Save the plot to a png file, with high resolution (300 dpi)
plt.savefig('risk_pie_chart_0.png', dpi=300, bbox_inches='tight')
# Save the plot to an SVG file
plt.savefig('risk_pie_chart_0.svg', bbox_inches='tight')
def draw_bar_chart(report):
# Calculate the percentage of each risk within each type
result_df = report.groupby(['Resource Type', 'QRisk']).size().unstack('QRisk', fill_value=0)
result_df = result_df.div(result_df.sum(axis=1), axis=0) * 100
# Define custom colors for each risk category
colors = {
'Very Low': '#C6EFCE',
'Low': '#FFEB9C',
'Medium': '#EFB78B',
'High': '#F4BFC8',
'Very High': '#F4BFC8'
}
# Plot the bar chart with custom colors
ax = result_df.plot(kind='bar', stacked=True, figsize=(10, 6), color=[colors.get(r, 'blue') for r in result_df.columns])
# Add labels and title
plt.title('Percentage of Risk for Each Type')
plt.xlabel('Type')
plt.ylabel('Percentage')
# Display the legend
plt.legend(title='Risk', bbox_to_anchor=(1.05, 1), loc='upper left')
# Show the plot
plt.show()
def draw_pie_charts(report):
# Calculate the percentage of each risk within each type
result_df = report.groupby(['Resource Type', 'QRisk']).size().unstack('QRisk', fill_value=0)
result_df = result_df.div(result_df.sum(axis=1), axis=0) * 100
# Define custom colors for each risk category
colors = {
'Very Low': '#C6EFCE',
'Low': '#FFEB9C',
'Medium': '#EFB78B',
'High': '#F4BFC8',
'Very High': '#F4BFC8'
}
# Iterate through each 'Resource Type' and create a pie chart
for resource_type in result_df.index:
data = result_df.loc[resource_type]
# Plot the pie chart with custom colors
plt.figure(figsize=(6, 6))
plt.pie(data, labels=data.index, autopct='%1.1f%%', colors=[colors.get(r, 'blue') for r in data.index])
# Add title
plt.title(f'Percentage of Risk for {resource_type}')
# Show the plot
plt.show()
def threats_report(onto):
# Assuming you have a class called 'Resource' and a data property called 'CPE'
resource_class = onto.Resource
resources = set(resource_class.instances()) # using set because, somehow, I get some resources twice in the array
# Sort resources by name
capec_global_count = 0
vuln_global_count = 0
# Initialize the results list
threats = []
resources = sorted(resources, key=lambda x: x.name)
for ont_resource in resources:
# Count the number of isAffectedBy object properties
capecs = ont_resource.isAffectedBy
# Get the class of the resource
resource_class = ont_resource.is_a[0].name
# Iterate over the list of CAPECs to build the dataframe
# We want each entry in the final excel file to be have: RESOURCE_NAME, CAPEC_NAME, CAPEC_LIKELIHOOD, CAPEC_SEVERITY, CAPEC_RISK
for capec in capecs:
# Get the name of each property object using the 'name' attribute
name = capec.name
likelihood_onto = capec.likelihood[0]
severity_onto = capec.severity[0]
# Strip any '*' from likelihood and severity
likelihood = likelihood_onto.replace('*', '')
severity = severity_onto.replace('*', '')
# assign to likelihood a value from 1 to 5 based on the string value (i.e. "Very Low" = 1, "Low" = 2, etc.)
likelihood_map = {
"Very Low": 1,
"Low": 2,
"Medium": 3,
"High": 4,
"Very High": 5
}
likelihood_val = likelihood_map.get(likelihood, 4)
severity_val = likelihood_map.get(severity, 4)
risk = likelihood_val * severity_val
qrisk = 0
if risk >= 20:
qrisk = 'Very High'
elif risk >= 15 and risk <= 19:
qrisk = 'High'
elif risk >= 5 and risk <= 14:
qrisk = 'Medium'
elif risk >= 3 and risk <= 4:
qrisk = 'Low'
else:
qrisk = 'Very Low'
# Add to threats list
threats.append({
'Resource': ont_resource.name,
'Resource Type': resource_class,
'CAPEC': name,
'Likelihood': likelihood_onto,
'Severity': severity_onto,
'Risk': risk,
'QRisk': qrisk
})
# Write to pandas Excel report
report = pd.DataFrame(threats)
# Sort by risk
report = report.sort_values(by=['Risk'], ascending=False)
######## Excel report ########
# report = report.style.apply(highlight_row, axis=1)
# report.to_excel("threats_3.xlsx", index=False)
# # Convert DataFrame to HTML
# # Guarantee minimum inner horizontal padding of 5px for each cell
# report = report.set_table_styles([dict(selector="th, td", props=[("padding", "5px")])])
# html_report = report.to_html(column_format="lllllcl", convert_css=True, index=False)
# # Write HTML string to file
# with open('report.html', 'w') as f:
# f.write(html_report)
# Draw charts
# risk_pie_chart(report)
# pie_with_legend(report)
fake_risk_pie_chart(report)
# top_10_resouces_at_risk(report)
# generate_summary(report)
# # Write to LateX, also formatting so that rows with Risk > 10 are highlighted
# def highlight_row(row):
# risk = row['Risk']
# background_color = "#F4BFC8" if risk > 19 else "#EFB78B" if risk > 11 else "#FFEB9C" if risk > 5 else "#C6EFCE"
# text_color = "#7A0306" if risk > 19 else "#974706" if risk > 11 else "#974706" if risk > 5 else "#006100"
# style = f"background-color: {background_color}; color: {text_color};"
# return [style] * len(row)
# report = report.style.apply(highlight_row, axis=1)
# report = report.to_html(column_format="lllllc", convert_css=True, index=False,)
# # report = report.style.highlight_max(
# # props='cellcolor:[HTML]{FFFF00}; color:{red};'
# # 'textit:--rwrap; textbf:--rwrap;')
############################################################################################################
################ Report on Latex
################
# report = report.to_latex(column_format="lllllc", index=False)
# # Write report to file
# with open("table2.latex", "w") as file:
# file.write(report)
############################################################################################################
# # styler = report.style
# # styler.map(rating_color, subset="Risk")
# # print("\n\n\n")
# # print(styler.to_latex(column_format="lllllc"))
def data_flows_table(onto):
results = []
data_flow_class = onto.DataFlow
data_flows = set(data_flow_class.instances()) # using set because, somehow, I get some resources twice in the array
for data_flow in data_flows:
# Get the name of the data flow
name = data_flow.name
# Get the name of the source
source = data_flow.hasSource[0].name
# Get the name of the destination
destination = data_flow.hasDestination[0].name
# Get the name of the Trust Boundary, after checking if the data flow instance has the 'crosses' object property
trust_boundary = ""
if len(data_flow.crosses) > 0:
trust_boundary = data_flow.crosses[0].name
# Add to threats list
results.append({
'Data Flow': name,
'Source': source,
'Destination': destination,
'Bidirectional': 'No',
'Crosses': trust_boundary
})
# Sort by data flow name
results = sorted(results, key=lambda x: x['Data Flow'])
# Now rename the data flows removing the A and B suffixes
for result in results:
result['Data Flow'] = result['Data Flow'][:-2]
# Sort by data flow by number (e.g. DF1, DF2, DF3, DF10 etc.) (DF10 must be after DF9)
results = sorted(results, key=lambda x: int(x['Data Flow'][2:]))
final_results = []
for result in results:
# If no data flow with the same name is already in the final results, add it
if not any(d['Data Flow'] == result['Data Flow'] for d in final_results):
final_results.append(result)
else: # set bidirectional to 'Yes' if the data flow is already in the final results
for d in final_results:
if d['Data Flow'] == result['Data Flow']:
d['Bidirectional'] = 'Yes'
# Write to pandas LateX table
report = pd.DataFrame(final_results)
report = report.to_latex(column_format="lllll", index=False)
# Print to standard output
print(report)
def threat_model_report(onto):
results = dict()
total = 0
for instance in onto.individuals():
# If belongs to a valid class
has_valid_class = True
for cls in instance.is_a:
if hasattr(cls, 'name') and (cls.name.startswith('CAPEC-') or cls.name == 'Threat'):
has_valid_class = False
break
if has_valid_class and hasattr(instance, "isAffectedBy"):
# Get the name of the instance
name = instance.name
# Get the class of the instance
instance_class = instance.is_a[0].name
# Get the isAffectedBy object properties
is_affected_by = instance.isAffectedBy
total += len(is_affected_by)
# Iterate over the list of isAffectedBy object properties
threat_categories = set()
stride_labels = set()
for prop in is_affected_by:
# Get threat categories
for cls in prop.is_a:
if cls.name.startswith('CAPEC-'):
cls_name = cls.name[6:]
threat_categories.add(cls_name)
if hasattr(prop, "isLabelledWithSTRIDE"):
for stride in prop.isLabelledWithSTRIDE:
stride_name = stride.name
stride_labels.add(stride_name)
# Remove '-A' and '-B' suffixes from the name of the instance (if present)
name = name[:-2] if name.endswith('-A') or name.endswith('-B') else name
# Check if individual exists in dictionary
if len(is_affected_by) > 0:
if name in results:
results[name]['count'] = results[name]['count'] + len(is_affected_by)
results[name]['threat_categories'].update(threat_categories)
results[name]['stride_labels'].update(set([l[0] for l in stride_labels]))
else:
results[name] = {
'count': len(is_affected_by),
'threat_categories': threat_categories,
'stride_labels': set([l[0] for l in stride_labels])
}
# For each resource, get the number of threats, threat categories and STRIDE labels
final_results = []
for name, data in results.items():
labels = data['stride_labels']
# Sort the labels in 'STRIDE' order
labels = sorted(labels, key=lambda x: ['S', 'T', 'R', 'I', 'D', 'E'].index(x))
final_results.append({
'Target': name,
'Threats Count': data['count'],
'Threat Categories': ', '.join(data['threat_categories']),
# 'STRIDE': ', '.join(labels)
})
# Add a total row
final_results.append({
'Target': 'Total',
'Threats Count': sum([r['Threats Count'] for r in final_results]),
'Threat Categories': '',
# 'STRIDE': ''
})
# print(total)
# Write to pandas LateX table, but set table width to 0.9\textwidth
report = pd.DataFrame(final_results)
report = report.to_latex(column_format="lc>{\\raggedright}p{.47\\textwidth}l", index=False, caption="Table with summarized results of the Threat Modeling phase.", label="tab:threat_model", longtable=True)
# Print to standard output
print(report)
def va_summary_report(onto):
# We want to generate a report table with the following columns: Total Resources, Total CVEs, Total CWEs, Total ATT&CKs
analyzed_resources = 0
for r in onto.Resource.instances():
has_cpe = hasattr(r, 'hasVulnerability') and len(r.CPE) > 0
has_info = hasattr(r, 'vendor') and len(r.vendor) > 0 and hasattr(r, 'product') and len(r.product) > 0
if has_cpe or has_info:
analyzed_resources += 1
total_resources = len(onto.Resource.instances())
cves_count = len(onto.CVE.instances())
cwes_count = len(onto.CWE.instances())
attacks_count = len(onto.ATTACK.instances())
print(f"Total Resources: {total_resources}")
print(f"Analyzed Resources: {analyzed_resources}")
print(f"Total CVEs: {cves_count}")
print(f"Total CWEs: {cwes_count}")
print(f"Total ATT&CKs: {attacks_count}")
# Write to pandas LateX table
report = pd.DataFrame([{
'Total Resources': total_resources,
'Analyzed Resources': analyzed_resources,
'Total CVEs': cves_count,
'Total CWEs': cwes_count,
'Total ATT&CKs': attacks_count
}])
report = report.to_latex(column_format="ccccc", index=False)
print(report)
def va_per_resource_report(onto):
# We want to generate a report table with the following columns: Resource, Total CVEs, Total CWEs, Total ATT&CKs
resources = onto.Resource.instances()
results = []
for resource in resources:
# Get the name of the resource
name = resource.name
vulnerabilities = resource.hasVulnerability
# Define sets for CWEs, CAPECs and ATT&CKs (# of CVES is the length of the vulnerabilities array)
cwes = set()
capecs = set()
attacks = set()
for vulnerability in vulnerabilities:
# Get the CWEs
if hasattr(vulnerability, 'hasCWE'):
cwes.update(vulnerability.hasCWE)
# Get CAPECs
if hasattr(vulnerability, 'RelatedAttackPatterns'):
related_capecs_lists = vulnerability.RelatedAttackPatterns
if len(related_capecs_lists) > 0:
curr_capecs = []
for r in related_capecs_lists:
# Split the string (comma separated) and place items into capecs array and strip whitespace
curr_capecs += [c.strip() for c in r.split(',')]
capecs.update(curr_capecs)
# Get ATT&CKs
if hasattr(vulnerability, 'isExploitedBy'):
attacks.update(vulnerability.isExploitedBy)
# Check if all counts are 0
if len(vulnerabilities) == 0:
continue
# Get a sorted array of CAPECS out of the set
if resource.name == 'OS3':
scapecs = sorted(list(capecs))
for capec in scapecs:
print(capec)
# Add to results
results.append({
'Resource': name,
'CVEs': len(vulnerabilities),
'CWEs': len(cwes),
'CAPECs': len(capecs),
'ATT&CKs': len(attacks)
})
# Add a total row
results.append({
'Resource': 'Total',
'CVEs': sum([r['CVEs'] for r in results]),
'CWEs': sum([r['CWEs'] for r in results]),
'CAPECs': sum([r['CAPECs'] for r in results]),
'ATT&CKs': sum([r['ATT&CKs'] for r in results])
})
# Sort by resource name
results = sorted(results, key=lambda x: x['Resource'])
# Write to pandas LateX table
report = pd.DataFrame(results)
report = report.to_latex(column_format="lllll", index=False)
# Print to standard output
print(report)
def print_results(results, name):
print("\\vspace{\\baselineskip}")
print("\\centering{Vulnerabilities for \\textbf{" + name + "}}")
print("\\begin{enumerate}")
for result in results:
print(" \\item \\textbf{CVE}:", result['CVE'])
print(" \\begin{itemize}")
print(" \\item \\textbf{CVSS}:", result['CVSS'])
print(" \\item \\textbf{CWEs}:", result['CWEs'])
print(" \\item \\textbf{CAPECs}:", result['CAPECs'])
print(" \\item \\textbf{ATT\\&CKs}:", result['ATT&CKs'])
print(" \\end{itemize}")
print("\\end{enumerate}\n")
def va_per_resource_detailed_report(onto):
# We want to generate one report for each resource with at least one vulnerability
# The report will have the following columns: CVE, CWEs, CAPECs, ATT&CKs
# The report will have the top 5 (evaluated by 'CVSS' data property score) vulnerabilities for each resource, sorted by CVSS score in descending order
resources = onto.Resource.instances()
# Sort resources by name
resources = sorted(resources, key=lambda x: x.name)
for resource in resources:
# Get the name of the resource
name = resource.name
# Get the vulnerabilities
vulnerabilities = resource.hasVulnerability
# If the resource has no vulnerabilities, skip it
if len(vulnerabilities) == 0:
continue
# Sort vulnerabilities by CVSS score
# vulnerabilities = sorted(vulnerabilities, key=lambda x: float(x.CVSS[0]), reverse=True)
# Keep only the top 5 vulnerabilities
vulnerabilities = vulnerabilities[:3]
# Sort vulnerabilities by CVSS score
vulnerabilities = sorted(vulnerabilities, key=lambda x: float(x.CVSS[0]), reverse=True)
results = []
for vulnerability in vulnerabilities:
# Get the CVE
cve = vulnerability.hasCVE[0].name
# Get the CWEs
cwes = vulnerability.hasCWE
# Get CAPECs
capecs = set()
if hasattr(vulnerability, 'RelatedAttackPatterns'):
related_capecs_lists = vulnerability.RelatedAttackPatterns
if len(related_capecs_lists) > 0:
curr_capecs = []
for r in related_capecs_lists:
# Split the string (comma separated) and place items into capecs array and strip whitespace
curr_capecs += [c.strip() for c in r.split(',')]
capecs.update(curr_capecs)
# Get ATT&CKs
attacks = vulnerability.isExploitedBy
# Now make a unique string out of the CWEs, CAPECs and ATT&CKs
if len(cwes) > 0:
cwes = ', '.join([c.name for c in cwes])
else:
# cwes = '\\hspace{2.3em}-'
cwes = 'N/A'
if len(capecs) > 0:
capecs = ', '.join(capecs)
else:
# capecs = '\\hspace{2.3em}-'
capecs = 'N/A'
if len(attacks) > 0:
attacks = ', '.join([a.name for a in attacks])
else:
# attacks = '\\hspace{2.3em}-'
attacks = 'N/A'
cvss = "{:.1f}".format(round(vulnerability.CVSS[0], 1))
# Add to results
results.append({
'CVE': cve,
'CWEs': cwes,
'CAPECs': capecs,
'ATT&CKs': attacks,
'CVSS': cvss
})
print_results(results, name)
# # Generate a good label for LateX references to the table (e.g. 'table:OS1detailedVA')
# label = name.replace(' ', '').replace('-', '').lower()
# label = f"table:{label}detailedVA"
# # Write to pandas LateX table (with resource name in caption)
# report = pd.DataFrame(results)
# report = report.to_latex(column_format="p{.22\linewidth}p{.16\linewidth}p{.16\linewidth}p{.16\linewidth}p{.10\linewidth}", index=False, caption=f"Vulnerabilities for {name}", label=label)
# # Replace in report each occurrence of 'CVE & CWEs & CAPECs & ATT&CKs & CVSS' with '\\textbf{CVE} & \\textbf{CWEs} & \\textbf{CAPECs} & \\textbf{ATT\&CKs} & \\textbf{CVSS}'
# report = report.replace('CVE & CWEs & CAPECs & ATT&CKs & CVSS', '\\textbf{CVE} & \\textbf{CWEs} & \\textbf{CAPECs} & \\textbf{ATT\\&CKs} & \\textbf{CVSS}')
# # Print to standard output
# print(report)
def report_resources(onto):
# For each resource report CPE, vendor, product, version
# place a '-' if the resource doesn't have one of the above
# Finally, print as Latex table with the following columns: Resource, CPE, Vendor, Product, Version
resources = onto.Resource.instances()
results = []
for resource in resources:
# Get the name of the resource
name = resource.name
# Get the CPE
cpe = resource.CPE[0] if len(resource.CPE) > 0 else 'MISSING'
# Get the vendor
vendor = resource.vendor[0] if len(resource.vendor) > 0 else 'MISSING'
# Get the product
product = resource.product[0] if len(resource.product) > 0 else 'MISSING'
# Get the version
version = resource.version[0] if len(resource.version) > 0 else 'MISSING'
# Add to results
results.append({
'Resource': name,
'CPE': cpe,
'Vendor': vendor,
'Product': product,
'Version': version
})
# Sort by resource name
results = sorted(results, key=lambda x: x['Resource'])
# # Write to pandas LateX table
# report = pd.DataFrame(results)
# report = report.to_latex(column_format="lllll", index=False)
# # Print to standard output
# print(report)
# Write to pandas Excel table
report = pd.DataFrame(results)
report = report.to_excel("resources.xlsx", index=False)
# # # Write to pandas CSV table
# report = pd.DataFrame(results)
# report = report.to_csv("resources.csv", index=False)
def report_cpes(onto):
# For each resource report CPE, vendor, product, version
# place a '-' if the resource doesn't have one of the above
# Finally, print as Latex table with the following columns: Resource, CPE, Vendor, Product, Version
resources = onto.Resource.instances()
results = []
for resource in resources:
# Get the name of the resource
name = resource.name
# Get the CPE
cpe = resource.CPE[0] if len(resource.CPE) > 0 else ''
# Escape the underscore character
cpe = cpe.replace('_', '\\_')
if (cpe != ''):
# Add to results
results.append({
'Resource': name,
'CPE': cpe
})
# Sort by resource name
results = sorted(results, key=lambda x: x['Resource'])
# Write to pandas LateX table
report = pd.DataFrame(results)
report = report.to_latex(column_format="ll", index=False)
# Print to standard output
print(report)
def risk_assessment_overview(onto):
results = []
for instance in onto.individuals():
# If belongs to a valid class
has_valid_class = True
for cls in instance.is_a:
if hasattr(cls, 'name') and (cls.name.startswith('CAPEC-') or cls.name == 'Threat'):
has_valid_class = False
break
if has_valid_class and hasattr(instance, "isAffectedBy"):
# Get the name of the resource
name = instance.name
very_low = 0
low = 0
medium = 0
high = 0
very_high = 0
threats = instance.isAffectedBy
if len(threats) == 0:
continue
# For each threat, compute the risk as likelihood * severity
for threat in threats:
# Get the likelihood and severity of each property object using the 'likelihood' and 'severity' attributes
likelihood = threat.likelihood[0]
severity = threat.severity[0]
# assign to likelihood a value from 1 to 5 based on the string value (i.e. "Very Low" = 1, "Low" = 2, etc.)
likelihood_map = {
"Very Low": 1,
"Low": 2,
"Medium": 3,
"High": 4,
"Very High": 5
}
likelihood_val = likelihood_map.get(likelihood, 4)
severity_val = likelihood_map.get(severity, 4)
risk = likelihood_val * severity_val
if risk >= 20:
very_high += 1
elif risk >= 15 and risk <= 19:
high += 1
elif risk >= 5 and risk <= 14:
medium += 1
elif risk >= 3 and risk <= 4:
low += 1
else:
very_low += 1
# Add to results
results.append({
'Resource': name,
'Very Low': very_low,
'Low': low,
'Medium': medium,
'High': high,
'Very High': very_high
})
# Print a total of totals
total_threats = sum([r['Very Low'] + r['Low'] + r['Medium'] + r['High'] + r['Very High'] for r in results])
print(f"Total threats: {total_threats}")
# Add a total row
results.append({
'Resource': '\\textbf{Total}',
'Very Low': sum([r['Very Low'] for r in results]),
'Low': sum([r['Low'] for r in results]),
'Medium': sum([r['Medium'] for r in results]),
'High': sum([r['High'] for r in results]),
'Very High': sum([r['Very High'] for r in results])
})
# Write to pandas LateX table
report = pd.DataFrame(results)
# Sort by resource name
report = report.sort_values(by=['Resource'])
# Export to LateX
report = report.to_latex(column_format="llllll", index=False, longtable=True, caption="Risk Assessment summary, showing the number of threats for each resource and risk level.", label="tab:risk_assessment_overview")
# Print to standard output
print(report)
def risk_assessment_overview_bar_chart(onto):
# We want to generate a bar chart with the number of threats for each risk level
very_low = 0
low = 0
medium = 0
high = 0
very_high = 0
for instance in onto.individuals():
# If belongs to a valid class
has_valid_class = True
for cls in instance.is_a:
if hasattr(cls, 'name') and (cls.name.startswith('CAPEC-') or cls.name == 'Threat'):
has_valid_class = False
break
if has_valid_class and hasattr(instance, "isAffectedBy"):
# Get the name of the resource
name = instance.name
# very_low = 0
# low = 0
# medium = 0
# high = 0
# very_high = 0
threats = instance.isAffectedBy
if len(threats) == 0:
continue
# For each threat, compute the risk as likelihood * severity
for threat in threats:
# Get the likelihood and severity of each property object using the 'likelihood' and 'severity' attributes
likelihood = threat.likelihood[0]