diff --git a/pytm/__init__.py b/pytm/__init__.py
index c827954..f0f7fa2 100644
--- a/pytm/__init__.py
+++ b/pytm/__init__.py
@@ -4,6 +4,8 @@
"Assumption",
"Boundary",
"Classification",
+ "Likelihood",
+ "Severity",
"TLSVersion",
"Data",
"Dataflow",
@@ -32,7 +34,7 @@
from .pytm import var
# Import from new Pydantic models
-from .enums import Action, Classification, DatastoreType, Lifetime, TLSVersion
+from .enums import Action, Classification, DatastoreType, Lifetime, Likelihood, Severity, TLSVersion
from .base import Assumption, Controls
from .element import Element
from .data import Data
diff --git a/pytm/enums.py b/pytm/enums.py
index 29c0840..b5bce6d 100644
--- a/pytm/enums.py
+++ b/pytm/enums.py
@@ -81,6 +81,30 @@ def label(self):
return self.value.lower().replace("_", " ")
+class Likelihood(OrderedEnum):
+ """Likelihood of a threat occurring."""
+
+ LOW = 1
+ MEDIUM = 2
+ HIGH = 3
+
+ def label(self):
+ return self.name.capitalize()
+
+
+class Severity(OrderedEnum):
+ """Severity level of a threat."""
+
+ VERY_LOW = 1
+ LOW = 2
+ MEDIUM = 3
+ HIGH = 4
+ VERY_HIGH = 5
+
+ def label(self):
+ return self.name.replace("_", " ").capitalize()
+
+
class TLSVersion(OrderedEnum):
"""TLS/SSL version levels."""
diff --git a/pytm/threat.py b/pytm/threat.py
index e972b8e..0c2d546 100644
--- a/pytm/threat.py
+++ b/pytm/threat.py
@@ -5,7 +5,7 @@
import ast
import sys
from types import CodeType
-from typing import Any, ClassVar, Tuple, List
+from typing import Any, ClassVar
from collections.abc import Iterable
import builtins
@@ -14,6 +14,7 @@
BaseModel,
Field,
ConfigDict,
+ field_validator,
model_validator,
PrivateAttr,
)
@@ -130,8 +131,8 @@ def visit_Name(self, node: ast.Name) -> Any: # noqa: D401
return None
@staticmethod
- def _attribute_chain(node: ast.Attribute) -> List[str]:
- chain: List[str] = [node.attr]
+ def _attribute_chain(node: ast.Attribute) -> list[str]:
+ chain: list[str] = [node.attr]
current = node.value
while isinstance(current, ast.Attribute):
if isinstance(current.attr, str) and current.attr.startswith("__"):
@@ -184,13 +185,21 @@ class Threat(BaseModel):
default="", description="Likelihood of the threat occurring"
)
severity: str = Field(default="", description="Severity level of the threat")
+
+ @field_validator("likelihood", "severity", mode="before")
+ @classmethod
+ def _coerce_enum_to_str(cls, v: Any) -> str:
+ """Accept Likelihood/Severity enum values and coerce them to their label strings."""
+ if hasattr(v, "label"):
+ return v.label()
+ return v
mitigations: str = Field(
default="", description="Possible mitigations for the threat"
)
prerequisites: str = Field(default="", description="Prerequisites for the threat")
example: str = Field(default="", description="Example of the threat")
references: str = Field(default="", description="References for the threat")
- target: Tuple = Field(default=(), description="Target classes for this threat")
+ target: tuple = Field(default=(), description="Target classes for this threat")
_compiled_condition: CodeType | None = PrivateAttr(default=None)
_eval_globals: ClassVar[dict[str, Any] | None] = None
@@ -210,26 +219,33 @@ def _normalize_input(cls, data: Any) -> Any:
if "Likelihood Of Attack" in data:
data.setdefault("likelihood", data.pop("Likelihood Of Attack"))
- # Normalise target to a tuple
- target = data.get("target", "Element")
- if isinstance(target, str) or not isinstance(target, Iterable):
- target = (target,)
- else:
- target = tuple(target)
-
- # Resolve target name strings to actual Python classes
- resolved = []
- for name in target:
- if isinstance(name, type):
- resolved.append(name)
+ # Normalise target to a tuple — only when explicitly passed (e.g. JSON
+ # loading). Class-level tuple defaults on Python-native Threat subclasses
+ # are already correct types and must not be overridden here.
+ if "target" in data:
+ target = data["target"]
+ if isinstance(target, str) or not isinstance(target, Iterable):
+ target = (target,)
else:
- klass = getattr(sys.modules.get("pytm"), name, None)
- resolved.append(klass if klass is not None else name)
- data["target"] = tuple(resolved)
+ target = tuple(target)
+
+ # Resolve target name strings to actual Python classes
+ resolved = []
+ for name in target:
+ if isinstance(name, type):
+ resolved.append(name)
+ else:
+ klass = getattr(sys.modules.get("pytm"), name, None)
+ resolved.append(klass if klass is not None else name)
+ data["target"] = tuple(resolved)
return data
def model_post_init(self, __context: Any) -> None: # noqa: D401
+ # Skip string compilation when _check_condition is overridden in a subclass.
+ if type(self)._check_condition is not Threat._check_condition:
+ return
+
if not self.condition:
self._compiled_condition = None
return
@@ -248,13 +264,6 @@ def model_post_init(self, __context: Any) -> None: # noqa: D401
f"Invalid syntax in condition for threat {self.id}: {exc}"
) from exc
- def _safeset(self, attr: str, value) -> None:
- """Safely set an attribute value."""
- try:
- setattr(self, attr, value)
- except (ValueError, TypeError):
- pass
-
def __repr__(self):
return (
f"<{self.__module__}.{type(self).__name__}({self.id}) at {hex(id(self))}>"
@@ -300,19 +309,29 @@ def _allowed_global_names(cls) -> set[str]:
globals_dict = cls._build_eval_globals()
return {key for key in globals_dict.keys() if key != "__builtins__"}
- def apply(self, target):
- """Apply the threat condition to a target."""
- # Check if target matches any of the target types
+ def _check_condition(self, target) -> bool:
+ """Evaluate whether this threat applies to the given target.
+
+ Override this method in subclasses to define conditions natively in Python
+ instead of using string eval. The base implementation uses the compiled
+ string condition (for JSON-loaded threats).
+ """
+ if self._compiled_condition is None:
+ return False
+
+ globals_dict = dict(self._build_eval_globals())
+ return bool(eval(self._compiled_condition, globals_dict, {"target": target}))
+
+ def apply(self, target) -> bool:
+ """Return True if this threat applies to the given target element."""
if self.target:
target_matches = False
for target_type in self.target:
if isinstance(target_type, str):
- # String comparison for backward compatibility
if target_type == type(target).__name__:
target_matches = True
break
elif isinstance(target_type, type):
- # Class type comparison
if isinstance(target, target_type):
target_matches = True
break
@@ -320,12 +339,7 @@ def apply(self, target):
if not target_matches:
return False
- if self._compiled_condition is None:
- return False
-
try:
- globals_dict = dict(self._build_eval_globals())
- locals_dict = {"target": target}
- return bool(eval(self._compiled_condition, globals_dict, locals_dict))
+ return bool(self._check_condition(target))
except Exception:
return False
diff --git a/pytm/threatlib/__init__.py b/pytm/threatlib/__init__.py
new file mode 100644
index 0000000..f941ab4
--- /dev/null
+++ b/pytm/threatlib/__init__.py
@@ -0,0 +1,19 @@
+"""Threat library — auto-exports all Threat subclasses from category modules.
+
+Import threat classes directly from this package without needing to know
+which file they live in::
+
+ from pytm.threatlib import INP01, CR01, AA01
+"""
+
+import inspect
+import importlib
+import pkgutil
+
+from pytm.threat import Threat
+
+for _finder, _mod_name, _ispkg in pkgutil.iter_modules(__path__, prefix=__name__ + "."):
+ _module = importlib.import_module(_mod_name)
+ for _cls_name, _cls in inspect.getmembers(_module, inspect.isclass):
+ if issubclass(_cls, Threat) and _cls is not Threat and _cls.__module__ == _module.__name__:
+ globals()[_cls_name] = _cls
diff --git a/pytm/threatlib/aa.py b/pytm/threatlib/aa.py
new file mode 100644
index 0000000..5160eac
--- /dev/null
+++ b/pytm/threatlib/aa.py
@@ -0,0 +1,73 @@
+"""Authentication and authorization threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+
+from pytm.threat import Threat
+
+class AA01(Threat):
+ """Authentication Abuse/ByPass."""
+
+ id: str = 'AA01'
+ target: tuple = (pytm.Server, pytm.Process)
+ description: str = 'Authentication Abuse/ByPass'
+ details: str = "An attacker obtains unauthorized access to an application, service or device either through knowledge of the inherent weaknesses of an authentication mechanism, or by exploiting a flaw in the authentication scheme's implementation. In such an attack an authentication mechanism is functioning but a carefully controlled sequence of events causes the mechanism to grant access to the attacker. This attack may exploit assumptions made by the target's authentication procedures, such as assumptions regarding trust relationships or assumptions regarding the generation of secret values. This attack differs from Authentication Bypass attacks in that Authentication Abuse allows the attacker to be certified as a valid user through illegitimate means, while Authentication Bypass allows the user to access protected material without ever being certified as an authenticated user. This attack does not rely on prior sessions established by successfully authenticating users, as relied upon for the Exploitation of Session Variables, Resource IDs and other Trusted Credentials attack patterns."
+ severity: str = "Medium"
+ prerequisites: str = 'An authentication mechanism or subsystem implementing some form of authentication such as passwords, digest authentication, security certificates, etc. which is flawed in some way.'
+ mitigations: str = 'Use strong authentication and authorization mechanisms. A proven protocol is OAuth 2.0, which enables a third-party application to obtain limited access to an API.'
+ example: str = 'An adversary that has previously obtained unauthorized access to certain device resources, uses that access to obtain information such as location and network information.'
+ references: str = 'https://capec.mitre.org/data/definitions/114.html, http://cwe.mitre.org/data/definitions/287.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.authenticatesSource is False
+
+class AA02(Threat):
+ """Principal Spoof."""
+
+ id: str = 'AA02'
+ target: tuple = (pytm.Server, pytm.Process)
+ description: str = 'Principal Spoof'
+ details: str = "A Principal Spoof is a form of Identity Spoofing where an adversary pretends to be some other person in an interaction. This is often accomplished by crafting a message (either written, verbal, or visual) that appears to come from a person other than the adversary. Phishing and Pharming attacks often attempt to do this so that their attempts to gather sensitive information appear to come from a legitimate source. A Principal Spoof does not use stolen or spoofed authentication credentials, instead relying on the appearance and content of the message to reflect identity. The possible outcomes of a Principal Spoof mirror those of Identity Spoofing. (e.g., escalation of privilege and false attribution of data or activities) Likewise, most techniques for Identity Spoofing (crafting messages or intercepting and replaying or modifying messages) can be used for a Principal Spoof attack. However, because a Principal Spoof is used to impersonate a person, social engineering can be both an attack technique (using social techniques to generate evidence in support of a false identity) as well as a possible outcome (manipulating people's perceptions by making statements or performing actions under a target's name)."
+ severity: str = "Medium"
+ prerequisites: str = "The target must associate data or activities with a person's identity and the adversary must be able to modify this identity without detection."
+ mitigations: str = 'Employ robust authentication processes (e.g., multi-factor authentication).'
+ example: str = 'An adversary may craft messages that appear to come from a different principle or use stolen / spoofed authentication credentials.'
+ references: str = 'https://capec.mitre.org/data/definitions/195.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.authenticatesSource is False
+
+class AA03(Threat):
+ """Exploitation of Trusted Credentials."""
+
+ id: str = 'AA03'
+ target: tuple = (pytm.Server,)
+ description: str = 'Exploitation of Trusted Credentials'
+ details: str = "Attacks on session IDs and resource IDs take advantage of the fact that some software accepts user input without verifying its authenticity. For example, a message queuing system that allows service requesters to post messages to its queue through an open channel (such as anonymous FTP), authorization is done through checking group or role membership contained in the posted message. However, there is no proof that the message itself, the information in the message (such group or role membership), or indeed the process that wrote the message to the queue are authentic and authorized to do so. Many server side processes are vulnerable to these attacks because the server to server communications have not been analyzed from a security perspective or the processes trust other systems because they are behind a firewall. In a similar way servers that use easy to guess or spoofable schemes for representing digital identity can also be vulnerable. Such systems frequently use schemes without cryptography and digital signatures (or with broken cryptography). Session IDs may be guessed due to insufficient randomness, poor protection (passed in the clear), lack of integrity (unsigned), or improperly correlation with access control policy enforcement points. Exposed configuration and properties files that contain system passwords, database connection strings, and such may also give an attacker an edge to identify these identifiers. The net result is that spoofing and impersonation is possible leading to an attacker's ability to break authentication, authorization, and audit controls on the system."
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'Server software must rely on weak session IDs proof and/or verification schemes'
+ mitigations: str = 'Design: utilize strong federated identity such as SAML to encrypt and sign identity tokens in transit.Implementation: Use industry standards session key generation mechanisms that utilize high amount of entropy to generate the session key. Many standard web and application servers will perform this task on your behalf.Implementation: If the session identifier is used for authentication, such as in the so-called single sign on use cases, then ensure that it is protected at the same level of assurance as authentication tokens.Implementation: If the web or application server supports it, then encrypting and/or signing the session ID (such as cookie) can protect the ID if intercepted.Design: Use strong session identifiers that are protected in transit and at rest.Implementation: Utilize a session timeout for all sessions, for example 20 minutes. If the user does not explicitly logout, the server terminates their session after this period of inactivity. If the user logs back in then a new session key is generated.Implementation: Verify of authenticity of all session IDs at runtime.'
+ example: str = "Thin client applications like web applications are particularly vulnerable to session ID attacks. Since the server has very little control over the client, but still must track sessions, data, and objects on the server side, cookies and other mechanisms have been used to pass the key to the session data between the client and server. When these session keys are compromised it is trivial for an attacker to impersonate a user's session in effect, have the same capabilities as the authorized user. There are two main ways for an attacker to exploit session IDs. A brute force attack involves an attacker repeatedly attempting to query the system with a spoofed session header in the HTTP request. A web server that uses a short session ID can be easily spoofed by trying many possible combinations so the parameters session-ID= 1234 has few possible combinations, and an attacker can retry several hundred or thousand request with little to no issue on their side. The second method is interception, where a tool such as wireshark is used to sniff the wire and pull off any unprotected session identifiers. The attacker can then use these variables and access the application."
+ references: str = 'https://capec.mitre.org/data/definitions/21.html, http://cwe.mitre.org/data/definitions/290.html, http://cwe.mitre.org/data/definitions/346.html, http://cwe.mitre.org/data/definitions/664.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.providesIntegrity is False or target.controls.authenticatesSource is False or target.controls.usesStrongSessionIdentifiers is False
+
+class AA04(Threat):
+ """Exploiting Trust in Client."""
+
+ id: str = 'AA04'
+ target: tuple = (pytm.Server,)
+ description: str = 'Exploiting Trust in Client'
+ details: str = 'An attack of this type exploits vulnerabilities in client/server communication channel authentication and data integrity. It leverages the implicit trust a server places in the client, or more importantly, that which the server believes is the client. An attacker executes this type of attack by placing themselves in the communication channel between client and server such that communication directly to the server is possible where the server believes it is communicating only with a valid client. There are numerous variations of this type of attack.'
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'Server software must rely on client side formatted and validated values, and not reinforce these checks on the server side.'
+ mitigations: str = 'Design: Ensure that client process and/or message is authenticated so that anonymous communications and/or messages are not accepted by the system.Design: Do not rely on client validation or encoding for security purposes.Design: Utilize digital signatures to increase authentication assurance.Design: Utilize two factor authentication to increase authentication assurance.Implementation: Perform input validation for all remote content.'
+ example: str = "Web applications may use JavaScript to perform client side validation, request encoding/formatting, and other security functions, which provides some usability benefits and eliminates some client-server round-tripping. However, the web server cannot assume that the requests it receives have been subject to those validations, because an attacker can use an alternate method for crafting the HTTP Request and submit data that contains poisoned values designed to spoof a user and/or get the web server to disclose information.Web 2.0 style applications may be particularly vulnerable because they in large part rely on existing infrastructure which provides scalability without the ability to govern the clients. Attackers identify vulnerabilities that either assume the client side is responsible for some security services (without the requisite ability to ensure enforcement of these checks) and/or the lack of a hardened, default deny server configuration that allows for an attacker probing for weaknesses in unexpected ways. Client side validation, request formatting and other services may be performed, but these are strictly usability enhancements not security enhancements.Many web applications use client side scripting like JavaScript to enforce authentication, authorization, session state and other variables, but at the end of day they all make requests to the server. These client side checks may provide usability and performance gains, but they lack integrity in terms of the http request. It is possible for an attacker to post variables directly to the server without using any of the client script security checks and customize the patterns to impersonate other users or probe for more information.Many message oriented middleware systems like MQ Series are rely on information that is passed along with the message request for making authorization decisions, for example what group or role the request should be passed. However, if the message server does not or cannot authenticate the authorization information in the request then the server's policy decisions about authorization are trivial to subvert because the client process can simply elevate privilege by passing in elevated group or role information which the message server accepts and acts on."
+ references: str = 'https://capec.mitre.org/data/definitions/22.html, http://cwe.mitre.org/data/definitions/287.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.implementsServerSideValidation is False and (target.controls.providesIntegrity is False or target.controls.authorizesSource is False)
diff --git a/pytm/threatlib/ac.py b/pytm/threatlib/ac.py
new file mode 100644
index 0000000..ca5e15d
--- /dev/null
+++ b/pytm/threatlib/ac.py
@@ -0,0 +1,404 @@
+"""Access control threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+from pytm.enums import Lifetime
+from pytm.threat import Threat
+
+class AC01(Threat):
+ """Privilege Abuse."""
+
+ id: str = 'AC01'
+ target: tuple = (pytm.Server, pytm.Process, pytm.Datastore)
+ description: str = 'Privilege Abuse'
+ details: str = 'An adversary is able to exploit features of the target that should be reserved for privileged users or administrators but are exposed to use by lower or non-privileged accounts. Access to sensitive information and functionality must be controlled to ensure that only authorized users are able to access these resources. If access control mechanisms are absent or misconfigured, a user may be able to access resources that are intended only for higher level users. An adversary may be able to exploit this to utilize a less trusted account to gain information and perform activities reserved for more trusted accounts. This attack differs from privilege escalation and other privilege stealing attacks in that the adversary never actually escalates their privileges but instead is able to use a lesser degree of privilege to access resources that should be (but are not) reserved for higher privilege accounts. Likewise, the adversary does not exploit trust or subvert systems - all control functionality is working as configured but the configuration does not adequately protect sensitive resources at an appropriate level.'
+ severity: str = "Medium"
+ prerequisites: str = 'The target must have misconfigured their access control mechanisms such that sensitive information, which should only be accessible to more trusted users, remains accessible to less trusted users.The adversary must have access to the target, albeit with an account that is less privileged than would be appropriate for the targeted resources.'
+ mitigations: str = 'Use strong authentication and authorization mechanisms. A proven protocol is OAuth 2.0, which enables a third-party application to obtain limited access to an API.'
+ example: str = 'An adversary that has previously obtained unauthorized access to certain device resources, uses that access to obtain information such as location and network information.'
+ references: str = 'https://capec.mitre.org/data/definitions/122.html, http://cwe.mitre.org/data/definitions/732.html, http://cwe.mitre.org/data/definitions/269.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.hasAccessControl is False or target.controls.authorizesSource is False
+
+class AC02(Threat):
+ """Shared Data Manipulation."""
+
+ id: str = 'AC02'
+ target: tuple = (pytm.Datastore,)
+ description: str = 'Shared Data Manipulation'
+ details: str = 'An adversary exploits a data structure shared between multiple applications or an application pool to affect application behavior. Data may be shared between multiple applications or between multiple threads of a single application. Data sharing is usually accomplished through mutual access to a single memory location. If an adversary can manipulate this shared data (usually by co-opting one of the applications or threads) the other applications or threads using the shared data will often continue to trust the validity of the compromised shared data and use it in their calculations. This can result in invalid trust assumptions, corruption of additional data through the normal operations of the other users of the shared data, or even cause a crash or compromise of the sharing applications.'
+ severity: str = "Medium"
+ prerequisites: str = 'The target applications (or target application threads) must share data between themselves.The adversary must be able to manipulate some piece of the shared data either directly or indirectly and the other users of the data must accept the changed data as valid. Usually this requires that the adversary be able to compromise one of the sharing applications or threads in order to manipulate the shared data.'
+ mitigations: str = 'Use strong authentication and authorization mechanisms. Use HTTPS/SSL for communication.'
+ example: str = 'Adversary was able to compromise one of the sharing applications or data stores in order to manipulate shared data.'
+ references: str = 'https://capec.mitre.org/data/definitions/124.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.isShared is True
+
+class AC03(Threat):
+ """Subverting Environment Variable Values."""
+
+ id: str = 'AC03'
+ target: tuple = (pytm.Process, pytm.Lambda)
+ description: str = 'Subverting Environment Variable Values'
+ details: str = "The attacker directly or indirectly modifies environment variables used by or controlling the target software. The attacker's goal is to cause the target software to deviate from its expected operation in a manner that benefits the attacker."
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = 'An environment variable is accessible to the user.An environment variable used by the application can be tainted with user supplied data.Input data used in an environment variable is not validated properly.The variables encapsulation is not done properly. For instance setting a variable as public in a class makes it visible and an attacker may attempt to manipulate that variable.'
+ mitigations: str = 'Protect environment variables against unauthorized read and write access. Protect the configuration files which contain environment variables against illegitimate read and write access. Assume all input is malicious. Create a white list that defines all valid input to the software system based on the requirements specifications. Input that does not match against the white list should not be permitted to enter into the system. Apply the least privilege principles. If a process has no legitimate reason to read an environment variable do not give that privilege.'
+ example: str = 'Changing the LD_LIBRARY_PATH environment variable in TELNET will cause TELNET to use an alternate (possibly Trojan) version of a function library. The Trojan library must be accessible using the target file system and should include Trojan code that will allow the user to log in with a bad password. This requires that the attacker upload the Trojan library to a specific location on the target. As an alternative to uploading a Trojan file, some file systems support file paths that include remote addresses, such as 172.16.2.100shared_filestrojan_dll.dll. See also: Path Manipulation (CVE-1999-0073). The HISTCONTROL environment variable keeps track of what should be saved by the history command and eventually into the ~/.bash_history file when a user logs out. This setting can be configured to ignore commands that start with a space by simply setting it to ignorespace. HISTCONTROL can also be set to ignore duplicate commands by setting it to ignoredups. In some Linux systems, this is set by default to ignoreboth which covers both of the previous examples. This means that “ ls” will not be saved, but “ls” would be saved by history. HISTCONTROL does not exist by default on macOS, but can be set by the user and will be respected. Adversaries can use this to operate without leaving traces by simply prepending a space to all of their terminal commands.'
+ references: str = 'https://capec.mitre.org/data/definitions/13.html, http://cwe.mitre.org/data/definitions/353.html, http://cwe.mitre.org/data/definitions/15.html, http://cwe.mitre.org/data/definitions/74.html, http://cwe.mitre.org/data/definitions/302.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.usesEnvironmentVariables is True and (target.controls.implementsAuthenticationScheme is False or target.controls.validatesInput is False or target.controls.authorizesSource is False)
+
+class AC04(Threat):
+ """XML Schema Poisoning."""
+
+ id: str = 'AC04'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'XML Schema Poisoning'
+ details: str = 'An adversary corrupts or modifies the content of XML schema information passed between a client and server for the purpose of undermining the security of the target. XML Schemas provide the structure and content definitions for XML documents. Schema poisoning is the ability to manipulate a schema either by replacing or modifying it to compromise the programs that process documents that use this schema. Possible attacks are denial of service attacks by modifying the schema so that it does not contain required information for subsequent processing. For example, the unaltered schema may require a @name attribute in all submitted documents. If the adversary removes this attribute from the schema then documents created using the new grammar may lack this field, which may cause the processing application to enter an unexpected state or record incomplete data. In addition, manipulation of the data types described in the schema may affect the results of calculations taken by the document reader. For example, a float field could be changed to an int field. Finally, the adversary may change the encoding defined in the schema for certain fields allowing the contents to bypass filters that scan for dangerous strings. For example, the modified schema might us a URL encoding instead of ASCII, and a filter that catches a semicolon (;) might fail to detect its URL encoding (%3B).'
+ likelihood: str = "Low"
+ severity: str = "High"
+ prerequisites: str = 'Some level of access to modify the target schema.The schema used by the target application must be improperly secured against unauthorized modification and manipulation.'
+ mitigations: str = 'Design: Protect the schema against unauthorized modification. Implementation: For applications that use a known schema, use a local copy or a known good repository instead of the schema reference supplied in the XML document. Additionally, ensure that the proper permissions are set on local files to avoid unauthorized modification. Implementation: For applications that leverage remote schemas, use the HTTPS protocol to prevent modification of traffic in transit and to avoid unauthorized modification.'
+ example: str = "XML Schema Poisoning Attacks can often occur locally due to being embedded within the XML document itself or being located on the host within an improperaly protected file. In these cases, the adversary can simply edit the XML schema without the need for additional privileges. An example of the former can be seen below: ]> John Smith 555-1234 jsmith@email.com 1 Example Lane If the 'name' attribute is required in all submitted documents and this field is removed by the adversary, the application may enter an unexpected state or record incomplete data. Additionally, if this data is needed to perform additional functions, a Denial of Service (DOS) may occur.XML Schema Poisoning Attacks can also be executed remotely if the HTTP protocol is being used to transport data. : John Smith 555-1234 jsmith@email.com
1 Example Lane The HTTP protocol does not encrypt the traffic it transports, so all communication occurs in plaintext. This traffic can be observed and modified by the adversary during transit to alter the XML schema before it reaches the end user. The adversary can perform a Man-in-the-Middle (MITM) Attack to alter the schema in the same way as the previous example and to acheive the same results."
+ references: str = 'https://capec.mitre.org/data/definitions/146.html, http://cwe.mitre.org/data/definitions/15.html, http://cwe.mitre.org/data/definitions/472.html'
+
+ def _check_condition(self, target) -> bool:
+ return any(d.format == 'XML' for d in target.data) and target.controls.authorizesSource is False
+
+class AC05(Threat):
+ """Content Spoofing."""
+
+ id: str = 'AC05'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Content Spoofing'
+ details: str = "An adversary modifies content to make it contain something other than what the original content producer intended while keeping the apparent source of the content unchanged. The term content spoofing is most often used to describe modification of web pages hosted by a target to display the adversary's content instead of the owner's content. However, any content can be spoofed, including the content of email messages, file transfers, or the content of other network communication protocols. Content can be modified at the source (e.g. modifying the source file for a web page) or in transit (e.g. intercepting and modifying a message between the sender and recipient). Usually, the adversary will attempt to hide the fact that the content has been modified, but in some cases, such as with web site defacement, this is not necessary. Content Spoofing can lead to malware exposure, financial fraud (if the content governs financial transactions), privacy violations, and other unwanted outcomes."
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The target must provide content but fail to adequately protect it against modification.The adversary must have the means to alter data to which he/she is not authorized.If the content is to be modified in transit, the adversary must be able to intercept the targeted messages.'
+ mitigations: str = 'Validation of user input for type, length, data-range, format, etc. Encoding any user input that will be output by the web application.'
+ example: str = "An attacker finds a site which is vulnerable to HTML Injection. He sends a URL with malicious code injected in the URL to the user of the website(victim) via email or some other social networking site. User visits the page because the page is located within trusted domain. When the victim accesses the page, the injected HTML code is rendered and presented to the user asking for username and password. The username and password are both sent to the attacker's server."
+ references: str = 'https://capec.mitre.org/data/definitions/148.html, http://cwe.mitre.org/data/definitions/345.html, https://cwe.mitre.org/data/definitions/299.html'
+
+ def _check_condition(self, target) -> bool:
+ return ((not target.source.controls.providesIntegrity or not target.sink.controls.providesIntegrity) and not target.controls.isEncrypted) or (target.source.inScope and not target.isResponse and (not target.controls.authenticatesDestination or not target.controls.checksDestinationRevocation))
+
+class AC06(Threat):
+ """Using Malicious Files."""
+
+ id: str = 'AC06'
+ target: tuple = (pytm.Server,)
+ description: str = 'Using Malicious Files'
+ details: str = "An attack of this type exploits a system's configuration that allows an attacker to either directly access an executable file, for example through shell access; or in a possible worst case allows an attacker to upload a file and then execute it. Web servers, ftp servers, and message oriented middleware systems which have many integration points are particularly vulnerable, because both the programmers and the administrators must be in synch regarding the interfaces and the correct privileges for each interface."
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = "System's configuration must allow an attacker to directly access executable files or upload files to execute. This means that any access control system that is supposed to mediate communications between the subject and the object is set incorrectly or assumes a benign environment."
+ mitigations: str = 'Design: Enforce principle of least privilegeDesign: Run server interfaces with a non-root account and/or utilize chroot jails or other configuration techniques to constrain privileges even if attacker gains some limited access to commands.Implementation: Perform testing such as pen-testing and vulnerability scanning to identify directories, programs, and interfaces that grant direct access to executables.'
+ example: str = "Consider a directory on a web server with the following permissions drwxrwxrwx 5 admin public 170 Nov 17 01:08 webroot This could allow an attacker to both execute and upload and execute programs' on the web server. This one vulnerability can be exploited by a threat to probe the system and identify additional vulnerabilities to exploit."
+ references: str = 'https://capec.mitre.org/data/definitions/17.html, http://cwe.mitre.org/data/definitions/732.html, http://cwe.mitre.org/data/definitions/272.html, http://cwe.mitre.org/data/definitions/270.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.isHardened is False or target.controls.hasAccessControl is False
+
+class AC07(Threat):
+ """Exploiting Incorrectly Configured Access Control Security Levels."""
+
+ id: str = 'AC07'
+ target: tuple = (pytm.Server,)
+ description: str = 'Exploiting Incorrectly Configured Access Control Security Levels'
+ details: str = 'An attacker exploits a weakness in the configuration of access controls and is able to bypass the intended protection that these measures guard against and thereby obtain unauthorized access to the system or network. Sensitive functionality should always be protected with access controls. However configuring all but the most trivial access control systems can be very complicated and there are many opportunities for mistakes. If an attacker can learn of incorrectly configured access security settings, they may be able to exploit this in an attack. Most commonly, attackers would take advantage of controls that provided too little protection for sensitive activities in order to perform actions that should be denied to them. In some circumstances, an attacker may be able to take advantage of overly restrictive access control policies, initiating denial of services (if an application locks because it unexpectedly failed to be granted access) or causing other legitimate actions to fail due to security. The latter class of attacks, however, is usually less severe and easier to detect than attacks based on inadequate security restrictions. This attack pattern differs from CAPEC 1, Accessing Functionality Not Properly Constrained by ACLs in that the latter describes attacks where sensitive functionality lacks access controls, where, in this pattern, the access control is present, but incorrectly configured.'
+ likelihood: str = "High"
+ severity: str = "Medium"
+ prerequisites: str = "The target must apply access controls, but incorrectly configure them. However, not all incorrect configurations can be exploited by an attacker. If the incorrect configuration applies too little security to some functionality, then the attacker may be able to exploit it if the access control would be the only thing preventing an attacker's access and it no longer does so. If the incorrect configuration applies too much security, it must prevent legitimate activity and the attacker must be able to force others to require this activity."
+ mitigations: str = 'Design: Configure the access control correctly.'
+ example: str = 'For example, an incorrectly configured Web server, may allow unauthorized access to it, thus threaten the security of the Web application.'
+ references: str = 'https://capec.mitre.org/data/definitions/180.html, http://cwe.mitre.org/data/definitions/732.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.hasAccessControl is False
+
+class AC08(Threat):
+ """Manipulate Registry Information."""
+
+ id: str = 'AC08'
+ target: tuple = (pytm.Server,)
+ description: str = 'Manipulate Registry Information'
+ details: str = 'An adversary exploits a weakness in authorization in order to modify content within a registry (e.g., Windows Registry, Mac plist, application registry). Editing registry information can permit the adversary to hide configuration information or remove indicators of compromise to cover up activity. Many applications utilize registries to store configuration and service information. As such, modification of registry information can affect individual services (affecting billing, authorization, or even allowing for identity spoofing) or the overall configuration of a targeted application. For example, both Java RMI and SOAP use registries to track available services. Changing registry values is sometimes a preliminary step towards completing another attack pattern, but given the long term usage of many registry values, manipulation of registry information could be its own end.'
+ severity: str = "Medium"
+ prerequisites: str = 'The targeted application must rely on values stored in a registry.The adversary must have a means of elevating permissions in order to access and modify registry content through either administrator privileges (e.g., credentialed access), or a remote access tool capable of editing a registry through an API.'
+ mitigations: str = 'Ensure proper permissions are set for Registry hives to prevent users from modifying keys.Employ a robust and layered defensive posture in order to prevent unauthorized users on your system.Employ robust identification and audit/blocking via whitelisting of applications on your system. Unnecessary applications, utilities, and configurations will have a presence in the system registry that can be leveraged by an adversary through this attack pattern.'
+ example: str = "Manipulating registration information can be undertaken in advance of a path traversal attack (inserting relative path modifiers) or buffer overflow attack (enlarging a registry value beyond an application's ability to store it)."
+ references: str = 'https://capec.mitre.org/data/definitions/203.html, http://cwe.mitre.org/data/definitions/15.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.hasAccessControl is False
+
+class AC09(Threat):
+ """Functionality Misuse."""
+
+ id: str = 'AC09'
+ target: tuple = (pytm.Server,)
+ description: str = 'Functionality Misuse'
+ details: str = 'An adversary leverages a legitimate capability of an application in such a way as to achieve a negative technical impact. The system functionality is not altered or modified but used in a way that was not intended. This is often accomplished through the overuse of a specific functionality or by leveraging functionality with design flaws that enables the adversary to gain access to unauthorized, sensitive data.'
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The adversary has the capability to interact with the application directly.The target system does not adequately implement safeguards to prevent misuse of authorized actions/processes.'
+ mitigations: str = 'Perform comprehensive threat modeling, a process of identifying, evaluating, and mitigating potential threats to the application. This effort can help reveal potentially obscure application functionality that can be manipulated for malicious purposes.When implementing security features, consider how they can be misused and compromised.'
+ example: str = "An attacker clicks on the 'forgot password' and is presented with a single security question. The question is regarding the name of the first dog of the user. The system does not limit the number of attempts to provide the dog's name. An attacker goes through a list of 100 most popular dog names and finds the right name, thus getting the ability to reset the password and access the system."
+ references: str = 'https://capec.mitre.org/data/definitions/212.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.hasAccessControl is False or target.controls.authorizesSource is False
+
+class AC10(Threat):
+ """Exploiting Incorrectly Configured SSL."""
+
+ id: str = 'AC10'
+ target: tuple = (pytm.Server,)
+ description: str = 'Exploiting Incorrectly Configured SSL'
+ details: str = 'An adversary takes advantage of incorrectly configured SSL communications that enables access to data intended to be encrypted. The adversary may also use this type of attack to inject commands or other traffic into the encrypted stream to cause compromise of either the client or server.'
+ likelihood: str = "Low"
+ severity: str = "High"
+ prerequisites: str = 'Access to the client/server stream.'
+ mitigations: str = 'Usage of configuration settings, such as stream ciphers vs. block ciphers and setting timeouts on SSL sessions to extremely low values lessens the potential impact. Use of later versions of TLS (e.g. TLS 1.1+) can also be effective, but not all clients or servers support the later versions.'
+ example: str = 'Using MITM techniques, an attacker launches a blockwise chosen-boundary attack to obtain plaintext HTTP headers by taking advantage of an SSL session using an encryption protocol in CBC mode with chained initialization vectors (IV). This allows the attacker to recover session IDs, authentication cookies, and possibly other valuable data that can be used for further exploitation. Additionally this could allow for the insertion of data into the stream, allowing for additional attacks (CSRF, SQL inject, etc) to occur.'
+ references: str = 'https://capec.mitre.org/data/definitions/217.html, http://cwe.mitre.org/data/definitions/201.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.checkTLSVersion(target.inputs) and (not target.controls.implementsAuthenticationScheme or not target.controls.authorizesSource)
+
+class AC11(Threat):
+ """Session Credential Falsification through Manipulation."""
+
+ id: str = 'AC11'
+ target: tuple = (pytm.Server,)
+ description: str = 'Session Credential Falsification through Manipulation'
+ details: str = 'An attacker manipulates an existing credential in order to gain access to a target application. Session credentials allow users to identify themselves to a service after an initial authentication without needing to resend the authentication information (usually a username and password) with every message. An attacker may be able to manipulate a credential sniffed from an existing connection in order to gain access to a target server. For example, a credential in the form of a web cookie might have a field that indicates the access rights of a user. By manually tweaking this cookie, a user might be able to increase their access rights to the server. Alternately an attacker may be able to manipulate an existing credential to appear as a different user. This attack differs from falsification through prediction in that the user bases their modified credentials off existing credentials instead of using patterns detected in prior credentials to create a new credential that is accepted because it fits the pattern. As a result, an attacker may be able to impersonate other users or elevate their permissions to a targeted service.'
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The targeted application must use session credentials to identify legitimate users.'
+ mitigations: str = 'Implementation: Use session IDs that are difficult to guess or brute-force: One way for the attackers to obtain valid session IDs is by brute-forcing or guessing them. By choosing session identifiers that are sufficiently random, brute-forcing or guessing becomes very difficult. Implementation: Regenerate and destroy session identifiers when there is a change in the level of privilege: This ensures that even though a potential victim may have followed a link with a fixated identifier, a new one is issued when the level of privilege changes.'
+ example: str = "An adversary uses client side scripting(JavaScript) to set session ID in the victim's browser using document.cookie. This fixates a falsified session credential into victim's browser with the help of a crafted URL link. Once the victim clicks on the link, the attacker is able to bypass authentication or piggyback off some other authenticated victim's session."
+ references: str = 'https://capec.mitre.org/data/definitions/226.html, http://cwe.mitre.org/data/definitions/565.html, http://cwe.mitre.org/data/definitions/472.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.usesStrongSessionIdentifiers is False
+
+class AC12(Threat):
+ """Privilege Escalation."""
+
+ id: str = 'AC12'
+ target: tuple = (pytm.Process,)
+ description: str = 'Privilege Escalation'
+ details: str = 'An adversary exploits a weakness enabling them to elevate their privilege and perform an action that they are not supposed to be authorized to perform.'
+ likelihood: str = "Medium"
+ severity: str = "High"
+ mitigations: str = 'Very carefully manage the setting, management, and handling of privileges. Explicitly manage trust zones in the software. Follow the principle of least privilege when assigning access rights to entities in a software system. Implement separation of privilege - Require multiple conditions to be met before permitting access to a system resource.'
+ example: str = 'The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. As a result, the program is indefinitely operating in a raised privilege state, possibly allowing further exploitation to occur.'
+ references: str = 'https://capec.mitre.org/data/definitions/233.html, http://cwe.mitre.org/data/definitions/269.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.hasAccessControl is False or target.controls.implementsPOLP is False
+
+class AC13(Threat):
+ """Hijacking a privileged process."""
+
+ id: str = 'AC13'
+ target: tuple = (pytm.Process,)
+ description: str = 'Hijacking a privileged process'
+ details: str = 'An attacker gains control of a process that is assigned elevated privileges in order to execute arbitrary code with those privileges. Some processes are assigned elevated privileges on an operating system, usually through association with a particular user, group, or role. If an attacker can hijack this process, they will be able to assume its level of privilege in order to execute their own code. Processes can be hijacked through improper handling of user input (for example, a buffer overflow or certain types of injection attacks) or by utilizing system utilities that support process control that have been inadequately secured.'
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The targeted process or operating system must contain a bug that allows attackers to hijack the targeted process.'
+ mitigations: str = 'Very carefully manage the setting, management, and handling of privileges. Explicitly manage trust zones in the software. Follow the principle of least privilege when assigning access rights to entities in a software system. Implement separation of privilege - Require multiple conditions to be met before permitting access to a system resource.'
+ example: str = 'The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. As a result, the program is indefinitely operating in a raised privilege state, possibly allowing further exploitation to occur.'
+ references: str = 'https://capec.mitre.org/data/definitions/234.html, http://cwe.mitre.org/data/definitions/732.html, http://cwe.mitre.org/data/definitions/648.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.hasAccessControl is False or target.controls.implementsPOLP is False
+
+class AC14(Threat):
+ """Catching exception throw/signal from privileged block."""
+
+ id: str = 'AC14'
+ target: tuple = (pytm.Process,)
+ description: str = 'Catching exception throw/signal from privileged block'
+ details: str = "Attackers can sometimes hijack a privileged thread from the underlying system through synchronous (calling a privileged function that returns incorrectly) or asynchronous (callbacks, signal handlers, and similar) means. Having done so, the Attacker may not only likely access functionality the system's designer didn't intend for them, but they may also go undetected or deny other users essential service in a catastrophic (or insidiously subtle) way."
+ likelihood: str = "Low"
+ severity: str = "Very high"
+ prerequisites: str = 'The application in question employs a threaded model of execution with the threads operating at, or having the ability to switch to, a higher privilege level than normal usersIn order to feasibly execute this class of attacks, the attacker must have the ability to hijack a privileged thread.This ability includes, but is not limited to, modifying environment variables that affect the process the thread belongs to, or providing malformed user-controllable input that causes the executing thread to fault and return to a higher privilege level or such.This does not preclude network-based attacks, but makes them conceptually more difficult to identify and execute.'
+ mitigations: str = 'Application Architects must be careful to design callback, signal, and similar asynchronous constructs such that they shed excess privilege prior to handing control to user-written (thus untrusted) code.Application Architects must be careful to design privileged code blocks such that upon return (successful, failed, or unpredicted) that privilege is shed prior to leaving the block/scope.'
+ example: str = "Attacker targets an application written using Java's AWT, with the 1.2.2 era event model. In this circumstance, any AWTEvent originating in the underlying OS (such as a mouse click) would return a privileged thread. The Attacker could choose to not return the AWT-generated thread upon consuming the event, but instead leveraging its privilege to conduct privileged operations."
+ references: str = 'https://capec.mitre.org/data/definitions/236.html, http://cwe.mitre.org/data/definitions/270.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.implementsPOLP is False and (target.usesEnvironmentVariables is True or target.controls.validatesInput is False)
+
+class AC15(Threat):
+ """Schema Poisoning."""
+
+ id: str = 'AC15'
+ target: tuple = (pytm.Process,)
+ description: str = 'Schema Poisoning'
+ details: str = 'An adversary corrupts or modifies the content of a schema for the purpose of undermining the security of the target. Schemas provide the structure and content definitions for resources used by an application. By replacing or modifying a schema, the adversary can affect how the application handles or interprets a resource, often leading to possible denial of service, entering into an unexpected state, or recording incomplete data.'
+ likelihood: str = "Low"
+ severity: str = "High"
+ prerequisites: str = 'Some level of access to modify the target schema.The schema used by the target application must be improperly secured against unauthorized modification and manipulation.'
+ mitigations: str = 'Design: Protect the schema against unauthorized modification.Implementation: For applications that use a known schema, use a local copy or a known good repository instead of the schema reference supplied in the schema document.Implementation: For applications that leverage remote schemas, use the HTTPS protocol to prevent modification of traffic in transit and to avoid unauthorized modification.'
+ example: str = "In a JSON Schema Poisoning Attack, an adervary modifies the JSON schema to cause a Denial of Service (DOS) or to submit malicious input: { title: Contact, type: object, properties: { Name: { type: string }, Phone: { type: string }, Email: { type: string }, Address: { type: string } }, required: [Name, Phone, Email, Address] } If the 'name' attribute is required in all submitted documents and this field is removed by the adversary, the application may enter an unexpected state or record incomplete data. Additionally, if this data is needed to perform additional functions, a Denial of Service (DOS) may occur.In a Database Schema Poisoning Attack, an adversary alters the database schema being used to modify the database in some way. This can result in loss of data, DOS, or malicious input being submitted. Assuming there is a column named name, an adversary could make the following schema change: ALTER TABLE Contacts MODIFY Name VARCHAR(65353); The Name field of the Conteacts table now allows the storing of names up to 65353 characters in length. This could allow the adversary to store excess data within the database to consume system resource or to execute a DOS."
+ references: str = 'https://capec.mitre.org/data/definitions/271.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.implementsPOLP is False
+
+class AC16(Threat):
+ """Session Credential Falsification through Prediction."""
+
+ id: str = 'AC16'
+ target: tuple = (pytm.Server,)
+ description: str = 'Session Credential Falsification through Prediction'
+ details: str = 'This attack targets predictable session ID in order to gain privileges. The attacker can predict the session ID used during a transaction to perform spoofing and session hijacking.'
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'The target host uses session IDs to keep track of the users.Session IDs are used to control access to resources.The session IDs used by the target host are predictable. For example, the session IDs are generated using predictable information (e.g., time).'
+ mitigations: str = 'Use a strong source of randomness to generate a session ID.Use adequate length session IDs. Do not use information available to the user in order to generate session ID (e.g., time).Ideas for creating random numbers are offered by Eastlake [RFC1750]. Encrypt the session ID if you expose it to the user. For instance session ID can be stored in a cookie in encrypted format.'
+ example: str = "Jetty before 4.2.27, 5.1 before 5.1.12, 6.0 before 6.0.2, and 6.1 before 6.1.0pre3 generates predictable session identifiers using java.util.random, which makes it easier for remote attackers to guess a session identifier through brute force attacks, bypass authentication requirements, and possibly conduct cross-site request forgery attacks. See also: CVE-2006-6969mod_usertrack in Apache 1.3.11 through 1.3.20 generates session ID's using predictable information including host IP address, system time and server process ID, which allows local users to obtain session ID's and bypass authentication when these session ID's are used for authentication. See also: CVE-2001-1534"
+ references: str = 'https://capec.mitre.org/data/definitions/59.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.usesStrongSessionIdentifiers is False
+
+class AC17(Threat):
+ """Session Hijacking - ServerSide."""
+
+ id: str = 'AC17'
+ target: tuple = (pytm.Server,)
+ description: str = 'Session Hijacking - ServerSide'
+ details: str = "This type of attack involves an adversary that exploits weaknesses in an application's use of sessions in performing authentication. The advarsary is able to steal or manipulate an active session and use it to gain unathorized access to the application."
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = 'An application that leverages sessions to perform authentication.'
+ mitigations: str = 'Properly encrypt and sign identity tokens in transit, and use industry standard session key generation mechanisms that utilize high amount of entropy to generate the session key. Many standard web and application servers will perform this task on your behalf. Utilize a session timeout for all sessions. If the user does not explicitly logout, terminate their session after this period of inactivity. If the user logs back in then a new session key should be generated.'
+ example: str = 'Cross Site Injection Attack is a great example of Session Hijacking. Attacker can capture victim’s Session ID using XSS attack by using javascript. If an attacker sends a crafted link to the victim with the malicious JavaScript, when the victim clicks on the link, the JavaScript will run and complete the instructions made by the attacker.'
+ references: str = 'https://capec.mitre.org/data/definitions/593.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.usesStrongSessionIdentifiers is False
+
+class AC18(Threat):
+ """Session Hijacking - ClientSide."""
+
+ id: str = 'AC18'
+ target: tuple = (pytm.Process,)
+ description: str = 'Session Hijacking - ClientSide'
+ details: str = "This type of attack involves an adversary that exploits weaknesses in an application's use of sessions in performing authentication. The advarsary is able to steal or manipulate an active session and use it to gain unathorized access to the application."
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = 'An application that leverages sessions to perform authentication.'
+ mitigations: str = 'Properly encrypt and sign identity tokens in transit, and use industry standard session key generation mechanisms that utilize high amount of entropy to generate the session key. Many standard web and application servers will perform this task on your behalf. Utilize a session timeout for all sessions. If the user does not explicitly logout, terminate their session after this period of inactivity. If the user logs back in then a new session key should be generated.'
+ example: str = 'Cross Site Injection Attack is a great example of Session Hijacking. Attacker can capture victim’s Session ID using XSS attack by using javascript. If an attacker sends a crafted link to the victim with the malicious JavaScript, when the victim clicks on the link, the JavaScript will run and complete the instructions made by the attacker.'
+ references: str = 'https://capec.mitre.org/data/definitions/593.html'
+
+ def _check_condition(self, target) -> bool:
+ return (target.controls.usesStrongSessionIdentifiers is False or target.controls.encryptsCookies is False) and target.controls.definesConnectionTimeout is False
+
+class AC19(Threat):
+ """Reusing Session IDs (aka Session Replay) - ServerSide."""
+
+ id: str = 'AC19'
+ target: tuple = (pytm.Server,)
+ description: str = 'Reusing Session IDs (aka Session Replay) - ServerSide'
+ details: str = 'This attack targets the reuse of valid session ID to spoof the target system in order to gain privileges. The attacker tries to reuse a stolen session ID used previously during a transaction to perform spoofing and session hijacking. Another name for this type of attack is Session Replay.'
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'The target host uses session IDs to keep track of the users.Session IDs are used to control access to resources.The session IDs used by the target host are not well protected from session theft.'
+ mitigations: str = 'Always invalidate a session ID after the user logout.Setup a session time out for the session IDs.Protect the communication between the client and server. For instance it is best practice to use SSL to mitigate man in the middle attack.Do not code send session ID with GET method, otherwise the session ID will be copied to the URL. In general avoid writing session IDs in the URLs. URLs can get logged in log files, which are vulnerable to an attacker.Encrypt the session data associated with the session ID.Use multifactor authentication.'
+ example: str = "OpenSSL and SSLeay allow remote attackers to reuse SSL sessions and bypass access controls. See also: CVE-1999-0428Merak Mail IceWarp Web Mail uses a static identifier as a user session ID that does not change across sessions, which could allow remote attackers with access to the ID to gain privileges as that user, e.g. by extracting the ID from the user's answer or forward URLs. See also: CVE-2002-0258"
+ references: str = 'https://capec.mitre.org/data/definitions/60.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.usesSessionTokens is True and target.controls.implementsNonce is False
+
+class AC20(Threat):
+ """Reusing Session IDs (aka Session Replay) - ClientSide."""
+
+ id: str = 'AC20'
+ target: tuple = (pytm.Process,)
+ description: str = 'Reusing Session IDs (aka Session Replay) - ClientSide'
+ details: str = 'This attack targets the reuse of valid session ID to spoof the target system in order to gain privileges. The attacker tries to reuse a stolen session ID used previously during a transaction to perform spoofing and session hijacking. Another name for this type of attack is Session Replay.'
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'The target host uses session IDs to keep track of the users.Session IDs are used to control access to resources.The session IDs used by the target host are not well protected from session theft.'
+ mitigations: str = 'Always invalidate a session ID after the user logout.Setup a session time out for the session IDs.Protect the communication between the client and server. For instance it is best practice to use SSL to mitigate man in the middle attack.Do not code send session ID with GET method, otherwise the session ID will be copied to the URL. In general avoid writing session IDs in the URLs. URLs can get logged in log files, which are vulnerable to an attacker.Encrypt the session data associated with the session ID.Use multifactor authentication.'
+ example: str = "OpenSSL and SSLeay allow remote attackers to reuse SSL sessions and bypass access controls. See also: CVE-1999-0428Merak Mail IceWarp Web Mail uses a static identifier as a user session ID that does not change across sessions, which could allow remote attackers with access to the ID to gain privileges as that user, e.g. by extracting the ID from the user's answer or forward URLs. See also: CVE-2002-0258"
+ references: str = 'https://capec.mitre.org/data/definitions/60.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.definesConnectionTimeout is False and (target.controls.usesMFA is False or target.controls.encryptsSessionData is False)
+
+class AC21(Threat):
+ """Cross Site Request Forgery."""
+
+ id: str = 'AC21'
+ target: tuple = (pytm.Process,)
+ description: str = 'Cross Site Request Forgery'
+ details: str = "An attacker crafts malicious web links and distributes them (via web pages, email, etc.), typically in a targeted manner, hoping to induce users to click on the link and execute the malicious action against some third-party application. If successful, the action embedded in the malicious link will be processed and accepted by the targeted application with the users' privilege level. This type of attack leverages the persistence and implicit trust placed in user session cookies by many web applications today. In such an architecture, once the user authenticates to an application and a session cookie is created on the user's system, all following transactions for that session are authenticated using that cookie including potential actions initiated by an attacker and simply riding the existing session cookie."
+ likelihood: str = "High"
+ severity: str = "Very high"
+ mitigations: str = 'Use cryptographic tokens to associate a request with a specific action. The token can be regenerated at every request so that if a request with an invalid token is encountered, it can be reliably discarded. The token is considered invalid if it arrived with a request other than the action it was supposed to be associated with.Although less reliable, the use of the optional HTTP Referrer header can also be used to determine whether an incoming request was actually one that the user is authorized for, in the current context.Additionally, the user can also be prompted to confirm an action every time an action concerning potentially sensitive data is invoked. This way, even if the attacker manages to get the user to click on a malicious link and request the desired action, the user has a chance to recover by denying confirmation. This solution is also implicitly tied to using a second factor of authentication before performing such actions.In general, every request must be checked for the appropriate authentication token as well as authorization in the current session context.'
+ example: str = "While a user is logged into his bank account, an attacker can send an email with some potentially interesting content and require the user to click on a link in the email. The link points to or contains an attacker setup script, probably even within an iFrame, that mimics an actual user form submission to perform a malicious activity, such as transferring funds from the victim's account. The attacker can have the script embedded in, or targeted by, the link perform any arbitrary action as the authenticated user. When this script is executed, the targeted application authenticates and accepts the actions based on the victims existing session cookie.See also: Cross-site request forgery (CSRF) vulnerability in util.pl in @Mail WebMail 4.51 allows remote attackers to modify arbitrary settings and perform unauthorized actions as an arbitrary user, as demonstrated using a settings action in the SRC attribute of an IMG element in an HTML e-mail."
+ references: str = 'https://capec.mitre.org/data/definitions/62.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.implementsCSRFToken is False or target.controls.verifySessionIdentifiers is False
+
+class AC22(Threat):
+ """Credentials Aging."""
+
+ id: str = 'AC22'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Credentials Aging'
+ details: str = 'If no mechanism is in place for managing credentials (passwords and certificates) aging, users will have no incentive to update passwords or rotate certificates in a timely manner. Allowing password aging to occur unchecked or long certificate expiration dates can result in the possibility of diminished password integrity.'
+ likelihood: str = "Medium"
+ severity: str = "High"
+ mitigations: str = 'All passwords and other credentials should have a relatively short expiration date with a possibility to be revoked immediately under special circumstances.'
+ references: str = 'https://cwe.mitre.org/data/definitions/262.html, https://cwe.mitre.org/data/definitions/263.html, https://cwe.mitre.org/data/definitions/798.html'
+
+ def _check_condition(self, target) -> bool:
+ return any(d.isCredentials for d in target.data) and target.sink.inScope and any(d.credentialsLife in (Lifetime.UNKNOWN, Lifetime.LONG, Lifetime.MANUAL, Lifetime.HARDCODED) for d in target.data)
+
+class AC23(Threat):
+ """Credentials Disclosure."""
+
+ id: str = 'AC23'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Credentials Disclosure'
+ details: str = 'If credentials (passwords or certificates) have a long lifetime their disclosure can have severe consequences, if the credentials cannot quickly be revoked and/or rotated.'
+ likelihood: str = "Medium"
+ severity: str = "High"
+ mitigations: str = 'Long living credentials need to have high entropy and length to be future proof, especially if it is unknwon how long these credentials will be used. Further should there be a mechanism to revoke the credentials immediately if a disclosure is suspected. To detect disclosure of the credentials their use should be monitored for suspicions activity.'
+ references: str = 'https://pages.nist.gov/800-63-3/sp800-63b.html#sec6'
+
+ def _check_condition(self, target) -> bool:
+ return any(d.isCredentials for d in target.data) and target.sink.inScope and any(d.credentialsLife in (Lifetime.UNKNOWN, Lifetime.LONG, Lifetime.MANUAL) for d in target.data)
+
+class AC24(Threat):
+ """Use of hardcoded credentials."""
+
+ id: str = 'AC24'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Use of hardcoded credentials'
+ details: str = 'Hardcoded credentials (password or certificates) cannot be changed and if these credentials are dislcosed they can be used by attackers to bypass the authentication mechanism.'
+ likelihood: str = "High"
+ severity: str = "Very high"
+ mitigations: str = 'Avoid hardcoded credentials. If you have to use hardcoded credentials make is possible to change the credentials or to deactivate them. A typical design is to use a "first login"-mode which forces the user to create new credentials, on the first login. If the credentials cannot be changed the sole actions in prodcution for the defender is to deactivate/remove the effected product.'
+ references: str = 'https://cwe.mitre.org/data/definitions/798.html, https://cwe.mitre.org/data/definitions/259.html, https://cwe.mitre.org/data/definitions/321.html'
+
+ def _check_condition(self, target) -> bool:
+ return any(d.isCredentials for d in target.data) and target.sink.inScope and any(d.credentialsLife == Lifetime.HARDCODED for d in target.data)
diff --git a/pytm/threatlib/api.py b/pytm/threatlib/api.py
new file mode 100644
index 0000000..07c8f6f
--- /dev/null
+++ b/pytm/threatlib/api.py
@@ -0,0 +1,40 @@
+"""API security threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+
+from pytm.threat import Threat
+
+class API01(Threat):
+ """Exploit Test APIs."""
+
+ id: str = 'API01'
+ target: tuple = (pytm.Process, pytm.Lambda)
+ description: str = 'Exploit Test APIs'
+ details: str = 'An attacker exploits a sample, demonstration, or test API that is insecure by default and should not be resident on production systems. Some applications include APIs that are intended to allow an administrator to test and refine their domain. These APIs should usually be disabled once a system enters a production environment. Testing APIs may expose a great deal of diagnostic information intended to aid an administrator, but which can also be used by an attacker to further refine their attack. Moreover, testing APIs may not have adequate security controls or may not have undergone rigorous testing since they were not intended for use in production environments. As such, they may have many flaws and vulnerabilities that would allow an attacker to severely disrupt a target.'
+ likelihood: str = "Low"
+ severity: str = "High"
+ prerequisites: str = 'The target must have installed test APIs and failed to secure or remove them when brought into a production environment.'
+ mitigations: str = 'Ensure that production systems to not contain sample or test APIs and that these APIs are only used in development environments.'
+ example: str = 'Since APIs can be accessed over the internet just like any other URI with some sensitive data attached to the request, they share the vulnerabilities of any other resource accessible on the internet like Man-in-the-middle, CSRF Attack, Denial of Services, etc.'
+ references: str = 'https://capec.mitre.org/data/definitions/121.html, http://cwe.mitre.org/data/definitions/489.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.implementsAPI is True
+
+class API02(Threat):
+ """Exploit Script-Based APIs."""
+
+ id: str = 'API02'
+ target: tuple = (pytm.Process, pytm.Lambda)
+ description: str = 'Exploit Script-Based APIs'
+ details: str = 'Some APIs support scripting instructions as arguments. Methods that take scripted instructions (or references to scripted instructions) can be very flexible and powerful. However, if an attacker can specify the script that serves as input to these methods they can gain access to a great deal of functionality. For example, HTML pages support A similar example uses session ID as an argument of the URL. http://www.example.com/index.php/sessionid=0123456789 Once the victim clicks the links, the attacker may be able to bypass authentication or piggy-back off some other authenticated victim's session."
+ references: str = 'https://capec.mitre.org/data/definitions/196.html, http://cwe.mitre.org/data/definitions/384.html, http://cwe.mitre.org/data/definitions/664.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.usesSessionTokens is True and target.controls.implementsNonce is False
+
+class CR05(Threat):
+ """Encryption Brute Forcing."""
+
+ id: str = 'CR05'
+ target: tuple = (pytm.Server, pytm.Datastore)
+ description: str = 'Encryption Brute Forcing'
+ details: str = 'An attacker, armed with the cipher text and the encryption algorithm used, performs an exhaustive (brute force) search on the key space to determine the key that decrypts the cipher text to obtain the plaintext.'
+ likelihood: str = "Low"
+ severity: str = "Low"
+ prerequisites: str = 'Ciphertext is known.Encryption algorithm and key size are known.'
+ mitigations: str = "Use commonly accepted algorithms and recommended key sizes. The key size used will depend on how important it is to keep the data confidential and for how long.In theory a brute force attack performing an exhaustive key space search will always succeed, so the goal is to have computational security. Moore's law needs to be taken into account that suggests that computing resources double every eighteen months."
+ example: str = 'In 1997 the original DES challenge used distributed net computing to brute force the encryption key and decrypt the ciphertext to obtain the original plaintext. Each machine was given its own section of the key space to cover. The ciphertext was decrypted in 96 days.'
+ references: str = 'https://capec.mitre.org/data/definitions/20.html, http://cwe.mitre.org/data/definitions/326.html, http://cwe.mitre.org/data/definitions/327.html, http://cwe.mitre.org/data/definitions/693.html, http://cwe.mitre.org/data/definitions/719.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.usesEncryptionAlgorithm != 'RSA' and target.controls.usesEncryptionAlgorithm != 'AES'
+
+class CR06(Threat):
+ """Communication Channel Manipulation."""
+
+ id: str = 'CR06'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Communication Channel Manipulation'
+ details: str = 'An adversary manipulates a setting or parameter on communications channel in order to compromise its security. This can result in information exposure, insertion/removal of information from the communications stream, and/or potentially system compromise.'
+ likelihood: str = "Medium"
+ severity: str = "High"
+ prerequisites: str = 'The target application must leverage an open communications channel.The channel on which the target communicates must be vulnerable to interception (e.g., man in the middle attack).'
+ mitigations: str = 'Encrypt all sensitive communications using properly-configured cryptography.Design the communication system such that it associates proper authentication/authorization with each channel/message.'
+ example: str = 'Using MITM techniques, an attacker launches a blockwise chosen-boundary attack to obtain plaintext HTTP headers by taking advantage of an SSL session using an encryption protocol in CBC mode with chained initialization vectors (IV). This allows the attacker to recover session IDs, authentication cookies, and possibly other valuable data that can be used for further exploitation. Additionally this could allow for the insertion of data into the stream, allowing for additional attacks (CSRF, SQL inject, etc) to occur.'
+ references: str = 'https://capec.mitre.org/data/definitions/216.html'
+
+ def _check_condition(self, target) -> bool:
+ return (target.protocol != 'HTTPS' or target.usesVPN is False) and (target.controls.implementsAuthenticationScheme is False or target.controls.authorizesSource is False)
+
+class CR07(Threat):
+ """XML Routing Detour Attacks."""
+
+ id: str = 'CR07'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'XML Routing Detour Attacks'
+ details: str = 'An attacker subverts an intermediate system used to process XML content and forces the intermediate to modify and/or re-route the processing of the content. XML Routing Detour Attacks are Man in the Middle type attacks. The attacker compromises or inserts an intermediate system in the processing of the XML message. For example, WS-Routing can be used to specify a series of nodes or intermediaries through which content is passed. If any of the intermediate nodes in this route are compromised by an attacker they could be used for a routing detour attack. From the compromised system the attacker is able to route the XML process to other nodes of his or her choice and modify the responses so that the normal chain of processing is unaware of the interception. This system can forward the message to an outside entity and hide the forwarding and processing from the legitimate processing systems by altering the header information.'
+ likelihood: str = "High"
+ severity: str = "Medium"
+ prerequisites: str = 'The targeted system must have multiple stages processing of XML content.'
+ mitigations: str = 'Design: Specify maximum number intermediate nodes for the request and require SSL connections with mutual authentication.Implementation: Use SSL for connections between all parties with mutual authentication.'
+ example: str = "Here is an example SOAP call from a client, example1.com, to a target, example4.com, via 2 intermediaries, example2.com and example3.com. (note: The client here is not necessarily a 'end user client' but rather the starting point of the XML transaction). Example SOAP message with routing information in header: <S:Envelope> <S:Header> <m:path xmlns:m=http://schemas.example.com/rp/ S:actor=http://schemas.example.com/soap/actor S:mustUnderstand=1> <m:action>http://example1.com/</m:action> <m:to>http://example4.com/router</m:to> <m:id>uuid:1235678-abcd-1a2b-3c4d-1a2b3c4d5e6f</m:id> <m:fwd> <m:via>http://example2.com/router</m:via> </m:fwd> <m:rev /> </m:path> </S:Header> <S:Body> ... </S:Body> </S:Envelope> Add an additional node (example3.com/router) to the XML path in a WS-Referral message <r:ref xmlns:r=http://schemas.example.com/referral> <r:for> <r:prefix>http://example2.com/router</r:prefix> </r:for> <r:if/> <r:go> <r:via>http://example3.com/router</r:via> </r:go> </r:ref> Resulting in the following SOAP Header:<S:Envelope> <S:Header> <m:path xmlns:m=http://schemas.example.com/rp/ S:actor=http://schemas.example.com/soap/actor S:mustUnderstand=1> <m:action>http://example1.com/</m:action> <m:to>http://example4.com/router</m:to> <m:id>uuid:1235678-abcd-1a2b-3c4d-1a2b3c4d5e6f</m:id> <m:fwd> <m:via>http://example2.com/router</m:via> <m:via>http://example3.com/router</m:via> </m:fwd> <m:rev /> </m:path> </S:Header> <S:Body>...</S:Body> </S:Envelope> In the following example, the attacker injects a bogus routing node (using a WS-Referral service) into the routing table of the XML header but not access the message directly on the initiator/intermediary node that he/she has targeted. Example of WS-Referral based WS-Routing injection of the bogus node route:<r:ref xmlns:r=http://schemas.example.com/referral> <r:for> <r:prefix>http://example2.com/router</r:prefix> </r:for> <r:if/> <r:go> <r:via>http://evilsite1.com/router</r:via> </r:go> </r:ref> Resulting XML Routing Detour attack:<S:Envelope> <S:Header> <m:path xmlns:m=http://schemas.example.com/rp/ S:actor=http://schemas.example.com/soap/actor S:mustUnderstand=1> <m:action>http://example_0.com/</m:action> <m:to>http://example_4.com/router</m:to> <m:id>uuid:1235678-abcd-1a2b-3c4d-1a2b3c4d5e6f</m:id> <m:fwd> <m:via>http://example2.com/router</m:via> <m:via>http://evilesite1.com/router</m:via> <m:via>http://example3.com/router</m:via> </m:fwd> <m:rev /> </m:path> </S:Header> <S:Body> ... </S:Body> </S:Envelope> Thus, the attacker can route the XML message to the attacker controlled node (and access to the message contents)."
+ references: str = 'https://capec.mitre.org/data/definitions/219.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.protocol == 'HTTP' and any(d.format == 'XML' for d in target.data)
+
+class CR08(Threat):
+ """Client-Server Protocol Manipulation."""
+
+ id: str = 'CR08'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Client-Server Protocol Manipulation'
+ details: str = 'An adversary takes advantage of weaknesses in the protocol by which a client and server are communicating to perform unexpected actions. Communication protocols are necessary to transfer messages between client and server applications. Moreover, different protocols may be used for different types of interactions. For example, an authentication protocol might be used to establish the identities of the server and client while a separate messaging protocol might be used to exchange data. If there is a weakness in a protocol used by the client and server, an attacker might take advantage of this to perform various types of attacks. For example, if the attacker is able to manipulate an authentication protocol, the attacker may be able spoof other clients or servers. If the attacker is able to manipulate a messaging protocol, the may be able to read sensitive information or modify message contents. This attack is often made easier by the fact that many clients and servers support multiple protocols to perform similar roles. For example, a server might support several different authentication protocols in order to support a wide range of clients, including legacy clients. Some of the older protocols may have vulnerabilities that allow an attacker to manipulate client-server interactions.'
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The client and/or server must utilize a protocol that has a weakness allowing manipulation of the interaction.'
+ mitigations: str = 'Use strong authentication protocols.'
+ example: str = 'An adversary could exploit existing communication protocol vulnerabilities and can launch MITM attacks and gain sensitive information or spoof client/server identities.'
+ references: str = 'https://capec.mitre.org/data/definitions/220.html, http://cwe.mitre.org/data/definitions/757.html'
+
+ def _check_condition(self, target) -> bool:
+ return not target.controls.isEncrypted or target.tlsVersion < target.sink.minTLSVersion
diff --git a/pytm/threatlib/de.py b/pytm/threatlib/de.py
new file mode 100644
index 0000000..0866c68
--- /dev/null
+++ b/pytm/threatlib/de.py
@@ -0,0 +1,74 @@
+"""Data exposure threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+
+from pytm.threat import Threat
+
+class DE01(Threat):
+ """Interception."""
+
+ id: str = 'DE01'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Interception'
+ details: str = 'An adversary monitors data streams to or from the target for information gathering purposes. This attack may be undertaken to solely gather sensitive information or to support a further attack against the target. This attack pattern can involve sniffing network traffic as well as other types of data streams (e.g. radio). The adversary can attempt to initiate the establishment of a data stream, influence the nature of the data transmitted, or passively observe the communications as they unfold. In all variants of this attack, the adversary is not the intended recipient of the data stream. In contrast to other means of gathering information (e.g., targeting data leaks), the adversary must actively position himself so as to observe explicit data channels (e.g. network traffic) and read the content.'
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The target must transmit data over a medium that is accessible to the adversary.'
+ mitigations: str = 'Leverage encryption to encode the transmission of data thus making it accessible only to authorized parties.'
+ example: str = 'Adversary tries to block, manipulate, and steal communications in an attempt to achieve a desired negative technical impact.'
+ references: str = 'https://capec.mitre.org/data/definitions/117.html, http://cwe.mitre.org/data/definitions/319.html, https://cwe.mitre.org/data/definitions/299.html'
+
+ def _check_condition(self, target) -> bool:
+ return not target.controls.isEncrypted or (target.source.inScope and not target.isResponse and (not target.controls.authenticatesDestination or not target.controls.checksDestinationRevocation)) or target.tlsVersion < target.sink.minTLSVersion
+
+class DE02(Threat):
+ """Double Encoding."""
+
+ id: str = 'DE02'
+ target: tuple = (pytm.Server, pytm.Process)
+ description: str = 'Double Encoding'
+ details: str = 'The adversary utilizes a repeating of the encoding process for a set of characters (that is, character encoding a character encoding of a character) to obfuscate the payload of a particular request. This may allow the adversary to bypass filters that attempt to detect illegal characters or strings, such as those that might be used in traversal or injection attacks. Filters may be able to catch illegal encoded strings, but may not catch doubly encoded strings. For example, a dot (.), often used in path traversal attacks and therefore often blocked by filters, could be URL encoded as %2E. However, many filters recognize this encoding and would still block the request. In a double encoding, the % in the above URL encoding would be encoded again as %25, resulting in %252E which some filters might not catch, but which could still be interpreted as a dot (.) by interpreters on the target.'
+ likelihood: str = "Low"
+ severity: str = "Medium"
+ prerequisites: str = "The target's filters must fail to detect that a character has been doubly encoded but its interpreting engine must still be able to convert a doubly encoded character to an un-encoded character.The application accepts and decodes URL string request.The application performs insufficient filtering/canonicalization on the URLs."
+ mitigations: str = 'Assume all input is malicious. Create a white list that defines all valid input to the software system based on the requirements specifications. Input that does not match against the white list should not be permitted to enter into the system. Test your decoding process against malicious input. Be aware of the threat of alternative method of data encoding and obfuscation technique such as IP address encoding. When client input is required from web-based forms, avoid using the GET method to submit data, as the method causes the form data to be appended to the URL and is easily manipulated. Instead, use the POST method whenever possible. Any security checks should occur after the data has been decoded and validated as correct data format. Do not repeat decoding process, if bad character are left after decoding process, treat the data as suspicious, and fail the validation process.Refer to the RFCs to safely decode URL. Regular expression can be used to match safe URL patterns. However, that may discard valid URL requests if the regular expression is too restrictive. There are tools to scan HTTP requests to the server for valid URL such as URLScan from Microsoft (http://www.microsoft.com/technet/security/tools/urlscan.mspx).'
+ example: str = 'Double Enconding Attacks can often be used to bypass Cross Site Scripting (XSS) detection and execute XSS attacks. The use of double encouding prevents the filter from working as intended and allows the XSS to bypass dectection. This can allow an adversary to execute malicious code.'
+ references: str = 'https://capec.mitre.org/data/definitions/120.html, http://cwe.mitre.org/data/definitions/173.html, http://cwe.mitre.org/data/definitions/177.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False or target.controls.sanitizesInput is False
+
+class DE03(Threat):
+ """Sniffing Attacks."""
+
+ id: str = 'DE03'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Sniffing Attacks'
+ details: str = 'In this attack pattern, the adversary intercepts information transmitted between two third parties. The adversary must be able to observe, read, and/or hear the communication traffic, but not necessarily block the communication or change its content. The adversary may precipitate or indirectly influence the content of the observed transaction, but is never the intended recipient of the information. Any transmission medium can theoretically be sniffed if the adversary can examine the contents between the sender and recipient.'
+ severity: str = "Medium"
+ prerequisites: str = 'The target data stream must be transmitted on a medium to which the adversary has access.'
+ mitigations: str = 'Encrypt sensitive information when transmitted on insecure mediums to prevent interception.'
+ example: str = 'Attacker knows that the computer/OS/application can request new applications to install, or it periodically checks for an available update. The attacker loads the sniffer set up during Explore phase, and extracts the application code from subsequent communication. The attacker then proceeds to reverse engineer the captured code.'
+ references: str = 'https://capec.mitre.org/data/definitions/157.html, http://cwe.mitre.org/data/definitions/311.html'
+
+ def _check_condition(self, target) -> bool:
+ return (target.protocol == 'HTTP' or target.controls.isEncrypted is False) or target.usesVPN is False
+
+class DE04(Threat):
+ """Audit Log Manipulation."""
+
+ id: str = 'DE04'
+ target: tuple = (pytm.Datastore,)
+ description: str = 'Audit Log Manipulation'
+ details: str = 'The attacker injects, manipulates, deletes, or forges malicious log entries into the log file, in an attempt to mislead an audit of the log file or cover tracks of an attack. Due to either insufficient access controls of the log files or the logging mechanism, the attacker is able to perform such actions.'
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'The target host is logging the action and data of the user.The target host insufficiently protects access to the logs or logging mechanisms.'
+ mitigations: str = 'Use Principle of Least Privilege to avoid unauthorized access to log files leading to manipulation/injection on those files. Do not allow tainted data to be written in the log file without prior input validation. Whitelisting may be used to properly validate the data. Use synchronization to control the flow of execution. Use static analysis tool to identify log forging vulnerabilities. Avoid viewing logs with tools that may interpret control characters in the file, such as command-line shells.'
+ example: str = "The attacker alters the log contents either directly through manipulation or forging or indirectly through injection of specially crafted input that the target software will write to the logs. This type of attack typically follows another attack and is used to try to cover the traces of the previous attack. Insert a script into the log file such that if it is viewed using a web browser, the attacker will get a copy of the operator/administrator's cookie and will be able to gain access as that user. For example, a log file entry could contain The script itself will be invisible to anybody viewing the logs in a web browser (unless they view the source for the page)."
+ references: str = 'https://capec.mitre.org/data/definitions/268.html, https://capec.mitre.org/data/definitions/93.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False or target.controls.implementsPOLP is False
diff --git a/pytm/threatlib/do.py b/pytm/threatlib/do.py
new file mode 100644
index 0000000..b6765e3
--- /dev/null
+++ b/pytm/threatlib/do.py
@@ -0,0 +1,92 @@
+"""Denial of service threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+
+from pytm.threat import Threat
+
+class DO01(Threat):
+ """Flooding."""
+
+ id: str = 'DO01'
+ target: tuple = (pytm.Process, pytm.Server)
+ description: str = 'Flooding'
+ details: str = "An adversary consumes the resources of a target by rapidly engaging in a large number of interactions with the target. This type of attack generally exposes a weakness in rate limiting or flow. When successful this attack prevents legitimate users from accessing the service and can cause the target to crash. This attack differs from resource depletion through leaks or allocations in that the latter attacks do not rely on the volume of requests made to the target but instead focus on manipulation of the target's operations. The key factor in a flooding attack is the number of requests the adversary can make in a given period of time. The greater this number, the more likely an attack is to succeed against a given target."
+ likelihood: str = "High"
+ severity: str = "Medium"
+ prerequisites: str = 'Any target that services requests is vulnerable to this attack on some level of scale.'
+ mitigations: str = 'Ensure that protocols have specific limits of scale configured. Specify expectations for capabilities and dictate which behaviors are acceptable when resource allocation reaches limits. Uniformly throttle all requests in order to make it more difficult to consume resources more quickly than they can again be freed.'
+ example: str = 'Adversary tries to bring a network or service down by flooding it with large amounts of traffic.'
+ references: str = 'https://capec.mitre.org/data/definitions/125.html, http://cwe.mitre.org/data/definitions/404.html, http://cwe.mitre.org/data/definitions/770.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.handlesResourceConsumption is False or target.controls.isResilient is False
+
+class DO02(Threat):
+ """Excessive Allocation."""
+
+ id: str = 'DO02'
+ target: tuple = (pytm.Process, pytm.Server, pytm.Datastore, pytm.Lambda)
+ description: str = 'Excessive Allocation'
+ details: str = "An adversary causes the target to allocate excessive resources to servicing the attackers' request, thereby reducing the resources available for legitimate services and degrading or denying services. Usually, this attack focuses on memory allocation, but any finite resource on the target could be the attacked, including bandwidth, processing cycles, or other resources. This attack does not attempt to force this allocation through a large number of requests (that would be Resource Depletion through Flooding) but instead uses one or a small number of requests that are carefully formatted to force the target to allocate excessive resources to service this request(s). Often this attack takes advantage of a bug in the target to cause the target to allocate resources vastly beyond what would be needed for a normal request."
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The target must accept service requests from the attacker and the adversary must be able to control the resource allocation associated with this request to be in excess of the normal allocation. The latter is usually accomplished through the presence of a bug on the target that allows the adversary to manipulate variables used in the allocation.'
+ mitigations: str = 'Limit the amount of resources that are accessible to unprivileged users. Assume all input is malicious. Consider all potentially relevant properties when validating input. Consider uniformly throttling all requests in order to make it more difficult to consume resources more quickly than they can again be freed. Use resource-limiting settings, if possible.'
+ example: str = 'In an Integer Attack, the adversary could cause a variable that controls allocation for a request to hold an excessively large value. Excessive allocation of resources can render a service degraded or unavailable to legitimate users and can even lead to crashing of the target.'
+ references: str = 'https://capec.mitre.org/data/definitions/130.html, http://cwe.mitre.org/data/definitions/770.html, http://cwe.mitre.org/data/definitions/404.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.handlesResourceConsumption is False
+
+class DO03(Threat):
+ """XML Ping of the Death."""
+
+ id: str = 'DO03'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'XML Ping of the Death'
+ details: str = 'An attacker initiates a resource depletion attack where a large number of small XML messages are delivered at a sufficiently rapid rate to cause a denial of service or crash of the target. Transactions such as repetitive SOAP transactions can deplete resources faster than a simple flooding attack because of the additional resources used by the SOAP protocol and the resources necessary to process SOAP messages. The transactions used are immaterial as long as they cause resource utilization on the target. In other words, this is a normal flooding attack augmented by using messages that will require extra processing on the target.'
+ likelihood: str = "Low"
+ severity: str = "Medium"
+ prerequisites: str = 'The target must receive and process XML transactions.'
+ mitigations: str = 'Design: Build throttling mechanism into the resource allocation. Provide for a timeout mechanism for allocated resources whose transaction does not complete within a specified interval. Implementation: Provide for network flow control and traffic shaping to control access to the resources.'
+ example: str = 'Consider the case of attack performed against the createCustomerBillingAccount Web Service for an online store. In this case, the createCustomerBillingAccount Web Service receives a huge number of simultaneous requests, containing nonsense billing account creation information (the small XML messages). The createCustomerBillingAccount Web Services may forward the messages to other Web Services for processing. The application suffers from a high load of requests, potentially leading to a complete loss of availability the involved Web Service.'
+ references: str = 'https://capec.mitre.org/data/definitions/147.html, http://cwe.mitre.org/data/definitions/400.html, http://cwe.mitre.org/data/definitions/770.html'
+
+ def _check_condition(self, target) -> bool:
+ return any(d.format == 'XML' for d in target.data)
+
+class DO04(Threat):
+ """XML Entity Expansion."""
+
+ id: str = 'DO04'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'XML Entity Expansion'
+ details: str = "An attacker submits an XML document to a target application where the XML document uses nested entity expansion to produce an excessively large output XML. XML allows the definition of macro-like structures that can be used to simplify the creation of complex structures. However, this capability can be abused to create excessive demands on a processor's CPU and memory. A small number of nested expansions can result in an exponential growth in demands on memory."
+ likelihood: str = "High"
+ severity: str = "Medium"
+ prerequisites: str = 'This type of attack requires that the target must receive XML input but either fail to provide an upper limit for entity expansion or provide a limit that is so large that it does not preclude significant resource consumption.'
+ mitigations: str = 'Design: Use libraries and templates that minimize unfiltered input. Use methods that limit entity expansion and throw exceptions on attempted entity expansion.Implementation: Disable altogether the use of inline DTD schemas in your XML parsing objects. If must use DTD, normalize, filter and white list and parse with methods and routines that will detect entity expansion from untrusted sources.'
+ example: str = "The most common example of this type of attack is the many laughs attack (sometimes called the 'billion laughs' attack). For example: ]>&lol9; This is well formed and valid XML according to the DTD. Each entity increases the number entities by a factor of 10. The line of XML containing lol9; expands out exponentially to a message with 10^9 entities. A small message of a few KBs in size can easily be expanded into a few GB of memory in the parser. By including 3 more entities similar to the lol9 entity in the above code to the DTD, the program could expand out over a TB as there will now be 10^12 entities. Depending on the robustness of the target machine, this can lead to resource depletion, application crash, or even the execution of arbitrary code through a buffer overflow."
+ references: str = 'https://capec.mitre.org/data/definitions/197.html, http://cwe.mitre.org/data/definitions/400.html, http://cwe.mitre.org/data/definitions/770.html'
+
+ def _check_condition(self, target) -> bool:
+ return any(d.format == 'XML' for d in target.data) and target.handlesResources is False
+
+class DO05(Threat):
+ """XML Nested Payloads."""
+
+ id: str = 'DO05'
+ target: tuple = (pytm.Server,)
+ description: str = 'XML Nested Payloads'
+ details: str = "Applications often need to transform data in and out of the XML format by using an XML parser. It may be possible for an attacker to inject data that may have an adverse effect on the XML parser when it is being processed. By nesting XML data and causing this data to be continuously self-referential, an attacker can cause the XML parser to consume more resources while processing, causing excessive memory consumption and CPU utilization. An attacker's goal is to leverage parser failure to his or her advantage. In most cases this type of an attack will result in a denial of service due to an application becoming unstable, freezing, or crash. However it may be possible to cause a crash resulting in arbitrary code execution, leading to a jump from the data plane to the control plane [R.230.1]."
+ likelihood: str = "Medium"
+ severity: str = "High"
+ prerequisites: str = 'An application uses an XML parser to perform transformation on user-controllable data.An application does not perform sufficient validation to ensure that user-controllable data is safe for an XML parser.'
+ mitigations: str = 'Carefully validate and sanitize all user-controllable data prior to passing it to the XML parser routine. Ensure that the resultant data is safe to pass to the XML parser.Perform validation on canonical data.Pick a robust implementation of an XML parser.Validate XML against a valid schema or DTD prior to parsing.'
+ example: str = "An adversary crafts input data that may have an adverse effect on the operation of the XML parser when the data is parsed on the victim's system."
+ references: str = 'https://capec.mitre.org/data/definitions/230.html, http://cwe.mitre.org/data/definitions/112.html, http://cwe.mitre.org/data/definitions/770.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.usesXMLParser is True and (target.controls.validatesInput is False or target.controls.sanitizesInput is False)
diff --git a/pytm/threatlib/dr.py b/pytm/threatlib/dr.py
new file mode 100644
index 0000000..97a642c
--- /dev/null
+++ b/pytm/threatlib/dr.py
@@ -0,0 +1,22 @@
+"""DR threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+from pytm.enums import Lifetime
+from pytm.threat import Threat
+
+class DR01(Threat):
+ """Unprotected Sensitive Data."""
+
+ id: str = 'DR01'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Unprotected Sensitive Data'
+ details: str = 'An attacker can access data in transit or at rest that is not sufficiently protected. If an attacker can decrypt a stored password, it might be used to authenticate against different services.'
+ likelihood: str = "Low"
+ severity: str = "High"
+ mitigations: str = 'All data should be encrypted in transit. All PII and restricted data must be encrypted at rest. If a service is storing credentials used to authenticate users or incoming connections, it must only store hashes of them created using cryptographic functions, so it is only possible to compare them against user input, without fully decoding them. If a client is storing credentials in either files or other data store, access to them must be as restrictive as possible, including using proper file permissions, database users with restricted access or separate storage.'
+ references: str = 'https://cwe.mitre.org/data/definitions/311.html, https://cwe.mitre.org/data/definitions/312.html, https://cwe.mitre.org/data/definitions/916.html, https://cwe.mitre.org/data/definitions/653.html'
+
+ def _check_condition(self, target) -> bool:
+ return (target.hasDataLeaks() or any(d.isCredentials or d.isPII for d in target.data)) and (not target.controls.isEncrypted or (not target.isResponse and any(d.isStored and d.isDestEncryptedAtRest for d in target.data)) or (target.isResponse and any(d.isStored and d.isSourceEncryptedAtRest for d in target.data)))
diff --git a/pytm/threatlib/ds.py b/pytm/threatlib/ds.py
new file mode 100644
index 0000000..c5d24e7
--- /dev/null
+++ b/pytm/threatlib/ds.py
@@ -0,0 +1,105 @@
+"""Data store threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+
+from pytm.threat import Threat
+
+class DS01(Threat):
+ """Excavation."""
+
+ id: str = 'DS01'
+ target: tuple = (pytm.Server,)
+ description: str = 'Excavation'
+ details: str = 'An adversary actively probes the target in a manner that is designed to solicit information that could be leveraged for malicious purposes. This is achieved by exploring the target via ordinary interactions for the purpose of gathering intelligence about the target, or by sending data that is syntactically invalid or non-standard in an attempt to produce a response that contains the desired data. As a result of these interactions, the adversary is able to obtain information from the target that aids the attacker in making inferences about its security, configuration, or potential vulnerabilities. Examplar exchanges with the target may trigger unhandled exceptions or verbose error messages that reveal information like stack traces, configuration information, path information, or database design. This type of attack also includes the manipulation of query strings in a URI to produce invalid SQL queries, or by trying alternative path values in the hope that the server will return useful information.'
+ likelihood: str = "High"
+ severity: str = "Medium"
+ prerequisites: str = 'An adversary requires some way of interacting with the system.'
+ mitigations: str = "Minimize error/response output to only what is necessary for functional use or corrective language. Remove potentially sensitive information that is not necessary for the application's functionality."
+ example: str = "The adversary may collect this information through a variety of methods including active querying as well as passive observation. By exploiting weaknesses in the design or configuration of the target and its communications, an adversary is able to get the target to reveal more information than intended. Information retrieved may aid the adversary in making inferences about potential weaknesses, vulnerabilities, or techniques that assist the adversary's objectives. This information may include details regarding the configuration or capabilities of the target, clues as to the timing or nature of activities, or otherwise sensitive information. Often this sort of attack is undertaken in preparation for some other type of attack, although the collection of information by itself may in some cases be the end goal of the adversary."
+ references: str = 'https://capec.mitre.org/data/definitions/116.html, http://cwe.mitre.org/data/definitions/200.html'
+
+ def _check_condition(self, target) -> bool:
+ return (target.controls.sanitizesInput is False or target.controls.validatesInput is False) or target.controls.encodesOutput is False
+
+class DS02(Threat):
+ """Try All Common Switches."""
+
+ id: str = 'DS02'
+ target: tuple = (pytm.Lambda, pytm.Process)
+ description: str = 'Try All Common Switches'
+ details: str = 'An attacker attempts to invoke all common switches and options in the target application for the purpose of discovering weaknesses in the target. For example, in some applications, adding a --debug switch causes debugging information to be displayed, which can sometimes reveal sensitive processing or configuration information to an attacker. This attack differs from other forms of API abuse in that the attacker is blindly attempting to invoke options in the hope that one of them will work rather than specifically targeting a known option. Nonetheless, even if the attacker is familiar with the published options of a targeted application this attack method may still be fruitful as it might discover unpublicized functionality.'
+ severity: str = "Medium"
+ prerequisites: str = 'The attacker must be able to control the options or switches sent to the target.'
+ mitigations: str = 'Design: Minimize switch and option functionality to only that necessary for correct function of the command. Implementation: Remove all debug and testing options from production code.'
+ example: str = 'Adversary is able to exploit the debug switch to discover unpublicized functionality.'
+ references: str = 'https://capec.mitre.org/data/definitions/133.html, http://cwe.mitre.org/data/definitions/912.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.environment == 'Production'
+
+class DS03(Threat):
+ """Footprinting."""
+
+ id: str = 'DS03'
+ target: tuple = (pytm.Server,)
+ description: str = 'Footprinting'
+ details: str = 'An adversary engages in probing and exploration activities to identify constituents and properties of the target. Footprinting is a general term to describe a variety of information gathering techniques, often used by attackers in preparation for some attack. It consists of using tools to learn as much as possible about the composition, configuration, and security mechanisms of the targeted application, system or network. Information that might be collected during a footprinting effort could include open ports, applications and their versions, network topology, and similar information. While footprinting is not intended to be damaging (although certain activities, such as network scans, can sometimes cause disruptions to vulnerable applications inadvertently) it may often pave the way for more damaging attacks.'
+ likelihood: str = "High"
+ severity: str = "Very low"
+ prerequisites: str = 'An application must publicize identifiable information about the system or application through voluntary or involuntary means. Certain identification details of information systems are visible on communication networks (e.g., if an adversary uses a sniffer to inspect the traffic) due to their inherent structure and protocol standards. Any system or network that can be detected can be footprinted. However, some configuration choices may limit the useful information that can be collected during a footprinting attack.'
+ mitigations: str = "Keep patches up to date by installing weekly or daily if possible.Shut down unnecessary services/ports.Change default passwords by choosing strong passwords.Curtail unexpected input.Encrypt and password-protect sensitive data.Avoid including information that has the potential to identify and compromise your organization's security such as access to business plans, formulas, and proprietary documents."
+ example: str = "In this example let us look at the website http://www.example.com to get much information we can about Alice. From the website, we find that Alice also runs foobar.org. We type in www example.com into the prompt of the Name Lookup window in a tool, and our result is this IP address: 192.173.28.130 We type the domain into the Name Lookup prompt and we are given the same IP. We can safely say that example and foobar.org are hosted on the same box. But if we were to do a reverse name lookup on the IP, which domain will come up? www.example.com or foobar.org? Neither, the result is nijasvspirates.org. So nijasvspirates.org is the name of the box hosting 31337squirrel.org and foobar.org. So now that we have the IP, let's check to see if nijasvspirates is awake. We type the IP into the prompt in the Ping window. We'll set the interval between packets to 1 millisecond. We'll set the number of seconds to wait until a ping times out to 5. We'll set the ping size to 500 bytes and we'll send ten pings. Ten packets sent and ten packets received. nijasvspirates.org returned a message to my computer within an average of 0.35 seconds for every packet sent. nijasvspirates is alive. We open the Whois window and type nijasvspirates.org into the Query prompt, and whois.networksolutions.com into the Server prompt. This means we'll be asking Network Solutions to tell us everything they know about nijasvspirates.org. The result is this laundry list of info: Registrant: FooBar (nijasvspirates -DOM) p.o.box 11111 SLC, UT 84151 US Domain Name: nijasvspirates.ORG Administrative Contact, Billing Contact: Smith, John jsmith@anonymous.net FooBar p.o.box 11111 SLC, UT 84151 555-555-6103 Technical Contact: Johnson, Ken kj@fierymonkey.org fierymonkey p.o.box 11111 SLC, UT 84151 555-555-3849 Record last updated on 17-Aug-2001. Record expires on 11-Aug-2002. Record created on 11-Aug-2000. Database last updated on 12-Dec-2001 04:06:00 EST. Domain servers in listed order: NS1. fierymonkey.ORG 192.173.28.130 NS2. fierymonkey.ORG 64.192.168.80 A corner stone of footprinting is Port Scanning. Let's port scan nijasvspirates.org and see what kind of services are running on that box. We type in the nijasvspirates IP into the Host prompt of the Port Scan window. We'll start searching from port number 1, and we'll stop at the default Sub7 port, 27374. Our results are: 21 TCP ftp 22 TCP ssh SSH-1.99-OpenSSH_2.30 25 TCP smtp 53 TCP domain 80 TCP www 110 TCP pop3 111 TCP sunrpc 113 TCP ident Just by this we know that Alice is running a website and email, using POP3, SUNRPC (SUN Remote Procedure Call), and ident."
+ references: str = 'https://capec.mitre.org/data/definitions/169.html, http://cwe.mitre.org/data/definitions/200.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.isHardened is False
+
+class DS04(Threat):
+ """XSS Targeting Error Pages."""
+
+ id: str = 'DS04'
+ target: tuple = (pytm.Server,)
+ description: str = 'XSS Targeting Error Pages'
+ details: str = "An adversary distributes a link (or possibly some other query structure) with a request to a third party web server that is malformed and also contains a block of exploit code in order to have the exploit become live code in the resulting error page. When the third party web server receives the crafted request and notes the error it then creates an error message that echoes the malformed message, including the exploit. Doing this converts the exploit portion of the message into to valid language elements that are executed by the viewing browser. When a victim executes the query provided by the attacker the infected error message error message is returned including the exploit code which then runs in the victim's browser. XSS can result in execution of code as well as data leakage (e.g. session cookies can be sent to the attacker). This type of attack is especially dangerous since the exploit appears to come from the third party web server, who the victim may trust and hence be more vulnerable to deception."
+ severity: str = "Medium"
+ prerequisites: str = 'A third party web server which fails to adequately sanitize messages sent in error pages.The victim must be made to execute a query crafted by the attacker which results in the infected error report.'
+ mitigations: str = 'Design: Use libraries and templates that minimize unfiltered input.Implementation: Normalize, filter and white list any input that will be used in error messages.Implementation: The victim should configure the browser to minimize active content from untrusted sources.'
+ example: str = 'A third party web server fails to adequately sanitize messages sent in error pages. Adversary takes advantage of the data displayed in the error message.'
+ references: str = 'https://capec.mitre.org/data/definitions/198.html, http://cwe.mitre.org/data/definitions/81.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.encodesOutput is False or target.controls.validatesInput is False or target.controls.sanitizesInput is False
+
+class DS05(Threat):
+ """Lifting Sensitive Data Embedded in Cache."""
+
+ id: str = 'DS05'
+ target: tuple = (pytm.Server,)
+ description: str = 'Lifting Sensitive Data Embedded in Cache'
+ details: str = "An attacker examines a target application's cache for sensitive information. Many applications that communicate with remote entities or which perform intensive calculations utilize caches to improve efficiency. However, if the application computes or receives sensitive information and the cache is not appropriately protected, an attacker can browse the cache and retrieve this information. This can result in the disclosure of sensitive information."
+ severity: str = "Medium"
+ prerequisites: str = 'The target application must store sensitive information in a cache.The cache must be inadequately protected against attacker access.'
+ mitigations: str = "Remove potentially sensitive information from cache that is not necessary for the application's functionality."
+ example: str = 'An adversary actively probes the target in a manner that is designed to solicit information that could be leveraged for malicious purposes. This is achieved by exploring the target via ordinary interactions for the purpose of gathering intelligence about the target, or by sending data that is syntactically invalid or non-standard in an attempt to produce a response that contains the desired data. As a result of these interactions, the adversary is able to obtain information from the target that aids the attacker in making inferences about its security, configuration, or potential vulnerabilities.'
+ references: str = 'https://capec.mitre.org/data/definitions/204.html, http://cwe.mitre.org/data/definitions/524.html, http://cwe.mitre.org/data/definitions/311.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.usesCache is True
+
+class DS06(Threat):
+ """Data Leak."""
+
+ id: str = 'DS06'
+ target: tuple = (pytm.Dataflow,)
+ description: str = 'Data Leak'
+ details: str = 'An attacker can access data in transit or at rest that is not sufficiently protected. If an attacker can decrypt a stored password, it might be used to authenticate against different services.'
+ likelihood: str = "High"
+ severity: str = "Very high"
+ mitigations: str = 'All data should be encrypted in transit. All PII and restricted data must be encrypted at rest. If a service is storing credentials used to authenticate users or incoming connections, it must only store hashes of them created using cryptographic functions, so it is only possible to compare them against user input, without fully decoding them. If a client is storing credentials in either files or other data store, access to them must be as restrictive as possible, including using proper file permissions, database users with restricted access or separate storage.'
+ example: str = 'An application, which connects to a database without TLS, performs a database query in which it compares the password to a stored hash, instead of fetching the hash and comparing it locally.'
+ references: str = 'https://cwe.mitre.org/data/definitions/311.html, https://cwe.mitre.org/data/definitions/312.html, https://cwe.mitre.org/data/definitions/916.html, https://cwe.mitre.org/data/definitions/653.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.hasDataLeaks()
diff --git a/pytm/threatlib/ha.py b/pytm/threatlib/ha.py
new file mode 100644
index 0000000..3175490
--- /dev/null
+++ b/pytm/threatlib/ha.py
@@ -0,0 +1,74 @@
+"""Hardware and path threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+
+from pytm.threat import Threat
+
+class HA01(Threat):
+ """Path Traversal."""
+
+ id: str = 'HA01'
+ target: tuple = (pytm.Server,)
+ description: str = 'Path Traversal'
+ details: str = 'An adversary uses path manipulation methods to exploit insufficient input validation of a target to obtain access to data that should be not be retrievable by ordinary well-formed requests. A typical variety of this attack involves specifying a path to a desired file together with dot-dot-slash characters, resulting in the file access API or function traversing out of the intended directory structure and into the root file system. By replacing or modifying the expected path information the access function or API retrieves the file desired by the attacker. These attacks either involve the attacker providing a complete path to a targeted file or using control characters (e.g. path separators (/ or ) and/or dots (.)) to reach desired directories or files.'
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = 'The attacker must be able to control the path that is requested of the target.The target must fail to adequately sanitize incoming paths'
+ mitigations: str = 'Design: Configure the access control correctly. Design: Enforce principle of least privilege. Design: Execute programs with constrained privileges, so parent process does not open up further vulnerabilities. Ensure that all directories, temporary directories and files, and memory are executing with limited privileges to protect against remote execution. Design: Input validation. Assume that user inputs are malicious. Utilize strict type, character, and encoding enforcement. Design: Proxy communication to host, so that communications are terminated at the proxy, sanitizing the requests before forwarding to server host. 6. Design: Run server interfaces with a non-root account and/or utilize chroot jails or other configuration techniques to constrain privileges even if attacker gains some limited access to commands. Implementation: Host integrity monitoring for critical files, directories, and processes. The goal of host integrity monitoring is to be aware when a security issue has occurred so that incident response and other forensic activities can begin. Implementation: Perform input validation for all remote content, including remote and user-generated content. Implementation: Perform testing such as pen-testing and vulnerability scanning to identify directories, programs, and interfaces that grant direct access to executables. Implementation: Use indirect references rather than actual file names. Implementation: Use possible permissions on file access when developing and deploying web applications. Implementation: Validate user input by only accepting known good. Ensure all content that is delivered to client is sanitized against an acceptable content specification -- whitelisting approach.'
+ example: str = 'An example of using path traversal to attack some set of resources on a web server is to use a standard HTTP request http://example/../../../../../etc/passwd From an attacker point of view, this may be sufficient to gain access to the password file on a poorly protected system. If the attacker can list directories of critical resources then read only access is not sufficient to protect the system.'
+ references: str = 'https://capec.mitre.org/data/definitions/126.html, http://cwe.mitre.org/data/definitions/22.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False and target.controls.sanitizesInput is False
+
+class HA02(Threat):
+ """White Box Reverse Engineering."""
+
+ id: str = 'HA02'
+ target: tuple = (pytm.ExternalEntity,)
+ description: str = 'White Box Reverse Engineering'
+ details: str = 'An attacker discovers the structure, function, and composition of a type of computer software through white box analysis techniques. White box techniques involve methods which can be applied to a piece of software when an executable or some other compiled object can be directly subjected to analysis, revealing at least a portion of its machine instructions that can be observed upon execution.'
+ severity: str = "Medium"
+ prerequisites: str = 'Direct access to the object or software.'
+ mitigations: str = 'Employ code obfuscation techniques to prevent the adversary from reverse engineering the targeted entity.'
+ example: str = 'Attacker identifies client components to extract information from. These may be binary executables, class files, shared libraries (e.g., DLLs), configuration files, or other system files.'
+ references: str = 'https://capec.mitre.org/data/definitions/167.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.hasPhysicalAccess is True
+
+class HA03(Threat):
+ """Web Application Fingerprinting."""
+
+ id: str = 'HA03'
+ target: tuple = (pytm.Server,)
+ description: str = 'Web Application Fingerprinting'
+ details: str = 'An attacker sends a series of probes to a web application in order to elicit version-dependent and type-dependent behavior that assists in identifying the target. An attacker could learn information such as software versions, error pages, and response headers, variations in implementations of the HTTP protocol, directory structures, and other similar information about the targeted service. This information can then be used by an attacker to formulate a targeted attack plan. While web application fingerprinting is not intended to be damaging (although certain activities, such as network scans, can sometimes cause disruptions to vulnerable applications inadvertently) it may often pave the way for more damaging attacks.'
+ likelihood: str = "High"
+ severity: str = "Low"
+ prerequisites: str = 'Any web application can be fingerprinted. However, some configuration choices can limit the useful information an attacker may collect during a fingerprinting attack.'
+ mitigations: str = "Implementation: Obfuscate server fields of HTTP response.Implementation: Hide inner ordering of HTTP response header.Implementation: Customizing HTTP error codes such as 404 or 500.Implementation: Hide URL file extension.Implementation: Hide HTTP response header software information filed.Implementation: Hide cookie's software information filed.Implementation: Appropriately deal with error messages.Implementation: Obfuscate database type in Database API's error message."
+ example: str = 'An attacker sends malformed requests or requests of nonexistent pages to the server. Consider the following HTTP responses. Response from Apache 1.3.23$ nc apache.server.com80 GET / HTTP/3.0 HTTP/1.1 400 Bad RequestDate: Sun, 15 Jun 2003 17:12: 37 GMTServer: Apache/1.3.23Connection: closeTransfer: chunkedContent-Type: text/HTML; charset=iso-8859-1 Response from IIS 5.0$ nc iis.server.com 80GET / HTTP/3.0 HTTP/1.1 200 OKServer: Microsoft-IIS/5.0Content-Location: http://iis.example.com/Default.htmDate: Fri, 01 Jan 1999 20:14: 02 GMTContent-Type: text/HTMLAccept-Ranges: bytes Last-Modified: Fri, 01 Jan 1999 20:14: 02 GMTETag: W/e0d362a4c335be1: ae1Content-Length: 133 [R.170.2]'
+ references: str = 'https://capec.mitre.org/data/definitions/170.html, http://cwe.mitre.org/data/definitions/497.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesHeaders is False or target.controls.encodesOutput is False or target.controls.isHardened is False
+
+class HA04(Threat):
+ """Reverse Engineering."""
+
+ id: str = 'HA04'
+ target: tuple = (pytm.ExternalEntity,)
+ description: str = 'Reverse Engineering'
+ details: str = 'An adversary discovers the structure, function, and composition of an object, resource, or system by using a variety of analysis techniques to effectively determine how the analyzed entity was constructed or operates. The goal of reverse engineering is often to duplicate the function, or a part of the function, of an object in order to duplicate or back engineer some aspect of its functioning. Reverse engineering techniques can be applied to mechanical objects, electronic devices, or software, although the methodology and techniques involved in each type of analysis differ widely.'
+ likelihood: str = "Low"
+ severity: str = "Low"
+ prerequisites: str = 'Access to targeted system, resources, and information.'
+ mitigations: str = 'Employ code obfuscation techniques to prevent the adversary from reverse engineering the targeted entity.'
+ example: str = "When adversaries are reverse engineering software, methodologies fall into two broad categories, 'white box' and 'black box.' White box techniques involve methods which can be applied to a piece of software when an executable or some other compiled object can be directly subjected to analysis, revealing at least a portion of its machine instructions that can be observed upon execution. 'Black Box' methods involve interacting with the software indirectly, in the absence of the ability to measure, instrument, or analyze an executable object directly. Such analysis typically involves interacting with the software at the boundaries of where the software interfaces with a larger execution environment, such as input-output vectors, libraries, or APIs."
+ references: str = 'https://capec.mitre.org/data/definitions/188.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.hasPhysicalAccess is True
diff --git a/pytm/threatlib/inp.py b/pytm/threatlib/inp.py
new file mode 100644
index 0000000..947e1d1
--- /dev/null
+++ b/pytm/threatlib/inp.py
@@ -0,0 +1,823 @@
+"""Input validation and injection threat definitions."""
+
+from __future__ import annotations
+
+import pytm
+
+from pytm.threat import Threat
+
+class INP01(Threat):
+ """Buffer Overflow via Environment Variables."""
+
+ id: str = "INP01"
+ target: tuple = (pytm.Lambda, pytm.Process)
+ description: str = "Buffer Overflow via Environment Variables"
+ details: str = (
+ "This attack pattern involves causing a buffer overflow through manipulation "
+ "of environment variables. Once the attacker finds that they can modify an "
+ "environment variable, they may try to overflow associated buffers. This "
+ "attack leverages implicit trust often placed in environment variables."
+ )
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = (
+ "The application uses environment variables. "
+ "An environment variable exposed to the user is vulnerable to a buffer overflow. "
+ "The vulnerable environment variable uses untrusted data. "
+ "Tainted data used in the environment variables is not properly validated. "
+ "For instance boundary checking is not done before copying the input data to a buffer."
+ )
+ mitigations: str = (
+ "Do not expose environment variable to the user. "
+ "Do not use untrusted data in your environment variables. "
+ "Use a language or compiler that performs automatic bounds checking. "
+ "There are tools such as Sharefuzz which is an environment variable fuzzer for Unix "
+ "that support loading a shared library. You can use Sharefuzz to determine if you are "
+ "exposing an environment variable vulnerable to buffer overflow."
+ )
+ example: str = (
+ "Attack Example: Buffer Overflow in $HOME "
+ "A buffer overflow in sccw allows local users to gain root access via the $HOME "
+ "environmental variable. "
+ "Attack Example: Buffer Overflow in TERM "
+ "A buffer overflow in the rlogin program involves its consumption of the TERM "
+ "environmental variable."
+ )
+ references: str = (
+ "https://capec.mitre.org/data/definitions/10.html, CVE-1999-0906, CVE-1999-0046, "
+ "http://cwe.mitre.org/data/definitions/120.html, "
+ "http://cwe.mitre.org/data/definitions/119.html, "
+ "http://cwe.mitre.org/data/definitions/680.html"
+ )
+
+ def _check_condition(self, target) -> bool:
+ return (
+ target.usesEnvironmentVariables is True
+ and target.controls.sanitizesInput is False
+ and target.controls.checksInputBounds is False
+ )
+
+class INP02(Threat):
+ """Overflow Buffers."""
+
+ id: str = "INP02"
+ target: tuple = (pytm.Process,)
+ description: str = "Overflow Buffers"
+ details: str = (
+ "Buffer Overflow attacks target improper or missing bounds checking on buffer "
+ "operations, typically triggered by input injected by an adversary. As a "
+ "consequence, an adversary is able to write past the boundaries of allocated "
+ "buffer regions in memory, causing a program crash or potentially redirection "
+ "of execution as per the adversaries' choice."
+ )
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = (
+ "Targeted software performs buffer operations. "
+ "Targeted software inadequately performs bounds-checking on buffer operations. "
+ "Adversary has the capability to influence the input to buffer operations."
+ )
+ mitigations: str = (
+ "Use a language or compiler that performs automatic bounds checking. "
+ "Use secure functions not vulnerable to buffer overflow. "
+ "If you have to use dangerous functions, make sure that you do boundary checking. "
+ "Compiler-based canary mechanisms such as StackGuard, ProPolice and the "
+ "Microsoft Visual Studio /GS flag. "
+ "Unless this provides automatic bounds checking, it is not a complete solution. "
+ "Use OS-level preventative functionality. Not a complete solution. "
+ "Utilize static source code analysis tools to identify potential buffer overflow "
+ "weaknesses in the software."
+ )
+ example: str = (
+ "The most straightforward example is an application that reads in input from "
+ "the user and stores it in an internal buffer but does not check that the size "
+ "of the input data is less than or equal to the size of the buffer. "
+ "If the user enters excessive length data, the buffer may overflow leading to "
+ "the application crashing, or worse, enabling the user to cause execution of "
+ "injected code."
+ )
+ references: str = (
+ "https://capec.mitre.org/data/definitions/100.html, "
+ "http://cwe.mitre.org/data/definitions/120.html, "
+ "http://cwe.mitre.org/data/definitions/119.html, "
+ "http://cwe.mitre.org/data/definitions/680.html"
+ )
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.checksInputBounds is False
+
+class INP03(Threat):
+ """Server Side Include (SSI) Injection."""
+
+ id: str = "INP03"
+ target: tuple = (pytm.Server,)
+ description: str = "Server Side Include (SSI) Injection"
+ details: str = (
+ "An attacker can use Server Side Include (SSI) Injection to send code to a web "
+ "application that then gets executed by the web server. Doing so enables the "
+ "attacker to achieve similar results to Cross Site Scripting, viz., arbitrary "
+ "code execution and information disclosure, albeit on a more limited scale, "
+ "since the SSI directives are nowhere near as powerful as a full-fledged "
+ "scripting language. Nonetheless, the attacker can conveniently gain access to "
+ "sensitive files, such as password files, and execute shell commands."
+ )
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = (
+ "A web server that supports server side includes and has them enabled. "
+ "User controllable input that can carry include directives to the web server."
+ )
+ mitigations: str = (
+ "Set the OPTIONS IncludesNOEXEC in the global access.conf file or local "
+ ".htaccess (Apache) file to deny SSI execution in directories that do not need them. "
+ "All user controllable input must be appropriately sanitized before use in the "
+ "application. This includes omitting, or encoding, certain characters or strings "
+ "that have the potential of being interpreted as part of an SSI directive. "
+ "Server Side Includes must be enabled only if there is a strong business reason to do so."
+ )
+ example: str = (
+ "Consider a website hosted on a server that permits Server Side Includes (SSI), "
+ "such as Apache with the Options Includes directive enabled. "
+ "Whenever an error occurs, the HTTP Headers along with the entire request are "
+ "logged, which can then be displayed on a page that allows review of such errors. "
+ "A malicious user can inject SSI directives in the HTTP Headers of a request "
+ "designed to create an error. When these logs are eventually reviewed, the server "
+ "parses the SSI directives and executes them."
+ )
+ references: str = (
+ "https://capec.mitre.org/data/definitions/101.html, "
+ "http://cwe.mitre.org/data/definitions/97.html, "
+ "http://cwe.mitre.org/data/definitions/74.html, "
+ "http://cwe.mitre.org/data/definitions/20.html, "
+ "http://cwe.mitre.org/data/definitions/713.html"
+ )
+
+ def _check_condition(self, target) -> bool:
+ return (
+ target.controls.sanitizesInput is False
+ or target.controls.encodesOutput is False
+ )
+
+class INP04(Threat):
+ """HTTP Request Splitting."""
+
+ id: str = "INP04"
+ target: tuple = (pytm.Server,)
+ description: str = "HTTP Request Splitting"
+ details: str = (
+ "HTTP Request Splitting (also known as HTTP Request Smuggling) is an attack "
+ "pattern where an attacker attempts to insert additional HTTP requests in the "
+ "body of the original (enveloping) HTTP request in such a way that the browser "
+ "interprets it as one request but the web server interprets it as two."
+ )
+ likelihood: str = "Medium"
+ severity: str = "High"
+ prerequisites: str = "User-manipulateable HTTP Request headers are processed by the web server."
+ mitigations: str = (
+ "Make sure to install the latest vendor security patches available for the web server. "
+ "If possible, make use of SSL. "
+ "Install a web application firewall that has been secured against HTTP Request Splitting. "
+ "Use web servers that employ a tight HTTP parsing process."
+ )
+ example: str = (
+ "Microsoft Internet Explorer versions 5.01 SP4 and prior, 6.0 SP2 and prior, "
+ "and 7.0 contain a vulnerability that could allow an unauthenticated, remote "
+ "attacker to conduct HTTP request splitting and smuggling attacks."
+ )
+ references: str = (
+ "https://capec.mitre.org/data/definitions/105.html, "
+ "http://cwe.mitre.org/data/definitions/436.html, "
+ "http://cwe.mitre.org/data/definitions/444.html"
+ )
+
+ def _check_condition(self, target) -> bool:
+ return (
+ target.controls.validatesInput is False
+ or target.controls.validatesHeaders is False
+ ) and target.protocol == "HTTP"
+
+class INP05(Threat):
+ """Command Line Execution through SQL Injection."""
+
+ id: str = 'INP05'
+ target: tuple = (pytm.Server,)
+ description: str = 'Command Line Execution through SQL Injection'
+ details: str = 'An attacker uses standard SQL injection methods to inject data into the command line for execution. This could be done directly through misuse of directives such as MSSQL_xp_cmdshell or indirectly through injection of data into the database that would be interpreted as shell commands. Sometime later, an unscrupulous backend application (or could be part of the functionality of the same application) fetches the injected data stored in the database and uses this data as command line arguments without performing proper validation. The malicious data escapes that data plane by spawning new commands to be executed on the host.'
+ likelihood: str = "Low"
+ severity: str = "Very high"
+ prerequisites: str = 'The application does not properly validate data before storing in the databaseBackend application implicitly trusts the data stored in the databaseMalicious data is used on the backend as a command line argument'
+ mitigations: str = 'Disable MSSQL xp_cmdshell directive on the databaseProperly validate the data (syntactically and semantically) before writing it to the database. Do not implicitly trust the data stored in the database. Re-validate it prior to usage to make sure that it is safe to use in a given context (e.g. as a command line argument).'
+ example: str = 'SQL injection vulnerability in Cacti 0.8.6i and earlier, when register_argc_argv is enabled, allows remote attackers to execute arbitrary SQL commands via the (1) second or (2) third arguments to cmd.php. NOTE: this issue can be leveraged to execute arbitrary commands since the SQL query results are later used in the polling_items array and popen function'
+ references: str = 'https://capec.mitre.org/data/definitions/108.html, http://cwe.mitre.org/data/definitions/89.html, http://cwe.mitre.org/data/definitions/74.html, http://cwe.mitre.org/data/definitions/20.html, http://cwe.mitre.org/data/definitions/78.html, http://cwe.mitre.org/data/definitions/114.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False
+
+class INP06(Threat):
+ """SQL Injection through SOAP Parameter Tampering."""
+
+ id: str = 'INP06'
+ target: tuple = (pytm.Server,)
+ description: str = 'SQL Injection through SOAP Parameter Tampering'
+ details: str = 'An attacker modifies the parameters of the SOAP message that is sent from the service consumer to the service provider to initiate a SQL injection attack. On the service provider side, the SOAP message is parsed and parameters are not properly validated before being used to access a database in a way that does not use parameter binding, thus enabling the attacker to control the structure of the executed SQL query. This pattern describes a SQL injection attack with the delivery mechanism being a SOAP message.'
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = 'SOAP messages are used as a communication mechanism in the systemSOAP parameters are not properly validated at the service providerThe service provider does not properly utilize parameter binding when building SQL queries'
+ mitigations: str = "Properly validate and sanitize/reject user input at the service provider. Ensure that prepared statements or other mechanism that enables parameter binding is used when accessing the database in a way that would prevent the attackers' supplied data from controlling the structure of the executed query. At the database level, ensure that the database user used by the application in a particular context has the minimum needed privileges to the database that are needed to perform the operation. When possible, run queries against pre-generated views rather than the tables directly."
+ example: str = "An attacker uses a travel booking system that leverages SOAP communication between the client and the travel booking service. An attacker begins to tamper with the outgoing SOAP messages by modifying their parameters to include characters that would break a dynamically constructed SQL query. He notices that the system fails to respond when these malicious inputs are injected in certain parameters transferred in a SOAP message. The attacker crafts a SQL query that modifies his payment amount in the travel system's database and passes it as one of the parameters . A backend batch payment system later fetches the payment amount from the database (the modified payment amount) and sends to the credit card processor, enabling the attacker to purchase the airfare at a lower price. An attacker needs to have some knowledge of the system's database, perhaps by exploiting another weakness that results in information disclosure."
+ references: str = 'https://capec.mitre.org/data/definitions/110.html, http://cwe.mitre.org/data/definitions/89.html, http://cwe.mitre.org/data/definitions/20.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.protocol == 'SOAP' and (target.controls.sanitizesInput is False or target.controls.validatesInput is False)
+
+class INP07(Threat):
+ """Buffer Manipulation."""
+
+ id: str = 'INP07'
+ target: tuple = (pytm.Process,)
+ description: str = 'Buffer Manipulation'
+ details: str = "An adversary manipulates an application's interaction with a buffer in an attempt to read or modify data they shouldn't have access to. Buffer attacks are distinguished in that it is the buffer space itself that is the target of the attack rather than any code responsible for interpreting the content of the buffer. In virtually all buffer attacks the content that is placed in the buffer is immaterial. Instead, most buffer attacks involve retrieving or providing more input than can be stored in the allocated buffer, resulting in the reading or overwriting of other unintended program memory."
+ likelihood: str = "High"
+ severity: str = "Very high"
+ prerequisites: str = 'The adversary must identify a programmatic means for interacting with a buffer, such as vulnerable C code, and be able to provide input to this interaction.'
+ mitigations: str = 'To help protect an application from buffer manipulation attacks, a number of potential mitigations can be leveraged. Before starting the development of the application, consider using a code language (e.g., Java) or compiler that limits the ability of developers to act beyond the bounds of a buffer. If the chosen language is susceptible to buffer related issues (e.g., C) then consider using secure functions instead of those vulnerable to buffer manipulations. If a potentially dangerous function must be used, make sure that proper boundary checking is performed. Additionally, there are often a number of compiler-based mechanisms (e.g., StackGuard, ProPolice and the Microsoft Visual Studio /GS flag) that can help identify and protect against potential buffer issues. Finally, there may be operating system level preventative functionality that can be applied.'
+ example: str = 'Attacker identifies programmatic means for interacting with a buffer, such as vulnerable C code, and is able to provide input to this interaction.'
+ references: str = 'https://capec.mitre.org/data/definitions/123.html, http://cwe.mitre.org/data/definitions/119.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.usesSecureFunctions is False
+
+class INP08(Threat):
+ """Format String Injection."""
+
+ id: str = 'INP08'
+ target: tuple = (pytm.Lambda, pytm.Process, pytm.Server)
+ description: str = 'Format String Injection'
+ details: str = 'An adversary includes formatting characters in a string input field on the target application. Most applications assume that users will provide static text and may respond unpredictably to the presence of formatting character. For example, in certain functions of the C programming languages such as printf, the formatting character %s will print the contents of a memory location expecting this location to identify a string and the formatting character %n prints the number of DWORD written in the memory. An adversary can use this to read or write to memory locations or files, or simply to manipulate the value of the resulting text in unexpected ways. Reading or writing memory may result in program crashes and writing memory could result in the execution of arbitrary code if the adversary can write to the program stack.'
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'The target application must accept a strings as user input, fail to sanitize string formatting characters in the user input, and process this string using functions that interpret string formatting characters.'
+ mitigations: str = 'Limit the usage of formatting string functions. Strong input validation - All user-controllable input must be validated and filtered for illegal formatting characters.'
+ example: str = 'Untrusted search path vulnerability in the add_filename_to_string function in intl/gettext/loadmsgcat.c for Elinks 0.11.1 allows local users to cause Elinks to use an untrusted gettext message catalog (.po file) in a ../po directory, which can be leveraged to conduct format string attacks.'
+ references: str = 'https://capec.mitre.org/data/definitions/135.html, http://cwe.mitre.org/data/definitions/134.html, http://cwe.mitre.org/data/definitions/133.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False or target.controls.sanitizesInput is False
+
+class INP09(Threat):
+ """LDAP Injection."""
+
+ id: str = 'INP09'
+ target: tuple = (pytm.Server,)
+ description: str = 'LDAP Injection'
+ details: str = 'An attacker manipulates or crafts an LDAP query for the purpose of undermining the security of the target. Some applications use user input to create LDAP queries that are processed by an LDAP server. For example, a user might provide their username during authentication and the username might be inserted in an LDAP query during the authentication process. An attacker could use this input to inject additional commands into an LDAP query that could disclose sensitive information. For example, entering a * in the aforementioned query might return information about all users on the system. This attack is very similar to an SQL injection attack in that it manipulates a query to gather additional information or coerce a particular return value.'
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'The target application must accept a string as user input, fail to sanitize characters that have a special meaning in LDAP queries in the user input, and insert the user-supplied string in an LDAP query which is then processed.'
+ mitigations: str = 'Strong input validation - All user-controllable input must be validated and filtered for illegal characters as well as LDAP content. Use of custom error pages - Attackers can glean information about the nature of queries from descriptive error messages. Input validation must be coupled with customized error pages that inform about an error without disclosing information about the LDAP or application.'
+ example: str = 'PowerDNS before 2.9.18, when running with an LDAP backend, does not properly escape LDAP queries, which allows remote attackers to cause a denial of service (failure to answer ldap questions) and possibly conduct an LDAP injection attack.'
+ references: str = 'https://capec.mitre.org/data/definitions/136.html, http://cwe.mitre.org/data/definitions/77.html, http://cwe.mitre.org/data/definitions/90.html, http://cwe.mitre.org/data/definitions/20.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False
+
+class INP10(Threat):
+ """Parameter Injection."""
+
+ id: str = 'INP10'
+ target: tuple = (pytm.Server,)
+ description: str = 'Parameter Injection'
+ details: str = 'An adversary manipulates the content of request parameters for the purpose of undermining the security of the target. Some parameter encodings use text characters as separators. For example, parameters in a HTTP GET message are encoded as name-value pairs separated by an ampersand (&). If an attacker can supply text strings that are used to fill in these parameters, then they can inject special characters used in the encoding scheme to add or modify parameters. For example, if user input is fed directly into an HTTP GET request and the user provides the value myInput&new_param=myValue, then the input parameter is set to myInput, but a new parameter (new_param) is also added with a value of myValue. This can significantly change the meaning of the query that is processed by the server. Any encoding scheme where parameters are identified and separated by text characters is potentially vulnerable to this attack - the HTTP GET encoding used above is just one example.'
+ likelihood: str = "Medium"
+ severity: str = "Medium"
+ prerequisites: str = 'The target application must use a parameter encoding where separators and parameter identifiers are expressed in regular text.The target application must accept a string as user input, fail to sanitize characters that have a special meaning in the parameter encoding, and insert the user-supplied string in an encoding which is then processed.'
+ mitigations: str = 'Implement an audit log written to a separate host. In the event of a compromise, the audit log may be able to provide evidence and details of the compromise. Treat all user input as untrusted data that must be validated before use.'
+ example: str = 'The target application accepts a string as user input, fails to sanitize characters that have a special meaning in the parameter encoding, and inserts the user-supplied string in an encoding which is then processed.'
+ references: str = 'https://capec.mitre.org/data/definitions/137.html, http://cwe.mitre.org/data/definitions/88.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False
+
+class INP11(Threat):
+ """Relative Path Traversal."""
+
+ id: str = 'INP11'
+ target: tuple = (pytm.Server,)
+ description: str = 'Relative Path Traversal'
+ details: str = "An attacker exploits a weakness in input validation on the target by supplying a specially constructed path utilizing dot and slash characters for the purpose of obtaining access to arbitrary files or resources. An attacker modifies a known path on the target in order to reach material that is not available through intended channels. These attacks normally involve adding additional path separators (/ or ) and/or dots (.), or encodings thereof, in various combinations in order to reach parent directories or entirely separate trees of the target's directory structure."
+ likelihood: str = "High"
+ severity: str = "High"
+ prerequisites: str = 'The target application must accept a string as user input, fail to sanitize combinations of characters in the input that have a special meaning in the context of path navigation, and insert the user-supplied string into path navigation commands.'
+ mitigations: str = 'Design: Input validation. Assume that user inputs are malicious. Utilize strict type, character, and encoding enforcement. Implementation: Perform input validation for all remote content, including remote and user-generated content. Implementation: Validate user input by only accepting known good. Ensure all content that is delivered to client is sanitized against an acceptable content specification -- whitelisting approach. Implementation: Prefer working without user input when using file system calls. Implementation: Use indirect references rather than actual file names. Implementation: Use possible permissions on file access when developing and deploying web applications.'
+ example: str = "The attacker uses relative path traversal to access files in the application. This is an example of accessing user's password file. http://www.example.com/getProfile.jsp?filename=../../../../etc/passwd However, the target application employs regular expressions to make sure no relative path sequences are being passed through the application to the web page. The application would replace all matches from this regex with the empty string. Then an attacker creates special payloads to bypass this filter: http://www.example.com/getProfile.jsp?filename=%2e%2e/%2e%2e/%2e%2e/%2e%2e /etc/passwd When the application gets this input string, it will be the desired vector by the attacker."
+ references: str = 'https://capec.mitre.org/data/definitions/139.html, http://cwe.mitre.org/data/definitions/23.html'
+
+ def _check_condition(self, target) -> bool:
+ return target.controls.validatesInput is False or target.controls.sanitizesInput is False
+
+class INP12(Threat):
+ """Client-side Injection-induced Buffer Overflow."""
+
+ id: str = 'INP12'
+ target: tuple = (pytm.Lambda, pytm.Process)
+ description: str = 'Client-side Injection-induced Buffer Overflow'
+ details: str = 'This type of attack exploits a buffer overflow vulnerability in targeted client software through injection of malicious content from a custom-built hostile service.'
+ likelihood: str = "Medium"
+ severity: str = "High"
+ prerequisites: str = 'The targeted client software communicates with an external server.The targeted client software has a buffer overflow vulnerability.'
+ mitigations: str = 'The client software should not install untrusted code from a non-authenticated server. The client software should have the latest patches and should be audited for vulnerabilities before being used to communicate with potentially hostile servers. Perform input validation for length of buffer inputs. Use a language or compiler that performs automatic bounds checking. Use an abstraction library to abstract away risky APIs. Not a complete solution. Compiler-based canary mechanisms such as StackGuard, ProPolice and the Microsoft Visual Studio /GS flag. Unless this provides automatic bounds checking, it is not a complete solution. Ensure all buffer uses are consistently bounds-checked. Use OS-level preventative functionality. Not a complete solution.'
+ example: str = 'Attack Example: Buffer Overflow in Internet Explorer 4.0 Via EMBED Tag Authors often use EMBED tags in HTML documents. For example