1:1 NAT with iptables and KVM

Use libvirt to add a network with NAT forwarding to an interface. It will add most of the iptables rules for you. It should looks something like below.
“iptables -L”:

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             10.7.0.0/24         state RELATED,ESTABLISHED
ACCEPT     all  --  10.7.0.0/24          anywhere
ACCEPT     all  --  anywhere             anywhere
REJECT     all  --  anywhere             anywhere            reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere            reject-with icmp-port-unreachable

“iptables -t nat -L”:

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  tcp  --  10.7.0.0/24         !10.7.0.0/24         masq ports: 1024-65535
MASQUERADE  udp  --  10.7.0.0/24         !10.7.0.0/24         masq ports: 1024-65535
MASQUERADE  all  --  10.7.0.0/24         !10.7.0.0/24

The outward-going iptables chains are already there. To allow incoming packets and 1:1 port mapping, add the following. Change addresses and interface names as needed.

iptables -I FORWARD -i eth1 -o virbr1 -d 10.7.0.0/24 -j ACCEPT
iptables -t nat -i eth1 -j DNAT --to-destination=10.7.0.1

Note: the first rule is the same rule as rule #1 in FORWARD but without the ESTABLISHED state condition.

To make the iptables permanent, use either “iptables-save” or add the rules to /etc/sysconfig/iptables. Everything should work at this point. If not, make sure forwarding is enabled.

echo "1" > /proc/sys/net/ipv4/ip_forward
#permanently set forwarding in /etc/sysctl.conf
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

2 Responses to 1:1 NAT with iptables and KVM

  1. Sandjay says:

    iptables -t nat -i eth1 -j DNAT –to-destination=10.7.0.1

    return :
    iptables v1.4.7: no command specified
    Try `iptables -h’ or ‘iptables –help’ for more information.

    🙁

Leave a Reply to Sandjay Cancel reply

Your email address will not be published. Required fields are marked *