AWS Builder Center
Weaponizing AWS Kiro for Cloud Purple-Teaming: Autonomous IAM Exploit Hunting Inside Kiro's Bubblewrap OS Sandbox

Weaponizing AWS Kiro for Cloud Purple-Teaming: Autonomous IAM Exploit Hunting Inside Kiro's Bubblewrap OS Sandbox

Learn how to use Kiro CLI v3's Bubblewrap OS sandbox and custom NetworkX MCP servers to autonomously hunt IAM privilege escalation vectors securely.

AWS Community Builder - Dev Tools | 2× AWS Certified | Devops/Cloud Consultant
Using an autonomous AI agent for offensive cloud security testing—hunting IAM privilege escalation paths, enumerating dormant policy versions, and validating exploit chains—introduces an obvious operational hazard: how do you give an AI agent offensive security tools without risking accidental mutations against production AWS accounts or local credential exfiltration?
With the introduction of the Local Command Sandbox in Kiro IDE 1.3+ and Kiro CLI v3 ( 2.31.0+  /  3.4.0+ ), alongside MCP Process Wrapping ( mcpSandboxing ) and granular  sandbox_network  rules, security engineers can lock Kiro's shell execution and stdio MCP servers inside an operating-system-level containment boundary.
This technical deep dive walks through architecting an isolated AWS IAM Red-Team & Purple-Team Hunting Engine using Kiro CLI v3, Linux  bwrap  (Bubblewrap) containment, a custom IAM Attack-Graph MCP Server built with  NetworkX  and  boto3  and adversarial property-based fuzzing.



1. Containing the Red-Team Agent: Kiro's OS Command Sandbox ( bwrap  +  socat )

By default, local stdio MCP servers and agent-invoked shell commands execute outside Kiro's local command sandbox with your user account's ambient network and filesystem privileges. When running offensive enumeration tools or untrusted exploit-validation scripts, relying solely on LLM prompt instructions for safety isn't enough.
Kiro's Local Command Sandbox enforces an operating-system boundary around every terminal command the agent runs, every child process those commands spawn, and—when  "mcpSandboxing": true  is enabled—every local stdio MCP server process.
Platform / Layer
Containment Mechanism
Security Enforcement Role
Linux Host ( Ubuntu 24.04 )
 bwrap  (Bubblewrap) +  socat 
Namespace isolation and outbound proxy filtering
macOS Host
Native  Seatbelt  framework
Kernel-level process and socket sandboxing
Network Mode
 DEFAULT_BLOCKED 
Drops all outbound traffic except explicit allowlists
MCP Isolation
 "mcpSandboxing": true 
Wraps stdio MCP servers inside the OS sandbox boundary
Hierarchy Lock
Global vs. Repo Config
Cloned repos can tighten rules but can never loosen global sandbox settings

Configuring Strict Containment on Ubuntu Linux

First, verify that  bubblewrap  and  socat  are installed on your Linux workstation so Kiro can enforce namespace and network proxy filtering:
sudo apt update && sudo apt install -y bubblewrap socat
which bwrap socat
Next, configure  ~/.kiro/settings/sandbox.json  to enforce  DEFAULT_BLOCKED  outbound networking and wrap all stdio MCP servers inside the OS sandbox:
{
"enabled": true,
"networkAccess": "DEFAULT_BLOCKED",
"mcpSandboxing": true
}
Finally, define  ~/.kiro/settings/permissions.yaml  so that sandboxed commands and offensive MCP tools can only communicate with your local CloudGoat/LocalStack target ( localhost:4566 ) or an isolated lab endpoint, blocking any accidental calls to live production endpoints:
# ~/.kiro/settings/permissions.yaml
# In sandbox_network rules, the FIRST matching rule wins.
rules:
- capability: sandbox_network
match:
- "127.0.0.1"
- "localhost"
- "sts.lab-sandbox.internal"
effect: allow

- capability: fs_write
match:
- "./reports/**"
- "./.kiro/specs/**"
effect: allow

- capability: fs_write
match:
- "**"
effect: deny
Notice an important architectural guarantee in Kiro: a repository-level  .kiro/settings/sandbox.json  can turn the sandbox on or tighten an active global policy, but it can never disable the global sandbox, open the network further, or turn off global  mcpSandboxing . Even if you clone a hostile repository with poisoned Kiro config files, your host boundary remains intact.

2. Building an Offensive IAM Attack-Graph MCP Server

Real-world AWS breaches rarely rely on zero-day vulnerabilities; instead, attackers chain subtle IAM misconfigurations—such as rolling back to a forgotten, over-privileged IAM policy version ( iam:SetDefaultPolicyVersion ), passing an existing role to a new compute service ( iam:PassRole  +  lambda:CreateFunction ), or traversing transitive  sts:AssumeRole  trust policies.


Let's build a custom MCP server ( iam_redteam_mcp.py ) using  FastMCP ,  boto3 , and  networkx . It inspects an AWS target environment, constructs a directed privilege-escalation graph across all IAM principals and historical policy versions, and exposes three offensive analysis tools to Kiro:
  1.  scan_shadow_policy_versions : Hunts non-default historical IAM policy versions ( v1 .. v5 ) that grant wildcard admin privileges when paired with  iam:SetDefaultPolicyVersion .
  1.  find_privesc_attack_paths : Builds a  NetworkX  directed graph of roles, policies, and pass-role primitives to discover multi-hop paths from a low-privilege principal to  AdministratorAccess .
  1.  generate_exploit_poc : Produces a safe, verifiable AWS CLI proof-of-concept command sequence for a discovered path so purple teams can validate the finding in their lab.
#!/usr/bin/env python3
import json
import os
import boto3
import networkx as nx
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("AWS-IAM-RedTeam-Hunter")

ENDPOINT_URL = os.environ.get("AWS_ENDPOINT_URL") # e.g., http://localhost:4566 for LocalStack
REGION = os.environ.get("AWS_REGION", "us-east-1")

iam = boto3.client("iam", region_name=REGION, endpoint_url=ENDPOINT_URL)

def _as_list(val):
if isinstance(val, list):
return val
return [val] if val else []

def _extract_allowed_actions(policy_doc: dict) -> set[str]:
actions = set()
for stmt in _as_list(policy_doc.get("Statement", [])):
if stmt.get("Effect") == "Allow":
for act in _as_list(stmt.get("Action", [])):
actions.add(act.lower())
return actions

@mcp.tool()
def scan_shadow_policy_versions(policy_arn: str) -> dict:
"""
Audits all historical versions (v1-v5) of a managed IAM policy to detect
shadow privilege escalation via iam:SetDefaultPolicyVersion rollback.
"""
versions_resp = iam.list_policy_versions(PolicyArn=policy_arn)
versions = versions_resp.get("Versions", [])

default_actions = set()
shadow_escalations = []

for ver in versions:
ver_id = ver["VersionId"]
doc = iam.get_policy_version(
PolicyArn=policy_arn, VersionId=ver_id
)["PolicyVersion"]["Document"]
allowed = _extract_allowed_actions(doc)

if ver.get("IsDefaultVersion"):
default_actions = allowed
else:
# Flag dormant versions containing wildcard admin or privesc primitives
dangerous_primitives = {
"*",
"iam:*",
"iam:putuserpolicy",
"iam:attachrolepolicy",
"iam:passrole",
"sts:assumerole",
}
matched = allowed.intersection(dangerous_primitives)
if matched:
shadow_escalations.append(
{
"versionId": ver_id,
"createDate": str(ver.get("CreateDate")),
"dangerousActions": sorted(list(matched)),
}
)

can_rollback = (
"iam:setdefaultpolicyversion" in default_actions
or "iam:*" in default_actions
or "*" in default_actions
)

return {
"policyArn": policy_arn,
"canSelfRollbackInDefaultVersion": can_rollback,
"exploitableShadowVersions": shadow_escalations,
"severity": "CRITICAL" if (can_rollback and shadow_escalations) else "HIGH" if shadow_escalations else "LOW",
}

@mcp.tool()
def find_privesc_attack_paths(start_principal_arn: str) -> dict:
"""
Constructs a directed attack graph using NetworkX to find multi-hop
privilege escalation paths from start_principal_arn to AdministratorAccess.
"""
G = nx.DiGraph()
TARGET_NODE = "CROWN_JEWEL:AdministratorAccess"
G.add_node(TARGET_NODE, type="privilege")

roles = iam.list_roles().get("Roles", [])
for role in roles:
role_arn = role["Arn"]
G.add_node(role_arn, type="role", name=role["RoleName"])

# 1. Inspect Trust Policy (who can sts:AssumeRole into this role)
trust_doc = role.get("AssumeRolePolicyDocument", {})
for stmt in _as_list(trust_doc.get("Statement", [])):
if stmt.get("Effect") == "Allow":
principals = stmt.get("Principal", {})
aws_principals = _as_list(principals.get("AWS", []))
service_principals = _as_list(principals.get("Service", []))

for p in aws_principals:
G.add_edge(p, role_arn, vector="sts:AssumeRole")
for svc in service_principals:
G.add_edge(f"SERVICE:{svc}", role_arn, vector="ServiceExecutionRole")

# 2. Inspect Attached Managed Policies & Inline Policies
attached = iam.list_attached_role_policies(RoleName=role["RoleName"]).get(
"AttachedPolicies", []
)
for pol in attached:
pol_arn = pol["PolicyArn"]
if pol_arn.endswith(":policy/AdministratorAccess"):
G.add_edge(role_arn, TARGET_NODE, vector="AttachedAdminPolicy")
continue

pol_meta = iam.get_policy(PolicyArn=pol_arn)["Policy"]
default_ver = pol_meta["DefaultVersionId"]
doc = iam.get_policy_version(
PolicyArn=pol_arn, VersionId=default_ver
)["PolicyVersion"]["Document"]
actions = _extract_allowed_actions(doc)

if "*" in actions or "iam:*" in actions:
G.add_edge(role_arn, TARGET_NODE, vector="WildcardActionPolicy")

# Vector: iam:PassRole + lambda:CreateFunction + lambda:InvokeFunction
if {"iam:passrole", "lambda:createfunction", "lambda:invokefunction"}.issubset(actions):
G.add_edge(
role_arn,
"SERVICE:lambda.amazonaws.com",
vector="iam:PassRole+lambda:CreateFunction",
)

# Vector: iam:SetDefaultPolicyVersion on a policy with shadow admin version
shadow_report = scan_shadow_policy_versions(pol_arn)
if shadow_report["canSelfRollbackInDefaultVersion"] and shadow_report["exploitableShadowVersions"]:
ver_id = shadow_report["exploitableShadowVersions"][0]["versionId"]
G.add_edge(
role_arn,
TARGET_NODE,
vector=f"iam:SetDefaultPolicyVersion({pol['PolicyName']}->{ver_id})",
)

paths = []
if G.has_node(start_principal_arn) and nx.has_path(G, start_principal_arn, TARGET_NODE):
for path in nx.all_simple_paths(G, source=start_principal_arn, target=TARGET_NODE, cutoff=6):
hops = []
for i in range(len(path) - 1):
edge_data = G.get_edge_data(path[i], path[i + 1])
hops.append(
{
"from": path[i],
"to": path[i + 1],
"exploitVector": edge_data.get("vector", "unknown"),
}
)
paths.append(hops)

return {
"startPrincipal": start_principal_arn,
"totalNodesEvaluated": G.number_of_nodes(),
"escalationPathsFound": len(paths),
"attackPaths": paths,
}

@mcp.tool()
def generate_exploit_poc(policy_arn: str, target_version_id: str) -> dict:
"""
Generates an audit-ready verification command and corresponding remediation
for an iam:SetDefaultPolicyVersion rollback vulnerability.
"""
return {
"vulnerability": "IAM Policy Version Rollback Privilege Escalation",
"verificationCommand": (
f"aws iam set-default-policy-version "
f"--policy-arn {policy_arn} "
f"--version-id {target_version_id}"
),
"remediationCommand": (
f"aws iam delete-policy-version "
f"--policy-arn {policy_arn} "
f"--version-id {target_version_id}"
),
}

if __name__ == "__main__":
mcp.run(transport="stdio")

Registering the Red-Team Server in  .kiro/settings/mcp.json 

Notice how we allow Kiro to auto-approve read-only graph discovery tools ( scan_shadow_policy_versions ,  find_privesc_attack_paths ) while keeping PoC generation gated, and how we restrict dangerous operations using  disabledTools  if needed:
{
"mcpServers": {
"aws-iam-redteam": {
"command": "uv",
"args": [
"run",
"--with",
"mcp[cli]",
"--with",
"boto3",
"--with",
"networkx",
"python3",
"./mcp/iam_redteam_mcp.py"
],
"env": {
"AWS_REGION": "us-east-1",
"AWS_ENDPOINT_URL": "http://localhost:4566"
},
"disabled": false,
"autoApprove": [
"scan_shadow_policy_versions",
"find_privesc_attack_paths"
]
}
}
}

3. Writing Adversarial Security Specs in Kiro (EARS Syntax)

Instead of using Kiro Specs only for feature building, you can author Offensive Security Specs ( .kiro/specs/iam-privilege-containment/requirements.md ) that define strict non-escalation invariants using EARS (Easy Approach to Requirements Syntax):
# Requirements Document: Zero-Escalation IAM Permission Boundary

## Requirements

### Requirement 1: Block Shadow Policy Version Rollbacks
**User Story:** As a cloud security architect, I want all developer-assumable IAM roles to be mathematically incapable of escalating privileges via historical policy versions or self-mutation.

#### Acceptance Criteria
1. WHEN a principal assumes any role in the `/developer/` path THE SYSTEM SHALL enforce an attached IAM Permissions Boundary (`arn:aws:iam::*:policy/DeveloperBoundary`).
2. IF a policy attached to a developer role grants `iam:SetDefaultPolicyVersion`, `iam:CreatePolicyVersion`, or `iam:PutRolePolicy` THEN THE SYSTEM SHALL deny the action unconditionally within the Permissions Boundary.
3. WHEN `iam:PassRole` is invoked by a developer principal THE SYSTEM SHALL allow passing only roles matching `arn:aws:iam::*:role/app-runtime-*` and only to `lambda.amazonaws.com` or `ecs-tasks.amazonaws.com`.

4. Adversarial Property-Based Fuzzing Against IAM Policies

Once Kiro generates the defensive IAM Permissions Boundary from the spec above, how do you prove an attacker cannot bypass it using case-sensitivity tricks ( iAm:sEtDeFaUlTpOlIcYvErSiOn ), wildcard prefixes ( iam:Set* ), or unexpected resource ARNs?
Kiro's property-based testing workflow uses Python  Hypothesis  to fuzz the Effective Permissions evaluation engine across thousands of randomized action strings and resource ARNs:
import fnmatch
from hypothesis import given, settings, strategies as st

# Simulated IAM Permission Boundary generated by Kiro Spec
PERMISSION_BOUNDARY = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowStandardDevServices",
"Effect": "Allow",
"Action": ["s3:*", "dynamodb:*", "lambda:*", "logs:*", "iam:PassRole"],
"Resource": "*",
},
{
"Sid": "ExplicitDenyPrivilegeEscalationPrimitives",
"Effect": "Deny",
"Action": [
"iam:SetDefaultPolicyVersion",
"iam:CreatePolicyVersion",
"iam:AttachRolePolicy",
"iam:PutRolePolicy",
"iam:DeleteRolePermissionsBoundary",
"iam:PutRolePermissionsBoundary",
],
"Resource": "*",
},
],
}

def evaluate_boundary(action: str, resource: str, Identity_allows: bool = True) -> bool:
"""
Evaluates effective permissions under AWS IAM logic:
1. Default Deny
2. Explicit Deny overrides everything
3. Both Identity Policy AND Permission Boundary must explicitly Allow
"""
act_norm = action.strip().lower()
res_norm = resource.strip()

# Step 1: Check Explicit Deny in Boundary (case-insensitive wildcard match)
for stmt in PERMISSION_BOUNDARY["Statement"]:
if stmt["Effect"] == "Deny":
for pattern in stmt["Action"]:
if fnmatch.fnmatch(act_norm, pattern.lower()):
return False

# Step 2: Check Explicit Allow in Boundary
boundary_allows = False
for stmt in PERMISSION_BOUNDARY["Statement"]:
if stmt["Effect"] == "Allow":
for pattern in stmt["Action"]:
if fnmatch.fnmatch(act_norm, pattern.lower()) and fnmatch.fnmatch(
res_norm, stmt["Resource"]
):
boundary_allows = True

return Identity_allows and boundary_allows

# Adversarial Strategy: Mutate casing and whitespace of forbidden IAM escalation actions
FORBIDDEN_PRIVESC_ACTIONS = [
"iam:SetDefaultPolicyVersion",
"iam:CreatePolicyVersion",
"iam:AttachRolePolicy",
"iam:PutRolePolicy",
"iam:DeleteRolePermissionsBoundary",
"iam:PutRolePermissionsBoundary",
]

@settings(max_examples=500)
@given(
base_action=st.sampled_from(FORBIDDEN_PRIVESC_ACTIONS),
uppercase_mask=st.lists(st.booleans(), min_size=35, max_size=35),
target_arn=st.text(min_size=1, max_size=120),
)
def test_property_privesc_primitives_never_bypass_boundary(
base_action: str, uppercase_mask: list[bool], target_arn: str
):
# Fuzz character casing (e.g., "IaM:sEtDeFaUlTpOlIcYvErSiOn")
fuzzed_action = "".join(
ch.upper() if mask else ch.lower()
for ch, mask in zip(base_action, uppercase_mask)
)

# Even if an attacker compromises an identity policy with Action: "*",
# the Permission Boundary invariant MUST always evaluate to False.
assert evaluate_boundary(fuzzed_action, target_arn, Identity_allows=True) is False

5. Running Autonomous Purple-Team Audits in CI/CD with Headless Kiro CLI v3

With Kiro CLI v3, you can run this entire offensive-to-defensive workflow unattended inside GitHub Actions using Headless Mode ( --no-interactive ) paired with the  --sandbox  enforcement flag.
When you pass  --v3 --sandbox --no-interactive , Kiro CLI verifies that the OS sandbox ( bwrap ) and  mcpSandboxing  wrapping are active before starting; if the sandbox cannot activate or an MCP server fails to wrap, Kiro immediately aborts before running a single instruction:
name: Kiro Sandboxed IAM Red-Team Audit
on:
pull_request:
paths:
- "infra/**"
- "iam/**"

jobs:
iam-purple-team:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Install Bubblewrap, Socat, and Kiro CLI
run: |
sudo apt-get update && sudo apt-get install -y bubblewrap socat
curl -fsSL https://cli.kiro.dev/install | bash

- name: Boot Ephemeral LocalStack IAM Target
run: |
docker run -d -p 4566:4566 localstack/localstack:latest
./scripts/seed_terraform_iam_to_localstack.sh

- name: Execute Sandboxed Kiro Red-Team Hunt
env:
KIRO_API_KEY: ${{ secrets.KIRO_API_KEY }}
run: |
kiro-cli chat --v3 --sandbox --no-interactive \
--trust-tools=@aws-iam-redteam/scan_shadow_policy_versions,@aws-iam-redteam/find_privesc_attack_paths \
"Audit all IAM roles in LocalStack starting from arn:aws:iam::000000000000:role/dev-ci-runner. If any escalation path to AdministratorAccess exists, fail the build and output the exact least-privilege Permission Boundary patch."
By combining Kiro's OS-level  bwrap  command sandbox, custom graph-based MCP security tools, and property-based policy fuzzing, you transform Kiro from a code generator into a deterministic, self-contained cloud red-teaming engine.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article