22

I created an AOI to restrict access of the s3 bucket to public. So you can not access the s3 objects via the s3 endpoint but cloudfront can access all those objects and serve them.

I setup an Alternate Domain Names and add the SSL Certificate for this domain.

I setup route 53 with a A rule to alias cloudfront distribution

I can access the page using the Cloudfront public url (*.cloudfront.net) and mydomain.com

How can I remove the *.cloudfront.net access to my page? This should be possible because the only service that needs this url is route 53.

2
  • 1
    I have the same question/issue. Have you found the solution?
    – illagrenan
    Commented Jan 12, 2018 at 11:19
  • My concern was to end up with duplicated content when Google will be crawling both domains. I used lambda edge to dynamically return a robots.txt that will deny all on *.cloudfront.net but will allow google bot on the real domain
    – rolele
    Commented Jan 22, 2018 at 10:54

4 Answers 4

8

Much easier than Lamda@Edge would be just to configure an ACL to block each request containing the Host header with your cloudfront distribution url.

Configure AWS WAF / ACL

3
  • I was looking at the lambda option originally but this is a much simpler method. Am I right in thinking that one ACL can be shared among many distributions?
    – Zakalwe
    Commented Aug 24, 2020 at 18:54
  • "Note that you can share a web ACL across multiple AWS resources within the same region" given at aws.amazon.com/waf/pricing under the pricing calculator. I believe this answers my question!
    – Zakalwe
    Commented Aug 24, 2020 at 18:58
  • 1
    Except that WAF costs $5 per month for each Web ACL, $1 for each rule, and then extra costs per request! For a simple site that is only costing a few cents per month to begin with, this doesn't make sense (pun unintended). It's good to know this alternative exists, though. Commented Apr 22, 2023 at 12:40
3

You can use Lambda@Edge Viewer Request trigger. This allows you to inspect the request before the cache is checked, and either allow processing to continue or to return a generated response.

So, you can check the referer and make sure the request coming from your domain.

'use strict';

exports.handler = (event, context, callback) => {

  // extract the request object
  const request = event.Records[0].cf.request;

  // extract the HTTP `Referer` header if present
  // otherwise an empty string to simplify the matching logic
  const referer = (request.headers['referer'] || [ { value: '' } ])[0].value;

  // verify that the referring page is yours
  // replace example.com with your domain
  // add other conditions with logical or ||
  if(referer.startsWith('https://example.com/') ||
     referer.startsWith('http://example.com/'))
  {
    // return control to CloudFront and allow the request to continue normally
    return callback(null,request);
  }

  // if we get here, the referring page is not yours.
  // generate a 403 Forbidden response
  // you can customize the body, but the size is limited to ~40 KB

  return callback(null, {
    status: '403',
    body: 'Access denied.',
    headers: {
      'cache-control': [{ key: 'Cache-Control', value: 'private, no-cache, no-store, max-age=0' }],
      'content-type': [{ key: 'Content-Type', value: 'text/plain' }],
    }
  });
};

For more info read the following pages:

https://stackoverflow.com/a/51006128/6619626

Generating HTTP Responses in Request Triggers

Updating HTTP Responses in Origin-Response Triggers

Finally, this article has a lot of valuable info

How to Prevent Hotlinking by Using AWS WAF, Amazon CloudFront, and Referer Checking

2

Also, a very simple solution is to add a CloudFront function on the viewer request event for your behaviour in question:

function isCloudFrontURL(headers) {
    if(headers && headers["host"]) {
        if(headers["host"].value.includes("cloudfront"))
            return true
        else if(headers["host"].multiValue)
            return headers["host"].multiValue.some(entry => entry.value.includes("cloudfront"))
    }
    return false
}

function handler(event) {
    if(isCloudFrontURL(event.request.headers))
        return {
            statusCode: 404,
            statusDescription: 'Page not found',
            headers: {
                "content-type": { 
                    "value": "text/plain; charset=UTF-8" 
                    
                }
            }
        }
    else
        return event.request;
}
2
  • The sample code is helpful as a head start to help me create my own. But it plays really loose with the checks—wouldn't this prevent someone from hosting their site at better-than-cloudfront.net or some such? Furthermore this approach assumes what the CloudFront URL will look like—maybe it will change in the future. I wonder if it would be more direct simply to confirm that the host is the custom domain, instead of ensuring it is not the CloudFront domain? Lastly multivalue Host headers are prohibited as per RFC 7230 § 5.4. Commented Apr 28, 2023 at 22:13
  • Sure, I agree that such a change would be beneficial. Nonetheless, then you have to deploy one function per domain, here you can just reuse the same function for all domains. The check for multiValue is more of a programmatic guard rather than an attempt to adhere to specification. Commented Apr 29, 2023 at 16:10
0

Based on @mhelf's answer, I prepared a demo in Terraform on how to set up WAF v2 for CloudFront.

Terraform resources

(1.) Configure AWS provider.

// WAF v2 for CloudFront MUST be created in us-east-1
provider "aws" {
  alias  = "virginia"
  region = "us-east-1"
}

(2.) Create CloudFront distribution.

// CloudFront which is accessible at example.com 
// and should not be accessible at ***.cloudfront.net
resource aws_cloudfront_distribution cf {
  // ...
  // ...

  web_acl_id = aws_wafv2_web_acl.waf.arn

  aliases = [
    "example.com",
  ]

  // ...
  // ...
}

(3.) Finally create WAF v2.

// WAF v2 that blocks all ***.cloudfront.net requests
resource aws_wafv2_web_acl waf {
  provider    = aws.virginia
  name        = "example-waf"
  description = "..."
  scope       = "CLOUDFRONT"

  default_action {
    allow {}
  }

  rule {
    name     = "cf-host-rule"
    priority = 0

    action {
      block {
      }
    }

    statement {
      regex_match_statement {
        regex_string = "\\w+.cloudfront.net"

        field_to_match {
          single_header {
            name = "host"
          }
        }

        text_transformation {
          priority = 0
          type     = "LOWERCASE"
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "example-waf-cf-host-rule"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "example-waf"
    sampled_requests_enabled   = true
  }
}

Notes

  1. It would probably be safer/cleaner to use byte_match_statement to check the Host header value against aws_cloudfront_distribution.cf.domain_name. However, this would create a cycle between the CF and the WAF resource, which is why I used regex_match_statement.
  2. Support for regex_match_statement has been added relatively recently in the AWS provider v4.34.0 (GH Issue 25101 / GH Pull request 22452 / GH Release v4.34.0)
  3. WAF is a paid service, see: https://aws.amazon.com/waf/pricing/

cURL test

curl -v https://example.com
> GET / HTTP/2
> Host: example.com
> user-agent: curl/7.68.0
> accept: */*
>

< HTTP/2 200
< content-type: image/jpeg
< content-length: 9047
< date: Wed, 19 Oct 2022 13:40:55 GMT
< x-cache: Hit from cloudfront
curl -v https://***.cloudfront.net
> GET / HTTP/2
> Host: ***.cloudfront.net
> user-agent: curl/7.68.0
> accept: */*
>
< HTTP/2 403
< server: CloudFront
< date: Thu, 20 Oct 2022 08:15:44 GMT
< content-type: text/html
< content-length: 919
< x-cache: Error from cloudfront
< via: 1.1 ***.cloudfront.net (CloudFront)
<
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>403 ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Request blocked.
We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
<BR clear="all">
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: ***
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>
1
  • You can pass a host header with curl to get around this. As in curl -H host:example.com foo.cloudfront.net
    – Sean
    Commented Aug 20 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.