NAT Script

From SlackWiki
Jump to navigation Jump to search
#!/bin/sh

# This is a very basic LAN NAT script, allowing only SSH to the firewall from
# the external interface, allowing all outbound LAN traffic, and allowing only
# established/related traffic back into the LAN.

ipt=/usr/sbin/iptables
extip=192.168.1.41 # replace with your EXTERNAL IP - eth0
lan=10.5.3.0/25 # your LAN CIDR range - eth1

# start firewall
start_firewall() {

  echo "Enabling IP forwarding."
  echo 1 > /proc/sys/net/ipv4/ip_forward

  echo "Enabling iptables firewall."
  # default policies
  $ipt -P INPUT DROP
  $ipt -P FORWARD DROP

  # NAT
  $ipt -t nat -A POSTROUTING -o eth0 -j SNAT --to-source $extip

  # INPUT chain
  $ipt -A INPUT -i lo -j ACCEPT
  $ipt -A INPUT -i eth1 -s $lan -j ACCEPT
  $ipt -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
  $ipt -A INPUT -p tcp --destination-port 22 -j ACCEPT

  # FORWARD chain
  $ipt -A FORWARD -i eth1 -s $lan -j ACCEPT
  $ipt -A FORWARD -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

}

# stop firewall
stop_firewall() {

  $ipt -P INPUT DROP
  $ipt -P OUTPUT DROP
  $ipt -P FORWARD DROP
  # allow internal traffic
  $ipt -A INPUT -i eth1 -j ACCEPT
  $ipt -A OUTPUT -o eth1 -j ACCEPT

}

# flushing, removing and zeroing tables
reset_firewall() {

  chains=`cat /proc/net/ip_tables_names`
  for i in $chains; do
    $debug $ipt -t $i -F
    $debug $ipt -t $i -X
    $debug $ipt -t $i -Z
  done

}

case "$1" in

  start|restart|reload)
    reset_firewall
    start_firewall
    ;;
  stop)
    reset_firewall
    stop_firewall
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|reload}"
    exit 1
    ;;

esac