Search code examples
amazon-web-servicesamazon-s3corsddos

Setting CORS config for AWS S3


To optimize my server usage I moved the images (~500) and rendered HTML files for SEO (~1000) to S3 storage & it works just fine, however, I am worried about having a DDoS attack which will, in the end, cost me a lot of money, since Amazon charges for every GET request.

I did some research on how to prevent that and found out that there is a CORS config option for S3.

I tried it out, but unfortunately, it didn't seem to work. Can still access the files from any URL

enter image description here enter image description here

What am I doing wrong?

UPDATE:

Also tried to set bucket policy:

enter image description here


Solution

  • CORS configuration permits cross-domain requests. It is not a method for restricting access to files.

    By default, browsers will not allow cross-domain requests. For example, the browser will not allow a page served from example1.com to access content from example2.com. This is done to protect your personal information, such as people trying to open iframes to Facebook to access your personal Facebook content.

    If, however, example2.com is willing to permit this cross-domain request, then it can add a Cross Original Resource Sharing (CORS) policy that says that example1.com is permitted to access the content in a cross-domain manner. The web browser will then permit the access.

    In summary: It is your web browser that is controlling CORS. The CORS policy just tells the web browser to permit it.

    See: Cross-Origin Resource Sharing (CORS)

    Restricting by Referrer

    Your particular requirement, however, appears to be that you are willing to serve content from Amazon S3, but only if it appears on a particular web page. For example, only show images from images.example.com if it is being requested by a page served by example.com. You can achieve this by specifying a Referrer in an Amazon S3 Bucket Policy.

    From Restricting Access to a Specific HTTP Referrer:

    {
      "Version":"2012-10-17",
      "Id":"http referer policy example",
      "Statement":[
        {
          "Sid":"Allow get requests originating from www.example.com and example.com.",
          "Effect":"Allow",
          "Principal":"*",
          "Action":"s3:GetObject",
          "Resource":"arn:aws:s3:::examplebucket/*",
          "Condition":{
            "StringLike":{"aws:Referer":["http://www.example.com/*","http://example.com/*"]}
          }
        }
      ]
    }
    

    It is relatively easy to fake a referrer, but this should generally give you what you are seeking.