agentcore-iam-audit 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Audit Amazon Bedrock AgentCore IAM for cross-agent access and code-interpreter privilege escalation."""
2
+
3
+ __version__ = "0.1.1"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,269 @@
1
+ """Checks. Each asks a concrete question with a probe ARN for a resource the principal does NOT own,
2
+ e.g. "can this agent's role read some *other* agent's memory?"."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from dataclasses import dataclass, field
8
+
9
+ from .iam import AGENTCORE_SERVICE, Principal
10
+ from .policy import Grant, as_list, evaluate
11
+
12
+ PROBE = "zz-acia-probe-other-agent"
13
+ DEFAULT_ROLE_RX = re.compile(r"^(AmazonBedrockAgentCoreSDKRuntime|AmazonBedrockAgentCoreSDKCodeBuild|AgentCoreEvalsSDK)-")
14
+ SEV = {"high": 3, "medium": 2, "low": 1, "info": 0}
15
+
16
+
17
+ @dataclass
18
+ class Finding:
19
+ id: str
20
+ severity: str
21
+ principal: str
22
+ title: str
23
+ detail: str
24
+ conditional: bool = False
25
+ refs: list[str] = field(default_factory=list)
26
+
27
+
28
+ def regions(p: Principal) -> list[str]:
29
+ found = {"us-east-1"}
30
+ for _, st in p.statements:
31
+ for r in as_list(st.get("Resource")) + as_list(st.get("NotResource")):
32
+ parts = str(r).split(":")
33
+ if len(parts) > 3 and parts[2] in ("bedrock-agentcore", "ecr", "secretsmanager") and parts[3] not in ("", "*"):
34
+ found.add(parts[3])
35
+ return sorted(found)
36
+
37
+
38
+ def can(p: Principal, action: str, arn_tpl: str, **kw) -> Grant:
39
+ """Allowed in any relevant region, after the permissions boundary (if any)."""
40
+ best = Grant(False)
41
+ for region in regions(p):
42
+ arn = arn_tpl.format(part=p.partition, region=region, account=p.account, probe=PROBE)
43
+ g = evaluate(p.statements, action, arn, **kw)
44
+ if g.allowed and p.boundary is not None:
45
+ b = evaluate(p.boundary, action, arn, **kw)
46
+ g = Grant(b.allowed, g.conditional or b.conditional, g.source) if b.allowed else Grant(False)
47
+ if g.allowed and (not best.allowed or (best.conditional and not g.conditional)):
48
+ best = g
49
+ return best
50
+
51
+
52
+ MEMORY = "arn:{part}:bedrock-agentcore:{region}:{account}:memory/{probe}"
53
+ RUNTIME = "arn:{part}:bedrock-agentcore:{region}:{account}:runtime/{probe}"
54
+ CODE_INTERPRETER = "arn:{part}:bedrock-agentcore:{region}:{account}:code-interpreter/{probe}"
55
+ ECR_REPO = "arn:{part}:ecr:{region}:{account}:repository/{probe}"
56
+ ID_SECRET = "arn:{part}:secretsmanager:{region}:{account}:secret:bedrock-agentcore-identity!default/oauth2/{probe}"
57
+ ID_APIKEY = "arn:{part}:secretsmanager:{region}:{account}:secret:bedrock-agentcore-identity!default/apikey/{probe}"
58
+ IAM_ROLE = "arn:{part}:iam::{account}:role/{probe}"
59
+
60
+ MEMORY_READ = [
61
+ "bedrock-agentcore:GetMemory",
62
+ "bedrock-agentcore:RetrieveMemoryRecords",
63
+ "bedrock-agentcore:ListEvents",
64
+ "bedrock-agentcore:GetEvent",
65
+ "bedrock-agentcore:ListMemoryRecords",
66
+ "bedrock-agentcore:GetMemoryRecord",
67
+ ]
68
+ MEMORY_WRITE = [
69
+ "bedrock-agentcore:CreateEvent",
70
+ "bedrock-agentcore:BatchCreateMemoryRecords",
71
+ "bedrock-agentcore:BatchUpdateMemoryRecords",
72
+ "bedrock-agentcore:DeleteMemoryRecord",
73
+ ]
74
+ U42 = "https://unit42.paloaltonetworks.com/exploit-of-aws-agentcore-iam-god-mode/"
75
+ SONRAI = "https://sonraisecurity.com/blog/aws-agentcore-privilege-escalation-bedrock-scp-fix/"
76
+ SONRAI_EXFIL = "https://sonraisecurity.com/blog/sandboxed-to-compromised-new-research-exposes-credential-exfiltration-paths-in-aws-code-interpreters/"
77
+ AWS_DEFAULT_ROLES = "https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-permissions.html"
78
+
79
+
80
+ def _any(p: Principal, actions: list[str], tpl: str) -> tuple[list[str], bool]:
81
+ hits, cond = [], False
82
+ for a in actions:
83
+ g = can(p, a, tpl)
84
+ if g.allowed:
85
+ hits.append(a.split(":")[1])
86
+ cond = cond or g.conditional
87
+ return hits, cond
88
+
89
+
90
+ def admin_like(p: Principal) -> bool:
91
+ return (
92
+ any(can(p, a, "arn:{part}:iam::{account}:role/{probe}").allowed for a in ("iam:PutRolePolicy", "iam:AttachRolePolicy"))
93
+ or can(p, "iam:CreateAccessKey", "arn:{part}:iam::{account}:user/{probe}").allowed
94
+ )
95
+
96
+
97
+ def check_agent_role(p: Principal) -> list[Finding]:
98
+ """Execution roles (trusted by bedrock-agentcore.amazonaws.com): cross-agent reach."""
99
+ out: list[Finding] = []
100
+ name = f"role/{p.name}"
101
+ read, c1 = _any(p, MEMORY_READ, MEMORY)
102
+ write, c2 = _any(p, MEMORY_WRITE, MEMORY)
103
+ if read or write:
104
+ out.append(
105
+ Finding(
106
+ "ACIA-001",
107
+ "high",
108
+ name,
109
+ "Agent role can reach other agents' memory",
110
+ f"read: {', '.join(read) or '-'}; write/poison: {', '.join(write) or '-'} on memory not owned by this agent "
111
+ "(memory/* or *). Scope Resource to this agent's memory ARN.",
112
+ c1 or c2,
113
+ [U42],
114
+ )
115
+ )
116
+ g = can(p, "bedrock-agentcore:InvokeAgentRuntime", RUNTIME)
117
+ if g.allowed:
118
+ out.append(
119
+ Finding(
120
+ "ACIA-002",
121
+ "high",
122
+ name,
123
+ "Agent role can invoke other agents",
124
+ "InvokeAgentRuntime on runtimes not owned by this agent (runtime/* or *). A compromised agent can "
125
+ "drive every other agent in the account.",
126
+ g.conditional,
127
+ [U42],
128
+ )
129
+ )
130
+ hits, c = _any(
131
+ p, ["bedrock-agentcore:InvokeCodeInterpreter", "bedrock-agentcore:StartCodeInterpreterSession"], CODE_INTERPRETER
132
+ )
133
+ if hits:
134
+ out.append(
135
+ Finding(
136
+ "ACIA-003",
137
+ "high",
138
+ name,
139
+ "Agent role can use other code interpreters in the account",
140
+ f"{', '.join(hits)} on account code interpreters (code-interpreter/* or *). Code runs with each "
141
+ "interpreter's execution role, not this agent's. Scope to aws.codeinterpreter.v1 or this agent's own.",
142
+ c,
143
+ [U42, SONRAI],
144
+ )
145
+ )
146
+ pull, c = _any(p, ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"], ECR_REPO)
147
+ if pull and can(p, "ecr:GetAuthorizationToken", "*").allowed:
148
+ out.append(
149
+ Finding(
150
+ "ACIA-004",
151
+ "medium",
152
+ name,
153
+ "Agent role can pull other agents' container images",
154
+ "ECR pull on repositories not owned by this agent (repository/* or *). Images can contain memory "
155
+ "IDs, endpoints and config used to target other agents.",
156
+ c,
157
+ [U42],
158
+ )
159
+ )
160
+ s1, s2 = can(p, "secretsmanager:GetSecretValue", ID_SECRET), can(p, "secretsmanager:GetSecretValue", ID_APIKEY)
161
+ if s1.allowed or s2.allowed:
162
+ out.append(
163
+ Finding(
164
+ "ACIA-005",
165
+ "medium",
166
+ name,
167
+ "Agent role can read every AgentCore Identity credential secret",
168
+ "secretsmanager:GetSecretValue on bedrock-agentcore-identity!default/oauth2/* or /apikey/*: the "
169
+ "OAuth client secrets and API keys of all credential providers in the account's default token "
170
+ "vault, not just the ones this agent uses (unless a resource policy on each secret denies it, which IAM data alone cannot show).",
171
+ all(g.conditional for g in (s1, s2) if g.allowed),
172
+ )
173
+ )
174
+ if DEFAULT_ROLE_RX.match(p.name):
175
+ out.append(
176
+ Finding(
177
+ "ACIA-020",
178
+ "low",
179
+ name,
180
+ "AgentCore starter-toolkit default role",
181
+ "Auto-created by the starter toolkit. AWS: these default roles are for development and testing "
182
+ "and should never be used in production. Replace with a least-privilege role per agent.",
183
+ refs=[AWS_DEFAULT_ROLES, U42],
184
+ )
185
+ )
186
+ conds = [
187
+ st.get("Condition") or {}
188
+ for st in as_list((p.trust or {}).get("Statement"))
189
+ if AGENTCORE_SERVICE
190
+ in as_list((st.get("Principal") or {}).get("Service") if isinstance(st.get("Principal"), dict) else [])
191
+ ]
192
+ keys = {k.lower() for c in conds for kv in c.values() for k in kv}
193
+ if conds and not ({"aws:sourceaccount", "aws:sourcearn"} & keys):
194
+ out.append(
195
+ Finding(
196
+ "ACIA-021",
197
+ "medium",
198
+ name,
199
+ "Trust policy lacks confused-deputy protection",
200
+ "bedrock-agentcore.amazonaws.com can assume this role with no aws:SourceAccount / aws:SourceArn "
201
+ "condition, so AgentCore resources in other accounts could be configured to use it.",
202
+ refs=["https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html"],
203
+ )
204
+ )
205
+ return out
206
+
207
+
208
+ def check_privesc(p: Principal, agent_roles: list[Principal]) -> list[Finding]:
209
+ """Any principal: create a code interpreter with a powerful AgentCore role, then run code as it."""
210
+ out: list[Finding] = []
211
+ name = f"{p.kind}/{p.name}"
212
+ if admin_like(p):
213
+ return out # already admin-equivalent: nothing to escalate to
214
+ create = can(p, "bedrock-agentcore:CreateCodeInterpreter", CODE_INTERPRETER)
215
+ invoke = can(p, "bedrock-agentcore:InvokeCodeInterpreter", CODE_INTERPRETER)
216
+ if invoke.allowed and not p.trusts_service():
217
+ out.append(
218
+ Finding(
219
+ "ACIA-011",
220
+ "medium",
221
+ name,
222
+ "Can run code in any custom code interpreter",
223
+ "InvokeCodeInterpreter on account code interpreters: code runs with each interpreter's execution "
224
+ "role, and CloudTrail attributes the role's API calls to the interpreter rather than this "
225
+ "principal.",
226
+ invoke.conditional,
227
+ [SONRAI],
228
+ )
229
+ )
230
+ if not (create.allowed and invoke.allowed):
231
+ return out
232
+ passable = []
233
+ for r in agent_roles:
234
+ if r.arn == p.arn:
235
+ continue
236
+ g = evaluate(p.statements, "iam:PassRole", r.arn, passed_to_service=AGENTCORE_SERVICE)
237
+ if g.allowed and p.boundary is not None:
238
+ g = evaluate(p.boundary, "iam:PassRole", r.arn, passed_to_service=AGENTCORE_SERVICE)
239
+ if g.allowed:
240
+ passable.append((r, g.conditional))
241
+ if not passable:
242
+ return out
243
+ strong = [r.name for r, _ in passable if admin_like(r)]
244
+ names = ", ".join(sorted(r.name for r, _ in passable)[:8]) + (" ..." if len(passable) > 8 else "")
245
+ out = [f for f in out if f.id != "ACIA-011"] # superseded by the escalation finding
246
+ out.append(
247
+ Finding(
248
+ "ACIA-010",
249
+ "high" if strong else "medium",
250
+ name,
251
+ "Privilege escalation via code interpreter (PassRole + Create/InvokeCodeInterpreter)",
252
+ f"Can create a code interpreter with an AgentCore role it can pass and run code as that role: {names}."
253
+ + (f" Admin-equivalent: {', '.join(strong)}." if strong else ""),
254
+ create.conditional or invoke.conditional or all(c for _, c in passable),
255
+ [SONRAI],
256
+ )
257
+ )
258
+ return out
259
+
260
+
261
+ def audit(principals: list[Principal]) -> list[Finding]:
262
+ agent_roles = [p for p in principals if p.kind == "role" and p.trusts_service()]
263
+ findings: list[Finding] = []
264
+ for r in agent_roles:
265
+ findings += check_agent_role(r)
266
+ for p in principals:
267
+ findings += check_privesc(p, agent_roles)
268
+ findings.sort(key=lambda f: (-SEV[f.severity], f.id, f.principal))
269
+ return findings
@@ -0,0 +1,135 @@
1
+ """agentcore-iam-audit command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from dataclasses import asdict
10
+ from pathlib import Path
11
+
12
+ from . import __version__
13
+ from .checks import SEV, audit
14
+ from .iam import from_file, from_live, load_gaad
15
+
16
+
17
+ def _single_policy(policy: str, trust: str | None, name: str, account: str) -> list:
18
+ doc = json.loads(Path(policy).read_text(encoding="utf-8-sig"))
19
+ trust_doc = (
20
+ json.loads(Path(trust).read_text(encoding="utf-8-sig"))
21
+ if trust
22
+ else {
23
+ "Statement": [
24
+ {
25
+ "Effect": "Allow",
26
+ "Principal": {"Service": "bedrock-agentcore.amazonaws.com"},
27
+ "Action": "sts:AssumeRole",
28
+ "Condition": {"StringEquals": {"aws:SourceAccount": account}},
29
+ }
30
+ ]
31
+ }
32
+ )
33
+ return load_gaad(
34
+ {
35
+ "RoleDetailList": [
36
+ {
37
+ "RoleName": name,
38
+ "Arn": f"arn:aws:iam::{account}:role/{name}",
39
+ "AssumeRolePolicyDocument": trust_doc,
40
+ "RolePolicyList": [{"PolicyName": Path(policy).name, "PolicyDocument": doc}],
41
+ "AttachedManagedPolicies": [],
42
+ }
43
+ ]
44
+ }
45
+ )
46
+
47
+
48
+ def render(findings, inventory, color: bool) -> str:
49
+ def c(code, s):
50
+ return f"\033[{code}m{s}\033[0m" if color else s
51
+
52
+ col = {"high": "31", "medium": "33", "low": "36", "info": "2"}
53
+ lines = [c("1", f"agentcore-iam-audit {__version__}"), ""]
54
+ if inventory:
55
+ lines.append(c("1", "AgentCore resources"))
56
+ for i in inventory:
57
+ lines.append(
58
+ f" {i['type']:<17} {i['name']:<30} role={str(i.get('role') or '-').split('/')[-1]} network={i.get('network') or '-'}"
59
+ )
60
+ lines.append("")
61
+ for f in findings:
62
+ tag = c(col[f.severity], f"[{f.severity.upper()}]")
63
+ lines.append(f"{tag} {f.id} {c('1', f.principal)} {f.title}" + (c("2", " (conditional)") if f.conditional else ""))
64
+ lines.append(f" {f.detail}")
65
+ for r in f.refs:
66
+ lines.append(c("2", f" ref: {r}"))
67
+ counts = {s: sum(1 for f in findings if f.severity == s) for s in SEV}
68
+ lines += ["", c("1", f"{len(findings)} finding(s): {counts['high']} high, {counts['medium']} medium, {counts['low']} low")]
69
+ return "\n".join(lines)
70
+
71
+
72
+ def main(argv: list[str] | None = None) -> int:
73
+ p = argparse.ArgumentParser(
74
+ prog="agentcore-iam-audit",
75
+ description="Find Amazon Bedrock AgentCore IAM paths: agents reaching other agents' memory, runtimes, code "
76
+ "interpreters, images and secrets, and privilege escalation through code interpreters.",
77
+ )
78
+ src = p.add_mutually_exclusive_group(required=True)
79
+ src.add_argument("--gaad", metavar="FILE", help="output of `aws iam get-account-authorization-details` (offline)")
80
+ src.add_argument("--live", action="store_true", help="read IAM + AgentCore inventory with your AWS credentials (read-only)")
81
+ src.add_argument("--policy", metavar="FILE", help="check one execution-role policy document before deploying it")
82
+ p.add_argument("--trust", metavar="FILE", help="with --policy: the role's trust policy")
83
+ p.add_argument("--role-name", default="candidate-agent-role", help="with --policy: role name to report")
84
+ p.add_argument("--account", default="111122223333", help="with --policy: account id the role lives in")
85
+ p.add_argument("--profile", help="with --live: AWS profile")
86
+ p.add_argument("--region", action="append", help="with --live: AgentCore region(s) to inventory (default: session region)")
87
+ p.add_argument("-f", "--format", choices=["text", "json"], default="text")
88
+ p.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="high")
89
+ p.add_argument("--no-color", action="store_true")
90
+ p.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
91
+ a = p.parse_args(argv)
92
+
93
+ inventory, extra = [], []
94
+ if a.gaad:
95
+ principals = from_file(a.gaad)
96
+ elif a.policy:
97
+ principals = _single_policy(a.policy, a.trust, a.role_name, a.account)
98
+ else:
99
+ try:
100
+ import boto3
101
+ except ImportError:
102
+ print("live mode needs boto3: pip install 'agentcore-iam-audit[live]'", file=sys.stderr)
103
+ return 2
104
+ from .live import inventory as live_inventory
105
+
106
+ session = boto3.session.Session(profile_name=a.profile)
107
+ principals = from_live(session)
108
+ for region in a.region or [session.region_name or "us-east-1"]:
109
+ items, f = live_inventory(session, region)
110
+ inventory += items
111
+ extra += f
112
+
113
+ findings = audit(principals) + extra
114
+ findings.sort(key=lambda f: (-SEV[f.severity], f.id, f.principal))
115
+ if a.format == "json":
116
+ print(
117
+ json.dumps(
118
+ {
119
+ "version": __version__,
120
+ "principals": len(principals),
121
+ "inventory": inventory,
122
+ "findings": [asdict(f) for f in findings],
123
+ },
124
+ indent=2,
125
+ )
126
+ )
127
+ else:
128
+ color = not a.no_color and sys.stdout.isatty() and "NO_COLOR" not in os.environ
129
+ print(render(findings, inventory, color))
130
+ threshold = {"none": 99, **SEV}[a.fail_on]
131
+ return 1 if any(SEV[f.severity] >= threshold for f in findings) else 0
132
+
133
+
134
+ if __name__ == "__main__":
135
+ raise SystemExit(main())
@@ -0,0 +1,113 @@
1
+ """Load IAM state from `aws iam get-account-authorization-details` (file or live) into principals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from urllib.parse import unquote
9
+
10
+ from .policy import as_list
11
+
12
+ AGENTCORE_SERVICE = "bedrock-agentcore.amazonaws.com"
13
+
14
+
15
+ def _doc(d):
16
+ """Policy documents arrive as dicts (boto3), JSON strings, or URL-encoded JSON (some CLI paths)."""
17
+ if isinstance(d, dict):
18
+ return d
19
+ if isinstance(d, str):
20
+ s = d if d.lstrip().startswith("{") else unquote(d)
21
+ return json.loads(s)
22
+ return {"Statement": []}
23
+
24
+
25
+ def _statements(name: str, doc) -> list[tuple[str, dict]]:
26
+ return [(name, st) for st in as_list(_doc(doc).get("Statement"))]
27
+
28
+
29
+ @dataclass
30
+ class Principal:
31
+ kind: str # role | user
32
+ name: str
33
+ arn: str
34
+ statements: list[tuple[str, dict]] = field(default_factory=list)
35
+ boundary: list[tuple[str, dict]] | None = None
36
+ trust: dict | None = None # roles only
37
+
38
+ @property
39
+ def account(self) -> str:
40
+ parts = self.arn.split(":")
41
+ return parts[4] if len(parts) > 4 else ""
42
+
43
+ @property
44
+ def partition(self) -> str:
45
+ parts = self.arn.split(":")
46
+ return parts[1] if len(parts) > 1 else "aws"
47
+
48
+ def trusts_service(self, service: str = AGENTCORE_SERVICE) -> bool:
49
+ for st in as_list((self.trust or {}).get("Statement")):
50
+ if st.get("Effect") != "Allow":
51
+ continue
52
+ svc = as_list((st.get("Principal") or {}).get("Service")) if isinstance(st.get("Principal"), dict) else []
53
+ if service in svc:
54
+ return True
55
+ return False
56
+
57
+
58
+ def load_gaad(data: dict) -> list[Principal]:
59
+ managed: dict[str, dict] = {}
60
+ for p in data.get("Policies", []):
61
+ default = next((v for v in p.get("PolicyVersionList", []) if v.get("IsDefaultVersion")), None)
62
+ if default:
63
+ managed[p["Arn"]] = {"name": p.get("PolicyName", p["Arn"]), "doc": default.get("Document")}
64
+
65
+ def attached(lst) -> list[tuple[str, dict]]:
66
+ out = []
67
+ for a in lst or []:
68
+ m = managed.get(a.get("PolicyArn"))
69
+ if m:
70
+ out += _statements(m["name"], m["doc"])
71
+ return out
72
+
73
+ groups = {}
74
+ for g in data.get("GroupDetailList", []):
75
+ st = attached(g.get("AttachedManagedPolicies"))
76
+ for ip in g.get("GroupPolicyList", []):
77
+ st += _statements(f"{g['GroupName']}/{ip['PolicyName']}", ip.get("PolicyDocument"))
78
+ groups[g["GroupName"]] = st
79
+
80
+ def boundary(entity) -> list[tuple[str, dict]] | None:
81
+ pb = entity.get("PermissionsBoundary")
82
+ if not pb:
83
+ return None
84
+ m = managed.get(pb.get("PermissionsBoundaryArn"))
85
+ return _statements(f"boundary:{m['name']}", m["doc"]) if m else None
86
+
87
+ out: list[Principal] = []
88
+ for r in data.get("RoleDetailList", []):
89
+ st = attached(r.get("AttachedManagedPolicies"))
90
+ for ip in r.get("RolePolicyList", []):
91
+ st += _statements(ip["PolicyName"], ip.get("PolicyDocument"))
92
+ out.append(Principal("role", r["RoleName"], r["Arn"], st, boundary(r), _doc(r.get("AssumeRolePolicyDocument") or {})))
93
+ for u in data.get("UserDetailList", []):
94
+ st = attached(u.get("AttachedManagedPolicies"))
95
+ for ip in u.get("UserPolicyList", []):
96
+ st += _statements(ip["PolicyName"], ip.get("PolicyDocument"))
97
+ for g in u.get("GroupList", []):
98
+ st += groups.get(g, [])
99
+ out.append(Principal("user", u["UserName"], u["Arn"], st, boundary(u)))
100
+ return out
101
+
102
+
103
+ def from_file(path: str | Path) -> list[Principal]:
104
+ return load_gaad(json.loads(Path(path).read_text(encoding="utf-8-sig")))
105
+
106
+
107
+ def from_live(session) -> list[Principal]:
108
+ iam = session.client("iam")
109
+ merged: dict[str, list] = {"UserDetailList": [], "GroupDetailList": [], "RoleDetailList": [], "Policies": []}
110
+ for page in iam.get_paginator("get_account_authorization_details").paginate():
111
+ for k in merged:
112
+ merged[k] += page.get(k, [])
113
+ return load_gaad(merged)
@@ -0,0 +1,64 @@
1
+ """Optional live inventory of AgentCore resources (needs boto3 and read-only credentials)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .checks import Finding
6
+
7
+
8
+ def _paginate(call, key, **kw):
9
+ token = None
10
+ while True:
11
+ resp = call(**kw, **({"nextToken": token} if token else {}))
12
+ yield from resp.get(key, [])
13
+ token = resp.get("nextToken")
14
+ if not token:
15
+ return
16
+
17
+
18
+ def inventory(session, region: str) -> tuple[list[dict], list[Finding]]:
19
+ c = session.client("bedrock-agentcore-control", region_name=region)
20
+ items, findings = [], []
21
+ for s in _paginate(c.list_code_interpreters, "codeInterpreterSummaries", type="CUSTOM"):
22
+ d = c.get_code_interpreter(codeInterpreterId=s["codeInterpreterId"])
23
+ mode = (d.get("networkConfiguration") or {}).get("networkMode")
24
+ role = d.get("executionRoleArn")
25
+ items.append(
26
+ {"type": "code-interpreter", "name": d.get("name"), "arn": d.get("codeInterpreterArn"), "role": role, "network": mode}
27
+ )
28
+ if role and mode == "PUBLIC":
29
+ findings.append(
30
+ Finding(
31
+ "ACIA-030",
32
+ "medium",
33
+ f"code-interpreter/{d.get('name')}",
34
+ "Custom code interpreter with an execution role and PUBLIC network",
35
+ f"Code running in it gets {role.split('/')[-1]} credentials and can send them anywhere. Use SANDBOX or VPC "
36
+ "mode, or drop the role.",
37
+ refs=[
38
+ "https://sonraisecurity.com/blog/sandboxed-to-compromised-new-research-exposes-credential-exfiltration-paths-in-aws-code-interpreters/"
39
+ ],
40
+ )
41
+ )
42
+ for s in _paginate(c.list_agent_runtimes, "agentRuntimes"):
43
+ d = c.get_agent_runtime(agentRuntimeId=s["agentRuntimeId"])
44
+ items.append(
45
+ {
46
+ "type": "runtime",
47
+ "name": d.get("agentRuntimeName"),
48
+ "arn": d.get("agentRuntimeArn"),
49
+ "role": d.get("roleArn"),
50
+ "network": (d.get("networkConfiguration") or {}).get("networkMode"),
51
+ }
52
+ )
53
+ for s in _paginate(c.list_browsers, "browserSummaries", type="CUSTOM"):
54
+ d = c.get_browser(browserId=s["browserId"])
55
+ items.append(
56
+ {
57
+ "type": "browser",
58
+ "name": d.get("name"),
59
+ "arn": d.get("browserArn"),
60
+ "role": d.get("executionRoleArn"),
61
+ "network": (d.get("networkConfiguration") or {}).get("networkMode"),
62
+ }
63
+ )
64
+ return items, findings
@@ -0,0 +1,88 @@
1
+ """Minimal IAM policy evaluator: does a set of statements allow an action on a specific resource ARN?
2
+
3
+ Covers what this audit needs: Allow/Deny, Action/NotAction, Resource/NotResource, wildcards (* and ?),
4
+ permission boundaries (by the caller), and visibility into Conditions (reported, not evaluated, except
5
+ `iam:PassedToService`, which is evaluated for iam:PassRole). SCPs and resource policies are out of scope.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass
12
+ from functools import lru_cache
13
+
14
+
15
+ def as_list(x) -> list:
16
+ if x is None:
17
+ return []
18
+ return x if isinstance(x, list) else [x]
19
+
20
+
21
+ @lru_cache(maxsize=4096)
22
+ def _rx(pattern: str, case_insensitive: bool) -> re.Pattern:
23
+ body = "".join(".*" if c == "*" else "." if c == "?" else re.escape(c) for c in pattern)
24
+ return re.compile(f"^{body}$", (re.I if case_insensitive else 0) | re.S)
25
+
26
+
27
+ def action_matches(pattern: str, action: str) -> bool:
28
+ return bool(_rx(pattern, True).match(action))
29
+
30
+
31
+ def resource_matches(pattern: str, arn: str) -> bool:
32
+ return bool(_rx(pattern, False).match(arn))
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Grant:
37
+ allowed: bool
38
+ conditional: bool = False # an allowing statement carried a Condition we did not evaluate
39
+ source: str = "" # policy name that granted it
40
+
41
+
42
+ def _matches(stmt: dict, action: str, arn: str) -> bool:
43
+ if "NotAction" in stmt:
44
+ if any(action_matches(p, action) for p in as_list(stmt["NotAction"])):
45
+ return False
46
+ elif not any(action_matches(p, action) for p in as_list(stmt.get("Action"))):
47
+ return False
48
+ if "NotResource" in stmt:
49
+ return not any(resource_matches(p, arn) for p in as_list(stmt["NotResource"]))
50
+ return any(resource_matches(p, arn) for p in as_list(stmt.get("Resource")))
51
+
52
+
53
+ def _passed_to_service_ok(stmt: dict, service: str | None) -> bool:
54
+ """Evaluate iam:PassedToService conditions for PassRole. Unknown conditions are treated as satisfiable."""
55
+ if not service:
56
+ return True
57
+ for op, kv in (stmt.get("Condition") or {}).items():
58
+ for key, vals in (kv or {}).items():
59
+ if key.lower() != "iam:passedtoservice":
60
+ continue
61
+ vals = [str(v) for v in as_list(vals)]
62
+ op_l = op.lower()
63
+ if op_l.startswith("stringequals") and service not in vals:
64
+ return False
65
+ if op_l.startswith("stringlike") and not any(action_matches(v, service) for v in vals):
66
+ return False
67
+ if op_l.startswith("stringnotequals") and service in vals:
68
+ return False
69
+ return True
70
+
71
+
72
+ def evaluate(statements: list[tuple[str, dict]], action: str, arn: str, *, passed_to_service: str | None = None) -> Grant:
73
+ """statements: (policy_name, statement) pairs from all identity policies of a principal."""
74
+ allow: Grant | None = None
75
+ for name, st in statements:
76
+ if not _matches(st, action, arn):
77
+ continue
78
+ if st.get("Effect") == "Deny":
79
+ if not st.get("Condition"):
80
+ return Grant(False, source=name)
81
+ continue # conditional deny: can't prove it applies; keep evaluating
82
+ if st.get("Effect") == "Allow" and _passed_to_service_ok(st, passed_to_service):
83
+ cond = bool(st.get("Condition")) and not (
84
+ passed_to_service and set(k.lower() for kv in st["Condition"].values() for k in kv) == {"iam:passedtoservice"}
85
+ )
86
+ if allow is None or (allow.conditional and not cond):
87
+ allow = Grant(True, conditional=cond, source=name)
88
+ return allow or Grant(False)
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentcore-iam-audit
3
+ Version: 0.1.1
4
+ Summary: Find Amazon Bedrock AgentCore IAM paths: agents reaching other agents' memory, runtimes, code interpreters and secrets, and code-interpreter privilege escalation.
5
+ Project-URL: Homepage, https://github.com/garag0l/agentcore-iam-audit
6
+ Project-URL: Issues, https://github.com/garag0l/agentcore-iam-audit/issues
7
+ Project-URL: Changelog, https://github.com/garag0l/agentcore-iam-audit/blob/main/CHANGELOG.md
8
+ Author: Murat Bekgi
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: agentcore,ai-security,aws,bedrock,cloud-security,iam,privilege-escalation,security
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Information Technology
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Security
17
+ Requires-Python: >=3.11
18
+ Provides-Extra: dev
19
+ Requires-Dist: boto3>=1.40; extra == 'dev'
20
+ Requires-Dist: pytest>=8; extra == 'dev'
21
+ Requires-Dist: ruff>=0.6; extra == 'dev'
22
+ Provides-Extra: live
23
+ Requires-Dist: boto3>=1.40; extra == 'live'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # agentcore-iam-audit
27
+
28
+ **Find the IAM paths that let one Amazon Bedrock AgentCore agent read or poison another agent's memory, invoke other agents, use their code interpreters, or let a developer run code as a more powerful role.**
29
+
30
+ [![CI](https://github.com/garag0l/agentcore-iam-audit/actions/workflows/ci.yml/badge.svg)](https://github.com/garag0l/agentcore-iam-audit/actions/workflows/ci.yml)
31
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
32
+ ![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)
33
+ ![Offline mode: zero dependencies](https://img.shields.io/badge/offline%20mode-0%20dependencies-brightgreen)
34
+
35
+ ![agentcore-iam-audit output](docs/demo.svg)
36
+
37
+ ## Why this exists
38
+
39
+ - **Agent "God Mode" (Unit 42, April 2026).** Execution roles auto-created by the AgentCore starter toolkit granted access to `memory/*`, `runtime/*`, `code-interpreter/*` and `repository/*`. Any agent could pull another agent's image, find its memory ID, then dump or poison that agent's memory, and invoke any other agent. AWS's answer: the default roles are for development and testing and "should never be used in a production system". The toolkit template was scoped down on 2025-12-09, but roles created before that still exist in accounts. ([Unit 42](https://unit42.paloaltonetworks.com/exploit-of-aws-agentcore-iam-god-mode/))
40
+ - **Code-interpreter privilege escalation (Sonrai, 2025).** A principal with `iam:PassRole` + `CreateCodeInterpreter` + `InvokeCodeInterpreter` runs code as the interpreter's role, and CloudTrail attributes the calls to the interpreter, not to the person. ([Sonrai](https://sonraisecurity.com/blog/aws-agentcore-privilege-escalation-bedrock-scp-fix/), [CSA](https://labs.cloudsecurityalliance.org/research/csa-research-note-bedrock-agentcore-enterprise-attack-surfac/))
41
+ - **AWS's own managed policy feeds that path.** `BedrockAgentCoreFullAccess` (v21) grants `bedrock-agentcore:*` and `iam:PassRole` on every role whose name contains `BedrockAgentCore`. That includes the toolkit's default roles and any admin role someone named `...BedrockAgentCore...`.
42
+
43
+ General IAM scanners don't model AgentCore resources. This tool asks the concrete question for each role: *can it reach a resource belonging to a **different** agent?* It evaluates Allow, Deny, NotAction/NotResource and permission boundaries against probe ARNs.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pipx install agentcore-iam-audit # offline mode, zero dependencies
49
+ pipx install "agentcore-iam-audit[live]" # + live mode (boto3)
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ```bash
55
+ # Offline: no credentials on the machine running the audit
56
+ aws iam get-account-authorization-details > gaad.json
57
+ agentcore-iam-audit --gaad gaad.json
58
+
59
+ # Live, read-only: IAM + AgentCore inventory (code interpreters, runtimes, browsers)
60
+ agentcore-iam-audit --live --profile audit --region us-east-1 --region us-west-2
61
+
62
+ # Before deploying: check one execution-role policy (e.g. from CDK/Terraform output)
63
+ agentcore-iam-audit --policy role-policy.json --trust trust-policy.json --role-name my-agent-role
64
+
65
+ agentcore-iam-audit --gaad gaad.json -f json --fail-on medium
66
+ ```
67
+
68
+ Live mode needs `iam:GetAccountAuthorizationDetails` plus `bedrock-agentcore:List*`/`Get*` on code interpreters, runtimes and browsers. The AWS managed `SecurityAudit` policy covers the IAM part. Exit code `1` when anything is at or above `--fail-on` (default `high`).
69
+
70
+ ## Checks
71
+
72
+ | ID | Severity | Who | Finding |
73
+ |---|---|---|---|
74
+ | ACIA-001 | high | agent role | Read or write memory not owned by this agent (memory dump / poisoning) |
75
+ | ACIA-002 | high | agent role | `InvokeAgentRuntime` on other agents |
76
+ | ACIA-003 | high | agent role | Invoke other code interpreters in the account (code runs as *their* roles) |
77
+ | ACIA-004 | medium | agent role | Pull other agents' container images (memory IDs and config inside) |
78
+ | ACIA-005 | medium | agent role | `GetSecretValue` on **all** AgentCore Identity credential-provider secrets (`bedrock-agentcore-identity!default/oauth2/*`, `/apikey/*`) |
79
+ | ACIA-010 | high / medium | any principal | Privilege escalation: PassRole an AgentCore role + Create/InvokeCodeInterpreter. High when a passable role is admin-equivalent |
80
+ | ACIA-011 | medium | any principal | Run code in existing custom code interpreters as their execution roles |
81
+ | ACIA-020 | low | agent role | Starter-toolkit default role (`AmazonBedrockAgentCoreSDKRuntime-*`, `...SDKCodeBuild-*`, `AgentCoreEvalsSDK-*`) |
82
+ | ACIA-021 | medium | agent role | Trust policy for `bedrock-agentcore.amazonaws.com` without `aws:SourceAccount`/`aws:SourceArn` (confused deputy) |
83
+ | ACIA-030 | medium | live | Custom code interpreter with an execution role in `PUBLIC` network mode (credential exfiltration path) |
84
+
85
+ "Agent role" means a role that `bedrock-agentcore.amazonaws.com` can assume. Findings marked `(conditional)` came from a statement with a Condition the tool didn't evaluate; check it by hand.
86
+
87
+ ## How it was tested
88
+
89
+ - **Real policy documents, not invented ones:**
90
+ - the starter toolkit's execution-role template from just before the 2025-12-09 scoping fix, and the current version, both rendered with Jinja2 as the toolkit does;
91
+ - its trust policy;
92
+ - AWS's managed `BedrockAgentCoreFullAccess` (v21, from the [MAMIP](https://github.com/z0ph/MAMIP) archive).
93
+ - **Results:**
94
+ - The pre-fix role produces every Unit 42 path.
95
+ - The current role produces only ACIA-005 and the default-role notice.
96
+ - A user holding only `BedrockAgentCoreFullAccess` is flagged for escalation to an admin role named `MyBedrockAgentCoreDeployRole`, but not to `prod-admin`.
97
+ - **Negative cases:** explicit `Deny` + `NotResource`, a read-only permission boundary, PassRole limited to another service (`iam:PassedToService`), region-scoped policies, and admin principals (nothing to escalate to).
98
+ - **Live mode:** tested with botocore's `Stubber`, so every request and response is validated against AWS's real API model for `bedrock-agentcore-control`.
99
+ - **CI:** Linux/macOS/Windows × Python 3.11–3.14. CI also rebuilds the account fixture from the source documents and fails if it drifts.
100
+
101
+ ## Limits
102
+
103
+ - SCPs, resource-based policies and session policies aren't evaluated. A finding means "identity policy allows it". An SCP may still block it, as Sonrai and CSA recommend.
104
+ - Conditions other than `iam:PassedToService` are reported, not evaluated.
105
+ - "Admin-equivalent" means the role can modify IAM role policies or create user access keys.
106
+
107
+ ## Responsible use
108
+
109
+ For accounts you own or are authorized to assess. The tool is read-only: offline mode reads a JSON file, and live mode calls only `Get*`/`List*` APIs.
110
+
111
+ ## License
112
+
113
+ [MIT](LICENSE)
@@ -0,0 +1,12 @@
1
+ agentcore_iam_audit/__init__.py,sha256=Sx6FNqVqMHANWg2izjiYEoy6K9yAboNuOa7cuPhTaPw,130
2
+ agentcore_iam_audit/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ agentcore_iam_audit/checks.py,sha256=lXkYOtHTF2YvUIFGu6_oAF-Z_tAiQxB4YZJ_KUKdyng,11447
4
+ agentcore_iam_audit/cli.py,sha256=26N-rBuM66usCBeQGf3AYmIbZaNf8GjdZf6DhkmXi5c,5589
5
+ agentcore_iam_audit/iam.py,sha256=axaTpNPaR8ogzOpZJ88i46ykhoIuiKmXDsewB8qTxrk,4138
6
+ agentcore_iam_audit/live.py,sha256=_-CY3qdddJ5toZpSEJx-Wz0p6a69e57CIkc3WicTSds,2674
7
+ agentcore_iam_audit/policy.py,sha256=loYiHnQ4VNYoFFL17h_5cLnKYrEcoQoVaykCgycxzJ4,3639
8
+ agentcore_iam_audit-0.1.1.dist-info/METADATA,sha256=PouG28rUbAaY6N5-9Af6WcwuywlJrkH9rkA8Jh9hkkg,7789
9
+ agentcore_iam_audit-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ agentcore_iam_audit-0.1.1.dist-info/entry_points.txt,sha256=N7ZO9bnYUO9qE6g6fcNFskc5mgAIXiG-1JuWlpAcXbI,69
11
+ agentcore_iam_audit-0.1.1.dist-info/licenses/LICENSE,sha256=D6JY7jCBe2W2D67E-6i-EEcUFpFb1--OY1eOiiLjbIM,1068
12
+ agentcore_iam_audit-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ agentcore-iam-audit = agentcore_iam_audit.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Murat Bekgi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.