#!/usr/bin/sh
# suricatavel-fw: the only firewall commands Suricatavel runs as root on an iptables, nftables or pf host.
#
# Installed root-owned in /usr/local/sbin by linux-firewall.yml or bsd-firewall.yml, with a sudoers rule that lets the SSH user run this
# script, and nothing else, without a password. A sudo rule on iptables, nft or pfctl themselves is close to root
# (iptables --modprobe=<program>, nft -f or pfctl -f on any file), so this script takes no options: each operation
# has fixed arguments, every one of them validated, and the firewall binary is called with an argument list.
#
# With iptables it only changes the chains of Suricatavel ("SURICATAVEL" or "SURICATAVEL_<name>") and the jumps to them.
#
#   suricatavel-fw iptables list <4|6>
#   suricatavel-fw iptables create <4|6> <our chain>
#   suricatavel-fw iptables jump <4|6> <chain> <our chain>
#   suricatavel-fw iptables unjump <4|6> <chain> <our chain> <rule number>
#   suricatavel-fw iptables keep <our chain> <address that opened the connections to keep>
#   suricatavel-fw iptables add <our chain> <src|dst|opened-by|opened-to> <address> <DROP|REJECT> <protocol|all> <source port|0> <destination port|0> <comment>
#   suricatavel-fw iptables delete <4|6> <our chain> <rule number>
#   suricatavel-fw nft get <family> <table> <set> <address>
#   suricatavel-fw nft add <family> <table> <set> <address> <timeout seconds, 0: none> [comment]
#   suricatavel-fw nft delete <family> <table> <set> <address>
#   suricatavel-fw nft list-table <family> <table>
#   suricatavel-fw conntrack version
#   suricatavel-fw conntrack list <address that receives the connections>
#   suricatavel-fw conntrack delete-from <address that opened the connections>
#   suricatavel-fw conntrack delete <address that opened the connections> <address that receives them>
#   suricatavel-fw pf add|delete <table> <address>
#   suricatavel-fw pf show <table>
#   suricatavel-fw pf info|rules|tables
#   suricatavel-fw pf connections <address>
#   suricatavel-fw pf close-from|close-to <address>
#   suricatavel-fw pf close <connection id>/<creator id>
#   suricatavel-fw version
set -eu

PATH=/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH

VERSION=5

die() {
    printf 'suricatavel-fw: %s\n' "$*" >&2
    exit 64
}

# Whole-value match of an extended regex; values with a line break never match (grep works line by line).
matches() {
    case $1 in
        *'
'*) return 1 ;;
    esac
    printf '%s\n' "$1" | grep -Eqx -- "$2"
}

identifier() {
    matches "$1" '[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}' || die "invalid $2: $1"
}

# iptables allows 28 characters.
own_chain() {
    matches "$1" 'SURICATAVEL(_[A-Za-z0-9_.-]{1,16})?' || die "not a chain of Suricatavel: $1"
}

rule_number() {
    matches "$1" '[1-9][0-9]{0,5}' || die "invalid rule number: $1"
}

port() {
    matches "$1" '[0-9]{1,5}' && [ "$1" -le 65535 ] || die "invalid port: $1"
}

address() {
    matches "$1" '([0-9]{1,3}\.){3}[0-9]{1,3}(/[0-9]{1,2})?' \
        || matches "$1" '[0-9A-Fa-f.]*:[0-9A-Fa-f:.]*(/[0-9]{1,3})?' \
        || die "invalid address: $1"
}

comment() {
    matches "$1" '[A-Za-z0-9 .:_-]{0,60}' || die "invalid comment"
}

family() {
    case $1 in
        ip | ip6 | inet | arp | bridge | netdev) ;;
        *) die "invalid nftables family: $1" ;;
    esac
}

ip_version_binary() {
    case $1 in
        4) echo iptables ;;
        6) echo ip6tables ;;
        *) die "invalid IP version: $1" ;;
    esac
}

address_binary() {
    case $1 in
        *:*) echo ip6tables ;;
        *) echo iptables ;;
    esac
}

connection_family() {
    case $1 in
        *:*) echo ipv6 ;;
        *) echo ipv4 ;;
    esac
}

# Who answers is the real destination, also after a DNAT. conntrack does not accept ranges there.
connection_destination() {
    case $1 in
        */*) echo --orig-dst ;;
        *) echo --reply-src ;;
    esac
}

arguments() {
    [ "$1" -ge "$2" ] && [ "$1" -le "$3" ] || die "wrong number of arguments"
}

[ $# -ge 1 ] || die "usage: suricatavel-fw iptables|nft|conntrack|pf|version ..."
tool=$1
shift

case $tool in
    version)
        echo "$VERSION"
        ;;

    iptables)
        [ $# -ge 1 ] || die "usage: suricatavel-fw iptables list|create|jump|unjump|keep|add|delete ..."
        operation=$1
        shift
        case $operation in
            list)
                arguments $# 1 1
                binary=$(ip_version_binary "$1")
                exec "$binary" -S
                ;;
            create)
                arguments $# 2 2
                binary=$(ip_version_binary "$1")
                own_chain "$2"
                exec "$binary" -N "$2"
                ;;
            jump)
                arguments $# 3 3
                binary=$(ip_version_binary "$1")
                identifier "$2" chain
                own_chain "$3"
                exec "$binary" -I "$2" -j "$3"
                ;;
            unjump)
                arguments $# 4 4
                binary=$(ip_version_binary "$1")
                identifier "$2" chain
                own_chain "$3"
                rule_number "$4"
                [ "$("$binary" -S "$2" "$4")" = "-A $2 -j $3" ] || die "rule $4 of $2 is not a jump to $3"
                exec "$binary" -D "$2" "$4"
                ;;
            keep)
                arguments $# 2 2
                own_chain "$1"
                address "$2"
                binary=$(address_binary "$2")
                exec "$binary" -I "$1" -m conntrack --ctstate ESTABLISHED --ctorigsrc "$2" -j RETURN
                ;;
            add)
                arguments $# 8 8
                own_chain "$1"
                # "opened-by" and "opened-to" only match who opened the connection, not its replies.
                opener=
                case $2 in
                    src) side=-s ;;
                    dst) side=-d ;;
                    opened-by) side=-s opener=1 ;;
                    opened-to) side=-d opener=1 ;;
                    *) die "invalid side: $2" ;;
                esac
                address "$3"
                case $4 in DROP | REJECT) ;; *) die "invalid target: $4" ;; esac
                case $5 in all | tcp | udp | icmp | icmpv6 | esp | ah | gre | igmp) ;; *) die "invalid protocol: $5" ;; esac
                port "$6"
                port "$7"
                comment "$8"
                binary=$(address_binary "$3")
                chain=$1 ip=$3 target=$4 protocol=$5 source_port=$6 destination_port=$7 text=$8
                set -- -A "$chain" "$side" "$ip" -p "$protocol"
                [ "$source_port" -eq 0 ] || set -- "$@" --sport "$source_port"
                [ "$destination_port" -eq 0 ] || set -- "$@" --dport "$destination_port"
                [ -z "$opener" ] || set -- "$@" -m conntrack --ctdir ORIGINAL
                exec "$binary" "$@" -m comment --comment "$text" -j "$target"
                ;;
            delete)
                arguments $# 3 3
                binary=$(ip_version_binary "$1")
                own_chain "$2"
                rule_number "$3"
                exec "$binary" -D "$2" "$3"
                ;;
            *) die "unknown iptables operation: $operation" ;;
        esac
        ;;

    nft)
        [ $# -ge 1 ] || die "usage: suricatavel-fw nft get|add|delete|list-table ..."
        operation=$1
        shift
        case $operation in
            get | delete)
                arguments $# 4 4
                family "$1"
                identifier "$2" table
                identifier "$3" set
                address "$4"
                exec nft "$operation" element "$1" "$2" "$3" "{ $4 }"
                ;;
            add)
                arguments $# 5 6
                family "$1"
                identifier "$2" table
                identifier "$3" set
                address "$4"
                matches "$5" '[0-9]{1,10}' || die "invalid timeout: $5"
                element=$4
                if [ "$5" != 0 ]; then
                    element="$element timeout ${5}s"
                fi
                if [ $# -eq 6 ] && [ -n "$6" ]; then
                    comment "$6"
                    element="$element comment \"$6\""
                fi
                exec nft add element "$1" "$2" "$3" "{ $element }"
                ;;
            list-table)
                arguments $# 2 2
                family "$1"
                identifier "$2" table
                exec nft -j list table "$1" "$2"
                ;;
            *) die "unknown nft operation: $operation" ;;
        esac
        ;;

    conntrack)
        [ $# -ge 1 ] || die "usage: suricatavel-fw conntrack version|list|delete-from|delete ..."
        operation=$1
        shift
        case $operation in
            version)
                arguments $# 0 0
                exec conntrack --version
                ;;
            list)
                arguments $# 1 1
                address "$1"
                exec conntrack -L -f "$(connection_family "$1")" "$(connection_destination "$1")" "$1"
                ;;
            delete-from)
                arguments $# 1 1
                address "$1"
                exec conntrack -D -f "$(connection_family "$1")" --orig-src "$1"
                ;;
            delete)
                arguments $# 2 2
                address "$1"
                address "$2"
                exec conntrack -D -f "$(connection_family "$2")" --orig-src "$1" "$(connection_destination "$2")" "$2"
                ;;
            *) die "unknown conntrack operation: $operation" ;;
        esac
        ;;

    pf)
        [ $# -ge 1 ] || die "usage: suricatavel-fw pf add|delete|show|info|rules|tables|connections|close-from|close-to|close ..."
        operation=$1
        shift
        case $operation in
            add | delete)
                arguments $# 2 2
                identifier "$1" table
                address "$2"
                exec pfctl -t "$1" -T "$operation" "$2"
                ;;
            show)
                arguments $# 1 1
                identifier "$1" table
                exec pfctl -t "$1" -T show
                ;;
            info)
                arguments $# 0 0
                exec pfctl -s info
                ;;
            rules)
                arguments $# 0 0
                exec pfctl -a '*' -s rules
                ;;
            tables)
                arguments $# 0 0
                exec pfctl -vv -s Tables
                ;;
            connections)
                arguments $# 1 1
                address "$1"
                pfctl -vv -s states | grep -F -A 3 -e "$1"
                ;;
            close-from)
                arguments $# 1 1
                address "$1"
                exec pfctl -k "$1"
                ;;
            close-to)
                arguments $# 1 1
                address "$1"
                case $1 in
                    *:*) exec pfctl -k ::/0 -k "$1" ;;
                    *) exec pfctl -k 0.0.0.0/0 -k "$1" ;;
                esac
                ;;
            close)
                arguments $# 1 1
                matches "$1" '[0-9a-f]{1,16}/[0-9a-f]{1,8}' || die "invalid connection: $1"
                exec pfctl -k id -k "$1"
                ;;
            *) die "unknown pf operation: $operation" ;;
        esac
        ;;

    *) die "unknown tool: $tool" ;;
esac
