How to create a security group allowing traffic from CloudFront only?
It is one of those problems for which there has been no satisfactory solution for years. How do you ensure that only CloudFront is granted access to an Elastic Load Balancer - CLB, ALB, or NLB? Without the ability to restrict incoming traffic, all of CloudFront’s network layer protection does little good. You will learn how to use AWS-managed prefix list for Amazon CloudFront in the following.
Until recently, when using a load balancer or similar endpoint as the origin for a CloudFront distribution, you had to allow incoming HTTPS traffic from anywhere (0.0.0.0/0
). At least, there was no simple way to maintain a list with all the IP addresses used by the CloudFront edge locations worldwide. In my opinion, automatically updating a security group by using a Lambda function is nothing I want to run in production.
Therefore, probably many other AWS customers and we ended up with the following situation. The load balancer was accessible not only from CloudFront but from anywhere. This made it possible to bypass CloudFront’s protective measures.
Luckily, AWS announced managed prefix lists for CloudFront on February 7, 2022. The prefix list contains all IP ranges used by CloudFront edge locations. AWS updates the prefix list when needed. You can easily use the prefix list to restrict access when configuring a security group, as shown in the following figure.
This means that CloudFront’s protection measures can no longer be bypassed. It is ensured that all incoming traffic on the load balancer comes from CloudFront.
However, keep in mind that anyone can create a CloudFront distribution. This does not guarantee that all the requests arriving at your load balancer originate from your CloudFront distribution. Check out to learn how to restrict access at the application layer.
So how do you create a security group that only allows incoming traffic from CloudFront by using an AWS-managed prefix list? We will present the Terraform and CloudFormation code in the following.
The following snippet shows the Terraform code needed to create a security group that allows incoming HTTPS traffic from CloudFront only. The data source aws_ec2_managed_prefix_list
fetches the ID of the prefix list by name.
data "aws_ec2_managed_prefix_list" "cloudfront" { |
Unfortunately, things are getting a little more complicated when using CloudFormation. The ID of the prefix list aws_ec2_managed_prefix_list
varies between the regions. Luckily, it seems to be the same for all AWS accounts. Therefore, I’m using a mapping between the region and the prefix list for CloudFront in the following snippet.
Mappings: |
There is one stumbling block to consider. The prefix list is not available in
ap-northeast-3
andap-southeast-3
.
I implemented this for one of our consulting clients and our open source project widdix/aws-cf-templates right away. I highly encourage you to do the same.