Red Hat Training

A Red Hat training course is available for RHEL 8

1.11. 使用 ModSecurity 在 web 服务器上保护 Web 应用程序

ModSecurity 是一个开源 Web 应用程序防火墙(WAF),受到各种 web 服务器(如 Apache、Nginx 和 IIS)支持,它可以降低 web 应用程序中的安全风险。ModSecurity 为配置服务器提供了可自定义的规则集。

mod_security-crs 软件包包含核心规则集(CRS),针对跨 Web 站点脚本、错误的用户代理、SQL 注入、Trojans、会话劫持和其他利用的规则。

1.11.1. 为 Apache 部署基于 web 的 ModSecurity 应用程序防火墙

要通过部署 ModSecurity 来降低在 web 服务器上运行的基于 Web 的应用程序的风险,请为 Apache HTTP 服务器安装 mod_securitymod_security_crs 软件包。mod_security_crs 软件包为 ModSecurity 基于 Web 的应用程序防火墙(WAF)模块提供核心规则集(CRS)。

流程

  1. 安装 mod_securitymod_security_crshttpd 软件包:

    # yum install -y mod_security mod_security_crs httpd
  2. 启动 httpd 服务器:

    # systemctl restart httpd

验证

  1. 验证 Apache HTTP 服务器上是否启用了 ModSecurity 基于 web 的应用程序防火墙:

    # httpd -M | grep security
     security2_module (shared)
  2. 检查 /etc/httpd/modsecurity.d/activated_rules/ 目录是否包含由 mod_security_crs 提供的规则:

    # ls /etc/httpd/modsecurity.d/activated_rules/
    ...
    REQUEST-921-PROTOCOL-ATTACK.conf
    REQUEST-930-APPLICATION-ATTACK-LFI.conf
    ...

1.11.2. 向 ModSecurity 中添加自定义规则

如果 ModSecurity 核心规则集(CRS)中包含的规则不能适合您的场景,如果您想要阻止其他可能的攻击,则可以将自定义规则添加到 ModSecurity 基于 web 的应用防火墙使用的规则集中。以下示例演示了添加一条简单的规则。有关创建更复杂的规则,请参阅 ModSecurity Wiki 网站上的参考手册。

先决条件

  • ModSecurity for Apache 已安装并启用。

流程

  1. 在您选择的文本编辑器中打开 /etc/httpd/conf.d/mod_security.conf 文件,例如:

    # vi /etc/httpd/conf.d/mod_security.conf
  2. 在以 SecRuleEngine On 开头的行后添加以下示例规则:

    SecRule ARGS:data "@contains evil" "deny,status:403,msg:'param data contains evil data',id:1"

    如果 data 参数包含 evil 字符串,则前面的规则禁止用户使用资源。

  3. 保存更改,退出编辑器。
  4. 重启 httpd 服务器:

    # systemctl restart httpd

验证

  1. 创建一个 test.html 页面:

    # echo "mod_security test" > /var/www/html/test.html
  2. 重启 httpd 服务器:

    # systemctl restart httpd
  3. 请求 test.html ,而在 HTTP 请求的 GET 变量没有恶意数据:

    $ curl http://localhost/test.html?data=good
    
    mod_security test
  4. 请求 test.html ,而在 HTTP 请求的 GET 变量中带有恶意数据:

    $ curl localhost/test.html?data=xxxevilxxx
    
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html><head>
    <title>403 Forbidden</title>
    </head><body>
    <h1>Forbidden</h1>
    <p>You do not have permission to access this resource.</p>
    </body></html>
  5. 检查 /var/log/httpd/error_log 文件,并找到带有 param data containing an evil data 信息的拒绝访问的日志条目:

    [Wed May 25 08:01:31.036297 2022] [:error] [pid 5839:tid 139874434791168] [client ::1:45658] [client ::1] ModSecurity: Access denied with code 403 (phase 2). String match "evil" at ARGS:data. [file "/etc/httpd/conf.d/mod_security.conf"] [line "4"] [id "1"] [msg "param data contains evil data"] [hostname "localhost"] [uri "/test.html"] [unique_id "Yo4amwIdsBG3yZqSzh2GuwAAAIY"]

其它资源