Ubuntu UFW防火墙启用NAT共享上网

Ufw firewall enable nat shared Internet access

Posted by BlueFat on Thursday, March 23, 2023

环境信息

内网

  • 网卡接口: ens160
  • 网段: 192.168.77.0/24
  • IP: 192.168.77.1 外网
  • 网卡接口: ens160

打开内核转发

echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p

启动nat转发测试

非持久化

# 启动
# 适用动态IP 自动转成网卡IP地址
iptables -t nat -A POSTROUTING -o ens192 -j MASQUERADE
# 适用静态IP
# iptables -t nat -A POSTROUTING -s 192.168.77.0/24 -j SNAT --to 119.38.120.1

# 默认是filter 可不加 -t filter
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -s 192.168.77.0/24 -j ACCEPT

上面FORWARD转发有偷懒方法 但不推荐

vim /etc/default/ufw
DEFAULT_FORWARD_POLICY="ACCEPT" # 修改默认所有允许,不安全

删除nat转发

iptables -t nat -D POSTROUTING -o ens192 -j MASQUERADE
iptables -D FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -D FORWARD -s 192.168.77.0/24 -j ACCEPT
# 或者
iptables -t nat -F
iptables -F FORWARD

ubuntu持久化配置

vim /etc/ufw/before.rule

# rules.before
#
# Rules that should be run before the ufw command line added rules. Custom
# rules should be added to one of these chains:
#   ufw-before-input
#   ufw-before-output
#   ufw-before-forward
#

# snat 
*nat
:POSTROUTING ACCEPT [0:0]

# allow lan access Internet
-A POSTROUTING -s 192.168.77.0/24 -o ens192 -j MASQUERADE

# Don't delete the 'COMMIT' line or these rules won't be processed
COMMIT

# Don't delete these required lines, otherwise there will be errors
*filter
:ufw-before-input - [0:0]
:ufw-before-output - [0:0]
:ufw-before-forward - [0:0]
:ufw-not-local - [0:0]
# End required lines

# allow lan forward nat
-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
-A FORWARD -s 192.168.77.0/24 -j ACCEPT
...

注意贴入位置

  • *nat 需放置于*filter之前
  • COMMIT 是必须的

ufw 启用规则

ufw disable
ufw enable

其他服务器上网修改

其他需要上网的服务器的网关 指向 这台nat转发服务器IP即可上网。

修改默认网关,可以使用route (推荐,需装net-tools) 或者ip route 命令进行修改添加默认网关 进行测试(非永久)

启用

# ip route add default via 192.168.77.1 dev ens160 
route add default gw 192.168.77.1 # nat网关内网ip (推荐)

删除

# ip route delete default
route delete default