nftables做DNAT转发

一.使用防火墙nftables做转发

1. 开启转发功能

sudo sysctl -w net.ipv4.ip_forward=1

  

2. 永久开启转发功能

vim /etc/sysctl.conf
添加
net.ipv4.ip_forward=1

  

3.编辑nftables脚本进行转发

编辑配置文件/etc/nftables.conf

#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0;
        iifname "lo" accept
        ct state { established, related } accept
        ip saddr 192.168.206.0/24 tcp dport 22 ct state { new, untracked } accept
        ip saddr 192.168.206.0/24 tcp dport 3389 ct state { new, untracked } accept
        ct state invalid drop
        reject with icmpx type admin-prohibited
    }
    chain forward {
        type filter hook forward priority 0;
    }
    chain output {
        type filter hook output priority 0;
    }
}

table ip nat {
    chain prerouting {
        type nat hook prerouting priority -100;
        tcp dport 22222 dnat to 192.168.206.26:22
        tcp dport 13306 dnat to 192.168.206.26:3306

    }

    chain postrouting {
        type nat hook postrouting priority 100;
        ip saddr 192.168.206.24 masquerade
    }
}

  

4.开启防火墙nftables,应用转发功能

1. 开启nftables

sudo systemctl restart nftables.service

2.开启开机自启动

sudo systemctl enable nftables.service

 

 

二. 解析nftables脚本

#!/usr/sbin/nft -f

flush ruleset
# 过滤表:对主机或网段开放端口(看需求,可不使用)
table inet filter {
    chain input {
        type filter hook input priority 0;
        iifname "lo" accept
        ct state { established, related } accept
        #对192.168.206,0网段开放端口22
        ip saddr 192.168.206.0/24 tcp dport 22 ct state { new, untracked } accept
        #对192.168.206,0网段开放端口3389
        ip saddr 192.168.206.0/24 tcp dport 3389 ct state { new, untracked } accept
        ct state invalid drop
        reject with icmpx type admin-prohibited
    }
    chain forward {
        type filter hook forward priority 0;
    }
    chain output {
        type filter hook output priority 0;
    }
}

#转发表
table ip nat {
    chain prerouting {
        type nat hook prerouting priority -100;
        #转发22222端口到192.168.206.26的22端口
        tcp dport 22222 dnat to 192.168.206.26:22
        #转发13306端口到192.168.206.26的3306端口
        tcp dport 13306 dnat to 192.168.206.26:3306

    }
#链:返回用
    chain postrouting {
        type nat hook postrouting priority 100;
        #只允许主机192.168.206.24访问这些转发端口
        ip saddr 192.168.206.24 masquerade
    }
}


###如果想运行所有主机访问转发端口,修改链如下:
    chain postrouting {
        type nat hook postrouting priority 100;
        #只允许所有主机访问这些转发端口
         masquerade
    }

  

三.参考链接

https://hostalk.net/posts/nftables_forward.html

https://farkasity.gitbooks.io/nftables-howto-zh/content/chapter1/what_is_nftables.html

https://www.arloor.com/posts/centos8-nftables-nat/#%E6%89%A7%E8%A1%8C%E8%84%9A%E6%9C%AC

 

posted @ 2025-06-04 21:03  铿锵有力自信且坚定  阅读(128)  评论(0)    收藏  举报