#!/bin/bash

# sample script for secure NAT setups
# Angulo Solido - http://www.angulosolido.pt

# clear all iptables rules

service iptables stop

#usually ppp0 for DSL, $INTIF or eth1 for cable or lan
EXTIF=ppp0
#usually the remaining ethernet interface
INTIF=eth0

# default policies: DROP everything but OUTPUT

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# accept everything from the loopback device

iptables -t filter -A INPUT -i lo -j ACCEPT

# open specific services

# ICMP

#iptables -t filter -A INPUT -p icmp -m icmp  -j ACCEPT

# enable ssh on all interfaces

iptables -t filter -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

#enable DNS on $INTIF

iptables -A INPUT -i $INTIF -p udp -m udp --dport 53 -j ACCEPT

# enable samba services on $INTIF

iptables -A INPUT -i $INTIF -p udp -m udp --dport 137 -j ACCEPT
iptables -A INPUT -i $INTIF -p udp -m udp --dport 138 -j ACCEPT
iptables -A INPUT -i $INTIF -p tcp -m tcp --dport 139 -j ACCEPT
iptables -A INPUT -i $INTIF -p tcp -m tcp --dport 445 -j ACCEPT

#enable cups on $INTIF

iptables -A INPUT -i $INTIF -p tcp -m tcp --dport 631 -j ACCEPT
iptables -A INPUT -i $INTIF -p udp -m udp --dport 631 -j ACCEPT

## accept connections which are ESTABLISHED or RELATED to the outgoing connections
## usually we don't need this rule for INPUT in a server
## RELATED is related to ip_conntrack and associated modules

#iptables -t filter -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT


# accept traffic related to ESTABLISHED connections

iptables -t filter -A INPUT -m state --state ESTABLISHED -j ACCEPT

# allow specific traffic to be forwarded (example)

# HTTPS=443

# iptables -t filter -A FORWARD -i $INTIF -o $EXTIF  -p tcp -m tcp --dport $HTTPS -j ACCEPT

# allow ftp connections to a specific IP (for clients that support passive ftp only!)

#IP=xx.xxx.xxx.xx

#iptables -t filter -A FORWARD -i $INTIF -o $EXTIF  -d $IP -p tcp -m tcp --dport 1024:65535 -j ACCEPT
#iptables -t filter -A FORWARD -i $INTIF -o $EXTIF  -d $IP -p tcp -m tcp --dport 21 -j ACCEPT

# transparent proxy to squid

#iptables -t nat -A PREROUTING -i $INTIF -p tcp --dport 80 -j REDIRECT --to-port 3128

# the nat stuff goes here

iptables -t filter -A FORWARD -i $EXTIF -o $INTIF -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -t filter -A FORWARD -i $INTIF -o $EXTIF -j ACCEPT
iptables -t nat -A POSTROUTING -o $EXTIF -j MASQUERADE

# forward specific ports to an internal machine

#DEST=192.168.1.13
#DPORT=4667
#DPROTO=tcp

#iptables -t nat -A PREROUTING -i $EXTIF -p $DPROTO -m $DPROTO --dport $DPORT -j DNAT --to-destination $DEST
#iptables -t filter -A FORWARD -d $DEST -i $EXTIF -p $DPROTO -m $DPROTO --dport $DPORT -j ACCEPT


# save the iptables rules

iptables-save >/etc/sysconfig/iptables

# this must be enabled on every boot, on /etc/sysctl.conf

echo "1" > /proc/sys/net/ipv4/ip_forward


