插件窝 干货文章 Nginx防火墙中怎样避免Web Shell的攻击

Nginx防火墙中怎样避免Web Shell的攻击

Nginx Shell 文件 攻击 833    来源:    2025-04-20

在Nginx防火墙中防范Web Shell攻击的综合策略

Web Shell攻击是常见的服务器入侵手段,通过在服务器上植入恶意脚本文件获取控制权。以下是针对Nginx环境的全面防护方案:

1. 基础防护措施

1.1 文件上传限制

location ~* \.(php|jsp|asp|aspx|sh|pl|py)$ {
    deny all;
    return 403;
}

1.2 禁用危险HTTP方法

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

2. 高级WAF规则配置

2.1 使用ModSecurity核心规则集(CRS)

SecRuleEngine On
SecRequestBodyAccess On
Include /path/to/owasp-modsecurity-crs/crs-setup.conf
Include /path/to/owasp-modsecurity-crs/rules/*.conf

2.2 特定Web Shell检测规则

SecRule REQUEST_URI|REQUEST_BODY "@rx (cmd\.exe|/bin/sh|wget|curl|nc|netcat|php\s*-r|eval\s*\(|base64_decode|system\s*\(|shell_exec\s*\()" \
    "id:1001,phase:2,log,deny,status:403,msg:'Web Shell Attack Detected'"

3. 文件系统监控

3.1 实时监控关键目录

# 使用inotify-tools监控web目录
inotifywait -m -r -e create,modify /var/www/html | while read path action file; do
    echo "文件变更: $path$file - $action"
    # 触发扫描或报警
done

4. 日志分析与实时告警

4.1 异常访问模式检测

map $status $loggable {
    ~^[23]  0;
    default 1;
}

access_log /var/log/nginx/access.log combined if=$loggable;

4.2 使用Fail2Ban自动封禁

# /etc/fail2ban/jail.d/nginx-webshell.conf
[nginx-webshell]
enabled = true
filter = nginx-webshell
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 3
bantime = 86400

5. 系统加固

5.1 权限最小化原则

chown -R www-data:www-data /var/www/html
find /var/www/html -type d -exec chmod 750 {} \;
find /var/www/html -type f -exec chmod 640 {} \;

5.2 PHP安全配置

; php.ini 关键设置
disable_functions = exec,passthru,shell_exec,system,proc_open,popen
open_basedir = /var/www/html
expose_php = Off

6. 定期维护

  • 每周执行Web Shell扫描工具如LMDClamAV
  • 每月审计服务器上的所有可执行文件
  • 及时更新Nginx和所有相关组件

7. 应急响应计划

  1. 发现可疑文件时立即隔离
  2. 分析访问日志确定入侵路径
  3. 修复漏洞后重置所有凭据
  4. 进行全面系统扫描

通过以上多层防御措施,可以显著降低Web Shell攻击的成功率,同时提高攻击检测能力。