-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot-attack-graph.py
executable file
·2197 lines (1886 loc) · 103 KB
/
plot-attack-graph.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
# Copyright 2023-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: 2023 The University of Southampton IT Innovation Centre -->
# <!-- SPDX-ArtifactOfProjectName: Spyderisk -->
# <!-- SPDX-FileType: Source code -->
# <!-- SPDX-FileComment: Original by Stephen Phillips, November 2023 -->
import argparse
import csv
import gzip
import logging
import re
import sys
import tempfile
import textwrap
import time
from collections import defaultdict
from itertools import chain
from pathlib import Path
import boolean
from graphviz import Digraph
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.INFO)
parser = argparse.ArgumentParser(description="Plot attack graphs for Spyderisk system models",
epilog="e.g. plot-attack-graph.py -i SteelMill.nq.gz -o steel.pdf -d ../domain-network/csv/ -m MS-LossOfControl-f8b49f60 MS-LossOfReliability-f8b49f60 --and --or --hide-misbehaviours --hide-secondary-threats --external-causes --initial-causes --hide-link-labels --hide-likelihood-in-description --hide-node-titles --compact --text-width 30")
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_image_filename", help="Output filename (PDF, SVG or PNG)")
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=True, nargs="+", metavar="URI_fragment", help="Target misbehaviour IDs, e.g. 'MS-LossOfControl-f8b49f60'")
parser.add_argument("--plot-direction", dest="plot_direction", choices=['BT', 'TB', 'RL', 'LR'], default='TB', help="The direction of the plot from causes to effects (B=bottom, T=top, L=left, R=right)")
parser.add_argument("--current-risk", action='store_true', help="Run in current (not future) risk mode, affecting the control strategies proposed")
parser.add_argument("--limit-logic", action='store_true', help="Compute the logical expressions to only target nodes on the shortest paths")
parser.add_argument("--and", action="store_true", help="Add explicit AND nodes to the displayed graph")
parser.add_argument("--or", action="store_true", help="Add explicit OR nodes to the displayed graph")
parser.add_argument("--all-routes", action='store_true', help="Show all routes through the graph, not just the shortest")
parser.add_argument("--highlight-short-routes", action='store_true', help="Highlight the shortest routes through the graph if all routes are shown")
parser.add_argument("--normal-ops", action='store_true', help="Show the normal operation graph (apart from embedded normal ops)")
parser.add_argument("--embedded-normal-ops", action='store_true', help="Show normal operation nodes embedded in the attack graph")
parser.add_argument("--external-causes", action='store_true', help="Show the external causes (apart from 'DefaultTW' ones)")
parser.add_argument("--default-tw", action='store_true', help="Show the 'DefaultTW' external causes")
parser.add_argument("--initial-causes", action='store_true', help="Show the initial causes (apart from 'InService' ones)")
parser.add_argument("--in-service", action='store_true', help="Show the 'InService' initial causes")
parser.add_argument("--hide-confusing-misbehaviours", action='store_true', help="Hide misbehaviours relating to inferred assets")
parser.add_argument("--hide-misbehaviours", action='store_true', help="Hide all misbehaviour nodes")
parser.add_argument("--hide-secondary-threats", action="store_true", help="Hide secondary threats in the graph")
parser.add_argument("--constrain-arrows", action='store_true', help="Force the arrows to enter/leave the nodes at the top/bottom (or left/right)")
parser.add_argument("--align-root-causes", action='store_true', help="Align the root causes")
parser.add_argument("--align-target-misbehaviours", action='store_true', help="Align the target misbehaviours") # TODO: needs to be mutually exclusive with align-root-causes
parser.add_argument("--blobs", action="store_true", help="Show all nodes as circles with no content")
parser.add_argument("--compact", action="store_true", help="Make the plot more compact by reducing margins between nodes")
parser.add_argument("--hide-link-labels", action="store_true", help="Hide the labels on the arrows connecting the nodes")
parser.add_argument("--hide-command", action='store_true', help="Hide the command line from the plot")
parser.add_argument("--likelihood", action='store_true', help="Show the likelihood on each node")
parser.add_argument("--impact", action='store_true', help="Show the impact on each node")
parser.add_argument("--risk", action='store_true', help="Show the risk on each node")
parser.add_argument("--uri", action='store_true', help="Show the URI of each node")
parser.add_argument("--distance-from-root", action='store_true', help="Show the distance from the root cause on a node")
parser.add_argument("--primary-threat-distance", action='store_true', help="Show the number of primary threats needed to get to each node")
parser.add_argument("--attack-graph-controls", action='store_true', help="Show logical expressions for controls that block the attack graph on each node")
parser.add_argument("--threat-graph-controls", action='store_true', help="Show logical expressions for controls that block the threat graph on each node")
parser.add_argument("--attack-graph-control-strategies", action='store_true', help="Show logical expressions for controls strategies that block the attack graph on each node")
parser.add_argument("--threat-graph-control-strategies", action='store_true', help="Show logical expressions for controls strategies that block the threat graph on each node")
parser.add_argument("--threat-description", action='store_true', help="Show the long threat descriptions")
parser.add_argument("--misbehaviour-description", action='store_true', help="Show the long misbehaviour descriptions")
parser.add_argument("--node-title", action="store_true", help="Show the titles on the nodes")
parser.add_argument("--likelihood-in-description", action="store_true", help="Show the likelihood in the node descriptions")
parser.add_argument("--text-width", metavar="integer", default="60", help="Character-width of the text in nodes")
parser.add_argument("--debug-csv", dest="csv_debug_filename", metavar="filename", help="Filename to dump CSV formatted node information for debugging")
parser.add_argument("--debug-logical-expressions", dest="le_debug_filename", metavar="filename", help="Filename to write logical expressions for target consequences into")
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, _, output_format = args["output"].rpartition(".")
target_ms_ids = args["misbehaviours"]
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"
# General plot options:
FUTURE_RISK = not args["current_risk"]
LIMIT_LOGIC_TO_SHORTEST_PATH = args["limit_logic"]
HIDE_LONG_ROUTES = not args["all_routes"]
SHOW_NORMAL_OPS = args["normal_ops"]
SHOW_EMBEDDED_NORMAL_OPS = args["embedded_normal_ops"]
SHOW_EXTERNAL_CAUSES = args["external_causes"]
SHOW_DEFAULT_TW = args["default_tw"]
SHOW_INITIAL_CAUSES = args["initial_causes"]
SHOW_IN_SERVICE = args["in_service"]
HIGHLIGHT_SHORT_ROUTES = args["highlight_short_routes"]
HIDE_CONFUSING_MISBEHAVIOURS = args["hide_confusing_misbehaviours"]
HIDE_ALL_MISBEHAVIOURS = args["hide_misbehaviours"]
HIDE_SECONDARY_THREATS = args["hide_secondary_threats"]
ALIGN_ROOT_CAUSES = args["align_root_causes"]
ALIGN_TARGET_MISBEHAVIOURS = args["align_target_misbehaviours"]
PLOT_DIRECTION = args["plot_direction"]
HIDE_COMMAND = args["hide_command"]
CONSTRAIN_ARROWS = args["constrain_arrows"]
HIDE_LINK_LABELS = args["hide_link_labels"]
ADD_ANDS = args["and"]
ADD_ORS = args["or"]
# Node plot options:
TEXT_WIDTH = int(args["text_width"]) # word-wrap limit in nodes
SHOW_DISTANCE_FROM_ROOT = args["distance_from_root"] # show the distance from the nearest root cause on each node
SHOW_THREAT_DESCRIPTION = args["threat_description"] # show full threat descriptions
SHOW_MISBEHAVIOUR_DESCRIPTION = args["misbehaviour_description"] # show full effect descriptions
SHOW_ATTACK_MITIGATION_CS = args["attack_graph_controls"] # show the attack tree control set mitigation Boolean expression on each node
SHOW_THREAT_MITIGATION_CS = args["threat_graph_controls"] # show the threat tree control set mitigation Boolean expression on each node
SHOW_ATTACK_MITIGATION_CSG = args["attack_graph_control_strategies"] # show the attack tree control strategy mitigation Boolean expression on each node
SHOW_THREAT_MITIGATION_CSG = args["threat_graph_control_strategies"] # show the threat tree control strategy mitigation Boolean expression on each node
SHOW_URI = args["uri"] # show the URI of a node
SHOW_BLOBS = args["blobs"]
COMPACT = args["compact"]
SHOW_PRIMARY_THREAT_DISTANCE = args["primary_threat_distance"]
SHOW_NODE_TITLE = args["node_title"]
SHOW_LIKELIHOOD_IN_DESCRIPTION = args["likelihood_in_description"]
SHOW_LIKELIHOOD = args["likelihood"] # show the likelihood on each node
SHOW_IMPACT = args["impact"] # show the impact on each node
SHOW_RISK = args["risk"] # show the risk on each node
# Rarely required options with no corresponding command line argument:
SHOW_ROOT_CAUSE = False # show the root cause of each node
SHOW_ATTACK_TREE = False # show the attack tree on each node
SHOW_THREAT_TREE = False # show the threat tree on each node
SHOW_CAUSE_URIS = False # show the URIs of a node's direct causes
SHOW_CACHE_DEBUG = False # show the number of visits and results of different types on each node
SHOW_RANK = False # show the "rank" of each node (useful for debugging)
# Debug options
csv_debug_filename = args["csv_debug_filename"]
le_debug_filename = args["le_debug_filename"]
# 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")
THREAT = URIRef(CORE + "#Threat")
HAS_LIKELIHOOD = URIRef(CORE + "#hasPrior")
HAS_IMPACT = URIRef(CORE + "#hasImpactLevel")
HAS_RISK = URIRef(CORE + "#hasRisk")
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_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")
DUMMY_CSG = "dummy-csg"
DEFAULT_TW_ATTRIBUTE = URIRef(DOMAIN + "#DefaultTW")
IN_SERVICE = URIRef(DOMAIN + "#InService")
INFINITY = 99999999
# 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
misbehaviour[row[uri_index]] = {}
misbehaviour[row[uri_index]]["label"] = row[label_index]
misbehaviour[row[uri_index]]["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
ta[row[uri_index]] = {}
ta[row[uri_index]]["label"] = row[label_index]
ta[row[uri_index]]["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
control[row[uri_index]] = {}
control[row[uri_index]]["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 = False if header.index("currentRisk") == "FALSE" else True
future_index = False if header.index("futureRisk") == "FALSE" else True
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"] = row[current_index]
csg[uri]["futureRisk"] = row[future_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 plot_graph(filename, nodes_to_plot, links_to_plot, rank_by_uri, highlighted_nodes):
"""Plot a graph of the attack tree.
filename: filename to write to
nodes_to_plot: set of TreeNode objects to include in the plot
links_to_plot: set of (node, predicate, node) tuples to plot (only those where both ends are in the nodes_to_plot set are used)
rank_by_uri: dictionary describing the numeric rank of each node using the node.uri as the key
highlighted_nodes: set of nodes which should be highlighted
"""
print("Plotting graph "+ filename + "...")
# the neato engine does a pretty good job but ignores the ranks
# gv = Digraph(engine="neato")
# the dot engine uses the rank info provided
gv = Digraph(engine="dot")
gv.format = output_format
gv.attr("node", shape="box")
gv.attr(overlap="scale") # "false" is often good but need to use "scale" in Windows because Windows binary does not inlcude necessary lib
gv.attr(splines="true") # "true" means arrows avoid nodes (but also means it is not the same style as SSM)
gv.attr(newrank="true")
if not COMPACT:
gv.attr(nodesep="1")
gv.attr(ranksep="1")
else:
gv.attr(nodesep="1")
gv.attr(ranksep="0.3")
gv.attr(pagedir="BL")
gv.attr(rankdir=PLOT_DIRECTION)
nodes_to_plot = sorted(nodes_to_plot, key=lambda n: n.uri)
if ALIGN_ROOT_CAUSES or ALIGN_TARGET_MISBEHAVIOURS:
nodes_by_rank = defaultdict(list)
for node in nodes_to_plot:
nodes_by_rank[rank_by_uri.get(node.uri, INFINITY)].append(node)
ranks = list(nodes_by_rank.keys())
ranks.sort()
if ALIGN_TARGET_MISBEHAVIOURS: ranks.reverse()
node_from_previous = None
for rank in ranks:
with gv.subgraph() as sub:
sub.attr(rank="same")
for node in nodes_by_rank[rank]:
plot_node(sub, node, node in highlighted_nodes, rank)
node_from_this_rank = nodes_by_rank[rank][0]
if node_from_previous != None:
# add an invisible constrained link forcing one rank to be further down the page than the next
gv.edge(node_from_previous.uri[7:], node_from_this_rank.uri[7:], "RANK", {"constraint": "True", "style": "invis"})
node_from_previous = node_from_this_rank
else:
for node in nodes_to_plot:
plot_node(gv, node, node in highlighted_nodes)
for link in links_to_plot:
start_node, predicate, end_node = link
if start_node not in nodes_to_plot or end_node not in nodes_to_plot:
continue
is_from_normal_op = start_node.is_normal_op
if ALIGN_TARGET_MISBEHAVIOURS:
is_back_link = rank_by_uri[start_node.uri] <= rank_by_uri[end_node.uri]
elif ALIGN_ROOT_CAUSES:
if start_node.is_normal_op and (not end_node.is_normal_op):
is_back_link = False
else:
is_back_link = rank_by_uri[start_node.uri] >= rank_by_uri[end_node.uri]
else:
is_back_link = False
is_highlighted = len(nodes_to_plot) > len(highlighted_nodes) and start_node in highlighted_nodes and end_node in highlighted_nodes
is_from_external_cause = start_node.is_external_cause
plot_link(gv, link, is_back_link, is_from_normal_op, is_highlighted, is_from_external_cause)
gv.body.append('labelloc="b";')
if not HIDE_COMMAND:
gv.body.append('label="\n\n{}";'.format(' '.join(sys.argv)))
# Tip: open PDF of graph in Chrome to avoid locking the file, the press F5 in Chrome to refresh page
gv.render(filename)
def plot_node(gv, node, is_highlighted=True, rank=None):
attr = {"style": "filled", "color": "#333333", "margin": "0"}
uriref = node.uri
if node.is_logic:
attr["fillcolor"] = "#65ff65"
attr["shape"] = "hexagon"
hex_size = 0.75
attr["width"] = str(hex_size)
attr["height"] = str(hex_size * (3**0.5) / 2)
attr["fixedsize"] = "true"
elif node.is_threat:
if node.is_normal_op:
if node.is_initial_cause:
node_type = "Initial Cause"
attr["fillcolor"] = "#dddddd"
attr["penwidth"] = "6"
else:
node_type = "Normal Operation"
attr["fillcolor"] = "#ffffff"
else:
if node.is_root_cause:
node_type = "Root Cause Threat"
attr["fillcolor"] = "#ff6565" # ff0000 40% lighter
attr["penwidth"] = "6"
else:
attr["fillcolor"] = "#ff9999" # ff0000 60% lighter
if node.is_secondary_threat:
node_type = "Secondary Threat"
if not HIDE_SECONDARY_THREATS:
attr["style"] += ",rounded"
else:
node_type = "Primary Threat"
if not HIDE_SECONDARY_THREATS:
attr["color"] = "#ff0000"
attr["penwidth"] = "4"
if not is_highlighted:
attr["fillcolor"] = "#ffe5e5" # ff0000 90% lighter
else:
if node.is_normal_op:
node_type = "Normal Effect"
attr["fillcolor"] = "#ffffff"
else:
if node.is_external_cause:
node_type = "External Cause"
attr["fillcolor"] = "#ffd700"
attr["penwidth"] = "6"
else:
node_type = "Consequence"
if node.is_target_ms:
attr["fillcolor"] = "#ffd700"
else:
attr["fillcolor"] = "#ffef99" # 60% lighter
if not is_highlighted:
attr["fillcolor"] = "#fffbe5" # 90% lighter
if ALIGN_ROOT_CAUSES or ALIGN_TARGET_MISBEHAVIOURS:
attr["rank"] = str(rank)
if node.is_logic:
if node.is_and:
text = ["AND"]
else:
text = ["OR"]
elif SHOW_BLOBS:
attr["shape"] = "circle"
if node.is_threat and not node.is_secondary_threat:
attr["shape"] = "square"
# if node.index != None:
# text = [str(node.index)]
# else:
text = []
else:
text = []
if SHOW_NODE_TITLE:
text.append("<B>{}</B>".format(node_type))
text.append(textwrap.fill(node.comment, TEXT_WIDTH))
if (node.is_threat and SHOW_THREAT_DESCRIPTION) or (not node.is_threat and SHOW_MISBEHAVIOUR_DESCRIPTION):
text.append(textwrap.fill(node.description, TEXT_WIDTH))
if SHOW_RANK and rank != None:
text.append("Rank: {}".format(rank))
if not node.is_external_cause:
levels = []
if COMPACT:
line = []
if SHOW_IMPACT and not node.is_threat:
line.append("I:{}".format(node.impact_text))
if SHOW_LIKELIHOOD:
line.append("L:{}".format(node.likelihood_text))
if SHOW_RISK:
line.append("R:{}".format(node.risk_text))
line = " / ".join(line)
levels.append(line)
else:
if SHOW_IMPACT and not node.is_threat:
levels.append("Impact: {}".format(node.impact_text))
if SHOW_LIKELIHOOD:
levels.append("Likelihood: {}".format(node.likelihood_text))
if SHOW_RISK:
if node.is_threat:
prefix = "System"
else:
prefix = "Direct"
levels.append("{} Risk: {}".format(prefix, node.risk_text))
if len(levels) > 0:
text.append("\n".join(levels))
if SHOW_PRIMARY_THREAT_DISTANCE and not node.is_logic:
text.append("{}".format(node.min_primary_threat_distance))
if SHOW_DISTANCE_FROM_ROOT and node.min_distance_from_root > 0 and not node.is_logic:
text.append("{}/{}".format(node.min_distance_from_root, node.max_distance_from_root))
if SHOW_ROOT_CAUSE and not node.is_root_cause and not node.is_external_cause and not node.is_initial_cause:
text.append("Root cause:\n" + str(node.root_cause).replace("\n", "\l") + "\l")
# Don't show attack tree on normal-ops
if SHOW_ATTACK_TREE and not node.is_normal_op:
text.append("Attack tree:\n" + str(node.attack_tree).replace("\n", "\l") + "\l")
# Don't show attack path mitigation on normal-ops
if SHOW_ATTACK_MITIGATION_CS and not node.is_normal_op:
text.append("Controls to block attack:\n" + str(node.attack_tree_mitigation_cs).replace("\n", "\l") + "\l")
# Don't show attack path mitigation on normal-ops
if SHOW_ATTACK_MITIGATION_CSG and not node.is_normal_op:
text.append("Control strategies to block attack:\n" + str(node.attack_tree_mitigation_csg).replace("\n", "\l") + "\l")
# Don't show threat tree if it's the same as the attack tree (and we're showing that)
if SHOW_THREAT_TREE and not (SHOW_ATTACK_TREE and str(node.attack_tree) == str(node.threat_tree)):
text.append("Threat tree:\n" + str(node.threat_tree).replace("\n", "\l") + "\l")
# Don't show threat path mitigation if it's the same as the attack path mitigation (and we're showing that)
if SHOW_THREAT_MITIGATION_CS and not (SHOW_ATTACK_MITIGATION_CS and str(node.attack_tree_mitigation_cs) == str(node.threat_tree_mitigation_cs)):
text.append("Controls to block threat:\n" + str(node.threat_tree_mitigation_cs).replace("\n", "\l") + "\l")
# Don't show threat path mitigation if it's the same as the attack path mitigation (and we're showing that)
if SHOW_THREAT_MITIGATION_CSG and not (SHOW_ATTACK_MITIGATION_CSG and str(node.attack_tree_mitigation_csg) == str(node.threat_tree_mitigation_csg)):
text.append("Control strategies to block threat:\n" + str(node.threat_tree_mitigation_csg).replace("\n", "\l") + "\l")
if SHOW_CAUSE_URIS:
# Put parentheses round normal-ops
text.append("Direct causes:")
# sort the parents so that we get a consistent comparable plot
for direct_cause_uri in sorted(node.direct_cause_uris):
# TODO: remove use of global threat_tree here
if not threat_tree[direct_cause_uri].is_normal_op:
text.append(get_comment(direct_cause_uri.split('#')[1]))
else:
text.append("(" + get_comment(direct_cause_uri.split('#')[1]) + ")")
if SHOW_CACHE_DEBUG:
text.append("Cache hits / Visits: {} / {}".format(node.cache_hit_visits, node.visits))
text.append("Cause / No cause: {} / {}".format(node.cause_visits, node.no_cause_visits))
if SHOW_URI:
text.append("<I>" + str(uriref).split('#')[1] + "</I>")
if not node.is_logic:
text = "</td></tr><tr><td>".join(text)
text = text.replace("\n", "<BR/>")
text = text.replace("\l", '<BR ALIGN="LEFT"/>')
if COMPACT:
padding = "5"
else:
padding = "10"
text = "<<table border='0' cellborder='1' cellpadding='" + padding + "' cellspacing='0'><tr><td>" + text + "</td></tr></table>>"
else:
text = text[0]
gv.node(uriref[7:], text, **attr)
def plot_link(gv, link, is_back_link, is_from_normal_op, is_highlighted, is_from_external_cause):
start_uri = link[0].uri
if not HIDE_LINK_LABELS:
label = link[1]
else:
label = ""
end_uri = link[2].uri
attr = {"fontcolor": "black", "color": "black", "style": "solid", "penwidth": "3"}
if CONSTRAIN_ARROWS:
if PLOT_DIRECTION == "TB":
attr["tailport"] = "s"
attr["headport"] = "n"
elif PLOT_DIRECTION == "BT":
attr["tailport"] = "n"
attr["headport"] = "s"
elif PLOT_DIRECTION == "LR":
attr["tailport"] = "e"
attr["headport"] = "w"
elif PLOT_DIRECTION == "RL":
attr["tailport"] = "w"
attr["headport"] = "e"
if is_from_normal_op or is_from_external_cause:
attr["style"] = "dashed"
attr["color"] = "gray"
if is_back_link:
attr["color"] = "red"
if is_highlighted:
attr["penwidth"] = "8"
gv.edge(start_uri[7:], end_uri[7:], label, **attr)
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 get_comment(uriref):
if (uriref, HAS_TYPE, MISBEHAVIOUR_SET) in graph:
return get_ms_comment(uriref)
elif (uriref, HAS_TYPE, CONTROL_SET) in graph:
return get_cs_comment(uriref)
elif (get_is_threat(uriref)):
return get_threat_comment(uriref)
elif DUMMY_CSG in str(uriref):
return get_csg_comment(uriref)
if str(uriref).startswith("http://"):
label = graph.label(subject=uriref, default=None)
if label is not None:
return label
if str(uriref).startswith(CORE):
label = "core" + str(uriref)[len(CORE):]
elif str(uriref).startswith(DOMAIN):
label = "domain" + str(uriref)[len(DOMAIN):]
else:
label = str(uriref)
return label
def _get_threat_comment(uriref):
"""Return the first part of the threat description (up to the colon)"""
comment = graph.value(subject=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
def get_threat_comment(uriref):
"""Return the first part of the threat description (up to the colon) and add in the likelihood if so configured"""
comment = _get_threat_comment(uriref)
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:
likelihood = un_camel_case(get_likelihood_text(uriref))
return '{} likelihood of: {}'.format(likelihood, comment)
def get_threat_description(uriref):
"""Return the longer description of a threat (after the colon)"""
short_comment = _get_threat_comment(uriref)
comment = graph.value(subject=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
def get_ms_comment(uriref):
"""Return a short description of a misbehaviour"""
likelihood = un_camel_case(get_likelihood_text(uriref))
consequence = get_ms_label(uriref)
asset_uri = graph.value(subject=uriref, predicate=LOCATED_AT)
asset = graph.label(asset_uri)
aspect = None
if consequence.startswith("LossOf"):
aspect = un_camel_case(consequence[6:])
consequence = "loses"
elif consequence.startswith("Loss Of"):
aspect = un_camel_case(consequence[7:])
consequence = "loses"
elif consequence.startswith("Not"):
aspect = un_camel_case(consequence[3:])
consequence = "is not"
if aspect != None:
if not SHOW_LIKELIHOOD_IN_DESCRIPTION:
return '"{}" {} {}'.format(un_camel_case(asset), consequence, aspect)
else:
return '{} likelihood that "{}" {} {}'.format(likelihood, un_camel_case(asset), consequence, aspect)
else:
if not SHOW_LIKELIHOOD_IN_DESCRIPTION:
return '{} at {}'.format(un_camel_case(consequence), un_camel_case(asset))
else:
return '{} likelihood of: {} at {}'.format(likelihood, un_camel_case(consequence), un_camel_case(asset))
def get_ms_description(uriref):
"""Return a long description of a misbehaviour"""
misbehaviour = graph.value(uriref, HAS_MISBEHAVIOUR)
try:
return misbehaviours[misbehaviour.split('/')[-1]]["description"]
except:
# might get here if the domain model CSVs are the wrong ones
logging.warning("No MS description for " + str(uriref))
return "**MS description**"
def get_ms_label(uriref):
"""Return a misbehaviour label"""
misbehaviour = graph.value(uriref, HAS_MISBEHAVIOUR)
try:
return misbehaviours[misbehaviour.split('/')[-1]]["label"]
except:
# might get here if the domain model CSVs are the wrong ones
logging.warning("No MS label for " + str(uriref))
return "**MS label**"
def get_twas_description(uriref):
"""Return a long description of a TWAS"""
twa = graph.value(uriref, HAS_TWA)
try:
return trustworthiness_attributes[twa.split('/')[-1]]["description"]
except:
# might get here if the domain model CSVs are the wrong ones
logging.warning("No TWAS description for " + str(uriref))
return "**TWAS description**"
def get_twas_comment(uriref):
"""Return a short description of a TWAS"""
tw_level = un_camel_case(get_trustworthiness_text(uriref))
twa = get_twas_label(uriref)
asset_uri = graph.value(subject=uriref, predicate=LOCATED_AT)
asset = graph.label(asset_uri)
return '{} of {} is {}'.format(un_camel_case(twa), asset, tw_level)
def get_twas_label(uriref):
"""Return a TWAS label"""
twa = graph.value(uriref, HAS_TWA)
try:
return trustworthiness_attributes[twa.split('/')[-1]]["label"]
except:
# might get here if the domain model CSVs are the wrong ones
logging.warning("No TWAS label for " + str(uriref))
return "**TWAS label**"
def get_cs_comment(cs_uri):
control_uri = graph.value(cs_uri, HAS_CONTROL)
control_label = un_camel_case(controls[control_uri.split('/')[-1]]["label"])
asset_uri = graph.value(cs_uri, LOCATED_AT)
asset_label = graph.value(asset_uri, HAS_LABEL)
if asset_label[0] != "[": asset_label = '"' + asset_label + '"'
return control_label + " at " + asset_label
def get_csg_comment(dummy_csg_uri):
# TODO: change this to not use the MyControlStrategy and just use the CSG directly
my_csg = MyControlStrategy.get_by_dummy_uriref(dummy_csg_uri)
# cs_comment = "AND(" + ", ".join([get_cs_comment(cs) for cs in my_csg.inactive_control_set_uris]) + ")"
# comment = "{}: {}".format(my_csg.label, cs_comment)
# comment = "{}: {}".format(my_csg.label, my_csg.description)
# comment = "{}".format(my_csg.label)
asset_labels = list(set(get_csg_asset_labels(my_csg))) # get unique set of asset labels the CSG involves (whether proposed or not)
asset_labels = [abbreviate_asset_label(label) for label in asset_labels]
asset_labels.sort()
comment = "{} ({})".format(my_csg.label, ", ".join(asset_labels))
return comment
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 URI fragment for us in logical expressions"""
return symbol(uriref.split('#')[1])
def get_comment_from_match(frag_match):
return get_comment(URIRef(SYSTEM + "#" + frag_match.group()[8:-2]))
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()
def __str__(self):
return self.pretty_print()
def __eq__(self, other):
return self.cause == other.cause
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()])
def pretty_print(self, max_complexity=30):
if self.cause is None:
return "-None-"
cause_complexity = str(self.cause.args).count("Symbol")
if cause_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(cause_complexity)
return cause
class TreeTraversalError(Exception):
"""Some error when recursing down the tree"""
def __init__(self, loopback_node_uris: set = None) -> None:
if loopback_node_uris is None: loopback_node_uris = set()
self.loopback_node_uris = loopback_node_uris
class ThreatTree():
"""The container for a set of TreeNodes"""
def __init__(self, target_uris=None, is_future_risk=True, shortest_path=False):
"""
Parameters
----------
target_uris : list of URIRef
describes the misbehaviours that we want to know the threat trees for
is_future_risk : bool, optional
whether to do a future or current risk analysis (affects which control strategies are considered)
shortest_path : bool, optional
if True then only the TreeNodes on the shortest paths are included in the ThreatTree
"""
self._node_by_uri = {}
self.target_uris = target_uris
self.is_future_risk = is_future_risk
self.bounding_urirefs = None
if not shortest_path:
logging.info("Running backtrace")
self._backtrace(compute_logic=True)
logging.info("Tree has " + str(len(self.nodes)) + " nodes")
else:
# If the shortest path is required then we get the URIRefs of the shortest path nodes from the first pass at the ThreatTree
# then discard all TreeNodes and create a new ThreatTree which is bounded by the shortest path URIRefs.
logging.info("Running first backtrace")
self._backtrace(compute_logic=False)
logging.info("Tree has " + str(len(self.nodes)) + " nodes")
self.bounding_urirefs = set([node.uri for node in self.shortest_path_nodes])
self._node_by_uri = {}
logging.info("Running second backtrace, bounded by " + str(len(self.bounding_urirefs)) + " nodes")
self._backtrace(compute_logic=True)
logging.info("Tree has " + str(len(self.nodes)) + " nodes")
def __getitem__(self, uri):
return self._node_by_uri[uri]
def get_or_create_node(self, uri):
if uri not in self._node_by_uri:
self._node_by_uri[uri] = TreeNode(uri, self)
return self._node_by_uri[uri]
def _backtrace(self, compute_logic=True):
for target_uri in self.target_uris:
node = self.get_or_create_node(target_uri)
node.is_target_ms = True
logging.info("Making tree for " + str(node.uri))
node.backtrace(compute_logic=compute_logic)
@property
def nodes(self):
# Don't return the nodes that are in the error state
return [node for node in self._node_by_uri.values() if not node.not_a_cause]
@property
def uris(self):
# Don't return the nodes that are in the error state
return [uri for uri in self._node_by_uri.keys() if not self._node_by_uri[uri].not_a_cause]
@property
def root_causes(self):
uris = set()
for node in self.nodes: # Using property
if node.is_root_cause:
uris.add(node.uri)
return uris
@property
def external_causes(self):
uris = set()
for node in self.nodes:
if node.is_external_cause:
uris.add(node.uri)
return uris
@property
def initial_causes(self):
uris = set()
for node in self.nodes:
if node.is_initial_cause:
uris.add(node.uri)
return uris
@property
def normal_operations(self):
uris = set()
for node in self.nodes:
if node.is_normal_op:
uris.add(node.uri)
return uris
def add_max_distance_from_target(self, uriref, current_path=None):
"""Find the maximum distance from a target URI (useful to space out nodes for plotting)."""
if current_path == None:
current_path = ()
# Using a tuple for current_path to ensure that when we change it we make a copy so that the addition is undone when the recursion unwinds
current_path = current_path + (uriref,)
current_node = self._node_by_uri[uriref]
target_uriref = current_path[0]
current_distance = current_node.max_distance_from_target_by_target.get(target_uriref, -1)
current_node.max_distance_from_target_by_target[target_uriref] = max(current_distance, len(current_path) - 1) # start at 0
for cause_uriref in current_node.direct_cause_uris:
# there can be loops in the "tree" so have to make sure we don't follow one
if cause_uriref not in current_path:
self.add_max_distance_from_target(cause_uriref, current_path)
# def get_nodes_in_target_tree(self, target_uriref):
#TODO: filter self.nodes to find those where max_distance_from_target_by_target has target_uriref as a key
@property
def shortest_path_nodes(self):
"""Return the set of nodes that are on the shortest path(s)."""
# The strategy is to start with all the nodes and remove nodes where none of the children are further away from the root cause, or where there are no children.
# Each pass through the nodes we look at each node's causes, therefore, if a node is not the cause of another then it gets removed (so dead branches are pruned node by node).
# We define "good nodes" to be cause nodes which have at least one child further away than (or same distance as) the node, remove the others and iterate until no change.
# As this is using the min_primary_threat_distance we need to accept distance equality as good.
short_path_nodes = set(self.nodes)
while True:
good_nodes = set([self[target_ms_uri] for target_ms_uri in self.target_uris]) # put these in because they are not anything's cause
for node in short_path_nodes:
for cause_node in [self[cause_uri] for cause_uri in node.direct_cause_uris]:
# Don't discard causes of threats (or, equivalently, ANDs) as they are all needed regardless of route taken to get to them
if node.is_threat or node.is_and:
good_nodes.add(cause_node)
else:
d_cause = cause_node.min_primary_threat_distance
d_node = node.min_primary_threat_distance
if d_cause is None or d_node is None:
logging.error('node {} [{}]\n cause {} [{}]'.format(node.uri.split('#')[1], d_node, cause_node.uri.split('#')[1], d_cause))
elif d_cause <= d_node:
good_nodes.add(cause_node)
if len(good_nodes & short_path_nodes) < len(short_path_nodes):
short_path_nodes = good_nodes & short_path_nodes
else:
break
return short_path_nodes
@property
def attack_graph_mitigation_csg(self):
return LogicalExpression([self[uri].attack_tree_mitigation_csg for uri in self.target_uris], all_required=True)
@property
def attack_graph_mitigation_cs(self):
return LogicalExpression([self[uri].attack_tree_mitigation_cs for uri in self.target_uris], all_required=True)
@property
def threat_graph_mitigation_csg(self):
return LogicalExpression([self[uri].threat_tree_mitigation_csg for uri in self.target_uris], all_required=True)
@property
def threat_graph_mitigation_cs(self):
return LogicalExpression([self[uri].threat_tree_mitigation_cs for uri in self.target_uris], all_required=True)
def add_node_indices(self, i=0, node=None):
if node == None:
for root_uri in self.root_causes:
i = self.add_node_indices(i, self[root_uri])
else:
if not node.index:
node.index = i
logging.debug("{}|{}".format(i, node.comment))
i += 1
for child_uri in node.direct_effect_uris:
i = self.add_node_indices(i, self[child_uri])
return i