我想防止 Amazon Elastic Container Service (Amazon ECS) 中的容器访问 Amazon Elastic Compute Cloud (Amazon EC2) 实例元数据。
简短描述
如果您在 Amazon EC2 实例中运行容器,出于安全考虑,最佳做法是避免让您的应用程序担任实例角色。
Amazon ECS 提供以下联网模式,以通过外部连接运行任务:
- bridge 模式。 任务使用 Docker 的内置虚拟网络。
- awsvpc 模式。 任务分配一个弹性网络接口,所有容器共享相同的网络命名空间。
- host 模式。 容器共享主机的网络命名空间。
以下解决方法介绍如何防止容器使用 bridge 和 awsvpc 网络模式访问实例元数据。
**注意:**在 host 网络模式下,无法防止访问,因为 Amazon ECS 代理在 host 网络命名空间上运行,需要进行访问。
解决方法
对于使用 awsvpc 网络模式的任务,请将以下参数添加到 Amazon ECS 配置文件 /etc/ecs/ecs.config:
ECS_AWSVPC_BLOCK_IMDS=true
对于使用 bridge 网络模式的任务,请使用 iptables 防止来自 docker0 bridge 的网络流量。
您可以在自定义 Amazon 系统映像 (AMI) 中,或在 Amazon EC2 实例用户数据中启动时,指定 iptables 的配置。请参阅以下 Amazon Linux 2 AMI 示例。
注意:如果您选择 Amazon EC2 实例用户数据,则必须在 Docker 进程守护程序启动之前写入以下配置。在引导过程中,cloud-boothook 用户数据格式的执行时间比大多数服务都要早。
#cloud-boothook
yum install iptables-services -y
cat <<EOF > /etc/sysconfig/iptables
*filter
:DOCKER-USER - [0:0]
-A DOCKER-USER -d 169.254.169.254/32 -j DROP
COMMIT
EOF
systemctl enable iptables && systemctl start iptables
要将此配置包含在现有用户数据中,请使用 MIME 分段存档。请参阅以下示例:
Content-Type: multipart/mixed; boundary="==BOUNDARY=="
MIME-Version: 1.0
--==BOUNDARY==
Content-Type: text/cloud-boothook; charset="us-ascii"
# Set iptables configuration
yum install iptables-services -y
cat <<EOF > /etc/sysconfig/iptables
*filter
:DOCKER-USER - [0:0]
-A DOCKER-USER -d 169.254.169.254/32 -j DROP
COMMIT
EOF
systemctl enable iptables && systemctl start iptables
--==BOUNDARY==
Content-Type: text/x-shellscript; charset="us-ascii"
#!/bin/bash
# Set any ECS agent configuration options
echo "ECS_CLUSTER=my-ecs-cluster" >> /etc/ecs/ecs.config
--==BOUNDARY==--