Secure Your AI Agents on AWS (Part 2): Tool Execution and Runtime Safety
Part 2 of a three-part series mapping the OWASP Top 10 for Agentic Applications 2026 to AWS security controls. This part covers what the agent runs at runtime: ASI02 (tool misuse and abuse), ASI04 (agentic supply chain issues), and ASI05 (unexpected code execution), using Amazon Bedrock AgentCore Gateway, Amazon Inspector enhanced scanning, AWS Signer, and AgentCore Code Interpreter / AWS Lambda sandboxing.
This is Part 2 of a three-part series mapping the OWASP Top 10 for Agentic Applications 2026 to AWS security controls. Part 1 established the framework and covered inputs, identity, and human oversight. Part 2 covers what the agent runs - tool execution and runtime safety. Part 3 covers state, inter-agent communication, and detection.
This is a personal post. The views are my own and do not represent AWS. The code samples are illustrative — validate every API shape against the current documentation and Regional availability before you deploy.
In Part 1, I established the OWASP Top 10 for Agentic Applications 2026 framework and the defense-in-depth architecture, then secured the agent's boundary with users and inputs. If you haven't read it, start there for the full framework table and the security-layer mapping.
This part covers the three risks that concern what your agent does at runtime: ASI02 (tool misuse and abuse), ASI04 (supply chain issues), and ASI05 (unexpected code execution). These map to the "add next" tier of the implementation roadmap - the tool and infrastructure controls you layer on after the foundational input and identity controls from Part 1.
ASI02: Tool misuse and abuse
Tool misuse happens when prompt injection, misalignment, or ambiguous instructions cause your agents to apply authorized capabilities in unsafe ways - for example, exfiltrating data, hijacking workflows, or modifying systems without authorization. Your agent operates within its authorized privileges but applies tools unsafely.
Consider an email summarizer that deletes important messages instead of archiving them, or a CRM agent that accesses records outside its intended scope. Even DNS queries can become a data exfiltration channel when a coding agent is misdirected.
Mitigation: Amazon Bedrock AgentCore Gateway
Amazon Bedrock AgentCore Gateway provides a secure mediation layer between your agents and tools, with built-in input validation and authorization on every tool invocation. For request-rate throttling, front the tool APIs with Amazon API Gateway. AgentCore Gateway supports the Model Context Protocol (MCP), an open standard for connecting agents to tools and data sources.
To set up a secure tool gateway with AgentCore:
- Create a gateway with JWT-based authorization using the AgentCore control plane API.
- Register your tools as gateway targets with appropriate configurations.
- Configure input validation policies, and add Amazon API Gateway in front for request-rate throttling.
The following code creates an MCP gateway with JWT authorization and registers a Lambda tool as a target:
# Create an MCP gateway with JWT auth and register a Lambda tool target import boto3 control_client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') gateway = control_client.create_gateway( name='secure-tool-gateway', roleArn='arn:aws:iam::<account-id>:role/GatewayRole', protocolType='MCP', authorizerType='CUSTOM_JWT', authorizerConfiguration={ 'customJWTAuthorizer': { 'allowedClients': ['agent-client-id'], # discoveryUrl must be the full OpenID Connect discovery document URL, # ending in /.well-known/openid-configuration 'discoveryUrl': 'https://cognito-idp.<region>.amazonaws.com/<region>_ExamplePool1/.well-known/openid-configuration' } } ) control_client.create_gateway_target( gatewayIdentifier=gateway['gatewayId'], name='customer-database', # A Lambda target nests under mcp -> lambda, and requires BOTH the # lambdaArn AND a toolSchema describing the tools the Lambda exposes. targetConfiguration={ 'mcp': { 'lambda': { 'lambdaArn': 'arn:aws:lambda:<region>:111122223333:function:query-customers', 'toolSchema': { 'inlinePayload': [ { 'name': 'query_customer', 'description': 'Look up a customer record by ID', 'inputSchema': { 'type': 'object', 'properties': { 'customer_id': {'type': 'string'} }, 'required': ['customer_id'] } } ] } } } } )
Alternatively, you can use the AgentCore starter toolkit for a simplified developer experience:
# Same gateway + target using the AgentCore starter toolkit from bedrock_agentcore_starter_toolkit.operations.gateway.client import GatewayClient client = GatewayClient(region_name="us-west-2") cognito_response = client.create_oauth_authorizer_with_cognito("secure-tool-gateway") gateway = client.create_mcp_gateway( name='secure-tool-gateway', authorizer_config=cognito_response["authorizer_config"], enable_semantic_search=True, ) client.create_mcp_gateway_target( gateway=gateway, name='customer-database', target_type='lambda', # For a Lambda target you still supply the ARN and tool schema via # target_payload; the toolkit wraps them into the mcp/lambda shape above. target_payload={ 'lambdaArn': 'arn:aws:lambda:<region>:111122223333:function:query-customers', 'toolSchema': { 'inlinePayload': [ { 'name': 'query_customer', 'description': 'Look up a customer record by ID', 'inputSchema': { 'type': 'object', 'properties': {'customer_id': {'type': 'string'}}, 'required': ['customer_id'] } } ] } }, )
Key security controls:
| Control | AWS service | Implementation |
|---|---|---|
| Input validation | AgentCore Gateway | JSON Schema enforcement |
| Injection protection | AWS WAF | SQL injection and cross-site scripting (XSS) filtering for agent APIs |
| Authorization | Cedar policies | Per-tool access control |
| Credential isolation | AgentCore Identity | Gateway-managed token exchange |
| Rate limiting | Amazon API Gateway | Per-endpoint throttling in front of tool APIs |
| Audit logging | AWS CloudTrail | Complete invocation trail |
Validation note: In a test account I created the Lambda tool and gateway IAM role successfully, and validated the Cedar per-tool authorization structure (forbid-wins). Amazon Bedrock AgentCore, including Gateway, is generally available; the
create_gatewayandcreate_gateway_targetcontrol-plane calls use thebedrock-agentcore-controlclient. Validate the exact request shapes against the current API version and confirm Regional availability before you deploy.
Controlling how a tool is invoked assumes the tool and its dependencies are trustworthy. The next risk addresses what happens when they aren't.
ASI04: Agentic supply chain issues
Third-party agents, tools, and artifacts may be unintended, unexpected, or tampered with in transit. Agentic systems compose capabilities at runtime, creating a live supply chain that can cascade issues across your environment.
A poisoned prompt template could exfiltrate data, an unintended MCP server could intercept communications, or a tampered-with npm package installed by a coding agent could create a backdoor.
Mitigation: Amazon Inspector, AWS Signer, and AWS CodeArtifact
End-to-end supply chain security requires multiple services working together.
To implement supply chain security for your agent containers:
- Enable Amazon Inspector enhanced scanning for Amazon ECR in your account.
- Push your agent images — enhanced scanning scans them automatically, on push and continuously.
- Retrieve and act on critical findings.
A distinction that matters for agent runtimes: Amazon ECR basic scanning detects vulnerabilities in operating-system packages only. The dependencies an agent actually pulls — Python, JavaScript, and other language packages — are covered only by enhanced scanning, which integrates Amazon Inspector. Since the supply-chain risk here is a tampered-with or vulnerable language package (a poisoned pip or npm dependency), enhanced scanning is the control you need; basic scanning will not surface it.
The following code enables Inspector enhanced scanning for ECR, then pulls critical findings. With enhanced scanning enabled, images are scanned automatically on push, so you do not initiate scans manually:
# Enable Inspector enhanced scanning for ECR (covers OS *and* language packages), # then pull critical findings. Images are scanned automatically on push. import boto3 inspector = boto3.client('inspector2') inspector.enable( resourceTypes=['ECR'], accountIds=['111122223333'] ) findings = inspector.list_findings( filterCriteria={ 'severity': [{'comparison': 'EQUALS', 'value': 'CRITICAL'}] } )
Supply chain security controls:
| Control | AWS service | Purpose |
|---|---|---|
| Security scanning | Amazon Inspector (ECR enhanced scanning) | Detect Common Vulnerabilities and Exposures (CVEs) in OS and language packages |
| Code signing | AWS Signer | Verify artifact integrity — Amazon ECR managed signing signs images automatically on push |
| Package curation | AWS CodeArtifact | Approved dependency repository |
| Patch management | AWS Systems Manager | Automated security updates |
| Posture management | AWS Security Hub | Aggregated findings view |
Validation note: In a test account I created the Amazon ECR repository and the AWS CodeArtifact domain/repository, and confirmed AWS Signer container signing is available. End-to-end validation — building a vulnerable image and confirming Inspector enhanced scanning surfaces the language-package CVE — requires enhanced scanning enabled and a build host with a running container daemon. Note that ECR basic scanning would not detect a language-package vulnerability; enable enhanced scanning first.
Beyond supply chain risks, your agents may also generate and run code dynamically - which introduces its own category of risk.
ASI05: Unexpected code execution
Your agents may generate and execute code in real-time, potentially bypassing traditional security controls. Code-generation features can be abused to achieve remote code execution, sandbox escape, or unintended access.
A development agent might generate code with a hidden backdoor, an agent might execute unintended shell commands from reflected prompts, or unsafe deserialization might lead to code execution.
Mitigation: AgentCore Code Interpreter and AWS Lambda
The control that matters most here is isolation: agent-generated code should never run with the privileges, network reach, or filesystem access of the agent process itself. Amazon Bedrock AgentCore Code Interpreter is purpose-built for this — a fully managed, containerized sandbox that executes agent-generated Python, JavaScript, or TypeScript in an isolated environment, with configurable network modes (including a no-network sandbox mode), session isolation, and CloudTrail logging. It is the recommended default for running code an agent produces.
To configure isolated code execution for your agents:
- Create an AWS Lambda function with an isolated Amazon Virtual Private Cloud (Amazon VPC) configuration that restricts network access.
- Apply minimal IAM permissions to the execution role.
- Set concurrency limits to prevent resource exhaustion.
For broader language support or custom runtimes, configure AWS Lambda with an isolated Amazon VPC:
{ "FunctionName": "agent-code-executor", "Runtime": "python3.11", "Handler": "index.handler", "Role": "arn:aws:iam::<account-id>:role/CodeExecutorMinimalRole", "Timeout": 30, "MemorySize": 512, "ReservedConcurrentExecutions": 10, "VpcConfig": { "SubnetIds": ["subnet-isolated"], "SecurityGroupIds": ["sg-no-internet"] } }
A note on what does not substitute for isolation. It is tempting to try to block dangerous code by denylisting tokens such as eval(, exec(, os.system, or subprocess. — for example, with an Amazon Bedrock Guardrails custom word filter. Do not rely on this as a code-execution control. The Guardrails word filter performs exact word-and-phrase matching (a phrase is up to three words) and is designed for profanity, competitor, and product-name filtering — not for catching code tokens inside a snippet. A denylist of "dangerous" strings is trivially bypassed with whitespace, aliasing, attribute lookups, or encoding (os . system, getattr(os, "system"), base64), and a bypassed denylist gives a false sense of safety. Guardrails is valuable in this pipeline for filtering the natural-language prompt-injection attempts that ask an agent to generate malicious code — but the control that actually contains executed code is the sandbox, not a word list.
Isolation technologies in AWS Lambda:
- Control groups (cgroups) for CPU and memory constraints
- Namespaces for process isolation
- seccomp-bpf to limit system calls
- Firecracker microVMs for hardware-level isolation
Validation note: The Lambda-in-isolated-VPC pattern (no internet gateway, all egress revoked) is deployable as shown. When validating in an account near its VPC quota, note that creating a dedicated isolated VPC counts against the per-Region VPC limit — use a spare VPC or request a quota increase in a sandbox rather than a production account. AgentCore Code Interpreter provides the same isolation as a managed service without provisioning a VPC.
What to implement in weeks 2–3
This part maps to the "add next" tier of the roadmap:
- Amazon Bedrock AgentCore Gateway (ASI02) - Mediated tool access with input validation and rate limiting
- AWS Lambda isolation (ASI05) - Sandboxed code execution for agent-generated code
- Amazon Inspector and AWS Signer (ASI04) - Supply chain scanning and artifact verification
Coming up in Part 3
Part 2 secured what the agent runs. Part 3 covers the system-level dynamics: memory and context poisoning (ASI06), insecure inter-agent communication (ASI07), cascading failures (ASI08), and rogue agents (ASI10) - plus the full series summary and cleanup.
Additional resources
About the author
Bharadwaz Kari is a Technical Account Manager at AWS, where he helps enterprise customers operate and secure their workloads on AWS. He focuses on generative AI, security, and developer tooling. This post reflects his personal views, not those of his employer.
- Language
- English
Relevant content
AWS OFFICIALUpdated 4 months ago- Accepted Answer
asked 2 years ago
AWS OFFICIALUpdated 5 months ago