Linux IPTables double NAT, SNAT / DNAT, portforwarding without default gateway

#!/bin/bash

# eth1 – inet – 195.184.117.131

# We asume that eth0 is on a private RFC1918 lan on which we are connected to as an ordinary client.
# we also asume that eth1 is connected to the internet with a public routable ip adress.
# This script will then setup, so called, double nat (proxying) to allow people on the internet to access
# systems on the inside by connection to eth1_ip and get forwardet to target_ip on the inside
# according to portnumbers as specified in the ports array down below.

eth0_ip=`ifconfig eth0 | head -n2 | tail -n1 | cut -d : -f 2 | cut -d \ -f 1`
eth1_ip=`ifconfig eth1 | head -n2 | tail -n1 | cut -d : -f 2 | cut -d \ -f 1`

# This is the ip on the inside that all requests will be directed to (sorry the scripts does not currently
# allow for multiple inside ip’s … if you need this you need to uncomment the “iptables -t nat -F line
# and run mutilple copies of the script)

target_ip=192.168.0.101

# Port 8080 on the public side will be forwardet to 80 on the internal side
ports=( 8080:80 20:20 30:30 )

# This should be removed if you want this to work with other rules / an existing script
iptables -t nat -F

# This loops through the ports array
for port in ${ports[@]}
do
# This splits the ports array

public_port=`echo $port | cut -d : -f 1`
private_port=`echo $port | cut -d : -f 2`

# … and apply the rules

iptables -t nat -A PREROUTING -i eth1 -p tcp -d $eth1_ip –dport $public_port -j DNAT –to-destination $target_ip:$private_port
iptables -t nat -A POSTROUTING -o eth0 -j SNAT –to-source $eth0_ip

done

Dette indlæg blev udgivet i Knowledge Base, Linux, Networking, Old Base. Bogmærk permalinket.

Skriv et svar