Created
June 18, 2024 00:31
-
-
Save pojntfx/cbc2e32b9ed1147ecb8c9c982830dfe8 to your computer and use it in GitHub Desktop.
Port-forwarding from a VM at a private IP to the outside with `iptables`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Expose all ports of the VM at `<guest-veth-ip>:<port>` (this is done by default) | |
# nc "${HOST_VETH_INTERNAL_IP}" guest-veth-port-here | |
export HOST_VETH_INTERNAL_IP="10.0.8.1" | |
export NAMESPACE_INTERFACE_IP="172.100.100.2" | |
sudo ip netns exec ark0 iptables -t nat -A PREROUTING -d "${HOST_VETH_INTERNAL_IP}" -j DNAT --to-destination "${NAMESPACE_INTERFACE_IP}" | |
sudo ip netns exec ark0 iptables -t nat -A POSTROUTING -d "${NAMESPACE_INTERFACE_IP}" -j MASQUERADE | |
# Expose a port of the VM on the host | |
# nc "${HOST_IP}" "${HOST_PORT}" | |
# Note that if you expose a port to an external IP like `192.168.245.31`, | |
# it will not be accessible from the host itself, that is only the case | |
# if it's forwarded to `127.0.0.1` explicitly | |
export HOST_VETH_INTERNAL_IP="10.0.8.1" | |
export HOST_VETH_INTERNAL_PORT="6379" | |
export HOST_IP="192.168.245.31" | |
export HOST_PORT="3333" | |
if [ "${HOST_IP}" = "127.0.0.1" ]; then | |
sudo sysctl -w net.ipv4.conf.all.route_localnet=1 | |
sudo sysctl -w net.ipv4.conf.lo.route_localnet=1 | |
else | |
sudo iptables -A FORWARD -d "${HOST_VETH_INTERNAL_IP}" -j ACCEPT | |
sudo iptables -A FORWARD -s "${HOST_VETH_INTERNAL_IP}" -j ACCEPT | |
fi | |
sudo iptables -t nat -A OUTPUT -p tcp -d "${HOST_IP}" --dport "${HOST_PORT}" -j DNAT --to-destination "${HOST_VETH_INTERNAL_IP}:${HOST_VETH_INTERNAL_PORT}" | |
sudo iptables -A PREROUTING -t nat -p tcp --dport "${HOST_PORT}" -d "${HOST_IP}" -j DNAT --to-destination "${HOST_VETH_INTERNAL_IP}:${HOST_VETH_INTERNAL_PORT}" | |
sudo iptables -t nat -A POSTROUTING -p tcp -d "${HOST_VETH_INTERNAL_IP}" --dport "${HOST_VETH_INTERNAL_PORT}" -j MASQUERADE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment