#!/usr/bin/env bash
# =============================================================================
#  VirtuaOS — host firewall (INPUT only)
#
#  Usage:
#    virtuaos-firewall write    Generate /etc/iptables/rules.v4|v6 from the config
#                               (no runtime change — used at image build time)
#    virtuaos-firewall apply    write + apply live, WITHOUT flushing the Docker /
#                               libvirt chains (safe on a running hypervisor)
#    virtuaos-firewall status   Show the active VIRTUAOS-INPUT chains
#
#  Config: /etc/virtuaos/firewall.conf
#    ALLOW_TCP="22 80 443 8441 3390:3489"
#                                   ports open to everyone (3390-3489 = per-VM
#                                   RDP consoles published by the Virtua panel).
#                                   The effective sshd port(s) are always added.
#    ALLOW_UDP=""
#    TRUSTED_IFACES="virbr+ lxcbr+ docker0 br-+"
#                                   guest bridges (DHCP/DNS served by the host)
#    TRUSTED_SOURCES=""             CIDRs allowed on ALL ports (cluster nodes,
#                                   admin LAN…), e.g. "10.0.0.0/24 192.168.1.10"
#
#  Model: INPUT policy DROP + one jump to a VIRTUAOS-INPUT chain holding every
#  accept rule. FORWARD/OUTPUT are left to Docker and libvirt.
#
#  Coexistence with the Virtua panel firewall (chain AUXINUX_INPUT, off by
#  default): our jump is APPENDED to INPUT while the panel INSERTS its jump at
#  position 1, so when the panel firewall is enabled it is evaluated first and
#  stays authoritative (it ends with its own DROP). When it is disabled, this
#  baseline applies.
# =============================================================================
set -euo pipefail

CONF="/etc/virtuaos/firewall.conf"
RULES_DIR="/etc/iptables"
CHAIN="VIRTUAOS-INPUT"

ALLOW_TCP="22 80 443 8441 3390:3489"
ALLOW_UDP=""
TRUSTED_IFACES="virbr+ lxcbr+ docker0 br-+"
TRUSTED_SOURCES=""
# shellcheck disable=SC1090
[[ -f "${CONF}" ]] && . "${CONF}"

is_v6() { [[ "$1" == *:* ]]; }

# Effective sshd port(s): never lock the admin out when sshd is not on 22.
ssh_ports() {
    local ports=""
    if command -v sshd >/dev/null 2>&1; then
        ports="$(sshd -T 2>/dev/null | awk '$1=="port"{print $2}' | sort -u | tr '\n' ' ' || true)"
    fi
    if [[ -z "${ports// /}" ]]; then
        ports="$(cat /etc/ssh/sshd_config /etc/ssh/sshd_config.d/*.conf 2>/dev/null \
                 | awk 'tolower($1)=="port"{print $2}' | sort -u | tr '\n' ' ' || true)"
    fi
    echo "${ports:-22}"
}

# Fail BEFORE touching anything on a malformed config (a bad token used to
# leave INPUT=DROP half-applied, or make iptables-restore reject the whole file
# at boot = fail-open).
validate_conf() {
    local p i s
    for p in ${ALLOW_TCP} ${ALLOW_UDP}; do
        [[ "${p}" =~ ^[0-9]{1,5}(:[0-9]{1,5})?$ ]] || { echo "invalid port '${p}' in ${CONF}" >&2; exit 1; }
    done
    for i in ${TRUSTED_IFACES}; do
        [[ "${i}" =~ ^[A-Za-z0-9_.@-]+\+?$ ]] || { echo "invalid interface '${i}' in ${CONF}" >&2; exit 1; }
    done
    for s in ${TRUSTED_SOURCES}; do
        [[ "${s}" =~ ^[0-9A-Fa-f:.]+(/[0-9]{1,3})?$ ]] || { echo "invalid source '${s}' in ${CONF}" >&2; exit 1; }
    done
}

# Print the accept rules of the chain (iptables-restore syntax) for one family.
chain_rules() {
    local fam="$1" p ifc src
    echo "-A ${CHAIN} -i lo -j ACCEPT"
    echo "-A ${CHAIN} -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT"
    echo "-A ${CHAIN} -m conntrack --ctstate INVALID -j DROP"
    if [[ "${fam}" == 4 ]]; then
        echo "-A ${CHAIN} -p icmp -j ACCEPT"
    else
        echo "-A ${CHAIN} -p ipv6-icmp -j ACCEPT"
        echo "-A ${CHAIN} -p udp --dport 546 -j ACCEPT"
    fi
    for ifc in ${TRUSTED_IFACES}; do
        echo "-A ${CHAIN} -i ${ifc} -j ACCEPT"
    done
    for src in ${TRUSTED_SOURCES}; do
        if [[ "${fam}" == 6 ]] && is_v6 "${src}"; then
            echo "-A ${CHAIN} -s ${src} -j ACCEPT"
        elif [[ "${fam}" == 4 ]] && ! is_v6 "${src}"; then
            echo "-A ${CHAIN} -s ${src} -j ACCEPT"
        fi
    done
    for p in $( (echo ${ALLOW_TCP}; ssh_ports) | tr ' ' '\n' | grep . | sort -u); do
        echo "-A ${CHAIN} -p tcp --dport ${p} -j ACCEPT"
    done
    for p in ${ALLOW_UDP}; do echo "-A ${CHAIN} -p udp --dport ${p} -j ACCEPT"; done
    echo "-A ${CHAIN} -j RETURN"
}

render() {
    local fam="$1"
    echo "# Generated by virtuaos-firewall from ${CONF} — edit the config, then run:"
    echo "#   virtuaos-firewall apply"
    echo "*filter"
    echo ":INPUT DROP [0:0]"
    echo ":FORWARD ACCEPT [0:0]"
    echo ":OUTPUT ACCEPT [0:0]"
    echo ":${CHAIN} - [0:0]"
    echo "-A INPUT -j ${CHAIN}"
    chain_rules "${fam}"
    echo "COMMIT"
}

# write_rules [test]: render rules.v4/v6; with "test", first check every file
# with the real parser (iptables-restore --test) and change nothing on error.
# (No --test at image build time: the chroot has no usable netfilter.)
write_rules() {
    local mode="${1:-}" fam restore
    mkdir -p "${RULES_DIR}"
    for fam in 4 6; do
        render "${fam}" > "${RULES_DIR}/rules.v${fam}.tmp"
    done
    if [[ "${mode}" == "test" ]]; then
        for fam in 4 6; do
            if [[ "${fam}" == 4 ]]; then restore=iptables-restore; else restore=ip6tables-restore; fi
            command -v "${restore}" >/dev/null 2>&1 || continue
            if ! "${restore}" --test < "${RULES_DIR}/rules.v${fam}.tmp"; then
                rm -f "${RULES_DIR}"/rules.v4.tmp "${RULES_DIR}"/rules.v6.tmp
                echo "generated rules.v${fam} rejected by ${restore} --test — nothing changed" >&2
                exit 1
            fi
        done
    fi
    for fam in 4 6; do
        chmod 0644 "${RULES_DIR}/rules.v${fam}.tmp"
        mv -f "${RULES_DIR}/rules.v${fam}.tmp" "${RULES_DIR}/rules.v${fam}"
    done
}

# Live apply: rebuild only our chain, keep every other chain (DOCKER*, LIBVIRT*)
# intact, make sure INPUT jumps to it first, then switch the policy to DROP.
apply_family() {
    local fam="$1" ipt rule
    if [[ "${fam}" == 4 ]]; then ipt=iptables; else ipt=ip6tables; fi
    command -v "${ipt}" >/dev/null 2>&1 || return 0
    "${ipt}" -N "${CHAIN}" 2>/dev/null || true
    "${ipt}" -F "${CHAIN}"
    while IFS= read -r rule; do
        # shellcheck disable=SC2086
        "${ipt}" ${rule}
    done < <(chain_rules "${fam}")
    # APPEND (not insert): the Virtua panel's AUXINUX_INPUT jump, inserted at
    # position 1, must stay first so the panel firewall wins when enabled.
    "${ipt}" -C INPUT -j "${CHAIN}" 2>/dev/null || "${ipt}" -A INPUT -j "${CHAIN}"
    "${ipt}" -P INPUT DROP
}

case "${1:-}" in
    write)
        validate_conf
        write_rules
        echo "[virtuaos-firewall] rules written to ${RULES_DIR}/rules.v4|v6"
        ;;
    apply)
        [[ $EUID -eq 0 ]] || { echo "run as root" >&2; exit 1; }
        validate_conf
        write_rules test
        apply_family 4
        apply_family 6
        echo "[virtuaos-firewall] applied (INPUT policy DROP; open tcp: ${ALLOW_TCP:-none}; trusted: ${TRUSTED_SOURCES:-none})"
        ;;
    status)
        iptables -S INPUT 2>/dev/null | head -3 || true
        iptables -S "${CHAIN}" 2>/dev/null || echo "${CHAIN} (v4) not loaded"
        ip6tables -S "${CHAIN}" 2>/dev/null || echo "${CHAIN} (v6) not loaded"
        ;;
    *)
        echo "usage: virtuaos-firewall write|apply|status" >&2
        exit 2
        ;;
esac
