🖥️

Securing Docker on public IP

Posted on Tue, Aug 15, 2017 Docker Microservices Security

Running a Docker server on a public IP can be a ticket to hell if you don't watch what services listening on 0.0.0.0/0. There is a small tip for secure Centos 7 with iptables.

Problem

Docker and iptables

On Linux, Docker manipulates iptables rules to provide network isolation. While this is an implementation detail and you should not modify the rules Docker inserts into your iptables policies, it does have some implications on what you need to do if you want to have your own policies in addition to those managed by Docker.

Resolution

What now?

Replace you firewalld or standard iptables-services service with customized iptables-services

In this example we allow only SSH to host and HTTP(s) to Docker containers.

sudo yum remove firewalld
sudo yum install iptables-services
mv /etc/sysconfig/iptables  /etc/sysconfig/iptables.$DATE.bak
mv /etc/systemd/system/iptables.service  /etc/systemd/system/iptables.service.$DATE.bak
[Install]
WantedBy=multi-user.target

[Unit]
Description=IPv4 firewall for Docker host
After=syslog.target
Before=docker.service

[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore -n /etc/sysconfig/iptables
StandardOutput=syslog
StandardError=syslog

[Install]
WantedBy=basic.target
systemctl daemon-reload
systemctl enable iptables > /dev/null
# Iptables config for Docker (17.06+)
# (re)load with iptables-restore -n /etc/sysconfig/iptables

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:FILTERS - [0:0]
:DOCKER-USER - [0:0]

-F INPUT
-F DOCKER-USER
-F FILTERS

-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp --icmp-type any -j ACCEPT
-A INPUT -j FILTERS

#Return internal to default Docker rules
# !!! change default externall interface !!!
-A DOCKER-USER ! -i eth0 -j RETURN

#Rules used before auto Docker rules
-A DOCKER-USER -j FILTERS

#Accept established
-A FILTERS -m state --state ESTABLISHED,RELATED -j ACCEPT

# CUSTOM RULES START
# rules for both host INPUT and Docker containers

#HTTP to host or containers
-A FILTERS -m state --state NEW -m tcp -p tcp  --dport 80 -j ACCEPT
-A FILTERS -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT

#SSH
-A FILTERS -m state --state NEW -p tcp -m tcp  -d <YOUR PUBLIC IP> --dport 22 -j ACCEPT
# or only from ip
#-A FILTERS -m state --state NEW -s <source-ip> -d <dest-ip> -p tcp -m tcp --dport 22 -j ACCEPT

# CUSTOM RULES END

#REJECT
-A FILTERS -j REJECT --reject-with icmp-host-prohibited

COMMIT
echo Fixing default interface to $DEF_INT
sed -i -e ''s/eth0/$DEF_INT/g'' /etc/sysconfig/iptables
sudo systemctl start iptables

Docker Swarm need some additional config