Master Linux Security Hardening: Advanced firewalld Rules & SELinux Context Management
This guide presents a production‑tested Linux hardening strategy that combines advanced firewalld zone and rich‑rule configurations with precise SELinux context management, offering step‑by‑step commands, custom scripts, troubleshooting tips, and performance optimizations to protect servers from the majority of common attacks.
Why Harden Linux Servers?
Over 80% of security incidents stem from misconfiguration; many operators rely on simple iptables rules only to discover breaches late at night.
Advanced firewalld Rules: From Basics to Mastery
Core Concepts
firewalld is a zone‑based dynamic firewall, not merely an iptables wrapper.
# 查看当前活跃区域
firewall-cmd --get-active-zones
# 默认区域查看
firewall-cmd --get-default-zoneScenario 1: Web Server Hardening
Goal: expose HTTPS publicly while restricting management ports to specific IPs.
# 创建自定义区域
firewall-cmd --permanent --new-zone=webserver
firewall-cmd --permanent --new-zone=management
# 配置Web服务区域
firewall-cmd --permanent --zone=webserver --add-service=https
firewall-cmd --permanent --zone=webserver --add-port=80/tcp
# 管理区域仅允许特定IP段
firewall-cmd --permanent --zone=management --add-source=192.168.1.0/24
firewall-cmd --permanent --zone=management --add-port=22/tcp
firewall-cmd --permanent --zone=management --add-port=3306/tcp
# 应用配置
firewall-cmd --reloadScenario 2: Rich Rules Power
Rich rules enable rate‑limiting, time‑based ports, and logging.
# 限制SSH连接频率,防暴力破解
firewall-cmd --permanent --add-rich-rule='
rule service name="ssh" accept limit value="3/m"'
# 特定时间段开放特定端口
firewall-cmd --permanent --add-rich-rule='
rule family="ipv4" source address="10.0.0.0/8" port protocol="tcp" port="8080" accept'
# 记录拒绝连接的日志
firewall-cmd --permanent --add-rich-rule='
rule service name="ftp" log prefix="FTP-REJECT: " level="warning" reject'Advanced Technique: IPSET Management
IPSET efficiently handles large IP lists.
# 创建IP集合
firewall-cmd --permanent --new-ipset=blacklist --type=hash:ip
# 添加恶意IP
firewall-cmd --permanent --ipset=blacklist --add-entry=1.2.3.4
firewall-cmd --permanent --ipset=blacklist --add-entry=5.6.7.8
# 在规则中使用IP集合
firewall-cmd --permanent --add-rich-rule='
rule source ipset="blacklist" drop'SELinux Context Management: Deep Defense
How SELinux Works
SELinux enforces MAC; each process and file carries a security context.
# 查看文件安全上下文
ls -Z /etc/passwd
# -rw-r--r--. root root system_u:object_r:passwd_file_t:s0 /etc/passwd
# 查看进程安全上下文
ps -eZ | grep httpdScenario 3: Web Service SELinux Configuration
Common issue: Apache cannot read user‑home directories.
# 检查SELinux状态
sestatus
# 查看SELinux布尔值
getsebool -a | grep httpd
# 允许Apache访问用户目录
setsebool -P httpd_enable_homedirs on
# 设置正确的文件上下文
semanage fcontext -a -t httpd_exec_t "/var/www/html/myapp(/.*)?"
restorecon -Rv /var/www/html/myapp/Scenario 4: Custom Application SELinux Policy
# 生成策略模板
sepolicy generate --init /usr/local/bin/myapp
# 编译并安装策略
make -f /usr/share/selinux/devel/Makefile myapp.pp
semodule -i myapp.pp
# 设置文件上下文
semanage fcontext -a -t myapp_exec_t "/usr/local/bin/myapp"
restorecon /usr/local/bin/myappSELinux Troubleshooting Tricks
# 查看SELinux拒绝日志
ausearch -m AVC -ts recent
# 使用audit2why分析原因
ausearch -m AVC -ts recent | audit2why
# 生成允许规则(谨慎使用)
ausearch -m AVC -ts recent | audit2allow -M mypolicy
semodule -i mypolicy.ppProduction Best Practices
1. Layered Defense
# 网络层
firewall-cmd --set-default-zone=drop
firewall-cmd --permanent --zone=public --add-service=ssh
firewall-cmd --permanent --zone=public --add-rich-rule='
rule family="ipv4" source address="!192.168.0.0/16" service name="ssh" limit value="2/m" accept'2. Automated Deployment Script
#!/bin/bash
# security_harden.sh – one‑click hardening
configure_firewall() {
systemctl enable firewalld
systemctl start firewalld
firewall-cmd --set-default-zone=drop
firewall-cmd --permanent --zone=public --add-service=ssh
firewall-cmd --reload
echo "✅ Firewalld配置完成"
}
configure_selinux() {
setenforce 1
sed -i 's/SELINUX=disabled/SELINUX=enforcing/' /etc/selinux/config
setsebool -P allow_execheap off
setsebool -P allow_execstack off
echo "✅ SELinux配置完成"
}
configure_firewall
configure_selinux3. Monitoring & Alerting
# 创建监控脚本
cat > /usr/local/bin/security_monitor.sh <<'EOF'
#!/bin/bash
DENIALS=$(ausearch -m AVC -ts today | wc -l)
if [ $DENIALS -gt 10 ]; then
echo "⚠️ SELinux拒绝事件过多: $DENIALS"
ausearch -m AVC -ts today | tail -5
fi
if ! systemctl is-active firewalld >/dev/null; then
echo "🚨 防火墙服务异常!"
fi
EOF
chmod +x /usr/local/bin/security_monitor.sh
# 每两小时运行一次
echo "0 */2 * * * /usr/local/bin/security_monitor.sh" | crontab -Pitfalls & Tips
Common Mistake 1: Zone Mis‑binding
# ❌ 错误做法
firewall-cmd --zone=public --add-service=http # 接口可能在其他zone
# ✅ 正确做法
firewall-cmd --get-active-zones
firewall-cmd --zone=public --change-interface=eth0
firewall-cmd --zone=public --add-service=httpCommon Mistake 2: SELinux Context Reset
# ❌ 临时修改上下文
chcon -t httpd_exec_t /var/www/myapp
# ✅ 永久策略设置
semanage fcontext -a -t httpd_exec_t /var/www/myapp
restorecon /var/www/myappPerformance Optimizations
Rule Order Optimization: Place frequently matched rules first.
Use IPSET: Improves performance when handling many IPs.
SELinux Caching: Persist boolean changes with setsebool -P.
Verification
Run security scanners after deployment:
# nmap -sS -O target_ip
# lynis audit systemConclusion
Combining advanced firewalld rules with fine‑grained SELinux context management creates a multi‑layered defense that mitigates the majority of common attacks in production environments.
Remember: Hardening is an ongoing process; regular reviews and updates are essential.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
