Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block docker access to specific IP

I'd like my EC2 instance to have IAM-based permissions, but don't want the docker containers on that instance to have the same permissions. I believe it should be sufficient to block access to the magic IP 169.254.169.254. Is it sufficient to run: iptables -I DOCKER -s 169.254.169.254 -j DROP

Do I also need to configure my docker daemon with --icc=false or --iptables=false?

like image 868
MattyB Avatar asked Sep 10 '15 22:09

MattyB


2 Answers

Finally got this working, you need to add this rule on the host machine:

1) Drop docker bridge packets when outbound to 169.254.169.254 port 80 or 443.

sudo iptables -I FORWARD -i docker0 -d 169.254.169.254 \
  -p tcp -m multiport --dports 80,443 -j DROP

Now, if I try to connect inside the container:

$ sudo docker run -it ubuntu bash
root@8dc525dc5a04:/# curl -I https://www.google.com
HTTP/1.1 200 OK
root@8dc525dc5a04:/# curl -I http://169.254.169.254/
  # <-- hangs indefinitely, which is what we want

Connections to the special IP still work from the host machine, but not from inside containers.

Note: my use case is for Google Compute Engine and prevents Docker containers from accessing the metadata server on 169.254.169.254, while still allowing DNS and other queries against that same IP. Your mileage may vary on AWS.

like image 68
fotinakis Avatar answered Oct 07 '22 15:10

fotinakis


I would recommend the following variation on the accepted answer:

sudo iptables \
        --insert DOCKER-USER \
        --destination 169.254.169.254 \
        --jump REJECT

The reason for this is that the above command adds the rule to the DOCKER-USER chain which Docker is guaranteed not to modify.

Sources:

  • https://ops.tips/blog/blocking-docker-containers-from-ec2-metadata/
  • https://docs.docker.com/network/iptables/
like image 5
Ben Elgar Avatar answered Oct 07 '22 15:10

Ben Elgar