18 September 2012

Secure SSH: SshGuard init script for CentOS

I've tried to find good init script for SshGuard daemon for CentOS 6.3, but mainly found scripts this:
http://www.sshguard.net/docs/faqs/#sshguard-start-at-boot

I've tried to improve script by adding different checks like existance of process, separated configuration with list of log files to be listened and white-listed IPs as it's usually done in init scripts in CentOS/RHEL.

Script itself (/etc/init.d/sshguard):
#!/bin/bash
#
# sshguard      Start up the sshguard daemon
#
# chkconfig:    2345 56 24
# description:  SshGuard daemon
#
# processname:  sshguard
# pidfile: /var/run/sshguard.pid

# source function library
. /etc/rc.d/init.d/functions

# pull in sysconfig settings
[ -f /etc/sysconfig/sshguard ] && . /etc/sysconfig/sshguard


RETVAL=0

exec=/usr/local/sbin/sshguard
prog=sshguard
lockfile=/var/lock/subsys/$prog
pidfile=/var/run/$prog.pid
args="$(for LOG in "${SSHGUARD_LISTEN_LOGS[@]}"; do echo -l $LOG; done) $(for IP in "${SSHGUARD_WHITELIST[@]}"; do echo -w $IP; done) $SSHGUARD_OPTIONS"

start()
{
    echo -n $"Starting $prog: "
    [ -x $exec ] || {
        failure $"$base startup"
        echo
        echo "Cannot find executable: $exec" >&2
        exit 5
    }

    [ -r ${pidfile} ] && {
        pid=$(cat ${pidfile})
        checkpid $pid && {
            failure $"$base startup"
            echo
            echo "sshguard already started: PID=$pid" >&2
            exit -1
        }
    }

    $exec $args &>/dev/null &
    echo $! > ${pidfile}
    success $"$base startup"
    echo 
    return 0
}

stop()
{
    echo -n $"Stopping $prog: "
    killproc -p ${pidfile} $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status -p ${pidfile} ${prog}
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|status}"
        RETVAL=2
esac
exit $RETVAL

Configuration file (/etc/sysconfig/sshguard):
# list of white listed IPs (bash array)
SSHGUARD_WHITELIST=( 94.10.107.15 144.113.0.156 )
# list of listened log files (bash array)
SSHGUARD_LISTEN_LOGS=( /var/log/secure )
# additional command line options (string)
SSHGUARD_OPTIONS=

Download scripts as tar.bz2 archive →

In order to use this script you have to:
  1. Put the script by path /etc/init.d/sshguard
  2. Change owner and group to root:
    sudo chown root:root /etc/init.d/sshguard
  3. Make it executable:
    sudo chmod +x /etc/init.d/sshguard
  4. Add to startup configuration:
    sudo chkconfig --add sshguard 
  5. Add configuration file by path /etc/sysconfig/sshguard (see example above)
  6. Start sshguard:
    sudo service sshguard start
    (or restart|stop|status)

No comments:

Post a Comment

Profile