Restrict S3 bucket access to cloudflare IPs only

Krzysztof Szarlej
2 min readNov 25, 2019

--

Photo by Utsman Media on Unsplash

Recently I had to create a bucket to host a static react application. One of the requirements was that the app should be accessible only through cloudflare CDN. Direct bucket access through https://BUCKET_NAME.s3-REGION.amazonaws.com should be denied unless request originates from one of CF IP addresses.

Cloudflare provides us with a list of IP classes they use at https://www.cloudflare.com/ips/. We can use this list and add a bucket policy with condition on aws:SourceIp variable to the bucket. Moreover, if using terraform you don’t even have to manually use the IP address list. You can use terraform cloudflare provider and cloudflare_ip_ranges resource.

Below you can find entire bucket policy written in Terraform syntax (note the BUCKET_NAME and ACCOUNT_ID placeholders):

The NotPrincipal is important. Using just Principal: “*”policy would deny the access for all IAM users of the account that owns the bucket — no IAM user could manage the bucket using API or console — only root account would work. Using NotPrincipal we effectively say deny all principals except the listed ones. In this case my policy allows user kszarlej to administer the bucket. You can allow there additional users or a group if needed.

Feel free to contact me at ks@kscloud.pl. You can subscribe to my substack at https://cloudtalks.substack.com/.

https://kscloud.pl

--

--