← 返回首页
🔧

WAF安全:Web应用防火墙

📂 devops ⏱ 3 min 574 words

WAF安全:Web应用防火墙

什么是WAF

WAF(Web Application Firewall,Web应用防火墙)是专门保护Web应用的安全设备,通过过滤和监控HTTP/HTTPS流量来阻止常见的Web攻击。

WAF架构

WAF部署架构:
  ├── 透明模式: 串联部署,不改变网络拓扑
  ├── 反向代理模式: 作为代理,隐藏后端服务器
  ├── 旁路模式: 镜像流量分析,不影响业务
  └── 云WAF: 云端部署,通过DNS或CDN接入

ModSecurity配置

安装和基础配置

# Ubuntu安装ModSecurity
sudo apt-get update
sudo apt-get install libmodsecurity3 modsecurity-crs

# 配置ModSecurity
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

# 启用ModSecurity
sudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/modsecurity/modsecurity.conf

Nginx集成配置

# nginx-waf.conf
load_module /etc/nginx/modules/ngx_http_modsecurity_module.so;

server {
    listen 443 ssl http2;
    server_name example.com;
    
    # 启用ModSecurity
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
    
    location / {
        proxy_pass http://backend;
    }
}

# ModSecurity主配置
# /etc/nginx/modsec/main.conf
Include /etc/nginx/modsec/modsecurity.conf
Include /etc/nginx/modsec/crs-setup.conf
Include /etc/nginx/modsec/rules/*.conf

OWASP CRS配置

# /etc/nginx/modsec/crs-setup.conf

# CRS配置
SecAction \
  "id:900000,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.crs_setup_version=400"

# 设置Paranoia Level
SecAction \
  "id:900010,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.paranoia_level=1"

# 阻止SQL注入
SecRule REQUEST_URI|REQUEST_HEADERS|REQUEST_BODY \
  "@detectSQLi" \
  "id:942100,\
   phase:2,\
   block,\
   severity:CRITICAL,\
   msg:'SQL Injection Attack Detected'"

# 阻止XSS攻击
SecRule REQUEST_URI|REQUEST_HEADERS|REQUEST_BODY \
  "@detectXSS" \
  "id:941100,\
   phase:2,\
   block,\
   severity:CRITICAL,\
   msg:'XSS Attack Detected'"

自定义规则

速率限制规则

# 速率限制规则
# /etc/nginx/modsec/rules/custom-rates.conf

# 限制每IP每分钟请求数
SecRule IP:REQUEST_COUNT "@gt 100" \
  "id:100001,\
   phase:2,\
   block,\
   severity:WARNING,\
   msg:'Rate limit exceeded: {{IP}} {{REQUEST_COUNT}} requests/min'"

# 初始化计数器
SecAction \
  "id:100000,\
   phase:1,\
   nolog,\
   pass,\
   initcol:ip=%{REMOTE_ADDR}"

# 增加计数器
SecRule REQUEST_URI ".*" \
  "id:100002,\
   phase:1,\
   nolog,\
   pass,\
   setvar:ip.REQUEST_COUNT=+1,\
   expirevar:ip.REQUEST_COUNT=60"

白名单规则

# 白名单配置
# /etc/nginx/modsec/rules/whitelist.conf

# 白名单IP
SecRule REMOTE_ADDR "@ipMatch 10.0.0.0/8,192.168.0.0/16" \
  "id:100010,\
   phase:1,\
   nolog,\
   pass,\
   allow,\
   ctl:ruleEngine=Off"

# 白名单URL
SecRule REQUEST_URI "@streq /api/health" \
  "id:100011,\
   phase:1,\
   nolog,\
   pass,\
   allow,\
   ctl:ruleRemoveById=942100"

AWS WAF配置

Terraform配置

# aws-waf.tf

resource "aws_wafv2_web_acl" "main" {
  name        = "web-acl"
  description = "Web ACL for application"
  scope       = "REGIONAL"
  
  default_action {
    allow {}
  }
  
  # SQL注入防护
  rule {
    name     = "SQLInjectionRule"
    priority = 1
    
    override_action {
      none {}
    }
    
    statement {
      managed_rule_group_statement {
        name        = "AWSManagedRulesSQLiRuleSet"
        vendor_name = "AWS"
      }
    }
    
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name               = "SQLInjectionMetric"
      sampled_requests_enabled  = true
    }
  }
  
  # XSS防护
  rule {
    name     = "XSSRule"
    priority = 2
    
    override_action {
      none {}
    }
    
    statement {
      managed_rule_group_statement {
        name        = "AWSManagedRulesCommonRuleSet"
        vendor_name = "AWS"
      }
    }
    
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name               = "XSSMetric"
      sampled_requests_enabled  = true
    }
  }
  
  # 速率限制
  rule {
    name     = "RateLimitRule"
    priority = 3
    
    action {
      block {}
    }
    
    statement {
      rate_based_statement {
        limit              = 2000
        aggregate_key_type = "IP"
      }
    }
    
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name               = "RateLimitMetric"
      sampled_requests_enabled  = true
    }
  }
  
  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name               = "WebACLMetric"
    sampled_requests_enabled  = true
  }
  
  tags = {
    Environment = "production"
  }
}

# 关联ALB
resource "aws_wafv2_web_acl_association" "main" {
  resource_arn = aws_lb.main.arn
  web_acl_arn  = aws_wafv2_web_acl.main.arn
}

攻击检测和响应

日志分析脚本

#!/bin/bash
# waf-log-analysis.sh

LOG_FILE="/var/log/modsec/modsec_audit.log"

echo "=== WAF日志分析 ==="
echo "时间范围: 最近24小时"

# 1. 统计攻击类型
echo -e "\n--- 攻击类型统计 ---"
grep -E "SQL Injection|XSS|Path Traversal" $LOG_FILE | \
  grep -oE "(SQL Injection|XSS|Path Traversal)" | \
  sort | uniq -c | sort -rn

# 2. 统计攻击来源IP
echo -e "\n--- 攻击来源IP Top 10 ---"
grep "REMOTE_ADDR" $LOG_FILE | \
  grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | \
  sort | uniq -c | sort -rn | head -10

# 3. 统计被阻止的请求
echo -e "\n--- 被阻止请求统计 ---"
grep "403\|406\|501" $LOG_FILE | \
  awk '{print $1}' | \
  sort | uniq -c | sort -rn

实时监控告警

# prometheus-rules.yaml
groups:
  - name: waf-alerts
    rules:
      - alert: HighAttackRate
        expr: rate(waf_blocked_requests_total[5m]) > 100
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "攻击请求率过高"
          description: "当前攻击率 {{ $value }}/s"
      
      - alert: SQLInjectionSpike
        expr: rate(waf_sql_injection_total[5m]) > 50
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "SQL注入攻击激增"
          description: "检测到SQL注入攻击激增"

WAF测试

测试脚本

#!/bin/bash
# waf-test.sh

TARGET="https://example.com"

echo "=== WAF测试 ==="

# 1. SQL注入测试
echo -e "\n--- SQL注入测试 ---"
curl -s -o /dev/null -w "%{http_code}" "$TARGET/?id=1%20OR%201=1"

# 2. XSS测试
echo -e "\n--- XSS测试 ---"
curl -s -o /dev/null -w "%{http_code}" "$TARGET/?q=<script>alert(1)</script>"

# 3. 路径遍历测试
echo -e "\n--- 路径遍历测试 ---"
curl -s -o /dev/null -w "%{http_code}" "$TARGET/../../../etc/passwd"

# 4. 命令注入测试
echo -e "\n--- 命令注入测试 ---"
curl -s -o /dev/null -w "%{http_code}" "$TARGET/?cmd=;cat%20/etc/passwd"

最佳实践

  1. 规则更新: 定期更新WAF规则库
  2. 误报处理: 监控和处理误报,优化规则
  3. 日志分析: 定期分析WAF日志
  4. 性能监控: 监控WAF对性能的影响
  5. 应急响应: 制定WAF相关的应急响应流程