Skip to content

Instantly share code, notes, and snippets.

@caHarkness
Last active May 7, 2024 14:55
Show Gist options
  • Save caHarkness/f169329fe75232d176fae5ab6e7818f8 to your computer and use it in GitHub Desktop.
Save caHarkness/f169329fe75232d176fae5ab6e7818f8 to your computer and use it in GitHub Desktop.
Script for configuring Debian to act as a router (Internet and port forwarding)
#!/bin/bash
# Q: What is this?
# A: This is a script designed to make a Debian install (with networking and iptables) serve as a router. If the Debian install this is running on can talk with the Internet already, this script will configure iptables to perform NAT for the specified networks, allowing other devices to use this Debian installation as a gateway. This script can also configure port forwarding. See the examples below!
# How to use:
# 1. Update networks, interfaces, and rules below
# 2. Run once after updating on Debian systems
# Guarantee reloading on reboot:
apt install iptables-persistent -y;
reset_iptables () {
iptables -F;
iptables -X;
iptables -t nat -F;
iptables -t nat -X;
iptables -t mangle -F;
iptables -t mangle -X;
iptables -t raw -F;
iptables -t raw -X;
iptables -t security -F;
iptables -t security -X;
iptables -P INPUT ACCEPT;
iptables -P FORWARD ACCEPT;
iptables -P OUTPUT ACCEPT;
}
forward_internet () {
CLIENT_NET=$1;
INET_IFACE=$2;
iptables -t nat -A POSTROUTING -o $INET_IFACE -j MASQUERADE;
iptables -I FORWARD -o $INET_IFACE -s $CLIENT_NET -j ACCEPT;
iptables -I INPUT -s $CLIENT_NET -j ACCEPT;
}
forward_port () {
OUTSIDE_INTERFACE=$1;
OUTSIDE_PORT=$2;
INSIDE_ADDRESS=$3;
INSIDE_PORT=$4;
sysctl net.ipv4.conf.all.forwarding=1 > /dev/null;
sysctl net.ipv6.conf.all.forwarding=1 > /dev/null;
iptables -A PREROUTING -t nat -p tcp -i $OUTSIDE_INTERFACE --dport $OUTSIDE_PORT -j DNAT --to-destination $INSIDE_ADDRESS:$INSIDE_PORT;
iptables -A POSTROUTING -t nat -p tcp -d $INSIDE_ADDRESS --dport $INSIDE_PORT -j MASQUERADE;
echo "$OUTSIDE_INTERFACE:$OUTSIDE_PORT -> $INSIDE_ADDRESS:$INSIDE_PORT";
}
reset_iptables;
# The rules:
forward_internet 10.0.0.1/24 vmbr0;
forward_port vmbr0 22100 10.0.0.100 22;
forward_port vmbr0 443 10.0.0.100 443;
forward_port vmbr0 44300 10.0.0.100 44300;
forward_port vmbr0 44301 10.0.0.100 44301;
forward_port vmbr0 44302 10.0.0.100 44302;
forward_port vmbr0 44303 10.0.0.100 44303;
forward_port vmbr0 44304 10.0.0.100 44304;
forward_port vmbr0 44305 10.0.0.100 44305;
forward_port vmbr0 44310 10.0.0.100 44310;
# Save the rules:
iptables-save > /etc/iptables/rules.v4;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment