patternterraformMinor
Terraform Aws S3 - deny all users except for a specific user
Viewed 0 times
alluserdenyforawsspecificusersexceptterraform
Problem
I have a bucket which I need to restrict to a specific user, I have written the following script but it still seems to allow all users to operate on the bucket.
resource "aws_s3_bucket" "vulnerability-scans" {
bucket = "vulnerability-scans"
}
resource "aws_s3_bucket_policy" "vulnerability-scans" {
bucket = aws_s3_bucket.vulnerability-scans.id
policy = data.aws_iam_policy_document.vulnerability-scans.json
}
data "aws_iam_policy_document" "vulnerability-scans" {
statement {
principals {
type = "AWS"
identifiers = [
aws_iam_user.circleci.arn,
]
}
actions = [
"s3:PutObject",
"s3:GetObject",
"s3:ListBucket",
]
resources = [
aws_s3_bucket.vulnerability-scans.arn,
"${aws_s3_bucket.vulnerability-scans.arn}/*",
]
}
}Solution
First, let's understand how roles and policies work on AWS. In order for an user to be able to access a bucket, we can allow it in 3 ways:
These are explicit
What is important is that an explicit
Bucket policy example:
Terraform code for this policy:
- Allow it using an IAM policy attached to the role the user is assuming;
- Allow it using a bucket policy;
- The group of the user has the policy attached to it or there is a policy directly attached to the user which allows access to the bucket.
These are explicit
Allow policies. The user will have access if there is at least on policy from above granting him/her access.What is important is that an explicit
Deny takes precedence of an explicit Allow. So, if we want to deny access to a specific user, we would want to create a bucket policy with an explicit Deny. In order to do this, we can use NotPrincipal.Bucket policy example:
{
"Id": "bucketPolicy",
"Statement": [
{
"Action": "s3:*",
"Effect": "Deny",
"NotPrincipal": {
"AWS": [
"arn:aws:iam::1234567890:user/alloweduser"
]
},
"Resource": [
"arn:aws:s3:::examplebucket",
"arn:aws:s3:::examplebucket/*"
]
}
],
"Version": "2012-10-17"
}Terraform code for this policy:
data "aws_iam_policy_document" "vulnerability-scans" {
statement {
not_principals {
type = "AWS"
identifiers = [
aws_iam_user.circleci.arn
]
}
effect = "Deny"
actions = [
"s3:*"
]
resources = [
aws_s3_bucket.vulnerability-scans.arn,
"${aws_s3_bucket.vulnerability-scans.arn}/*",
]
}
}Code Snippets
{
"Id": "bucketPolicy",
"Statement": [
{
"Action": "s3:*",
"Effect": "Deny",
"NotPrincipal": {
"AWS": [
"arn:aws:iam::1234567890:user/alloweduser"
]
},
"Resource": [
"arn:aws:s3:::examplebucket",
"arn:aws:s3:::examplebucket/*"
]
}
],
"Version": "2012-10-17"
}data "aws_iam_policy_document" "vulnerability-scans" {
statement {
not_principals {
type = "AWS"
identifiers = [
aws_iam_user.circleci.arn
]
}
effect = "Deny"
actions = [
"s3:*"
]
resources = [
aws_s3_bucket.vulnerability-scans.arn,
"${aws_s3_bucket.vulnerability-scans.arn}/*",
]
}
}Context
StackExchange DevOps Q#15753, answer score: 2
Revisions (0)
No revisions yet.