🔒 Security

WAF

Web Application Firewall

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.

📖 Detailed Explanation

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)]*>|javascript:|on\w+\s*=" \
    "id:100002,\
     phase:2,\
     deny,\
     status:403,\
     log,\
     msg:'XSS Attack Attempt',\
     tag:'attack-xss'"

# 경로 탐색 공격 방어
SecRule REQUEST_URI|ARGS \
    "@rx (?:\.\.[\\/]|\.\.%2f|\.\.%5c)" \
    "id:100003,\
     phase:1,\
     deny,\
     status:403,\
     log,\
     msg:'Path Traversal Attempt'"

# 특정 User-Agent 차단 (스캐너, 봇)
SecRule REQUEST_HEADERS:User-Agent \
    "@rx (?i)(sqlmap|nikto|nmap|masscan|havij|acunetix)" \
    "id:100004,\
     phase:1,\
     deny,\
     status:403,\
     log,\
     msg:'Security Scanner Detected'"

# API 엔드포인트별 커스텀 규칙
SecRule REQUEST_URI "@beginsWith /api/admin" \
    "id:100005,\
     phase:1,\
     chain"
    SecRule REMOTE_ADDR "!@ipMatch 10.0.0.0/8,192.168.0.0/16" \
        "deny,\
         status:403,\
         log,\
         msg:'Admin API access from non-internal IP'"

# === nginx.conf 설정 ===
# http {
#     modsecurity on;
#     modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
#
#     server {
#         listen 443 ssl;
#         server_name example.com;
#
#         # WAF 적용
#         modsecurity on;
#
#         location / {
#             proxy_pass http://backend;
#         }
#
#         # 특정 경로 WAF 제외 (예: 파일 업로드)
#         location /api/upload {
#             modsecurity off;  # 또는 modsecurity_rules 'SecRuleRemoveById 100001';
#             proxy_pass http://backend;
#         }
#     }
# }

# === 규칙 제외 (오탐 처리) ===
# 특정 URI에서 특정 규칙 제외
SecRule REQUEST_URI "@beginsWith /api/webhook" \
    "id:100010,\
     phase:1,\
     pass,\
     nolog,\
     ctl:ruleRemoveById=942100"  # 특정 SQLi 규칙 제외
// Express.js 애플리케이션 레벨 보안 (WAF 보완)
// WAF와 함께 사용하는 애플리케이션 계층 방어

const express = require('express');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const slowDown = require('express-slow-down');
const hpp = require('hpp');
const xss = require('xss-clean');
const mongoSanitize = require('express-mongo-sanitize');

const app = express();

// 1. HTTP 헤더 보안 (Helmet)
app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            defaultSrc: ["'self'"],
            scriptSrc: ["'self'", "'strict-dynamic'"],
            styleSrc: ["'self'", "'unsafe-inline'"],
            imgSrc: ["'self'", "data:", "https:"],
            connectSrc: ["'self'"],
            fontSrc: ["'self'"],
            objectSrc: ["'none'"],
            mediaSrc: ["'self'"],
            frameSrc: ["'none'"],
        },
    },
    crossOriginEmbedderPolicy: true,
    crossOriginOpenerPolicy: true,
    crossOriginResourcePolicy: { policy: "same-site" },
    dnsPrefetchControl: { allow: false },
    frameguard: { action: "deny" },
    hidePoweredBy: true,
    hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
    ieNoOpen: true,
    noSniff: true,
    referrerPolicy: { policy: "strict-origin-when-cross-origin" },
    xssFilter: true,
}));

// 2. Rate Limiting (DDoS, Brute Force 방어)
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000,  // 15분
    max: 100,                   // IP당 100 요청
    standardHeaders: true,
    legacyHeaders: false,
    message: {
        error: 'Too many requests',
        retryAfter: '15 minutes'
    },
    // Redis store 사용 권장 (클러스터 환경)
    // store: new RedisStore({ client: redisClient }),
});
app.use('/api/', limiter);

// 로그인 엔드포인트 강화된 Rate Limit
const loginLimiter = rateLimit({
    windowMs: 60 * 60 * 1000,  // 1시간
    max: 5,                     // IP당 5회 시도
    skipSuccessfulRequests: true,
    message: { error: 'Too many login attempts. Try again in 1 hour.' }
});
app.use('/api/auth/login', loginLimiter);

// 3. Slow Down (점진적 지연)
const speedLimiter = slowDown({
    windowMs: 15 * 60 * 1000,
    delayAfter: 50,    // 50번째 요청 후
    delayMs: (hits) => hits * 100,  // 점진적 지연 증가
    maxDelayMs: 2000,
});
app.use('/api/', speedLimiter);

// 4. HTTP Parameter Pollution 방어
app.use(hpp());

// 5. XSS 필터링 (입력 새니타이징)
app.use(xss());

// 6. NoSQL Injection 방어 (MongoDB)
app.use(mongoSanitize({
    replaceWith: '_',
    onSanitize: ({ req, key }) => {
        console.warn(`[SECURITY] Sanitized key: ${key} from ${req.ip}`);
    }
}));

// 7. 요청 바디 크기 제한
app.use(express.json({ limit: '10kb' }));
app.use(express.urlencoded({ extended: true, limit: '10kb' }));

// 8. 커스텀 보안 미들웨어
const securityMiddleware = (req, res, next) => {
    // SQL Injection 패턴 탐지
    const sqlPatterns = /(\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|EXEC)\b)/gi;
    const body = JSON.stringify(req.body);
    const query = JSON.stringify(req.query);

    if (sqlPatterns.test(body) || sqlPatterns.test(query)) {
        console.warn(`[WAF-APP] SQL Injection attempt from ${req.ip}`);
        return res.status(403).json({ error: 'Forbidden request pattern' });
    }

    // Path Traversal 탐지
    if (req.url.includes('..') || req.url.includes('%2e%2e')) {
        console.warn(`[WAF-APP] Path Traversal attempt from ${req.ip}`);
        return res.status(403).json({ error: 'Forbidden request pattern' });
    }

    next();
};
app.use(securityMiddleware);

// 9. 요청 로깅 (Threat Hunting용)
const requestLogger = (req, res, next) => {
    const logData = {
        timestamp: new Date().toISOString(),
        method: req.method,
        url: req.url,
        ip: req.ip,
        userAgent: req.headers['user-agent'],
        contentLength: req.headers['content-length'],
    };

    // 의심스러운 User-Agent 플래그
    const suspiciousAgents = ['sqlmap', 'nikto', 'nmap', 'curl', 'python-requests'];
    if (suspiciousAgents.some(agent =>
        logData.userAgent?.toLowerCase().includes(agent))) {
        logData.suspicious = true;
    }

    console.log('[REQUEST]', JSON.stringify(logData));
    next();
};
app.use(requestLogger);

// 10. 에러 핸들러 (정보 노출 방지)
app.use((err, req, res, next) => {
    console.error('[ERROR]', err.stack);

    // 프로덕션에서는 상세 에러 노출 금지
    const message = process.env.NODE_ENV === 'production'
        ? 'Internal Server Error'
        : err.message;

    res.status(err.status || 500).json({
        error: message,
        requestId: req.id  // 추적용 ID
    });
});

app.listen(3000);

🗣️ Say It Like This in Practice

💬 In a security architecture review
"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.

🔗 Related Terms

📚 Learn More