跳至正文

[教程]使用UFW为多张网卡提供完全不同的规则

UFW基本工作方式

UFW在识别到连接后依次匹配规则,如果发现了对应规则,则按照规则给定的做法进行下一步操作,以此类推。
虚拟网卡(dummy)似乎并不能直接通过UFW管控,所以需要通过限制访问虚拟网卡IP地址上的端口的方式进行处理。

你可能会发现:当你通过UFW拒绝某个IP发的包后,这个IP还能正常连接,正是因为这个原因,所以ban IP的时候要ufw insert,直接输入可能会卡在IPv4规则和IPv6规则之间。(扯远了)

设置思路

既然我们知道了UFW的工作方式,那么我们就能通过不断的insert来为各个网卡分出他们的规则,并在该网卡规则的最后加上禁止所有端口入站的规则,这样我们就能划分出完全不同的规则。

例如:

[1]80/tcp (v6) on eth1    ALLOW IN     Anywhere/tcp (v6)        #允许访问eth1的80端口
[2]443/tcp (v6) on eth1    ALLOW IN     Anywhere/tcp (v6)       #允许访问eth1的443端口
[3]Anywhere/tcp (v6) on eth1    DENY IN     Anywhere/tcp (v6)   #拒绝访问eth1的所有端口
[4]25/tcp (v6) on eth2    ALLOW IN     Anywhere/tcp (v6)        #允许访问eth2的25端口
[5]587/tcp (v6) on eth2    ALLOW IN     Anywhere/tcp (v6)       #允许访问eth2的587端口
[6]Anywhere/tcp (v6) on eth2    DENY IN     Anywhere/tcp (v6)   #拒绝访问eth2的所有端口

这时如果有IP尝试访问eth1的80端口,第一个条件与其匹配,则通过,但是如果访问eth1的25端口,因为第一项与第二项不是允许25端口,则匹配第三条规则,则拒绝访问
如果该IP访问eth2的25端口,因为1-3的适用前提是通向eth1的网卡的连接,所以前三项对此连接无效,从第四项匹配起,因为第四项与其匹配,则通过

制作方法

假设我们有3张网卡,名字分别为eth1, eth2, eth3

我想给eth1允许80 443 1234 TCP端口和53 UDP端口,eth2允许25 110 143 587 TCP端口,eth3允许3306 3389 TCP与UDP端口

ufw enable              #打开UFW
ufw status numbered     #查看目前规则状态并列出对应行数

先写eth1的规则

sudo ufw allow in on eth1 proto udp from any to any port 53        #允许外部连接至eth1的53端口
sudo ufw allow in on eth1 proto tcp from any to any port 80        #允许外部连接至eth1的80端口
sudo ufw allow in on eth1 proto tcp from any to any port 443       #允许外部连接至eth1的443端口
sudo ufw allow in on eth1 proto tcp from any to any port 1234      #允许外部连接至eth1的1234端口
sudo ufw deny in on eth1 proto tcp from any to any                 #禁止所有TCP连接通过eth1
sudo ufw deny in on eth1 proto udp from any to any                 #禁止所有UDP连接通过eth1
sudo ufw status numbered         #显示防火墙规则

再写eth2的规则

sudo ufw allow in on eth2 proto tcp from any to any port 25
sudo ufw allow in on eth2 proto tcp from any to any port 110
sudo ufw allow in on eth2 proto tcp from any to any port 143
sudo ufw allow in on eth2 proto tcp from any to any port 587
sudo ufw deny in on eth2 proto tcp from any to any                 
sudo ufw deny in on eth2 proto udp from any to any                 
ufw status numbered

eth3的规则

sudo ufw allow in on eth3 proto tcp from any to any port 3306
sudo ufw allow in on eth3 proto udp from any to any port 3306
sudo ufw allow in on eth3 proto tcp from any to any port 3389
sudo ufw allow in on eth3 proto udp from any to any port 3389
sudo ufw deny in on eth3 proto tcp from any to any                 
sudo ufw deny in on eth3 proto udp from any to any    
ufw status numbered

为了方便,我把网卡名字修改成了ens33, ens38, ens39,ens33对应eth1,ens38对应eth2,ens39对应eth3。
现在ens33的IP为192.168.0.220,ens38的IP为192.168.0.221,ens39的IP为192.168.0.222

验证可用性

我们使用一台Windows主机模拟外网IP访问

我们使用了tcping来测试端口是否开启

这时,模拟外网访问80端口时符合ens33 (192.168.0.220)的规则,允许连接

这时,模拟外网访问80端口时不符合ens33 (192.168.0.220)的规则,拒绝连接