Public domain
#!/bin/bash
# Configuration
INTIF="eth1"
DHCPDCONF="/etc/dhcpd.conf"
TMP="/tmp/firewall.sh"
FW="/etc/rc.d/rc.firewall"
# Making new firewall
echo "#!/bin/bash" > "${TMP}"
echo "echo 'Starting Firewall : ${FW}'" >> "${TMP}"
echo "# Flush Previous rules" >> "${TMP}"
echo "iptables -F FORWARD" >> "${TMP}"
cat "${DHCPDCONF}" | while read line; do
if $(echo "$line" | grep -q 'host') && $(echo "$line" | grep -q '{'); then
HOST=$(echo $line | sed -e 's,.*host *,,' -e 's, *{.*,,')
fi
if $(echo "$line" | grep -q 'hardware ethernet'); then
MAC=$(echo $line | sed -e 's,.*hardware ethernet *,,' -e 's,;.*,,')
fi
if $(echo "$line" | grep -q 'fixed-address'); then
IP=$(echo $line | sed -e 's,.*fixed-address *,,' -e 's,;.*,,')
fi
if [ "$HOST" != "" ] && [ "$MAC" != "" ] && [ "$IP" != "" ]; then
echo "# $HOST $MAC $IP" >> "${TMP}"
echo "iptables -A FORWARD -i $INTIF -s $IP -m mac --mac-source $MAC -j ACCEPT -m comment --comment '$HOST'" >> "${TMP}"
HOST=""
MAC=""
IP=""
fi
done
echo "# Change default policy" >> "${TMP}"
echo "iptables -A FORWARD -i $INTIF -j LOG --log-prefix 'Firewall: ' -m comment --comment 'Log everything else'" >> "${TMP}"
echo "iptables -A FORWARD -i $INTIF -j DROP -m comment --comment 'Drop everything else'" >> "${TMP}"
# Exit if previous and current firewalls are the same
if [ -e "${FW}" ] && diff "${FW}" "${TMP}" &> /dev/null; then
exit
fi
# Run new firewall if thay are different
cp "${TMP}" "${FW}"
chmod +x "${FW}"
"${FW}"
ddns-update-style none;
subnet 192.168.0.0 netmask 255.255.255.0 {
option routers 192.168.0.1;
option subnet-mask 255.255.255.0;
option domain-name-servers 8.8.8.8, 8.8.4.4;
default-lease-time 60;
max-lease-time 600;
host sysop {
hardware ethernet 6c:f0:49:45:e9:ba;
fixed-address 192.168.0.11;
}
host station01 {
hardware ethernet 00:11:2f:4b:63:1b;
fixed-address 192.168.0.12;
}
host station02 {
hardware ethernet 00:14:85:ee:92:3a;
fixed-address 192.168.0.13;
}
host station03 {
hardware ethernet 1c:af:f7:10:56:8b;
fixed-address 192.168.0.14;
}
}
BY: Pejman Moghadam
TAG: firewall, iptables, dhcpd, bash-script, bash
DATE: 2011-07-30 00:38:01