diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d9d67d..1f8a6e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,33 @@ below). ## [Unreleased] +### BREAKING + +- **`Agent` is now an `LLM` with `hasAgentCapabilities=True`.** It used to be + a separate `Asset` subclass. `Agent("x")` and + `LLM("x", hasAgentCapabilities=True)` are now equivalent and match the same + threats. Existing `Agent` elements therefore inherit the `LLM` attributes + and their defaults (`isThirdParty`, `processesUntrustedInput` and + `hasSystemPrompt` are `True`), so they start matching `LLM` threats: with + default attributes that means `LLM01` and `LLM07`. `usesExternalTools` and + `validatesToolLaunchConfig` moved from `Agent` to `LLM`, and `LLM09` now + targets `LLM` so it also applies to an `LLM` that uses external tools. + +### Added + +- Thirteen threats, `AG01` to `AG13`, derived from the OWASP Top 10 for + Agentic Applications 2026 (ASI01 to ASI08): goal hijack via untrusted + content, over-privileged or unbounded tool use, tool invocation without + per-action authorization, confused deputy between agents, credential + inheritance across delegation, unverified agentic components, impersonated + or tampered third-party endpoints, model output executed without + sanitization or sandbox, memory and context poisoning, cross-session or + cross-tenant memory bleed, spoofed or tampered inter-agent messages, + inter-agent message replay, and agent feedback loops without a circuit + breaker. Each applies only where an `LLM` with `hasAgentCapabilities=True` + is involved. ASI09 (human-agent trust) and ASI10 (rogue agents) are not + covered; they need attributes the model does not have yet. + ## [1.4.1] - 2026-10-31 ### BREAKING diff --git a/README.md b/README.md index eb46012..1783ed9 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,8 @@ The *stale_days* argument tries to determine how far apart in days the model scr Currently available elements are: TM, Element, Server, ExternalEntity, Datastore, Actor, Process, Dataflow, Boundary, Lambda, LLM and Agent. +An `Agent` is an `LLM` whose `hasAgentCapabilities` is `True`: `Agent("Planner")` and `LLM("Planner", hasAgentCapabilities=True)` describe the same element and match the same threats. The agentic threats (`AG01` to `AG13`, based on the [OWASP Top 10 for Agentic Applications 2026](https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/)) apply wherever an `LLM` with that flag is involved. + The available properties of an element can be listed by using `--describe` followed by the name of an element: ```text @@ -615,6 +617,19 @@ LLM07 - Jailbreaking and Safety Bypass LLM08 - Sensitive Information Disclosure Through Output LLM09 - Untrusted Tool Launch Configuration LLM10 - Personal Data Retained by Third-Party LLM Provider +AG01 - Agent Goal Hijack via Untrusted Content +AG02 - Over-Privileged or Unbounded Tool Use +AG03 - Tool Invocation Without Per-Action Authorization +AG04 - Confused Deputy Between Agents +AG05 - Credential Inheritance Across Agent Delegation +AG06 - Unverified Agentic Components +AG07 - Impersonated or Tampered Third-Party Tool or Agent Endpoint +AG08 - Model Output Executed Without Sanitization or Sandbox +AG09 - Agent Memory and Context Poisoning +AG10 - Cross-Session or Cross-Tenant Memory Bleed +AG11 - Spoofed or Tampered Inter-Agent Message +AG12 - Inter-Agent Message Replay +AG13 - Agent Feedback Loop Without Circuit Breaker ``` diff --git a/pytm/asset.py b/pytm/asset.py index 9538b83..f374734 100644 --- a/pytm/asset.py +++ b/pytm/asset.py @@ -287,56 +287,6 @@ def __init__(self, name: str = None, **data): super().__init__(name, **data) -class Agent(Asset): - """An agentic harness that can reason with an LLM and invoke tools. - - Attributes: - port (int): Default TCP port for incoming data flows - protocol (str): Default network protocol for incoming data flows - data (DataSet): pytm.Data object(s) in incoming data flows - inputs (List[Dataflow]): Incoming Dataflows - outputs (List[Dataflow]): Outgoing Dataflows - onAWS (bool): Is this asset on AWS? - handlesResources (bool): Does this asset handle resources? - usesEnvironmentVariables (bool): Does this asset use environment variables? - OS (str): Operating system - usesExternalTools (bool): Does this agent use external tools or servers? - validatesToolLaunchConfig (bool): Does this agent validate tool/server launch configuration before execution? - """ - - usesExternalTools: bool = Field( - default=False, description="Does this agent use external tools or servers?" - ) - validatesToolLaunchConfig: bool = Field( - default=False, - description="Does this agent validate tool/server launch configuration before execution?", - ) - - def __init__(self, name: str = None, **data): - """Initialize an Agent. - - Args: - name (str): Name of the agent. - **data: Optional agent properties: - - port (int): Default TCP port for incoming data flows - - protocol (str): Default network protocol for incoming data flows - - data (DataSet): pytm.Data object(s) in incoming data flows - - inputs (List[Dataflow]): Incoming Dataflows - - outputs (List[Dataflow]): Outgoing Dataflows - - onAWS (bool): Is this asset on AWS? - - handlesResources (bool): Does this asset handle resources? - - usesEnvironmentVariables (bool): Does this asset use environment variables? - - OS (str): Operating system - - usesExternalTools (bool): Does this agent use external tools or servers? - - validatesToolLaunchConfig (bool): Does this agent validate tool/server launch configuration before execution? - """ - super().__init__(name, **data) - - def _shape(self) -> str: - """Get shape for DFD representation.""" - return "hexagon" - - class LLM(Asset): """A Large Language Model element, either third-party or self-hosted. @@ -362,6 +312,8 @@ class LLM(Asset): processesUntrustedInput (bool): Does this LLM process untrusted input? hasRAG (bool): Does this LLM use retrieval-augmented generation? hasFineTuning (bool): Has this LLM been fine-tuned? + usesExternalTools (bool): Does this LLM use external tools or servers? + validatesToolLaunchConfig (bool): Does this LLM validate tool/server launch configuration before execution? """ isThirdParty: bool = Field( @@ -396,6 +348,13 @@ class LLM(Asset): hasFineTuning: bool = Field( default=False, description="Has this LLM been fine-tuned?" ) + usesExternalTools: bool = Field( + default=False, description="Does this LLM use external tools or servers?" + ) + validatesToolLaunchConfig: bool = Field( + default=False, + description="Does this LLM validate tool/server launch configuration before execution?", + ) def __init__(self, name: str = None, **data): """Initialize an LLM. @@ -424,9 +383,28 @@ def __init__(self, name: str = None, **data): - processesUntrustedInput (bool): Does this LLM process untrusted input? - hasRAG (bool): Does this LLM use retrieval-augmented generation? - hasFineTuning (bool): Has this LLM been fine-tuned? + - usesExternalTools (bool): Does this LLM use external tools or servers? + - validatesToolLaunchConfig (bool): Does this LLM validate tool/server launch configuration before execution? """ super().__init__(name, **data) def _shape(self) -> str: """Get shape for DFD representation.""" return "hexagon" + + +class Agent(LLM): + """An agentic harness that can reason with an LLM and invoke tools. + + An agent is modelled as an :class:`LLM` whose ``hasAgentCapabilities`` is + True, so ``Agent("x")`` and ``LLM("x", hasAgentCapabilities=True)`` + describe the same thing and match the same threats. This class adds no + attributes of its own; it only flips that default. + + Attributes: + hasAgentCapabilities (bool): Does this LLM have agent capabilities? Defaults to True. + """ + + hasAgentCapabilities: bool = Field( + default=True, description="Does this LLM have agent capabilities?" + ) diff --git a/pytm/threatlib/threats.json b/pytm/threatlib/threats.json index 0ef43bc..743dd9c 100644 --- a/pytm/threatlib/threats.json +++ b/pytm/threatlib/threats.json @@ -1727,7 +1727,7 @@ { "SID": "LLM09", "target": [ - "Agent" + "LLM" ], "description": "Untrusted Tool Launch Configuration", "details": "An agentic harness that launches external tools or local servers from untrusted or weakly validated configuration can treat setup metadata as execution authority. In local tool integrations, including MCP-style stdio servers, command and argument configuration may determine which local process is started.", @@ -1753,5 +1753,200 @@ "mitigations": "Use a provider setting or contract that gives zero data retention, or a retention period no longer than the controller needs. Put a data processing agreement in place that covers retention, deletion and return of data. Remove or pseudonymise personal data before it is sent to the provider. Prefer a self-hosted model for data that cannot leave the organisation.", "example": "A support tool sends customer messages to a hosted LLM API. The provider stores every request for a fixed period for abuse monitoring. The company's own retention policy is shorter, so customer messages outlive the period the company can justify.", "references": "https://owasp.org/www-project-top-10-for-large-language-model-applications/, https://eur-lex.europa.eu/eli/reg/2016/679/oj (GDPR Art. 5(1)(e) storage limitation, Art. 28(3) processor contract), https://cwe.mitre.org/data/definitions/359.html" + }, + { + "SID": "AG01", + "target": [ + "LLM" + ], + "description": "Agent Goal Hijack via Untrusted Content", + "details": "An agent cannot reliably separate instructions from content. When the same agent reads content an attacker can influence, holds or retrieves sensitive data, and has a path out of the system, instructions planted in that content can redirect its goals and drive exfiltration or unauthorized actions without any user interaction.", + "Likelihood Of Attack": "High", + "severity": "Very High", + "condition": "target.hasAgentCapabilities is True and target.processesUntrustedInput is True and target.hasContentFiltering is False and (any((f.source.oneOf(ExternalEntity) or f.source.inScope is False) for f in target.inputs) or any(f.response is not None and (f.sink.oneOf(ExternalEntity) or f.sink.inScope is False) for f in target.outputs)) and (target.processesPersonalData is True or any(d.isPII or d.isCredentials or d.classification >= Classification.SENSITIVE for f in target.inputs for d in f.data) or any(d.isPII or d.isCredentials or d.classification >= Classification.SENSITIVE for f in target.outputs if f.response is not None for d in f.response.data) or any(f.source.oneOf(Datastore) and (f.source.storesPII or f.source.storesSensitiveData) for f in target.inputs) or any(f.sink.oneOf(Datastore) and (f.sink.storesPII or f.sink.storesSensitiveData) for f in target.outputs)) and any((f.sink.oneOf(ExternalEntity) or f.sink.inScope is False) for f in target.outputs)", + "prerequisites": "The agent ingests content from an external or out-of-scope source (web, email, documents, third-party APIs, peer agents), either pushed to it or returned in response to its own request. The agent processes personal data, receives PII, credentials or data classified SENSITIVE or above, or is connected to a datastore holding such data. The agent has an outbound flow to an external or out-of-scope element.", + "mitigations": "Remove one of the three legs: isolate untrusted content from privileged context, strip sensitive data from the agent's reach, or enforce an egress allowlist. Treat all retrieved natural-language content as untrusted and filter it before it reaches planning (hasContentFiltering). Require human approval for goal-changing or high-impact actions. Lock and version system prompts. Log goal state and alert on deviation.", + "example": "A crafted email is read by a mail assistant with access to the user's files. Hidden instructions cause it to embed file contents in a request to an attacker-controlled URL.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI01, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/, LLM01:2025 Prompt Injection, https://genai.owasp.org/llmrisk/llm01-prompt-injection/" + }, + { + "SID": "AG02", + "target": [ + "LLM" + ], + "description": "Over-Privileged or Unbounded Tool Use", + "details": "An agent that operates within its granted privileges can still apply a legitimate tool in a destructive, costly or data-leaking way when tool scopes are wider than the task needs or when nothing caps invocation rate and cost.", + "Likelihood Of Attack": "High", + "severity": "High", + "condition": "target.hasAgentCapabilities is True and target.usesExternalTools is True and (target.controls.implementsPOLP is False or target.controls.handlesResourceConsumption is False)", + "prerequisites": "The agent can invoke external tools or servers. Tool permissions are not scoped per tool, or there is no budget, rate limit or loop bound on tool invocation.", + "mitigations": "Define per-tool least-privilege profiles (scopes, data access, egress allowlist). Prefer read-only access. Apply cost, rate and token budgets with automatic throttling. Put a policy enforcement point between planner output and tool execution. Keep immutable logs of tool calls and watch for unusual tool chains.", + "example": "An email summarizer is wired to a mail tool that can also send and delete. A planner loop calls a paid API until the bill spikes.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI02, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/, LLM06:2025 Excessive Agency" + }, + { + "SID": "AG03", + "target": [ + "Dataflow" + ], + "description": "Tool Invocation Without Per-Action Authorization", + "details": "A tool, API or datastore that executes whatever an agent sends, without checking that the specific action is authorized for the originating user and task, turns any successful manipulation of the agent into a privileged operation.", + "Likelihood Of Attack": "High", + "severity": "High", + "condition": "target.isResponse is False and target.source.oneOf(LLM) and target.source.hasAgentCapabilities is True and target.sink.oneOf(Server, Lambda, Process, Datastore) and target.controls.authorizesSource is False", + "prerequisites": "An agent invokes a tool, service or datastore. The call is accepted on the strength of the agent's standing credentials with no per-action policy decision.", + "mitigations": "Authorize each invocation against a central policy engine using subject, resource, purpose and duration. Issue short-lived, task-scoped credentials. Require human confirmation with a dry-run preview for destructive or irreversible actions.", + "example": "A customer service agent meant to read order history calls the refund endpoint because the tool token covers the whole financial API.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI02, ASI03, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/" + }, + { + "SID": "AG04", + "target": [ + "Dataflow" + ], + "description": "Confused Deputy Between Agents", + "details": "Agents tend to trust requests from peer agents by default. A low-privilege or compromised agent can relay instructions to a higher-privilege agent, which executes them with its own permissions without re-checking the original user's intent.", + "Likelihood Of Attack": "Medium", + "severity": "Very High", + "condition": "target.isResponse is False and target.source.oneOf(LLM) and target.source.hasAgentCapabilities is True and target.sink.oneOf(LLM) and target.sink.hasAgentCapabilities is True and target.controls.authorizesSource is False", + "prerequisites": "Two or more agents exchange tasks or instructions. The receiving agent does not authorize the request against the originating principal and intent.", + "mitigations": "Re-validate original user intent at every delegation hop. Bind delegated tokens to a signed intent (subject, audience, purpose, session). Do not allow privilege inheritance across agents by default. Monitor for transitive permission gain along delegation chains.", + "example": "A mail-sorting agent forwards an attacker's instruction to a finance agent, which processes the payment because the request came from an internal agent.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI03, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/, https://css.csail.mit.edu/6.858/2015/readings/confused-deputy.html" + }, + { + "SID": "AG05", + "target": [ + "Dataflow" + ], + "description": "Credential Inheritance Across Agent Delegation", + "details": "Credentials passed from an agent into a model context or to another agent outlive the task they were meant for. They can be cached in memory, replayed by a later session, or used by the receiving agent well beyond the intended scope.", + "Likelihood Of Attack": "Medium", + "severity": "High", + "condition": "target.source.oneOf(LLM) and target.source.hasAgentCapabilities is True and target.sink.oneOf(LLM) and ((target.sink.hasAgentCapabilities is False and any(d.isCredentials for d in target.data)) or (target.sink.hasAgentCapabilities is True and any(d.isCredentials and d.credentialsLife != Lifetime.SHORT for d in target.data)))", + "prerequisites": "An agent sends credentials to a non-agentic LLM, or sends credentials that are not short-lived to another agent.", + "mitigations": "Keep secrets out of model context; let the harness or a broker attach them at call time. Delegate with short-lived, narrowly scoped, audience-bound tokens. Wipe session state between tasks and users. Give each agent its own managed identity.", + "example": "An IT agent caches SSH credentials during a patch task. A later, non-admin session prompts it to reuse them to create an account.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI03, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/" + }, + { + "SID": "AG06", + "target": [ + "LLM" + ], + "description": "Unverified Agentic Components", + "details": "Tools, MCP servers, prompt templates, agent cards and plugins are often resolved and loaded at run time. Without signature or provenance checks, a tampered, typosquatted or malicious component enters the agent's execution chain with the agent's own authority.", + "Likelihood Of Attack": "Medium", + "severity": "High", + "condition": "target.hasAgentCapabilities is True and target.usesExternalTools is True and target.controls.usesCodeSigning is False", + "prerequisites": "The agent loads third-party tools, servers, prompts or peer agents. Their origin and integrity are not verified before activation.", + "mitigations": "Sign and attest manifests, prompts and tool definitions. Allowlist and pin by content hash and version. Use curated registries and reject unsigned components. Maintain an SBOM/AIBOM. Re-verify at run time and keep a kill switch to revoke a tool or prompt across deployments.", + "example": "A package impersonating a legitimate mail MCP server is installed by an agent and silently copies every outgoing message to the attacker.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI04, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/, LLM03:2025 Supply Chain" + }, + { + "SID": "AG07", + "target": [ + "Dataflow" + ], + "description": "Impersonated or Tampered Third-Party Tool or Agent Endpoint", + "details": "Descriptors, schemas and results that reach an agent from an external tool server, registry or peer agent are interpreted as trusted guidance. If the agent does not verify which endpoint it is talking to, or the exchange can be modified, an attacker can advertise false capabilities, hide instructions in metadata, or route sensitive requests through infrastructure they control.", + "Likelihood Of Attack": "Medium", + "severity": "High", + "condition": "target.isResponse is False and ((target.source.oneOf(LLM) and target.source.hasAgentCapabilities is True and (target.sink.oneOf(ExternalEntity) or target.sink.inScope is False) and (target.controls.authenticatesDestination is False or target.controls.providesIntegrity is False)) or (target.sink.oneOf(LLM) and target.sink.hasAgentCapabilities is True and (target.source.oneOf(ExternalEntity) or target.source.inScope is False) and (target.controls.authenticatesSource is False or target.controls.providesIntegrity is False)))", + "prerequisites": "An agent calls an external or out-of-scope tool server, registry or peer agent without authenticating it, or accepts requests from one without authenticating the source. The exchange is not integrity-protected.", + "mitigations": "Mutual authentication with pinned identities for tool servers and peer agents. Signed descriptors and agent cards. Fully qualified, version-pinned tool names; fail closed on ambiguous resolution. No open registration in agent registries.", + "example": "A rogue peer advertises inflated capabilities in its agent card, wins task routing, and reads or alters every request that passes through it.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI04, ASI02, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/" + }, + { + "SID": "AG08", + "target": [ + "Dataflow" + ], + "description": "Model Output Executed Without Sanitization or Sandbox", + "details": "Text produced by a model becomes executable behavior when an agent passes it to a shell, interpreter, function runtime or deserializer. Generated in real time, it bypasses code review and static controls, and can lead to host or container compromise.", + "Likelihood Of Attack": "High", + "severity": "Very High", + "condition": "target.isResponse is False and target.source.oneOf(LLM) and target.source.hasAgentCapabilities is True and target.sink.oneOf(Process, Lambda) and (target.sink.controls.sanitizesInput is False or target.sink.controls.isHardened is False)", + "prerequisites": "An agent sends output to a process or function that executes it. The executor does not sanitize the input, or does not run in a hardened, sandboxed environment.", + "mitigations": "Separate generation from execution with a validation gate. Run generated code in a sandboxed container with no root, a dedicated working directory and restricted network. Ban eval on model output. Static-scan before execution. Keep an allowlist for auto-execution under version control and require approval for anything else.", + "example": "A user asks a coding agent to process a file whose name carries a chained shell command. The agent passes the string to its shell tool and the command runs.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI05, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/, LLM05:2025 Improper Output Handling" + }, + { + "SID": "AG09", + "target": [ + "Datastore" + ], + "description": "Agent Memory and Context Poisoning", + "details": "Content written to a store that agents later retrieve (conversation memory, summaries, embeddings, RAG corpora) persists across sessions. An attacker who gets data into the store biases future reasoning, planning and tool selection long after the original interaction ended.", + "Likelihood Of Attack": "High", + "severity": "High", + "condition": "target.controls.validatesInput is False and (any(f.sink.oneOf(LLM) and f.sink.hasAgentCapabilities is True for f in target.outputs) or any(f.source.oneOf(LLM) and f.source.hasAgentCapabilities is True for f in target.inputs))", + "prerequisites": "An agent reads from or writes to the datastore. Writes are not validated before commit.", + "mitigations": "Scan memory writes for instructions and sensitive content before commit. Record provenance and trust for each entry. Expire or decay unverified entries. Do not re-ingest the agent's own output into trusted memory. Keep snapshots and support rollback and quarantine.", + "example": "An attacker repeats a false refund policy across chats until the assistant stores it. Other agents sharing the memory then apply it.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI06, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/, LLM04:2025 Data and Model Poisoning, LLM08:2025 Vector and Embedding Weaknesses" + }, + { + "SID": "AG10", + "target": [ + "Datastore" + ], + "description": "Cross-Session or Cross-Tenant Memory Bleed", + "details": "A memory or vector store shared across users, tenants or agents without per-principal access control lets one session retrieve data that belongs to another, either by crafted near-duplicate content or by prompting the agent to recall cached material.", + "Likelihood Of Attack": "Medium", + "severity": "High", + "condition": "target.isShared is True and (target.storesPII is True or target.storesSensitiveData is True) and target.controls.hasAccessControl is False and (any(f.sink.oneOf(LLM) and f.sink.hasAgentCapabilities is True for f in target.outputs) or any(f.source.oneOf(LLM) and f.source.hasAgentCapabilities is True for f in target.inputs))", + "prerequisites": "The datastore is shared, holds PII or sensitive data, is reachable by an agent, and does not enforce access control per user, tenant or task.", + "mitigations": "Per-tenant namespaces and per-session segmentation. Enforce access control at retrieval time, bound to the requesting principal and task. Minimize retention by sensitivity. Clear session memory between users.", + "example": "An attacker seeds content similar to another tenant's documents; loose namespace filters return the other tenant's chunk on similarity.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI06, ASI03, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/" + }, + { + "SID": "AG11", + "target": [ + "Dataflow" + ], + "description": "Spoofed or Tampered Inter-Agent Message", + "details": "Messages between agents that are not encrypted, mutually authenticated and integrity-protected can be intercepted, forged or altered in transit. Because the payload is natural language that the receiver will interpret, a modified message changes goals and decisions while the exchange still looks normal.", + "Likelihood Of Attack": "Medium", + "severity": "High", + "condition": "target.source.oneOf(LLM) and target.source.hasAgentCapabilities is True and target.sink.oneOf(LLM) and target.sink.hasAgentCapabilities is True and (target.controls.isEncrypted is False or target.controls.authenticatesSource is False or target.controls.providesIntegrity is False)", + "prerequisites": "Agents communicate over a network channel, message bus or shared protocol (A2A, MCP, HTTP, gRPC). Transport encryption, source authentication or message integrity is missing.", + "mitigations": "End-to-end encryption with per-agent credentials and mutual authentication. Digitally signed messages covering payload and context. Disable legacy protocol modes and reject downgrade. Versioned, typed message schemas with explicit audiences.", + "example": "A man-in-the-middle on an unauthenticated channel injects instructions into a coordination message, and the receiving agent returns biased results.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI07, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/" + }, + { + "SID": "AG12", + "target": [ + "Dataflow" + ], + "description": "Inter-Agent Message Replay", + "details": "A captured delegation, approval or coordination message that carries no freshness guarantee can be replayed later to obtain access again or trigger a stale procedure.", + "Likelihood Of Attack": "Low", + "severity": "Medium", + "condition": "target.source.oneOf(LLM) and target.source.hasAgentCapabilities is True and target.sink.oneOf(LLM) and target.sink.hasAgentCapabilities is True and target.controls.implementsNonce is False", + "prerequisites": "Agents exchange delegation or trust messages. Messages are not bound to a nonce, session or task window.", + "mitigations": "Nonces, session identifiers and timestamps tied to the task window. Keep short-term message fingerprints to detect cross-context replay.", + "example": "A replayed emergency coordination message triggers an outdated procedure and misallocates resources.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI07, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/" + }, + { + "SID": "AG13", + "target": [ + "LLM" + ], + "description": "Agent Feedback Loop Without Circuit Breaker", + "details": "Two agents that consume each other's output can amplify one error, hallucination or injected instruction into a self-reinforcing loop, with retry storms, runaway cost and fan-out to downstream systems before a human can intervene.", + "Likelihood Of Attack": "Medium", + "severity": "High", + "condition": "target.hasAgentCapabilities is True and target.controls.handlesResourceConsumption is False and any(f.isResponse is False and f.sink.oneOf(LLM) and f.sink.hasAgentCapabilities is True and any(g.isResponse is False and g.sink is f.source for g in f.sink.outputs) for f in target.outputs)", + "prerequisites": "The agent sends requests to another agent that also sends requests back to it. There is no quota, progress cap or circuit breaker on the exchange.", + "mitigations": "Circuit breakers, quotas and progress caps between planner and executor. Validate or gate agent output before it propagates. Rate-limit and pause on fast-spreading identical intents. Tamper-evident logs with lineage for every propagated action.", + "example": "A remediation agent suppresses alerts to meet latency targets; a planning agent reads fewer alerts as success and widens automation.", + "references": "OWASP Top 10 for Agentic Applications 2026 ASI08, https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/, https://sre.google/sre-book/addressing-cascading-failures/" } ] diff --git a/tests/test_pytmfunc.py b/tests/test_pytmfunc.py index bfde4d2..26ce636 100644 --- a/tests/test_pytmfunc.py +++ b/tests/test_pytmfunc.py @@ -1886,6 +1886,13 @@ def test_LLM09(self): threat = threats["LLM09"] assert threat.apply(agent) + def test_LLM09_applies_to_llm_with_agent_capabilities(self): + llm = LLM("Tool LLM", hasAgentCapabilities=True) + llm.usesExternalTools = True + llm.validatesToolLaunchConfig = False + threat = threats["LLM09"] + assert threat.apply(llm) + def test_LLM09_mitigated(self): agent = Agent("Tool Agent") agent.usesExternalTools = True @@ -1918,6 +1925,355 @@ def test_LLM10_self_hosted(self): assert not threat.apply(llm) +def _agent(name): + return Agent(name) + + +def _agentic_llm(name): + return LLM(name, hasAgentCapabilities=True) + + +AGENT_FACTORIES = pytest.mark.parametrize( + "make_agent", [_agent, _agentic_llm], ids=["Agent", "LLM-hasAgentCapabilities"] +) + + +class TestAgenticThreats: + """AG01-AG13: OWASP Top 10 for Agentic Applications 2026. + + Every rule keys on ``LLM.hasAgentCapabilities``, so each test runs once + with ``Agent`` and once with ``LLM(hasAgentCapabilities=True)``. + """ + + @staticmethod + def _tm(): + TM.reset() + return TM("agentic tm", description="test") + + # -- AG01 --------------------------------------------------------------- + + @staticmethod + def _trifecta(make_agent, untrusted=True, sensitive=True, egress=True): + """An agent with any combination of the three AG01 legs, all pushed to it.""" + tm = TestAgenticThreats._tm() + agent = make_agent("Assistant") + if untrusted: + Dataflow(ExternalEntity("Inbound mail"), agent, "email") + if sensitive: + records = Dataflow(Server("CRM"), agent, "customer records") + records.data = Data("Customer records", isPII=True) + if egress: + Dataflow(agent, ExternalEntity("Webhook"), "notify") + assert tm.check() + return agent + + @AGENT_FACTORIES + def test_AG01(self, make_agent): + assert threats["AG01"].apply(self._trifecta(make_agent)) + + @AGENT_FACTORIES + @pytest.mark.parametrize("missing", ["untrusted", "sensitive", "egress"]) + def test_AG01_needs_all_three_legs(self, make_agent, missing): + agent = self._trifecta(make_agent, **{missing: False}) + assert not threats["AG01"].apply(agent) + + @AGENT_FACTORIES + def test_AG01_mitigated(self, make_agent): + agent = self._trifecta(make_agent) + agent.hasContentFiltering = True + assert not threats["AG01"].apply(agent) + + @AGENT_FACTORIES + def test_AG01_content_and_data_arrive_as_responses(self, make_agent): + tm = self._tm() + agent = make_agent("Researcher") + web = ExternalEntity("Public web") + crm = Server("CRM") + fetch = Dataflow(agent, web, "fetch page") + page = Dataflow(web, agent, "page content") + page.responseTo = fetch + query = Dataflow(agent, crm, "query") + rows = Dataflow(crm, agent, "rows") + rows.responseTo = query + rows.data = Data("Customer records", isPII=True) + assert tm.check() + # Responses are not listed in ``inputs``; the rule follows ``response``. + assert agent.inputs == [] + assert threats["AG01"].apply(agent) + + @AGENT_FACTORIES + def test_AG01_sensitive_datastore(self, make_agent): + tm = self._tm() + agent = make_agent("Assistant") + Dataflow(ExternalEntity("Inbound mail"), agent, "email") + Dataflow(agent, Datastore("Customer DB", storesPII=True), "query") + Dataflow(agent, ExternalEntity("Webhook"), "notify") + assert tm.check() + assert threats["AG01"].apply(agent) + + def test_AG01_ignores_plain_llm(self): + llm = self._trifecta(LLM) + assert llm.hasAgentCapabilities is False + assert not threats["AG01"].apply(llm) + + # -- AG02 / AG06 -------------------------------------------------------- + + @AGENT_FACTORIES + def test_AG02(self, make_agent): + agent = make_agent("Tool Agent") + agent.usesExternalTools = True + assert threats["AG02"].apply(agent) + agent.controls.implementsPOLP = True + assert threats["AG02"].apply(agent) # still unbounded + agent.controls.handlesResourceConsumption = True + assert not threats["AG02"].apply(agent) + + @AGENT_FACTORIES + def test_AG06(self, make_agent): + agent = make_agent("Tool Agent") + assert not threats["AG06"].apply(agent) # no external tools + agent.usesExternalTools = True + assert threats["AG06"].apply(agent) + agent.controls.usesCodeSigning = True + assert not threats["AG06"].apply(agent) + + def test_AG02_AG06_ignore_plain_llm(self): + llm = LLM("Chatbot", usesExternalTools=True) + assert not threats["AG02"].apply(llm) + assert not threats["AG06"].apply(llm) + + # -- AG03 --------------------------------------------------------------- + + @AGENT_FACTORIES + @pytest.mark.parametrize("tool", [Server, Lambda, Process, Datastore]) + def test_AG03(self, make_agent, tool): + call = Dataflow(make_agent("Agent"), tool("Tool"), "call") + assert threats["AG03"].apply(call) + call.controls.authorizesSource = True + assert not threats["AG03"].apply(call) + + def test_AG03_ignores_responses_and_plain_callers(self): + tool = Server("Tool") + result = Dataflow(tool, Agent("Agent"), "result", isResponse=True) + assert not threats["AG03"].apply(result) + assert not threats["AG03"].apply(Dataflow(LLM("Chatbot"), tool, "call")) + assert not threats["AG03"].apply(Dataflow(Server("App"), tool, "call")) + + # -- AG04 / AG11 / AG12 ------------------------------------------------- + + @AGENT_FACTORIES + def test_AG04(self, make_agent): + task = Dataflow(make_agent("Sorter"), make_agent("Finance"), "task") + assert threats["AG04"].apply(task) + task.controls.authorizesSource = True + assert not threats["AG04"].apply(task) + + @AGENT_FACTORIES + @pytest.mark.parametrize( + "missing", ["isEncrypted", "authenticatesSource", "providesIntegrity"] + ) + def test_AG11(self, make_agent, missing): + message = Dataflow(make_agent("A"), make_agent("B"), "message") + for control in ("isEncrypted", "authenticatesSource", "providesIntegrity"): + setattr(message.controls, control, True) + assert not threats["AG11"].apply(message) + setattr(message.controls, missing, False) + assert threats["AG11"].apply(message) + + @AGENT_FACTORIES + def test_AG12(self, make_agent): + message = Dataflow(make_agent("A"), make_agent("B"), "message") + assert threats["AG12"].apply(message) + message.controls.implementsNonce = True + assert not threats["AG12"].apply(message) + + @pytest.mark.parametrize("sid", ["AG04", "AG11", "AG12"]) + def test_inter_agent_rules_need_two_agents(self, sid): + agent = Agent("Agent") + assert not threats[sid].apply(Dataflow(agent, LLM("Model"), "prompt")) + assert not threats[sid].apply(Dataflow(agent, Server("API"), "call")) + assert not threats[sid].apply(Dataflow(Server("App"), agent, "task")) + + # -- AG05 --------------------------------------------------------------- + + @AGENT_FACTORIES + def test_AG05_credentials_into_model_context(self, make_agent): + prompt = Dataflow(make_agent("Agent"), LLM("Model"), "prompt") + assert not threats["AG05"].apply(prompt) + prompt.data = Data( + "Scoped token", isCredentials=True, credentialsLife=Lifetime.SHORT + ) + assert threats["AG05"].apply(prompt) + + @AGENT_FACTORIES + def test_AG05_delegated_credentials(self, make_agent): + short = Dataflow(make_agent("Manager"), make_agent("Worker"), "delegate") + short.data = Data( + "Scoped token", isCredentials=True, credentialsLife=Lifetime.SHORT + ) + assert not threats["AG05"].apply(short) + + long = Dataflow(make_agent("Manager 2"), make_agent("Worker 2"), "delegate") + long.data = Data("API key", isCredentials=True, credentialsLife=Lifetime.LONG) + assert threats["AG05"].apply(long) + + # -- AG07 --------------------------------------------------------------- + + @AGENT_FACTORIES + def test_AG07_outbound(self, make_agent): + call = Dataflow(make_agent("Agent"), ExternalEntity("MCP server"), "tool call") + assert threats["AG07"].apply(call) + call.controls.authenticatesDestination = True + assert threats["AG07"].apply(call) # still no integrity + call.controls.providesIntegrity = True + assert not threats["AG07"].apply(call) + + @AGENT_FACTORIES + def test_AG07_inbound(self, make_agent): + task = Dataflow(ExternalEntity("Peer agent"), make_agent("Agent"), "task") + assert threats["AG07"].apply(task) + task.controls.authenticatesSource = True + task.controls.providesIntegrity = True + assert not threats["AG07"].apply(task) + + @AGENT_FACTORIES + def test_AG07_out_of_scope_endpoint(self, make_agent): + vendor = Server("Vendor tool server", inScope=False) + assert threats["AG07"].apply(Dataflow(make_agent("Agent"), vendor, "call")) + + def test_AG07_ignores_internal_and_plain(self): + external = ExternalEntity("MCP server") + assert not threats["AG07"].apply( + Dataflow(Agent("Agent"), Server("API"), "call") + ) + assert not threats["AG07"].apply(Dataflow(LLM("Chatbot"), external, "call")) + + # -- AG08 --------------------------------------------------------------- + + @AGENT_FACTORIES + @pytest.mark.parametrize("executor", [Process, Lambda]) + def test_AG08(self, make_agent, executor): + runner = executor("Runner") + command = Dataflow(make_agent("Coder"), runner, "command") + assert threats["AG08"].apply(command) + runner.controls.sanitizesInput = True + assert threats["AG08"].apply(command) # still not sandboxed + runner.controls.isHardened = True + assert not threats["AG08"].apply(command) + + def test_AG08_ignores_non_executors_and_plain_llm(self): + assert not threats["AG08"].apply( + Dataflow(Agent("Coder"), Server("API"), "call") + ) + assert not threats["AG08"].apply( + Dataflow(LLM("Chatbot"), Process("Runner"), "text") + ) + + # -- AG09 / AG10 -------------------------------------------------------- + + @staticmethod + def _memory(make_agent, reads=True, **store): + tm = TestAgenticThreats._tm() + memory = Datastore("Memory", **store) + agent = make_agent("Assistant") + if reads: + Dataflow(memory, agent, "recall") + else: + Dataflow(agent, memory, "remember") + assert tm.check() + return memory + + @AGENT_FACTORIES + @pytest.mark.parametrize("reads", [True, False], ids=["read", "write"]) + def test_AG09(self, make_agent, reads): + memory = self._memory(make_agent, reads=reads) + assert threats["AG09"].apply(memory) + memory.controls.validatesInput = True + assert not threats["AG09"].apply(memory) + + @AGENT_FACTORIES + def test_AG10(self, make_agent): + memory = self._memory(make_agent, isShared=True, storesPII=True) + assert threats["AG10"].apply(memory) + memory.controls.hasAccessControl = True + assert not threats["AG10"].apply(memory) + + @AGENT_FACTORIES + def test_AG10_needs_shared_sensitive_store(self, make_agent): + assert not threats["AG10"].apply(self._memory(make_agent, storesPII=True)) + assert not threats["AG10"].apply(self._memory(make_agent, isShared=True)) + assert threats["AG10"].apply( + self._memory(make_agent, isShared=True, storesSensitiveData=True) + ) + + def test_AG09_AG10_ignore_stores_without_an_agent(self): + memory = self._memory(LLM, isShared=True, storesPII=True) + assert not threats["AG09"].apply(memory) + assert not threats["AG10"].apply(memory) + + # -- AG13 --------------------------------------------------------------- + + @AGENT_FACTORIES + def test_AG13(self, make_agent): + tm = self._tm() + planner = make_agent("Planner") + executor = make_agent("Executor") + Dataflow(planner, executor, "plan") + Dataflow(executor, planner, "replan request") + assert tm.check() + assert threats["AG13"].apply(planner) + assert threats["AG13"].apply(executor) + planner.controls.handlesResourceConsumption = True + assert not threats["AG13"].apply(planner) + assert threats["AG13"].apply(executor) + + @AGENT_FACTORIES + def test_AG13_request_response_is_not_a_loop(self, make_agent): + tm = self._tm() + planner = make_agent("Planner") + executor = make_agent("Executor") + plan = Dataflow(planner, executor, "plan") + result = Dataflow(executor, planner, "result") + result.responseTo = plan + assert tm.check() + assert not threats["AG13"].apply(planner) + assert not threats["AG13"].apply(executor) + + def test_AG13_needs_an_agent_on_both_sides(self): + tm = self._tm() + agent = Agent("Agent") + service = Server("Service") + Dataflow(agent, service, "call") + Dataflow(service, agent, "callback") + assert tm.check() + assert not threats["AG13"].apply(agent) + + # -- end to end --------------------------------------------------------- + + @AGENT_FACTORIES + def test_findings_from_resolve(self, make_agent): + """The rules load from the shipped library and surface through resolve().""" + tm = self._tm() + agent = make_agent("Orchestrator") + agent.usesExternalTools = True + worker = make_agent("Worker") + web = ExternalEntity("Public web") + memory = Datastore("Shared memory", isShared=True, storesPII=True) + fetch = Dataflow(agent, web, "fetch page") + page = Dataflow(web, agent, "page content") + page.responseTo = fetch + Dataflow(agent, memory, "remember") + Dataflow(agent, Process("Shell"), "command") + key = Dataflow(agent, worker, "delegate") + key.data = Data("API key", isCredentials=True, credentialsLife=Lifetime.LONG) + Dataflow(worker, agent, "sub-request") + assert tm.check() + tm.resolve() + + found = {f.threat_id for f in tm.findings if f.threat_id.startswith("AG")} + assert found == {f"AG{n:02d}" for n in range(1, 14)} + + class TestLLM: def test_defaults(self): TM.reset() @@ -1935,6 +2291,8 @@ def test_defaults(self): assert llm.processesUntrustedInput is True assert llm.hasRAG is False assert llm.hasFineTuning is False + assert llm.usesExternalTools is False + assert llm.validatesToolLaunchConfig is False def test_shape(self): TM.reset() @@ -1955,9 +2313,33 @@ def test_defaults(self): TM.reset() TM("test tm") agent = Agent("Test Agent") + assert agent.hasAgentCapabilities is True assert agent.usesExternalTools is False assert agent.validatesToolLaunchConfig is False + def test_is_an_llm_with_agent_capabilities(self): + TM.reset() + TM("test tm") + agent = Agent("Test Agent") + llm = LLM("Test LLM", hasAgentCapabilities=True) + assert isinstance(agent, LLM) + assert agent.oneOf(LLM) + # Agent adds no fields of its own; only the default differs. + assert set(Agent.model_fields) == set(LLM.model_fields) + differing = { + name + for name in LLM.model_fields + if name not in ("name", "uuid") + and getattr(agent, name) != getattr(llm, name) + } + assert differing == set() + + def test_agent_capabilities_can_be_switched_off(self): + TM.reset() + TM("test tm") + agent = Agent("Test Agent", hasAgentCapabilities=False) + assert agent.hasAgentCapabilities is False + def test_shape(self): TM.reset() TM("test tm")