You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

K8s Ingress中ModSecurity WAF日志如何屏蔽请求头或Bearer令牌?

问题描述

在K8s Ingress中为应用配置了ModSecurity WAF,已将SecAuditLogParts设为AZ(仅记录强制部分),但日志仍包含带有Bearer令牌的请求头。尝试使用SanitiseRequestHeader时因2023年10月上报的已知Bug导致部署报错,需实现日志不包含请求头或至少屏蔽敏感令牌。

当前配置

nginx.ingress.kubernetes.io/enable-owasp-core-rules: "true"
nginx.ingress.kubernetes.io/enable-modsecurity: "true"
nginx.ingress.kubernetes.io/modsecurity-snippet: |
  SecAuditEngine RelevantOnly
  SecRuleEngine On
  SecAuditLogParts AZ
  SecAuditLog /dev/stdout
  SecAuditLogFormat JSON
  SecRequestBodyAccess On

  SecRequestBodyLimit 104857600
  SecRequestBodyNoFilesLimit 5242880
  SecRequestBodyLimitAction Reject
  SecAction "id:900200,phase:1,nolog,pass,t:none,\
    setvar:tx.allowed_methods=GET HEAD POST OPTIONS PUT PATCH DELETE"

  SecRuleRemoveById 949110
  SecRule REQUEST_HEADERS:Content-Type "^application/[a-z0-9.-]+[+]json"  "id:9990001,phase:1,t:none,t:lowercase,pass,log,ctl:requestBodyProcessor=JSON"

日志示例

{
  "transaction": {
    "client_ip": "",
    "time_stamp": "",
    "server_id": "",
    "client_port": "",
    "host_ip": "",
    "host_port": "",
    "unique_id": "",
    "request":
      {
        "headers": { ... },
        ...
       },
    "response": { ... }, 
    "producer": { ... },
    "messages": { ... }
  }
}
解决方案
  • 彻底排除请求头:修改SecAuditLogParts参数
    将SecAuditLogParts AZ改为SecAuditLogParts Z,仅保留审计日志的强制结束部分,彻底移除所有请求相关内容。但此操作会丢失所有请求层面的审计信息,适合完全不需要请求日志的场景。

  • 屏蔽令牌:用ModSecurity变量替换敏感内容
    避开SanitiseRequestHeader的Bug,直接在日志生成阶段替换Authorization头中的令牌。在modsecurity-snippet中添加以下规则:

    # 捕获Bearer令牌并替换为占位符
    SecRule REQUEST_HEADERS:Authorization "@rx ^Bearer\s+.+" "id:9990002,phase:5,t:none,pass,nolog,setvar:tx.sanitized_auth=Bearer [REDACTED]"
    # 自定义JSON日志格式,替换原Authorization字段
    SecAuditLogFormat '{"transaction": {"client_ip":"%{client_ip}", "time_stamp":"%{time_stamp}", "request": {"headers": {"Authorization":"%{tx.sanitized_auth}"}, ...}, "response": {...}, "producer": {...}, "messages": {...}}}'
    

    注意:需根据默认JSON日志结构补全完整的格式字符串,确保其他字段正常输出,仅替换Authorization字段为 sanitized 的变量。

  • 修复Bug:升级Ingress Nginx版本
    若该Bug已在后续版本中修复,可升级Ingress Nginx至包含修复的版本,之后使用SanitiseRequestHeader指令屏蔽令牌:

    SanitiseRequestHeader Authorization "(Bearer\s+).+" "\1[REDACTED]"
    

    此方式更简洁,但需提前确认目标版本已修复该Bug。

  • 日志后处理:通过Nginx过滤修改输出
    若ModSecurity层面修改受限,可在Ingress的Nginx配置中添加日志后处理规则,比如用sed替换日志中的令牌内容。但此方式属于日志输出后的间接处理,可靠性不如ModSecurity层面的直接修改。

内容的提问来源于stack exchange,提问作者j0zeft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 17:53:17