AWS S3 存储桶策略白名单

AWS S3 Bucket Policy Whitelist

我有一个将我在 AWS 中的 IP 范围列入白名单的存储桶策略。我有一个 EC2 服务器 运行 正在执行 Packer 构建作业,它试图从我的存储桶中提取一个对象,但我收到 403 Forbidden 错误,即使我的 EC2 服务器的 IP 运行该作业明显在白名单范围内。即使当我从 CIDR 范围内的机器 运行 wget 时,我也会得到同样的错误。我很困惑为什么会这样。政策好像没问题以下是我的存储桶策略、我的服务器 IP 和错误:

Bucket Policy:

{
    "Version": "2012-10-17",
    "Id": "S3PolicyId1",
    "Statement": [
        {
            "Sid": "IPAllow",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::xxxxxxx",
                "arn:aws:s3:::xxxxxxx/*"
            ],
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "10.x.x.x/12"
                    ]
                }
            }
        }
    ]
}

Server IP:

10.x.x.x/32

Error:

ui,message,    amazon-ebs:     "msg": "Error downloading 
https://s3.amazonaws.com/xxxxx/yyyy.zip to C:\temp\xxx.zip Exception 
calling \"DownloadFile\" with \"2\" argument(s): \"The remote server 
returned an error: (403) Forbidden.\""

Amazon S3 存在于 Internet 上。

因此,当与 S3 通信时,您的系统将使用 Public IP 地址

但是您的政策只包括私人 IP 地址。这就是它不起作用的原因。

您的选择是:

  • 修改策略以使用实例的 Public IP 地址,或者 NAT 网关的 Public IP 地址,如果您实例位于私有子网中,OR
  • 创建一个 Gateway VPC Endpoint 将 VPC 直接连接到 Amazon S3。然后,您可以配置一个只接受通过 VPC 端点的流量的桶策略。

aws:sourceIp 需要一个 public IP 地址。根据定义,私有地址是不明确的,10.x.x.x/12 是私有 (RFC-1918) 地址,因此它永远不会匹配。

如果您没有使用 S3 VPC 端点,您可以将 NAT 网关的 public IP 地址列入白名单(假设所有有权访问 thr 网关的实例都应该能够访问存储桶)。

如果您使用的是 S3 VPC 端点,则无法按 IP 列入白名单:

you cannot use the aws:SourceIp condition in your IAM policies for requests to Amazon S3 through a VPC endpoint. This applies to IAM policies for users and roles, and any bucket policies. If a statement includes the aws:SourceIp condition, the value fails to match any provided IP address or range.

https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-s3.html

此外,还有这个:

Note: It's a best practice not to use the aws:SourceIp condition key.

https://aws.amazon.com/premiumsupport/knowledge-center/iam-restrict-calls-ip-addresses/