-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrisk-report.py
executable file
·1715 lines (1441 loc) · 82.3 KB
/
risk-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
#!/usr/bin/python3.9
# Copyright 2024 University of Southampton IT Innovation Centre
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# <!-- SPDX-License-Identifier: Apache 2.0 -->
# <!-- SPDX-FileCopyrightText: 2024 The University of Southampton IT Innovation Centre -->
# <!-- SPDX-ArtifactOfProjectName: Spyderisk -->
# <!-- SPDX-FileType: Source code -->
# <!-- SPDX-FileComment: Original by Stephen Phillips, May 2024 -->
import argparse
import copy
import csv
import gzip
import logging
import re
import tempfile
import time
from functools import cache, cached_property
from itertools import chain
from pathlib import Path
import boolean
from rdflib import ConjunctiveGraph, Literal, URIRef
VERSION = "1.0"
algebra = boolean.BooleanAlgebra()
TRUE, FALSE, NOT, AND, OR, symbol = algebra.definition()
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
parser = argparse.ArgumentParser(description="Generate risk reports for Spyderisk system models",
epilog="e.g. risk-report.py -i SteelMill.nq.gz -o steel.pdf -d ../domain-network/csv/ -m MS-LossOfControl-f8b49f60")
parser.add_argument("-i", "--input", dest="input", required=True, metavar="input_NQ_filename", help="Filename of the validated system model NQ file (compressed or not)")
parser.add_argument("-o", "--output", dest="output", required=True, metavar="output_csv_filename", help="Output CSV filename")
parser.add_argument("-d", "--domain", dest="csvs", required=True, metavar="CSV_directory", help="Directory containing the domain model CSV files")
parser.add_argument("-m", "--misbehaviour", dest="misbehaviours", required=False, nargs="+", metavar="URI_fragment", help="Target misbehaviour IDs, e.g. 'MS-LossOfControl-f8b49f60'. If not specified then the high impact and high risk ones will be analysed.")
parser.add_argument("-s", "--simple-root-causes", dest="simple_root_causes", action="store_true", help="Keep the root causes simple (no top-level OR). Using this means more repetition.")
parser.add_argument("--hide-initial-causes", dest="hide_initial_causes", action="store_true", help="Don't output the initial causes")
parser.add_argument("--version", action="version", version="%(prog)s " + VERSION)
raw = parser.parse_args()
args = vars(raw)
nq_filename = args["input"]
csv_directory = args["csvs"]
output_filename = args["output"]
target_ms_uris = args["misbehaviours"]
SHOW_LIKELIHOOD_IN_DESCRIPTION = False
domain_misbehaviours_filename = Path(csv_directory) / "Misbehaviour.csv"
domain_trustworthiness_attributes_filename = Path(csv_directory) / "TrustworthinessAttribute.csv"
domain_ca_settings_filename = Path(csv_directory) / "CASetting.csv"
domain_controls_filename = Path(csv_directory) / "Control.csv"
domain_control_strategies_filename = Path(csv_directory) / "ControlStrategy.csv"
domain_trustworthiness_levels_filename = Path(csv_directory) / "TrustworthinessLevel.csv"
domain_likelihood_levels_filename = Path(csv_directory) / "Likelihood.csv"
domain_impact_levels_filename = Path(csv_directory) / "ImpactLevel.csv"
domain_risk_levels_filename = Path(csv_directory) / "RiskLevel.csv"
domain_risk_lookup_filename = Path(csv_directory) / "RiskLookupTable.csv"
# Constants to query RDF:
CORE = "http://it-innovation.soton.ac.uk/ontologies/trustworthiness/core"
DOMAIN = "http://it-innovation.soton.ac.uk/ontologies/trustworthiness/domain"
SYSTEM = "http://it-innovation.soton.ac.uk/ontologies/trustworthiness/system"
HAS_TYPE = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
HAS_ID = URIRef(CORE + "#hasID")
HAS_COMMENT = URIRef("http://www.w3.org/2000/01/rdf-schema#comment")
HAS_LABEL = URIRef("http://www.w3.org/2000/01/rdf-schema#label")
CAUSES_DIRECT_MISBEHAVIOUR = URIRef(CORE + "#causesDirectMisbehaviour")
CAUSES_INDIRECT_MISBEHAVIOUR = URIRef(CORE + "#causesIndirectMisbehaviour")
HAS_SECONDARY_EFFECT_CONDITION = URIRef(CORE + "#hasSecondaryEffectCondition")
AFFECTS = URIRef(CORE + "#affects")
AFFECTED_BY = URIRef(CORE + "#affectedBy")
HAS_ENTRY_POINT = URIRef(CORE + "#hasEntryPoint")
IS_ROOT_CAUSE = URIRef(CORE + "#isRootCause")
APPLIES_TO = URIRef(CORE + "#appliesTo")
LOCATED_AT = URIRef(CORE + "#locatedAt")
HAS_NODE = URIRef(CORE + "#hasNode")
HAS_ASSET = URIRef(CORE + "#hasAsset")
HAS_MISBEHAVIOUR = URIRef(CORE + "#hasMisbehaviour")
HAS_TWA = URIRef(CORE + "#hasTrustworthinessAttribute")
HAS_INFERRED_LEVEL = URIRef(CORE + "#hasInferredLevel")
HAS_ASSERTED_LEVEL = URIRef(CORE + "#hasAssertedLevel")
THREAT = URIRef(CORE + "#Threat")
HAS_PRIOR = URIRef(CORE + "#hasPrior")
HAS_IMPACT = URIRef(CORE + "#hasImpactLevel")
HAS_RISK = URIRef(CORE + "#hasRisk")
HAS_FREQUENCY = URIRef(CORE + "#hasFrequency")
MISBEHAVIOUR_SET = URIRef(CORE + "#MisbehaviourSet")
MITIGATES = URIRef(CORE + "#mitigates")
BLOCKS = URIRef(CORE + "#blocks")
HAS_CONTROL_SET = URIRef(CORE + "#hasControlSet")
HAS_MANDATORY_CONTROL_SET = URIRef(CORE + "#hasMandatoryCS")
CONTROL_SET = URIRef(CORE + "#ControlSet")
HAS_COVERAGE = URIRef(CORE + "#hasCoverageLevel")
HAS_CONTROL = URIRef(CORE + "#hasControl")
IS_PROPOSED = URIRef(CORE + "#isProposed")
CAUSES_THREAT = URIRef(CORE + "#causesThreat")
CAUSES_MISBEHAVIOUR = URIRef(CORE + "#causesMisbehaviour")
IS_EXTERNAL_CAUSE = URIRef(CORE + "#isExternalCause")
IS_INITIAL_CAUSE = URIRef(CORE + "#isInitialCause")
IS_NORMAL_OP = URIRef(CORE + "#isNormalOp")
IS_NORMAL_OP_EFFECT = URIRef(CORE + "#isNormalOpEffect")
PARENT = URIRef(CORE + "#parent")
CONTROL_STRATEGY = URIRef(CORE + "#ControlStrategy")
TRUSTWORTHINESS_ATTRIBUTE_SET = URIRef(CORE + "#TrustworthinessAttributeSet")
INFINITY = 99999999
# WARNING: Domain model specific predicates
DEFAULT_TW_ATTRIBUTE = URIRef(DOMAIN + "#DefaultTW")
IN_SERVICE = URIRef(DOMAIN + "#InService")
# The second line of a CSV file often contains default values and if so will include domain#000000
DUMMY_URI = "domain#000000"
def load_domain_misbehaviours(filename):
"""Load misbehaviours from the domain model so that we can use the labels"""
misbehaviour = {}
with open(filename, newline="") as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
uri_index = header.index("URI")
label_index = header.index("label")
comment_index = header.index("comment")
for row in reader:
if DUMMY_URI in row: continue
uri = row[uri_index]
misbehaviour[uri] = {}
misbehaviour[uri]["label"] = row[label_index]
misbehaviour[uri]["description"] = row[comment_index]
return misbehaviour
def load_domain_trustworthiness_attributes(filename):
"""Load trustworthiness attributes from the domain model so that we can use the labels"""
ta = {}
with open(filename, newline="") as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
uri_index = header.index("URI")
label_index = header.index("label")
comment_index = header.index("comment")
for row in reader:
if DUMMY_URI in row: continue
uri = row[uri_index]
ta[uri] = {}
ta[uri]["label"] = row[label_index]
ta[uri]["description"] = row[comment_index]
return ta
def load_domain_controls(filename):
"""Load controls from the domain model so that we can use the labels"""
control = {}
with open(filename, newline="") as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
uri_index = header.index("URI")
label_index = header.index("label")
for row in reader:
if DUMMY_URI in row: continue
uri = row[uri_index]
control[uri] = {}
control[uri]["label"] = row[label_index]
return control
def load_domain_control_strategies(filename):
"""Load control strategies from the domain model so that we can use the labels and current/future attributes"""
csg = {}
with open(filename, newline="") as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
uri_index = header.index("URI")
label_index = header.index("label")
current_index = header.index("currentRisk")
future_index = header.index("futureRisk")
blocking_index = header.index("hasBlockingEffect")
for row in reader:
if DUMMY_URI in row: continue
uri = row[uri_index]
csg[uri] = {}
csg[uri]["label"] = row[label_index]
csg[uri]["currentRisk"] = False if row[current_index] == "FALSE" else True
csg[uri]["futureRisk"] = False if row[future_index] == "FALSE" else True
csg[uri]["hasBlockingEffect"] = row[blocking_index]
return csg
def load_domain_ca_settings(filename):
"""Load information from the domain model so that we know which control sets are assertable"""
settings = {}
with open(filename, newline="") as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
uri_index = header.index("URI")
assertable_index = header.index("isAssertable")
for row in reader:
if DUMMY_URI in row: continue
assertable = True if row[assertable_index] == "TRUE" else False
settings[row[uri_index].split('#')[1]] = assertable
return settings
def load_domain_levels(filename):
"""Load levels from the domain model (works for impact, risk, trustworthiness and likelihood)"""
tw = {}
with open(filename, newline="") as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
uri_index = header.index("URI")
level_index = header.index("levelValue")
label_index = header.index("label")
for row in reader:
if DUMMY_URI in row: continue
uri = row[uri_index]
tw[uri] = {}
tw[uri]["number"] = int(row[level_index])
tw[uri]["label"] = row[label_index]
return tw
def load_risk_lookup(filename):
"""Load the risk lookup matrix"""
risk = {}
with open(filename, newline="") as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
iv_index = header.index("IV")
lv_index = header.index("LV")
rv_index = header.index("RV")
for row in reader:
if DUMMY_URI in row: continue
iv = int(row[iv_index])
lv = int(row[lv_index])
rv = int(row[rv_index])
if iv not in risk:
risk[iv] = { lv: rv }
else:
risk[iv][lv] = rv
return risk
def un_camel_case(text):
text = text.strip()
if text == "": return "****"
text = text.replace("TW", "Trustworthiness")
if text[0] == "[":
return text
else:
text = re.sub('([a-z])([A-Z])', r'\1 \2', text)
text = text.replace("Auth N", "AuthN") # re-join "AuthN" into one word
text = re.sub('(AuthN)([A-Z])', r'\1 \2', text)
text = text.replace("Io T", "IoT") # re-join "IoT" into one word
text = re.sub('(IoT)([A-Z])', r'\1 \2', text)
text = re.sub('([A-Z]{2,})([A-Z][a-z])', r'\1 \2', text) # split out e.g. "PIN" or "ID" as a separate word
text = text.replace('BIO S', 'BIOS ') # one label is "BIOSatHost"
return text
def abbreviate_asset_label(label):
if label.startswith("[ClientServiceChannel:"):
# Example input:
# [ClientServiceChannel:(Philip's PC)-(Philip's Web Browser)-(Web Server)-Website-[NetworkPath:Internet-[NetworkPath:(Shop DMZ)]]]
bits = label.split("-")
return "[ClientServiceChannel:" + bits[1] + "-" + bits[3]
return label
def make_symbol(uriref):
"""Make a symbol from the URIRef for use in logical expressions"""
return symbol(uriref.split('#')[1])
def get_comment_from_match(frag_match):
"""Converts from e.g. Symbol('MS-LossOfControl-f8b49f60') to the entity's comment"""
# TODO: this references a global variable, which is not ideal
return system_model.get_entity(URIRef(SYSTEM + "#" + frag_match.group()[8:-2])).short_comment
class LogicalExpression():
"""Represents a Boolean expression using URI fragments as the symbols."""
def __init__(self, cause_list, all_required=True):
"""Arguments:
cause_list: list
can be a mixture of None, LogicalExpression and symbol
all_required: Boolean
whether all the parts of the expression are required (resulting in an AND) or not (giving an OR)
"""
all_causes = []
for cause in cause_list:
if isinstance(cause, LogicalExpression):
all_causes.append(cause.cause)
else:
all_causes.append(cause)
all_causes = [c for c in all_causes if c is not None]
if len(all_causes) == 0:
self.cause = None
elif len(all_causes) == 1:
self.cause = all_causes[0]
else:
if all_required:
self.cause = AND(*all_causes).simplify()
else:
self.cause = OR(*all_causes).simplify()
@classmethod
def create_or_none(cls, cause_list, all_required=True):
"""Factory method to create a LogicalExpression or return None if the cause_list is empty after filtering out None values"""
cause_list = [cause for cause in cause_list if cause is not None]
if len(cause_list) == 0:
return None
return cls(cause_list, all_required)
def __str__(self):
"""Single line representation with the URIs replaced with the entity comment"""
if self.cause is None:
return "-None-"
cause = algebra.dnf(self.cause.simplify())
symb = re.compile(r'Symbol\(\'.*?\'\)')
return symb.sub(get_comment_from_match, repr(cause))
def __eq__(self, other):
if hasattr(other, 'cause'):
return self.cause == other.cause
else:
return False
def __hash__(self) -> int:
return hash(self.cause)
@property
def uris(self):
return set([URIRef(SYSTEM + "#" + str(symbol)) for symbol in self.cause.get_symbols()])
@property
def complexity(self):
return str(self.cause.args).count("Symbol")
def pretty_print(self, max_complexity=500):
if self.cause is None:
return "None"
if self.complexity <= max_complexity:
cause = algebra.dnf(self.cause.simplify())
symb = re.compile(r'Symbol\(\'.*?\'\)')
cause = symb.sub(get_comment_from_match, cause.pretty())
else:
cause = "Complexity: " + str(self.complexity)
return cause
@property
def dnf_terms(self):
"""Return the terms of the DNF form of the expression as a list."""
if self.cause is None:
return []
dnf = algebra.dnf(self.cause.simplify())
# if dnf form is just 1 symbol or the operator is AND then just return it, otherwise it is an OR and we need to return its terms (args)
if len(dnf.symbols) == 1 or dnf.operator == "AND":
return [dnf]
else:
return dnf.args
class LoopbackError(Exception):
"""Exception raised when attempting to visit a parent node (cause) that is also a child (effect) during tree traversal."""
def __init__(self, loopback_node_uris: set = None) -> None:
"""
Initialize the LoopbackError exception.
Args:
loopback_node_uris (set): Set of URIs of nodes causing the loopback (non-empty).
"""
if loopback_node_uris is None:
# TODO: following line is never used. Should probably throw an exception and also check that set is not empty
loopback_node_uris = set()
self.loopback_node_uris = loopback_node_uris
def __str__(self) -> str:
return f"Error encountered during tree traversal. Loopback nodes: {self.loopback_node_uris}"
# TODO: Add the domain model as a parameter? And load domain model from NQ rather than CSV files
class Graph(ConjunctiveGraph):
"""Represents the system model as an RDF graph."""
def __init__(self, nq_filename):
super().__init__()
if nq_filename.endswith(".gz"):
with gzip.open(nq_filename, "rb") as f:
self.parse(f, format="nquads")
else:
self.parse(nq_filename, format="nquads")
def get_entity(self, uriref):
if (uriref, HAS_TYPE, MISBEHAVIOUR_SET) in self:
return MisbehaviourSet(uriref, self)
elif (uriref, HAS_TYPE, THREAT) in self:
return Threat(uriref, self)
elif (uriref, HAS_TYPE, CONTROL_STRATEGY) in self:
return ControlStrategy(uriref, self)
elif (uriref, HAS_TYPE, TRUSTWORTHINESS_ATTRIBUTE_SET) in self:
return TrustworthinessAttributeSet(uriref, self)
else:
raise KeyError(uriref)
@cache
def threat(self, uriref):
return Threat(uriref, self)
@cache
def misbehaviour(self, uriref):
return MisbehaviourSet(uriref, self)
@cache
def control_strategy(self, uriref):
return ControlStrategy(uriref, self)
@cache
def trustworthiness_attribute_set(self, uriref):
return TrustworthinessAttributeSet(uriref, self)
@property
def threats(self):
return [self.threat(uriref) for uriref in self.subjects(HAS_TYPE, THREAT)]
@property
def misbehaviours(self):
return [self.misbehaviour(uriref) for uriref in self.subjects(HAS_TYPE, MISBEHAVIOUR_SET)]
@property
def control_strategies(self):
return [self.control_strategy(uriref) for uriref in self.subjects(HAS_TYPE, CONTROL_STRATEGY)]
@property
def trustworthiness_attribute_sets(self):
return [self.trustworthiness_attribute_set(uriref) for uriref in self.subjects(HAS_TYPE, TRUSTWORTHINESS_ATTRIBUTE_SET)]
def label(self, uriref):
return self.value(subject=uriref, predicate=HAS_LABEL)
# TODO: consider making this extend URIRef as this might provide useful identity value. We could then use the Entity subclasses in the current_path for instance
class Entity():
"""Superclass of Threat, Misbehaviour, Trustwworthiness Attribute or Control Strategy."""
def __init__(self, uriref, graph):
self.uriref = uriref
self.graph = graph
def __hash__(self):
return hash(self.uriref)
def __eq__(self, other):
if not isinstance(other, Entity):
return False
return (self.uriref == other.uriref)
class ControlStrategy(Entity):
"""Represents a Control Strategy."""
def __init__(self, uriref, graph):
super().__init__(uriref, graph)
def __str__(self):
return "Control Strategy: {} ({}) / Effectiveness: {} / Max Likelihood: {}".format(
self.description, str(self.uriref), str(self.effectiveness_number), str(self.maximum_likelihood))
@property
def description(self):
asset_labels = self.control_set_asset_labels() # get unique set of asset labels the CSG involves (whether proposed or not)
asset_labels = [f'"{abbreviate_asset_label(label)}"' for label in asset_labels]
asset_labels.sort()
comment = "{} ({})".format(un_camel_case(dm_control_strategies[self._domain_model_uri()]["label"]), ", ".join(asset_labels))
return comment
def _domain_model_uri(self):
return self.graph.value(self.uriref, PARENT).split("/")[-1]
def _effectiveness_uri(self):
return dm_control_strategies[self._domain_model_uri()]["hasBlockingEffect"].split("/")[-1]
@property
def effectiveness_number(self):
return dm_trustworthiness_levels[self._effectiveness_uri()]["number"]
@property
def effectiveness_label(self):
return dm_trustworthiness_levels[self._effectiveness_uri()]["label"]
@property
def maximum_likelihood(self):
"""Return the maximum likelihood of the Threats that this Control Strategy can block.
Simply, this is the inverse of the CSG's effectiveness. However, we also need to take into account the coverage levels of the mandatory control sets.
The maximum likelihood is the minimum of the CSG's effectiveness and the minimum coverage of the mandatory control sets.
We do not check here whether the CSG or CS are active or not, as we want to know the maximum potential effectiveness.
"""
control_sets = self.graph.objects(self.uriref, HAS_MANDATORY_CONTROL_SET)
min_coverage = INFINITY
for cs in control_sets:
coverage_uri_fragment = self.graph.value(cs, HAS_COVERAGE).split("/")[-1]
coverage_level = dm_trustworthiness_levels[coverage_uri_fragment]["number"]
min_coverage = min(min_coverage, coverage_level)
return inverse(min(self.effectiveness_number, min_coverage))
@property
def is_current_risk_csg(self):
parent_uriref = self._domain_model_uri()
return dm_control_strategies[parent_uriref]["currentRisk"] and ("-Runtime" in str(parent_uriref) or "-Implementation" in str(parent_uriref))
@property
def is_future_risk_csg(self):
return dm_control_strategies[self._domain_model_uri()]["futureRisk"]
@cached_property
def blocked_threats(self):
return [self.graph.threat(threat_uriref) for threat_uriref in self.graph.value(self.uriref, BLOCKS)]
@property
def is_active(self):
# TODO: do we need to check sufficient CS?
# TODO: make a CS class?
control_sets = self.graph.objects(self.uriref, HAS_MANDATORY_CONTROL_SET)
all_proposed = True
for cs in control_sets:
if (cs, IS_PROPOSED, Literal(True)) not in self.graph:
all_proposed = False
return all_proposed
def control_set_urirefs(self):
return self.graph.objects(self.uriref, HAS_MANDATORY_CONTROL_SET)
def control_set_asset_urirefs(self):
cs_urirefs = self.control_set_urirefs()
asset_urirefs = []
for cs_uriref in cs_urirefs:
asset_urirefs += self.graph.objects(cs_uriref, LOCATED_AT)
return asset_urirefs
def control_set_asset_labels(self):
return sorted(list(set([self.graph.label(asset_uriref) for asset_uriref in self.control_set_asset_urirefs()])))
class TrustworthinessAttributeSet(Entity):
"""Represents a Trustworthiness Attribute Set."""
def __init__(self, uriref, graph):
super().__init__(uriref, graph)
def __str__(self):
return "Trustworthiness Attribute Set: {}\n Label: {}\n Description: {}\n".format(
str(self.uriref), self.label, self.description)
def _twa_uri(self):
return self.graph.value(self.uriref, HAS_TWA).split('/')[-1]
def _asserted_tw_level_uri(self):
uriref = self.graph.value(self.uriref, HAS_ASSERTED_LEVEL)
if uriref is None:
return None
return uriref.split('/')[-1]
def _inferred_tw_level_uri(self):
uriref = self.graph.value(self.uriref, HAS_INFERRED_LEVEL)
if uriref is None:
return None
return uriref.split('/')[-1]
@property
def label(self):
"""Return a TWAS label"""
try:
return dm_trustworthiness_attributes[self._twa_uri()]["label"]
except KeyError:
# might get here if the domain model CSVs are the wrong ones
logging.warning("No TWAS label for " + str(self.uriref))
return "**TWAS label**"
@property
def comment(self):
"""Return a short description of a TWAS"""
tw_level = self.inferred_level_label
twa = self.label
asset_uriref = self.graph.value(subject=self.uriref, predicate=LOCATED_AT)
asset = self.graph.label(asset_uriref)
return '{} of {} is {}'.format(un_camel_case(twa), asset, tw_level)
@property
def description(self):
"""Return a long description of a TWAS"""
try:
return dm_trustworthiness_attributes[self._twa_uri()]["description"]
except KeyError:
# might get here if the domain model CSVs are the wrong ones
logging.warning("No TWAS description for " + str(self.uriref))
return "**TWAS description**"
@property
def inferred_level_number(self):
return dm_trustworthiness_levels[self._inferred_tw_level_uri()]["number"]
@property
def inferred_level_label(self):
return dm_trustworthiness_levels[self._inferred_tw_level_uri()]["label"]
@property
def asserted_level_number(self):
return dm_trustworthiness_levels[self._asserted_tw_level_uri()]["number"]
@property
def inferred_level_label(self):
return dm_trustworthiness_levels[self._asserted_tw_level_uri()]["label"]
@property
def is_external_cause(self):
return (self.uriref, IS_EXTERNAL_CAUSE, Literal(True)) in self.graph
# TODO: this uses a domain-specific predicate. Don't incorporate it into a general class
@property
def is_default_tw(self):
"""Return Boolean describing whether this is a TWAS which has the Default TW attribute"""
return (self.uriref, HAS_TWA, DEFAULT_TW_ATTRIBUTE) in self.graph
class Threat(Entity):
"""Represents a Threat."""
def __init__(self, uri_ref, graph):
super().__init__(uri_ref, graph)
self.cached_explanations = []
def __str__(self):
return "Threat: {} ({})".format(self.short_comment, str(self.uriref))
def _likelihood_uri(self):
uriref = self.graph.value(self.uriref, HAS_PRIOR)
if uriref is None:
return None
return uriref.split('/')[-1]
def _risk_uri(self):
uriref = self.graph.value(self.uriref, HAS_RISK)
if uriref is None:
return None
return uriref.split('/')[-1]
def _frequency_uri(self):
uriref = self.graph.value(self.uriref, HAS_FREQUENCY)
if uriref is None:
return None
return uriref.split('/')[-1]
def _short_comment(self):
"""Return the first part of the threat description (up to the colon)"""
comment = self.graph.value(subject=self.uriref, predicate=HAS_COMMENT)
quote_counter = 0
char_index = 0
# need to deal with the case where there is a colon in a quoted asset label
while (comment[char_index] != ":" or quote_counter % 2 != 0):
if comment[char_index] == '"':
quote_counter += 1
char_index += 1
comment = comment[0:char_index]
return comment
@property
def short_comment(self):
"""Return the first part of the threat description (up to the colon) and add in the likelihood if so configured"""
comment = self._short_comment()
comment = comment.replace('re-disabled at "Router"', 're-enabled at "Router"') # hack that is necessary to correct an error in v6a3-1-4 for the overview paper system model
if not SHOW_LIKELIHOOD_IN_DESCRIPTION:
return comment
else:
return '{} likelihood of: {}'.format(self.likelihood_label, comment)
@property
def comment(self):
"""Return the full threat description"""
return self.graph.value(subject=self.uriref, predicate=HAS_COMMENT)
@property
def description(self):
"""Return the longer description of a threat (after the colon)"""
short_comment = self._short_comment()
comment = self.graph.value(subject=self.uriref, predicate=HAS_COMMENT)
comment = comment[len(short_comment) + 1:] # remove the short comment from the start
comment = comment.lstrip() # there is conventionally a space after the colon
char = comment[0]
return char.upper() + comment[1:] # uppercase the first word
@property
def likelihood_number(self):
if self._likelihood_uri() is None:
return -1
return dm_likelihood_levels[self._likelihood_uri()]["number"]
@property
def likelihood_label(self):
if self._likelihood_uri() is None:
return "N/A"
return dm_likelihood_levels[self._likelihood_uri()]["label"]
@property
def risk_number(self):
if self._risk_uri() is None:
return -1
return dm_risk_levels[self._risk_uri()]["number"]
@property
def risk_label(self):
if self._risk_uri() is None:
return "N/A"
return dm_risk_levels[self._risk_uri()]["label"]
@property
def frequency_number(self):
if self._frequency_uri() is None:
return None
return dm_likelihood_levels[self._frequency_uri()]["number"]
@property
def frequency_label(self):
if self._frequency_uri() is None:
return None
return dm_likelihood_levels[self._frequency_uri()]["label"]
@property
def is_normal_op(self):
return (self.uriref, IS_NORMAL_OP, Literal(True)) in self.graph
@property
def is_root_cause(self):
return (self.uriref, IS_ROOT_CAUSE, Literal(True)) in self.graph
@property
def is_secondary_threat(self):
return (self.uriref, HAS_SECONDARY_EFFECT_CONDITION, None) in self.graph
@property
def is_primary_threat(self):
return (self.uriref, HAS_ENTRY_POINT, None) in self.graph
@property
def is_initial_cause(self):
"""Return Boolean describing if the Threat is an 'initial cause'"""
return (self.uriref, IS_INITIAL_CAUSE, Literal(True)) in self.graph
@property
def trustworthiness_attribute_sets(self):
return [self.graph.trustworthiness_attribute_set(uriref) for uriref in self.graph.objects(self.uriref, HAS_ENTRY_POINT)]
@property
def primary_threat_misbehaviour_parents(self):
"""Get all the Misbehaviours that can cause this Threat (disregarding likelihoods), for primary Threat types"""
ms_urirefs = []
entry_points = self.graph.objects(self.uriref, HAS_ENTRY_POINT)
for twas in entry_points:
twis = self.graph.value(predicate=AFFECTS, object=twas)
ms_urirefs.append(self.graph.value(twis, AFFECTED_BY))
return [self.graph.misbehaviour(ms_uriref) for ms_uriref in ms_urirefs]
@property
def primary_threat_twas_ms(self):
"""Get all the (TWAS, MisbehaviourSets) that can cause this Threat (disregarding likelihoods), for primary Threat types"""
twas_ms = []
entry_points = self.graph.objects(self.uriref, HAS_ENTRY_POINT)
for twas_uriref in entry_points:
twas = self.graph.trustworthiness_attribute_set(twas_uriref)
twis = self.graph.value(predicate=AFFECTS, object=twas_uriref)
ms = self.graph.misbehaviour(self.graph.value(twis, AFFECTED_BY))
twas_ms.append((twas, ms))
return twas_ms
@property
def secondary_threat_misbehaviour_parents(self):
"""Get all the Misbehaviours that can cause this Threat (disregarding likelihoods), for secondary Threat types"""
ms_urirefs = self.graph.objects(self.uriref, HAS_SECONDARY_EFFECT_CONDITION)
return [self.graph.misbehaviour(ms_uriref) for ms_uriref in ms_urirefs]
@property
def misbehaviour_parents(self):
"""Get all the Misbehaviours that can cause this Threat (disregarding likelihoods), for all Threat types"""
return self.primary_threat_misbehaviour_parents + self.secondary_threat_misbehaviour_parents
@property
def twas_ms_parents(self):
"""Get all the (TWAS, MisbehaviourSets) that can cause this Threat (disregarding likelihoods), for all Threat types. For secondary Threats, the TWAS is None."""
p = self.primary_threat_twas_ms
s = self.secondary_threat_misbehaviour_parents
for ms in s:
p.append((None, ms))
return p
@property
def control_strategies(self, future_risk=True):
"""Return list of control strategy objects that block the threat"""
csgs = []
# the "blocks" predicate means a CSG appropriate for current or future risk calc
# the "mitigates" predicate means a CSG appropriate for future risk (often a contingency plan for a current risk CSG); excluded from likelihood calc in current risk
# The "mitigates" predicate is not used in newer domain models
if future_risk:
for csg_uri in chain(self.graph.subjects(BLOCKS, self.uriref), self.graph.subjects(MITIGATES, self.uriref)):
csg = self.graph.control_strategy(csg_uri)
if csg.is_future_risk_csg:
csgs.append(csg)
else:
for csg_uri in self.graph.subjects(BLOCKS, self.uriref):
csg = self.graph.control_strategy(csg_uri)
if csg.is_current_risk_csg and not csg.has_inactive_contingency_plan:
csgs.append(csg)
return csgs
def is_root_cause_disregarding_likelihood(self, is_normal_effect):
"""Return whether the Threat is a root cause, disregarding the likelihood from the risk calculation.
A root cause from the risk calculation is defined as a threat which:
- is not a normal operation (it is an “offensive” threat);
- has a non-negligible likelihood (it will cause something else);
- all its entry points:
- are external causes (TWAS) or
- are normal operation effects (Misbehaviours in the normal operation graph).
Here we check everything apart from the non-negligible likelihood condition.
"""
if self.is_normal_op:
# logging.debug(f"Threat {self.uriref} is normal operation")
return False
for twas, ms in self.twas_ms_parents:
if twas is not None:
# Then it was a TWAS/MS pair (as in primary threat)
if not twas.is_external_cause and not is_normal_effect[ms.uriref]:
# logging.debug(f"Threat {self.uriref} has a non-external TWAS {twas.uriref} and non-normal operation Misbehaviour {ms.uriref}")
return False
else:
# Then it was an MS only (as in secondary threat)
if not ms.is_normal_op:
# logging.debug(f"Threat {self.uriref} has a non-normal operation Misbehaviour {ms.uriref}")
return False
return True
@property
def local_uncontrolled_likelihood(self):
"""The likelihood of the threat disregarding any active control strategies at the threat."""
# For a primary threat it's the entry-point TWASs' inferred values we need to look at.
# The inferred TWAS levels will have taken into account the asserted levels and the inferred likelihoods of the causing misbehaviours.
# For a secondary threat it's the minimum likelihood of the causal misbehaviours (secondary effect conditions).
# We need to take into account that threats can have mixed causes (so can be both "primary" and "secondary"). The minimum likelihood of these causes is used.
# TODO: do we ever get here for a triggered threat with no triggers?
# Would need to check something like: if threat.isTriggered() and threat.getTriggeredByCSG().isEmpty()
inferred_twas_trustworthiness_levels = [twas.inferred_level_number for twas in self.trustworthiness_attribute_sets]
inferred_twas_likelihoods = [inverse(level) for level in inferred_twas_trustworthiness_levels]
if len(inferred_twas_likelihoods) > 0:
inferred_twas_likelihood = min(inferred_twas_likelihoods) # take min() as this is a threat
else:
inferred_twas_likelihood = INFINITY # Larger than the top of the actual scale
secondary_parent_misbehaviour_likelihoods = [ms.likelihood_number for ms in self.secondary_threat_misbehaviour_parents]
if len(secondary_parent_misbehaviour_likelihoods) > 0:
secondary_parent_misbehaviour_likelihood = min(secondary_parent_misbehaviour_likelihoods) # take min() as this is a threat
else:
secondary_parent_misbehaviour_likelihood = INFINITY
likelihood = min(inferred_twas_likelihood, secondary_parent_misbehaviour_likelihood) # take min() as all causes are needed
# A threat's likelihood cannot go above its frequency, if it is defined
if self.frequency_number is not None:
likelihood = min(likelihood, self.frequency_number)
return likelihood
def explain_likelihood(self, current_path=None):
"""Return an explanation of the likelihood of the Threat, given the path taken to get to the Threat. Return a cached result if there is a valid one."""
if current_path is None:
current_path = ()
normal_op = " (normal operation)" if self.is_normal_op else ""
logging.debug(" " * len(current_path) + "Explaining Threat: " + str(self.uriref) + " (" + self.short_comment + ")" + normal_op)
# See MisbehaviourSet.explain_likelihood for explanation of cache validity
for index, explanation in enumerate(self.cached_explanations):
if len(explanation.loopback_node_uris.intersection(current_path)) == len(explanation.loopback_node_uris) and len(explanation.cause_node_uris.intersection(current_path)) == 0:
logging.debug(" " * (len(current_path) + 1) + f"Reusing cached explanation {index}: {explanation}")
return explanation
# If there was nothing in the cache we can use, do the calculation and save the result before returning it
explanation = self._explain_likelihood(current_path)
logging.debug(" " * (len(current_path) + 1) + f"New explanation {len(self.cached_explanations)}: {explanation}")
self.cached_explanations.append(explanation)
return explanation
def _explain_likelihood(self, current_path):
"""Return an explanation of the likelihood of the Threat, given the path taken to get to the Threat."""
# General strategy:
# Examine all parent Misbehaviours (of both primary and secondary Threats) that are not already in the current path
# Put the returned tuples in parent_explanations
# A Threat requires all of its causes to be on good paths
# Combine and return parent explanations:
# AND(initial_cause expressions) or self if self is initial_cause
# AND(root_cause expressions) or self if self is root_cause
# min(upstream_uncontrolled_likelihood values) combined with the uncontrolled_inferred_likelihood
# union(all cause_node_uris)
# also adding self to the set
# union(loopback_node_uris)
# also removing self from the set to ensure the return value describes just the tree starting at self
# union(csg_reports)
# also adding any at self
# AND(uncontrolled_initial_cause expressions) - though there are complications
# AND(uncontrolled_root_cause expressions) - though there are complications
# make a copy of current_path, add self
current_path = set(current_path)
current_path.add(self.uriref)
parent_explanations = []
twas_ms_parents = self.twas_ms_parents
is_normal_effect = {}
if len(twas_ms_parents) == 0:
# this shouldn't happen
raise Exception("Threat has no parents")
# We only need one error to know we should throw an exception, but examining all paths will find all loopback nodes and may make the cached result more useful.
# TODO: need to check if that is the right strategy, or whether aborting as soon as there is an error is better
combined_loopback_node_uris = set()
throw_error = False
for (twas, ms) in twas_ms_parents:
if ms.uriref not in current_path:
try:
parent_explanation = ms.explain_likelihood(current_path) # may throw an exception
parent_explanations.append(parent_explanation)
is_normal_effect[ms.uriref] = parent_explanation.is_normal_effect # store this so we can easily use this when working out of the threat is a root cause
if twas is not None:
# We've jumped from the threat to a misbehaviour parent, bypassing the TWAS which is inbetween.
# Save the initial value so we can debug log if it changes
initial_upstream = parent_explanation.upstream_uncontrolled_likelihood
# A TWAS which is an external cause is normally at the top of the tree but it can be in the middle in some cases.
# We want to have the uncontrolled upstream likelihood of a threat to be defined by the first external cause met when moving upstream on any path.
# A common case at the top of the tree is when a threat has "NetworkUserTW of Internet" has a TWAS which is asserted to be level 0 (implying level 5 likelihood),
# the causing MS is "Internet loses Network User Trustworthiness" and that has max likelihood 0.
if twas.is_external_cause:
parent_explanation.upstream_uncontrolled_likelihood = inverse(twas.asserted_level_number)
if initial_upstream != parent_explanation.upstream_uncontrolled_likelihood:
logging.debug(" " * len(current_path) + "Parent TWAS is_external_cause: changing upstream uncontrolled likelihood from " + str(initial_upstream) + " to " + str(parent_explanation.upstream_uncontrolled_likelihood))
else:
# Potentially increase the upstream_uncontrolled_likelihood if the TWAS is not an external cause and the asserted trustworthiness level is low.
twas_ms_likelihood = max(initial_upstream, inverse(twas.asserted_level_number))
if twas_ms_likelihood != initial_upstream:
parent_explanation.upstream_uncontrolled_likelihood = twas_ms_likelihood
logging.debug(" " * len(current_path) + "Parent TWAS has low asserted TW: increasing upstream uncontrolled likelihood from " + str(initial_upstream) + " to " + str(twas_ms_likelihood))
except LoopbackError as error:
logging.debug(" " * len(current_path) + "Error: parent Misbehaviour cannot be caused: " + str(ms.uriref))
combined_loopback_node_uris |= error.loopback_node_uris
throw_error = True
else:
logging.debug(" " * len(current_path) + "Error: parent Misbehaviour is on current path: " + str(ms.uriref))
combined_loopback_node_uris.add(ms.uriref)
throw_error = True
combined_loopback_node_uris.discard(self.uriref)
if throw_error:
logging.debug(" " * len(current_path) + "Error: path is not viable")
raise LoopbackError(combined_loopback_node_uris)
logging.debug(" " * len(current_path) + "Parent upstream uncontrolled likelihoods: " + str([ret.upstream_uncontrolled_likelihood for ret in parent_explanations]))
combined_cause_node_uris = set().union(*[ret.cause_node_uris for ret in parent_explanations])
combined_cause_node_uris.add(self.uriref)
combined_upstream_uncontrolled_likelihood = min([ret.upstream_uncontrolled_likelihood for ret in parent_explanations]) # take min() as this is a threat
combined_csg_reports = set().union(*[ret.csg_reports for ret in parent_explanations])
# If the maximum likelihood this could ever be is zero then just abort as it cannot be a "cause" of anything: we don't care about CSGs at this Threat and it cannot be an uncontrolled cause
if combined_upstream_uncontrolled_likelihood == 0:
logging.debug(" " * len(current_path) + "Threat has zero max likelihood so cannot be the cause of anything")
logging.debug(" " * len(current_path) + "Discarding " + str(len(combined_csg_reports)) + " CSG reports")
for csg_report in combined_csg_reports:
logging.debug(" " * len(current_path) + " - " + str(csg_report))
return Explanation(
initial_cause=None,
root_cause=None,
upstream_uncontrolled_likelihood=0,
local_uncontrolled_likelihood=self.local_uncontrolled_likelihood,
cause_node_uris=combined_cause_node_uris,
loopback_node_uris=combined_loopback_node_uris,
csg_reports=set(),
uncontrolled_initial_cause=None,