#!/bin/bash

### iptables-Setup für die von /etc/init.d/iptables-base angelegten
### user-defined Chains. Einige (komplexere) Setups sind in eigene
### Scripts ausgelagert, die von hier aufgerufen werden.

## Fehlermeldungen und sonstigen Output auf Wunsch per E-Mail an die
## Hostmaster melden. (Wird in den Initscripts verwendet.) Zur
## Aktivierung die Umgebungsvariable ReportByMail auf einen beliebigen
## Wert != "" setzen.

PUBLIC_DEV=$( ls /sys/class/net/ | egrep -e "(pub|eth0)" )

if [ ! -f /etc/init.d/iptables-hostsharing ]; then
    echo "we are not using iptables anymore"
    exit 0
fi

if [ -n "${ReportByMail}" ]; then
	unset ReportByMail
	
	source /root/etc/config
	
	"$0" "$@" 2>&1 | \
	\
	mail -e -s "${THIS_HIVE}: Error while executing $0 $*" \
	 "${EMAIL_HOSTMASTER}"
	
	exit "${PIPESTATUS[0]}"
fi	

## Kommandozeilenargumente

if [ $# -ne 1 ]; then
	echo "Usage: $0 <chain>" >&2
	exit 1
fi

chain="$1"

## Konfiguration einlesen

ConfFile="/usr/local/etc/iptables.conf"

source "${ConfFile}" || {
	echo "$0: Invalid configuration file ${ConfFile}." >&2
	exit 1
}

## Temporäre Datei zum Zwischenspeichern der iptables-restore-Befehle.

CmdFile="$(mktemp -t "mk-iptables-rules.XXXXXX")" || {
	echo "$0: Cannot create a temporary file." >&2
	exit 1
}

## Simple Subroutine, die übergebene iptables-restore-Kommandos in die
## oben angelegte temporäre Datei schreibt.

function addCmd(){
	echo "$@" >>"${CmdFile}"
}

## Das eigentliche Anlegen der iptables-Regeln.

addCmd '*filter'

case "${chain}" in
RateLimits)
    addCmd --flush RateLimits
    addCmd --append RateLimits -p tcp --dport 21 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_ftp_015
    addCmd --append RateLimits -p tcp --dport 21 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_ftp_060
    addCmd --append RateLimits -p tcp --dport 21 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_ftp_300
    addCmd --append RateLimits -p tcp --dport 21 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_ftp_015 --update --seconds 15  --hitcount 15 -j REJECT
    addCmd --append RateLimits -p tcp --dport 21 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_ftp_060 --update --seconds 60  --hitcount 30 -j REJECT
    addCmd --append RateLimits -p tcp --dport 21 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_ftp_300 --update --seconds 300 --hitcount 45 -j REJECT
    addCmd --append RateLimits -p tcp --dport 22 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_ssh_015
    addCmd --append RateLimits -p tcp --dport 22 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_ssh_060
    addCmd --append RateLimits -p tcp --dport 22 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_ssh_300
    addCmd --append RateLimits -p tcp --dport 22 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_ssh_015 --update --seconds 15  --hitcount 15 -j REJECT
    addCmd --append RateLimits -p tcp --dport 22 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_ssh_060 --update --seconds 60  --hitcount 30 -j REJECT
    addCmd --append RateLimits -p tcp --dport 22 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_ssh_300 --update --seconds 300 --hitcount 45 -j REJECT
    addCmd --append RateLimits -p tcp --dport 222 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_sshhm_015
    addCmd --append RateLimits -p tcp --dport 222 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_sshhm_060
    addCmd --append RateLimits -p tcp --dport 222 -i $PUBLIC_DEV -m state --state NEW -m recent --set --name count_sshhm_300
    addCmd --append RateLimits -p tcp --dport 222 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_sshhm_015 --update --seconds 15  --hitcount 15 -j REJECT
    addCmd --append RateLimits -p tcp --dport 222 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_sshhm_060 --update --seconds 60  --hitcount 30 -j REJECT
    addCmd --append RateLimits -p tcp --dport 222 -i $PUBLIC_DEV -m state --state NEW -m recent --name count_sshhm_300 --update --seconds 300 --hitcount 45 -j REJECT
    ;;
AccFilter)
	# Chains zum Ausfiltern des lokalen Traffics aus dem Traffic-Accounting.

	addCmd --flush AccFilterIn
	addCmd --flush AccFilterOut

	for src in ${LocalNetworks}; do
		for dst in ${LocalNetworks}; do
			addCmd --append AccFilterIn --source "${src}" \
			 --destination "${dst}" --jump RETURN
	
			addCmd --append AccFilterOut --source "${src}" \
			 --destination "${dst}" --jump RETURN
		done
	done

	addCmd --append AccFilterIn  --jump AccountingIn
	addCmd --append AccFilterOut --jump AccountingOut
	;;
Accounting)
	# Zählung des Traffics (u.a. nach lokaler IP-Adresse).

	addCmd --flush AccountingIn
	addCmd --flush AccountingOut

	addCmd --append AccountingIn
	addCmd --append AccountingOut

    for addr in $(ip -4 addr |grep ' inet ' |sed -e's/^ *//g' |cut -d ' ' -f2 |cut -d '/' -f1); do
		addCmd --append AccountingIn  --destination "${addr}"
		addCmd --append AccountingOut --source      "${addr}"
	done

	save-iptcnt
	;;
PacDaemons)
	# Regeln für Daemons, die in Hostsharing-Paketen laufen
	
	mk-pac-daemons-ipt
	;;
UnPrivSysDaemons)
	# Chain, um zu verhindern, dass User Daemons auf einem der
	# unprivilegierten Ports betreiben, die für Systemdaemons
	# (PostgreSQL und co.) reserviert sind.

	addCmd --flush UnPrivSysDaemons

	for daemon in ${UnPrivSysDaemons}; do
		port="$(echo "${daemon}" | cut -d '/' -f 1)"
		users="$(echo "${daemon}" | cut -d '/' -f 2)"

		users="$(echo "${users}" | tr ',' ' ')"

		for user in ${users}; do
			addCmd --append UnPrivSysDaemons \
			 --protocol tcp --match tcp \
			 --source-port "${port}" \
			 --match owner --uid-owner "${user}" \
			 --jump RETURN
		done

		addCmd --append UnPrivSysDaemons --protocol tcp \
		 --match tcp --source-port "${port}" \
		 --tcp-flags SYN SYN --jump REJECT
	done
	;;
*)
	rm -f "${CmdFile}"

	echo "$0: Unknown chain ${chain}." >&2
	exit 1
	;;
esac

addCmd 'COMMIT'

## Ausführung der gecachten Kommandos.

${IptablesRestore} <"${CmdFile}" || {
	rm -f "${CmdFile}"
	
	echo "$0: An error occured while committing the rules." >&2
	exit 1
}

rm -f "${CmdFile}"

exit 0

