TL;DR Playing with Linux network namespaces

I had a Linux server with two physical network interfaces which were separated into two network namespaces. Security was set up like two machines with single network card in each connected to different physical networks.

At one day, someone found out, that a process runs in the ‘red’ network namespace needs to connect to a remote machine, reachable via the physical network interface connected to the other namespace we call as host namespace. How to do so?

Let’s create a virtual network interface pair like a cable between the host namespace and the ‘red’ namespace, then configure link-local IP addresses on both ends. Finally, configure a NAT rule with iptables to ensure host namespace forwards traffic from ‘red’ towards the 443/TCP port of remote host.

I know, in the below snippet, 10.0.0.0/8 is not a link-local IP subnet, sorry for that :)

# Create new namespace called red
ip netns add red

# Set loopback interface of the red namespace up
ip -n red link set dev lo up

# Create virtual cable between the host
# and the recently created namespace
ip link add vred type veth peer name vhost

# Connect one end of the cable to the namespace
# and configure an IP address for it
ip link set vred netns red
ip -n red link set vred up
ip -n red a a 10.0.0.1/24 dev vred

# Configure the other end of that virtual cable
# on the host and ensure interface is up
ip link set vhost up
ip a a 10.0.0.2/24 dev vhost

# Used by NAT, forward IP host connections on 6789/tcp
# toward another IP:port pair
iptables -t nat -A PREROUTING -p tcp --dport 6789 -j DNAT \
                --to-destination [remote-host-ip]:443
iptables -t nat -A POSTROUTING -j MASQUERADE
sysctl -w net.ipv4.ip_forward=1