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

IPFW_TABLE=22

fw_init() {
    # Starting in FreeBSD 11, tables must first be created.
    ipfw table ${IPFW_TABLE} create 2>/dev/null || \
        ipfw table ${IPFW_TABLE} list > /dev/null
}

fw_block() {
    ipfw -q table ${IPFW_TABLE} add $1/$3
}

fw_release() {
    ipfw -q table ${IPFW_TABLE} delete $1/$3
}

fw_flush() {
    ipfw table ${IPFW_TABLE} flush
}

fw_fin() {
    ipfw table ${IPFW_TABLE} destroy 2>/dev/null
}
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
