Ubuntu 16.04系统配置iptables防火墙加强系统安全

这几天使用EasyEngine配置一台VPS主机,安装好之后,发现EasyEngine虽然有安装iptables防火墙程序,但没有配置文件,为了服务器的安全,建议大家启用防火墙设置,所以就需要手动来配置iptables.rules文件。

使用指令查看系统是否安装防火墙:

whereis iptables

输出:

iptables: /sbin/iptables /etc/iptables.rules /usr/share/iptables /usr/share/man/man8/iptables.8.gz #表示已經安裝 iptables

如果 Ubuntu 默认没有安装,请运行此指令安装 iptables 防火墙

apt-get install iptables

查看防火墙配置信息,显示如下:

#iptables -L -n

Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination

开始配置 iptables.rules 文件,因为 VPS 主机是安装 EasyEngine 程序,所以下面的 port 要打开:

22 / TCP (Inbound / Outbound) : Standard SSH port
80 / TCP (Inbound / Outbound) : Standard HTTP port
443 / TCP(Inbound / Outbound) : Standard HTTPS port
22222 / TCP (Inbound) : To access EasyEngine admin tools
11371 / TCP (Outbound) : To connect to GPG Key Server

可将下面的配置 copy 贴上:

# sample configuration for iptables service
# you can edit this manually or use system-config-firewall
# please do not ask us to add additional ports/services to this default configuration
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 465 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 587 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22222 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 11371 -j ACCEPT
-A INPUT -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT
-A INPUT -p icmp -m limit --limit 100/sec --limit-burst 100 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

我增加了两条规则,作用是每秒钟只允许 100 个数据包,用来防止 DDoS 攻击

-A INPUT -p icmp -m limit --limit 1/sec --limit-burst 10 -j ACCEPT
-A INPUT -f -m limit --limit 100/sec --limit-burst 100 -j ACCEPT

使防火墙规则生效:

iptables-restore < /etc/iptables.rules

CentOS 上可以执行:service iptables save 保存规则,但是需要注意的是 Debian / Ubuntu 上 iptables 是不会保存规则的。需要按如下步骤进行,让网卡关闭保存 iptables 规则,启动时加载 iptables 规则。

创建 /etc/network/if-post-down.d/iptables 文件,添加如下内容:

#!/bin/bash
iptables-save > /etc/iptables.rules

添加执行权限:

chmod +x /etc/network/if-post-down.d/iptables

创建 /etc/network/if-pre-up.d/iptables 文件,添加如下内容:

#!/bin/bash
iptables-restore < /etc/iptables.rules

添加执行权限:

chmod +x /etc/network/if-pre-up.d/iptables

最后查看 iptables 规则是否生效:

iptables -L -n

iptables 的规则其实还有很多,这边只有列出基本常用到的规则,更多的规则说明就要请各位自行上网查询了。

标签:IptablesUbuntu 发布于:2019-11-16 14:17:13