Skip to content

IdentityService 06 of 139 controls

AWS IAM security hardening

Reach least privilege in AWS IAM: Access Analyzer, policy validation in CI, permissions boundaries, conditions, and a plan to remove old access keys.

Published on Updated on 11 min readTags:#identity#least-privilege#access-management
On this page

AWS Identity and Access Management (IAM) decides who can do what in every AWS account: users, roles, the policies attached to them, and the resource policies that let other principals in. It fails in two predictable ways. First, permissions only grow: teams start with AdministratorAccess or a broad managed policy to unblock delivery, and nobody shrinks it, so one compromised role or SSRF-reachable instance profile becomes an account takeover. Second, long-lived IAM user access keys leak, through public repositories, CI variables, container images and laptops, and automated scanners use them within minutes for cryptomining or data theft. Neither problem is solved by a policy you write once. This page covers the tooling that closes the gap in a repeatable way: IAM Access Analyzer to find external sharing and unused access, policy generation from CloudTrail, validation and custom policy checks in CI, permissions boundaries and conditions, then the inventory, rotation and removal of the access keys and secrets you already have. Human sign-in belongs in IAM Identity Center; this page assumes that is in place or in progress.

Baseline controls

9 controlsCIS numbers refer to the CIS AWS Foundations Benchmark v7.1.0 unless another CIS benchmark is named; Security Hub CSPM IDs are listed where a control exists.
  1. 01External access analyzer in every Region you use

    Shows which resources are reachable from outside your organization.

    How to check: aws accessanalyzer list-analyzers --type ORGANIZATION --region eu-west-1
    Mapping: IAM.28, CIS 2.18
  2. 02Unused roles, keys and permissions reviewed monthly

    Permissions nobody uses are pure attack surface for whoever steals the role.

    How to check: aws accessanalyzer list-analyzers --type ORGANIZATION_UNUSED_ACCESS
  3. 03No full admin or service wildcard customer policies

    Action "*" policies turn any compromised principal into an administrator.

    How to check: aws accessanalyzer validate-policy --policy-type IDENTITY_POLICY --policy-document file://p.json
    Mapping: IAM.1, IAM.21, CIS 2.14
  4. 04Permission increases blocked in CI until reviewed

    Catches new privileges in pull requests instead of in production.

    How to check: aws accessanalyzer check-no-new-access --policy-type IDENTITY_POLICY ...
  5. 05Permissions boundary required for delegated role creation

    Stops developers from creating a role more powerful than themselves.

    How to check: aws iam get-role --role-name <role> --query Role.PermissionsBoundary
  6. 06Credentials unused for 45 days removed

    Forgotten keys and passwords are the easiest credentials to steal unnoticed.

    How to check: aws iam generate-credential-report
    Mapping: IAM.22, CIS 2.11
  7. 07Remaining access keys rotated every 90 days

    Limits how long a leaked key stays valid.

    How to check: aws iam list-access-keys --user-name <user>
    Mapping: IAM.3, CIS 2.12
  8. 08Permissions through groups or roles, not users

    User-attached policies are invisible in group reviews and outlive role changes.

    How to check: aws iam list-attached-user-policies --user-name <user>
    Mapping: IAM.2, CIS 2.13
  9. 09Application secrets in Secrets Manager with rotation

    Moves passwords and tokens out of environment variables and config files.

    How to check: aws secretsmanager list-secrets --query 'SecretList[?!RotationEnabled].Name'
    Mapping: SecretsManager.1, SecretsManager.4

Enable the analyzers at organization level

IAM Access Analyzer has four capabilities, and you want all of them:

CapabilityQuestion it answersWhere it runs
External access analyzerWhich of my resources can be reached from outside my zone of trust?Continuous, per Region
Unused access analyzerWhich roles, users, keys and permissions are not being used?Continuous, organization or account
Policy generationWhat does this role actually need, based on CloudTrail?On demand
Policy validation and custom checksIs this policy valid, and does it grant something it should not?On demand, in CI

Generation and validation shape new policies; the analyzers catch drift after deployment.

Create analyzers from a delegated administrator such as your security tooling account rather than the management account:

aws organizations register-delegated-administrator \
  --service-principal access-analyzer.amazonaws.com \
  --account-id 222233334444

Then, from the delegated administrator, create an external access analyzer in every Region you use. External access findings are Regional because the resources are Regional. This is CIS AWS Foundations Benchmark v7.1.0 recommendation 2.18 and Security Hub CSPM control IAM.28:

for r in eu-west-1 eu-central-1 us-east-1; do
  aws accessanalyzer create-analyzer \
    --region "$r" \
    --analyzer-name org-external-access \
    --type ORGANIZATION
done

With --type ORGANIZATION, the zone of trust is your whole organization. A bucket shared with another account in the same organization is not a finding; a bucket shared with an account outside it, or with "Principal": "*", is.

Add one unused access analyzer. It is billed per IAM role and user analyzed per month, so check pricing before enabling it on very large organizations:

aws accessanalyzer create-analyzer \
  --region eu-west-1 \
  --analyzer-name org-unused-access \
  --type ORGANIZATION_UNUSED_ACCESS \
  --configuration '{"unusedAccess":{"unusedAccessAge":90}}'

The unusedAccessAge value sets how many days without activity count as unused. Ninety days is a reasonable start; IAM user credentials have their own, stricter 45-day rule handled through the credential report.

Triage external access findings

List active findings and look at the principal and condition that make each resource reachable:

aws accessanalyzer list-findings-v2 \
  --analyzer-arn arn:aws:access-analyzer:eu-west-1:222233334444:analyzer/org-external-access \
  --filter '{"status":{"eq":["ACTIVE"]}}' \
  --query 'findings[].{Resource:resource,Type:resourceType,Owner:resourceOwnerAccount}'

For each finding, decide one of three things:

  1. Intended: a partner account that must read a bucket. Create an archive rule scoped to that account ID so the finding stays closed, and document the reason.
  2. Unintended but harmless: an old cross-account trust to a decommissioned account. Remove the statement.
  3. Unintended and exposed: a public bucket policy or a role that any AWS account can assume. Fix it now, then check CloudTrail for access from unknown principals.

Archive rules keep the queue clean:

aws accessanalyzer create-archive-rule \
  --analyzer-name org-external-access \
  --rule-name partner-reporting-bucket \
  --filter '{"principal.AWS":{"eq":["333344445555"]},"resourceType":{"eq":["AWS::S3::Bucket"]}}'

Access Analyzer tells you what is exposed; it does not prevent it. Block public S3 access at the source with S3 Block Public Access, and keep resources inside your organization with the RCPs described on the Organizations page.

Remove unused access

The unused access analyzer reports four finding types: unused roles, unused IAM user passwords, unused IAM user access keys, and unused permissions on roles and users that are still active. The last one is where least privilege is won, because it names services and actions the principal has permission for but has not called.

aws accessanalyzer list-findings-v2 \
  --analyzer-arn arn:aws:access-analyzer:eu-west-1:222233334444:analyzer/org-unused-access \
  --filter '{"findingType":{"eq":["UnusedPermission"]},"status":{"eq":["ACTIVE"]}}'

aws accessanalyzer get-finding-v2 \
  --analyzer-arn arn:aws:access-analyzer:eu-west-1:222233334444:analyzer/org-unused-access \
  --id <finding-id>

For unused permission findings, Access Analyzer can produce a recommended remediation: a proposed replacement policy with the unused actions removed.

aws accessanalyzer generate-finding-recommendation \
  --analyzer-arn arn:aws:access-analyzer:eu-west-1:222233334444:analyzer/org-unused-access \
  --id <finding-id>

aws accessanalyzer get-finding-recommendation \
  --analyzer-arn arn:aws:access-analyzer:eu-west-1:222233334444:analyzer/org-unused-access \
  --id <finding-id>

Treat the recommendation as a draft. Quarterly jobs, disaster recovery runbooks and incident response roles legitimately go months without using some permissions. Tag those principals and exclude them from the analyzer configuration rather than stripping permissions they will need on a bad day.

The underlying data is the same as IAM last accessed information, which you can also query per principal with aws iam generate-service-last-accessed-details.

Generate a policy from CloudTrail activity

For a new or over-privileged role, let Access Analyzer write the first version of the policy from what the role did. It reads up to 90 days of CloudTrail management events through a service role you provide:

aws accessanalyzer start-policy-generation \
  --policy-generation-details '{"principalArn":"arn:aws:iam::111122223333:role/orders-api"}' \
  --cloud-trail-details '{
    "trails": [{
      "cloudTrailArn": "arn:aws:cloudtrail:eu-west-1:999988887777:trail/org-trail",
      "allRegions": true
    }],
    "accessRole": "arn:aws:iam::111122223333:role/service-role/AccessAnalyzerMonitorServiceRole",
    "startTime": "2026-08-01T00:00:00Z",
    "endTime": "2026-10-30T00:00:00Z"
  }'

aws accessanalyzer get-generated-policy --job-id <job-id>

Know the limits before you trust the output:

  • Data events such as s3:GetObject are not used for action-level detail, so add data actions by hand.
  • iam:PassRole is not tracked and never appears in generated policies.
  • Resource ARNs come back as placeholders for many actions. Replace them with real ARNs; a generated policy with "Resource": "*" everywhere is not least privilege.
  • Trails created by AWS Control Tower are not supported for policy generation because the log bucket is locked by Control Tower guardrails.

If your logs live in a central log archive account, as described on the CloudTrail page, the bucket policy and KMS key policy there must let the AccessAnalyzerMonitorServiceRole* roles read objects. AWS documents the exact statements in the policy generation guide listed in the references.

Validate every policy before it ships

validate-policy runs more than 100 checks covering JSON errors, security warnings and suggestions. It is free and fast, so run it on every policy in CI:

aws accessanalyzer validate-policy \
  --policy-type IDENTITY_POLICY \
  --policy-document file://orders-api.json \
  --query 'findings[?findingType==`SECURITY_WARNING` || findingType==`ERROR`]'

Use --policy-type RESOURCE_POLICY with --validate-policy-resource-type AWS::S3::Bucket (or another supported type) for resource policies, and SERVICE_CONTROL_POLICY for SCPs. Typical security warnings include iam:PassRole with a wildcard resource and NotAction combined with Allow.

Security Hub CSPM checks the result in deployed accounts: IAM.1 fails customer managed policies that allow "Action": "*" on "Resource": "*", and IAM.21 fails customer managed policies with service-wide wildcards such as "s3:*". Neither control looks at inline or AWS managed policies, so AdministratorAccess attachments need their own review.

Custom policy checks in CI

Custom policy checks use automated reasoning to prove properties of a policy. Three are useful in a pull request pipeline:

# Does the new version grant anything the old one did not?
aws accessanalyzer check-no-new-access \
  --policy-type IDENTITY_POLICY \
  --existing-policy-document file://main/orders-api.json \
  --new-policy-document file://pr/orders-api.json

# Does this policy grant any of these sensitive actions?
aws accessanalyzer check-access-not-granted \
  --policy-type IDENTITY_POLICY \
  --policy-document file://pr/orders-api.json \
  --access '[{"actions":["iam:PassRole","iam:CreateAccessKey","kms:Decrypt"]}]'

# Does this bucket policy allow public access?
aws accessanalyzer check-no-public-access \
  --resource-type AWS::S3::Bucket \
  --policy-document file://pr/bucket-policy.json

Each returns PASS or FAIL with reasons. A practical pattern: run check-no-new-access on every change, and require a security reviewer only when it fails. That keeps reviews focused on permission increases instead of every whitespace edit. AWS publishes a GitHub Action and a CloudFormation hook for these checks, and open source tools such as Parliament and Cloudsplaining add extra linting and risk reports on existing account authorization data.

Tighten what remains with conditions

Generated policies give you the right actions. Conditions narrow them further:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadOrdersTable",
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:Query"],
      "Resource": "arn:aws:dynamodb:eu-west-1:111122223333:table/orders",
      "Condition": {
        "StringEquals": { "aws:ResourceAccount": "111122223333" }
      }
    },
    {
      "Sid": "PassOnlyTheWorkerRole",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::111122223333:role/orders-worker",
      "Condition": {
        "StringEquals": { "iam:PassedToService": "ecs-tasks.amazonaws.com" }
      }
    }
  ]
}

iam:PassRole deserves special care: most published AWS privilege escalation paths combine it with a compute service (ec2:RunInstances, lambda:CreateFunction, glue:CreateDevEndpoint) to run code as a more privileged role. Always scope it to specific role ARNs and to the service that needs it.

Other keys worth knowing: aws:RequestedRegion to pin a workload to its Regions, aws:PrincipalTag and aws:ResourceTag for attribute based access control, aws:SourceVpce to require a VPC endpoint (see the VPC page), and aws:ViaAWSService for KMS calls made by services on your behalf (see the KMS page).

Permissions boundaries for delegated role creation

Developers often need to create roles for their own Lambda functions. Without a guardrail, that is a path to privilege escalation: create a role with AdministratorAccess, pass it to a function, and run code as admin. A permissions boundary caps what any role they create can do:

{
  "Effect": "Allow",
  "Action": ["iam:CreateRole", "iam:AttachRolePolicy", "iam:PutRolePolicy"],
  "Resource": "arn:aws:iam::111122223333:role/app/*",
  "Condition": {
    "StringEquals": {
      "iam:PermissionsBoundary": "arn:aws:iam::111122223333:policy/AppWorkloadBoundary"
    }
  }
}

Pair it with a deny on iam:DeleteRolePermissionsBoundary, iam:PutRolePermissionsBoundary to another policy, and on iam:CreatePolicyVersion or iam:DeletePolicy for the boundary policy itself, otherwise the developer can simply remove or rewrite it. Effective permissions are the intersection of the identity policy and the boundary, and then of any SCPs and RCPs above them. Identity Center can attach the same boundary to a developer permission set, as shown on the Identity Center page.

Verify

aws iam list-roles --path-prefix /app/ \
  --query 'Roles[?PermissionsBoundary==null].RoleName'

Any role returned was created outside the guardrail.

Phase out IAM users and access keys

Humans should sign in through Identity Center and workloads should use roles or OIDC federation. Long-lived IAM user keys become rare exceptions with an owner and a rotation date.

Inventory access keys with the credential report

The credential report lists every IAM user in the account with password and key status, last use and rotation dates:

aws iam generate-credential-report
aws iam get-credential-report --query Content --output text \
  | base64 --decode > credential-report.csv

Useful columns: password_enabled, mfa_active, access_key_1_active, access_key_1_last_rotated, access_key_1_last_used_date, and the same for key 2. A quick filter for active keys older than 90 days:

python3 - <<'EOF'
import csv, datetime
now = datetime.datetime.now(datetime.timezone.utc)
for row in csv.DictReader(open("credential-report.csv")):
    for k in ("1", "2"):
        if row[f"access_key_{k}_active"] == "true":
            rotated = datetime.datetime.fromisoformat(row[f"access_key_{k}_last_rotated"])
            age = (now - rotated).days
            if age > 90:
                print(row["user"], f"key{k}", age, "days, last used", row[f"access_key_{k}_last_used_date"])
EOF

Across an organization, Security Hub CSPM gives the same view without scripts: IAM.3 for keys older than 90 days, IAM.22 for credentials unused for 45 days (CIS 2.11), and IAM.5 for console users without MFA. The unused access analyzer reports unused keys too.

Rotate or remove each key

For each key, the right answer is usually removal, not rotation. Ask who owns it and whether the workload can move to a role or OIDC federation. If it can, migrate and delete the user.

When a key must stay (a third-party SaaS that only accepts keys, for example), rotate without downtime using the two-key slot:

USER=legacy-reporting

# 1. Create the second key
aws iam create-access-key --user-name "$USER"

# 2. Deploy the new key to the consumer, confirm it works,
#    then check the old key is no longer used
aws iam get-access-key-last-used --access-key-id AKIAOLDKEYEXAMPLE

# 3. Deactivate, wait, then delete the old key
aws iam update-access-key --user-name "$USER" \
  --access-key-id AKIAOLDKEYEXAMPLE --status Inactive
aws iam delete-access-key --user-name "$USER" \
  --access-key-id AKIAOLDKEYEXAMPLE

Deactivating first gives you a rollback: if something breaks, reactivate the old key while you find the consumer you missed.

Keep one active key and no user policies

Keep only one active key per user outside the rotation window. Attach permissions to groups or roles rather than directly to the user (CIS 2.13, IAM.2), and give every remaining user a tag with an owner and a review date.

Enforce across the organization

Creating additional access keys for an existing user is a known persistence technique, tracked as MITRE ATT&CK T1098.001 Additional Cloud Credentials. An SCP can stop new IAM users and keys outside an approved automation role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyIamUsersAndKeys",
      "Effect": "Deny",
      "Action": ["iam:CreateUser", "iam:CreateAccessKey", "iam:CreateLoginProfile"],
      "Resource": "*",
      "Condition": {
        "ArnNotLike": {
          "aws:PrincipalArn": "arn:aws:iam::*:role/platform/iam-automation"
        }
      }
    }
  ]
}

The Organizations page shows how to roll SCPs out by OU without locking yourself out.

Move application secrets to Secrets Manager

Access keys are not the only long-lived secrets. Database passwords, API tokens and third-party keys often sit in environment variables or configuration files. Store them in AWS Secrets Manager, grant read access to the workload role only, and turn on rotation:

aws secretsmanager create-secret \
  --name prod/orders/db \
  --kms-key-id alias/secrets-prod \
  --secret-string file://db-credentials.json

aws secretsmanager rotate-secret \
  --secret-id prod/orders/db \
  --rotation-lambda-arn arn:aws:lambda:eu-west-1:111122223333:function:rds-rotation \
  --rotation-rules '{"ScheduleExpression":"rate(30 days)"}'

For Amazon RDS and Aurora, prefer the managed master user password (--manage-master-user-password), which Secrets Manager rotates for you; see the RDS page. Encrypt secrets with a customer managed KMS key whose key policy is scoped as described on the KMS page. Security Hub CSPM tracks this with SecretsManager.1 (automatic rotation enabled), SecretsManager.2 (rotation succeeds), SecretsManager.3 (unused secrets removed) and SecretsManager.4 (rotated within 90 days by default).

Logging and detection

Your CloudTrail organization trail records every IAM API call as a management event. Alert on:

  • Credential creation: CreateAccessKey, CreateLoginProfile and UpdateLoginProfile, especially when the caller differs from the target user.
  • Privilege changes: AttachUserPolicy, AttachRolePolicy, PutRolePolicy, CreatePolicyVersion with a new default version, UpdateAssumeRolePolicy, and DeleteRolePermissionsBoundary.
  • Trust expansion: CreateOpenIDConnectProvider, CreateSAMLProvider and role trust policies that add an external account.

An EventBridge rule for the most sensitive calls:

{
  "source": ["aws.iam"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": ["iam.amazonaws.com"],
    "eventName": [
      "CreateAccessKey",
      "CreateLoginProfile",
      "UpdateAssumeRolePolicy",
      "DeleteRolePermissionsBoundary",
      "CreatePolicyVersion"
    ]
  }
}

IAM is a global service and its events are delivered in us-east-1, so create the rule there.

Amazon GuardDuty covers the behavioral side: UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS for instance credentials used elsewhere, and CredentialAccess:IAMUser/AnomalousBehavior, Persistence:IAMUser/AnomalousBehavior and PrivilegeEscalation:IAMUser/AnomalousBehavior for unusual API sequences. Send Access Analyzer findings to Security Hub CSPM so they sit next to IAM.1, IAM.2, IAM.3, IAM.21, IAM.22 and IAM.28, and run a weekly triage of external access findings and a monthly review of unused access.

Common mistakes

  • Treating generated policies as final. They miss data actions and iam:PassRole, and use placeholder resources. Review and complete them.
  • Rotating keys that should be deleted. Rotation keeps a long-lived secret alive. Migrate to roles or OIDC first and rotate only what truly cannot move.
  • Wildcard iam:PassRole. Combined with any compute service it is a path to admin. Scope it to role ARNs and iam:PassedToService.
  • Boundaries the developer can remove. A permissions boundary without a deny on deleting or editing it is a suggestion.
  • An external access analyzer in one Region only. Findings are Regional; resources in other Regions stay invisible.
  • Stripping break-glass and DR roles because they look unused. Exclude them from unused access recommendations by tag.
  • Relying on IAM.1 alone. It ignores AWS managed and inline policies, so AdministratorAccess attachments pass.

References

Written by

Florian Amette

Security engineer writing practical, benchmark-aligned hardening baselines for AWS services, from the organization and identities to data, networks and workloads.

Related services

All services