nftables 防火墙的详细使用示例
涵盖基础规则配置、NAT、端口转发、访问控制等核心操作:
二、nftables 防火墙 (现代替代工具)
1. 基础规则管理
查看规则集
nft list ruleset # 显示所有规则
清除规则
nft flush ruleset # 清空所有规则
2. 创建表与链
# 创建 filter 表和 input/output 链
nft add table inet filter
nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }
nft add chain inet filter output { type filter hook output priority 0 \; policy accept \; }
3. 定义规则
允许特定流量
# 允许 SSH(链式语法)
nft add rule inet filter input tcp dport 22 ct state new,established accept
# 允许来自特定 IP 的 HTTP
nft add rule inet filter input ip saddr 192.168.1.100 tcp dport 80 accept
# 允许环回接口流量
nft add rule inet filter input iif "lo" accept
阻止流量
# 阻止 ICMP(按协议)
nft add rule inet filter input meta l4proto icmp drop
# 阻止 IP 范围
nft add rule inet filter input ip saddr 10.0.0.0/24 drop
4. NAT 与端口转发
共享网络(MASQUERADE)
nft add table nat
nft add chain nat postrouting { type nat hook postrouting priority 100 \; }
nft add rule nat postrouting oif eth0 masquerade
端口转发(DNAT)
nft add chain nat prerouting { type nat hook prerouting priority -100 \; }
nft add rule nat prerouting iif eth0 tcp dport 8080 dnat to 192.168.1.10:80
nft add rule inet filter forward ip daddr 192.168.1.10 tcp dport 80 accept
5. 规则持久化
# 备份当前规则
nft list ruleset > /etc/nftables.conf
# 开机自动加载
systemctl enable nftables