Skip to main content

VPN Mode using TUN Interface Setup with iptables

This section explains how to configure routing and firewall rules on Linux when using NanoPing in VPN mode. The setup assumes the use of TUN interfaces:

  • tun0 on the client
  • tun1 on the server

These interfaces are created and managed by NanoPing to carry VPN traffic.

Client-Side Configuration

Assumptions

  • LAN interface on the client: enp4s0
  • TUN interface: tun0
  • LAN subnet: 192.168.0.0/24

Setup Script

Create the following script on the client device (e.g., setup_client_routing.sh):

#!/bin/sh

# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# Allow traffic forwarding between LAN and VPN tunnel
iptables -A FORWARD -i enp4s0 -o tun0 -j ACCEPT
iptables -A FORWARD -i tun0 -o enp4s0 -j ACCEPT

# Apply NAT for traffic leaving through the tunnel
iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE

# Use policy routing to send LAN traffic through the VPN tunnel
ip route add default dev tun0 table 200
ip rule add from 192.168.0.0/24 table 200

# Flush routing cache to apply rules
ip route flush cache

Run the Script

Make the script executable and run it:

chmod +x setup_client_routing.sh
sudo ./setup_client_routing.sh

Server-Side Configuration

Assumptions

  • Public network interface on the server: enp3s0
  • TUN interface: tun1

Setup Script

Create the following script on the server device (e.g., setup_server_routing.sh):

#!/bin/sh

# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# Allow forwarding between VPN tunnel and public interface
iptables -A FORWARD -i tun1 -o enp3s0 -j ACCEPT
iptables -A FORWARD -i enp3s0 -o tun1 -j ACCEPT

# Apply NAT for traffic going out the public interface
iptables -t nat -A POSTROUTING -o enp3s0 -j MASQUERADE

Run the Script

Make the script executable and run it:

chmod +x setup_server_routing.sh
sudo ./setup_server_routing.sh

Resetting Routing Rules

To remove all forwarding and NAT rules and reset IP routing:

Create a cleanup script (e.g., reset_routing.sh):

#!/bin/sh

# Disable IP forwarding
echo 0 > /proc/sys/net/ipv4/ip_forward

# Set default policies
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

# Flush all iptables rules
iptables -F
iptables -X
iptables -t nat -F
iptables -t mangle -F

# Delete custom routing rules
ip rule del from 192.168.0.0/24 table 200 2>/dev/null
ip route flush table 200
ip route flush cache

Run it the same way:

chmod +x reset_routing.sh
sudo ./reset_routing.sh

Notes

  • Replace interface names (enp3s0, enp4s0) and subnet ranges as needed to match your environment.
  • This configuration only applies to IPv4.
  • For persistent configurations, consider saving the iptables rules using iptables-save and loading them at boot using iptables-restore or a tool like netfilter-persistent.