WAF 是什么?Web 应用防火墙详解
Security

WAF 是什么?Web 应用防火墙详解

WAF(Web 应用防火墙)提供第 7 层防护,抵御 SQL 注入、XSS、LFI 等 Web 应用攻击。了解工作原理、ModSecurity、AWS WAF、Cloudflare WAF 及部署模式。

系列文章: 安全
  1. 1 什么是勒索软件?文件加密恶意软件与防护策略
  2. 2 WAF 是什么?Web 应用防火墙详解
✦ 快速摘要
WAF(Web 应用防火墙)提供第 7 层防护,抵御 SQL 注入、XSS、LFI 等 Web 应用攻击。了解工作原理、ModSecurity、AWS WAF、Cloudflare WAF 及部署模式。
这篇文章怎么样?

WAF 是什么?为什么需要它?

WAF(Web 应用防火墙)是一种工作在 OSI 模型第 7 层的安全组件,用于监控和过滤互联网与 Web 应用之间的 HTTP/HTTPS 流量。

与仅检查 IP 地址和端口的传统防火墙不同,WAF 能理解 HTTP 请求的语义——分析 URL、请求头、Cookie、查询字符串和请求体,从而识别攻击模式。

为什么需要 WAF?

Web 应用是头号攻击目标。根据 Verizon DBIR 2024 报告,超过 40% 的数据泄露事件涉及 Web 应用。OWASP Top 10——十大最关键 Web 安全风险榜单——中的所有风险都可以由配置得当的 WAF 检测并拦截。

WAF vs. 防火墙 vs. IDS/IPS:

类型 层次 分析内容 检测目标
网络防火墙 L3/L4 IP、端口、协议 IP 拦截、端口过滤
IDS/IPS L3–L7 数据包模式 网络入侵
WAF L7 HTTP 载荷 SQLi、XSS、LFI、RCE

WAF 的检测机制

1. 基于签名的检测

将每个请求与已知攻击签名数据库进行比对。速度快、误报少,但只能检测已知攻击。

Request: GET /users?id=1' OR '1'='1
WAF rule: matches SQL injection pattern → BLOCK

2. 基于异常的检测(规则评分)

对每个请求计算异常分数,超过阈值则触发拦截。比纯签名匹配更难被绕过。

3. 基于机器学习 / 行为的检测

学习正常流量基线,检测偏差。对零日漏洞和未知攻击有效,但调优较为复杂。

**OWASP 核心规则集(CRS)**是 WAF 最广泛使用的开放规则集,涵盖:

  • SQL 注入(REQUEST-942)
  • XSS(REQUEST-941)
  • 本地文件包含(REQUEST-930)
  • 远程代码执行(REQUEST-932)
  • 扫描器检测(REQUEST-913)

ModSecurity 与 OWASP CRS 实战

ModSecurity 是嵌入 NGINX 或 Apache 的开源 WAF 引擎。与 OWASP CRS 结合使用时,是最流行的自托管 WAF 解决方案。

在 NGINX 上安装 ModSecurity:

Bash
1# Cài modsecurity và nginx connector
2apt-get install libmodsecurity3 libmodsecurity-dev
3git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx
4# Build nginx với modsecurity module

NGINX 配置:

nginx
1load_module modules/ngx_http_modsecurity_module.so;
2
3server {
4    listen 443 ssl;
5    modsecurity on;
6    modsecurity_rules_file /etc/nginx/modsec/main.conf;
7}

ModSecurity 规则示例——检测 SQL 注入:

SecRule ARGS "@detectSQLi" \
    "id:942100,\
    phase:2,\
    block,\
    capture,\
    t:none,t:utf8toUnicode,t:urlDecodeUni,t:removeNulls,t:removeComments,t:compressWhitespace,\
    msg:'SQL Injection Attack Detected via libinjection',\
    logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',\
    tag:'application-multi',\
    tag:'language-multi',\
    tag:'platform-multi',\
    tag:'attack-sqli',\
    tag:'OWASP_CRS',\
    tag:'capec/1000/152/248/66',\
    tag:'PCI/6.5.2',\
    ver:'OWASP_CRS/3.3.4',\
    severity:'CRITICAL',\
    setvar:'tx.sql_injection_score=+%{tx.critical_anomaly_score}',\
    setvar:'tx.anomaly_score_pl1=+%{tx.critical_anomaly_score}'"

每条规则包含:idphase(处理阶段)、block/detect、转换链、消息、标签、严重程度和异常分数动作。

市场上的主流 WAF 产品

AWS WAF:

  • 托管服务,与 CloudFront、ALB 和 API Gateway 集成
  • 提供现成的托管规则组(AWS 托管规则、Bot 控制、欺诈控制)
  • 通过控制台或 Terraform 管理规则
hcl
 1resource "aws_wafv2_web_acl" "example" {
 2  name  = "example-waf"
 3  scope = "REGIONAL"
 4
 5  default_action { allow {} }
 6
 7  rule {
 8    name     = "AWSManagedRulesCommonRuleSet"
 9    priority = 1
10    override_action { none {} }
11    statement {
12      managed_rule_group_statement {
13        name        = "AWSManagedRulesCommonRuleSet"
14        vendor_name = "AWS"
15      }
16    }
17    visibility_config {
18      cloudwatch_metrics_enabled = true
19      metric_name                = "CommonRuleSetMetric"
20      sampled_requests_enabled   = true
21    }
22  }
23
24  visibility_config {
25    cloudwatch_metrics_enabled = true
26    metric_name                = "ExampleWAF"
27    sampled_requests_enabled   = true
28  }
29}

Cloudflare WAF: 托管规则与自定义规则兼备,易于使用,集成 CDN 和 DDoS 防护。

ModSecurity(自托管): 开源、完全可控、成本低,但需要自行维护。

WAF 绕过技术(教育目的)

了解绕过技术有助于更有效地调优 WAF,并认识其局限性。

URL 编码绕过:

# Payload gốc (bị block):
' OR '1'='1

# URL encoded (có thể bypass WAF không decode đúng):
%27%20OR%20%271%27%3D%271

大小写变形:

SQL
1# Original (blocked):
2SELECT * FROM users
3
4# Bypass attempt:
5SeLeCt * FrOm UsErS

现代 WAF 通过以下方式防御绕过:匹配前对输入进行规范化处理(转小写、URL 解码、多轮 HTML 解码),使用基于解析器的检测代替简单正则表达式,以及利用机器学习检测规避模式。

注意: 绕过技术知识仅应用于测试自己的 WAF(渗透测试)或用于更好地理解 WAF 配置。

WAF 部署模式

内联(拦截模式):

  • WAF 直接位于请求路径中
  • 立即拦截恶意请求
  • 风险:配置错误可能拦截合法用户
  • 适合在规则充分调优后使用

监控(仅检测模式):

  • WAF 记录日志但不拦截
  • 适合初次部署时观察误报情况
  • 监控 2–4 周后,调整规则,再切换至拦截模式

接入 WAF 的最佳实践:

  1. 以监控模式部署
  2. 运行 2–4 周,每天审查日志
  3. 为误报添加白名单(自定义排除规则)
  4. 对已验证的规则启用拦截模式
  5. 持续监控并定期调优

SQL 注入是什么?WAF 如何防御

XSS 是什么?跨站脚本攻击与防御

API 网关是什么?架构与 WAF 集成

TLS 1.3 是什么?高级 HTTPS 加密

常见问题Q&A

What Is a WAF and Why Do You Need One?

A WAF (Web Application Firewall) is a security component that operates at Layer 7 of the OSI model, monitoring and filtering HTTP/HTTPS traffic between the internet and your web application.

Unlike traditional firewalls that only inspect IP addresses and ports, a WAF understands the semantics of HTTP requests — analyzing URLs, headers, cookies, query strings, and request bodies to detect attack patterns.

Why do you need a WAF?

Web applications are the number one attack target. According to the Verizon DBIR 2024 report, more than 40% of data breaches involve web applications. The OWASP Top 10 — the list of the ten most critical web security risks — can all be detected and blocked by a properly configured WAF.

WAF vs. Firewall vs. IDS/IPS:

Type Layer Analyzes Detects
Network Firewall L3/L4 IP, Port, Protocol IP block, port filter
IDS/IPS L3–L7 Packet pattern Network intrusion
WAF L7 HTTP payload SQLi, XSS, LFI, RCE

How WAF Detection Works

1. Signature-based detection

Compares each request against a database of known attack signatures. Fast with low false positives, but only catches known attacks.

Request: GET /users?id=1' OR '1'='1
WAF rule: matches SQL injection pattern → BLOCK

2. Anomaly-based detection (Rule scoring)

Each request receives an anomaly score. Exceeding the threshold triggers a block. Less susceptible to bypass than pure signature matching.

3. ML-based / Behavioral detection

Learns a baseline of normal traffic and flags deviations. Effective against zero-days and unknown attacks, but more complex to tune.

OWASP Core Rule Set (CRS) is the most widely used open rule set for WAFs, covering:

  • SQL Injection (REQUEST-942)
  • XSS (REQUEST-941)
  • Local File Inclusion (REQUEST-930)
  • Remote Code Execution (REQUEST-932)
  • Scanner detection (REQUEST-913)

ModSecurity and OWASP CRS in Practice

ModSecurity is an open-source WAF engine embedded into NGINX or Apache. Combined with OWASP CRS, it is the most popular self-hosted WAF solution.

Installing ModSecurity with NGINX:

Bash
1# Cài modsecurity và nginx connector
2apt-get install libmodsecurity3 libmodsecurity-dev
3git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx
4# Build nginx với modsecurity module

NGINX configuration:

nginx
1load_module modules/ngx_http_modsecurity_module.so;
2
3server {
4    listen 443 ssl;
5    modsecurity on;
6    modsecurity_rules_file /etc/nginx/modsec/main.conf;
7}

Example ModSecurity rule — detecting SQL injection:

SecRule ARGS "@detectSQLi" \
    "id:942100,\
    phase:2,\
    block,\
    capture,\
    t:none,t:utf8toUnicode,t:urlDecodeUni,t:removeNulls,t:removeComments,t:compressWhitespace,\
    msg:'SQL Injection Attack Detected via libinjection',\
    logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',\
    tag:'application-multi',\
    tag:'language-multi',\
    tag:'platform-multi',\
    tag:'attack-sqli',\
    tag:'OWASP_CRS',\
    tag:'capec/1000/152/248/66',\
    tag:'PCI/6.5.2',\
    ver:'OWASP_CRS/3.3.4',\
    severity:'CRITICAL',\
    setvar:'tx.sql_injection_score=+%{tx.critical_anomaly_score}',\
    setvar:'tx.anomaly_score_pl1=+%{tx.critical_anomaly_score}'"

Each rule includes: id, phase (processing stage), block/detect, a transform chain, message, tags, severity, and anomaly score actions.

AWS WAF:

  • Managed service, integrates with CloudFront, ALB, and API Gateway
  • Ready-made managed rule groups (AWS Managed Rules, Bot Control, Fraud Control)
  • Manage rules via the Console or Terraform
hcl
 1resource "aws_wafv2_web_acl" "example" {
 2  name  = "example-waf"
 3  scope = "REGIONAL"
 4
 5  default_action { allow {} }
 6
 7  rule {
 8    name     = "AWSManagedRulesCommonRuleSet"
 9    priority = 1
10    override_action { none {} }
11    statement {
12      managed_rule_group_statement {
13        name        = "AWSManagedRulesCommonRuleSet"
14        vendor_name = "AWS"
15      }
16    }
17    visibility_config {
18      cloudwatch_metrics_enabled = true
19      metric_name                = "CommonRuleSetMetric"
20      sampled_requests_enabled   = true
21    }
22  }
23
24  visibility_config {
25    cloudwatch_metrics_enabled = true
26    metric_name                = "ExampleWAF"
27    sampled_requests_enabled   = true
28  }
29}

Cloudflare WAF: Managed and custom rules, easy to use, integrated with CDN and DDoS protection.

ModSecurity (self-hosted): Open-source, full control, low cost but requires self-maintenance.

WAF Bypass Techniques (Educational)

Understanding bypass techniques helps you tune your WAF more effectively and recognize its limitations.

URL Encoding bypass:

# Payload gốc (bị block):
' OR '1'='1

# URL encoded (có thể bypass WAF không decode đúng):
%27%20OR%20%271%27%3D%271

Case variation:

SQL
1# Original (blocked):
2SELECT * FROM users
3
4# Bypass attempt:
5SeLeCt * FrOm UsErS

Modern WAFs counter bypass attempts by: normalizing input before matching (lowercase, URL decode, multiple rounds of HTML decode), using parser-based detection instead of simple regex, and applying ML to detect evasion patterns.

Note: Knowledge of bypass techniques should only be used to test your own WAF (penetration testing) or to better understand how to configure WAF rules.

WAF Deployment Modes

Inline (Blocking mode):

  • The WAF sits directly in the request path
  • Bad requests are blocked immediately
  • Risk: misconfiguration can block legitimate users
  • Best suited after thorough rule tuning

Monitor (Detection-only mode):

  • The WAF logs but does not block
  • Ideal when first deploying, allowing you to observe false positives
  • After 2–4 weeks of monitoring, tune rules, then switch to blocking

Best practices when onboarding a WAF:

  1. Deploy in monitor mode
  2. Run for 2–4 weeks, reviewing logs daily
  3. Whitelist false positives (custom exclude rules)
  4. Enable blocking mode for verified rules
  5. Continue monitoring and tuning regularly

What is SQL Injection? How WAF blocks it

What is XSS? Cross-site scripting attack and defense

What is an API Gateway? Architecture and WAF integration

What is TLS 1.3? Advanced HTTPS encryption

Frequently Asked QuestionsQ&A