Skip to content

Instantly share code, notes, and snippets.

@Nesh108
Forked from mattbell87/iptables.md
Created January 3, 2023 11:53
Show Gist options
  • Save Nesh108/b9d21db77557802e23041ae682581bb8 to your computer and use it in GitHub Desktop.
Save Nesh108/b9d21db77557802e23041ae682581bb8 to your computer and use it in GitHub Desktop.
IPtables for routing over OpenVPN on Linux

Enable forwarding:

sysctl -w net.ipv4.ip_forward=1

Create this script eg sudo nano iptables.sh

eth=$1
proto=$2
port=$3

# OpenVPN
iptables -A INPUT -i "$eth" -m state --state NEW -p "$proto" --dport "$port" -j ACCEPT

# Allow TUN interface connections to OpenVPN server
iptables -A INPUT -i tun+ -j ACCEPT

# Allow TUN interface connections to be forwarded through other interfaces
iptables -A FORWARD -i tun+ -j ACCEPT
iptables -A FORWARD -i tun+ -o "$eth" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i "$eth" -o tun+ -m state --state RELATED,ESTABLISHED -j ACCEPT

# NAT the VPN client traffic to the internet
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o "$eth" -j MASQUERADE

Run the script with sudo bash iptables.sh eth0 udp 1194:

  • where eth0 is the interface your server is running on. Could be br0 if using VMs.
  • where udp is the protocol you're using for OpenVPN
  • where 1194 is the port you're using for OpenVPN

Now test it!

If it didn't work reboot.

If it did work save the configuration with iptables-persistent.

Debian/Ubuntu: sudo apt install iptables-persistent. If already installed you can use sudo dpkg-reconfigure iptables-persistent.

Fedora: Consider using firewalld instead of iptables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment