11 - 防火墙与安全加固
一、防火墙概述
Linux 防火墙主要分为两代:
| 工具 | 说明 | 使用场景 |
|---|---|---|
| firewalld | 动态防火墙,区域概念,CentOS 默认 | CentOS 7+ / RHEL |
| iptables | 传统防火墙,规则链 | 通用 / 旧系统 |
| nftables | iptables 的继任者 | 内核 3.13+ / 新系统 |
| ufw | iptables 的简化前端 | Ubuntu 默认 |
数据包过滤流程
数据包进入 → PREROUTING → 路由判断
├─ 本机处理 → INPUT → 应用程序 → OUTPUT → POSTROUTING → 发出
└─ 转发 → FORWARD → POSTROUTING → 发出
二、firewalld
2.1 基本操作
bash
# 查看状态
systemctl status firewalld
firewall-cmd --state
# 启动/停止/重启
systemctl start firewalld
systemctl stop firewalld
systemctl restart firewalld
# 开机自启
systemctl enable firewalld
systemctl disable firewalld
2.2 区域(Zone)管理
firewalld 使用区域概念,不同区域有不同的信任级别:
| 区域 | 信任级别 | 说明 |
|---|---|---|
| trusted | 完全信任 | 允许所有流量 |
| public | 不信任 | 默认区域,仅允许选中服务 |
| home | 较信任 | 家庭网络 |
| internal | 较信任 | 内部网络 |
| work | 较信任 | 工作网络 |
| dmz | 不信任 | DMZ 隔离区 |
| block | 拒绝 | 拒绝所有流量 |
| drop | 丢弃 | 丢弃所有包(不回应) |
bash
# 查看默认区域
firewall-cmd --get-default-zone
# 查看所有区域
firewall-cmd --get-zones
# 查看当前激活的区域
firewall-cmd --get-active-zones
# 查看区域配置
firewall-cmd --zone=public --list-all
# 切换默认区域
firewall-cmd --set-default-zone=public
2.3 服务与端口管理
bash
# 查看已开放的服务
firewall-cmd --zone=public --list-services
# 开放服务(服务名来自 /etc/services)
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --permanent --zone=public --add-service=ssh
# 移除服务
firewall-cmd --permanent --zone=public --remove-service=http
# 开放端口
firewall-cmd --permanent --zone=public --add-port=8080/tcp
firewall-cmd --permanent --zone=public --add-port=3000-3100/tcp # 端口范围
firewall-cmd --permanent --zone=public --add-port=53/udp # UDP 端口
# 移除端口
firewall-cmd --permanent --zone=public --remove-port=8080/tcp
# 查看已开放的端口
firewall-cmd --zone=public --list-ports
# 重新加载(永久规则生效)
firewall-cmd --reload
# 查看所有配置
firewall-cmd --zone=public --list-all
重要 :使用
--permanent的规则需要--reload才生效。不加--permanent则立即生效但重启后丢失。
2.4 IP 伪装与端口转发
bash
# 开启 IP 伪装(NAT,让内网机器通过本机上网)
firewall-cmd --permanent --zone=public --add-masquerade
firewall-cmd --reload
# 端口转发:将 80 端口转发到 8080
firewall-cmd --permanent --zone=public --add-forward-port=port=80:proto=tcp:toport=8080
# 端口转发到其他机器
firewall-cmd --permanent --zone=public --add-forward-port=port=80:proto=tcp:toaddr=192.168.1.20:toport=8080
firewall-cmd --reload
2.5 Rich Rules(富规则)
富规则提供更精细的控制:
bash
# 允许指定 IP 访问指定端口
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" port port="3306" protocol="tcp" accept'
# 拒绝指定 IP 的所有访问
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.200" reject'
# 允许指定网段
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" accept'
# 限制连接数(防止暴力破解)
firewall-cmd --permanent --add-rich-rule='rule service name="ssh" limit value="3/m" accept'
# 查看富规则
firewall-cmd --zone=public --list-rich-rules
# 删除富规则
firewall-cmd --permanent --remove-rich-rule='rule family="ipv4" source address="192.168.1.200" reject'
firewall-cmd --reload
三、iptables
3.1 基本概念
iptables 有四表五链:
四表:
| 表 | 作用 |
|---|---|
| filter | 包过滤(默认) |
| nat | 地址转换 |
| mangle | 包修改 |
| raw | 连接追踪豁免 |
五链:
| 链 | 时机 |
|---|---|
| INPUT | 入站包 |
| OUTPUT | 出站包 |
| FORWARD | 转发包 |
| PREROUTING | 路由前 |
| POSTROUTING | 路由后 |
3.2 常用命令
bash
# 查看规则
iptables -L -n -v # 查看所有规则(带统计)
iptables -L -n --line-numbers # 显示行号
iptables -t nat -L -n # 查看 NAT 表
# 允许已建立的连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 允许本地回环
iptables -A INPUT -i lo -j ACCEPT
# 允许 SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# 允许 HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# 允许指定 IP 访问 MySQL
iptables -A INPUT -p tcp -s 192.168.1.100 --dport 3306 -j ACCEPT
# 拒绝其他所有入站流量
iptables -A INPUT -j DROP
iptables -P INPUT DROP # 设置默认策略
3.3 规则管理
bash
# 插入规则(插入到指定位置,默认第1位)
iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT
# 删除规则
iptables -D INPUT 3 # 删除第 3 条规则
iptables -D INPUT -p tcp --dport 80 -j ACCEPT # 按内容删除
# 清空所有规则(危险!)
iptables -F
# 清空指定链
iptables -F INPUT
# 清空计数器
iptables -Z
# 设置默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
3.4 保存与恢复
bash
# 保存规则(CentOS)
iptables-save > /etc/sysconfig/iptables
# 保存规则(Ubuntu)
iptables-save > /etc/iptables/rules.v4
# 恢复规则
iptables-restore < /etc/sysconfig/iptables
# 安装持久化工具
yum install -y iptables-services # CentOS
systemctl enable iptables
3.5 常用 iptables 脚本
bash
#!/bin/bash
# firewall_setup.sh - 基础防火墙配置
# 清空现有规则
iptables -F
iptables -X
iptables -Z
# 设置默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# 允许本地回环
iptables -A INPUT -i lo -j ACCEPT
# 允许已建立的连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 允许 ICMP(ping)
iptables -A INPUT -p icmp -j ACCEPT
# 开放服务端口
iptables -A INPUT -p tcp --dport 22 -j ACCEPT # SSH
iptables -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
# 防 SSH 暴力破解(每分钟最多 5 次新连接)
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 -j DROP
# 防 SYN Flood
iptables -A INPUT -p tcp --syn -m limit --limit 20/s --limit-burst 40 -j ACCEPT
iptables -A INPUT -p tcp --syn -j DROP
# 保存规则
iptables-save > /etc/sysconfig/iptables
echo "防火墙配置完成"
四、ufw(Ubuntu)
bash
# 安装
apt install -y ufw
# 查看状态
ufw status verbose
# 启用/禁用
ufw enable
ufw disable
# 允许/拒绝端口
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 22/tcp
ufw deny 3306/tcp
# 允许指定 IP
ufw allow from 192.168.1.100 to any port 3306
# 允许网段
ufw allow from 192.168.1.0/24 to any port 22
# 删除规则
ufw delete allow 80/tcp
# 按编号删除
ufw status numbered
ufw delete 3
# 重置
ufw reset
# 默认策略
ufw default deny incoming
ufw default allow outgoing
五、SELinux
5.1 SELinux 概念
SELinux(Security-Enhanced Linux)是 Linux 内核的强制访问控制(MAC)安全模块。
三种模式:
| 模式 | 说明 |
|---|---|
| enforcing | 强制执行,违规即阻止 |
| permissive | 宽容模式,违规只记录不阻止 |
| disabled | 禁用 |
5.2 SELinux 操作
bash
# 查看状态
getenforce
sestatus
# 临时切换模式
setenforce 0 # 切换到 permissive
setenforce 1 # 切换到 enforcing
# 永久修改(重启生效)
# 编辑 /etc/selinux/config
SELINUX=permissive # 或 enforcing / disabled
5.3 SELinux 上下文
bash
# 查看文件上下文
ls -Z /var/www/html/index.html
# 修改文件上下文
chcon -t httpd_sys_content_t /var/www/html/index.html
chcon -R -t httpd_sys_content_t /var/www/html/
# 恢复默认上下文
restorecon -Rv /var/www/html/
# 查看进程上下文
ps -eZ | grep nginx
# 查看端口上下文
semanage port -l | grep http
5.4 SELinux 排错
bash
# 查看 SELinux 拒绝日志
ausearch -m avc -ts recent
grep denied /var/log/audit/audit.log
# 使用 audit2allow 生成策略
grep httpd /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.pp
# 查看 SELinux 布尔值
getsebool -a | grep httpd
setsebool -P httpd_can_network_connect on
运维建议:生产环境建议保持 SELinux 为 enforcing 模式。遇到问题时先用 permissive 模式排查,找到原因后调整策略,而不是直接关闭。
六、SSH 安全加固
6.1 sshd 配置
编辑 /etc/ssh/sshd_config:
bash
# 禁止 root 直接登录
PermitRootLogin no
# 禁止密码登录,仅用密钥
PasswordAuthentication no
# 修改默认端口(减少扫描)
Port 2222
# 禁止空密码
PermitEmptyPasswords no
# 限制登录用户
AllowUsers alice bob
# 或限制组
AllowGroups sshusers
# 登录超时(秒)
LoginGraceTime 30
# 最大尝试次数
MaxAuthTries 3
# 禁止 X11 转发(不需要的话)
X11Forwarding no
# 空闲超时自动断开
ClientAliveInterval 300
ClientAliveCountMax 0
# 禁止 DNS 反查(加快登录)
UseDNS no
bash
# 重启生效
systemctl restart sshd
6.2 fail2ban 防 SSH 暴力破解
bash
# 安装
yum install -y epel-release && yum install -y fail2ban # CentOS
apt install -y fail2ban # Ubuntu
# 配置
cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
port = 2222
maxretry = 5
findtime = 600
bantime = 3600
# bantime = -1 # 永久封禁
EOF
# 启动
systemctl enable --now fail2ban
# 查看状态
fail2ban-client status
fail2ban-client status sshd
# 手动解封 IP
fail2ban-client set sshd unbanip 192.168.1.100
七、系统安全加固清单
7.1 账户安全
bash
# 1. 删除不必要的账户
userdel -r games
userdel -r news
# 2. 检查空密码账户
awk -F: '($2 == "") {print $1}' /etc/shadow
# 3. 锁定不使用的账户
passwd -l username
# 4. 设置密码策略
# /etc/login.defs
PASS_MAX_DAYS 90
PASS_MIN_DAYS 2
PASS_MIN_LEN 12
PASS_WARN_AGE 7
# 5. 密码复杂度(安装 pam_pwquality)
# /etc/security/pwquality.conf
minlen = 12
minclass = 4 # 至少包含4类字符
maxrepeat = 3
7.2 文件权限
bash
# 设置关键文件权限
chattr +i /etc/passwd # 不可修改(连 root 也不能改,需 chattr -i 解除)
chattr +i /etc/shadow
chattr +i /etc/group
chattr +i /etc/gshadow
# 设置关键目录权限
chmod 700 /root
chmod 700 /boot
chmod 600 /etc/ssh/sshd_config
# 查找 SUID 文件(可能被利用提权)
find / -perm -4000 -type f 2>/dev/null
# 查找无主文件
find / -nouser -o -nogroup 2>/dev/null
7.3 内核安全参数
bash
# /etc/sysctl.conf
# 禁用 ICMP 重定向
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
# 禁用源路由
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# 开启反向路径过滤
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# 禁用 ICMP 广播
net.ipv4.icmp_echo_ignore_broadcasts = 1
# 开启 SYN Cookie
net.ipv4.tcp_syncookies = 1
# 禁用 IP 转发(非路由器)
net.ipv4.ip_forward = 0
# 应用
sysctl -p
7.4 服务最小化
bash
# 查看正在运行的服务
systemctl list-units --type=service --state=running
# 禁用不必要的服务
systemctl disable --now avahi-daemon
systemctl disable --now cups
systemctl disable --now bluetooth
systemctl disable --now rpcbind
# 检查监听端口
ss -tlnp
# 确认每个端口都是必要的
八、小结
本篇介绍了 firewalld、iptables、ufw 三种防火墙工具,SELinux 强制访问控制,SSH 安全加固以及系统级安全加固清单。安全是一个持续的过程,建议定期进行安全审计和漏洞扫描。
上一篇 :10 - 日志管理与故障排查
下一篇 :12 - 性能监控与优化