2

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}/*",
    ]
  }
}

1 Answer 1

2

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:

  1. Allow it using an IAM policy attached to the role the user is assuming;
  2. Allow it using a bucket policy;
  3. 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}/*",
    ]
  }
}
1
  • restrict as in only allow for that user. not deny it.
    – xerxes
    Commented Apr 12, 2022 at 20:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.