{T}

服务器安全加固

0. 引言

进入"模块三 Web 安全建设":即使应用存在漏洞,安全加固策略也能提高攻击成本、阻止进一步攻击。本节以 Apache 与 Nginx 为例介绍服务器加固,并讲解 PHP 本身的安全配置。

1. Apache 服务器加固(httpd.conf / apache2.conf)

策略配置要点
删除默认页面删除 icons、manual 目录,避免信息泄露
关闭目录浏览Indexes 改为 -Indexes,防止目录无默认页时暴露文件列表
开启访问日志确认 CustomLog 已配置(/etc/apache2/sites-available/000-default.conf 等),便于安全事件回溯
禁止特定目录解析 PHP上传目录等无需执行脚本的目录关闭 PHP 解析,防上传漏洞攻击
apache
<Directory "/www/html/uploads">
  php_flag engine off
</Directory>
策略配置要点
不以 Root 启动确认 User/Group 为低权限账号(如 www-data)
禁止访问外部文件先 Deny 所有目录,再 Allow 网站根目录,防目录遍历(../)危害
错误页面重定向自定义各错误码页面,防路径等敏感信息泄露
apache
# 禁止任何目录访问,再开启网站根目录
Order Deny,Allow
Deny from all
Order Allow,Deny
Allow from {网站根目录}

# 错误页面重定向
ErrorDocument 404 /custom404.html
ErrorDocument 500 /custom500.html

2. Nginx 服务器加固(nginx.conf)

策略配置要点
关闭目录浏览默认关闭,确认 autoindex off
开启访问日志确认 access_log 已配置,便于追踪攻击途径
禁止特定目录解析 PHPdeny all 限制上传等目录的 PHP 解析
nginx
location ~* ^/data/cgisvr/log/.*\.(php|php5)$ {
    deny all;
}
策略配置要点
删除默认页面删除 /doc/images 等默认 location 配置
nginx
location /doc {
    root /usr/share;
    autoindex on;
    allow 127.0.0.1;
    deny all;
}

3. PHP 安全配置(php.ini)

配置项作用示例
open_basedir限制脚本访问权限,只能访问网站目录,限制木马危害open_basedir = /usr/local/apache2/htdocs
disable_functions禁止危险函数(木马常用命令执行函数)disable_functions = exec,popen,system,passthru,shell_exec,escapeshellarg,escapeshellcmd,proc_close,proc_open
display_errors关闭错误显示,防路径、SQL 语句等敏感信息泄露display_errors = Off
allow_url_fopen / allow_url_include禁止远程文件访问,防远程文件包含漏洞 getshell均设为 Off(需要时改用 libcurl)

注:PHP 近年安全能力持续提升,许多功能默认开启,部分旧配置项(如 magic_quotes_gpc)已被移除。

4. 小结

  • 统一原则:删默认页面、关目录浏览、开日志、禁上传目录解析、低权限运行、隔离外部文件、错误页重定向;
  • Apache 与 Nginx:加固项一一对应(Apache 用 Directory 指令,Nginx 用 location + deny all);
  • PHP 层:open_basedir 限目录、disable_functions 禁危险函数、display_errors 关回显、allow_url 禁远程文件——四者配合可有效遏制 Webshell 危害;
  • 加固无法消灭漏洞,但能显著提高攻击成本,是纵深防御的重要一环。

下一章讲解入侵排查与追踪。