Wednesday, April 9, 2008

Fischer Price "My First FireWall"

We had an assignment in class this week to write our own personal firewall for a personal PC. We had to use variables and have a least a few outside services running. I thought I may as a well post it here since by default Backtrack does not have a firewall or even IPtables running when it starts up. In the past I'll be honest I've always cheated with a GUI firewall program like Guard Dog or Firestarter but now I am slowly learning to write one from scratch. If you would like to use it just copy and paste it in a file called firewall.sh. Give it exec permissions and start it with ./firewall.sh and stop it with ./firewall.sh stop. Special thanks to linuxchuck for his help with iptable'fu.

#!/bin/bash
#Fischer Price "My First Firewall"
#define variables
SERVICES="ftp ssh"
INT=""
EXT="eth0"
if [ "$1" = "start" ]
then
echo "Starting firewall..."
# Flush all existing chains and erase personal chains
CHAINS=$(cat /proc/net/ip_tables_names 2>/dev/null)
for i in $CHAINS;
do
$IPT -t $i -F
done
for i in $CHAINS;
do
$IPT -t $i -X
done
echo 1 > /proc/sys/net/ipv4/tcp_syncookies
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
#creating rules
iptables -P INPUT REJECT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -P OUTPUT ACCEPT
#enable services
for x in ${SERVICES}
do
iptables -A INPUT -p tcp --dport ${x} -m state --state NEW -j ACCEPT
done

iptables -A INPUT -p udp -i ${EXT}-j REJECT --reject-with icmp-port-unreachable
#hide our firewall
iptables -A INPUT -p tcp -i ${EXT}-j REJECT --reject-with tcp-reset
iptables -A INPUT -p udp -i ${EXT} -j REJECT --reject-with icmp-port-unreachable

# disable ECN
if [ -e /proc/sys/net/ipv4/tcp_ecn ]
then
echo 0 > /proc/sys/net/ipv4/tcp_ecn
fi

#disable spoofing on all interfaces
for x in ${INT} ${EXT}
do
echo 1 > /proc/sys/net/ipv4/conf/${x}/rp_filter
done

echo 1 > /proc/sys/net/ipv4/ip_forward
#ping rules
PERMIT_ICMP="destination-unreachable echo-reply time-exceeded"
for i in ${PERMIT_ICMP}
do
iptables -A INPUT -p icmp --icmp-type ${i} -j ACCEPT
done
elif [ "$1" = "stop" ]
then
echo "Stopping firewall..."
iptables -F INPUT
iptables -P INPUT ACCEPT
fi