How can I prevent containers from accessing Amazon EC2 instance metadata in Amazon ECS?

2 minute read
0

I want to prevent containers from accessing Amazon Elastic Compute Cloud (Amazon EC2) instance metadata in Amazon Elastic Container Service (Amazon ECS).

Short description

If you run containers in an Amazon EC2 instance, it's a best practice for security reasons to avoid allowing your applications to assume an instance role.

Amazon ECS provides the following networking modes to run a task with external connectivity:

  • The bridge mode. The task uses Docker's built-in virtual network.
  • The awsvpc mode. The task allocates an elastic network interface, and all the containers share the same networking namespace.
  • The host mode. The containers share the host's networking namespace.

The following resolution shows you how to prevent containers from accessing the instance metadata using the bridge and awsvpc networking modes.

Note: It's not possible to prevent access with the host networking mode, because the Amazon ECS agent runs on the host networking namespace and requires access to it.

Resolution

For tasks using the awsvpc networking mode, add the following parameter to the Amazon ECS configuration file /etc/ecs/ecs.config:

ECS_AWSVPC_BLOCK_IMDS=true

For tasks using the bridge networking mode, use iptables to block the network traffic from the docker0 bridge.

You can specify the configuration of iptables in your custom Amazon Machine Image (AMI) or at launch in Amazon EC2 instance user data. See the following example for Amazon Linux 2 AMIs.

Note: If you choose Amazon EC2 instance user data, the following configuration must be written before the Docker daemon starts. The cloud-boothook user data format executes earlier in the boot process than most services.

#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

To include this configuration with your existing user data, use the MIME multi part archive. See the following example:

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==--

AWS OFFICIAL
AWS OFFICIALUpdated 2 years ago