#!/bin/bash
#
# $Id$
#
# /etc/init.d/sfw
#
# starts/stops/statuses sfw, IBCL's Simple FireWall
#
#
# hints for update-rc.d on Debian like distros and chkconfig on SuSE like distros
#
### BEGIN INIT INFO
# Provides:          sfw
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $network iptables ipmasq arno-iptables-firewall iptables-persistent ferm fail2ban
# Should-Stop:       $network iptables ipmasq arno-iptables-firewall iptables-persistent ferm fail2ban
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start or stop the Simple FireWall sfw.
# Description:       Start or stop the Simple FireWall sfw.
### END INIT INFO
#
#
# hints for chkconfig on RedHat like distros
#
# chkconfig: 345 90 10
# description: Start or stop the Simple FireWall sfw.
# processname: 
#

# Defaults

START_SFW="no"
BLACKLISTED_HOSTS=""
ALLOWED_TCPPORTS=""
ALLOWED_UDPPORTS=""
SWALLOWED_TCPPORTS=""
SWALLOWED_UDPPORTS=""
PING_LIMIT="5/s"
LOG_LIMIT="1/s"
LOG_DROPS="no"
VERBOSITY=0
SFW_LOG="/var/log/sfw.log"

SFWCONF="/etc/sfw/sfw.conf"

. /usr/lib/sfw/parse_sfw_conf.sh

if [ -z "$VERBOSITY" ] ; then
  VERBOSITY=0
fi

if [ "$2" = "-v" ] ; then
  VERBOSITY=$((VERBOSITY + 1))
fi

export IPTOPTIONS=" -w "
if [ -f /etc/debian_version ] ; then
  OLDDEB=$(egrep "^[2-7]" /etc/debian_version)
  if [ -n "$OLDDEB" ] ; then
    echo "Detected old debian without support for -w, clearing IPTOPTIONS and sleeping a bit"
    IPTOPTIONS=""
    sleep 3
  fi
fi
#echo "DEBUG: IPTOPTIONS=${IPTOPTIONS}"

case "$1" in

  start)
    echo "Starting SFW (Simple FireWall)."

    test -f ${SFW_LOG} && mv ${SFW_LOG} ${SFW_LOG}.former
    echo "Starting SFW (Simple FireWall)." >${SFW_LOG}

    DO_START_SFW=$(echo "$START_SFW" |egrep -i '^(yes|true)$')
    if [ -z "$DO_START_SFW" ] ; then
      echo "WARNING: START_SFW set to '$START_SFW' rather than yes or true, quitting." |tee -a ${SFW_LOG}
      exit 0
    fi

    #echo "1" > /proc/sys/net/ipv4/ip_forward

    if [ $VERBOSITY -gt 1 ] ; then
      echo "" >> ${SFW_LOG}
      echo "iptables before ..." >> ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -L -n 2>&1 >> ${SFW_LOG}
      echo "" >> ${SFW_LOG}
      echo "iptables -t nat before ..." >> ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -t nat -L -n 2>&1 >> ${SFW_LOG}
      echo "" >> ${SFW_LOG}
    fi

    #echo "Sleeping a bit" |tee -a ${SFW_LOG}
    #sleep 1 2>&1 |tee -a ${SFW_LOG}

    # - clear existing tables
    SFWININPUT=$(/sbin/iptables ${IPTOPTIONS} -L INPUT -n 2>/dev/null |egrep "^sfw ")
    if [ -n "$SFWININPUT" ] ; then
      /sbin/iptables ${IPTOPTIONS} -D INPUT -j sfw 2>&1 |tee -a ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -F sfw 2>&1 |tee -a ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -X sfw 2>&1 |tee -a ${SFW_LOG}
    fi

    # create my rule
    /sbin/iptables ${IPTOPTIONS} -N sfw 2>&1 |tee -a ${SFW_LOG}
    /sbin/iptables ${IPTOPTIONS} -A INPUT -j sfw 2>&1 |tee -a ${SFW_LOG}

    # check if we are allowed to load modules
    LOADEDMODULES=$(cat /proc/modules 2>/dev/null |grep -iv "Modules")
    NRMODULES=$(( $(echo "$LOADEDMODULES" |wc -l |tr -d ' ') - 1 ))
    test -z $NRMODULES && NRMODULES="0"
    if [ $NRMODULES -gt 0 ] ; then
      test $VERBOSITY -gt 0 && echo "$NRMODULES modules loaded, runnig module checks." |tee -a ${SFW_LOG}
      # module xt_state (formerly named ipt_state)
      if echo "$LOADEDMODULES" |egrep "ipt_state|xt_state" >/dev/null ; then
        test $VERBOSITY -gt 0 && echo "xt_state module already loaded." |tee -a ${SFW_LOG}
      else
        test $VERBOSITY -gt 0 && echo "xt_state module not loaded, calling modprobe." |tee -a ${SFW_LOG}
        modprobe xt_state 2>&1 |tee -a ${SFW_LOG}
      fi
      # the future might see a configurable list of modules to check for
      #if echo "$LOADEDMODULES" |egrep "gibtsnet" >/dev/null ; then
      #  test $VERBOSITY -gt 0 && echo "gibtsnet module already loaded."
      #else
      #  test $VERBOSITY -gt 0 && echo "gibtsnet module not loaded, calling modprobe."
      #  modprobe gibtsnet
      #fi
    else
      test $VERBOSITY -gt 0 && echo "No modules loaded, probably running in container. Skipping module checks." |tee -a ${SFW_LOG}
    fi
    # due to the large number of kernel level container technologies neither the lack of /proc/modules content
    # nor the inability to modprobe a module really proof a module problem.
    # therefore we leave failure and exiting to the -A statements below and in called scripts

    # - allowed_input

    # Protect against CVE-2019-11477, SACK panic
    # https://security-tracker.debian.org/tracker/CVE-2019-11477
    # based on sugguestion by Richard Weinberger workaround
    SACKON=$(cat /proc/sys/net/ipv4/tcp_sack |grep 1)
    if [ -n "$SACKON" ] ; then
      test $VERBOSITY -gt 0 && echo "Stripping SACK stuff to protect against CVE-2019-11477"
      /sbin/iptables -t mangle -A INPUT   -i !lo -p tcp -j TCPOPTSTRIP --strip-options sack-permitted,sack
      /sbin/iptables -t mangle -A FORWARD -i !lo -p tcp -j TCPOPTSTRIP --strip-options sack-permitted,sack
    else
      test $VERBOSITY -gt 0 && echo "SACK turned off anyway, no need to strip SACK stuff to protect against CVE-2019-11477"
    fi 

    # DROP configured BLACKLISTED_HOSTS
    if [ -n "$BLACKLISTED_HOSTS" ] ; then
      for HOST in $BLACKLISTED_HOSTS ; do
        test $VERBOSITY -gt 0 && echo "Adding DROP for blacklisted Host/Network $HOST" |tee -a ${SFW_LOG}
        /sbin/iptables ${IPTOPTIONS} -A sfw -s $HOST -j DROP 2>&1 |tee -a ${SFW_LOG}
        PRC=${PIPESTATUS[0]}
        if [ "${PRC}" != "0" ] ; then
          echo "ERROR: Failed to add DROP for blacklisted Host/Network $HOST" |tee -a ${SFW_LOG}
          exit 11
        fi
      done
    fi

    # SPECIAL_RULES
    if [ -x "/etc/sfw/special_rules.sh" ] ; then
      test $VERBOSITY -gt 0 && echo "Calling /etc/sfw/special_rules.sh" |tee -a ${SFW_LOG}
      /etc/sfw/special_rules.sh $* 2>&1 |tee -a ${SFW_LOG}
      PRC=${PIPESTATUS[0]}
      if [ "${PRC}" != "0" ] ; then
        echo "ERROR: Failed to execute /etc/sfw/special_rules.sh" |tee -a ${SFW_LOG}
        exit 20
      fi
    else
      test $VERBOSITY -gt 0 && echo "No executable /etc/sfw/special_rules.sh to call." |tee -a ${SFW_LOG}
    fi

    # ACCEPT existing connections
    test $VERBOSITY -gt 0 && echo "Addding ACCEPT for established connections." |tee -a ${SFW_LOG}
    /sbin/iptables ${IPTOPTIONS} -A sfw -m state --state ESTABLISHED,RELATED -j ACCEPT 2>&1 |tee -a ${SFW_LOG}
    PRC=${PIPESTATUS[0]}
    if [ "${PRC}" != "0" ] ; then
      echo "ERROR: Failed to add ACCEPT for established connections." |tee -a ${SFW_LOG}
      exit 21
    fi

    # ACCEPT myself
    test $VERBOSITY -gt 0 && echo "Addding ACCEPT for local connections." |tee -a ${SFW_LOG}
    /sbin/iptables ${IPTOPTIONS} -A sfw -i lo -j ACCEPT 2>&1 |tee -a ${SFW_LOG}
    PRC=${PIPESTATUS[0]}
    if [ "${PRC}" != "0" ] ; then
      echo "ERROR: Failed to add ACCEPT for local connections." |tee -a ${SFW_LOG}
      exit 22
    fi
    /sbin/iptables ${IPTOPTIONS} -A sfw -s 127.0.0.1 -j ACCEPT 2>&1 |tee -a ${SFW_LOG}
    PRC=${PIPESTATUS[0]}
    if [ "${PRC}" != "0" ] ; then
      echo "ERROR: Failed to add ACCEPT for 127.0.0.1 connections." |tee -a ${SFW_LOG}
      exit 23
    fi

    # ACCEPT configured TRUSTED_HOSTS
    if [ -n "$TRUSTED_HOSTS" ] ; then
      for HOST in $TRUSTED_HOSTS ; do
        test $VERBOSITY -gt 0 && echo "Adding ACCEPT for Host/Network $HOST" |tee -a ${SFW_LOG}
        /sbin/iptables ${IPTOPTIONS} -A sfw -s $HOST -j ACCEPT 2>&1 |tee -a ${SFW_LOG}
        PRC=${PIPESTATUS[0]}
        if [ "${PRC}" != "0" ] ; then
          echo "ERROR: Failed to add ACCEPT for Host/Network $HOST" |tee -a ${SFW_LOG}
          exit 31
        fi
      done
    fi

    # ACCEPT configured ALLOWED_TCPPORTS
    if [ -n "$ALLOWED_TCPPORTS" ] ; then
      for PORT in $ALLOWED_TCPPORTS ; do
        test $VERBOSITY -gt 0 && echo "Adding ACCEPT for new connections to TCP Port $PORT" |tee -a ${SFW_LOG}
        /sbin/iptables ${IPTOPTIONS} -A sfw -m state --state NEW -p tcp --destination-port $PORT -j ACCEPT 2>&1 |tee -a ${SFW_LOG}
        PRC=${PIPESTATUS[0]}
        if [ "${PRC}" != "0" ] ; then
          echo "ERROR: Failed to add ACCEPT for new connections to TCP Port $PORT" |tee -a ${SFW_LOG}
          exit 32
        fi
      done
    fi

    # ACCEPT configured ALLOWED_UDPPORTS
    if [ -n "$ALLOWED_UDPPORTS" ] ; then
      for PORT in $ALLOWED_UDPPORTS ; do
        test $VERBOSITY -gt 0 && echo "Adding ACCEPT for new connections to UDP Port $PORT" |tee -a ${SFW_LOG}
        /sbin/iptables ${IPTOPTIONS} -A sfw -m state --state NEW -p udp --destination-port $PORT -j ACCEPT 2>&1 |tee -a ${SFW_LOG}
        PRC=${PIPESTATUS[0]}
        if [ "${PRC}" != "0" ] ; then
          echo "ERROR: Failed to add ACCEPT for new connections to UDP Port $PORT" |tee -a ${SFW_LOG}
          exit 33
        fi
      done
    fi

    # SWALLOW configured SWALLOWED_TCPPORTS
    if [ -n "$SWALLOWED_TCPPORTS" ] ; then
      for PORT in $SWALLOWED_TCPPORTS ; do
        test $VERBOSITY -gt 0 && echo "Adding swallowing of new connections to TCP Port $PORT" |tee -a ${SFW_LOG}
        /sbin/iptables ${IPTOPTIONS} -A sfw -m state --state NEW -p tcp --destination-port $PORT -j DROP 2>&1 |tee -a ${SFW_LOG}
        PRC=${PIPESTATUS[0]}
        if [ "${PRC}" != "0" ] ; then
          echo "ERROR: Failed to add swallowing of new connections to TCP Port $PORT" |tee -a ${SFW_LOG}
          exit 34
        fi
      done
    fi

    # SWALLOW configured SWALLOWED_UDPPORTS
    if [ -n "$SWALLOWED_UDPPORTS" ] ; then
      for PORT in $SWALLOWED_UDPPORTS ; do
        test $VERBOSITY -gt 0 && echo "Adding swallowing of new connections to UDP Port $PORT" |tee -a ${SFW_LOG}
        /sbin/iptables ${IPTOPTIONS} -A sfw -m state --state NEW -p udp --destination-port $PORT -j DROP 2>&1 |tee -a ${SFW_LOG} || exit 35
        PRC=${PIPESTATUS[0]}
        if [ "${PRC}" != "0" ] ; then
          echo "ERROR: Failed to add swallowing of new connections to UDP Port $PORT" |tee -a ${SFW_LOG}
          exit 35
        fi
      done
    fi

    # ACCEPT some pings
    test $VERBOSITY -gt 0 && echo "Adding ACCEPT for $PING_LIMIT pings." |tee -a ${SFW_LOG}
    /sbin/iptables ${IPTOPTIONS} -A sfw -p icmp --icmp-type echo-request -m limit --limit $PING_LIMIT -j ACCEPT 2>&1 |tee -a ${SFW_LOG} || exit 51
    PRC=${PIPESTATUS[0]}
    if [ "${PRC}" != "0" ] ; then
      echo "ERROR: Failed to add ACCEPT for $PING_LIMIT pings." |tee -a ${SFW_LOG}
      exit 51
    fi

    # - block rest_of_input

    #DOCKERUSERRULE=$(/sbin/iptables -L DOCKER-USER 2>/dev/null)
    #if [ -n "${DOCKERUSERRULE}" ] ; then
    #  test $VERBOSITY -gt 0 && echo "Detected DOCKER-USER rule, inserting myself there, ending myself with un-logged RETURN instead of DROP." |tee -a ${SFW_LOG}
    #  /sbin/iptables ${IPTOPTIONS} -A sfw -j RETURN 2>&1 |tee -a ${SFW_LOG} || exit 61
    #  PRC=${PIPESTATUS[0]}
    #  if [ "${PRC}" != "0" ] ; then
    #    echo "ERROR: Failed to add RETURNing of rest, without failing in case of error" |tee -a ${SFW_LOG}
    #    exit 61
    #  fi
    #  /sbin/iptables ${IPTOPTIONS} -I DOCKER-USER -j sfw 2>&1 |tee -a ${SFW_LOG} || exit 62
    #  PRC=${PIPESTATUS[0]}
    #  if [ "${PRC}" != "0" ] ; then
    #    echo "ERROR: Failed to add INSERT myself in DOCKER-USER" |tee -a ${SFW_LOG}
    #    exit 62
    #  fi
    #else
      DO_LOG_DROPS=$(echo "$LOG_DROPS" |egrep -i '^(yes|true)$')
      if [ -z "$DO_LOG_DROPS" ] ; then
        test $VERBOSITY -gt 0 && echo "Not adding LOGing of rest, because LOG_DROPS is not set to 'yes' or 'true'"
      else
        if [ $NRMODULES -gt 0 ] ; then
          test $VERBOSITY -gt 0 && echo "Adding LOGing of rest, with --limit $LOG_LIMIT" |tee -a ${SFW_LOG}
          /sbin/iptables ${IPTOPTIONS} -A sfw -m limit --limit $LOG_LIMIT -j LOG --log-prefix "DROPping unknown packet: " 2>&1 |tee -a ${SFW_LOG} || exit 52
          PRC=${PIPESTATUS[0]}
          if [ "${PRC}" != "0" ] ; then
            echo "ERROR: Failed to add LOGing of rest, with --limit $LOG_LIMIT" |tee -a ${SFW_LOG}
            exit 52
          fi
        else
          test $VERBOSITY -gt 0 && echo "Adding LOGing of rest, without failing in case of error" |tee -a ${SFW_LOG}
          /sbin/iptables ${IPTOPTIONS} -A sfw -m limit --limit $LOG_LIMIT -j LOG --log-prefix "DROPping unknown packet: "
        fi
      fi
      test $VERBOSITY -gt 0 && echo "Adding DROP of rest." |tee -a ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -A sfw -j DROP 2>&1 |tee -a ${SFW_LOG} || exit 53
      PRC=${PIPESTATUS[0]}
      if [ "${PRC}" != "0" ] ; then
        echo "ERROR: Failed to add DROPing of rest, without failing in case of error" |tee -a ${SFW_LOG}
        exit 53
      fi
    #fi
    echo "Done Starting SFW (Simple FireWall)." |tee -a ${SFW_LOG}

    if [ $VERBOSITY -gt 1 ] ; then
      echo "" >> ${SFW_LOG}
      echo "iptables after ..." >> ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -L -n 2>&1 >> ${SFW_LOG}
      echo "" >> ${SFW_LOG}
      echo "iptables -t nat after ..." >> ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -t nat -L -n 2>&1 >> ${SFW_LOG}
      echo "" >> ${SFW_LOG}
    fi

    ;;

  stop)
    echo "Stopping SFW (Simple FireWall)." |tee -a ${SFW_LOG}

    SFWININPUT=$(/sbin/iptables ${IPTOPTIONS} -L INPUT -n 2>/dev/null |egrep "^sfw ")
    if [ -n "$SFWININPUT" ] ; then
      /sbin/iptables ${IPTOPTIONS} -D INPUT -j sfw 2>&1 >> ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -F sfw 2>&1 >> ${SFW_LOG}
      /sbin/iptables ${IPTOPTIONS} -X sfw 2>&1 >> ${SFW_LOG}
      DOCKERUSERRULE=$(/sbin/iptables -L DOCKER-USER 2>/dev/null)
      #if [ -n "${DOCKERUSERRULE}" ] ; then
      #  test $VERBOSITY -gt 0 && echo "Detected DOCKER-USER rule, removing myself there." |tee -a ${SFW_LOG}
      #  /sbin/iptables ${IPTOPTIONS} -D DOCKER-USER -j sfw 2>&1 >> ${SFW_LOG}
      #fi
    fi
    
    SACKON=$(cat /proc/sys/net/ipv4/tcp_sack |grep 1)
    if [ -n "$SACKON" ] ; then
      /sbin/iptables -t mangle -D INPUT   -i !lo -p tcp -j TCPOPTSTRIP --strip-options sack-permitted,sack || /bin/true
      /sbin/iptables -t mangle -D FORWARD -i !lo -p tcp -j TCPOPTSTRIP --strip-options sack-permitted,sack || /bin/true
    fi 

   ;;

  restart|reload)
    $0 stop $2 && $0 start $2
    ;;

  status)
    echo "Statussing SFW (Simple FireWall)."
    /sbin/iptables ${IPTOPTIONS} -L -n
    ;;

  configure)
    # it's ok to do nothing here
    ;;

  *)
    echo "Usage: $0 {start|stop|restart|reload|status}"
    exit 1

esac

