Recently I came across an issue where I had to whitelist certain IP addresses to have access over a S3 bucket.

AWS is really great. It supports granular control over buckets and objects in them.

From what I could infer, there are 3 basic types of access settings that you can customise in AWS.

  1. Public Access Setting -> control the settings that allow public access to your data.
  2. Access Control List (ACLs) -> Grant basic read/write permissions to other AWS accounts.
  3. Bucket Policy -> Use json based access policy language to manage advanced permissions to your S3 resources.

We will be using Bucket Policy to achieve our use case.

{
    "Version": "2012-10-17",
    "Id": "S3PolicyIPRestrict",
    "Statement": [
        {
            "Sid": "IPAllow",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::your-bucket-items/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "ip-address/subnet-mask",
                        "other-ip-address/subnet-mask"
                    ]
                }
            }
        }
    ]
}

Let's go through the above structure.

  1. Id -> unique id to identify the policy with.
  2. Statement -> actual logic.
  3. Effect -> Allow/Block access via this policy.
  4. Principal -> specifies the user, account, service, or other entity that is allowed or denied access to a resource.
  5. Action ->  define the permissions for anyone performing an operation in AWS.
  6. Resources -> where this particular setting will take effect in.
  7. Condition -> object of conditions. Here we are putting list of all IP addresses we need to whitelist which can access a particular bucket.

Hope this was helpful!