CentOS Apache日志安全审计指南
要实现有效的安全审计,首先需要配置Apache日志以记录足够的安全相关信息。修改Apache主配置文件(/etc/httpd/conf/httpd.conf)或虚拟主机配置文件,设置自定义日志格式,包含客户端IP、请求时间、方法、路径、状态码、Referer、User-Agent及真实IP(适用于反向隧道)等关键字段,例如:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %{X-Forwarded-For}i" combined_with_all_vars
将此格式应用于访问日志(CustomLog "/var/log/httpd/access_log" combined_with_all_vars)和错误日志(ErrorLog "/var/log/httpd/error_log")。确保日志路径存在且Apache用户(通常为apache或httpd)有写入权限(chown apache:apache /var/log/httpd/*.log)。
访问日志记录所有对网站的HTTP请求,是检测异常行为的核心来源。需重点监控以下内容:
POST /login.php),统计同一IP的失败次数。例如,使用命令grep "POST /login.php" /var/log/httpd/access_log | awk '{print $1}' | sort | uniq -c | sort -nr,若某IP尝试次数超过阈值(如10次/分钟),可能存在暴力破解。sqlmap、nikto、wget、curl)或访问敏感路径(如wp-admin、wp-login、adminer、phpmyadmin)的请求,例如grep -i "sqlmap\|wp-admin" /var/log/httpd/access_log。PUT、DELETE,若未开启此类功能)或大体积POST请求(可能用于数据上传攻击),可通过LimitRequestBody指令限制POST数据大小(如LimitRequestBody 1048576,限制为1MB)。错误日志记录服务器处理请求时的故障信息,可揭示攻击者的攻击意图。需重点关注:
union、select.*from、order by、syntax error),例如grep -i "union\|select.*from" /var/log/httpd/error_log。../(试图访问上级目录)或文件路径的内容(如/etc/passwd),例如grep -i "\.\./" /var/log/httpd/error_log。PHP Notice: Undefined variable可能暴露代码逻辑),可通过grep -i "PHP Error" /var/log/httpd/error_log筛选。手动分析日志效率低,需借助自动化工具实现实时监控与告警:
/etc/fail2ban/jail.local,启用apache-auth监狱(针对登录失败),设置maxretry(最大尝试次数,如5次)、findtime(时间窗口,如1分钟)、bantime(封锁时间,如30分钟),例如:[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/httpd/error_log
maxretry = 5
findtime = 60
bantime = 1800
重启Fail2ban后,符合条件的IP将被自动加入防火墙封锁列表。/etc/logwatch/conf/services/http.conf,设置Title = "Apache Security Audit",并启用每日报告。goaccess /var/log/httpd/access_log -o /var/www/html/report.html --log-format=COMBINED,即可生成HTML报告。日志本身是安全审计的关键证据,需采取措施保护其完整性与保密性:
root和apache用户读取,例如chmod 640 /var/log/httpd/*.log、chown root:apache /var/log/httpd/*.log。logrotate定期压缩、删除旧日志,避免日志文件过大占用磁盘空间。编辑/etc/logrotate.d/httpd,设置rotate 30(保留30天)、compress(压缩旧日志)、missingok(缺失日志不报错),例如:/var/log/httpd/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 root apache
sharedscripts
postrotate
systemctl reload httpd > /dev/null 2>&1 || true
endscript
}
Tripwire或AIDE等工具定期校验日志文件的哈希值,确保未被篡改。安装后配置策略文件,添加日志路径(如/var/log/httpd/access_log),定期运行校验命令(如tripwire --check)。omfwd模块配置TLS参数,或Logstash的Beats输入默认使用SSL),防止中间人攻击窃取日志。logrotate的maxage参数设置日志保留天数。grok过滤器提取并替换密码字段:filter {
grok {
match => { "message" => "(?<pre_password>password=)(?<password_value>[^& ]+)" }
add_field => { "sanitized_message" => "%{pre_password}[REDACTED]" }
remove_field => ["password_value"]
}
mutate {
replace => { "message" => "%{sanitized_message}" }
remove_field => ["sanitized_message"]
}
}
auditd监控/var/log/httpd/目录的写入操作,配置/etc/audit/audit.rules添加规则:-w /var/log/httpd/ -p wa -k apache_logs
使用ausearch -k apache_logs查看相关操作记录。