设置符合自己要求的iptables

在之前的几篇文章里,已经介绍过了iptables的表、链,以及如何增加规则链等。这里,想和大家分享一个简单的防火墙的规则,这里主要针对filter的input链设置规则,本篇文章相当于一个iptables规则实战,帮助大家加深巩固所学的知识。

应用规则如下:

  • 清除已有规则,将原有的规则全部清除。
  • 设定默认策略,将filter的input链默认策略设置为drop,其他的都设置为accept。
  • 信任本机,对于回环网卡lo必须设置为可信任的。
  • 响应数据包,对于主机主动向外请求的而响应的数据包可以进入本机(establish/related)
  • 拒绝无效数据包,对于无效的数据包都拒绝(INVALID)
  • 白名单,信任某些ip或网络地址等
  • 黑名单,不信任的ip或网络地址等
  • 允许icmp包,对于icmp包放行
  • 开放部分端口, 有些服务的端口是必须要向外开放的,比如80、443、22等端口

我们准备制作3个shell脚本文件:iptables.rule、iptables.allow(白名单)、iptables.deny(黑名单)文件。这三个文件,我一般会先建立一个目录/etc/iptables,这三个文件存在这个目录。

下面,我们看这个iptables.rule的脚本内容:

#!/bin/bash
# iptables rule

# 清楚默认规则
iptables -F
iptables -X
iptables -Z

# 修改默认策略
iptables -P INPUT  DROP
iptables -P FORWARD  ACCEPT
iptables -P OUTPUT  ACCEPT

# 信任本机
iptables -A INPUT -i lo -j ACCEPT 
# 响应数据包
iptables -A INPUT  -m state --state ESTABLISHED,RELATED -j ACCEPT
# 拒绝无效数据包
iptables -A INPUT  -m state --state INVALID -j DROP

# 白名单
if [ -f "/etc/iptables/iptables.allow" ];then
    sh /etc/iptables/iptables.allow
fi

# 黑名单
if [ -f "/etc/iptables/iptables.deny" ];then
    sh /etc/iptables/iptables.deny
fi

# 允许icmp包
iptables -A INPUT -p icmp -j ACCEPT

# 开放部分端口
iptables -A INPUT -p tcp --dport 22  -j ACCEPT # ssh服务
iptables -A INPUT -p tcp --dport 80 -j ACCEPT # www服务
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # ssl

# 保存规则
/usr/libexec/iptables/iptables.init save

对于iptables.allow,我们一般会将信任的ip或网络地址写入到这个文件,比如该主机所在局域网络为192.168.1.0/24,想要信任该局域网内的主机的话,可以在该文件写入

iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT

而iptables.deny则是用来阻挡某些恶意ip的流量进入到本机,比如像阻挡8.210.247.5这个ip,可以在该文件写入

iptables -A INPUT -s 8.210.247.5/32 -j DROP

在iptables.rule的最后,我们使用的命令来保存了防火墙规则,注意,如果不加入本命令,该规则只会零时生效,当重启了iptables或重启了系统,我们之前设定的规则就会失效了。