#!/bin/sh
# sshg-fw-ipfilter
# This file is part of SSHGuard.

IPFILTER_CMD=ipf
IPFILTER_CONF=/etc/ipfilter.conf

fw_init() {
    :
}

fw_block() {
    FAM=""
    if [ -n "$2" ]; then
        FAM="-$2"
    fi
    echo "block in quick proto tcp from $1/$3 to any" | \
        ${IPFILTER_CMD} ${FAM} -A -f -
}

fw_release() {
    FAM=""
    if [ -n "$2" ]; then
        FAM="-$2"
    fi
    echo "block in quick proto tcp from $1/$3 to any" | \
        ${IPFILTER_CMD} ${FAM} -A -r -f -
}

fw_flush() {
    ${IPFILTER_CMD} -Fa && ${IPFILTER_CMD} -f ${IPFILTER_CONF}
}

fw_fin() {
    :
}
die() {
    echo "$(basename "$0"): $2" >&2
    exit "$1"
}

fw_init || die 69 "Could not initialize firewall"

cleanup() {
    trap "" EXIT
    if [ "YES" = "$flushonexit" ]; then
        fw_flush
    fi
    fw_fin
    exit
}

trap cleanup EXIT INT TERM

while read -r cmd address addrtype cidr; do
    case $cmd in
        block)
            fw_block "$address" "$addrtype" "$cidr";;
        release)
            fw_release "$address" "$addrtype" "$cidr";;
        flush)
            fw_flush;;
        flushonexit)
            flushonexit=YES;;
        *)
            die 65 "Invalid command";;
    esac
done
