Communicating Internal NICs using iptables: Route Internet Traffic
In this article, we will discuss how to communicate internal Network Interface Controllers (NICs) using iptables to route Internet traffic. This is particularly useful in a setup where one NIC is connected to the Internet and the other two NICs are forwarding Internet access to local devices.
Prerequisites
Before we begin, let's ensure that we have the necessary setup. In this example, we will use a PC with three NICs, where one NIC (enp1s0) is connected to the Internet, and the other two NICs (enp2s0 and enp3s0) are forwarding Internet access to local devices.
Setting up iptables
The first step is to set up iptables to forward traffic between the NICs. To do this, we need to allow IP forwarding by executing the following command:
echo 1 > /proc/sys/net/ipv4/ip_forward
Next, we need to set up iptables rules to forward traffic between the NICs. The following iptables command will forward traffic from enp2s0 to enp1s0 and vice versa:
iptables -A FORWARD -i enp2s0 -o enp1s0 -j ACCEPT
iptables -A FORWARD -i enp1s0 -o enp2s0 -m state --state RELATED,ESTABLISHED -j ACCEPT
Similarly, we can set up iptables rules to forward traffic from enp3s0 to enp1s0 and vice versa:
iptables -A FORWARD -i enp3s0 -o enp1s0 -j ACCEPT
iptables -A FORWARD -i enp1s0 -o enp3s0 -m state --state RELATED,ESTABLISHED -j ACCEPT
NAT Configuration
Now that we have set up iptables to forward traffic between the NICs, we need to configure Network Address Translation (NAT) to enable Internet access for the local devices. To do this, we need to add the following iptables command:
iptables -t nat -A POSTROUTING -o enp1s0 -j MASQUERADE
This command will masquerade the source IP address of the outgoing packets with the IP address of enp1s0, allowing the local devices to access the Internet.
Testing the Setup
To test the setup, we can use the ping command to check the connectivity between the NICs and the Internet. For example, we can ping a website from a local device connected to enp2s0 or enp3s0, and we should see the response coming from the Internet.
- Ensure that IP forwarding is enabled.
- Set up iptables rules to forward traffic between the NICs.
- Configure Network Address Translation (NAT) to enable Internet access for the local devices.
- Test the setup using the ping command.