Skip to content

Instantly share code, notes, and snippets.

@rukh-debug
Created May 26, 2024 15:16
Show Gist options
  • Save rukh-debug/025b6b2f4bfd5c083c3bb14e01678e76 to your computer and use it in GitHub Desktop.
Save rukh-debug/025b6b2f4bfd5c083c3bb14e01678e76 to your computer and use it in GitHub Desktop.
Forwarding incoming request coming on X interface to Y interface for list of ports at once.
#!/bin/bash
# Define the destination IP
DEST_IP="100.124.186.54" # Replace it with your tailscale / Wireguard ip of the destination server
# Define the network interfaces
INTERFACE_IN="eth0"
INTERFACE_OUT="tailscale0" # Replace with your interfce name of tailscale / wireguard interface name.
# Define the ports
PORTS=(80 443)
# Loop over the ports and apply iptables rules
for PORT in "${PORTS[@]}"; do
# Allow incoming traffic on the specified port
iptables -A INPUT -p tcp --dport $PORT -j ACCEPT
# Forward traffic between interfaces for the specified port
iptables -A FORWARD -i $INTERFACE_IN -o $INTERFACE_OUT -p tcp --dport $PORT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i $INTERFACE_OUT -o $INTERFACE_IN -p tcp --sport $PORT -m conntrack --ctstate ESTABLISHED -j ACCEPT
# PREROUTING rule for the specified port
iptables -t nat -A PREROUTING -i $INTERFACE_IN -p tcp --dport $PORT -j DNAT --to-destination $DEST_IP
# POSTROUTING rule for the specified port
iptables -t nat -A POSTROUTING -o $INTERFACE_IN -p tcp --dport $PORT -j MASQUERADE
done
echo "iptables rules have been successfully added for ports: ${PORTS[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment