#!/bin/bash

# ID: rc.fw.wlan-gw Sun Dec  3 13:07:18 EST 2006 ground/X
# Based on:
# ID: rc.tables-2 Sat May 24 01:08:36 EST 2003 ground/X

# Second generation masq firewall.
# Including stateful masq forwarding support.
# written fresh for iptables
# This is used as a masq gateway to open/cracked wifi networks.
# It should allow you to use this machine as a gateway while hiding the machine
# itself and protecting the internal network.

bin="iptables"
wlan_iface='eth1'
lan_iface='eth0'
int_subnet='192.168.0.0/16'
 
# Flush old rules.
$bin -F
$bin -X
$bin -t nat -F
$bin -t nat -X
# Reset packet counters
$bin -Z
# Set default policy
$bin -P INPUT ACCEPT
$bin -P OUTPUT ACCEPT
$bin -P FORWARD DROP

# NAT table
# default line to mask
$bin -t nat -A POSTROUTING -s $int_subnet -d ! $int_subnet \
-o $wlan_iface -j MASQUERADE

 # filtering table-input
# drop icmp redirect
$bin -A INPUT -i $wlan_iface -p icmp --icmp-type 5 -j DROP
# drop icmp echo request
$bin -A INPUT -i $wlan_iface -p icmp --icmp-type 8 -j LOG \
--log-prefix drop_icmp_echo_$wlan_iface_ -m limit --limit 3m
$bin -A INPUT -i $wlan_iface -p icmp --icmp-type 8 -j DROP

# drop all tcp syn packets.
$bin -A INPUT -p tcp -i $wlan_iface --syn -j LOG \
--log-prefix drop_external_syn_ -m limit --limit 3m
$bin -A INPUT -p tcp -i $wlan_iface --syn -j DROP

# drop incoming using the stateful firewall.
$bin -A INPUT -i $wlan_iface -m state --state ESTABLISHED -j ACCEPT
$bin -A INPUT -i $wlan_iface -j DROP

# Filtering table-forwarding
# no internal addresses from the big bad world at all.
$bin -A FORWARD -i $wlan_iface -s $int_subnet -j LOG \
--log-prefix drop_prvaddr_$wlan_iface_ -m limit --limit 3m
$bin -A FORWARD -i $wlan_iface -s $int_subnet -j DROP
# no intra network routing here.
$bin -A FORWARD -s $int_subnet -d $int_subnet -j LOG \
--log-prefix drop_intra_route_ -m limit --limit 3m
$bin -A FORWARD -s $int_subnet -d $int_subnet -j DROP

# Allow forward of masked traffic.
# note a simple masquerade is not enough since we set are fwd policy to drop
$bin -A FORWARD -i $lan_iface -o $wlan_iface \
-s $int_subnet -d ! $int_subnet -j ACCEPT
$bin -A FORWARD -i $wlan_iface -o $lan_iface \
-m state --state ESTABLISHED \
-s ! $int_subnet -d $int_subnet -j ACCEPT

$bin -A FORWARD -j LOG

# Ending setup.
# enable forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# No broadcast storms pls..
echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
# This helps against IP spoofing.
echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
