防火墙是用户限制某些ip或用户对其主机的访问。防火墙从种类上分为两大类,硬件防火墙以及软件防火墙。软件防火墙主要是对数据包进行过滤,硬件防火墙主要用来对恶意攻击的防护以及数据包的过滤,比如ddos攻击。这里,我们来讲解linux下的软件防火墙——iptables。
iptables与firewalld
在centos6下,默认的软件防火墙是iptables,而到了centos7,则是firewalld。它们之间有什么联系了,其实firewalld就是在原iptables上新封装成的一个软件。
学习iptables时,建议先关闭firewalld,并开启iptables
yum install iptables-servicessystemctl stop firewalldsystemctl start iptables
iptables的表和链
iptables的不同的表代表着不同的功能,默认有4个表
filter(过滤器) nat(地址转换) mangle raw
不同的表下面,有着自己的规则链:
filter(input/output/forward)
nat(prerouting/output/postouting)
这些链代表的意义如下:
input链——进来的数据包应用此规则链中的规则
output链——外出的数据包应用此规则链中的规则
forward链——转发数据包时应用此规则链中的规则
prerouting链——对数据包作路由选择前应用此链中的规则
postrouting链——对数据包作路由选择后应用此链中的规则
iptables的规则查看与清除
规则查看
用法示例:iptables [-t tables] -l [-nv]
选项与参数:
-t后接表类型,省略该选项,则默认为filter表。
-l列出当前表的规则
-n 不进行域名与ip反查
-v 显示更多信息
# 查看filter表的规则# iptables -nvlchain input (policy accept 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 67 4444 accept all -- * * 0.0.0.0/0 0.0.0.0/0 state related,established 0 0 accept icmp -- * * 0.0.0.0/0 0.0.0.0/0 0 0 accept all -- lo * 0.0.0.0/0 0.0.0.0/0 0 0 accept tcp -- * * 0.0.0.0/0 0.0.0.0/0 state new tcp dpt:22 2 286 reject all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibitedchain forward (policy accept 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 0 0 reject all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibitedchain output (policy accept 38 packets, 4664 bytes) pkts bytes target prot opt in out source destination # 查看nat表的规则iptables -t nat -l -nv
链下的规则选项的含义如下:
target:代表进行的操作,accept放行、drop丢弃、reject拒绝
prot:代表使用的数据包协议,有tcp、udp以及icmp
opt:说明信息
source:对某来源主机进行限制
destination:对某目标主机进行限制
上面显示的input链的5条规则含义如下:
只要数据包的状态为related,established,都接受
只要是icmp包都接受
只要是本地回环网卡,所有数据都接受
只要是发送给22端口的主动式连接的tcp数据包都接受。
拒绝所有的数据包
清楚iptables的规则
默认安装centos7后,系统就已经有许多iptables的规则,这里教大家如何去清除这些规则。
用法示例:iptables [-t tables] [-fxz]
选项与参数:
-f 清理所有已定制的规则
-x 清理所有用户自定义的规则
-z 将所有的统计计数置零
# iptables -f# iptables -x# iptables -z
查看具体的规则
使用iptables-save可以查看具体的规则
用法:iptables-save [-t tables]
# iptables-save -t filter# generated by iptables-save v1.4.21 on sat nov 14 21:51:56 2020*filter:input accept [0:0]:forward accept [0:0]:output accept [56:7196]-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 -j reject --reject-with icmp-host-prohibited-a forward -j reject --reject-with icmp-host-prohibited # completed on sat nov 14 21:51:56 2020
定义默认策略
当我们清楚完规则后,就只剩下默认的策略了。什么是默认的策略,就是当不满足我们任何一条规则时,就采用默认规则。默认的策略有accept(接受数据包)和drop(丢弃数据包)
用法:iptables [-t tables] -p [input|output|forward……] [accept|drop]
现在,我们尝试将filter的input链的默认修改为drop、output及forward链修改为accetp
iptables -t filter -p input drop# 注意,该命令敲完后,你的终端就可能会断开连接了iptables -p output acceptiptables -p forward accept
相关推荐:《linux课程》
以上就是linux下的软件防火墙iptables——规则的查看与清除、定义默认策略的详细内容。