iptables防火墙
Linux包过滤防火墙
netfilter
1、位于Linux内核中的包过滤功能体系
2、称为Linux防火墙的“内核态”
ptables
1、位于/sbin/iptables,用来管理防火墙规则的工具
2、称为Linux防火墙的“用户态”
包过滤的工作层次
1、主要是网络层,针对IP数据包
2、体现在对包内的IP地址、端口等信息的处理上
iptables的表、链结构
规则表
1、表的作用:容纳各种规则链
2、表的划分依据:防火墙规则的作用相似
默认包括4个规则表
**raw表:**确定是否对该数据包进行状态跟踪
**mangle表:**为数据包设置标记
**nat表:**修改数据包中的源、目标IP地址或端口
**filter表:**确定是否放行该数据包(过滤)
规则链
1、规则的作用:对数据包进行过滤或处理
2、链的作用:容纳各种防火墙规则
3、链的分类依据:处理数据包的不同时机
默认包括5种规则链
INPUT:处理入站数据包
OUTPUT:处理出站数据包
FORWARD:处理转发数据包
POSTROUTING链:在进行路由选择后处理数据包
PREROUTING链:在进行路由选择前处理数据包
数据包过滤的匹配流程
规则表之间的顺序
raw→mangle→nat→filter
规则链之间的顺序
入站:PREROUTING→INPUT
出站:OUTPUT→POSTROUTING
转发:PREOUTING→FORWARD→POSTROUTING
规则链内的匹配顺序
1、按顺序依次检查,匹配即停止(LOG策略例外)
2、若找不到相匹配的规则,则按该链的默认策略处理
编写防火墙规则
iptables安装
关闭firewalld防火墙
systemctl stop firewalld.service
systemctl disable firewalld.service
安装iptables防火墙
yum -y install iptables iptables-services
设置iptables开机启动
systemctl start iptables.service
systemctl enable iptables.service
iptables的基本语法
语法构成
iptables [-t 表名] 选项 [链名] [条件] [-j 控制类型]
注意事项
1、不指定表名时,默认指filter表
2、不指定链名时,默认指表内的所有链
3、除非设置链的默认策略,否则必须指定匹配条件
4、选项、链名、控制类型使用大写字母,其余均为小写字母
数据包的常见控制类型
ACCEPT:允许通过
DROP:直接丢弃,不给出任何回应
REJECT:拒绝通过,必要时会给出提示
LOG:记录日志信息,然后传给下一条规则继续匹配
-A:末尾追加规则
例:在filter表INPUT链的末尾添加一条防火墙(“-p 协议名” 作为匹配条件)
[root@client1 ~]# iptables -t filter -A INPUT -p tcp -j ACCEPT
-I:指定序号追加新规则,若无指定,默认为第一条
例:给filter表追加第一条规则(省略了“-t filter”,默认使用filter表)
追加第二条规则
[root@client1 ~]# iptables -I INPUT -p udp -j ACCEPT
[root@client1 ~]# iptables -I INPUT 2 -p udp -j ACCEPT
查看规则列表:
-L结合–line-numbers:指定链内的各条规则,并显示序列号
[root@client1 ~]# iptables -L INPUT --line-numbers
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT udp – anywhere anywhere
2 ACCEPT udp – anywhere anywhere
3 ACCEPT tcp – anywhere anywhere
-n结合-L:以数字显示显示链内的各条规则
[root@client1 ~]# iptables -nL INPUT --line-numbers
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT udp – 0.0.0.0/0 0.0.0.0/0
2 ACCEPT udp – 0.0.0.0/0 0.0.0.0/0
3 ACCEPT tcp – 0.0.0.0/0 0.0.0.0/0
删除、清空规则
-D:删除一条规则
[root@client1 ~]# iptables -D INPUT 2
[root@client1 ~]# iptables -nL INPUT --line-numbers
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT udp – 0.0.0.0/0 0.0.0.0/0
2 ACCEPT udp – 0.0.0.0/0 0.0.0.0/0
-F:清空规则(不指定表,默认是filter表)
[root@client1 ~]# iptables -F INPUT(清空input链)
[root@client1 ~]# iptables -nL INPUT --line-numbers
Chain INPUT (policy ACCEPT)
num target prot opt source destination
[root@client1 ~]# iptables -F (清空filter表)
[root@client1 ~]# iptables -t nat -F(清空nat表)