#!/bin/bash

# CVE-2026-98432 temporary nftables mitigation for RHEL 9 + firewalld.
# Based on Red Hat RHSB-2026-016 (2026-10-30).
# https://access.redhat.com/security/vulnerabilities/RHSB-2026-016
# Usage: ./cve-2026-98432.sh install|status|apply|test-reload|remove


NAME='cve-2026-98432'
TABLE='cve_2026_98432'
RULEFILE="/etc/nftables/${NAME}.nft"
UNITFILE="/etc/systemd/system/${NAME}.service"
HELPER="/usr/local/sbin/${NAME}"

say() { printf '%s\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
need_root() { [ "$(id -u)" -eq 0 ] || die 'Run as root.'; }
require_commands() {
    local cmd
    for cmd in nft systemctl firewall-cmd mktemp grep install; do
        command -v "$cmd" >/dev/null 2>&1 || die "Missing command: $cmd"
    done
}
ensure_firewalld() {
    systemctl is-active --quiet firewalld || die 'firewalld is not active; refusing to change firewall configuration.'
    if systemctl is-active --quiet nftables.service; then
        die 'nftables.service is active alongside firewalld; resolve this conflict first.'
    fi
    if systemctl is-enabled --quiet nftables.service 2>/dev/null; then
        die 'nftables.service is enabled; resolve competing firewall startup configuration first.'
    fi
}
write_rulefile() {
    install -d -m 0755 /etc/nftables || die "Could not create /etc/nftables."
    local tmp
    tmp=$(mktemp /etc/nftables/.cve-2026-98432.XXXXXX) || die "Could not create temporary rule file."
    cat > "$tmp" <<'NFT'
table inet cve_2026_98432 {
    chain input {
        type filter hook input priority -310; policy accept;
        ip protocol tcp ip hdrlength > 5 counter drop
    }
}
NFT
    chmod 0644 "$tmp" || die "Could not set file permissions."
    # Test the exact transaction, including replacement if the table exists.
    validate_transaction "$tmp" || { rm -f "$tmp"; die 'nftables syntax check failed; existing rule left untouched.'; }
    mv -f "$tmp" "$RULEFILE" || die "Could not install rule file."
}

# nft -f processes a batch atomically. Delete + recreate in ONE batch so
# repeated runs cannot append duplicate rules. No nft flush ruleset.
transaction() {
    local source=$1 dest=$2
    if nft list table inet "$TABLE" >/dev/null 2>&1; then
        printf 'delete table inet %s\n' "$TABLE" > "$dest"
    else
        : > "$dest"
    fi
    cat "$source" >> "$dest"
}
validate_transaction() {
    local source=$1 tmp
    tmp=$(mktemp /run/.cve-2026-98432-check.XXXXXX) || return 1
    transaction "$source" "$tmp" || { rm -f "$tmp"; return 1; }
    if nft --check --file "$tmp"; then
        rm -f "$tmp"
        return 0
    fi
    rm -f "$tmp"
    return 1
}
apply() {
    [ -r "$RULEFILE" ] || die "Missing $RULEFILE; run install first."
    local tmp
    tmp=$(mktemp /run/.cve-2026-98432-apply.XXXXXX) || die "Could not create temporary transaction."
    transaction "$RULEFILE" "$tmp" || { rm -f "$tmp"; die "Could not create nftables transaction."; }
    if ! nft --check --file "$tmp"; then
        rm -f "$tmp"
        die 'nftables transaction validation failed; existing rules unchanged.'
    fi
    if ! nft --file "$tmp"; then
        rm -f "$tmp"
        die 'Failed to apply mitigation.'
    fi
    rm -f "$tmp"
    verify
}
verify() {
    local output count
    output=$(nft -a list chain inet "$TABLE" input) || die 'Mitigation input chain is missing.'
    count=$(printf '%s\n' "$output" | grep -Ec 'ip protocol tcp ip hdrlength > 5 .*drop' || true)
    [ "$count" -eq 1 ] || die "Expected exactly one mitigation rule, found $count."
    say 'OK: exactly one IPv4/TCP IP-options drop rule is installed.'
    nft -a list table inet "$TABLE"
}
install_mitigation() {
    ensure_firewalld
    write_rulefile
    # Install a self-contained helper used by systemd on every boot.
    local self
    self=$(readlink -f "$0")
    if [ "$self" != "$HELPER" ]; then
        install -D -m 0755 "$self" "$HELPER" || die "Could not install helper."
    fi
    local tmp
    tmp=$(mktemp /etc/systemd/system/.cve-2026-98432.XXXXXX) || die "Could not create temporary service file."
    cat > "$tmp" <<'UNIT'
[Unit]
Description=Temporary mitigation for CVE-2026-98432 (Red Hat RHSB-2026-016)
Requires=firewalld.service
After=firewalld.service

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/cve-2026-98432 apply
ExecReload=/usr/local/sbin/cve-2026-98432 apply
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
UNIT
    chmod 0644 "$tmp" || die "Could not set file permissions."
    mv -f "$tmp" "$UNITFILE" || die "Could not install service file."
    systemctl daemon-reload || die "systemd daemon-reload failed."
    systemctl enable "$NAME.service" || die "Could not enable service."
    # enable --now does not reexecute an already active oneshot unit.
    systemctl restart "$NAME.service" || die "Could not start service."
    say "Installed and enabled ${NAME}.service."
    say 'Check again after your next reboot or firewalld reload.'
}
remove_mitigation() {
    if [ -e "$UNITFILE" ]; then
        systemctl disable --now "$NAME.service" || die 'Could not disable service.'
    fi
    if nft list table inet "$TABLE" >/dev/null 2>&1; then
        nft delete table inet "$TABLE" || die 'Failed to remove nftables table.'
    fi
    rm -f "$UNITFILE" "$RULEFILE" "$HELPER" || die "Could not remove installed files."
    systemctl daemon-reload || die "systemd daemon-reload failed."
    say 'Mitigation removed. Do this only after confirming a fixed running kernel.'
}
test_reload() {
    ensure_firewalld
    say 'Reloading firewalld and checking the mitigation...'
    firewall-cmd --reload || die 'firewalld reload failed.'
    if ! (verify); then
        say 'Rule was lost on reload. Reapplying it now.' >&2
        apply
        die 'firewalld reload did not preserve the rule. Add a reload integration before relying on this installation.'
    fi
}

need_root
require_commands
case "${1:-}" in
    install) install_mitigation ;;
    status)
        systemctl is-enabled "$NAME.service" || true
        systemctl is-active "$NAME.service" || true
        verify
        ;;
    apply) ensure_firewalld; apply ;;
    test-reload) test_reload ;;
    remove) remove_mitigation ;;
    *)
        say "Usage: $0 {install|status|apply|test-reload|remove}"
        exit 2
        ;;
esac