Home > Linux / Unix, Security, Tutorial > CentOS Firewall Init Script

CentOS Firewall Init Script

I wrote a simple chkconfig compatible firewall init script for CentOS/RedHat/Fedora based Linux systems.

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:

  1. Create a file named /etc/init.d/firewall
  2. Copy and paste the script into it and save
  3. Edit the ALLOWED variable with port numbers you want to allow, default is ports 22 (SSH) and 80 (HTTP)
  4. Execute:
  5. touch /usr/local/etc/whitelist.txt && touch /usr/local/etc/blacklist.txt
  6. Edit the whitelist/blacklist files if you want
  7. Execute:
  8. chmod 755 /etc/init.d/firewall
  9. Execute:
  10. 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
  1. June 19, 2012 at 3:20 pm

    you posted this in 2010, and zero comments?! nice. that tells me, zero bugs. this is awesome and is exactly what i was looking for… thank you much!

  2. August 18, 2014 at 6:56 pm

    Visit my website! Thanks

  1. February 18, 2012 at 11:03 am

Leave a comment