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, then it's a best practice to block applications so that they can't 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. In this setup, all the containers share the same networking namespace.
  • The host mode: The containers share the host's networking namespace.

You can use the bridge and awsvpc networking modes to block containers so that they can't access the instance metadata.

Note: The Amazon ECS agent runs on the host networking namespace and requires access to it. You can't prevent access with the host networking mode.

Resolution

For tasks that use 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 that use 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

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

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

Content-Type: multipart/mixed; boundary="==BOUNDARY=="MIME-Version: 1.0

--==BOUNDARY==
Content-Type: text/cloud-boothook; charset="us-ascii"

#!/bin/sh
# 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 a year ago