CentOS默认安装了Firewalld,但没有激活。
1、启动和停止服务
sudo systemctl start firewalld #启动防火墙
sudo systemctl enable firewalld #设置开机启动
sudo systemctl stop firewalld #停止防火墙
sudo systemctl disable firewalld #取消开机启动
sudo firewall-cmd --reload #重启服务
2、状态检查
sudo firewall-cmd --version #查看版本
sudo firewall-cmd --state #仅检查是否运行
sudo systemctl status firewalld #更详细的运行信息
3、添加删除规则
#永久添加或删除服务,比如http, snmp 等
sudo firewall-cmd --zone=public --add-service=http --permanent
sudo firewall-cmd --zone=public --remove-service=http --permanent
#永久添加或删除端口
sudo firewall-cmd --zone=public --add-port=123/tcp --permanent
sudo firewall-cmd --zone=public --remove-port=123/tcp --permanent
#端口转发,同一台主机或远程服务器
sudo firewall-cmd --zone="public" --add-forward-port=port=80:proto=tcp:toport=1234
sudo firewall-cmd --zone="public" --add-forward-port=port=80:proto=tcp:toport=8080:toaddr=xxx.xxx.xxx.xxx
#富规则,允许为任何端口、协议、地址和操作向任何区域 添加完全自定义的防火墙规则
#查看现有富规则
sudo firewall-cmd --list-rich-rules
#eg. 允许来自ip 192.168.0.255的所有ipv4流量
sudo firewall-cmd --zone=public --add-rich-rule 'rule family="ipv4" source address=192.168.0.255 accept'
#eg. 拒绝所有来自192.168.0.1的ipv4 ssh流量
sudo firewall-cmd --zone=public --add-rich-rule 'rule family="ipv4" source address="192.168.0.1" port port=22 protocol=tcp reject'
#eg. 允许来自10.0.0.1的80端口ipv4流量并转发到12345端口
sudo firewall-cmd --zone=public --add-rich-rule 'rule family=ipv4 source address=10.0.0.1 forward-port port=80 protocol=tcp to-port=12345'
4、配置案例:http服务器防火墙初始化
#查看默认区域,默认是public
sudo firewall-cmd --get-default-zone
#查看网卡所在区域
sudo firewall-cmd --get-active-zones
#查看区域防火墙配置
sudo firewall-cmd --zone=public --list-all
#查看所有防火墙配置
sudo firewall-cmd --list-all
#查看主机的所有服务
sudo firewall-cmd --get-services
#将默认区域更改的dmz(该区域默认ssh和icmp)
sudo firewall-cmd --set-default-zone=dmz
sudo firewall-cmd --zone=dmz --add-interface=eth0
#永久添加http和https规则
sudo firewall-cmd --zone=dmz --add-service=http --permanent
sudo firewall-cmd --zone=dmz --add-service=https --permanent
#重启防火墙使配置生效
sudo firewall-cmd --reload
#配置完成后,效果如下:
#默认区域dmz
#应用于eth0 接口中所有网络的源地址和端口
#允许传入 HTTP(80)、HTTPS(443)和 SSH(22)的流量( IPv4 和 IPv6)
#不允许IP 伪装和端口转发
#允许ICMP
#没有丰富规则,允许所有出站流量
记得永久生效加 --permanent, 添加规则后要reload生效