Package pytm

Sub-modules

pytm.flows
pytm.report_util

Functions

def load(fp)
Expand source code
def load(fp):
    """Load a TM object from an open file containing JSON."""
    result = json.load(fp, object_hook=decode)
    if not isinstance(result, TM):
        raise ValueError("Failed to decode JSON input as TM")
    return result

Load a TM object from an open file containing JSON.

def loads(s)
Expand source code
def loads(s):
    """Load a TM object from a JSON string *s*."""
    result = json.loads(s, object_hook=decode)
    if not isinstance(result, TM):
        raise ValueError("Failed to decode JSON input as TM")
    return result

Load a TM object from a JSON string s.

Classes

class Action (*args, **kwds)
Expand source code
class Action(Enum):
    """Action taken when validating a threat model."""

    NO_ACTION = "NO_ACTION"
    RESTRICT = "RESTRICT"
    IGNORE = "IGNORE"

Action taken when validating a threat model.

Ancestors

  • enum.Enum

Class variables

var IGNORE

The type of the None singleton.

var NO_ACTION

The type of the None singleton.

var RESTRICT

The type of the None singleton.

class Actor (name, **kwargs)
Expand source code
class Actor(Element):
    """An entity usually initiating actions"""

    port = varInt(-1, doc="Default TCP port for outgoing data flows")
    protocol = varString("", doc="Default network protocol for outgoing data flows")
    data = varData([], doc="pytm.Data object(s) in outgoing data flows")
    inputs = varElements([], doc="incoming Dataflows")
    outputs = varElements([], doc="outgoing Dataflows")
    isAdmin = varBool(False)

    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)
        TM._actors.append(self)

An entity usually initiating actions

Ancestors

  • pytm.pytm.Element

Instance variables

var data
Expand source code
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)

pytm.Data object(s) in outgoing data flows

var inputs
Expand source code
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)

incoming Dataflows

var isAdmin
Expand source code
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)
var outputs
Expand source code
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)

outgoing Dataflows

var port
Expand source code
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)

Default TCP port for outgoing data flows

var protocol
Expand source code
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)

Default network protocol for outgoing data flows

class Assumption (name, **kwargs)
Expand source code
class Assumption:
    """
    Assumption used by an Element.
    Used to exclude threats on a per-element basis.
    """
    name = varString("", required=True)
    exclude = varStrings([], doc="A list of threat SIDs to exclude for this assumption. For example: INP01")
    description = varString("", doc="An additional description of the assumption")

    def __init__(self, name, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
        self.name = name

    def __str__(self):
        return self.name

Assumption used by an Element. Used to exclude threats on a per-element basis.

Instance variables

var description
Expand source code
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)

An additional description of the assumption

var exclude
Expand source code
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)

A list of threat SIDs to exclude for this assumption. For example: INP01

var name
Expand source code
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)
class Boundary (name, **kwargs)
Expand source code
class Boundary(Element):
    """Trust boundary groups elements and data with the same trust level."""

    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)
        if name not in TM._boundaries:
            TM._boundaries.append(self)

    def _dfd_template(self):
        return """subgraph cluster_{uniq_name} {{
    graph [
        fontsize = 10;
        fontcolor = black;
        style = dashed;
        color = {color};
        label = <<i>{label}</i>>;
    ]

{edges}
}}
"""

    def dfd(self, **kwargs):
        if self._is_drawn:
            return ""

        self._is_drawn = True

        edges = []
        for e in TM._elements:
            if e.inBoundary != self or e._is_drawn:
                continue
            # The content to draw can include Boundary objects
            edges.append(e.dfd(**kwargs))

        return self._dfd_template().format(
            uniq_name=self._uniq_name(),
            label=self._label(),
            color=self._color(**kwargs),
            edges=indent("\n".join(edges), "    "),
        )

    def _color(self, **kwargs):
        if kwargs.get("colormap", False):
            return "black"
        else:
            return "firebrick2"

    def parents(self):
        result = []
        parent = self.inBoundary
        while parent is not None:
            result.append(parent)
            parent = parent.inBoundary
        return result

Trust boundary groups elements and data with the same trust level.

Ancestors

  • pytm.pytm.Element

Methods

def parents(self)
Expand source code
def parents(self):
    result = []
    parent = self.inBoundary
    while parent is not None:
        result.append(parent)
        parent = parent.inBoundary
    return result
class Classification (*args, **kwds)
Expand source code
class Classification(OrderedEnum):
    UNKNOWN = 0
    PUBLIC = 1
    RESTRICTED = 2
    SENSITIVE = 3
    SECRET = 4
    TOP_SECRET = 5

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

Color.RED

  • value lookup:

Color(1)

  • name lookup:

Color['RED']

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

Ancestors

  • pytm.pytm.OrderedEnum
  • enum.Enum

Class variables

var PUBLIC

The type of the None singleton.

var RESTRICTED

The type of the None singleton.

var SECRET

The type of the None singleton.

var SENSITIVE

The type of the None singleton.

var TOP_SECRET

The type of the None singleton.

var UNKNOWN

The type of the None singleton.

class Data (name, **kwargs)
Expand source code
class Data:
    """Represents a single piece of data that traverses the system"""

    name = varString("", required=True)
    description = varString("")
    format = varString("")
    classification = varClassification(
        Classification.UNKNOWN,
        required=True,
        doc="Level of classification for this piece of data",
    )
    isPII = varBool(
        False,
        doc="""Does the data contain personally identifyable information.
Should always be encrypted both in transmission and at rest.""",
    )
    isCredentials = varBool(
        False,
        doc="""Does the data contain authentication information,
like passwords or cryptographic keys, with or without expiration date.
Should always be encrypted in transmission. If stored, they should be hashed
using a cryptographic hash function.""",
    )
    credentialsLife = varLifetime(
        Lifetime.NONE,
        doc="""Credentials lifetime, describing if and how
credentials can be revoked. One of:
* NONE - not applicable
* UNKNOWN - unknown lifetime
* SHORT - relatively short expiration date, with an allowed maximum
* LONG - long or no expiration date
* AUTO - no expiration date but can be revoked/invalidated automatically
  in some conditions
* MANUAL - no expiration date but can be revoked/invalidated manually
* HARDCODED - cannot be invalidated at all""",
    )
    isStored = varBool(
        False,
        doc="""Is the data going to be stored by the target or only processed.
If only derivative data is stored (a hash) it can be set to False.""",
    )
    isDestEncryptedAtRest = varBool(False, doc="Is data encrypted at rest at dest")
    isSourceEncryptedAtRest = varBool(False, doc="Is data encrypted at rest at source")
    carriedBy = varElements([], doc="Dataflows that carries this piece of data")
    processedBy = varElements([], doc="Elements that store/process this piece of data")

    def __init__(self, name, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
        self.name = name
        TM._data.append(self)

    def __repr__(self):
        return "<{0}.{1}({2}) at {3}>".format(
            self.__module__, type(self).__name__, self.name, hex(id(self))
        )

    def __str__(self):
        return "{0}({1})".format(type(self).__name__, self.name)

    def _safeset(self, attr, value):
        try:
            setattr(self, attr, value)
        except ValueError:
            pass

Represents a single piece of data that traverses the system

Instance variables

var carriedBy
Expand source code
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)

Dataflows that carries this piece of data

var classification
Expand source code
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)

Level of classification for this piece of data

var credentialsLife
Expand source code
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)

Credentials lifetime, describing if and how credentials can be revoked. One of: * NONE - not applicable * UNKNOWN - unknown lifetime * SHORT - relatively short expiration date, with an allowed maximum * LONG - long or no expiration date * AUTO - no expiration date but can be revoked/invalidated automatically in some conditions * MANUAL - no expiration date but can be revoked/invalidated manually * HARDCODED - cannot be invalidated at all

var description
Expand source code
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)
var format
Expand source code
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)
var isCredentials
Expand source code
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)

Does the data contain authentication information, like passwords or cryptographic keys, with or without expiration date. Should always be encrypted in transmission. If stored, they should be hashed using a cryptographic hash function.

var isDestEncryptedAtRest
Expand source code
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)

Is data encrypted at rest at dest

var isPII
Expand source code
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)

Does the data contain personally identifyable information. Should always be encrypted both in transmission and at rest.

var isSourceEncryptedAtRest
Expand source code
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)

Is data encrypted at rest at source

var isStored
Expand source code
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)

Is the data going to be stored by the target or only processed. If only derivative data is stored (a hash) it can be set to False.

var name
Expand source code
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)
var processedBy
Expand source code
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)

Elements that store/process this piece of data

class Dataflow (source, sink, name, **kwargs)
Expand source code
class Dataflow(Element):
    """A data flow from a source to a sink"""

    source = varElement(None, required=True)
    sink = varElement(None, required=True)
    isResponse = varBool(False, doc="Is a response to another data flow")
    response = varElement(None, doc="Another data flow that is a response to this one")
    responseTo = varElement(None, doc="Is a response to this data flow")
    srcPort = varInt(-1, doc="Source TCP port")
    dstPort = varInt(-1, doc="Destination TCP port")
    tlsVersion = varTLSVersion(
        TLSVersion.NONE,
        required=True,
        doc="TLS version used.",
    )
    protocol = varString("", doc="Protocol used in this data flow")
    data = varData([], doc="pytm.Data object(s) in incoming data flows")
    order = varInt(-1, doc="Number of this data flow in the threat model")
    implementsCommunicationProtocol = varBool(False)
    note = varString("")
    usesVPN = varBool(False)
    usesSessionTokens = varBool(False)
    severity = 0

    def __init__(self, source, sink, name, **kwargs):
        self.source = source
        self.sink = sink
        super().__init__(name, **kwargs)
        TM._flows.append(self)

    def display_name(self):
        if self.order == -1:
            return self.name
        return "({}) {}".format(self.order, self.name)

    def _dfd_template(self):
        return """{source} -> {sink} [
    color = {color};
    fontcolor = {color};
    dir = {direction};
    label = "{label}";
]
"""

    def dfd(self, mergeResponses=False, **kwargs):
        self._is_drawn = True

        levels = kwargs.get("levels", None)
        if (
            levels
            and not levels & self.levels
            and not (levels & self.source.levels and levels & self.sink.levels)
        ):
            return ""

        color = self._color()

        if kwargs.get("colormap", False):
            color = sev_to_color(self.severity)

        direction = "forward"
        label = self._label()
        if mergeResponses and self.response is not None:
            direction = "both"
            label += "\n" + self.response._label()

        return self._dfd_template().format(
            source=self.source._uniq_name(),
            sink=self.sink._uniq_name(),
            direction=direction,
            label=label,
            color=color,
        )

    def hasDataLeaks(self):
        return any(
            d.classification > self.source.maxClassification
            or d.classification > self.sink.maxClassification
            or d.classification > self.maxClassification
            for d in self.data
        )

A data flow from a source to a sink

Ancestors

  • pytm.pytm.Element

Class variables

var severity

The type of the None singleton.

Instance variables

var data
Expand source code
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)

pytm.Data object(s) in incoming data flows

var dstPort
Expand source code
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)

Destination TCP port

var implementsCommunicationProtocol
Expand source code
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)
var isResponse
Expand source code
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)

Is a response to another data flow

var note
Expand source code
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)
var order
Expand source code
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)

Number of this data flow in the threat model

var protocol
Expand source code
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)

Protocol used in this data flow

var response
Expand source code
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)

Another data flow that is a response to this one

var responseTo
Expand source code
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)

Is a response to this data flow

var sink
Expand source code
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)
var source
Expand source code
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)
var srcPort
Expand source code
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)

Source TCP port

var tlsVersion
Expand source code
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)

TLS version used.

var usesSessionTokens
Expand source code
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)
var usesVPN
Expand source code
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)

Methods

def display_name(self)
Expand source code
def display_name(self):
    if self.order == -1:
        return self.name
    return "({}) {}".format(self.order, self.name)
def hasDataLeaks(self)
Expand source code
def hasDataLeaks(self):
    return any(
        d.classification > self.source.maxClassification
        or d.classification > self.sink.maxClassification
        or d.classification > self.maxClassification
        for d in self.data
    )
class Datastore (name, **kwargs)
Expand source code
class Datastore(Asset):
    """An entity storing data"""

    onRDS = varBool(False)
    storesLogData = varBool(False)
    storesPII = varBool(
        False,
        doc="""Personally Identifiable Information
is any information relating to an identifiable person.""",
    )
    storesSensitiveData = varBool(False)
    isSQL = varBool(True)
    isShared = varBool(False)
    hasWriteAccess = varBool(False)
    type = varDatastoreType(
        DatastoreType.UNKNOWN,
        doc="""The  type of Datastore, values may be one of:
* UNKNOWN - unknown applicable
* FILE_SYSTEM - files on a file system
* SQL - A SQL Database
* LDAP - An LDAP Server
* AWS_S3 - An S3 Bucket within AWS""",
    )

    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)

    def _dfd_template(self):
        return """{uniq_name} [
    shape = {shape};
    fixedsize = shape;
    image = "{image}";
    imagescale = true;
    color = {color};
    fontcolor = black;
    xlabel = "{label}";
    label = "";
]
"""

    def _shape(self):
        return "none"

    def dfd(self, **kwargs):
        self._is_drawn = True

        levels = kwargs.get("levels", None)
        if levels and not levels & self.levels:
            return ""

        color = self._color()
        color_file = "black"

        if kwargs.get("colormap", False):
            color = sev_to_color(self.severity)
            color_file = color.split(";")[0]

        return self._dfd_template().format(
            uniq_name=self._uniq_name(),
            label=self._label(),
            color=color,
            shape=self._shape(),
            image=os.path.join(
                os.path.dirname(__file__), "images", f"datastore_{color_file}.png"
            ),
        )

An entity storing data

Ancestors

  • pytm.pytm.Asset
  • pytm.pytm.Element

Instance variables

var hasWriteAccess
Expand source code
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)
var isSQL
Expand source code
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)
var isShared
Expand source code
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)
var onRDS
Expand source code
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)
var storesLogData
Expand source code
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)
var storesPII
Expand source code
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)

Personally Identifiable Information is any information relating to an identifiable person.

var storesSensitiveData
Expand source code
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)
var type
Expand source code
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)

The type of Datastore, values may be one of: * UNKNOWN - unknown applicable * FILE_SYSTEM - files on a file system * SQL - A SQL Database * LDAP - An LDAP Server * AWS_S3 - An S3 Bucket within AWS

class DatastoreType (*args, **kwds)
Expand source code
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("_", " ")

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

Color.RED

  • value lookup:

Color(1)

  • name lookup:

Color['RED']

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

Ancestors

  • enum.Enum

Class variables

var AWS_S3

The type of the None singleton.

var FILE_SYSTEM

The type of the None singleton.

var LDAP

The type of the None singleton.

var SQL

The type of the None singleton.

var UNKNOWN

The type of the None singleton.

Methods

def label(self)
Expand source code
def label(self):
    return self.value.lower().replace("_", " ")
class Element (name, **kwargs)
Expand source code
class Element:
    """A generic element"""

    name = varString("", required=True)
    description = varString("")
    inBoundary = varBoundary(None, doc="Trust boundary this element exists in")
    inScope = varBool(True, doc="Is the element in scope of the threat model")
    maxClassification = varClassification(
        Classification.UNKNOWN,
        required=False,
        doc="Maximum data classification this element can handle.",
    )
    minTLSVersion = varTLSVersion(
        TLSVersion.NONE,
        required=False,
        doc="""Minimum TLS version required.""",
    )
    findings = varFindings([], doc="Threats that apply to this element")
    overrides = varFindings(
        [],
        doc="""Overrides to findings, allowing to set
a custom response, CVSS score or override other attributes.""",
    )
    assumptions = varAssumptions(
        [],
        doc="Assumptions about the element. These optionally allow to exclude threats with the given SIDs.",
    )
    levels = varInts({0}, doc="List of levels (0, 1, 2, ...) to be drawn in the model.")
    sourceFiles = varStrings(
        [],
        required=False,
        doc="Location of the source code that describes this element relative to the directory of the model script.",
    )
    controls = varControls(None)
    severity = 0

    def __init__(self, name, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
        self.name = name
        self.controls = Controls()
        self.uuid = uuid.UUID(int=random.getrandbits(128))
        self._is_drawn = False
        TM._elements.append(self)

    def __repr__(self):
        return "<{0}.{1}({2}) at {3}>".format(
            self.__module__, type(self).__name__, self.name, hex(id(self))
        )

    def __str__(self):
        return "{0}({1})".format(type(self).__name__, self.name)

    def _uniq_name(self):
        """transform name and uuid into a unique string"""
        h = sha224(str(self.uuid).encode("utf-8")).hexdigest()
        name = "".join(x for x in self.name if x.isalpha())
        return "{0}_{1}_{2}".format(type(self).__name__.lower(), name, h[:10])

    def check(self):
        return True

    def _dfd_template(self):
        return """{uniq_name} [
    shape = {shape};
    color = {color};
    fontcolor = black;
    label = "{label}";
    margin = 0.02;
]
"""

    def dfd(self, **kwargs):
        self._is_drawn = True

        levels = kwargs.get("levels", None)
        if levels and not levels & self.levels:
            return ""

        color = self._color()
        if kwargs.get("colormap", False):
            color = sev_to_color(self.severity)

        return self._dfd_template().format(
            uniq_name=self._uniq_name(),
            label=self._label(),
            color=color,
            shape=self._shape(),
        )

    def _color(self):
        if self.inScope is True:
            return "black"
        else:
            return "grey69"

    def display_name(self):
        return self.name

    def _label(self):
        return "\\n".join(wrap(self.display_name(), 18))

    def _shape(self):
        return "square"

    def _safeset(self, attr, value):
        try:
            setattr(self, attr, value)
        except ValueError:
            pass

    def oneOf(self, *elements):
        """Is self one of a list of Elements"""
        for element in elements:
            if inspect.isclass(element):
                if isinstance(self, element):
                    return True
            elif self is element:
                return True
        return False

    def crosses(self, *boundaries):
        """Does self (dataflow) cross any of the list of boundaries"""
        if self.source.inBoundary is self.sink.inBoundary:
            return False
        for boundary in boundaries:
            if inspect.isclass(boundary):
                if (
                    (
                        isinstance(self.source.inBoundary, boundary)
                        and not isinstance(self.sink.inBoundary, boundary)
                    )
                    or (
                        not isinstance(self.source.inBoundary, boundary)
                        and isinstance(self.sink.inBoundary, boundary)
                    )
                    or self.source.inBoundary is not self.sink.inBoundary
                ):
                    return True
            elif (self.source.inside(boundary) and not self.sink.inside(boundary)) or (
                not self.source.inside(boundary) and self.sink.inside(boundary)
            ):
                return True
        return False

    def enters(self, *boundaries):
        """does self (dataflow) enter into one of the list of boundaries"""
        return self.source.inBoundary is None and self.sink.inside(*boundaries)

    def exits(self, *boundaries):
        """does self (dataflow) exit one of the list of boundaries"""
        return self.source.inside(*boundaries) and self.sink.inBoundary is None

    def inside(self, *boundaries):
        """is self inside of one of the list of boundaries"""
        for boundary in boundaries:
            if inspect.isclass(boundary):
                if isinstance(self.inBoundary, boundary):
                    return True
            elif self.inBoundary is boundary:
                return True
        return False

    def _attr_values(self):
        klass = self.__class__
        result = {}
        for i in dir(klass):
            if i.startswith("_") or callable(getattr(klass, i)):
                continue
            attr = getattr(klass, i, {})
            if isinstance(attr, var):
                value = attr.data.get(self, attr.default)
            else:
                value = getattr(self, i)
            result[i] = value
        return result

    def checkTLSVersion(self, flows):
        return any(f.tlsVersion < self.minTLSVersion for f in flows)

    def _set_severity(self, sev):
        sevs = {
            "very high": 5,
            "high": 4,
            "medium": 3,
            "low": 2,
            "very low": 1,
            "info": 0,
        }

        if sev.lower() not in sevs.keys():
            return

        if self.severity < sevs[sev.lower()]:
            self.severity = sevs[sev.lower()]
        return

A generic element

Subclasses

  • pytm.pytm.Actor
  • pytm.pytm.Asset
  • pytm.pytm.Boundary
  • pytm.pytm.Dataflow

Class variables

var severity

The type of the None singleton.

Instance variables

var assumptions
Expand source code
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)

Assumptions about the element. These optionally allow to exclude threats with the given SIDs.

var controls
Expand source code
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)
var description
Expand source code
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)
var findings
Expand source code
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)

Threats that apply to this element

var inBoundary
Expand source code
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)

Trust boundary this element exists in

var inScope
Expand source code
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)

Is the element in scope of the threat model

var levels
Expand source code
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)

List of levels (0, 1, 2, …) to be drawn in the model.

var maxClassification
Expand source code
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)

Maximum data classification this element can handle.

var minTLSVersion
Expand source code
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)

Minimum TLS version required.

var name
Expand source code
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)
var overrides
Expand source code
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)

Overrides to findings, allowing to set a custom response, CVSS score or override other attributes.

var sourceFiles
Expand source code
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)

Location of the source code that describes this element relative to the directory of the model script.

Methods

def checkTLSVersion(self, flows)
Expand source code
def checkTLSVersion(self, flows):
    return any(f.tlsVersion < self.minTLSVersion for f in flows)
def crosses(self, *boundaries)
Expand source code
def crosses(self, *boundaries):
    """Does self (dataflow) cross any of the list of boundaries"""
    if self.source.inBoundary is self.sink.inBoundary:
        return False
    for boundary in boundaries:
        if inspect.isclass(boundary):
            if (
                (
                    isinstance(self.source.inBoundary, boundary)
                    and not isinstance(self.sink.inBoundary, boundary)
                )
                or (
                    not isinstance(self.source.inBoundary, boundary)
                    and isinstance(self.sink.inBoundary, boundary)
                )
                or self.source.inBoundary is not self.sink.inBoundary
            ):
                return True
        elif (self.source.inside(boundary) and not self.sink.inside(boundary)) or (
            not self.source.inside(boundary) and self.sink.inside(boundary)
        ):
            return True
    return False

Does self (dataflow) cross any of the list of boundaries

def display_name(self)
Expand source code
def display_name(self):
    return self.name
def enters(self, *boundaries)
Expand source code
def enters(self, *boundaries):
    """does self (dataflow) enter into one of the list of boundaries"""
    return self.source.inBoundary is None and self.sink.inside(*boundaries)

does self (dataflow) enter into one of the list of boundaries

def exits(self, *boundaries)
Expand source code
def exits(self, *boundaries):
    """does self (dataflow) exit one of the list of boundaries"""
    return self.source.inside(*boundaries) and self.sink.inBoundary is None

does self (dataflow) exit one of the list of boundaries

def inside(self, *boundaries)
Expand source code
def inside(self, *boundaries):
    """is self inside of one of the list of boundaries"""
    for boundary in boundaries:
        if inspect.isclass(boundary):
            if isinstance(self.inBoundary, boundary):
                return True
        elif self.inBoundary is boundary:
            return True
    return False

is self inside of one of the list of boundaries

def oneOf(self, *elements)
Expand source code
def oneOf(self, *elements):
    """Is self one of a list of Elements"""
    for element in elements:
        if inspect.isclass(element):
            if isinstance(self, element):
                return True
        elif self is element:
            return True
    return False

Is self one of a list of Elements

class ExternalEntity (name, **kwargs)
Expand source code
class ExternalEntity(Asset):
    hasPhysicalAccess = varBool(False)

    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)

An asset with outgoing or incoming dataflows

Ancestors

  • pytm.pytm.Asset
  • pytm.pytm.Element

Instance variables

var hasPhysicalAccess
Expand source code
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)
class Finding (*args, **kwargs)
Expand source code
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")
    assumption = varAssumption(None, required=False, doc="The assumption, that caused this finding to be excluded")
    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 occurring 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}"

Represents a Finding - the element in question and a description of the finding

Instance variables

var assumption
Expand source code
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)

The assumption, that caused this finding to be excluded

var condition
Expand source code
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)

Threat condition

var cvss
Expand source code
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)

The CVSS score and/or vector

var description
Expand source code
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)

Threat description

var details
Expand source code
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)

Threat details

var element
Expand source code
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)

Element this finding applies to

var example
Expand source code
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)

Threat example

var id
Expand source code
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)

Finding ID

var mitigations
Expand source code
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)

Threat mitigations

var references
Expand source code
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)

Threat references

var response
Expand source code
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)

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 occurring 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

var severity
Expand source code
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)

Threat severity

var target
Expand source code
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)

Name of the element this finding applies to

var threat_id
Expand source code
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)

Threat ID

class Lambda (name, **kwargs)
Expand source code
class Lambda(Asset):
    """A lambda function running in a Function-as-a-Service (FaaS) environment"""

    onAWS = varBool(True)
    environment = varString("")
    implementsAPI = varBool(False)

    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)

    def _dfd_template(self):
        return """{uniq_name} [
    shape = {shape};

    color = {color};
    fontcolor = "black";
    label = <
        <table border="0" cellborder="0" cellpadding="2">
            <tr><td><b>{label}</b></td></tr>
        </table>
    >;
]
"""

    def dfd(self, **kwargs):
        self._is_drawn = True

        levels = kwargs.get("levels", None)
        if levels and not levels & self.levels:
            return ""

        color = self._color()

        if kwargs.get("colormap", False):
            color = sev_to_color(self.severity)

        return self._dfd_template().format(
            uniq_name=self._uniq_name(),
            label=self._label(),
            color=color,
            shape=self._shape(),
        )

    def _shape(self):
        return "rectangle; style=rounded"

A lambda function running in a Function-as-a-Service (FaaS) environment

Ancestors

  • pytm.pytm.Asset
  • pytm.pytm.Element

Instance variables

var environment
Expand source code
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)
var implementsAPI
Expand source code
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)
var onAWS
Expand source code
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)
class Lifetime (*args, **kwds)
Expand source code
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("_", " ")

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

Color.RED

  • value lookup:

Color(1)

  • name lookup:

Color['RED']

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

Ancestors

  • enum.Enum

Class variables

var AUTO

The type of the None singleton.

var HARDCODED

The type of the None singleton.

var LONG

The type of the None singleton.

var MANUAL

The type of the None singleton.

var NONE

The type of the None singleton.

var SHORT

The type of the None singleton.

var UNKNOWN

The type of the None singleton.

Methods

def label(self)
Expand source code
def label(self):
    return self.value.lower().replace("_", " ")
class Process (name, **kwargs)
Expand source code
class Process(Asset):
    """An entity processing data"""

    codeType = varString("Unmanaged")
    implementsCommunicationProtocol = varBool(False)
    tracksExecutionFlow = varBool(False)
    implementsAPI = varBool(False)
    environment = varString("")
    allowsClientSideScripting = varBool(False)

    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)

    def _shape(self):
        return "circle"

An entity processing data

Ancestors

  • pytm.pytm.Asset
  • pytm.pytm.Element

Subclasses

  • pytm.pytm.SetOfProcesses

Instance variables

var allowsClientSideScripting
Expand source code
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)
var codeType
Expand source code
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)
var environment
Expand source code
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)
var implementsAPI
Expand source code
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)
var implementsCommunicationProtocol
Expand source code
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)
var tracksExecutionFlow
Expand source code
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)
class Server (name, **kwargs)
Expand source code
class Server(Asset):
    """An entity processing data"""

    usesSessionTokens = varBool(False)
    usesCache = varBool(False)
    usesVPN = varBool(False)
    usesXMLParser = varBool(False)

    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)

    def _shape(self):
        return "circle"

An entity processing data

Ancestors

  • pytm.pytm.Asset
  • pytm.pytm.Element

Instance variables

var usesCache
Expand source code
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)
var usesSessionTokens
Expand source code
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)
var usesVPN
Expand source code
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)
var usesXMLParser
Expand source code
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)
class SetOfProcesses (name, **kwargs)
Expand source code
class SetOfProcesses(Process):
    def __init__(self, name, **kwargs):
        super().__init__(name, **kwargs)

    def _shape(self):
        return "doublecircle"

An entity processing data

Ancestors

  • pytm.pytm.Process
  • pytm.pytm.Asset
  • pytm.pytm.Element
class TLSVersion (*args, **kwds)
Expand source code
class TLSVersion(OrderedEnum):
    NONE = 0
    SSLv1 = 1
    SSLv2 = 2
    SSLv3 = 3
    TLSv10 = 4
    TLSv11 = 5
    TLSv12 = 6
    TLSv13 = 7

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

Color.RED

  • value lookup:

Color(1)

  • name lookup:

Color['RED']

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

Ancestors

  • pytm.pytm.OrderedEnum
  • enum.Enum

Class variables

var NONE

The type of the None singleton.

var SSLv1

The type of the None singleton.

var SSLv2

The type of the None singleton.

var SSLv3

The type of the None singleton.

var TLSv10

The type of the None singleton.

var TLSv11

The type of the None singleton.

var TLSv12

The type of the None singleton.

var TLSv13

The type of the None singleton.

class TM (name, **kwargs)
Expand source code
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")
    excluded_findings = varFindings(
        [],
        doc="Threats found for elements of this model, "
        "that were excluded on a per-element basis, using the Assumptions class"
    )
    onDuplicates = varAction(
        Action.NO_ACTION,
        doc="""How to handle duplicate Dataflow
with same properties, except name and notes""",
    )
    assumptions = varAssumptions(
        [],
        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})."
            )
        active_threats = (threat for threat in threats_json if "DEPRECATED" not in threat)
        for threat in active_threats:
            TM._threats.append(Threat(**threat))

    def resolve(self):
        finding_count = 0
        excluded_finding_count = 0
        findings = []
        excluded_findings = []
        # We just need the assumptions with SIDs to exclude
        global_assumptions = [a for a in self.assumptions if len(a.exclude) > 0]
        elements = defaultdict(list)
        for e in TM._elements:
            if not e.inScope:
                e.findings = findings
                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

                _continue = False
                for assumption in e.assumptions + global_assumptions:  # type: Assumption
                    if t.id in assumption.exclude:
                        excluded_finding_count += 1
                        f = Finding(e, id=str(excluded_finding_count), threat=t, assumption=assumption)
                        excluded_findings.append(f)
                        _continue = True
                        break
                if _continue:
                    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
        self.excluded_findings = excluded_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)), "    ")
        )

    def _seq_template(self):
        return """@startuml
{participants}

{messages}
@enduml"""

    def seq(self):
        participants = []
        for e in TM._elements:
            if isinstance(e, Actor):
                participants.append(
                    'actor {0} as "{1}"'.format(e._uniq_name(), e.display_name())
                )
            elif isinstance(e, Datastore):
                participants.append(
                    'database {0} as "{1}"'.format(e._uniq_name(), e.display_name())
                )
            elif not isinstance(e, Dataflow) and not isinstance(e, Boundary):
                participants.append(
                    'entity {0} as "{1}"'.format(e._uniq_name(), e.display_name())
                )

        messages = []
        for e in TM._flows:
            message = "{0} -> {1}: {2}".format(
                e.source._uniq_name(), e.sink._uniq_name(), e.display_name()
            )
            note = ""
            if e.note != "":
                note = "\nnote left\n{}\nend note".format(e.note)
            messages.append("{}{}".format(message, note))

        return self._seq_template().format(
            participants="\n".join(participants), messages="\n".join(messages)
        )

    def report(self, template_path):
        try:
            with open(template_path) as file:
                template = file.read()
        except (FileNotFoundError, PermissionError, IsADirectoryError) as e:
            raise UIError(
                e, f"while trying to open the report template file ({template_path})."
            )

        threats = encode_threat_data(TM._threats)
        findings = encode_threat_data(self.findings)

        elements = encode_element_threat_data(TM._elements)
        assets = encode_element_threat_data(TM._assets)
        actors = encode_element_threat_data(TM._actors)
        boundaries = encode_element_threat_data(TM._boundaries)
        flows = encode_element_threat_data(TM._flows)

        data = {
            "tm": self,
            "dataflows": flows,
            "threats": threats,
            "findings": findings,
            "elements": elements,
            "assets": assets,
            "actors": actors,
            "boundaries": boundaries,
            "data": TM._data,
        }

        return self._sf.format(template, **data)

    def process(self):
        try:
            self._process()
        except UIError as e:
            erromsg = f"""Failed to excecute
    {e.context}
    {e.error}
"""
            sys.stderr.write(erromsg)
            sys.exit(127)

    def _process(self):
        self.check()
        result = get_args()
        logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

        if result.debug:
            logger.setLevel(logging.DEBUG)

        if result.exclude is not None:
            TM._threatsExcluded = result.exclude.split(",")

        if result.seq is True:
            print(self.seq())

        if result.dfd is True:
            if result.colormap is True:
                self.resolve()
            print(self.dfd(colormap=result.colormap, levels=(result.levels or set())))

        if (
            result.report is not None
            or result.json is not None
            or result.sqldump is not None
            or result.stale_days is not None
        ):
            self.resolve()

        if result.sqldump is not None:
            self.sqlDump(result.sqldump)

        if result.json:
            try:
                with open(result.json, "w", encoding="utf8") as f:
                    json.dump(self, f, default=to_serializable)
            except (FileExistsError, PermissionError, IsADirectoryError) as e:
                raise UIError(
                    e, f"while trying to write to the result file ({result.json})"
                )

        if result.report is not None:
            print(self.report(result.report))

        if result.describe is not None:
            _describe_classes(result.describe.split())

        if result.list_elements:
            _list_elements()

        if result.list is True:
            [print("{} - {}".format(t.id, t.description)) for t in TM._threats]

        if result.stale_days is not None:
            print(self._stale(result.stale_days))

    def _stale(self, days):
        try:
            base_path = os.path.dirname(sys.argv[0])
            tm_mtime = datetime.fromtimestamp(
                os.stat(base_path + f"/{sys.argv[0]}").st_mtime
            )
        except os.error as err:
            sys.stderr.write(f"{sys.argv[0]} - {err}\n")
            sys.stderr.flush()
            return "[ERROR]"

        print(f"Checking for code {days} days older than this model.")

        for e in TM._elements:
            for src in e.sourceFiles:
                try:
                    src_mtime = datetime.fromtimestamp(
                        os.stat(base_path + f"/{src}").st_mtime
                    )
                except os.error as err:
                    sys.stderr.write(f"{sys.argv[0]} - {err}\n")
                    sys.stderr.flush()
                    continue

                age = (src_mtime - tm_mtime).days

                # source code is older than model by more than the speficied delta
                if (age) >= days:
                    print(f"This model is {age} days older than {base_path}/{src}.")
                elif age <= -days:
                    print(
                        f"Model script {sys.argv[0]}"
                        + " is only "
                        + str(-1 * age)
                        + " days newer than source code file "
                        + f"{base_path}/{src}"
                    )

        return ""

    def sqlDump(self, filename):
        try:
            from pydal import DAL, Field
        except ImportError as e:
            raise UIError(
                e, """This feature requires the pyDAL package,
    Please install the package via pip or your packagemanger of choice.
                """
            )

        @lru_cache(maxsize=None)
        def get_table(db, klass):
            name = klass.__name__
            fields = [
                Field("SID" if i == "id" else i)
                for i in dir(klass)
                if not i.startswith("_") and not callable(getattr(klass, i))
            ]
            return db.define_table(name, fields)

        try:
            rmtree("./sqldump")
            os.mkdir("./sqldump")
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise
            else:
                os.mkdir("./sqldump")

        db = DAL("sqlite://" + filename, folder="sqldump")

        for klass in (
            Server,
            ExternalEntity,
            Dataflow,
            Datastore,
            Actor,
            Process,
            SetOfProcesses,
            Boundary,
            TM,
            Threat,
            Lambda,
            Data,
            Finding,
        ):
            get_table(db, klass)

        for e in TM._threats + TM._data + TM._elements + self.findings + [self]:
            table = get_table(db, e.__class__)
            row = {}
            for k, v in serialize(e).items():
                if k == "id":
                    k = "SID"
                row[k] = ", ".join(str(i) for i in v) if isinstance(v, list) else v
            db[table].bulk_insert([row])

        db.close()

Describes the threat model administratively, and holds all details during a run

Static methods

def reset()

Instance variables

var assumptions
Expand source code
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)

A list of assumptions about the design/model.

var description
Expand source code
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)

Model description

var excluded_findings
Expand source code
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)

Threats found for elements of this model, that were excluded on a per-element basis, using the Assumptions class

var findings
Expand source code
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)

Threats found for elements of this model

var ignoreUnused
Expand source code
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)

Ignore elements not used in any Dataflow

var isOrdered
Expand source code
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)

Automatically order all Dataflows

var mergeResponses
Expand source code
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)

Merge response edges in DFDs

var name
Expand source code
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)

Model name

var onDuplicates
Expand source code
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)

How to handle duplicate Dataflow with same properties, except name and notes

var threatsFile
Expand source code
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)

JSON file with custom threats

Methods

def process(self)
Expand source code
    def process(self):
        try:
            self._process()
        except UIError as e:
            erromsg = f"""Failed to excecute
    {e.context}
    {e.error}
"""
            sys.stderr.write(erromsg)
            sys.exit(127)
def report(self, template_path)
Expand source code
def report(self, template_path):
    try:
        with open(template_path) as file:
            template = file.read()
    except (FileNotFoundError, PermissionError, IsADirectoryError) as e:
        raise UIError(
            e, f"while trying to open the report template file ({template_path})."
        )

    threats = encode_threat_data(TM._threats)
    findings = encode_threat_data(self.findings)

    elements = encode_element_threat_data(TM._elements)
    assets = encode_element_threat_data(TM._assets)
    actors = encode_element_threat_data(TM._actors)
    boundaries = encode_element_threat_data(TM._boundaries)
    flows = encode_element_threat_data(TM._flows)

    data = {
        "tm": self,
        "dataflows": flows,
        "threats": threats,
        "findings": findings,
        "elements": elements,
        "assets": assets,
        "actors": actors,
        "boundaries": boundaries,
        "data": TM._data,
    }

    return self._sf.format(template, **data)
def resolve(self)
Expand source code
def resolve(self):
    finding_count = 0
    excluded_finding_count = 0
    findings = []
    excluded_findings = []
    # We just need the assumptions with SIDs to exclude
    global_assumptions = [a for a in self.assumptions if len(a.exclude) > 0]
    elements = defaultdict(list)
    for e in TM._elements:
        if not e.inScope:
            e.findings = findings
            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

            _continue = False
            for assumption in e.assumptions + global_assumptions:  # type: Assumption
                if t.id in assumption.exclude:
                    excluded_finding_count += 1
                    f = Finding(e, id=str(excluded_finding_count), threat=t, assumption=assumption)
                    excluded_findings.append(f)
                    _continue = True
                    break
            if _continue:
                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
    self.excluded_findings = excluded_findings
    for e, findings in elements.items():
        e.findings = findings
def sqlDump(self, filename)
Expand source code
def sqlDump(self, filename):
    try:
        from pydal import DAL, Field
    except ImportError as e:
        raise UIError(
            e, """This feature requires the pyDAL package,
Please install the package via pip or your packagemanger of choice.
            """
        )

    @lru_cache(maxsize=None)
    def get_table(db, klass):
        name = klass.__name__
        fields = [
            Field("SID" if i == "id" else i)
            for i in dir(klass)
            if not i.startswith("_") and not callable(getattr(klass, i))
        ]
        return db.define_table(name, fields)

    try:
        rmtree("./sqldump")
        os.mkdir("./sqldump")
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
        else:
            os.mkdir("./sqldump")

    db = DAL("sqlite://" + filename, folder="sqldump")

    for klass in (
        Server,
        ExternalEntity,
        Dataflow,
        Datastore,
        Actor,
        Process,
        SetOfProcesses,
        Boundary,
        TM,
        Threat,
        Lambda,
        Data,
        Finding,
    ):
        get_table(db, klass)

    for e in TM._threats + TM._data + TM._elements + self.findings + [self]:
        table = get_table(db, e.__class__)
        row = {}
        for k, v in serialize(e).items():
            if k == "id":
                k = "SID"
            row[k] = ", ".join(str(i) for i in v) if isinstance(v, list) else v
        db[table].bulk_insert([row])

    db.close()
class Threat (**kwargs)
Expand source code
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)

Represents a possible threat

Class variables

var target

The type of the None singleton.

Instance variables

var condition
Expand source code
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)

a Python expression that should evaluate to a boolean True or False

var description
Expand source code
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)
var details
Expand source code
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)
var example
Expand source code
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)
var id
Expand source code
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)
var likelihood
Expand source code
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)
var mitigations
Expand source code
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)
var prerequisites
Expand source code
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)
var references
Expand source code
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)
var severity
Expand source code
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)

Methods

def apply(self, target)
Expand source code
def apply(self, target):
    if not isinstance(target, self.target):
        return None
    return eval(self.condition)