How create a AWS S3 bucket policy to grant access to specific IPs?

How create a AWS S3 bucket policy to grant access to specific IPs?

June 6, 2020 / Eternal Team

Introduction

  • In this, we are going to learn about how to grant access to the bucket to specific tips to secure our bucket
  • So if the bucket is public no one can access the bucket if they are out of the allowed IP range
  • Eg: if there are multiple projects in a single account and are storing their static data in individual buckets so it is not a good practice that the server can access all the S3 buckets. If for any reason the server gets compromised the person/hacker will get the access of all the bucket so to stop this we can implement a bucket policy by which the specific Public IP or the Private IP only can access the data of the bucket programmatically.

Pre-requirements

  • Server public IP
  • Server private IP
  • Amazon S3 bucket

To create the policy and attach it to the bucket steps are as follow

  • Select the bucket in which you want to apply the policy .
  • In our case, we have created a new bucket name bucket-policy-access.
  • Select permission on the top menu.
  • Select Block Public Access and check that Block all public access is turned on.

  • Now click on bucket policy.
  • Add the following policy to the editor

    Please replace the bucket-name and bucket-name & private-ip-oftheserver/32 as shown in the image below
  • 	{
    	  "Version": "2012-10-17",
    	  "Id": "S3PolicyId1",
    	  "Statement": [
    	    {
    	      "Sid": "IPAllow",
    	      "Effect": "Allow",
    	      "Principal": "*",
    	      "Action": "s3:*",
    	      "Resource": "arn:aws:s3:::bucket-name/*",
    	      "Condition": {
    	        "IpAddress": {
    	          "aws:SourceIp": [
    	            "public-ip-oftheserver/32",
    	            "private-ip-oftheserver/32"
    	          ]
    	        }
    	      }
    	    }
    	  ]
    	}
    	

  • If it shows the “The block public access settings turned on for this bucket prevent granting public access.” then your policy is applied correctly.
  • Now to verify the upload an object and try to access it via browser if it shows the below output policy is working.

Want to start a project?

It’s simple.

Contact us