Packet forwarding between interfaces | Linux IPtables

If you are IPtables nooob just like me, then you might find it hard to work with it. But today here I have a simple script that allows packet forwarding between Interfaces.

Scenario

Let us consider a scenario where you have multiple interfaces. But you have to somehow link those two because you want packet forwarding.

A simple real world use case for such situation can be something like. Creating WireGuard VPN on your VPS instance.

I came across this script while I was setting up the VPN on a VPS.

The Script

Change the WANIF and LANIF variables with the interface that you want to forward.

#! /bin/bash

IPTABLES=/sbin/iptables

WANIF='wlan0'
LANIF='eth0'

# enable ip forwarding in the kernel
echo 'Enabling Kernel IP forwarding...'
/bin/echo 1 > /proc/sys/net/ipv4/ip_forward

# flush rules and delete chains
echo 'Flushing rules and deleting existing chains...'
$IPTABLES -F
$IPTABLES -X

# enable masquerading to allow LAN internet access
echo 'Enabling IP Masquerading and other rules...'
$IPTABLES -t nat -A POSTROUTING -o $LANIF -j MASQUERADE
$IPTABLES -A FORWARD -i $LANIF -o $WANIF -m state --state RELATED,ESTABLISHED -j ACCEPT
$IPTABLES -A FORWARD -i $WANIF -o $LANIF -j ACCEPT

$IPTABLES -t nat -A POSTROUTING -o $WANIF -j MASQUERADE
$IPTABLES -A FORWARD -i $WANIF -o $LANIF -m state --state RELATED,ESTABLISHED -j ACCEPT
$IPTABLES -A FORWARD -i $LANIF -o $WANIF -j ACCEPT

echo 'Done.'Code language: Bash (bash)

I would love to break down the script but the comments are already in place. And that concludes our packet forwarding between interfaces tutorial.

Keep learning.

Suggested

Install RaspberryPi Selenium ChromeDriver

Bash Programming: Conditionals IF / ELSE Statements

Related Posts