firewall-cmd 是Linux系统中防火墙命令。如果想了解这个命令怎么使用,可以先了解下 linux 中防火墙的发展历史。
Linux 中的防火墙发展历史
- ipfwadm: 从名字可以看出应该 ip firewall admin 的缩写,这个是最早的linux中的防火墙,仅仅支持基本的包过滤功能。
- ipchains: 引入了链式规则,支持 输入、输出、转发三条链。有一定的局限性,几乎不支持状态跟踪。
- iptables: 这个就比较有名了,支持 5表5链, 是基于 Netfilter 框架。
- nftables: 这个是iptables 的升级版,性能更好、语法更简洁,支持原子更新。性能最高。
- firewalld: 这个是最新的防火墙,也是当前系统中使用最多的。底层还是使用的是 nftables 和 iptables 。提供了 D-Bus 接口和 区域(zone)管理,适合动态环境。
Netfilter框架(iptables和nftables的共用基础)
Netfilter是Linux内核的包处理框架,定义了钩子点(hook points):
NF_IP_PRE_ROUTINGNF_IP_LOCAL_INNF_IP_FORWARDNF_IP_LOCAL_OUTNF_IP_POST_ROUTING
iptables和nftables都基于这些相同的Netfilter钩子点工作,只是用户态配置工具和内核模块实现不同。
firewalld与底层的关系
- firewalld在底层动态调用iptables或nftables(取决于配置和系统支持)
- 它通过D-Bus接口接收请求,生成对应的底层规则
- 与直接使用iptables/nftables共用同一套内核防火墙机制
学习建议
- 先学习 firewalld 入门比较简单,方便使用,使用的适合不用把底层技术 Netfilter 理解很清楚也,也可以使用。
- 再 iptables: 资料比较齐全,应用也比较多。
- nftables : 高度可配置,不像iptables 有预定义的表。规则集在内核中采用链表等高效数据结构,支持原子规则更新,效率高。
- 学习 Netfilter 内核框架原理。
使用 firewall-cmd
重要的资料
1. 检查状态
firewall-cmd --state
not running
2. 启动服务
systemctl start firewalld
firewall-cmd --state
running
3. 查看当前规则
firewall-cmd --list-all
public (active) # 当前正在使用的区域(zone)是public,且处于激活状态
target: default # 定义该区域的默认行为
icmp-block-inversion: no # 不禁用ping
interfaces: eth0 #当前区域绑定的网络接口是 eth0(一个接口只能属于一个区域)
sources:源地址限制(当前为空)
services: cockpit dhcpv6-client ssh # 允许的服务
ports:
protocols:
forward: yes #表示允许IP转发(系统充当路由器)
masquerade: no #表示未启用IP伪装(NAT)
forward-ports:
source-ports:
icmp-blocks:
rich rules:
4、放行 https 和 http 两个端口
首先放行 http 和 https , 对于是一个 web 服务器首先放行的是 这两个端口。
firewall-cmd --add-service=http
firewall-cmd --add-service=https
# firewall-cmd --permanent --remove-service={http,https} # 移除的命令
firewall-cmd --list-all | grep http
services: cockpit dhcpv6-client http https ssh
可以看到 services 支持了 http 和 https
5. 放行指定的端口
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload
# 移除命令 firewall-cmd --remove-port=2222/tcp
为问什么使用: –permanent (永久) ,如果不使用这个参数,表示修改的是运行时配置,意思是命令输入后,立即生效,但是不是永久的,如果重启了防火墙,这些运行时的配置会丢失。通过 –permanent 这个参数表示永久生效,但是需要重新加载。
firewall-cmd --runtime-to-permanent # 将当前的运行时保存为永久
6. 屏蔽指定的ip的ping
firewall-cmd --add-rich-rule='rule family="ipv4" source address="xxx.xxx.xxx.xxx" protocol value="icmp" reject
7. 屏蔽指定的ip
firewall-cmd --add-rich-rule='rule family="ipv4" source address="xxx.xxx.xxx.xxx"'