在配置iptables之前,建议先去了解一下iptables的基础知识.本文主要是讲解如何配置一个filter表的防火墙.
1.查看iptables的设置情况
[root@localhost ~]# 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
Chain RH-Firewall-1-INPUT (0 references)
target prot opt source destination
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 icmp type 255
ACCEPT esp -- 0.0.0.0/0 0.0.0.0/0
ACCEPT ah -- 0.0.0.0/0 0.0.0.0/0
ACCEPT udp -- 0.0.0.0/0 224.0.0.251 udp dpt:5353
ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:631
ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:80
ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:25
REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
可以看出我在安装Linux时选择了有防火墙,并且开放了22,80,25端口.如果在安装Linux时没有选择启用防火墙的话,是这样的
[root@localhost ~]# 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
什么规则都没有
2.清除原有规则
无论在安装Linux时是否启用了防火墙,在配置属于自己的防火墙之前,请先清除原有规则.
a.清除预设表filter中的所有规则链的规则
[root@localhost ~]# iptables -F
b.清除预设表filter中使用者自定链中的规则
[root@localhost ~]# iptables -X
用iptables -L -n命令再看一下,这时显示的结果和没有启用防火墙是一样的.(提前说一句,这些配置就像用命令配置IP一样,重启就会失去作用, 保存一下.)
c.将配置写到/etc/sysconfig/iptables文件里
[root@localhost ~]# /etc/rc.d/init.d/iptables save
d.重启防火墙,新的配置才能起作用
[root@localhost ~]# service iptables restart
现在iptables已经是空的了,那我们就开始配置属于自己的防火墙吧.
3.设定预设规则
[root@localhost ~]# iptables -p INPUT DROP
[root@localhost ~]# iptables -p OUTPUT ACCEPT
[root@localhost ~]# iptables -p FORWARD DROP
上面三行命令的意思是:
当超出了iptables里filter表里的两个链规则(INPUT,FORWARD)时,不在这两个规则里的数据包如何处理呢,那就是DROP(放弃).这样配置是很安全的,我们要控制流入的数据包.
而对于OUTPUT链,也就是流出的数据包,我们不用做限制,也就是说,不在这个规则里的数据包怎么办呢,那就是通过.
可以看出,INPUT、FORWARD两个链采用的是允许什么包通过的规则,而OUTPUT链采用的是不允许什么包通过的规则.
这样设置还是挺合理的,当然你也可以三个链都DROP,但这样做我认为是没有必要的, 要写的规则就会增加.但如果你只想要有限的几个规则的话,比如只做web服务器,那还是推荐三个链都DROP.
注:如果不是本机操作,而是远程SSH的话,在写规则之前最好先将防火墙停掉,否则写完上面三行规则后,你就会断线,连接不上服务器了.停止防火墙:service iptables stop
4.添加规则
a. 添加INPUT链,INPUT链的默认规则是DROP, 我们就写允许通过(ACCETP)的链.
为了能采用SSH远程登陆,开启22端口
[r |