Terraform Aws S3 - deny all users except for a specific user



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

    }
    }



  • 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, https://aws.amazon.com/blogs/security/how-to-restrict-amazon-s3-bucket-access-to-a-specific-iam-role/ .

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

    }
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2