服务器禁止访问外网策略配置

avatar
作者
猴君
阅读量:0

我什么要禁用外网

抵御外网入侵风险要从根上做起,即在服务器主机上写外网防护策略。如果服务器只有内网业务,没有外网业务,可以禁掉所有外网访问请求。

内网IP段

10.0.0.0-10.255.255.255 172.16.0.0-172.31.255.255 192.168.0.0-192.168.255.255 

外网IP段

0.0.0.0-9.255.255.255 11.0.0.0-172.15.255.255 172.32.0.0-192.167.255.255 192.169.0.0-255.255.255.255 

主角IPSET上场

Linux 下的禁外网主机策略可以这么写,先在主机上创建一个 ipset www ,将所有的外网网段加入到这个 ipset 集合中。然后在 iptables 中引用这个 ipset 。

ipset 创建网段集合的命令为
ipset create www hash:net family inet hashsize 1024 maxelem 65536 
ipset 添加地址段的命令为
ipset add www 0.0.0.0-9.255.255.255 

这里要注意,x.x.x.x - y.y.y.y 的地址段格式在 ipset 添加后将转为 CIDR 格式,即网段加掩码的格式:

ipset list www Name: www Type: hash:net Header: family inet hashsize 1024 maxelem 65536 Size in memory: 8596 References: 0 Members: 0.0.0.0/5 8.0.0.0/7 

并且 ipset 存在一个 bug,即网段过大时,CIDR 转化会失败:

ipset flush www ipset add www 11.0.0.0-172.15.255.255 ipset list www Name: www Type: hash:net Header: family inet hashsize 1024 maxelem 65536 Size in memory: 8532 References: 0 Members: 

比如以上例子,当添加 11.0.0.0-172.15.255.255 网段时,ipset 添加会失败。www 集合中并没有加进去任何网段,所以安全的做法是直接添加 CIDR 格式的网段。将外网网段 x.x.x.x - y.y.y.y 换为 CIDR 格式的后为:

0.0.0.0/5 8.0.0.0/7 11.0.0.0/8 12.0.0.0/6 16.0.0.0/4 32.0.0.0/3 64.0.0.0/2 128.0.0.0/3 160.0.0.0/5 168.0.0.0/6 172.0.0.0/12 172.32.0.0/11 172.64.0.0/10 172.128.0.0/9 173.0.0.0/8 174.0.0.0/7 176.0.0.0/4 192.0.0.0/9 192.128.0.0/11 192.160.0.0/13 192.169.0.0/16 192.170.0.0/15 192.172.0.0/14 192.176.0.0/12 192.192.0.0/10 193.0.0.0/8 194.0.0.0/7 196.0.0.0/6 200.0.0.0/5 208.0.0.0/4 224.0.0.0/3 

将这些地址段加入到 www ipset 中,命令如下:

ipset add www 0.0.0.0/5 ipset add www 8.0.0.0/7 ipset add www 11.0.0.0/8 ipset add www 12.0.0.0/6 ipset add www 16.0.0.0/4 ipset add www 32.0.0.0/3 ipset add www 64.0.0.0/2 ipset add www 128.0.0.0/3 ipset add www 160.0.0.0/5 ipset add www 168.0.0.0/6 ipset add www 172.0.0.0/12 ipset add www 172.32.0.0/11 ipset add www 172.64.0.0/10 ipset add www 172.128.0.0/9 ipset add www 173.0.0.0/8 ipset add www 174.0.0.0/7 ipset add www 176.0.0.0/4 ipset add www 192.0.0.0/9 ipset add www 192.128.0.0/11 ipset add www 192.160.0.0/13 ipset add www 192.169.0.0/16 ipset add www 192.170.0.0/15 ipset add www 192.172.0.0/14 ipset add www 192.176.0.0/12 ipset add www 192.192.0.0/10 ipset add www 193.0.0.0/8 ipset add www 194.0.0.0/7 ipset add www 196.0.0.0/6 ipset add www 200.0.0.0/5 ipset add www 208.0.0.0/4 ipset add www 224.0.0.0/3 

出站入站规则添加

之后就可以在 iptables 中正常引用 www ipset,在 INPUT 和 OUTPUT 出入站中禁用外网,命令如下:

iptables -I INPUT -m set --match-set www src -j DROP iptables -I OUTPUT -m set --match-set www dst -j DROP 

通过以上两条基础策略可以阻止服务器访问互联网或互联网访问服务器,同时又不会对内网造成影响。

如果去掉 OUTPUT 出站策略,再配合以下策略可以让服务器访问互联网但外网IP无法主动访问服务器:

iptables -I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 

一般入出站策略需要配对写,如果在出站策略中把包全封死了,入站的包将无法回包。此时也相当于把回去的路封死了,大多数策略只写一半,另一半默认放行,即在入站中写禁止,出站默认放行。

iptables 管理起来比较灵活,但复杂度也随之上升。做完安全策略一定要进行测试,存在漏洞的策略是非常危险的。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!