npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
Overview
IAM permission boundaries are an advanced AWS feature that sets the maximum permissions an identity-based policy can grant to an IAM entity (user or role). They enable centralized security teams to safely delegate IAM role and policy creation to application developers without risking privilege escalation. The effective permissions of an entity are the intersection of its identity-based policies and its permission boundary -- even if an identity policy grants AdministratorAccess, the permission boundary restricts it to only the allowed actions.
When to Use
- When deploying or configuring implementing aws iam permission boundaries capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- AWS account with IAM administrative access
- Understanding of AWS IAM policy language (JSON)
- AWS CLI v2 configured with appropriate credentials
- Terraform or CloudFormation for infrastructure-as-code deployment
Core Concepts
How Permission Boundaries Work
Identity-Based Policy Permission Boundary
(What the role CAN do) ∩ (What the role MAY do)
│ │
└──────────┬───────────────────┘
│
Effective Permissions
(Only actions in BOTH policies)Policy Evaluation Logic
AWS evaluates permissions in this order:
- Explicit Deny in any policy - always wins
- Organizations SCP - sets org-wide maximum
- Permission Boundary - sets entity-level maximum
- Identity-Based Policy - grants actual permissions
- Resource-Based Policy - cross-account access (evaluated separately)
The entity can only perform an action if ALL applicable policy types allow it.
Key Use Cases
| Use Case | Description |
|---|---|
| Developer Delegation | Allow devs to create IAM roles without escalating beyond their boundary |
| Sandbox Isolation | Limit what roles can do in sandbox/dev accounts |
| Multi-Tenant Workloads | Ensure tenant-specific roles cannot access other tenants' resources |
| CI/CD Pipeline Roles | Restrict automation roles to specific services |
Workflow
Step 1: Define the Permission Boundary Policy
Create a managed policy that defines the maximum allowed permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowedServices",
"Effect": "Allow",
"Action": [
"s3:*",
"dynamodb:*",
"lambda:*",
"logs:*",
"cloudwatch:*",
"sqs:*",
"sns:*",
"events:*",
"states:*",
"xray:*",
"ec2:Describe*",
"ec2:CreateTags",
"sts:AssumeRole",
"kms:Decrypt",
"kms:GenerateDataKey",
"kms:DescribeKey",
"secretsmanager:GetSecretValue"
],
"Resource": "*"
},
{
"Sid": "AllowIAMPassRole",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::*:role/app-*",
"Condition": {
"StringEquals": {
"iam:PassedToService": [
"lambda.amazonaws.com",
"states.amazonaws.com"
]
}
}
},
{
"Sid": "DenyBoundaryDeletion",
"Effect": "Deny",
"Action": [
"iam:DeletePolicy",
"iam:DeletePolicyVersion",
"iam:CreatePolicyVersion"
],
"Resource": "arn:aws:iam::*:policy/DeveloperBoundary"
},
{
"Sid": "DenyBoundaryRemoval",
"Effect": "Deny",
"Action": [
"iam:DeleteUserPermissionsBoundary",
"iam:DeleteRolePermissionsBoundary"
],
"Resource": "*"
}
]
}Step 2: Create the Developer Delegation Policy
Grant developers the ability to create IAM roles, but only with the boundary attached:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCreateRoleWithBoundary",
"Effect": "Allow",
"Action": [
"iam:CreateRole",
"iam:AttachRolePolicy",
"iam:DetachRolePolicy",
"iam:PutRolePolicy",
"iam:DeleteRolePolicy"
],
"Resource": "arn:aws:iam::*:role/app-*",
"Condition": {
"StringEquals": {
"iam:PermissionsBoundary": "arn:aws:iam::*:policy/DeveloperBoundary"
}
}
},
{
"Sid": "AllowCreatePolicyScoped",
"Effect": "Allow",
"Action": [
"iam:CreatePolicy",
"iam:DeletePolicy",
"iam:CreatePolicyVersion",
"iam:DeletePolicyVersion"
],
"Resource": "arn:aws:iam::*:policy/app-*"
},
{
"Sid": "AllowViewIAM",
"Effect": "Allow",
"Action": [
"iam:Get*",
"iam:List*"
],
"Resource": "*"
}
]
}Step 3: Attach the Boundary
# Create the boundary policy
aws iam create-policy \
--policy-name DeveloperBoundary \
--policy-document file://developer-boundary.json
# Attach boundary to an existing role
aws iam put-role-permissions-boundary \
--role-name developer-role \
--permissions-boundary arn:aws:iam::123456789012:policy/DeveloperBoundary
# Create a new role with boundary
aws iam create-role \
--role-name app-lambda-executor \
--assume-role-policy-document file://trust-policy.json \
--permissions-boundary arn:aws:iam::123456789012:policy/DeveloperBoundaryStep 4: Prevent Privilege Escalation
The boundary must include deny statements to prevent developers from:
- Removing the boundary from their own roles
- Modifying the boundary policy itself
- Creating roles without the boundary attached
- Accessing IAM services to escalate privileges
Step 5: Deploy with Terraform
resource "aws_iam_policy" "developer_boundary" {
name = "DeveloperBoundary"
path = "/"
policy = file("${path.module}/policies/developer-boundary.json")
}
resource "aws_iam_role" "app_role" {
name = "app-lambda-executor"
assume_role_policy = data.aws_iam_policy_document.lambda_trust.json
permissions_boundary = aws_iam_policy.developer_boundary.arn
}Validation Checklist
- Permission boundary policy created and reviewed by security team
- Boundary includes deny statements preventing self-modification
- Developer delegation policy requires boundary on all new roles
- Role naming convention enforced (e.g.,
app-*prefix) - Developers tested creating roles with and without boundary (should fail without)
- Privilege escalation paths tested and blocked
- CloudTrail logging enabled for IAM API calls
- Boundary policy versioned in source control
- Automated tests validate boundary effectiveness
- Documentation provided to development teams
References
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.8 KB
API Reference: AWS IAM Permission Boundary Agent
Dependencies
| Library | Version | Purpose |
|---|---|---|
| boto3 | >=1.28 | AWS SDK for IAM permission boundary management |
CLI Usage
python scripts/agent.py \
--profile security-admin \
--region us-east-1 \
--audit \
--output-dir /reports/ \
--output iam_boundary_report.jsonFunctions
get_iam_client(profile, region)
Creates boto3 IAM client with optional named profile.
create_permission_boundary(client, policy_name, allowed_services, allowed_regions) -> dict
Creates an IAM policy for use as a permission boundary. Includes a DenyBoundaryChanges statement to prevent boundary removal. Uses client.create_policy().
attach_boundary_to_role(client, role_name, boundary_arn) -> dict
Calls client.put_role_permissions_boundary() to attach a boundary to a role.
audit_roles_without_boundary(client) -> list
Paginates client.list_roles() and identifies roles missing PermissionsBoundary.
audit_boundary_effectiveness(client, role_name) -> dict
Calls client.get_role(), list_attached_role_policies(), list_role_policies() to show effective policy stack.
generate_report(client) -> dict
Orchestrates audit and generates compliance report.
boto3 IAM Methods Used
| Method | Purpose |
|---|---|
create_policy(PolicyName, PolicyDocument) |
Create boundary policy |
put_role_permissions_boundary(RoleName, PermissionsBoundary) |
Attach boundary |
list_roles() |
Enumerate all roles |
get_role(RoleName) |
Get role details including boundary |
Output Schema
{
"roles_without_boundary_count": 12,
"roles_without_boundary": [{"role_name": "dev-role", "arn": "arn:aws:iam::..."}],
"recommendations": ["Attach permission boundaries to 12 roles"]
}standards.md1.8 KB
AWS IAM Permission Boundaries - Standards Reference
AWS IAM Policy Types
| Policy Type | Scope | Purpose |
|---|---|---|
| Identity-Based | Attached to users/roles/groups | Grants permissions |
| Resource-Based | Attached to resources (S3, KMS) | Cross-account access |
| Permission Boundary | Attached to users/roles | Maximum permission limit |
| Organizations SCP | Attached to OUs/accounts | Organization-wide limit |
| Session Policy | Passed during AssumeRole | Session-level limit |
AWS Well-Architected Framework - Security Pillar
SEC02 - Identity Management
- SEC02-BP02: Use temporary credentials (permission boundaries enforce this)
- SEC02-BP05: Audit and rotate credentials regularly
- SEC02-BP06: Employ user groups and attributes for fine-grained access
SEC03 - Permissions Management
- SEC03-BP01: Define access requirements (boundary defines maximum)
- SEC03-BP02: Grant least privilege access
- SEC03-BP06: Manage access based on lifecycle
- SEC03-BP07: Analyze public and cross-account access
CIS AWS Foundations Benchmark v3.0
- 1.4: Ensure no root account access key exists
- 1.15: Ensure IAM users receive permissions only through groups
- 1.16: Ensure IAM policies that allow full admin privileges are not attached
- 1.17: Ensure a support role has been created for incident management
- 1.22: Ensure IAM policies with admin access are reviewed regularly
NIST SP 800-53 Mapping
- AC-2: Account Management (boundary controls role creation)
- AC-3: Access Enforcement (intersection of policies)
- AC-5: Separation of Duties (boundary prevents security role access)
- AC-6: Least Privilege (boundary enforces maximum permissions)
- AC-6(1): Authorize Access to Security Functions
- AC-6(5): Privileged Accounts (boundary limits even admin roles)
workflows.md2.5 KB
AWS IAM Permission Boundaries - Workflows
Boundary Policy Creation Workflow
1. Security team identifies allowed services for developer workloads
│
2. Draft permission boundary policy (JSON)
│
3. Peer review by second security engineer
│
4. Test in sandbox account:
├── Create test role with boundary
├── Verify allowed actions succeed
├── Verify blocked actions are denied
└── Verify boundary cannot be self-modified
│
5. Commit policy to version control (IaC repository)
│
6. Deploy via CI/CD pipeline (Terraform/CloudFormation)
│
7. Attach boundary to all developer-created rolesDeveloper Role Creation Workflow (with Boundary)
Developer wants to create a new IAM role
│
├── Developer writes role policy (only app-* prefixed)
│
├── Developer creates role with --permissions-boundary flag
│ │
│ └── If boundary not attached → API returns AccessDenied
│
├── AWS IAM validates:
│ ├── Role name matches required prefix (app-*)
│ ├── Permission boundary ARN matches required boundary
│ └── Developer has iam:CreateRole with boundary condition
│
├── Role created successfully with boundary attached
│
└── Effective permissions = identity policy ∩ boundary policyPrivilege Escalation Prevention Workflow
Attacker attempts to escalate privileges:
Attempt 1: Create role without boundary
→ Denied by developer policy (condition requires boundary)
Attempt 2: Modify the boundary policy itself
→ Denied by boundary's own deny statements
Attempt 3: Remove boundary from existing role
→ Denied by boundary deny on DeleteRolePermissionsBoundary
Attempt 4: Create policy granting iam:* access
→ Policy can only grant actions within boundary intersection
Attempt 5: Assume a role without boundary
→ Developer can only create roles with boundary condition
All escalation paths blocked ✓Boundary Audit Workflow
Monthly audit:
│
├── List all IAM roles in account
│
├── Check each role for boundary attachment:
│ ├── Has boundary → Verify correct boundary ARN
│ └── No boundary → Flag for remediation
│
├── Review boundary policy changes (CloudTrail)
│
├── Check for new IAM actions added to AWS services
│ └── Update boundary if new actions should be restricted
│
└── Generate compliance reportScripts 2
agent.py5.2 KB
#!/usr/bin/env python3
"""AWS IAM permission boundary management agent using boto3."""
import argparse
import json
import logging
import os
import sys
from datetime import datetime
from typing import List
try:
import boto3
from botocore.exceptions import ClientError
except ImportError:
sys.exit("boto3 required: pip install boto3")
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def get_iam_client(profile: str = "", region: str = "us-east-1"):
"""Create IAM client with optional profile."""
session = boto3.Session(profile_name=profile) if profile else boto3.Session()
return session.client("iam", region_name=region)
def create_permission_boundary(client, policy_name: str, allowed_services: List[str],
allowed_regions: List[str] = None) -> dict:
"""Create a permission boundary policy restricting services and regions."""
statements = [{
"Sid": "AllowedServices",
"Effect": "Allow",
"Action": [f"{svc}:*" for svc in allowed_services],
"Resource": "*",
}]
if allowed_regions:
statements[0]["Condition"] = {
"StringEquals": {"aws:RequestedRegion": allowed_regions}
}
statements.append({
"Sid": "DenyBoundaryChanges",
"Effect": "Deny",
"Action": ["iam:DeleteRolePermissionsBoundary", "iam:PutRolePermissionsBoundary"],
"Resource": "*",
})
policy_doc = {"Version": "2012-10-17", "Statement": statements}
try:
resp = client.create_policy(
PolicyName=policy_name,
PolicyDocument=json.dumps(policy_doc),
Description=f"Permission boundary: {', '.join(allowed_services)}",
)
arn = resp["Policy"]["Arn"]
logger.info("Created boundary policy: %s", arn)
return {"policy_arn": arn, "policy_document": policy_doc}
except ClientError as exc:
return {"error": str(exc)}
def attach_boundary_to_role(client, role_name: str, boundary_arn: str) -> dict:
"""Attach permission boundary to an IAM role."""
try:
client.put_role_permissions_boundary(
RoleName=role_name, PermissionsBoundary=boundary_arn)
logger.info("Attached boundary %s to role %s", boundary_arn, role_name)
return {"role": role_name, "boundary_arn": boundary_arn, "attached": True}
except ClientError as exc:
return {"role": role_name, "error": str(exc)}
def audit_roles_without_boundary(client) -> List[dict]:
"""Find IAM roles that lack a permission boundary."""
paginator = client.get_paginator("list_roles")
unbounded = []
for page in paginator.paginate():
for role in page["Roles"]:
if "PermissionsBoundary" not in role:
unbounded.append({
"role_name": role["RoleName"],
"arn": role["Arn"],
"created": role["CreateDate"].isoformat(),
})
logger.info("Found %d roles without permission boundary", len(unbounded))
return unbounded
def audit_boundary_effectiveness(client, role_name: str) -> dict:
"""Audit effective permissions for a role with boundary."""
try:
role = client.get_role(RoleName=role_name)["Role"]
boundary = role.get("PermissionsBoundary", {})
policies_resp = client.list_attached_role_policies(RoleName=role_name)
inline_resp = client.list_role_policies(RoleName=role_name)
return {
"role": role_name,
"boundary_arn": boundary.get("PermissionsBoundaryArn", "NONE"),
"attached_policies": [p["PolicyName"] for p in policies_resp["AttachedPolicies"]],
"inline_policies": inline_resp["PolicyNames"],
}
except ClientError as exc:
return {"role": role_name, "error": str(exc)}
def generate_report(client) -> dict:
"""Generate permission boundary compliance report."""
unbounded = audit_roles_without_boundary(client)
report = {
"analysis_date": datetime.utcnow().isoformat(),
"roles_without_boundary": unbounded,
"roles_without_boundary_count": len(unbounded),
"recommendations": [],
}
if unbounded:
report["recommendations"].append(
f"Attach permission boundaries to {len(unbounded)} roles lacking boundaries")
return report
def main():
parser = argparse.ArgumentParser(description="AWS IAM Permission Boundary Agent")
parser.add_argument("--profile", default="", help="AWS CLI profile name")
parser.add_argument("--region", default="us-east-1")
parser.add_argument("--audit", action="store_true", help="Audit roles without boundaries")
parser.add_argument("--output-dir", default=".")
parser.add_argument("--output", default="iam_boundary_report.json")
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
client = get_iam_client(args.profile, args.region)
report = generate_report(client)
out_path = os.path.join(args.output_dir, args.output)
with open(out_path, "w") as f:
json.dump(report, f, indent=2, default=str)
logger.info("Report saved to %s", out_path)
print(json.dumps(report, indent=2, default=str))
if __name__ == "__main__":
main()
process.py8.9 KB
#!/usr/bin/env python3
"""
AWS IAM Permission Boundary Management Tool
Audits IAM roles for permission boundary compliance, identifies roles
without boundaries, and generates boundary policies based on actual
usage patterns from CloudTrail.
Requirements:
pip install boto3 pandas
"""
import json
import sys
from datetime import datetime, timezone
try:
import boto3
from botocore.exceptions import ClientError
except ImportError:
print("[ERROR] boto3 is required: pip install boto3")
sys.exit(1)
class PermissionBoundaryAuditor:
"""Audit IAM roles for permission boundary compliance."""
def __init__(self, profile_name=None, region="us-east-1"):
session = boto3.Session(profile_name=profile_name, region_name=region)
self.iam = session.client("iam")
self.account_id = session.client("sts").get_caller_identity()["Account"]
def list_roles_without_boundary(self):
"""Find all IAM roles that do not have a permission boundary attached."""
roles_without_boundary = []
paginator = self.iam.get_paginator("list_roles")
for page in paginator.paginate():
for role in page["Roles"]:
role_name = role["RoleName"]
boundary = role.get("PermissionsBoundary")
if boundary is None:
# Skip AWS service-linked roles
if role["Path"].startswith("/aws-service-role/"):
continue
roles_without_boundary.append({
"RoleName": role_name,
"Arn": role["Arn"],
"CreateDate": role["CreateDate"].isoformat(),
"Path": role["Path"],
"HasBoundary": False,
})
return roles_without_boundary
def list_roles_with_boundary(self):
"""List all roles that have a permission boundary and which boundary."""
roles_with_boundary = []
paginator = self.iam.get_paginator("list_roles")
for page in paginator.paginate():
for role in page["Roles"]:
boundary = role.get("PermissionsBoundary")
if boundary:
roles_with_boundary.append({
"RoleName": role["RoleName"],
"Arn": role["Arn"],
"BoundaryArn": boundary["PermissionsBoundaryArn"],
"BoundaryType": boundary["PermissionsBoundaryType"],
})
return roles_with_boundary
def verify_boundary_denies_escalation(self, boundary_policy_arn):
"""Check that a permission boundary includes anti-escalation deny statements."""
try:
policy = self.iam.get_policy(PolicyArn=boundary_policy_arn)
version_id = policy["Policy"]["DefaultVersionId"]
policy_version = self.iam.get_policy_version(
PolicyArn=boundary_policy_arn, VersionId=version_id
)
document = policy_version["PolicyVersion"]["Document"]
except ClientError as e:
return {"error": str(e)}
if isinstance(document, str):
document = json.loads(document)
escalation_actions = {
"iam:DeleteRolePermissionsBoundary",
"iam:DeleteUserPermissionsBoundary",
"iam:CreatePolicyVersion",
"iam:SetDefaultPolicyVersion",
}
denied_actions = set()
for statement in document.get("Statement", []):
if statement.get("Effect") == "Deny":
actions = statement.get("Action", [])
if isinstance(actions, str):
actions = [actions]
denied_actions.update(actions)
missing_denies = escalation_actions - denied_actions
return {
"boundary_arn": boundary_policy_arn,
"has_escalation_protection": len(missing_denies) == 0,
"denied_actions": list(denied_actions),
"missing_deny_actions": list(missing_denies),
}
def attach_boundary_to_role(self, role_name, boundary_policy_arn):
"""Attach a permission boundary to an existing IAM role."""
try:
self.iam.put_role_permissions_boundary(
RoleName=role_name,
PermissionsBoundary=boundary_policy_arn
)
return {"success": True, "role": role_name, "boundary": boundary_policy_arn}
except ClientError as e:
return {"success": False, "role": role_name, "error": str(e)}
def generate_audit_report(self):
"""Generate a full compliance report for permission boundaries."""
roles_without = self.list_roles_without_boundary()
roles_with = self.list_roles_with_boundary()
# Check escalation protection for each unique boundary
boundary_arns = set(r["BoundaryArn"] for r in roles_with)
boundary_checks = {}
for arn in boundary_arns:
boundary_checks[arn] = self.verify_boundary_denies_escalation(arn)
report = {
"report_title": "IAM Permission Boundary Compliance Audit",
"account_id": self.account_id,
"generated_at": datetime.now(timezone.utc).isoformat(),
"summary": {
"total_roles_with_boundary": len(roles_with),
"total_roles_without_boundary": len(roles_without),
"unique_boundaries": len(boundary_arns),
"boundaries_with_escalation_protection": sum(
1 for v in boundary_checks.values()
if v.get("has_escalation_protection")
),
},
"roles_without_boundary": roles_without,
"boundary_escalation_analysis": boundary_checks,
}
return report
def generate_boundary_policy(allowed_services, role_prefix="app-",
boundary_name="DeveloperBoundary"):
"""Generate a permission boundary policy JSON for given allowed services."""
service_action_map = {
"s3": "s3:*",
"dynamodb": "dynamodb:*",
"lambda": "lambda:*",
"sqs": "sqs:*",
"sns": "sns:*",
"logs": "logs:*",
"cloudwatch": "cloudwatch:*",
"events": "events:*",
"states": "states:*",
"xray": "xray:*",
"ec2": ["ec2:Describe*", "ec2:CreateTags"],
"ecs": ["ecs:*", "ecr:*"],
"rds": "rds:*",
"secretsmanager": "secretsmanager:GetSecretValue",
"kms": ["kms:Decrypt", "kms:GenerateDataKey", "kms:DescribeKey"],
"ssm": ["ssm:GetParameter", "ssm:GetParameters", "ssm:GetParametersByPath"],
}
actions = []
for service in allowed_services:
service_lower = service.lower()
if service_lower in service_action_map:
action = service_action_map[service_lower]
if isinstance(action, list):
actions.extend(action)
else:
actions.append(action)
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowedServices",
"Effect": "Allow",
"Action": actions,
"Resource": "*"
},
{
"Sid": "AllowPassRole",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": f"arn:aws:iam::*:role/{role_prefix}*",
"Condition": {
"StringEquals": {
"iam:PassedToService": [
"lambda.amazonaws.com",
"ecs-tasks.amazonaws.com",
"states.amazonaws.com"
]
}
}
},
{
"Sid": "DenyBoundaryModification",
"Effect": "Deny",
"Action": [
"iam:DeletePolicy",
"iam:DeletePolicyVersion",
"iam:CreatePolicyVersion",
"iam:SetDefaultPolicyVersion"
],
"Resource": f"arn:aws:iam::*:policy/{boundary_name}"
},
{
"Sid": "DenyBoundaryRemoval",
"Effect": "Deny",
"Action": [
"iam:DeleteUserPermissionsBoundary",
"iam:DeleteRolePermissionsBoundary"
],
"Resource": "*"
}
]
}
return json.dumps(policy, indent=2)
if __name__ == "__main__":
print("=" * 60)
print("AWS IAM Permission Boundary Management Tool")
print("=" * 60)
print()
print("Usage:")
print(" auditor = PermissionBoundaryAuditor(profile='prod')")
print(" report = auditor.generate_audit_report()")
print()
print("Generate a boundary policy:")
services = ["s3", "dynamodb", "lambda", "sqs", "logs", "cloudwatch"]
policy = generate_boundary_policy(services)
print(policy)