forked from OWASP/pytm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpytm.py
2097 lines (1765 loc) · 64.4 KB
/
pytm.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 argparse
import errno
import inspect
import json
import logging
import os
import random
import sys
import uuid
import html
import copy
from collections import Counter, defaultdict
from collections.abc import Iterable
from enum import Enum
from functools import lru_cache, singledispatch
from hashlib import sha224
from itertools import combinations
from shutil import rmtree
from textwrap import indent, wrap
from weakref import WeakKeyDictionary
from datetime import datetime
from .template_engine import SuperFormatter
""" Helper functions """
""" The base for this (descriptors instead of properties) has been
shamelessly lifted from
https://nbviewer.jupyter.org/urls/gist.github.com/ChrisBeaumont/5758381/raw/descriptor_writeup.ipynb
By Chris Beaumont
"""
def sev_to_color(sev):
# calculate the color depending on the severity
if sev == 5:
return 'firebrick3; fillcolor="#b2222222"; style=filled '
elif sev <= 4 and sev >= 2:
return 'gold; fillcolor="#ffd80022"; style=filled'
elif sev < 2 and sev >= 0:
return 'darkgreen; fillcolor="#00630022"; style=filled'
return "black"
class UIError(Exception):
def __init__(self, e, context):
self.error = e
self.context = context
logger = logging.getLogger(__name__)
class var(object):
"""A descriptor that allows setting a value only once"""
def __init__(self, default, required=False, doc="", onSet=None):
self.default = default
self.required = required
self.doc = doc
self.data = WeakKeyDictionary()
self.onSet = onSet
def __get__(self, instance, owner):
# when x.d is called we get here
# instance = x
# owner = type(x)
if instance is None:
return self
return self.data.get(instance, self.default)
def __set__(self, instance, value):
# called when x.d = val
# instance = x
# value = val
if instance in self.data:
raise ValueError(
"cannot overwrite {}.{} value with {}, already set to {}".format(
instance, self.__class__.__name__, value, self.data[instance]
)
)
self.data[instance] = value
if self.onSet is not None:
self.onSet(instance, value)
class varString(var):
def __set__(self, instance, value):
if not isinstance(value, str):
raise ValueError("expecting a String value, got a {}".format(type(value)))
super().__set__(instance, value)
class varStrings(var):
def __set__(self, instance, value):
if not isinstance(value, Iterable) or isinstance(value, str):
value = [value]
for i, e in enumerate(value):
if not isinstance(e, str):
raise ValueError(
f"expecting a list of str, item number {i} is a {type(e)}"
)
super().__set__(instance, set(value))
class varBoundary(var):
def __set__(self, instance, value):
if not isinstance(value, Boundary):
raise ValueError("expecting a Boundary value, got a {}".format(type(value)))
super().__set__(instance, value)
class varBool(var):
def __set__(self, instance, value):
if not isinstance(value, bool):
raise ValueError("expecting a boolean value, got a {}".format(type(value)))
super().__set__(instance, value)
class varInt(var):
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError("expecting an integer value, got a {}".format(type(value)))
super().__set__(instance, value)
class varInts(var):
def __set__(self, instance, value):
if not isinstance(value, Iterable):
value = [value]
for i, e in enumerate(value):
if not isinstance(e, int):
raise ValueError(
f"expecting a list of int, item number {i} is a {type(e)}"
)
super().__set__(instance, set(value))
class varElement(var):
def __set__(self, instance, value):
if not isinstance(value, Element):
raise ValueError(
"expecting an Element (or inherited) "
"value, got a {}".format(type(value))
)
super().__set__(instance, value)
class varElements(var):
def __set__(self, instance, value):
for i, e in enumerate(value):
if not isinstance(e, Element):
raise ValueError(
"expecting a list of Elements, item number {} is a {}".format(
i, type(e)
)
)
super().__set__(instance, list(value))
class varFindings(var):
def __set__(self, instance, value):
for i, e in enumerate(value):
if not isinstance(e, Finding):
raise ValueError(
"expecting a list of Findings, item number {} is a {}".format(
i, type(e)
)
)
super().__set__(instance, list(value))
class varAction(var):
def __set__(self, instance, value):
if not isinstance(value, Action):
raise ValueError("expecting an Action, got a {}".format(type(value)))
super().__set__(instance, value)
class varClassification(var):
def __set__(self, instance, value):
if not isinstance(value, Classification):
raise ValueError("expecting a Classification, got a {}".format(type(value)))
super().__set__(instance, value)
class varLifetime(var):
def __set__(self, instance, value):
if not isinstance(value, Lifetime):
raise ValueError("expecting a Lifetime, got a {}".format(type(value)))
super().__set__(instance, value)
class varDatastoreType(var):
def __set__(self, instance, value):
if not isinstance(value, DatastoreType):
raise ValueError("expecting a DatastoreType, got a {}".format(type(value)))
super().__set__(instance, value)
class varTLSVersion(var):
def __set__(self, instance, value):
if not isinstance(value, TLSVersion):
raise ValueError("expecting a TLSVersion, got a {}".format(type(value)))
super().__set__(instance, value)
class varData(var):
def __set__(self, instance, value):
if isinstance(value, str):
value = [
Data(
name="undefined",
description=value,
classification=Classification.UNKNOWN,
)
]
sys.stderr.write(
"FIXME: a dataflow is using a string as the Data attribute. This has been deprecated and Data objects should be created instead.\n"
)
if not isinstance(value, Iterable):
value = [value]
for i, e in enumerate(value):
if not isinstance(e, Data):
raise ValueError(
"expecting a list of pytm.Data, item number {} is a {}".format(
i, type(e)
)
)
super().__set__(instance, DataSet(value))
class DataSet(set):
def __contains__(self, item):
if isinstance(item, str):
return item in [d.name for d in self]
if isinstance(item, Data):
return super().__contains__(item)
return NotImplemented
def __eq__(self, other):
if isinstance(other, set):
return super().__eq__(other)
if isinstance(other, str):
return other in self
return NotImplemented
def __ne__(self, other):
if isinstance(other, set):
return super().__ne__(other)
if isinstance(other, str):
return other not in self
return NotImplemented
def __str__(self):
return ", ".join(sorted(set(d.name for d in self)))
class varControls(var):
def __set__(self, instance, value):
if not isinstance(value, Controls):
raise ValueError(
"expecting an Controls " "value, got a {}".format(type(value))
)
super().__set__(instance, value)
class Action(Enum):
"""Action taken when validating a threat model."""
NO_ACTION = "NO_ACTION"
RESTRICT = "RESTRICT"
IGNORE = "IGNORE"
class OrderedEnum(Enum):
def __ge__(self, other):
if self.__class__ is other.__class__:
return self.value >= other.value
return NotImplemented
def __gt__(self, other):
if self.__class__ is other.__class__:
return self.value > other.value
return NotImplemented
def __le__(self, other):
if self.__class__ is other.__class__:
return self.value <= other.value
return NotImplemented
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented
class Classification(OrderedEnum):
UNKNOWN = 0
PUBLIC = 1
RESTRICTED = 2
SENSITIVE = 3
SECRET = 4
TOP_SECRET = 5
class Lifetime(Enum):
# not applicable
NONE = "NONE"
# unknown lifetime
UNKNOWN = "UNKNOWN"
# relatively short expiration date (time to live)
SHORT = "SHORT_LIVED"
# long or no expiration date
LONG = "LONG_LIVED"
# no expiration date but revoked/invalidated automatically in some conditions
AUTO = "AUTO_REVOKABLE"
# no expiration date but can be invalidated manually
MANUAL = "MANUALLY_REVOKABLE"
# cannot be invalidated at all
HARDCODED = "HARDCODED"
def label(self):
return self.value.lower().replace("_", " ")
class DatastoreType(Enum):
UNKNOWN = "UNKNOWN"
FILE_SYSTEM = "FILE_SYSTEM"
SQL = "SQL"
LDAP = "LDAP"
AWS_S3 = "AWS_S3"
def label(self):
return self.value.lower().replace("_", " ")
class TLSVersion(OrderedEnum):
NONE = 0
SSLv1 = 1
SSLv2 = 2
SSLv3 = 3
TLSv10 = 4
TLSv11 = 5
TLSv12 = 6
TLSv13 = 7
def _sort(flows, addOrder=False):
ordered = sorted(flows, key=lambda flow: flow.order)
if not addOrder:
return ordered
for i, flow in enumerate(ordered):
if flow.order != -1:
break
ordered[i].order = i + 1
return ordered
def _sort_elem(elements):
if len(elements) == 0:
return elements
orders = {}
for e in elements:
try:
order = e.order
except AttributeError:
continue
if e.source not in orders or orders[e.source] > order:
orders[e.source] = order
m = max(orders.values()) + 1
return sorted(
elements,
key=lambda e: (
orders.get(e, m),
e.__class__.__name__,
getattr(e, "order", 0),
str(e),
),
)
def _match_responses(flows):
"""Ensure that responses are pointing to requests"""
index = defaultdict(list)
for e in flows:
key = (e.source, e.sink)
index[key].append(e)
for e in flows:
if e.responseTo is not None:
if not e.isResponse:
e.isResponse = True
if e.responseTo.response is None:
e.responseTo.response = e
if e.response is not None:
if not e.response.isResponse:
e.response.isResponse = True
if e.response.responseTo is None:
e.response.responseTo = e
for e in flows:
if not e.isResponse or e.responseTo is not None:
continue
key = (e.sink, e.source)
if len(index[key]) == 1:
e.responseTo = index[key][0]
index[key][0].response = e
return flows
def _apply_defaults(flows, data):
inputs = defaultdict(list)
outputs = defaultdict(list)
carriers = defaultdict(set)
processors = defaultdict(set)
for d in data:
for e in d.carriedBy:
try:
setattr(e, "data", d)
except ValueError:
e.data.add(d)
for e in flows:
if e.source.data:
try:
setattr(e, "data", e.source.data.copy())
except ValueError:
e.data.update(e.source.data)
for d in e.data:
carriers[d].add(e)
processors[d].add(e.source)
processors[d].add(e.sink)
e._safeset("levels", e.source.levels & e.sink.levels)
try:
e.overrides = e.sink.overrides
e.overrides.extend(
f
for f in e.source.overrides
if f.threat_id not in (f.threat_id for f in e.overrides)
)
except ValueError:
pass
if e.isResponse:
e._safeset("protocol", e.source.protocol)
e._safeset("srcPort", e.source.port)
e.controls._safeset("isEncrypted", e.source.controls.isEncrypted)
continue
e._safeset("protocol", e.sink.protocol)
e._safeset("dstPort", e.sink.port)
if hasattr(e.sink.controls, "isEncrypted"):
e.controls._safeset("isEncrypted", e.sink.controls.isEncrypted)
e.controls._safeset(
"authenticatesDestination", e.source.controls.authenticatesDestination
)
e.controls._safeset(
"checksDestinationRevocation", e.source.controls.checksDestinationRevocation
)
for d in e.data:
if d.isStored:
if hasattr(e.sink.controls, "isEncryptedAtRest"):
for d in e.data:
d._safeset(
"isDestEncryptedAtRest", e.sink.controls.isEncryptedAtRest
)
if hasattr(e.source, "isEncryptedAtRest"):
for d in e.data:
d._safeset(
"isSourceEncryptedAtRest",
e.source.controls.isEncryptedAtRest,
)
if d.credentialsLife != Lifetime.NONE and not d.isCredentials:
d._safeset("isCredentials", True)
if d.isCredentials and d.credentialsLife == Lifetime.NONE:
d._safeset("credentialsLife", Lifetime.UNKNOWN)
outputs[e.source].append(e)
inputs[e.sink].append(e)
for e, flows in inputs.items():
try:
e.inputs = flows
except (AttributeError, ValueError):
pass
for e, flows in outputs.items():
try:
e.outputs = flows
except (AttributeError, ValueError):
pass
for d, flows in carriers.items():
flows = sorted(flows, key=lambda f: f.name)
try:
setattr(d, "carriedBy", list(flows))
except ValueError:
for e in flows:
if e not in d.carriedBy:
d.carriedBy.append(e)
for d, elements in processors.items():
elements = sorted(elements, key=lambda e: e.name)
try:
setattr(d, "processedBy", elements)
except ValueError:
for e in elements:
if e not in d.processedBy:
d.processedBy.append(e)
def _describe_classes(classes):
for name in classes:
klass = getattr(sys.modules[__name__], name, None)
if klass is None:
logger.error("No such class to describe: %s\n", name)
sys.exit(1)
print("{} class attributes:".format(name))
attrs = []
for i in dir(klass):
if i.startswith("_") or callable(getattr(klass, i)):
continue
attrs.append(i)
longest = len(max(attrs, key=len)) + 2
for i in attrs:
attr = getattr(klass, i, {})
docs = []
if isinstance(attr, var):
if attr.doc:
docs.extend(attr.doc.split("\n"))
if attr.required:
docs.append("required")
if attr.default or isinstance(attr.default, bool):
docs.append("default: {}".format(attr.default))
lpadding = f'\n{" ":<{longest+2}}'
print(f" {i:<{longest}}{lpadding.join(docs)}")
print()
def _list_elements():
"""List all elements which can be used in a threat model with the corresponding description"""
def all_subclasses(cls):
"""Get all sub classes of a class"""
subclasses = set(cls.__subclasses__())
return subclasses.union((s for c in subclasses for s in all_subclasses(c)))
def print_components(cls_list):
elements = sorted(cls_list, key=lambda c: c.__name__)
max_len = max((len(e.__name__) for e in elements))
for sc in elements:
doc = sc.__doc__ if sc.__doc__ is not None else ""
print(f"{sc.__name__:<{max_len}} -- {doc}")
# print all elements
print("Elements:")
print_components(all_subclasses(Element))
# Print Attributes
print("\nAtributes:")
print_components(all_subclasses(OrderedEnum) | {Data, Action, Lifetime})
def _get_elements_and_boundaries(flows):
"""filter out elements and boundaries not used in this TM"""
elements = set()
boundaries = set()
for e in flows:
elements.add(e)
elements.add(e.source)
elements.add(e.sink)
if e.source.inBoundary is not None:
elements.add(e.source.inBoundary)
boundaries.add(e.source.inBoundary)
for b in e.source.inBoundary.parents():
elements.add(b)
boundaries.add(b)
if e.sink.inBoundary is not None:
elements.add(e.sink.inBoundary)
boundaries.add(e.sink.inBoundary)
for b in e.sink.inBoundary.parents():
elements.add(b)
boundaries.add(b)
return (list(elements), list(boundaries))
""" End of help functions """
class Threat:
"""Represents a possible threat"""
id = varString("", required=True)
description = varString("")
condition = varString(
"",
doc="""a Python expression that should evaluate
to a boolean True or False""",
)
details = varString("")
likelihood = varString("")
severity = varString("")
mitigations = varString("")
prerequisites = varString("")
example = varString("")
references = varString("")
target = ()
def __init__(self, **kwargs):
self.id = kwargs["SID"]
self.description = kwargs.get("description", "")
self.likelihood = kwargs.get("Likelihood Of Attack", "")
self.condition = kwargs.get("condition", "True")
target = kwargs.get("target", "Element")
if not isinstance(target, str) and isinstance(target, Iterable):
target = tuple(target)
else:
target = (target,)
self.target = tuple(getattr(sys.modules[__name__], x) for x in target)
self.details = kwargs.get("details", "")
self.severity = kwargs.get("severity", "")
self.mitigations = kwargs.get("mitigations", "")
self.prerequisites = kwargs.get("prerequisites", "")
self.example = kwargs.get("example", "")
self.references = kwargs.get("references", "")
def _safeset(self, attr, value):
try:
setattr(self, attr, value)
except ValueError:
pass
def __repr__(self):
return "<{0}.{1}({2}) at {3}>".format(
self.__module__, type(self).__name__, self.id, hex(id(self))
)
def __str__(self):
return "{0}({1})".format(type(self).__name__, self.id)
def apply(self, target):
if not isinstance(target, self.target):
return None
return eval(self.condition)
class Finding:
"""Represents a Finding - the element in question
and a description of the finding"""
element = varElement(None, required=True, doc="Element this finding applies to")
target = varString("", doc="Name of the element this finding applies to")
description = varString("", required=True, doc="Threat description")
details = varString("", required=True, doc="Threat details")
severity = varString("", required=True, doc="Threat severity")
mitigations = varString("", required=True, doc="Threat mitigations")
example = varString("", required=True, doc="Threat example")
id = varString("", required=True, doc="Finding ID")
threat_id = varString("", required=True, doc="Threat ID")
references = varString("", required=True, doc="Threat references")
condition = varString("", required=True, doc="Threat condition")
response = varString(
"",
required=False,
doc="""Describes how this threat matching this particular asset or dataflow is being handled.
Can be one of:
* mitigated - there were changes made in the modeled system to reduce the probability of this threat ocurring or the impact when it does,
* transferred - users of the system are required to mitigate this threat,
* avoided - this asset or dataflow is removed from the system,
* accepted - no action is taken as the probability and/or impact is very low
""",
)
cvss = varString("", required=False, doc="The CVSS score and/or vector")
def __init__(
self,
*args,
**kwargs,
):
if args:
element = args[0]
else:
element = kwargs.pop("element", Element("invalid"))
self.target = element.name
self.element = element
attrs = [
"description",
"details",
"severity",
"mitigations",
"example",
"references",
"condition",
]
threat = kwargs.pop("threat", None)
if threat:
kwargs["threat_id"] = getattr(threat, "id")
for a in attrs:
# copy threat attrs into kwargs to allow to override them in next step
kwargs[a] = getattr(threat, a)
threat_id = kwargs.get("threat_id", None)
for f in element.overrides:
if f.threat_id != threat_id:
continue
for i in dir(f.__class__):
attr = getattr(f.__class__, i)
if (
i in ("element", "target")
or i.startswith("_")
or callable(attr)
or not isinstance(attr, var)
):
continue
if f in attr.data:
kwargs[i] = attr.data[f]
break
for k, v in kwargs.items():
setattr(self, k, v)
def _safeset(self, attr, value):
try:
setattr(self, attr, value)
except ValueError:
pass
def __repr__(self):
return "<{0}.{1}({2}) at {3}>".format(
self.__module__, type(self).__name__, self.id, hex(id(self))
)
def __str__(self):
return f"'{self.target}': {self.description}\n{self.details}\n{self.severity}"
class TM:
"""Describes the threat model administratively,
and holds all details during a run"""
_flows = []
_elements = []
_actors = []
_assets = []
_threats = []
_boundaries = []
_data = []
_threatsExcluded = []
_sf = None
_duplicate_ignored_attrs = (
"name",
"note",
"order",
"response",
"responseTo",
"controls",
)
name = varString("", required=True, doc="Model name")
description = varString("", required=True, doc="Model description")
threatsFile = varString(
os.path.dirname(__file__) + "/threatlib/threats.json",
onSet=lambda i, v: i._init_threats(),
doc="JSON file with custom threats",
)
isOrdered = varBool(False, doc="Automatically order all Dataflows")
mergeResponses = varBool(False, doc="Merge response edges in DFDs")
ignoreUnused = varBool(False, doc="Ignore elements not used in any Dataflow")
findings = varFindings([], doc="threats found for elements of this model")
onDuplicates = varAction(
Action.NO_ACTION,
doc="""How to handle duplicate Dataflow
with same properties, except name and notes""",
)
assumptions = varStrings(
[],
required=False,
doc="A list of assumptions about the design/model.",
)
_colormap = False
def __init__(self, name, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
self.name = name
self._sf = SuperFormatter()
self._add_threats()
# make sure generated diagrams do not change, makes sense if they're commited
random.seed(0)
@classmethod
def reset(cls):
cls._flows = []
cls._elements = []
cls._actors = []
cls._assets = []
cls._threats = []
cls._boundaries = []
cls._data = []
cls._threatsExcluded = []
def _init_threats(self):
TM._threats = []
self._add_threats()
def _add_threats(self):
try:
with open(self.threatsFile, "r", encoding="utf8") as threat_file:
threats_json = json.load(threat_file)
except (FileNotFoundError, PermissionError, IsADirectoryError) as e:
raise UIError(
e, f"while trying to open the the threat file ({self.threatsFile})."
)
for i in threats_json:
TM._threats.append(Threat(**i))
def resolve(self):
finding_count = 0
findings = []
elements = defaultdict(list)
for e in TM._elements:
if not e.inScope:
continue
override_ids = set(f.threat_id for f in e.overrides)
# if element is a dataflow filter out overrides from source and sink
# because they will be always applied there anyway
try:
override_ids -= set(
f.threat_id for f in e.source.overrides + e.sink.overrides
)
except AttributeError:
pass
for t in TM._threats:
if not t.apply(e) and t.id not in override_ids:
continue
if t.id in TM._threatsExcluded:
continue
finding_count += 1
f = Finding(e, id=str(finding_count), threat=t)
findings.append(f)
elements[e].append(f)
e._set_severity(f.severity)
self.findings = findings
for e, findings in elements.items():
e.findings = findings
def check(self):
if self.description is None:
raise ValueError(
"""Every threat model should have at least
a brief description of the system being modeled."""
)
TM._flows = _match_responses(_sort(TM._flows, self.isOrdered))
self._check_duplicates(TM._flows)
_apply_defaults(TM._flows, TM._data)
for e in TM._elements:
top = Counter(f.threat_id for f in e.overrides).most_common(1)
if not top:
continue
threat_id, count = top[0]
if count != 1:
raise ValueError(
f"Finding {threat_id} have more than one override in {e}"
)
if self.ignoreUnused:
TM._elements, TM._boundaries = _get_elements_and_boundaries(TM._flows)
result = True
for e in TM._elements:
if not e.check():
result = False
if self.ignoreUnused:
# cannot rely on user defined order if assets are re-used in multiple models
TM._elements = _sort_elem(TM._elements)
return result
def _check_duplicates(self, flows):
if self.onDuplicates == Action.NO_ACTION:
return
index = defaultdict(list)
for e in flows:
key = (e.source, e.sink)
index[key].append(e)
for flows in index.values():
for left, right in combinations(flows, 2):
left_attrs = left._attr_values()
right_attrs = right._attr_values()
for a in self._duplicate_ignored_attrs:
del left_attrs[a], right_attrs[a]
if left_attrs != right_attrs:
continue
if self.onDuplicates == Action.IGNORE:
right._is_drawn = True
continue
left_controls_attrs = left.controls._attr_values()
right_controls_attrs = right.controls._attr_values()
# for a in self._duplicate_ignored_attrs:
# del left_controls_attrs[a], right_controls_attrs[a]
if left_controls_attrs != right_controls_attrs:
continue
if self.onDuplicates == Action.IGNORE:
right._is_drawn = True
continue
raise ValueError(
"Duplicate Dataflow found between {} and {}: "
"{} is same as {}".format(
left.source,
left.sink,
left,
right,
)
)
def _dfd_template(self):
return """digraph tm {{
graph [
fontname = Arial;
fontsize = 14;
]
node [
fontname = Arial;
fontsize = 14;
rankdir = lr;
]
edge [
shape = none;
arrowtail = onormal;
fontname = Arial;
fontsize = 12;
]
labelloc = "t";
fontsize = 20;
nodesep = 1;
{edges}
}}"""
def dfd(self, **kwargs):
if "levels" in kwargs:
levels = kwargs["levels"]
if not isinstance(kwargs["levels"], Iterable):
kwargs["levels"] = [levels]
kwargs["levels"] = set(levels)
edges = []
# since boundaries can be nested sort them by level and start from top
parents = set(b.inBoundary for b in TM._boundaries if b.inBoundary)
# TODO boundaries should not be drawn if they don't contain elements matching requested levels
# or contain only empty boundaries
boundary_levels = defaultdict(set)
max_level = 0
for b in TM._boundaries:
if b in parents:
continue
boundary_levels[0].add(b)
for i, p in enumerate(b.parents()):
i = i + 1
boundary_levels[i].add(p)
if i > max_level:
max_level = i
for i in range(max_level, -1, -1):
for b in sorted(boundary_levels[i], key=lambda b: b.name):
edges.append(b.dfd(**kwargs))
if self.mergeResponses:
for e in TM._flows:
if e.response is not None:
e.response._is_drawn = True
kwargs["mergeResponses"] = self.mergeResponses
for e in TM._elements:
if not e._is_drawn and not isinstance(e, Boundary) and e.inBoundary is None:
edges.append(e.dfd(**kwargs))
return self._dfd_template().format(
edges=indent("\n".join(filter(len, edges)), " ")