带有 CloudFlare 的 S3 存储桶:防止盗链

dij*_*jon 2 amazon-s3 hotlinking cloudflare

我正在使用名为 images.example.com 的 Amazon S3 存储桶,该存储桶使用如下 URL 成功通过 Cloudflare CDN 提供内容:

https://images.example.com/myfile.jpg
Run Code Online (Sandbox Code Playgroud)

我想防止热链接到图像和其他内容,购买限制仅访问引用域:example.com 以及可能用作开发服务器的另一个域。

我尝试过一种存储桶策略,它既允许来自特定域,又拒绝来自任何非特定域的域:

 {
"Version": "2012-10-17",
"Id": "http referer policy example",
"Statement": [
    {
        "Sid": "Allow get requests referred by www.example.com",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::images.example.com/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": [
                    "http://www.example.com/*",
                    "http://example.com/*"
                    ]
            }
        }
    },
    {
        "Sid": "Explicit deny to ensure requests are allowed only from specific referer.",
        "Effect": "Deny",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::images.example.com/*",
        "Condition": {
            "StringNotLike": {
                "aws:Referer": [
                    "http://www.example.com/*",
                    "http://example.com/*"
                    ]
            }
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

}

为了测试这个。我在不同的服务器上上传了一个小网页:www.notExample.com,我尝试使用以下方法热链接图像:

 <img src="https://images.example.com/myfile.jpg">
Run Code Online (Sandbox Code Playgroud)

但无论如何都会出现热链接图像。

我还尝试了以下 CORS 规则

 <CORSConfiguration>
  <CORSRule>
    <AllowedOrigin>http://www.example.com</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
   </CORSRule>
 </CORSConfiguration>
Run Code Online (Sandbox Code Playgroud)

这些都不能有效防止热链接。我尝试使用存储桶策略和 CORS(其中之一或两者加两者)的组合来清除 CloudFlare 中的缓存文件,但没有任何效果。

这似乎是一件比较简单的事情。我究竟做错了什么?

Joh*_*ein 5

Cloudflare 是一个内容分发网络,可缓存更靠近最终用户的信息。

当用户通过 Cloudflare 访问内容时,该内容将从 Cloudflare 的缓存中提供。如果内容不在缓存中,Cloudflare 将检索内容,将其存储在缓存中并将其返回给原始请求。

因此,您的 Amazon S3 存储桶策略将无法与 Cloudflare 配合使用,因为页面请求要么来自 Cloudflare(不是生成 Referrer 的用户浏览器),要么直接从 Cloudflare 的缓存提供服务(因此请求永远不会到达 S3)。

您需要使用引用规则(而不是 S3)配置 Cloudflare 。

请参阅:启用 CloudFlare 热链接保护有什么作用?

一些替代方案:

  • 使用 Amazon CloudFront - 它能够通过使用签名 URL 来提供私有内容- 您的应用程序可以通过在创建 HTML 页面时生成特殊 URL 来授予访问权限。
  • 直接从 Amazon S3 提供内容,它可以使用规则referer。Amazon S3 还支持您的应用程序可以生成的预签名 URL 。