一、iptables的安装
#检查iptables是否已安装
service iptables status
#安装iptables
yum install -y iptables
#升级iptables
yum update iptables
#注册iptables服务
chkconfig iptables on
二、iptables规则的维护
2.1配置规则
编辑防火墙
vi /etc/iptables-rules
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
# 常用端口
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#允许loopback!(不然会导致DNS无法正常关闭等问题)
-A OUTPUT -o lo -p all -j ACCEPT
-A INPUT -i lo -p all -j ACCEPT
# 允许SSH连接
# The --dport 端口号要与 /etc/ssh/sshd_config 中的Port参数相同
-A INPUT -p tcp --dport 22 -j ACCEPT
-A OUTPUT -p tcp --sport 22 -j ACCEPT
#允许icmp包通过,也就是允许ping
-I INPUT -p icmp --icmp-type echo-request -j ACCEPT
-A INPUT -p ICMP --icmp-type timestamp-request -j DROP
-A INPUT -p ICMP --icmp-type timestamp-reply -j DROP
-A INPUT -p ICMP --icmp-type time-exceeded -j DROP
-A INPUT -p icmp --icmp-type 8 -s 0/0 -j DROP
-A OUTPUT -p ICMP --icmp-type time-exceeded -j DROP
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A INPUT -p tcp -m tcp --dport 8080 -j DROP
COMMIT############################
2.2配置生效
iptables-restore < /etc/iptables.rules
2.3查看防火墙规则
iptables -vnL
输出字段意思如下
- pkts:对应规则匹配到的报文的个数
- bytes:对应匹配到的报文包的大小总和
- target:规则对应的target,往往表示规则对应的”动作”,即规则匹配成功后需要采取的措施
- prot:表示规则对应的协议,是否只针对某些协议应用此规则。
- opt:表示规则对应的选项。
- in:表示数据包由哪个接口(网卡)流入,即从哪个网卡来。
- out:表示数据包将由哪个接口(网卡)流出,即到哪个网卡去。
- source:表示规则对应的源头地址,可以是一个IP,也可以是一个网段。
- destination:表示规则对应的目标地址。可以是一个IP,也可以是一个网段。
2.4 新增
iptables -A INPUT -p tcp -m tcp --dport 8080 -j ACCEPT
2.5 删除
iptables -D INPUT 1
2.6 修改
iptables -R INPUT 1 -s 10.250.143.29 -j REJECT
- 最重要的:使用
-s
指定对应规则中原本的源地址,否则修改的规则中的源地址会自动变为0.0.0.0/0
,即那么所有IP的请求都被拒绝了 - 一定要指定规则的序号
三、iptables备份与恢复
备份
iptables-save > /etc/iptables.rules
恢复
iptables-restore < /etc/iptables.rules