dockernetwork-programmingcoreosopenvpntun

CoreOS - expose host ports to VPN


I run docker Openvpn container in CoreOS:

docker run --cap-add NET_ADMIN --device /dev/net/tun ...

Container connects to VPN as client and other VPN clients can ping the container. It runs normal openvpn process inside it with dev tun option in config.

My task is to make host ports (-publushed ports from any other containers) on this machine available to other VPN clients, via that tun0 inside VPN client container (so it must be host's to set up routing?). How to implement this?


Solution

  • So I will assume that you have a container connected to a VPN server and you need to access a server through this container due to IP restrictions and so on.

    1- In case you are using Bridge Network which is the default when you run a container:

    In order to achieve you will need to have IPTables installed inside the container and after starting the VPN connection run the following command:

    iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
    

    And from the host machine where you want to access a service you can use iproute command to route the connection through the container as below:

    Assuming you want to access a remote server with IP 192.168.0.20 through a container with IP: 172.17.0.4

    ip route add 192.168.0.20 via 172.17.0.4
    

    Now whenever you access the server which is 192.168.0.20 it will be through the VPN client inside your container.

    2- You can pass --network=host to docker run and in this case you wont need any extra steps to do as the connection will be routed through the VPN by default


    Update:

    Given that you have a Container Y with port 9000 and accessible through Container X.

    Container X is connected to a VPN.

    A User connected to the same VPN wants to access Container Y and he should go through Container X, then you need to apply the following firewall rules inside Container X

    iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE 
    
    iptables -t nat -A PREROUTING -i tun0 -p tcp --dport 9000 -j DNAT --to-destination $CONTAINER_Y_DOCKER_IP 
    
    iptables -t nat -A POSTROUTING -p tcp -d $CONTAINER_Y_DOCKER_IP --dport 9000 -j SNAT --to-source $CONTAINER_X_DOCKER_IP
    
    iptables -A FORWARD -m state -p tcp -d $CONTAINER_Y_DOCKER_IP --dport 9000 --state NEW,ESTABLISHED,RELATED -j ACCEPT