How can I specify which VPC endpoints or IP addresses can access my Amazon S3 bucket?

Last updated: 2020-03-09

I want to block all traffic to my Amazon Simple Storage Service (Amazon S3) bucket unless the traffic is from specific Amazon Virtual Private Cloud (VPC) endpoints or certain external IP addresses. Or, I'm using a bucket to host a static website and I want the website to be accessible only from specific VPC endpoints or IP addresses. How can I do that?

Resolution

Use a bucket policy to specify which VPC endpoints or external IP addresses can access the S3 bucket.

Note: An external IP address is a public IP address that can be from within a VPC or outside of a VPC. For example, an external IP address can be an Amazon Elastic Compute Cloud (Amazon EC2) instance's Elastic IP address, or the IP address of a VPC's NAT gateway or proxy server.

For example, the following bucket policy blocks traffic to the bucket unless the request is from specified VPC endpoints (aws:sourceVpce) or external IP addresses (aws:SourceIp). Note the following:

Warning: This example bucket policy explicitly denies access to any requests outside the allowed VPC endpoints or IP addresses. Even the user that entered the bucket policy can be denied access to the bucket if the user doesn't meet the conditions. You must review the bucket policy carefully before you save it. If you get accidentally locked out, see I accidentally denied everyone access to my Amazon S3 bucket. How do I regain access?

{
  "Version": "2012-10-17",
  "Id": "VPCe and SourceIP",
  "Statement": [{
    "Sid": "VPCe and SourceIP",
    "Effect": "Deny",
    "Principal": "*",
    "Action": "s3:*",
    "Resource": [
      "arn:aws:s3:::awsexamplebucket",
      "arn:aws:s3:::awsexamplebucket/*"
    ],
    "Condition": {
      "StringNotEquals": {
        "aws:sourceVpce": [
          "vpce-1111111",
          "vpce-2222222"
        ]
      },
      "NotIpAddress": {
        "aws:SourceIp": [
          "11.11.11.11/32",
          "22.22.22.22/32"
        ]
      }
    }
  }]
}

If you must allow specific users (within the same AWS account) access to the bucket even if the users aren't sending requests from the allowed VPC endpoints or IP addresses, then you can include the following statement within the same Condition block of the bucket policy:

  • AROAEXAMPLEID is the role ID of an IAM role that you want to allow
  • AIDAEXAMPLEID is the user ID of an IAM user that you want to allow
  • 111111111111 is the AWS account ID of the bucket, which represents the account's root credentials
"StringNotLike": {
"aws:userId": [
"AROAEXAMPLEID:*",
"AIDAEXAMPLEID",
"111111111111"
]
}

For more information on granting access to specific IAM roles, see How to Restrict Amazon S3 Bucket Access to a Specific IAM Role.


Did this article help you?

Anything we could improve?


Need more help?