Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 70 ยท Identity and access management

IAM Best Practices and Least Privilege

Apply least privilege on AWS: tighten policies with Access Analyzer, read credential reports, rotate keys, use IAM Identity Center and enforce MFA, with runnable linters.

IAM is the part of AWS where small mistakes become big incidents. A forgotten access key, a policy with "Action": "*" or a user without MFA is how most real-world cloud breaches begin. The good news is that the habits that prevent these problems are few, and you can check most of them automatically.

This lesson collects those habits. They build on IAM Users, Groups and Roles, Writing IAM Policies and How Policy Evaluation Works. The central idea is least privilege: give every person and workload exactly the permissions it needs, for exactly as long as it needs them, and no more.

AWS itself cannot run on this site, so the console steps and CLI commands below are read-only. The runnable examples are Python stand-ins: a small policy linter and a credential-report checker. They show the same checks AWS tools perform, but on sample data you can edit.

The short list of habits

These are the habits that matter most. Most of them are one-time setup.

  1. Lock down the root user. Enable MFA, delete any root access keys, and use root only for the few tasks that require it (closing the account, changing the support plan, and similar). See Creating and Securing an Account.
  2. Give people individual identities, not shared logins. Use IAM Identity Center (below) instead of creating an IAM user per person.
  3. Prefer roles and temporary credentials. EC2 instances, Lambda functions and containers get roles, not access keys.
  4. Require MFA for humans, and for sensitive actions through a policy condition.
  5. Start narrow and widen with evidence. Do not begin with AdministratorAccess and plan to tighten later. Later rarely comes.
  6. Review regularly. Remove unused users, roles, keys and permissions.
  7. Use conditions and guardrails. Restrict by region, source IP, MFA or tag where it makes sense, and use SCPs at the organization level.

Least privilege as a workflow

Nobody knows the exact permissions a new application needs on day one, so least privilege is a process, not a single policy.

flowchart LR
    A["Start with a narrow<br/>policy for known actions"] --> B["Run the workload<br/>in a test account"]
    B --> C["Read the denied calls<br/>from errors or CloudTrail"]
    C --> D["Add only the missing<br/>actions and resources"]
    D --> E["Review with Access Analyzer<br/>before production"]
    E --> F["Revisit every few months<br/>and remove unused access"]
    F --> B

Least privilege is a loop: tighten, test, observe, adjust, review.

AWS gives you tools for this loop:

  • IAM Access Analyzer has several features. External access findings tell you which resources (buckets, roles, KMS keys, queues) are shared with someone outside your account or organization. Unused access findings list roles, users and permissions that have not been used. Policy generation builds a policy from the actions a role actually performed according to CloudTrail. Policy validation checks a policy for syntax problems and suggests improvements.
  • "Last accessed" information in the IAM console shows when a service or action was last used by a principal. A permission that has been unused for months is a candidate for removal.
  • Policy simulator (aws iam simulate-principal-policy) tests whether a principal would be allowed an action, without making the call.

Generated policies are a starting point, not the final answer: review them, replace broad resources with specific ARNs and add conditions.

A typical read-only validation command looks like this:

Terminal
aws accessanalyzer validate-policy \
  --policy-type IDENTITY_POLICY \
  --policy-document file://policy.json

Smell test: wildcards

The easiest warning sign is a wildcard. Compare these two statements for a function that reads one folder of one bucket:

JSON
{ "Effect": "Allow", "Action": "s3:*", "Resource": "*" }
JSON
{
  "Effect": "Allow",
  "Action": ["s3:GetObject"],
  "Resource": "arn:aws:s3:::invoices-prod/exports/*"
}

The first can delete every bucket in the account. The second can read exports in one place. Both "work", and only the second is safe.

Some wildcards are fine, for example "Action": "s3:Get*" on a specific bucket, or "Resource": "*" for actions that do not support resource-level permissions (many Describe* and List* calls). The point is to make each wildcard a decision.

The next stand-in is a tiny policy linter. It scans policy statements for typical smells: full admin, service-wide wildcards, NotAction with Allow, unconstrained iam:PassRole, and public principals. Real tools (Access Analyzer's validation, open-source linters) check hundreds of rules. The idea is the same.

Python A policy linter for wildcards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The tight-reader policy comes out clean. The others each trigger at least one finding. Try adding a Condition to the sloppy-app statement and see which warnings disappear. Notice that a clean lint result does not prove a policy is safe, because it only finds patterns. It is a safety net, not a proof.

Humans: Identity Center, not IAM users

Creating one IAM user per employee with a password and long-term access keys does not scale and is hard to secure. AWS recommends IAM Identity Center (the successor of AWS SSO) for people:

  • You connect your company directory (or use Identity Center's own user store).
  • You define permission sets (for example ReadOnly, Developer, BillingAdmin) and assign them to users or groups for specific accounts.
  • People sign in to a portal, get temporary credentials for the account and role they choose, and those credentials expire after a short time.
  • Joiners and leavers are handled in one place. When someone leaves the company, access ends everywhere.

On the command line the flow is short (read-only here):

Terminal
aws configure sso          # one-time: the start URL and region of your portal
aws sso login --profile dev
aws s3 ls --profile dev    # uses temporary credentials from the portal

You will see more of this setup in Console, CLI and SDKs and Multi-Account Strategy and Control Tower.

MFA

Multi-factor authentication means a stolen password alone is not enough. Enable it for the root user and for every human. Prefer phishing-resistant methods (passkeys and FIDO2 security keys) over one-time codes where you can. You can also require MFA for risky actions with a policy condition:

JSON
{
  "Effect": "Deny",
  "Action": ["ec2:TerminateInstances", "iam:*"],
  "Resource": "*",
  "Condition": { "BoolIfExists": { "aws:MultiFactorAuthPresent": "false" } }
}

Because this is an explicit deny, it wins over any allow (as you saw in policy evaluation). The BoolIfExists form also blocks requests where the key is missing, for example calls made with long-term access keys.

Access keys: rotate, restrict, or remove

Long-term access keys (an AKIA... ID and a secret) are the riskiest credential type, because they do not expire and they leak: committed to Git, pasted into chat, left in a container image. Rules of thumb:

  • Do not create them if a role works. Workloads inside AWS use instance profiles, task roles and Lambda execution roles. External systems such as CI can often use OIDC federation to assume a role.
  • If a key is unavoidable, give it a narrow policy, rotate it at least every 90 days, and keep at most two keys per user so rotation is possible without downtime.
  • Rotation means: create a second key, switch the application to it, check that the old key shows no recent use, deactivate it, and delete it later.
  • Turn on secret scanning in your source host so leaked keys are noticed early.

The credential report is a CSV that IAM generates for the whole account, with one row per user: password status, last console sign-in, MFA, and the age and last use of each key. It is the quickest audit tool you have:

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

This stand-in reads a small report (with a fixed "today" so the output is always the same) and flags the common problems.

Python Auditing a credential report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You should see alice, ci-deploy and the root row come out clean, bob with three findings (no MFA, a stale console password and an old key) and carol with two (no MFA and a console password that was never used). Notice what is not automatic: ci-deploy is clean here only because its key is new. It still has a long-term key that a role could replace.

Other good habits

  • Use groups and roles for permissions, not per-user policies, so that access follows job function.
  • Prefer customer-managed policies over copying inline policies around, so changes happen in one place.
  • Use permission boundaries to let teams create their own roles safely: they can create roles, but only up to the boundary.
  • Tag principals and resources and write policies using tags (attribute-based access control), so access scales without writing a new policy per project.
  • Turn on CloudTrail in all regions and keep the logs in a protected bucket; see CloudTrail, Config and X-Ray.
  • Separate accounts for production and development. An account is the strongest boundary AWS offers.

Setting up MFA step by step

Enabling a virtual MFA device takes a couple of minutes:

  1. Sign in, open your name in the top bar and choose Security credentials. (For the root user, sign in as root first. For an IAM user, an administrator can also assign a device from the user's page.)
  2. Choose Assign MFA device, give the device a name, and select the type: an authenticator app (virtual MFA), a passkey or security key (FIDO2), or a hardware TOTP token.
  3. For an authenticator app, scan the QR code with the app. If you cannot scan it, choose to show the secret key and type it into the app by hand. Treat that secret like a password.
  4. Type two consecutive one-time codes from the app. The second code proves that the device keeps correct time.
  5. Choose Add MFA. From the next sign-in, AWS asks for the code after the password. A user can register several devices (up to eight), which is how you keep a backup.

The same steps by CLI, read-only:

Terminal
aws iam create-virtual-mfa-device --virtual-mfa-device-name alice \
  --outfile alice-qr.png --bootstrap-method QRCodePNG
aws iam enable-mfa-device --user-name alice \
  --serial-number arn:aws:iam::123456789012:mfa/alice \
  --authentication-code1 123456 --authentication-code2 654321

An authenticator app does not talk to AWS. Both sides compute the same TOTP (time-based one-time password, RFC 6238) from a shared secret and the current 30-second time step, which is why two consecutive codes prove the setup works. The stand-in below implements the algorithm and checks it against a published test vector from the RFC (the secret 12345678901234567890 at Unix time 59 gives the 6-digit code 287082).

Python How an authenticator app makes its codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does least privilege mean?

    Least privilege means narrow, task-specific permissions that you review and adjust. It is a continuous process, not a one-time policy.
  2. 2. Which is the best way to give an EC2 instance access to an S3 bucket?

    A role through an instance profile provides temporary credentials that rotate automatically, with no secret to store or leak.
  3. 3. What is the IAM credential report useful for?

    The credential report is an account-wide CSV about the state of credentials. Policy generation is a separate Access Analyzer feature.
  4. 4. Why does AWS recommend IAM Identity Center for employees instead of one IAM user each?

    People get temporary credentials from a portal and access is managed in one place. IAM users can have MFA and cost nothing, but they scale poorly and often have long-term keys.
  5. 5. A policy statement allows Action "" on Resource "". What is the best description?

    Both wildcards together grant every action on every resource, which is what the AdministratorAccess managed policy contains.

Summary

  • Least privilege is a loop: start narrow, test, read the denied calls, add what is missing, review and remove unused access.
  • Use Access Analyzer (external and unused access, policy generation and validation), last-accessed data and the policy simulator.
  • Treat wildcards as decisions. Lint policies for admin access, service-wide wildcards, NotAction, open iam:PassRole and public principals.
  • Use IAM Identity Center for people and roles for workloads. Avoid long-term access keys, and rotate and restrict the ones you must keep.
  • Enable MFA for the root user and humans, and use deny-with-condition statements to require it for sensitive actions.
  • Audit regularly with the credential report.

Next: EC2 Instances