Debian系列发行版管理iptables

Debian系列发行版管理iptables

RedHat系列下有比较好用的iptables管理工具,可以像控制服务进程一样来对防火墙进行管理及控制,Debian系发行版默认不开启iptables,当然也没有与之相关的能直接管理的工具了。 正常情况下,我们写入的iptables规则将会在系统重启时消失。

安装iptables并启用规则

apt-get update
apt-get install iptables -y

# 清除默认规则
iptables -F && iptables -X && iptables -Z

vim /etc/iptables.test.rules
#自定义规则
*filter
# Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT
# Accepts all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# You could modify this to only allow certain traffic
# Allows SSH connections from anywhere
-A INPUT -p tcp --dport 22 -j ACCEPT
# Open TCP port
-A INPUT -p tcp --dport xxxx -j ACCEPT
# Allows specify ip access to the specified port
-A INPUT -s 103.21.244.0/22 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 10.1.108.0/22 -p tcp -m multiport --dport 22,80,8080,6700:6704 -j ACCEPT
# Allow ping
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
# log iptables denied calls (access via 'dmesg' command)
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
# Reject all other inbound - default deny unless explicitly allowed policy
-A INPUT -j DROP
# Allows all outbound traffic
-A OUTPUT -j ACCEPT
COMMIT

# 启用规则
iptables-restore < /etc/iptables.test.rules

# 查看规则是否生效
iptables -L

现在已经自定义好防火墙规则了,但是重启之后就会失效

这里我们有一个更好的iptables持久化方案,让防火墙规则重启后依旧有效。即使用iptables-persistent工具。

使用iptables-persistent

安装

apt-get install iptables-persistent -y

iptables-persistent指令使用语法

# Ubuntu 14.04
/etc/init.d/netfilter-persistent {start|restart|reload|force-reload|save|flush}

# Ubuntu 16.04
/etc/init.d/netfilter-persistent {start|restart|reload|force-reload|save|flush}

安装完后即可使用以下命令保存或载入规则:

# Ubuntu 14.04
/etc/init.d/iptables-persistent save
/etc/init.d/iptables-persistent reload

# Ubuntu 16.04
netfilter-persistent save
netfilter-persistent reload

通过iptables-persistent生成的规则默认将被存储在以下文件中,可随时查看

/etc/iptables/rules.v4

/etc/iptables/rules.v6

之后即使系统重启,iptables 规则也不会失效了。


参考资料:

Debian 使用 iptables-persistent 持久化 iptables 规则