Blog

AI agent code execution security explained: why it happens and how to fix it

Written by Daniel Whitenack | Aug 21, 2026, 11:07:40 AM

Updated August 21, 2026

TL;DR: AI agents that execute code create three attack patterns invisible to traditional input filtering: prompt-to-shell attacks, tool-chain escalation, and container escapes. Input sanitization cannot stop them because attackers bypass filters with encoding, multi-turn manipulation, and semantic paraphrasing. The fix pairs runtime policy enforcement at a self-hosted control plane with isolated execution environments like MicroVMs. Prediction Guard enforces AIUC-1, OWASP, and NIST-aligned policies on every model call, generating SIEM-ready audit logs and an exportable AI Bill of Materials inside your infrastructure.

Most security teams treat AI agents like traditional software applications. A traditional API call carries predictable, deterministic payloads that a gateway can inspect against a fixed rule set. An AI agent generates its execution path at runtime, in natural language, and then acts on it. That distinction, between deterministic traffic and probabilistic traffic, is why securing agentic workloads requires rebuilding the security model from the architecture up, not patching it at the perimeter.

AI models generate code probabilistically, without runtime awareness of the environment in which that code will execute. This architectural characteristic means insecure patterns are a predictable output of the generation process, not an edge case. When an autonomous agent is authorized to execute that code directly on your network, those patterns stop being theoretical risks and become active remote code execution vectors. This article maps each exploitation path to its underlying mechanism and to the specific architectural controls that interrupt it before execution completes.

Architecting agents for secure code execution

Modern AI agents generate and execute code to complete tasks: running analyses on uploaded datasets, querying databases dynamically based on natural language requests, orchestrating configuration workflows, or calling external application programming interfaces (APIs) to produce formatted outputs. This capability is the value proposition and the attack surface simultaneously. Disabling code execution removes the utility that justifies the agent's existence in the first place.

The Prediction Guard team has documented the governance and cost trade-offs of operating agentic AI at enterprise scale, including the compounding risk created when code execution runs outside a governed perimeter.

Each agent execution follows the same structural pattern: a user prompt arrives, the model reasons about the task, it generates code, that code passes to an interpreter tool, the interpreter executes it in a connected environment, and the result returns. Security boundaries need to be established at every handshake in that chain, between the user and the model, between the model and the tool, and between the tool and the execution environment. Every input channel across that chain is a potential injection surface, including user-supplied text, retrieved documents from a Retrieval-Augmented Generation (RAG) pipeline, and outputs from a prior tool call.

Mapping agent capabilities to remote code execution (RCE) vectors

Traditional perimeter controls assume threats originate from outside the application trust boundary. Code-executing agents break that assumption: the threat can originate from inside the chain itself, from a retrieved document, a tool output, or a manipulated system prompt. As the OWASP LLM Top 10 establishes with LLM01 (Prompt Injection), the model cannot reliably distinguish between instructions and data because everything flows through the same token stream.

Establishing secure runtime perimeters

Traditional API gateways operate on deterministic rules. They expect fixed parameter schemas, predictable request structures, and patterns that match against known exploit signatures. AI agents produce none of these. The same user intent may generate entirely different tool calls, code structures, and parameter values depending on the model's reasoning path on that particular request. A gateway with no matching rule offers no protection. The OWASP Agentic AI Top 10 (2026) identifies this ambiguity as central to ASI01 (Agent Goal Hijack) and ASI05 (Unexpected Code Execution): attackers do not need to bypass the perimeter. They redirect the agent's own reasoning toward their objective.

Preventing injection in AI logic flows

Untrusted data entering the agent's context through a RAG pipeline is a particularly reliable injection vector. A malicious document retrieved during a legitimate analysis task can contain crafted text that overrides the agent's operating instructions and redirects the code generation step. Unlike a network-layer attack, this injection arrives as content the agent was explicitly designed to process and act on.

Mitigating implicit privilege escalation

Agents inherit the system privileges of the host application. If the code interpreter tool runs under a service account with read access to internal databases and write access to a message queue, every piece of code the agent generates executes with those same permissions. An attacker does not need to escalate privileges through an exploit. They simply prompt the agent to use the permissions it already holds.

Exploitation pattern 1: Prompt injection to RCE

Prompt injection is the entry point. The OWASP LLM Top Ten describes LLM01 and LLM06 as the two halves of this problem: LLM01 (Prompt Injection) is the entry mechanism, and LLM06 (Excessive Agency) is the amplifier that turns a manipulated string into a meaningful execution event. These two categories together explain why a single crafted input can escalate to host-level code execution with no additional exploit required.

Mechanism and anatomy of prompt-to-shell attacks

The crafted payloads exploit the agent's design: when malicious instructions arrive through a RAG pipeline as part of a legitimate retrieval task, they can override the agent's operating instructions and redirect the code generation step. CVE-2026-26030 demonstrates this precisely: a prompt injection reached an eval() sink in semantic-kernel's In-Memory Vector Store filter and produced arbitrary code execution, patched in semantic-kernel 1.39.4. No browser exploit, malicious attachment, or memory corruption bug was required. CVE-2026-25592 shows where that leads: once code executes, DownloadFileAsync wrote a payload to the host Startup folder, escaping the sandbox entirely, patched in .NET SDK 1.71.0. The agent does exactly what it was designed to do: interpret natural language, choose a tool, and pass parameters into code.

Prompts crafted to resemble inline code or shell syntax can influence the model's code generation step toward producing executable system commands, because the model processes the prompt as context for what to generate rather than as input to sanitize. If the agent application passes it to an interpreter without sandboxing, the shell command executes on the server. Models that generate insecure code under normal conditions become substantially more likely to produce exploitable code when the prompt has been adversarially crafted.

Why filters fail and what works instead

Simple regex or keyword filters fail for a structural reason: the model does not require a specific keyword to produce dangerous code. Attackers encode instructions in base64, bypassing string-matching checks entirely. The phrase "ignore previous instructions" becomes aWdub3JlIHByZXZpb3VzIGluc3RydWN0aW9ucw==, and a filter scanning for the original phrase has nothing to match. Encoding-based evasion defeats pattern matching at the structural level: the encoded variant shares no characters with the original phrase, so no filter has anything to match against, regardless of how comprehensive its rule set is. Multi-step manipulation, role-playing scenarios, and style injection compound this problem, and no static pattern library can keep pace with the combinatorial space of evasion techniques.

Because input sanitization is insufficient, the architectural requirement shifts to containing the blast radius of a successful injection. Agent-generated code must execute in a short-lived, isolated environment with no access to the host network, no persistent filesystem, and no inherited service account privileges. Without this isolation, a successful prompt injection is also a successful RCE, container escape, and lateral movement opportunity.

Exploitation pattern 2: Tool-chain escalation

The second exploitation path requires no injection at all. It relies on the agent's legitimate tool access and its ability to chain calls across multiple tools in a sequence that appears individually authorized but is collectively destructive.

Privilege abuse via chained agent calls

When an agent decides to use a tool, it formats the call, passes it to the tool server, receives the output, and feeds that output back into its reasoning to determine the next step. Each step is autonomous, with no human review between calls. The OWASP Agentic AI category ASI03 (Identity and Privilege Abuse) captures this precisely: exploits manipulate delegation chains, role inheritance, and cached credentials to escalate access across an agent's tool calls. An agent with read access to a customer relationship management (CRM) system and send access to an email tool can receive an embedded instruction to export VIP customer records and send them externally. Each individual call is within the agent's authorized permissions. The exfiltration only becomes visible when the chain is analyzed as a whole.

ASI02 (Tool Misuse and Exploitation) covers the adjacent risk: an agent that caches a high-privilege credential to complete an earlier task may carry that credential forward into subsequent calls, granting an attacker access to resources they were never authorized to reach. Agentic AI exposure, where developers connect agents to sensitive internal APIs without formal security reviews, is a consistent source of this risk in enterprise environments: every unreviewed tool connection is a potential chain link in an escalation path.

Architectural prevention: Policy enforcement at the control plane

Defending against tool-chain escalation requires system-level access controls: a centralized policy that defines which agents are permitted to call which tools at all, enforced before any call proceeds. Security and governance, risk, and compliance (GRC) teams configure these access controls through the Admin Console, specifying which models and tools each registered agent is permitted to invoke. Developers point their existing OpenAI-compatible or Anthropic-compatible software development kit (SDK) calls at the control plane endpoint by changing only the base_url. Code stays unchanged. Policy enforcement is transparent to the developer and applied on every request before it completes. A gateway-based approach enforces policy from outside your infrastructure, meaning telemetry and enforcement decisions route through a third-party system; a self-hosted control plane enforces the same policies from inside your environment, so governance logic and audit logs never leave your perimeter.

Exploitation pattern 3: Container runtime escapes

The third exploitation path converts an agent compromise into a network-level incident. If agent-generated code executes inside a container with the wrong configuration, an attacker can move from the container environment to the host system and, from there, to any resource the host can reach. Agent-generated code running inside a misconfigured container shares the host kernel, and a successful escape gives the attacker the same network reach as the host process, including access to internal databases, message queues, and credentials mounted into the container at startup. The structural risk is the same regardless of which kernel vulnerability or misconfiguration provides the escape path.

The anatomy of a container breach and key vulnerabilities

Container security rests on Linux namespaces and cgroups, which isolate processes and resources but share the host kernel. An attacker who gains code execution inside a container can probe the kernel version, identify known vulnerabilities, and attempt an escape. More commonly, attackers exploit misconfigurations that require no kernel exploit at all:

  • Mounting /var/run/docker.sock inside the container lets an attacker mount the entire host filesystem with a single command.
  • Running containers with the --privileged flag grants host-level control over the container runtime.
  • Over-provisioning CAP_SYS_ADMIN allows filesystem mounting and other elevated operations.
  • Mounting sensitive host directories like /proc, /sys, or /dev provides trivial escape paths that bypass all other controls.

Agent workloads frequently inherit all four of these misconfigurations from early-stage development environments that were never hardened for production.

Choosing your agent isolation strategy

The isolation architecture you choose determines how much damage a successful exploit can inflict.

Isolation model Kernel sharing Escape risk Operational complexity Best fit
Standard Docker (runc) Shares host kernel High (misconfiguration dependent) Low Development and low-risk workloads
gVisor (runsc) User-space kernel intercepts syscalls Significantly reduced Moderate Production workloads with moderate risk tolerance
Firecracker MicroVM Hardware-level VM boundary Near-complete isolation Higher Regulated workloads requiring maximum isolation

gVisor works by running a user-space kernel in Go. When a container process makes a system call, gVisor's Sentry process intercepts it rather than passing it to the host kernel, eliminating the kernel attack surface for most syscall-based escapes. It integrates with existing container runtimes via runsc and existing images work without modification. Firecracker provides hardware-level VM isolation at near-native performance but requires VM orchestration infrastructure that standard Kubernetes deployments do not include by default.

Reducing blast radius via runtime isolation

The zero-trust execution principle is that every code execution task runs in a short-lived, single-use sandbox destroyed immediately after execution completes, with no persistent access to the internal network, no access to host filesystem paths, and no inherited credentials. Even if an attacker achieves code execution, they reach a dead end before they can enumerate their options.

Designing agentic workflows with zero trust

These five architectural controls form the minimum viable governance stack for a code-executing agent in a regulated environment. Address them in sequence because each layer depends on the one before it. The Practical AI podcast's episode on zero trust for AI agents walks through Anthropic's zero trust framework for agentic systems, covering threat categories including prompt injection, tool misuse, and identity and privilege abuse, the concepts of blast radius and least agency, and a tiered implementation structure from foundation-level controls to enterprise-grade enforcement.

1. Establish pre-runtime security guardrails

Every prompt and every retrieved document must be validated before it reaches the model, including prompt injection detection on user inputs and on content retrieved from external sources such as RAG pipelines, web searches, and database results. The NIST AI RMF implementation playbook on the Prediction Guard blog maps the Govern and Map functions to specific pre-runtime controls.

2. Govern unpredictable AI behaviors

Probabilistic systems require deterministic boundaries. Prediction Guard's control plane enforces AI governance policies at runtime, checking every model call and tool invocation against configured policies. If a call violates policy, the control plane blocks it or rewrites it before the response returns. This is not retrospective log analysis. The decision happens at the moment of the call. Enforcement covers prompt injection, toxicity, personally identifiable information (PII) detection and masking, grounding verification against trusted data sources, and AI supply chain vulnerability scanning, applied in real time across every registered agent interaction. The Prediction Guard AI engineers page explains how this enforcement integrates with existing development workflows.

3. Secure audit trails for agent actions

ISO/IEC 42001 Annex A Control A.6.2.8 establishes the requirement for event log recording across the AI system lifecycle. Logs must capture governance events, policy decisions, outputs, and affected resources as a replayable trace bound to users, sessions, and data sources. Prediction Guard generates structured, SIEM-ready audit logs as a byproduct of active runtime enforcement, formatted for native ingestion into Splunk, Datadog, or Grafana through the Monitor page in the Admin Console. The customer's existing ingestion pipeline handles delivery. No SIEM credentials, API keys, or HTTP Event Collector (HEC) tokens are stored by the control plane at any point.

4. Unify governance for complex agent chains

A patchwork of per-tool security controls creates gaps at every seam between tools. Multi-agent workflows need a single policy framework applied uniformly across every model call and tool invocation, regardless of which SDK the developer used or which model vendor provided the underlying capability. Prediction Guard is model agnostic, governing open-source models, closed-vendor endpoints, and self-hosted models under one policy framework. Swap the underlying model and governance policies carry over without rebuilding the configuration.

5. Design for blast radius containment

No security architecture eliminates every risk. The design goal is to ensure that a compromise of a single agent task cannot escalate into a broader network breach. That requires short-lived execution sandboxes with no network egress and access controls that define exactly which tools and models each agent is permitted to invoke.

OWASP Agentic AI: A security mapping guide

You cannot secure what you have not inventoried. Most regulated enterprises discover AI agent deployments through incident reviews and security retrospectives rather than through a proactive registry. Every unregistered agent is an unaudited compliance gap and an ungoverned execution surface.

Cataloging your active AI agent assets

Prediction Guard requires AI assets, including models, tools, Model Context Protocol (MCP) servers, and datasets, to be registered within an AI System before they can be governed. That registration produces the active control plane enforcement and, as an exportable byproduct, an AI Bill of Materials (AIBOM) in CycloneDX format. CycloneDX supports full-stack bill of materials specifications including machine learning model inventories, software-as-a-service components, and vulnerability disclosure records. AIUC-1 or an enterprise procurement reviewer can verify which models and tools are in production, which versions they are running, and which governance policies apply to each from a single exported document.

Mapping exploitation patterns to OWASP items

Risk vector OWASP Agentic AI (2026) category NIST AI RMF function Prevention control
Prompt-to-shell ASI05: Unexpected Code Execution Measure, Manage Runtime sandboxing and input validation
Tool-chain escalation ASI02: Tool Misuse / ASI03: Privilege Abuse Govern, Manage Control plane access controls
Container escape ASI05: Unexpected Code Execution Manage MicroVM or runtime isolation
Agentic AI exposure ASI04: Agentic Supply Chain Vulnerabilities Govern, Map AI System registration and AIBOM export

The OWASP Agentic AI 2026 primary document includes Appendix A, which cross-maps each ASI entry to specific OWASP LLM Top 10 items, providing a direct line from the agent-level risk to the underlying model-level vulnerability. AIUC-1's crosswalk at aiuc-1.com/crosswalks maps OWASP Top 10 for LLM Applications to its six pillars (Data and Privacy, Security, Safety, Reliability, Accountability, Society), giving compliance teams a unified view across frameworks without maintaining separate mapping spreadsheets.

Logging agent actions for audit review

ISO/IEC 42001 Annex A Control A.6.2.8 requires event log recording at each phase of the AI system lifecycle where operational traceability and accountability are required. In practice, logs must capture every governance event, policy decision, model output, and code execution event as a replayable trace bound to the user, session, and data source that triggered it. For NIST AI RMF's Measure function, these logs are the evidence that governance policies are actually being applied, not just documented. Prediction Guard generates that evidence inside the customer's environment on every request.

From framework mapping to deployment decisions

Mapping exploitation patterns to OWASP categories and NIST AI RMF functions establishes the governance vocabulary, but it does not resolve the architectural trade-offs engineering teams face when deploying code-executing agents in production. The questions below address the implementation decisions that no framework table answers on its own.

Should code execution be disabled to reduce attack surface?

The architectural tension is straightforward: disabling code execution removes the attack surface and removes the capability that justifies deploying an agent over a simpler retrieval or query tool.

Disabling code execution reduces the attack surface but removes the analytical capability that justifies deploying an agent over a simpler retrieval or query tool. The correct frame is secure enablement: run execution inside a short-lived MicroVM sandbox with no network egress and no persistent filesystem, governed by a control plane that blocks unauthorized tool calls before they proceed. The deeper challenge is that agent inputs are natural language authored by users and enriched with retrieved content, meaning execution paths are generated dynamically at the moment of the request. Quality assurance (QA) processes designed for deterministic software do not map cleanly to this environment, and adversarial prompt testing along with red-teaming retrieved content are required components of any security validation program. See the Prediction Guard control plane overview for how policy enforcement adapts to probabilistic agent behavior.

Security risks of managed platforms and verifying integrity

External, closed-source agent platforms introduce two compounding risks: data egress, where prompts and code execution outputs transit the vendor's servers, and governance lock-in, where your policy configuration is tied to the vendor's format and cannot be migrated without rebuilding. Noma Security's Kong Gateway plugin requires outbound HTTPS traffic to api.noma.security on port 443 for enforcement and telemetry, as confirmed in Kong's developer documentation.

For regulated workloads where prompts may contain sensitive, export-controlled, or non-public financial information, routing that traffic through a third-party enforcement layer is a data boundary violation, not a security control. Continuous verification of agent actions means generating a structured record of every agent call and feeding that record into your SIEM through your own ingestion pipeline. Prediction Guard formats audit log output for native Splunk, Datadog, or Grafana ingestion, configured through the Monitor page in the Admin Console. The control plane generates the log as evidence that enforcement happened before execution completed.

Security readiness checklist for AI agents:

  • AI asset inventory: Are all active AI agents, models, MCP servers, and tools registered within their AI System before being governed?
  • Access control: Do you enforce system-level policies defining which agents are permitted to call specific tools?
  • Execution isolation: Does agent-generated code execute in an isolated, short-lived sandbox (MicroVM or gVisor container) with no host network access?
  • Runtime enforcement: Are security policies enforced in real time on every model call, or do you rely on retrospective log analysis?
  • Data sovereignty: Do your agent governance logic and audit logs remain entirely within your secure perimeter?
  • Audit readiness: Can you export an AI Bill of Materials in CycloneDX format for your next regulatory review?

If any of these boxes is unchecked, the gap is not a documentation problem. It is a governance architecture problem. Book a deployment scoping call to assess how a self-hosted control plane fits your infrastructure and compliance requirements.

FAQs

What are the security risks of AI agents executing code?

AI agents executing code introduce risks of RCE, prompt-to-shell exploits, tool-chain escalation, and container escapes. Attackers can manipulate prompts or retrieved data to force the agent to run malicious commands, potentially compromising the host system or internal network.

Is input filtering alone sufficient to secure code-executing agents?

No. Input filtering is insufficient because attackers use base64 encoding, multi-turn manipulation, and semantic paraphrasing to bypass static checks. True security requires combining runtime policy enforcement at the control plane with isolated execution environments such as MicroVMs that contain the blast radius of any successful injection.

How does a self-hosted control plane mitigate agent execution risks?

A self-hosted control plane enforces standards-aligned security policies at the API level on every model call, keeping all data, governance logic, and audit logs within your perimeter. It ensures every agent interaction is checked against policy and restricted to authorized tools without routing telemetry to external vendors.

What is ASI05 in the OWASP Agentic AI Top Ten?

ASI05 (Unexpected Code Execution) is the OWASP Agentic AI 2026 category covering exploitation of code-generation features or embedded tool access to escalate agent actions into remote code execution or container compromise. It is the primary OWASP category for both prompt-to-shell and container escape attack patterns.

What is the difference between a gateway and a control plane for AI security?

An AI gateway intercepts traffic from outside your infrastructure, meaning enforcement telemetry and logs route through the vendor's systems. A self-hosted control plane runs inside your own environment, so governance logic, policy enforcement, and audit logs are generated entirely within your perimeter, satisfying data sovereignty requirements that external tools cannot meet.

How does AIUC-1 apply to AI agent code execution security?

AIUC-1 maps to OWASP Top 10 for LLM Applications and OWASP Agentic AI at aiuc-1.com/crosswalks, spanning its Security, Data and Privacy, Reliability, and Accountability pillars. Prompt injection (LLM01) maps to the Security pillar. Documenting your control plane enforcement against AIUC-1's structure satisfies the enterprise vendor due diligence requirement that procurement reviewers increasingly require before approving AI tools for production deployment.

Key terms glossary

AIUC-1: A cross-framework compliance standard that maps AI governance requirements across multiple regulatory and voluntary standards, providing a unified view for compliance teams. Available at aiuc-1.com/crosswalks.

RAG (Retrieval-Augmented Generation): An AI architecture pattern where a model retrieves relevant documents or data from external sources before generating a response, enhancing accuracy but introducing potential injection vectors through retrieved content.

SIEM (Security Information and Event Management): A system that aggregates and analyzes security logs from across an organization's infrastructure to detect threats and maintain an audit log.

PII (Personally Identifiable Information): Data that can be used to identify a specific individual, such as names, addresses, social security numbers, or email addresses, subject to various privacy regulations.

MCP (Model Context Protocol): A protocol for integrating AI models with external tools and data sources in a standardized way, enabling agent workflows to access diverse capabilities.

Sovereign AI control plane: A self-hosted software system that unifies, secures, and governs disparate AI models, tools, and agents entirely within an organization's secure infrastructure.

Remote Code Execution (RCE): A vulnerability that allows an attacker to execute arbitrary commands or code on a target machine or container over a network.

AI Bill of Materials (AIBOM): A structured inventory of the models, datasets, tools, and dependencies comprising an AI system, typically exported in CycloneDX format for compliance audits.

Probabilistic traffic: Application interactions generated by AI models where inputs and outputs are non-deterministic and dynamically generated at runtime, making them impossible to secure using traditional static, rule-based API gateways that assume predictable request structures.

MicroVM isolation: A security pattern that runs untrusted code inside lightweight, short-lived virtual machines to prevent container escapes and contain the blast radius of an exploit.

ASI05 (Unexpected Code Execution): The OWASP Top 10 for Agentic Applications 2026 category covering exploitation of code-generation capabilities to escalate agent actions into remote code execution or host compromise.

Tool-chain escalation: An attack pattern where an agent chains individually authorized tool calls in a sequence that, taken together, exfiltrates data, abuses privileges, or causes harm beyond the agent's intended scope.