LinuxNOTE
Debian 13 服务器安全加固指南(Firewall 与 Fail2ban)
#Linux#安全#nftables#Fail2ban
本文提供适用于 Debian 13 (Trixie) 及主流现代 Linux 服务器的安全加固方案,包含两套经过工程验证的一键部署脚本:
- 模块化 nftables 防火墙:具备 60 秒看门狗自动回滚机制、防丢包防失联保护、内网/虚拟接口白名单放行及模块化规则目录;
- 智能 Fail2ban 联动:基于 systemd 日志后端、nftables 封禁动作、自动侦测 SSH 端口及指数递增式渐进封禁(Progressive Banning)。
一、基于 nftables 的模块化防火墙部署h2
架构特性h3
- 防失联保护:交互式运行下自动套入 tmux 会话并启动后台 60 秒看门狗脚本,超时未确认自动回滚原有规则,杜绝因规则错误导致的 SSH 锁死。
- 默认零端口暴露:物理 WAN 接口默认策略为
drop,仅开放核心必要服务。 - 虚拟与容器网络自动放行:内置白名单自动信任 Docker、K3s/Cilium/Flannel、EasyTier (
100.64.0.0/10)、Tailscale、WireGuard 等虚拟接口与私有 LAN 网段 (RFC 1918)。 - 模块化扩展:规则配置由
/etc/nftables.conf自动include /etc/nftables.d/*.conf,便于根据业务需求解耦管理。
部署脚本 (deploy-firewall.sh)h3
#!/usr/bin/env bashset -euo pipefail
# ------------------------------------------------------------------------------# Argument Parsing (-f / --force bypasses interactive confirmation)# ------------------------------------------------------------------------------FORCE_MODE=0for arg in "$@"; do case "$arg" in -f|--force) FORCE_MODE=1 ;; esacdone
# ------------------------------------------------------------------------------# Stage 0: Privilege & tmux Environment Handling# ------------------------------------------------------------------------------if [[ $EUID -ne 0 ]]; then echo "[ERROR] Root privileges required: please run as root or with sudo!" exit 1fi
# Auto-wrap into tmux in interactive mode to survive accidental SSH disconnectionif [[ ${FORCE_MODE} -eq 0 && -t 0 && -z "${TMUX:-}" && "${1:-}" != "inside-tmux" ]]; then if ! command -v tmux >/dev/null 2>&1; then echo "===> [tmux Check] tmux not found. Installing via apt-get..." export DEBIAN_FRONTEND=noninteractive apt-get update -qq && apt-get install -y -qq tmux if ! command -v tmux >/dev/null 2>&1; then echo "[ERROR] Failed to install tmux. Please install it manually." exit 1 fi echo " [*] tmux installed successfully." fi
SESSION_NAME="nft-deploy" tmux kill-session -t "${SESSION_NAME}" 2>/dev/null || true
echo "===> [tmux Wrapper] Launching session: ${SESSION_NAME}..." echo " Notice: If SSH disconnects, run 'tmux a -t ${SESSION_NAME}' to reattach!" sleep 1
SCRIPT_PATH=$(realpath "$0") exec tmux -u new-session -s "${SESSION_NAME}" "bash \"${SCRIPT_PATH}\" inside-tmux; echo 'Press any key to close...'; read -n 1"fi
echo "=========================================================="echo " Debian 13 Modular Firewall Deploy (deploy-firewall.sh)"if [[ ${FORCE_MODE} -eq 1 ]]; then echo " Mode: FORCE (-f) - Confirmation and Watchdog Bypassed"fiecho "=========================================================="
# ------------------------------------------------------------------------------# Stage 1: Pre-flight System & Environment Checks# ------------------------------------------------------------------------------echo "===> [1/5] Running pre-flight system checks..."
# 1. nftables toolchainif ! command -v nft >/dev/null 2>&1; then echo " [INFO] nftables not found. Installing via apt-get..." export DEBIAN_FRONTEND=noninteractive apt-get update -qq && apt-get install -y -qq nftables echo " [*] nftables installed."else NFT_VER=$(nft --version 2>/dev/null | head -n 1) echo " [*] Detected: ${NFT_VER}"fi
# 2. Kernel nf_tables module supportif ! nft list tables >/dev/null 2>&1; then echo " [INFO] Loading kernel module: nf_tables..." modprobe nf_tables 2>/dev/null || true if ! nft list tables >/dev/null 2>&1; then echo "[ERROR] Kernel does not support nf_tables. Aborting!" exit 1 fifiecho " [*] Kernel nf_tables: OK"
# 3. Check conflicting servicesfor CONFLICT_SVC in ufw firewalld; do if systemctl is-active --quiet "${CONFLICT_SVC}" 2>/dev/null; then echo " [WARN] Conflicting firewall active: ${CONFLICT_SVC}!" echo " Recommended: systemctl disable --now ${CONFLICT_SVC}" fidone
# 4. Kernel IPv4 forwardingIP_FORWARD=$(sysctl -n net.ipv4.ip_forward 2>/dev/null || echo 0)if [[ "${IP_FORWARD}" -ne 1 ]]; then echo " [INFO] Enabling IP forwarding: net.ipv4.ip_forward=1" sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true echo "net.ipv4.ip_forward = 1" > /etc/sysctl.d/99-k3s-ipforward.conffiecho " [*] Kernel IP forwarding: OK"
# 5. Display current default routeACTIVE_GW_DEV=$(ip route show default 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i=="dev") print $(i+1)}' | head -n 1 || echo "unknown")echo " [*] Current Default Gateway Device: ${ACTIVE_GW_DEV}"
# ------------------------------------------------------------------------------# Stage 2: Backup & Modular Configuration Creation# ------------------------------------------------------------------------------NFT_CONF="/etc/nftables.conf"NFT_CUSTOM_DIR="/etc/nftables.d"BACKUP_FILE="${NFT_CONF}.bak.$(date +%Y%m%d%H%M%S)"
if [[ -f "${NFT_CONF}" ]]; then cp "${NFT_CONF}" "${BACKUP_FILE}" echo "===> [2/5] Current config backed up to: ${BACKUP_FILE}"fi
mkdir -p "${NFT_CUSTOM_DIR}"# Clean legacy files if upgrading from earlier versionrm -f "${NFT_CUSTOM_DIR}/10-public-services.conf"
echo " [*] Writing 01-base-services.conf (SSH, EasyTier)..."cat <<'CONF_01' > "${NFT_CUSTOM_DIR}/01-base-services.conf"table inet custom_filter { chain manual_wan_input { # Core Infrastructure: SSH tcp dport 22 accept
# EasyTier P2P handshake and tunnel communication tcp dport 11010-11013 accept udp dport 11010-11013 accept }
chain manual_forward { # Public DNAT restrictions (Docker -p / Ingress HostPort from WAN) }}CONF_01
echo " [*] Writing 02-custom-rule.conf (Web Services & Port Forwards)..."cat <<'CONF_02' > "${NFT_CUSTOM_DIR}/02-custom-rule.conf"table inet custom_filter { chain manual_wan_input { # Standard Web Services (HTTP/HTTPS/HTTP3 QUIC) tcp dport { 80, 443, 4443 } accept udp dport 443 accept }
chain manual_forward { # Custom High Ports (Docker / K3s container port forwarding example) # ct status dnat meta l4proto { tcp, udp } ct original proto-dst 10000-20000 accept }}CONF_02
# ------------------------------------------------------------------------------# Stage 3: Generate Base Configuration (Zero Port Allowed by Default)# ------------------------------------------------------------------------------echo "===> [3/5] Generating zero-port-exposure base configuration..."TEMP_CONF=$(mktemp)cat <<'CONFIG' > "${TEMP_CONF}"#!/usr/sbin/nft -f
destroy table inet custom_filter
table inet custom_filter { # 1. Standard RFC 1918 Private IPv4 Subnets (trusted LANs) set private_lan_v4 { type ipv4_addr flags interval elements = { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 } }
# 2. Local/ULA Private IPv6 Subnets set private_lan_v6 { type ipv6_addr flags interval elements = { fc00::/7, fe80::/10 } }
# Modular Hook Chains (Populated exclusively by /etc/nftables.d/*.conf) chain manual_wan_input { }
chain manual_forward { }
# WAN / Physical Interface Inbound Security Chain chain wan_input { # Anti-Spoofing: Drop spoofed EasyTier virtual subnets arriving via physical interfaces ip saddr 100.64.0.0/10 drop
# Allow DHCP client lease negotiation and renewal (essential for cloud VMs) udp sport 67 udp dport 68 accept
# Full port access for verified physical LAN devices ip saddr @private_lan_v4 accept ip6 saddr @private_lan_v6 accept
# Modular Custom Ports Hook (SSH, EasyTier, Web, High-ports injected here) jump manual_wan_input
# Default Drop: No public port is opened in this base table drop }
chain input { type filter hook input priority filter; policy drop;
# Connection state tracking: allow established & related packets ct state established,related accept ct state invalid drop
# Allow ICMP / ICMPv6 (ping, path MTU discovery, IPv6 neighbor discovery) ip protocol icmp accept ip6 nexthdr icmpv6 accept
# Loopback interface: full trust iifname "lo" accept
# Virtual & Overlay Interface Whitelist (Split to avoid Linux kernel ASCII interval merge bug) iifname { "es*", "tailscale*", "tap*", "tun*", "wg*", "zt*" } accept iifname { "br-*", "docker*", "nerdctl*", "podman*" } accept iifname { "cali*", "cilium*", "cni*", "dummy*", "flannel*", "kube-ipvs*" } accept iifname { "incus*", "lxc*", "virbr*" } accept iifname "lxd*" accept iifname "veth*" accept
# Any interface not matched above is treated as external/physical WAN jump wan_input }
chain forward { type filter hook forward priority filter - 1; policy drop;
ct state established,related accept ct state invalid drop
# 1. 内部虚拟网络互转放行 iifname { "es*", "tailscale*", "tap*", "tun*", "wg*", "zt*" } accept iifname { "br-*", "docker*", "nerdctl*", "podman*" } accept iifname { "cali*", "cilium*", "cni*", "dummy*", "flannel*", "kube-ipvs*" } accept iifname { "incus*", "lxc*", "virbr*" } accept iifname "lxd*" accept iifname "veth*" accept
# 2. 放行物理局域网设备对所有容器映射端口的访问 ip saddr @private_lan_v4 accept ip6 saddr @private_lan_v6 accept
# 3. Modular Custom Forward Hook (Container DNAT port forwards injected here) jump manual_forward
# Default Drop: No public port forward is allowed by default drop }
chain output { type filter hook output priority filter; policy accept; }}
# Include all modular rulesinclude "/etc/nftables.d/*.conf"CONFIG
# ------------------------------------------------------------------------------# Stage 4: Syntax Verification# ------------------------------------------------------------------------------echo "===> [4/5] Checking rule syntax..."if ! nft -c -f "${TEMP_CONF}"; then echo "[ERROR] nftables syntax check failed. Aborting!" rm -f "${TEMP_CONF}" exit 1fi
cp "${TEMP_CONF}" "${NFT_CONF}"rm -f "${TEMP_CONF}"
# ------------------------------------------------------------------------------# Stage 5: Execution, Watchdog & Persistence# ------------------------------------------------------------------------------if [[ ${FORCE_MODE} -eq 1 ]]; then echo "===> [5/5] Applying rules directly (-f flag detected)..." nft -f "${NFT_CONF}" systemctl enable --now nftables >/dev/null 2>&1 echo "" echo "[SUCCESS] Configuration applied and enabled on boot (forced mode)!" echo "--- Active Hook: manual_wan_input ---" nft list chain inet custom_filter manual_wan_input echo "--- Active Hook: manual_forward ---" nft list chain inet custom_filter manual_forward exit 0fi
# Interactive mode: Start 60-second watchdogWATCHDOG_SCRIPT=$(mktemp /tmp/nft-watchdog-XXXXXX.sh)cat <<WATCHDOG > "${WATCHDOG_SCRIPT}"#!/usr/bin/env bashsleep 60echo "[FIREWALL WATCHDOG] 60s timeout without confirmation. Rolling back..." > /dev/kmsg 2>/dev/null || truenft delete table inet custom_filter 2>/dev/null || trueif [[ -f "${BACKUP_FILE}" ]]; then cp -f "${BACKUP_FILE}" "${NFT_CONF}" nft -f "${NFT_CONF}" 2>/dev/null || truefilogger -t nft-watchdog "60s confirmation timeout. Reverted to backup firewall rules."rm -f "${WATCHDOG_SCRIPT}"WATCHDOGchmod +x "${WATCHDOG_SCRIPT}"
nohup "${WATCHDOG_SCRIPT}" >/dev/null 2>&1 &WATCHDOG_PID=$!
echo "===> [5/5] Loading rules with 60s watchdog protection (Watchdog PID: ${WATCHDOG_PID})..."
set +enft -f "${NFT_CONF}"APPLY_STATUS=$?set -e
if [[ ${APPLY_STATUS} -ne 0 ]]; then echo "[ERROR] Failed to apply rules! Reverting immediately..." kill "${WATCHDOG_PID}" 2>/dev/null || true "${WATCHDOG_SCRIPT}" exit 1fi
echo "--------------------------------------------------------"echo " [SAFETY CHECK] Firewall rules temporarily active!"echo " Running inside tmux session: rules auto-revert in 60s."echo " Test SSH access and services from a separate terminal."echo " Press [Enter] or type [y/yes] to persist; timeout will revert."echo "--------------------------------------------------------"
set +eread -t 60 -r -p "Keep this configuration? [Y/n] (Timeout in 60s): " USER_INPUTREAD_STATUS=$?set -e
if [[ ${READ_STATUS} -eq 0 && ( -z "${USER_INPUT}" || "${USER_INPUT}" =~ ^[Yy]([Ee][Ss])?$ ) ]]; then kill "${WATCHDOG_PID}" 2>/dev/null || true rm -f "${WATCHDOG_SCRIPT}" systemctl enable --now nftables >/dev/null 2>&1 echo "" echo "[SUCCESS] Configuration saved and enabled on boot!" echo "--- Active Hook: manual_wan_input ---" nft list chain inet custom_filter manual_wan_input echo "--- Active Hook: manual_forward ---" nft list chain inet custom_filter manual_forward exit 0else echo "" echo "[WARN] Confirmation canceled or timed out. Reverting rules..." kill "${WATCHDOG_PID}" 2>/dev/null || true "${WATCHDOG_SCRIPT}" echo "[OK] Successfully reverted to backup firewall rules." exit 1fi运行方式h3
chmod +x deploy-firewall.sh
# 推荐:交互模式(自动开启 60 秒看门狗回滚机制,超时不确认自动恢复备份)sudo ./deploy-firewall.sh
# 自动化/非交互模式:直接应用并持久化(绕过看门狗)sudo ./deploy-firewall.sh -f二、基于 Fail2ban 的防暴力破解配置h2
架构特性h3
- 适配 Debian 13 原生日志:采用
backend = systemd,无需额外安装或依赖 syslog/rsyslog。 - 与 nftables 原生协同:通过
nftables-multiport封禁动作,直接在内核态快速丢弃恶意扫描报文。 - 动态探测 SSH 端口:自动检测
sshd进程实际监听的端口,避免固定 22 端口导致的失效问题。 - 智能白名单:默认放行回环地址、RFC 1918 私网网段与 EasyTier Mesh 子网 (
100.64.0.0/10),杜绝内网管理机误封。 - 指数渐进式封禁:启用
bantime.increment,随着攻击次数增加封禁时长呈指数上升,最长可自动封禁 4 周。
部署脚本 (deploy-fail2ban.sh)h3
#!/usr/bin/env bashset -euo pipefail
# ------------------------------------------------------------------------------# Argument Parsing (-f / --force for non-interactive execution)# ------------------------------------------------------------------------------FORCE_MODE=0for arg in "$@"; do case "$arg" in -f|--force) FORCE_MODE=1 ;; esacdone
echo "=========================================================="echo " Debian 13 Fail2ban Deployment (deploy-fail2ban.sh)"if [[ ${FORCE_MODE} -eq 1 ]]; then echo " Mode: FORCE (-f) - Non-interactive Execution"fiecho "=========================================================="
# ------------------------------------------------------------------------------# Phase 1: Pre-flight Environment & State Inspection (READ-ONLY)# ------------------------------------------------------------------------------echo "===> [1/4] Running pre-flight environment checks..."
# 1. Check Root Privilegesif [[ $EUID -ne 0 ]]; then echo "[ERROR] Pre-flight failed: root privileges required!" exit 1fiecho " [*] Privilege: root (OK)"
# 2. Check Init System (Debian 13 fail2ban journal backend requires systemd as PID 1)if [[ ! -d /run/systemd/system ]]; then echo "[ERROR] Pre-flight failed: systemd is not running as PID 1." echo " Cannot use 'backend = systemd' in this environment (e.g., bare container)." exit 1fiecho " [*] Init System: systemd active (OK)"
# 3. Check Package Managerif ! command -v apt-get >/dev/null 2>&1; then echo "[ERROR] Pre-flight failed: 'apt-get' not found. This script is intended for Debian/Ubuntu." exit 1fiecho " [*] Package Manager: apt-get available (OK)"
# 4. Check Kernel & nftables Readinessif ! command -v nft >/dev/null 2>&1; then echo " [WARN] nftables command not found; will be installed in Phase 2."else if ! nft list tables >/dev/null 2>&1; then modprobe nf_tables 2>/dev/null || true if ! nft list tables >/dev/null 2>&1; then echo "[ERROR] Pre-flight failed: Kernel lacks nf_tables support or running in unprivileged container!" exit 1 fi fi echo " [*] Firewall Engine: nftables kernel support verified (OK)"fi
# 5. Detect Actual SSH Listening Ports (Do not assume port 22 blindly)DETECTED_SSH_PORTS=$(ss -tlnp 2>/dev/null | grep -E 'sshd' | awk '{print $4}' | grep -oE '[0-9]+$' | sort -nu | tr '\n' ',' | sed 's/,$//' || true)
if [[ -z "${DETECTED_SSH_PORTS}" ]]; then DETECTED_SSH_PORTS=$(sshd -T 2>/dev/null | grep -E '^port ' | awk '{print $2}' || true)fi
SSH_TARGET_PORT="${DETECTED_SSH_PORTS:-22}"echo " [*] Target SSH Port(s): ${SSH_TARGET_PORT}"
echo "===> All pre-flight checks passed successfully!"
# ------------------------------------------------------------------------------# Phase 2: Dependency Remediation (Install ONLY what is missing)# ------------------------------------------------------------------------------echo "===> [2/4] Verifying and installing required packages..."MISSING_PKGS=()
for pkg in fail2ban python3-systemd nftables; do if ! dpkg -s "${pkg}" >/dev/null 2>&1; then MISSING_PKGS+=("${pkg}") fidone
if [[ ${#MISSING_PKGS[@]} -gt 0 ]]; then echo " [*] Missing packages detected: ${MISSING_PKGS[*]}" echo " [*] Updating package cache and installing..." export DEBIAN_FRONTEND=noninteractive apt-get update -qq apt-get install -y -qq "${MISSING_PKGS[@]}" echo " [*] Package installation completed."else echo " [*] All dependencies already satisfied. Skipping apt-get."fi
# ------------------------------------------------------------------------------# Phase 3: Write Tailored Fail2ban Configuration# ------------------------------------------------------------------------------echo "===> [3/4] Generating configuration based on detected environment..."
rm -f /etc/fail2ban/jail.d/00-custom.local /etc/fail2ban/jail.d/defaults-debian.conf
cat <<CONFIG > /etc/fail2ban/jail.d/00-custom.local[DEFAULT]# Logging Backend: Systemd Journal (Native Debian 13)backend = systemd
# Firewall Actions: Native nftables backend (creates dedicated f2b-table in nftables)banaction = nftables-multiportbanaction_allports = nftables-allports
# Whitelist: Localhost, RFC1918 Private LANs, and EasyTier Mesh Subnet (100.64.0.0/10)ignoreip = 127.0.0.1/8 ::1 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10
# Base Ban Parametersfindtime = 10mmaxretry = 5bantime = 1h
# Progressive Banning (Exponentially increase ban time for persistent scanners)bantime.increment = truebantime.factor = 2bantime.formula = ban.Time * (1<<(ban.Count if ban.Count<20 else 20)) * (banner_opt_factor if banner_opt_factor else 1)bantime.maxtime = 4w
# ------------------------------------------------------------------------------# Jails# ------------------------------------------------------------------------------
[sshd]enabled = trueport = ${SSH_TARGET_PORT}mode = aggressiveCONFIG
# ------------------------------------------------------------------------------# Phase 4: Service Initialization & Post-Flight Health Verification# ------------------------------------------------------------------------------echo "===> [4/4] Starting fail2ban and verifying runtime health..."systemctl enable --now fail2ban >/dev/null 2>&1systemctl restart fail2ban
READY=0for i in {1..5}; do if fail2ban-client ping >/dev/null 2>&1; then READY=1 break fi sleep 1done
if [[ ${READY} -eq 0 ]]; then echo "[ERROR] fail2ban-server failed to respond via socket." journalctl -u fail2ban -n 20 --no-pager exit 1fi
echo ""echo "--- Runtime Status Summary ---"fail2ban-client status sshd
echo ""echo "[SUCCESS] deploy-fail2ban.sh completed safely and successfully!"运行方式与状态检查h3
chmod +x deploy-fail2ban.sh
# 一键安装并启动sudo ./deploy-fail2ban.sh -f
# 查看 sshd 防护 jail 运行状态与当前被封禁的 IPsudo fail2ban-client status sshd
# 手动解封误封的 IP(如需)sudo fail2ban-client set sshd unbanip <IP_ADDRESS>