Skip to content

Instantly share code, notes, and snippets.

@sandipb
Created April 22, 2023 06:58
Show Gist options
  • Save sandipb/0cf6b9bfc90735fc473161249daa7e46 to your computer and use it in GitHub Desktop.
Save sandipb/0cf6b9bfc90735fc473161249daa7e46 to your computer and use it in GitHub Desktop.
How to enable a linux host to route between two lans
#!/bin/bash
# $PRIVATE_IF is private lan, $PUBLIC_IF is public lan
# the interface which is connected to the interface.
# The default route of this host is already set via this interface
PUBLIC_IF=enp1s0
# The interface connecting to the internal lan, which needs this host to be a router to the Internet
PRIVATE_IF=enp2s0
# The network of the internal lan
PRIVATE_CIDR=192.168.0.1/24
# Enable forwarding in kernel
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
# Accept all packets from private network into the stack
sudo iptables -A INPUT -i $PRIVATE_IF -j ACCEPT
# Accept all packets which relate to a previously initiated connection. i.e. not the first packet of a session
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow forwarding for all packets from internal to external network
sudo iptables -A FORWARD -i $PRIVATE_IF -o $PUBLIC_IF -j ACCEPT
# Don't allow new connections from external network to internal network. Only follow up packets to traffic
# initiated from the internal network is allowed to be forwarded between interfaces
sudo iptables -A FORWARD -i $PUBLIC_IF -o $PRIVATE_IF -m state --state RELATED,ESTABLISHED -j ACCEPT
# SNAT packets going from internal network to external
sudo iptables -t nat -A POSTROUTING -o $PUBLIC_IF -s $PRIVATE_CIDR -j MASQUERADE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment