Created
July 9, 2020 02:36
-
-
Save MxBlu/bde70ae4f7295e5462366596ead0f1b0 to your computer and use it in GitHub Desktop.
Set up port forwarding inside Linux, primarily made for use for a server with a Wireguard connection to a backend on a dynamic IP or something of the like.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -x | |
ACTION=$1 | |
PRIV_IFACE=$2 | |
# IP of private interface | |
# PostDown obviously doesn't get the IP, which means unportforward won't work... hardcoding | |
# INTERFACE_IP=$(/sbin/ifconfig $INTERFACE | grep -i mask | awk '{print $2}'| cut -f2 -d:) | |
PRIV_IFACE_IP=10.0.4.1 | |
# Name of public interface | |
PUBL_IFACE=eth0 | |
portforward () { | |
local FPORT=$1 | |
local FDEST=$2 | |
# Explicitly allow forwarding port $FPORT | |
iptables -A FORWARD -i $PUBL_IFACE -o $PRIV_IFACE -p tcp --syn --dport $FPORT -m conntrack --ctstate NEW -j ACCEPT | |
# Forward port $FPORT to $FDEST via NAT | |
iptables -t nat -A PREROUTING -p tcp --dport $FPORT -j DNAT --to-destination $FDEST | |
iptables -t nat -A POSTROUTING -d $FDEST -o $PRIV_IFACE -p tcp --dport $FPORT -j SNAT --to-source $PRIV_IFACE_IP | |
} | |
unportforward() { | |
local FPORT=$1 | |
local FDEST=$2 | |
# Remove forwarding and NAT rules for $INTERFACE and $FPORT to $FDEST | |
iptables -D FORWARD -i $PUBL_IFACE -o $PRIV_IFACE -p tcp --syn --dport $FPORT -m conntrack --ctstate NEW -j ACCEPT | |
iptables -t nat -D PREROUTING -p tcp --dport $FPORT -j DNAT --to-destination $FDEST | |
iptables -t nat -D POSTROUTING -d $FDEST -o $PRIV_IFACE -p tcp --dport $FPORT -j SNAT --to-source $PRIV_IFACE_IP | |
} | |
if [ $ACTION = "up" ]; then | |
# iptables config on | |
# Allow packet forwarding from $INTERFACE | |
iptables -A FORWARD -i $PRIV_IFACE -j ACCEPT | |
# Forward port 5000 from $PUBL_IFACE to 10.0.4.2:5000 | |
# portforward 5000 10.0.4.2 | |
# Allow NAT routing | |
iptables -t nat -A POSTROUTING -j MASQUERADE | |
else | |
# iptables config off | |
# Revert config on | |
iptables -D FORWARD -i $PRIV_IFACE -j ACCEPT | |
# unportforward 5000 10.0.4.2 | |
iptables -t nat -D POSTROUTING -j MASQUERADE | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment