目录

Nftables简单配置

虽然可以按部就班的敲命令, 但是我觉得直接编辑nftables的默认配置文件更快一些, 而且因为nftables.service启动时会自动加载默认配置文件, 这样相当于使规则持久化, 不用担心nftables.service停止时清空规则导致规则丢失。

nftables默认配置文件一般是/etc/nftables.conf, 但是还是确定一下情况比较放心, 毕竟考虑到系统不同或版本不同, 默认配置文件还有可能是/etc/nftables.start.conf, 或者其他。

参考nftables官方文档Advanced ruleset for dynamic environments, nftables默认配置文件的路径可以通过查看nftables.service文件得知, 但使用find /etc -name "nftables.service"搜索后发现我的Debian 11中nftables.service文件的路径并不是/etc/systemd/system/nftables.service, 而是/etc/systemd/system/sysinit.target.wants/nftables.service, 文件内容中注意到以下三行:

...
ExecStart=/usr/sbin/nft -f /etc/nftables.conf
ExecReload=/usr/sbin/nft -f /etc/nftables.conf
ExecStop=/usr/sbin/nft flush ruleset
...

nftables.service启动和重载时都加载/etc/nftables.conf文件, 停止时清空规则。

参考nftables官方文档Simple ruleset for a server, 将/etc/nftables.conf文件更改为以下内容:

flush ruleset

table inet firewall {
    chain input {
        type filter hook input priority 0; policy drop;
        # 允许回环接口
        iif lo accept
        # 状态检查
        ct state invalid drop
        ct state { established, related } accept
        # 反欺骗检查
        fib saddr . iif oif missing drop
        # 允许特定 TCP/UDP 端口
        tcp dport { 80, 443, 50022 } accept
        udp dport 443 accept
        # ICMP 处理
        meta protocol vmap { ip : jump input_ipv4, ip6 : jump input_ipv6 }
    }

    chain input_ipv4 {
        # 允许 Ping
        icmp type echo-request limit rate 5/second burst 10 packets accept
        # 允许路径 MTU 发现
        icmp type { destination-unreachable, time-exceeded, parameter-problem } accept
    }

    chain input_ipv6 {
        # 允许 Ping
        icmpv6 type echo-request limit rate 5/second burst 10 packets accept
        # 允许 IPv6 邻居发现
        icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert } ip6 hoplimit 255 accept
        # 允许路径 MTU 发现
        icmpv6 type { packet-too-big, destination-unreachable, time-exceeded, parameter-problem } accept
    }

    chain forward {
        type filter hook forward priority 0; policy drop;
    }

    chain output {
        type filter hook output priority 0; policy accept;
    }
}

重启nftables.service服务:

systemctl restart nftables.service

检查nftables当前应用的规则:

nft list ruleset