Skip to content

Instantly share code, notes, and snippets.

@pawal
Last active September 26, 2023 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pawal/c3c945a7e29887a35f343b4fcbf323ef to your computer and use it in GitHub Desktop.
Save pawal/c3c945a7e29887a35f343b4fcbf323ef to your computer and use it in GitHub Desktop.
UFW and NAT reflection (hairpin) rules for before.rules, KVM setup with VMs with different services

These are the set of rules for making internal services of a KVM setup be reachable using the public WAN IP addresses of the services from the VMs or local hosts in the local network.

Use case may be a KVM set up, with a bunch of VMs that needs to talk to eachother using the public DNS that contains the public WAN address. Any traffic that goes out to the public WAN IP address will be rewritten to go back to the host responsible for the port. Traffic for these ports originating for internetservices coming from the local network will still be sent out to the Internet through the WAN.

This entire set of rules for enabling this in the before.rules file for the UFW firewall.

  • First part, directing external WAN traffic to internal hosts.
  • Second part, reflecting local traffic going to the WAN IP address to the ports on the local machines.
  • Last part, masquerading local traffic out on the internet using the MASQUERADE rule.
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-F
-A PREROUTING -i eno1 -p udp -d <wan-ip> --dport 53 -j DNAT --to-destination <LAN>.53
-A PREROUTING -i eno1 -p tcp -d <wan-ip> --dport 53 -j DNAT --to-destination <LAN>.53
-A PREROUTING -i eno1 -p tcp -d <wan-ip> --dport 33 -j DNAT --to-destination <LAN>.22
-A PREROUTING -i eno1 -p tcp -d <wan-ip> --dport 80 -j DNAT --to-destination <LAN>.80
-A PREROUTING -i eno1 -p tcp -d <wan-ip> --dport 443 -j DNAT --to-destination <LAN>.80
-A PREROUTING -i eno1 -p tcp -d <wan-ip> --dport 25 -j DNAT --to-destination <LAN>.25
-A PREROUTING -i eno1 -p tcp -d <wan-ip> --dport 587 -j DNAT --to-destination <LAN>.25
-A PREROUTING -i eno1 -p tcp -d <wan-ip> --dport 993 -j DNAT --to-destination <LAN>.25
-A POSTROUTING -s <LAN>/24  -d <LAN> -p tcp --dport 80 -j MASQUERADE
-A POSTROUTING -s <LAN>/24 -o eno1 -j MASQUERADE
COMMIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment