简体   繁体   中英

Terraform AWS S3 - deny to all except 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}/*",
    ]
  }
}

I think you have to take into account that other users may have Allow in their policies, so the approach here should be to deny access to any users not being the user you want it to be. There is a detailed explanation in the AWS docs [1], but for the sake of brevity, I think the terraform code should look like the following:

data "aws_iam_policy_document" "vulnerability-scans" {
  statement {
    sid    = "AllExceptUser"
    effect = "Deny"
    principals {
      type = "AWS"
      identifiers = ["*"]
    }

    actions = [
      "s3:PutObject",
      "s3:GetObject",
      "s3:ListBucket",
    ]

    resources = [
      aws_s3_bucket.vulnerability-scans.arn,
      "${aws_s3_bucket.vulnerability-scans.arn}/*",
    ]

    condition {
      test     = "StringNotLike"
      variable = "aws:userId"
      values = [
        aws_iam_user.circleci.arn
      ]
    }
  }
}

Even though the reference URL says it is for an IAM role, the same applies for a user. The StringNotLike condition operator has more detailed explanation in [2].


[1] https://aws.amazon.com/blogs/security/how-to-restrict-amazon-s3-bucket-access-to-a-specific-iam-role/

[2] https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM