#!/bin/sh
# /etc/init.d/dropbear : Start, stop and restart SSH server on SliTaz, at
# boot time or with the command line.
#
# To start SSH server at boot time, just put dropbear in the $RUN_DAEMONS
# variable of /etc/rcS.conf and configure options with /etc/daemons.conf
#
. /etc/init.d/rc.functions
. /etc/daemons.conf

NAME=Dropbear
DESC="$(_ '%s server' SSH)"
DAEMON=/usr/sbin/dropbear
OPTIONS=$DROPBEAR_OPTIONS
PIDFILE=/var/run/dropbear.pid

case "$1" in
  start)
    # We need rsa and dss host key file to start dropbear.
    for type in rsa dss ecdsa ed25519 ; do
	[ -s /etc/dropbear/dropbear_${type}_host_key ] && continue
	action 'Generating Dropbear %s key... ' $type
	# Need to delete key before creating it.
	rm -f /etc/dropbear/dropbear_${type}_host_key
	dropbearkey -t $type -f /etc/dropbear/dropbear_${type}_host_key >/dev/null 2>&1
	status
    done
    if active_pidfile $PIDFILE dropbear ; then
      _ '%s is already running.' $NAME
      exit 1
    fi
    if [ -n "$(which iptables)" ] && ! iptables -L | grep 'tcp dpt:ssh ' ; then
    	tcp22new='iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent'
	$tcp22new --set --name DEFAULT --rsource
	limit='--seconds 300 --hitcount 5 --name DEFAULT --rsource'
	$tcp22new --update $limit -j LOG --log-prefix "SSH-Bruteforce : "
	$tcp22new --update $limit -j DROP
    fi
    action 'Starting %s: %s...' "$DESC" $NAME
    $DAEMON $OPTIONS
    status
    ;;
  stop)
    if ! active_pidfile $PIDFILE dropbear ; then
      _ '%s is not running.' $NAME
      exit 1
    fi
    action 'Stopping %s: %s...' "$DESC" $NAME
    kill $(cat $PIDFILE)
    status
    ;;
  restart)
    if ! active_pidfile $PIDFILE dropbear ; then
      _ '%s is not running.' $NAME
      exit 1
    fi
    action 'Restarting %s: %s...' "$DESC" $NAME
    kill $(cat $PIDFILE)
    sleep 2
    $DAEMON $OPTIONS
    status
    ;;
  *)
    emsg "<n><b>$(_ 'Usage:')</b> $0 [start|stop|restart]"
    newline
    exit 1
    ;;
esac

exit 0
