How to simply forward a port with iptables on Fedora 28 - Carlos Ravelo
Carlos Ravelo

Carlos Ravelo

I'm a Javascript developer with in-depth experience with React, Node.js, webpack, babel and all things js. I have 10+ years of experience with Web Development.

How to simply forward a port with iptables on Fedora 28

02 Mar 2019 » kvm, fedora

I have KVM (libvirtd) installed on a Fedora 28 server and wanted to access some services inside the VMs like RDP for windows for example, this is how you do it with IPTables:

  1. Give your VM a static IP
  2. Gather information
    • To check which bridge device libvirt is using you can use virsh
    • Run virsh net-edit default but dont actually change anything, just take note of the bridge name: <bridge name='virbr0' ...
  3. Run these 2 commands as root (sudo):
    1. Accepts traffic destined to the VM’s ip address:
      sudo iptables -I FORWARD -o virbr0 -d [VM IP HERE] -j ACCEPT
    2. Forward the port:
      sudo iptables -t nat -I PREROUTING -p tcp --dport [OUTSIDE PORT] -j DNAT --to [VM IP]:[SERVICE PORT]
  4. Now you can connect to ip.of.host:[OUTSIDE PORT] and it will be forwarded to the VM on SERVICE PORT.
  5. To persist the changes:
    1. Install iptables-services sudo dnf install iptables-services
    2. to make sure they are loaded after restart sudo systemsctl enable iptables
    3. To save them run sudo service iptables save

After the first time when you want to forward a new port:

  1. Run these 2 commands as root (sudo):
    sudo iptables -I FORWARD -o virbr0 -d [VM IP] -j ACCEPT
    sudo iptables -t nat -I PREROUTING -p tcp --dport [OUTSIDE PORT] -j DNAT --to [VM IP]:[SERVICE PORT]
    
  2. Test that the port is forwarded
  3. Then save them sudo service iptables save

Hope this was helpful, open an issue here if you need help: https://github.com/gandazgul/k8s-infrastructure