本页目录
nftables 操作手册
nftables 是 Linux 下一代防火墙框架,替代 iptables/ip6tables/arptables/ebtables。使用 nft 命令管理,配置可原子性加载。Gentoo 上内核需开启 CONFIG_NF_TABLES 及相关模块。
核心概念: table (namespace, 按 family 分组), chain (规则容器, 分 type/hook/priority), rule (匹配+动作), set (IP/端口集合), verdict (accept/drop/reject/跳转)。
状态查看
# 列出所有规则
# 按表/链查看
# 查看 sets / counters
# 规则集统计
|
基础规则管理
# 临时修改 (重启丢失, 用于测试)
# 查看 handle
# 输出: tcp dport 22 accept # handle 5
持久化与原子加载
# 保存当前规则集
# 原子性替换 (推荐)
# 检查语法 (不加载)
# systemd 自动加载
常用表/链结构模板
table inet filter { # inet = IPv4 + IPv6
chain input {
type filter hook input priority 0; policy drop;
# 允许 lo
iif lo accept
# 允许已建立/相关连接
ct state established,related accept
# 允许 SSH
tcp dport 22 accept
# 允许 ICMPv6 (IPv6 必需)
ip6 nexthdr icmpv6 accept
}
chain forward {
type filter hook forward priority 0; policy drop;
ct state established,related accept
}
chain output {
type filter hook output priority 0; policy accept;
}
}
规则写法
# 匹配
# 动作
# 从自定义链返回
NAT / 端口转发
# 表定义
# DNAT (端口转发, 外→内)
# SNAT (出口统一 IP)
# MASQUERADE (动态 IP 出口, 如 DHCP 接口)
# 端口重定向 (本机 80 → 8080)
Sets (集合, 高效批量匹配)
# 定义命名集合
# 或在配置文件中:
# set blackhole { type ipv4_addr; }
# 动态添加/删除元素
# 在规则中使用
# ip saddr @blackhole drop
# 带超时的集合 (自动过期)
# set ratelimit { type ipv4_addr; timeout 1h; }
# ip saddr @ratelimit counter drop
# 集合类型:
# ipv4_addr / ipv6_addr IP 地址
# ipv4_addr . inet_service IP+端口组合
# ifname 接口名
# mark 连接标记
运维操作
# 插入规则到指定位置 (默认 append)
# 替换规则
# 规则注释
# 在文件中: tcp dport 22 accept comment "SSH access"
# 计数器清零
# 实时监控
# 调试
常见场景
# 防 SSH 爆破 (限制新连接速率)
# tcp dport 22 ct state new limit rate 4/minute accept
# tcp dport 22 ct state new drop
# 只允许特定 IP 访问某端口
# ip saddr {10.0.0.1, 10.0.0.2} tcp dport 5432 accept
# tcp dport 5432 drop
# 透明代理 (TPROXY, 需配合 mihomo/v2ray)
# table ip mangle {
# chain prerouting { type filter hook prerouting priority mangle; }
# }
# meta l4proto tcp ip daddr != 127.0.0.0/8 tproxy to :12345
# Docker 用户注意
# Docker 会插入自己的 iptables 规则, 与 nftables 混用可能乱序。
# 建议: 要么只用 iptables (Docker 兼容模式), 要么确保 nftables 规则在 Docker 之前加载
# 检查: nft list ruleset | grep -i docker
# Docker 的 nftables 支持: /etc/docker/daemon.json → "iptables": false
迁移备忘 (iptables → nft)
# 查看当前 iptables 规则
# 自动翻译 (不完美, 只能做参考)
# 输出: nft add rule ip filter INPUT tcp dport 22 counter accept
# 批量翻译 (完整规则集)