Farhad-Taran
Farhad-Taran

Reputation: 6512

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

Upvotes: 3

Views: 1577

Answers (1)

Marko E
Marko E

Reputation: 18158

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

Upvotes: 7

Related Questions