systemd/honeypot-firewall.sh

#!/bin/bash
# Helper script for honeypot systemd service to manage nftables rules

HONEYPOT_CONFIG="${1:-/opt/honeypot/config.json}"
ACTION="$2"

if [ "$ACTION" = "start" ]; then
    # Ensure table exists
    nft list table inet filter >/dev/null 2>&1 || \
        nft add table inet filter

    # Ensure input chain exists
    nft list chain inet filter input >/dev/null 2>&1 || \
        nft add chain inet filter input "{ type filter hook input priority 0; policy drop; }"

    # Collect all honeypot ports from JSON config into a single array
    # This combines: ssh_ports, telnet_ports, rdp_ports, smtp_ports, smtps_ports, sip_ports, dns_ports, ftp_ports, ftps_ports, http_ports, https_ports, ui_port
    if [ -f "${HONEYPOT_CONFIG}" ]; then
        ALL_PORTS=$(jq -r '
            [
                (if .ssh_ports then .ssh_ports else [] end),
                (if .telnet_ports then .telnet_ports else [] end),
                (if .rdp_ports then .rdp_ports else [] end),
                (if .smtp_ports then .smtp_ports else [] end),
                (if .smtps_ports then .smtps_ports else [] end),
                (if .ftp_ports then .ftp_ports else [] end),
                (if .ftps_ports then .ftps_ports else [] end),
                (if .sip_ports then .sip_ports else [] end),
                (if .dns_ports then .dns_ports else [] end),
                (if .http_ports then .http_ports else [] end),
                (if .https_ports then .https_ports else [] end),
                (if .ui_port > 0 then [.ui_port] else [] end)
            ] | flatten | unique | sort | join(",")
        ' "${HONEYPOT_CONFIG}")
        UDP_PORTS=$(jq -r '
            [
                (if .sip_ports then .sip_ports else [] end),
                (if .dns_ports then .dns_ports else [] end)
            ] | flatten | unique | sort | join(",")
        ' "${HONEYPOT_CONFIG}")

        if [ -n "${ALL_PORTS}" ]; then
            # Check if rule already exists
            if ! nft list chain inet filter input | grep -q 'comment "honeypot-ports"'; then
                nft add rule inet filter input tcp dport { ${ALL_PORTS} } accept comment "honeypot-ports"
                if [ -n "${UDP_PORTS}" ]; then
                    nft add rule inet filter input udp dport { ${UDP_PORTS} } accept comment "honeypot-ports"
                fi
            fi
        fi
    fi
elif [ "$ACTION" = "stop" ]; then
    # Remove the single honeypot ports rule by comment
    for h in $(nft -a list chain inet filter input | \
        awk '/comment "honeypot-ports"/ {print $NF}'); do
        nft delete rule inet filter input handle "$h" 2>/dev/null
    done
fi