A security solution that monitors HTTP/HTTPS traffic between a web application and the Internet and detects and blocks OWASP Top 10 web attacks such as SQL injection, XSS (Cross-Site Scripting), and CSRF. It combines signature-based detection with anomaly behavior analysis to defend against known attacks and zero-day attacks. AWS WAF, Cloudflare WAF, Imperva, and ModSecurity (open source) are representative, and in recent benchmarks Barracuda recorded a high detection rate of 91% for injection defense and Imperva 93% for vulnerable component defense.
WAF (Web Application Firewall) is a security solution that operates at Layer 7 (the application layer) of the OSI model. Unlike a traditional network firewall, which filters traffic based on IP/port, a WAF analyzes the content of HTTP requests (URI, headers, body, cookies) to detect malicious patterns. Deployed in front of a web server as a reverse proxy, it inspects all inbound traffic and forwards only safe requests to the backend.
WAF detection methods are broadly divided into signature-based and anomaly-based. Signature-based detection stores known attack patterns (e.g., ' OR 1=1 --, <script>alert) in a database and matches against them. The OWASP Core Rule Set (CRS) is the most widely used open-source signature set. Anomaly-based detection learns a baseline of normal traffic and detects requests that deviate from it. Modern WAFs combine both approaches and add machine learning to reduce false positives while increasing the detection rate.
WAF deployment models include on-premises appliances, cloud-based services, and software/container deployments. AWS WAF integrates with CloudFront, ALB, and API Gateway and can be enabled easily. Cloudflare WAF is integrated with the CDN and is provided together with DDoS protection. ModSecurity is an open-source WAF engine that can be used with Apache, Nginx, and IIS, and is used together with the OWASP CRS. Coraza is a modern open-source WAF written in Go, and integrates with Envoy, Caddy, and others.
A WAF is one layer of Defense in Depth and does not replace secure coding in the application itself. The fundamental defense against SQL injection is parameterized queries (Prepared Statements), and for XSS the fundamental countermeasure is output encoding. A WAF serves as Virtual Patching until the development team fixes a vulnerability, as an additional defense layer against unknown vulnerabilities, and as logging/monitoring for attack pattern analysis. Recently, API protection (API Gateway + WAF), bot detection, and rate limiting features are also being integrated.
💻 Code Example
# AWS WAF 구성 - Terraform
# OWASP Top 10 공격 방어를 위한 규칙 세트 구성
# WAF Web ACL 생성
resource "aws_wafv2_web_acl" "main" {
name = "production-waf"
description = "WAF for production environment"
scope = "REGIONAL" # ALB, API Gateway용. CloudFront는 CLOUDFRONT
default_action {
allow {} # 기본 허용, 규칙에 매치되면 차단
}
# 규칙 1: AWS 관리형 규칙 - SQL 인젝션 방어
rule {
name = "AWS-AWSManagedRulesSQLiRuleSet"
priority = 1
override_action {
none {} # 규칙 그대로 적용
}
statement {
managed_rule_group_statement {
name = "AWSManagedRulesSQLiRuleSet"
vendor_name = "AWS"
}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "SQLiRuleSet"
sampled_requests_enabled = true
}
}
# 규칙 2: AWS 관리형 규칙 - XSS 방어
rule {
name = "AWS-AWSManagedRulesCommonRuleSet"
priority = 2
override_action {
none {}
}
statement {
managed_rule_group_statement {
name = "AWSManagedRulesCommonRuleSet"
vendor_name = "AWS"
# 특정 규칙 오버라이드 (오탐 발생 시)
rule_action_override {
name = "SizeRestrictions_BODY"
action_to_use {
count {} # 차단 대신 카운트만
}
}
}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "CommonRuleSet"
sampled_requests_enabled = true
}
}
# 규칙 3: 알려진 악성 IP 차단
rule {
name = "AWS-AWSManagedRulesAmazonIpReputationList"
priority = 3
override_action {
none {}
}
statement {
managed_rule_group_statement {
name = "AWSManagedRulesAmazonIpReputationList"
vendor_name = "AWS"
}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "IpReputationList"
sampled_requests_enabled = true
}
}
# 규칙 4: Rate Limiting - DDoS/Brute Force 방어
rule {
name = "RateLimitRule"
priority = 4
action {
block {
custom_response {
response_code = 429
custom_response_body_key = "rate_limit_exceeded"
}
}
}
statement {
rate_based_statement {
limit = 2000 # 5분당 2000 요청
aggregate_key_type = "IP"
}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "RateLimitRule"
sampled_requests_enabled = true
}
}
# 규칙 5: 지역 기반 차단 (Geo Blocking)
rule {
name = "GeoBlockRule"
priority = 5
action {
block {}
}
statement {
geo_match_statement {
country_codes = ["CN", "RU", "KP"] # 예시: 특정 국가 차단
}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "GeoBlockRule"
sampled_requests_enabled = true
}
}
# 커스텀 응답 바디 정의
custom_response_body {
key = "rate_limit_exceeded"
content = "{\"error\": \"Too many requests. Please try again later.\"}"
content_type = "APPLICATION_JSON"
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "ProductionWAF"
sampled_requests_enabled = true
}
tags = {
Environment = "production"
ManagedBy = "terraform"
}
}
# WAF를 ALB에 연결
resource "aws_wafv2_web_acl_association" "alb" {
resource_arn = aws_lb.main.arn
web_acl_arn = aws_wafv2_web_acl.main.arn
}
# WAF 로그를 CloudWatch Logs로 전송
resource "aws_wafv2_web_acl_logging_configuration" "main" {
log_destination_configs = [aws_cloudwatch_log_group.waf.arn]
resource_arn = aws_wafv2_web_acl.main.arn
logging_filter {
default_behavior = "DROP" # 기본적으로 로깅 안 함
filter {
behavior = "KEEP"
condition {
action_condition {
action = "BLOCK" # 차단된 요청만 로깅
}
}
requirement = "MEETS_ANY"
}
}
}
# CloudWatch 알람 - 높은 차단률 감지
resource "aws_cloudwatch_metric_alarm" "waf_high_block_rate" {
alarm_name = "waf-high-block-rate"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = 2
metric_name = "BlockedRequests"
namespace = "AWS/WAFV2"
period = 300
statistic = "Sum"
threshold = 1000
alarm_description = "WAF blocked more than 1000 requests in 5 minutes"
dimensions = {
WebACL = aws_wafv2_web_acl.main.name
Region = data.aws_region.current.name
Rule = "ALL"
}
alarm_actions = [aws_sns_topic.alerts.arn]
}
# NGINX + ModSecurity (OWASP CRS) 설정
# 오픈소스 WAF 구성
# === modsecurity.conf (메인 설정) ===
SecRuleEngine On # WAF 활성화 (DetectionOnly로 테스트 가능)
# 요청 바디 처리
SecRequestBodyAccess On
SecRequestBodyLimit 13107200 # 12.5MB
SecRequestBodyNoFilesLimit 131072 # 128KB (파일 제외)
# 응답 바디 처리 (선택)
SecResponseBodyAccess Off
# 감사 로그 설정
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))" # 4xx, 5xx 응답 로깅 (404 제외)
SecAuditLogParts ABIJDEFHZ
SecAuditLogType Serial
SecAuditLog /var/log/modsec_audit.log
# 디버그 로그
SecDebugLog /var/log/modsec_debug.log
SecDebugLogLevel 0 # 프로덕션: 0, 디버깅: 3-9
# 기본 액션 설정
SecDefaultAction "phase:1,deny,status:403,log"
# === OWASP CRS 규칙 로드 ===
Include /etc/nginx/modsecurity/crs-setup.conf
Include /etc/nginx/modsecurity/rules/*.conf
# === 커스텀 규칙 ===
# SQL 인젝션 강화 탐지
SecRule ARGS|ARGS_NAMES|REQUEST_COOKIES|REQUEST_HEADERS \
"@rx (?i)(?:select|insert|update|delete|drop|union|exec)\s+" \
"id:100001,\
phase:2,\
deny,\
status:403,\
log,\
msg:'SQL Injection Attempt',\
tag:'OWASP_CRS',\
tag:'attack-sqli'"
# XSS 강화 탐지
SecRule ARGS|ARGS_NAMES|REQUEST_BODY \
"@rx (?i)
"A WAF is one layer of defense in depth, not a cure-all. The fundamental defense against SQL injection is Prepared Statements, and for XSS it is output encoding. A WAF should be viewed as virtual patching before the development team patches a vulnerability, an additional defense against zero-days, and logging for attack pattern analysis."
💬 In a WAF adoption discussion
"Let's start by running in DetectionOnly mode for about two weeks and identify false positives. The OWASP CRS is strict by default, so it can block legitimate requests too. For rules that cause false positives, you can add exceptions for specific URIs or adjust the score threshold, and then switch to blocking mode."
💬 In an incident analysis
"Analyzing the WAF logs, we found an automated SQL injection scan using SQLMap from a specific IP. The WAF blocked it, but we should permanently block this IP range and also verify at the code level whether that endpoint is vulnerable. A WAF buys time; it does not replace a fundamental fix."
⚠️ Cautions & Best Practices
❌
The misconception that a WAF alone completes security
A WAF defends against known attack patterns, but it has limitations against business logic vulnerabilities, authentication/authorization bypass, and zero-day attacks. It should be used together with secure coding, code review, and penetration testing.
❌
Neglecting excessive False Positives
When legitimate requests are blocked, the user experience suffers and the development team tries to disable the WAF. Regularly analyze block logs and tune the rules that cause false positives. Adding exceptions only for specific URIs is also an option.
❌
Missing rule updates
When a new vulnerability (CVE) is discovered, WAF rules must be updated as well. The OWASP CRS receives regular updates, and a CRS bypass vulnerability such as CVE-2026-21876 was recently discovered. Update to 4.22.0 or later.
✅
WAF Best Practices
Start with DetectionOnly, and switch to blocking mode after analyzing false positives. Use the OWASP CRS as the baseline, and add application-specific custom rules. Integrate block logs with a SIEM for threat hunting, and configure Rate Limiting and Geo Blocking together.