#!/usr/bin/bash
#
#       salpack-shield
#
#   Copyright (C) 2014  Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

CHAIN=pam_shield
RULE="-j DROP"
PATH=/sbin:/usr/sbin:/bin:/usr/bin

usage() {
	echo "$0 add|del|flush|clear|reset|list IP"
	exit 0
}

log() {
	logger -i -t shield-trigger -p authpriv.info "$@"
}

update_rules() {
	# ipv4 or ipv6?
	IP="`echo \"$2\" | sed 's/^::ffff://'`"
	if [ -z "`echo \"$IP\" | sed 's/[0-9\.]//g'`" ]; then
		IPT=iptables
	else
		IPT=ip6tables
	fi

	# create pam_shield chain if not exists
	if [ -z "`$IPT -L $CHAIN 2>/dev/null`" ]; then
		$IPT -N $CHAIN
	fi

	# add/del rule
	$IPT $1 $CHAIN -s "$IP" $RULE
}

case "$1" in
	add|-a)
		[ -z "$2" ] && usage
		log "blocking $2"
		update_rules -A $2
		;;
	del|-d)
		[ -z "$2" ] && usage
		log "unblocking $2"
		update_rules -D $2
		;;
	flush|clear|reset|-f|-c|-r)
		log "flushing all rules"
		iptables -F $CHAIN
		ip6tables -F $CHAIN
		shield-purge -f
		;;
	list|-l)
		shield-purge -l
		iptables -L $CHAIN -n
		ip6tables -L $CHAIN -n
		;;
	*)
		usage
		;;
esac

# make pam_shield happy
exit 0
