A client asks you to let their contractor update the company website. The site
is a folder of files in an S3 bucket behind CloudFront. The quick way is to
make the contractor an IAM user and attach AdministratorAccess.
That works, however it does not follow the principal of least privilege
access.
This is the second of three posts on AWS Identity and Access Management (IAM) series that I'm writing while studying for the AWS Solutions Architect Associate exam. The first post locked down the root user. This one covers the four building blocks you use to give everyone else access:
- Users: who someone is.
- Groups: a way to manage many users the same way.
- Policies: what they're allowed to do.
- Access keys: how a program signs in as a user.
Putting them together is how we give the contractor exactly what they need to update the website and meet the expectations of the client's request.
Users
An IAM user is an identity in a single AWS account, with long-term credentials. It can have two kinds of credentials:
- A password, to sign in to the console.
- Up to two access keys, to call AWS from the CLI, an SDK or a script.
A new user has no permissions at all. Remember the rule from the first post: everything is denied by default, and only an explicitly attached policy grants access. A user with no policies can sign in however they will see an empty console full of "access denied" messages.
You should use one identity per person, never shared identities. If three
people share a
deploy user, CloudTrail can't tell you which of them deleted the
bucket, and you can't remove one person without changing the password for
everyone.
Groups
A group is a collection of users. Attach a policy to the group, and every user in it gets those permissions. When someone joins the team you add them to the group; when they leave you remove them. You never have to work out which of twelve policies a departing user had.
Groups have a few limits that show up on the exam:
- Groups contain users only. A group can't contain another group.
- A group isn't a principal. You can't sign in as a group, and you can't name a group in a resource policy, such as an S3 bucket policy.
Policies
A policy is a JSON document that lists what's allowed or denied. Here's one that lets its holder read objects from a single bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadSiteFiles",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-site-bucket/*"
}
]
}
| Element | What it means |
|---|---|
Version |
The policy language version. Always 2012-10-17; it isn't a
date you change.
|
Statement |
A list of rules. A policy can have many. |
Sid |
An optional label so you can tell statements apart. |
Effect |
Allow or Deny. |
Action |
The API calls, written as service:Operation. Wildcards
work: s3:Get*.
|
Resource |
The ARNs the statement applies to. |
Condition |
Optional extra checks, such as the caller's IP address or whether they used MFA. |
Resource-based policies, such as S3 bucket policies, also have a
Principal element that says who the statement applies
to. Identity-based policies don't need one, because the principal is whoever
the policy is attached to.
Managed vs. inline
| Type | Who writes it | When to use it |
|---|---|---|
| AWS managed | AWS, for example ReadOnlyAccess |
Broad job functions. AWS updates them when services change, which also means they can grow without you noticing. |
| Customer managed | You | Most things. Reusable across users, groups and roles, and versioned so you can roll back. |
| Inline | You, embedded in one user, group or role | A strict one-to-one link, where the policy should be deleted with its identity. |
For the demo we'll write a customer managed policy, because AWS managed policies are almost always broader than one contractor needs.
Access keys
An access key is a pair: an access key ID (AKIA…) and a secret
access key. Together they work like a username and password for the API, with
two big differences: they don't expire, and they don't ask for MFA. Anyone who
copies them from a laptop, a CI variable or a public Git repository can use
them until you notice.
So the rule is to avoid them where something better exists:
-
For people using the CLI, use IAM Identity Center and
aws sso login, as in the first post. - For code running on AWS, such as EC2 or Lambda, use a role. That's the next post.
- For CI pipelines, use OIDC to assume a role. For instance you can deploy a site from your CI pipelines with no stored AWS keys.
Access keys are still the right tool in a few places, such as a third-party tool that only accepts keys, or a contractor's machine outside your Identity Center. The demo uses them because that's the situation this post started with. When you do use them, rotate them. With two key slots per user, you can do it without downtime:
# 1. Create the new key (the user now has two)
aws iam create-access-key --user-name contractor
# 2. Switch the program to the new key, then check the old one has stopped being used
aws iam get-access-key-last-used --access-key-id AKIAOLDKEYEXAMPLE
# 3. Deactivate the old key; reactivate it if something breaks
aws iam update-access-key --user-name contractor \
--access-key-id AKIAOLDKEYEXAMPLE --status Inactive
# 4. A week later, delete it
aws iam delete-access-key --user-name contractor --access-key-id AKIAOLDKEYEXAMPLE
Demo: deploy one website and nothing else
To log into your sandbox account ensure you have the Access Key Id and Secret Access Key. Then run
aws configure --profile my-sandbox
Inputs on the CLI
aws configure --profile my-sandbox AWS Access Key ID [****************XZO7]: AWS Secret Access Key [****************o/3A]: Default region name [us-east-1]: Default output format [json]:
Once you have that done you can check you are using the correct profile with
aws sts get-caller-identity --profile my-sandbox
The contractor needs to upload the site's files with
aws s3 sync and then tell CloudFront to drop its cached copies.
That's four S3 actions on one bucket and one CloudFront action on one
distribution. Replace the bucket name, account ID and distribution ID with
yours.
To practice without a real site, create a bucket of your own and keep the made-up distribution ID. Every test below works without a distribution.
BUCKET=site-demo-$(aws sts get-caller-identity --query Account --output text)
aws s3 mb s3://$BUCKET
Bucket names are unique across all of AWS, not just your account, and
example-site-bucket already belongs to someone else. If you leave
it in the policy, the sync in step 4 fails with AccessDenied on
ListObjectsV2, because you're asking to write to a stranger's
bucket. Replace example-site-bucket with your bucket name
everywhere below.
Step 1: Write the policy
Save this as deploy-example-site.json:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListSiteBucket",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::$BUCKET"
},
{
"Sid": "WriteSiteFiles",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": "arn:aws:s3:::$BUCKET/*"
},
{
"Sid": "ClearSiteCache",
"Effect": "Allow",
"Action": "cloudfront:CreateInvalidation",
"Resource": "arn:aws:cloudfront::111122223333:distribution/E2EXAMPLE123"
}
]
}
Two details catch people out:
-
s3:ListBucketapplies to the bucket itself (arn:aws:s3:::$BUCKET), while the object actions apply to the objects inside it (…/*). Put them in one statement with only one of those ARNs and half of them silently match nothing. -
CloudFront is a global service, so its ARNs have no region:
arn:aws:cloudfront::account:distribution/id.
Step 2: Create the policy, group and user
aws iam create-policy --policy-name deploy-example-site \
--policy-document file://deploy-example-site.json
aws iam create-group --group-name site-deployers
aws iam attach-group-policy --group-name site-deployers \
--policy-arn arn:aws:iam::111122223333:policy/deploy-example-site
aws iam create-user --user-name contractor
aws iam add-user-to-group --group-name site-deployers --user-name contractor
The policy goes on the group, not the user. When a second contractor starts,
you add them to site-deployers and you're done.
Step 3: Check it before handing anything over
The IAM policy simulator evaluates a user's policies without making real calls, so you can test what they can and can't do before they have any credentials:
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::111122223333:user/contractor \
--action-names s3:PutObject s3:DeleteBucket ec2:RunInstances \
--resource-arns 'arn:aws:s3:::example-site-bucket/index.html' \
--query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output table
-------------------------------------
| SimulatePrincipalPolicy |
+-------------------+---------------+
| s3:PutObject | allowed |
| s3:DeleteBucket | implicitDeny |
| ec2:RunInstances | implicitDeny |
+-------------------+---------------+
implicitDeny means no policy allowed it, which is the default. If
you ever see explicitDeny, a Deny statement
somewhere matched.
Step 4: Create the access key and test it for real
aws iam create-access-key --user-name contractor
The secret access key is shown once, in this output. Send it to the contractor through a password manager's sharing feature, not email or chat. To test it yourself, put it in a separate profile:
aws configure --profile contractor
Then try what the contractor should be able to do, and a few things they shouldn't:
mkdir -p site && echo '<h1>Hello</h1>' > site/index.html
aws s3 sync site/ s3://example-site-bucket/ --delete --profile contractor
# upload: site/index.html to s3://example-site-bucket/index.html
aws s3 ls --profile contractor
# An error occurred (AccessDenied) when calling the ListBuckets operation
aws ec2 describe-instances --profile contractor
# An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation
The contractor can't even see that other buckets exist. That's the point: least privilege means starting from nothing and adding only what the job needs, instead of starting from everything and trying to take things away.
If the contractor finds the AccessDenied on aws s3 ls annoying,
that's a reasonable request to add s3:ListAllMyBuckets. Make that
a deliberate choice, though: it shows them the names of every bucket in the
account.
Changing the policy later
A customer managed policy keeps up to five versions. To change it, create a new version and make it the default:
aws iam create-policy-version \
--policy-arn arn:aws:iam::111122223333:policy/deploy-example-site \
--policy-document file://deploy-example-site.json --set-as-default
If the change breaks something,
aws iam set-default-policy-version switches back to the previous
one.
Clean up
IAM won't delete a user or group that still has things attached, so remove them in this order:
aws iam list-access-keys --user-name contractor # note the key ID
aws iam delete-access-key --user-name contractor --access-key-id AKIA...
aws iam remove-user-from-group --group-name site-deployers --user-name contractor
aws iam delete-user --user-name contractor
aws iam detach-group-policy --group-name site-deployers \
--policy-arn arn:aws:iam::111122223333:policy/deploy-example-site
aws iam delete-group --group-name site-deployers
aws iam delete-policy --policy-arn arn:aws:iam::111122223333:policy/deploy-example-site
Then delete the [contractor] block from
~/.aws/credentials and [profile contractor] from
~/.aws/config.
On the exam
- Attach policies to groups, not individual users. Groups can't be nested and can't be used as a principal.
-
Default deny, explicit
Allowgrants, explicitDenyalways wins. -
Grant least privilege: the specific actions on the specific resources, not
*. - Never share credentials or embed access keys in code. Create one identity per user.
- Each user can have two access keys, which is what makes rotation without downtime possible.
- The IAM policy simulator tests policies without making real calls.
Checklist
- Every person has their own user (or, better, their own Identity Center user).
- Permissions come from groups, using customer managed policies.
- Each policy names specific actions and specific resource ARNs.
- You've tested new policies with the simulator before handing out credentials.
- Access keys exist only where nothing better works, and none are older than about 90 days. The credential report script from the first post checks this.
Next
Every access key in this post is a long-lived secret someone has to look after. The last post in the series covers IAM roles, which hands out temporary credentials instead, and how EC2, Lambda and a GitLab CI pipeline use them so there are no keys to leak.