在CentOS上搭建Web服务器时,网络安全是需要重点考虑的环节。以下是关键注意事项及解决方案:
最小化安装
yum remove $(package-cleanup --leaves)
用户与权限控制
# 禁用root远程登录
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
systemctl restart sshd
# 创建专用web用户
useradd -r -s /sbin/nologin webadmin
防火墙配置(firewalld)
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --remove-service=ssh # 如需SSH需单独配置端口
firewall-cmd --reload
Apache安全设置
# /etc/httpd/conf/httpd.conf
ServerTokens Prod
ServerSignature Off
TraceEnable Off
FileETag None
# 限制目录权限
<Directory /var/www/html>
Options -Indexes -Includes
AllowOverride None
</Directory>
Nginx安全设置
# /etc/nginx/nginx.conf
server_tokens off;
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
# 限制HTTP方法
limit_except GET POST { deny all; }
文件权限控制
chown -R webadmin:webadmin /var/www/html
find /var/www/html -type d -exec chmod 750 {} \;
find /var/www/html -type f -exec chmod 640 {} \;
数据库安全
-- MySQL示例
DELETE FROM mysql.user WHERE User='';
DROP DATABASE test;
FLUSH PRIVILEGES;
自动化更新
# 配置自动安全更新
yum install -y yum-cron
sed -i 's/apply_updates = no/apply_updates = yes/' /etc/yum/yum-cron.conf
systemctl enable --now yum-cron
日志监控
# 安装日志分析工具
yum install -y logwatch
echo "/usr/sbin/logwatch --output mail --mailto admin@example.com" >> /etc/cron.daily/0logwatch
Fail2Ban安装
yum install -y epel-release
yum install -y fail2ban
systemctl enable --now fail2ban
ModSecurity安装(Apache)
yum install -y mod_security mod_security_crs
cp /etc/httpd/modsecurity.d/modsecurity.conf-recommended /etc/httpd/modsecurity.d/modsecurity.conf
systemctl restart httpd
使用Let's Encrypt免费证书
yum install -y certbot python2-certbot-apache
certbot --apache -d example.com --non-interactive --agree-tos -m admin@example.com
# 设置自动续期
echo "0 0,12 * * * root python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew" | sudo tee -a /etc/crontab > /dev/null
强加密套件配置(Nginx示例)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 每日自动备份
tar -zcvf /backups/web-$(date +%Y%m%d).tar.gz /var/www/html
mysqldump -u root -p[password] --all-databases > /backups/db-$(date +%Y%m%d).sql
find /backups -type f -mtime +30 -delete
建议定期进行:
1. 漏洞扫描(使用OpenVAS或Nessus)
2. 渗透测试(使用Metasploit框架)
3. 安全审计(使用Lynis:yum install lynis && lynis audit system
)
通过以上措施的综合实施,可显著提升CentOS Web服务器的安全性。安全防护需要持续维护,建议至少每季度进行一次全面安全检查。