CentOS 8防火墙配置:彻底禁用firewalld后如何持久化nftables规则


阅读 3 次

从iptables到nftables的转变

在CentOS 7时代,我们习惯直接编写iptables规则来管理防火墙。但CentOS 8开始,默认防火墙后端已从iptables迁移到nftables。虽然iptables命令仍然可用,但实际上它只是nftables的前端兼容层。

firewalld与nftables的关系

firewalld作为动态防火墙管理器,在CentOS 8中默认使用nftables作为其后端。它会自动加载自己的规则集,这就是为什么我们手动配置的nftables规则会在重启后失效的原因。

完全禁用firewalld的解决方案

如果你像我一样更喜欢直接管理nftables,可以完全禁用firewalld:

# 停止并禁用firewalld
systemctl stop firewalld
systemctl disable firewalld

# 启用nftables服务
systemctl enable nftables
systemctl start nftables

nftables规则持久化配置

确保你的规则在/etc/nftables.conf中正确配置,这是nftables服务启动时自动加载的文件。例如:

#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0;
        
        # 允许本地回环
        iif "lo" accept
        
        # 允许已建立的连接
        ct state established,related accept
        
        # 允许SSH
        tcp dport 22 accept
        
        # 默认拒绝策略
        drop
    }
}

验证规则是否生效

重启后,使用以下命令检查规则是否加载:

nft list ruleset

替代方案:与firewalld共存

如果你不想完全禁用firewalld,可以通过以下方式让两者共存:

# 在firewalld配置文件中添加直接规则
vim /etc/firewalld/direct.xml

<direct>
    <rule ipv="filter" table="filter" chain="INPUT" priority="0">-p tcp --dport 8080 -j ACCEPT</rule>
</direct>

然后重启firewalld服务:

systemctl restart firewalld

性能考量

直接使用nftables相比firewalld会有轻微的性能优势,因为减少了抽象层。但在大多数场景下,这种差异可以忽略不计。

管理复杂度对比

firewalld提供了更高级的抽象和区域概念,适合需要动态调整防火墙规则的场景。而直接使用nftables则更适合需要精细控制规则的场景。