CentOS Firewall Init Script
I wrote a simple chkconfig compatible firewall init script for CentOS/RedHat/Fedora based Linux systems. It is based on the Quick n’ Dirty script from vpslink’s wiki.
It will setup iptables firewall rules allowing anyone to access user defined ports (22,80 by default). It also has the ability to whitelist and blacklist IP’s. I’ve tested it with chkconfig on CentOS 5.
To use it:
- Create a file named /etc/init.d/firewall
- Copy and paste the script into it and save
- Edit the ALLOWED variable with port numbers you want to allow, default is ports 22 (SSH) and 80 (HTTP)
- Execute:
touch /usr/local/etc/whitelist.txt && touch /usr/local/etc/blacklist.txt
- Edit the whitelist/blacklist files if you want
- Execute:
chmod 755 /etc/init.d/firewall
- Execute:
chkconfig --add firewall && chkconfig firewall on
The script:
#!/bin/bash
# chkconfig: 345 30 99
# description: Starts and stops iptables based firewall
## List Locations
#
WHITELIST=/usr/local/etc/whitelist.txt
BLACKLIST=/usr/local/etc/blacklist.txt
#
## Specify ports you wish to use.
#
ALLOWED="22 80"
#
## Specify where IP Tables is located
#
IPTABLES=/sbin/iptables
##
#DO NOT EDIT BELOW THIS LINE
###
RETVAL=0
# To start the firewall
start() {
echo "Setting up firewall rules..."
echo 'Allowing Localhost'
#Allow localhost.
$IPTABLES -A INPUT -t filter -s 127.0.0.1 -j ACCEPT
#
## Whitelist
#
for x in `grep -v ^# $WHITELIST | awk '{print $1}'`; do
echo "Permitting $x..."
$IPTABLES -A INPUT -t filter -s $x -j ACCEPT
done
#
## Blacklist
#
for x in `grep -v ^# $BLACKLIST | awk '{print $1}'`; do
echo "Denying $x..."
$IPTABLES -A INPUT -t filter -s $x -j DROP
done
#
## Permitted Ports
#
for port in $ALLOWED; do
echo "Accepting port TCP $port..."
$IPTABLES -A INPUT -t filter -p tcp --dport $port -j ACCEPT
done
for port in $ALLOWED; do
echo "Accepting port UDP $port..."
$IPTABLES -A INPUT -t filter -p udp --dport $port -j ACCEPT
done
$IPTABLES -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
$IPTABLES -A INPUT -p udp -j DROP
$IPTABLES -A INPUT -p tcp --syn -j DROP
RETVAL=0
}
# To stop the firewall
stop() {
echo "Removing all iptables rules..."
/sbin/iptables -F
/sbin/iptables -X
/sbin/iptables -Z
RETVAL=0
}
case $1 in
start)
stop
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
/sbin/iptables -L
/sbin/iptables -t nat -L
RETVAL=0
;;
*)
echo "Usage: firewall {start|stop|restart|status}"
RETVAL=1
esac
exit $RETVAL
March 8th, 2008 at 12:27 pm
Thanks !
This is a great solution for me.
June 22nd, 2008 at 5:40 pm
Very good script. Is there anyway to apply an ip range or subnet in the whitelist? It would be very helpful!