温馨提示×

Debian Dopra如何设置防火墙

小樊
44
2025-12-30 18:09:14
栏目: 智能运维

Debian 防火墙设置指南

说明与准备

  • 你提到的“Debian Dopra”应为Debian 系统。Debian 默认不预装防火墙,常用方案有:UFW(上手简单)、iptables(传统工具)、nftables(新一代)。以下按这三种方式给出可直接执行的步骤。操作前建议先备份现有规则,并在变更前确保可通过控制台/带外访问,避免被锁在外面。

方案一 UFW 快速配置

  • 安装与启用
    • 安装:sudo apt update && sudo apt install ufw
    • 允许 SSH(务必在启用前放行,防止断连):sudo ufw allow OpenSSHsudo ufw allow 22/tcp
    • 启用:sudo ufw enable
  • 常用规则
    • 放行 HTTP/HTTPS:sudo ufw allow 80/tcpsudo ufw allow 443/tcp
    • 放行端口区间:sudo ufw allow 8090:9090/tcp
    • 按来源 IP/网段放行:sudo ufw allow from 203.0.113.10 to any port 22sudo ufw allow from 192.168.1.0/24
    • 按网卡放行:sudo ufw allow in on eth1 to any port 3306
    • 拒绝来源:sudo ufw deny from 198.51.100.0/24
  • 管理与查看
    • 状态与编号:sudo ufw status verbosesudo ufw status numbered
    • 删除规则:sudo ufw delete 3sudo ufw delete allow 3306/tcp
    • 禁用/重置:sudo ufw disablesudo ufw reset
  • 提示:UFW 在启用前不会自动放行 SSH,务必先执行放行命令再启用。

方案二 iptables 配置

  • 安装与查看
    • 安装:sudo apt update && sudo apt install iptables
    • 查看:sudo iptables -L -n -v
  • 基础规则模板(按需调整)
    • 放行回环与已建立连接:sudo iptables -A INPUT -i lo -j ACCEPTsudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
    • 放行 SSH/HTTP/HTTPS:sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPTsudo iptables -A INPUT -p tcp --dport 80 -j ACCEPTsudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    • 默认策略(谨慎):sudo iptables -P INPUT DROPsudo iptables -P FORWARD DROPsudo iptables -P OUTPUT ACCEPT
  • 持久化
    • Debian 10/11 常用:sudo apt install iptables-persistent,安装时选择保存当前规则;后续可用 sudo systemctl restart netfilter-persistent 重载
    • 通用导出/导入:sudo iptables-save > /etc/iptables/rules.v4,开机恢复可用 systemd 服务或 /etc/rc.local 执行 iptables-restore < /etc/iptables/rules.v4
  • 提示:设置默认丢弃策略前,务必确保已放行 SSH,以免失联。

方案三 nftables 配置

  • 安装与查看
    • 安装:sudo apt update && sudo apt install nftables
    • 查看:sudo nft list ruleset
  • 基础规则模板
    • 创建表与链:sudo nft add table inet my_tablesudo nft add chain inet my_table my_input '{ type filter hook input priority 0; policy drop; }'
    • 放行回环/已建立:sudo nft add rule inet my_table my_input iif lo acceptsudo nft add rule inet my_table my_input ct state established,related accept
    • 放行 SSH/HTTP/HTTPS:sudo nft add rule inet my_table my_input tcp dport 22 acceptsudo nft add rule inet my_table my_input tcp dport 80 acceptsudo nft add rule inet my_table my_input tcp dport 443 accept
  • 持久化与开机加载
    • 导出:sudo nft list ruleset > /etc/nftables.conf
    • 开机加载:sudo systemctl enable nftables(确保 /etc/nftables.conf 包含你的规则)
  • 提示:nftables 为新系统推荐方案,语法更简洁,性能更好。

通用安全与排错建议

  • 安全原则
    • 默认拒绝入站、按需放行;限制敏感端口(如数据库、管理口)仅对受控来源开放;必要时按网卡/网段细化策略。
  • 日志与限速
    • 记录被丢弃包:sudo iptables -A INPUT -j LOG --log-prefix "DROPPED: "
    • 限制新连接速率(防暴力):sudo iptables -A INPUT -p tcp --syn -m limit --limit 1/s -j ACCEPT
  • 排错要点
    • 核对服务实际监听端口与协议:ss -tulpen | grep -E '(:22|:80|:443)'
    • 核对规则顺序与默认策略;UFW 可用 status numbered 精确定位;iptables/nftables 用 -L -v -n/list ruleset 检查命中计数与策略。

0