← 返回首页
🔒

WAF架构:规则引擎与智能检测

📂 architecture ⏱ 3 min 513 words

WAF架构:规则引擎与智能检测

WAF规则引擎

Web应用防火墙(WAF)通过规则引擎检测和阻止恶意请求,保护Web应用免受攻击。

// WAF规则引擎
@Component
public class WAFRuleEngine {
    
    private final List<WAFRule> rules;
    private final RuleLoader ruleLoader;
    
    public WAFResult evaluate(HttpRequest request) {
        List<RuleViolation> violations = new ArrayList<>();
        
        // 加载当前生效的规则
        List<WAFRule> activeRules = ruleLoader.loadActiveRules();
        
        for (WAFRule rule : activeRules) {
            RuleMatch match = rule.match(request);
            
            if (match.isMatched()) {
                violations.add(RuleViolation.builder()
                    .ruleId(rule.getId())
                    .ruleName(rule.getName())
                    .severity(rule.getSeverity())
                    .action(rule.getAction())
                    .matchedContent(match.getMatchedContent())
                    .build());
            }
        }
        
        // 根据违规情况决定处理方式
        return decideAction(violations, request);
    }
    
    private WAFResult decideAction(List<RuleViolation> violations, HttpRequest request) {
        if (violations.isEmpty()) {
            return WAFResult.allow();
        }
        
        // 检查是否有高危规则匹配
        boolean hasHighSeverity = violations.stream()
            .anyMatch(v -> v.getSeverity() == Severity.HIGH);
        
        if (hasHighSeverity) {
            // 记录并阻断
            logSecurityEvent(violations, request);
            return WAFResult.block("安全规则触发", violations);
        }
        
        // 中等风险:警告但允许
        boolean hasMediumSeverity = violations.stream()
            .anyMatch(v -> v.getSeverity() == Severity.MEDIUM);
        
        if (hasMediumSeverity) {
            logSecurityEvent(violations, request);
            return WAFResult.warn(violations);
        }
        
        // 低风险:记录日志
        logSecurityEvent(violations, request);
        return WAFResult.allow();
    }
}

// WAF规则定义
@Data
public class WAFRule {
    private String id;
    private String name;
    private String description;
    private Severity severity;
    private RuleAction action;
    private List<RuleCondition> conditions;
    private List<RuleException> exceptions;
    
    public RuleMatch match(HttpRequest request) {
        for (RuleCondition condition : conditions) {
            RuleMatch match = condition.evaluate(request);
            if (match.isMatched()) {
                // 检查是否在例外列表中
                if (isException(request)) {
                    return RuleMatch.notMatched();
                }
                return match;
            }
        }
        return RuleMatch.notMatched();
    }
}

ML智能检测

// 基于机器学习的异常检测
@Component
public class MLAnomalyDetector {
    
    private final Model model;
    private final FeatureExtractor featureExtractor;
    private final AnomalyThreshold threshold;
    
    public DetectionResult detect(HttpRequest request) {
        // 特征提取
        FeatureVector features = featureExtractor.extract(request);
        
        // 模型预测
        double anomalyScore = model.predict(features);
        
        // 与阈值比较
        if (anomalyScore > threshold.getHighThreshold()) {
            return DetectionResult.malicious(anomalyScore, 
                "高风险异常请求");
        } else if (anomalyScore > threshold.getMediumThreshold()) {
            return DetectionResult.suspicious(anomalyScore, 
                "可疑请求,建议进一步检查");
        }
        
        return DetectionResult.normal(anomalyScore);
    }
    
    private static class FeatureExtractor {
        
        public FeatureVector extract(HttpRequest request) {
            Map<String, Double> features = new HashMap<>();
            
            // 请求特征
            features.put("url_length", (double) request.getUrl().length());
            features.put("param_count", (double) request.getParameters().size());
            features.put("header_count", (double) request.getHeaders().size());
            
            // 内容特征
            String body = request.getBody();
            if (body != null) {
                features.put("body_length", (double) body.length());
                features.put("special_char_ratio", calculateSpecialCharRatio(body));
                features.put("entropy", calculateEntropy(body));
            }
            
            // 时间特征
            features.put("hour_of_day", (double) request.getTimestamp().getHour());
            features.put("is_weekend", request.getTimestamp().getDayOfWeek().getValue() > 5 ? 1.0 : 0.0);
            
            // 行为特征
            features.put("request_frequency", getRequestFrequency(request));
            features.put("unique_paths", getUniquePaths(request));
            
            return new FeatureVector(features);
        }
    }
}

DDoS防护

// DDoS防护系统
@Component
public class DDoSProtection {
    
    private final TrafficAnalyzer trafficAnalyzer;
    private final RateLimiter rateLimiter;
    private final GeoFilter geoFilter;
    
    public ProtectionResult protect(HttpRequest request) {
        // 1. 基础速率限制
        if (!rateLimiter.tryAcquire(request.getClientIp())) {
            return ProtectionResult.blocked("速率限制",
                "请求频率超过阈值");
        }
        
        // 2. 流量分析
        TrafficPattern pattern = trafficAnalyzer.analyze(request);
        
        if (pattern.isDDoSAttack()) {
            // 触发DDoS防护
            activateDDoSProtection(pattern);
            return ProtectionResult.blocked("DDoS攻击检测",
                "检测到分布式拒绝服务攻击");
        }
        
        // 3. 地理位置过滤
        if (geoFilter.isBlocked(request.getClientIp())) {
            return ProtectionResult.blocked("地理位置限制",
                "来自被限制地区的请求");
        }
        
        // 4. 行为分析
        if (isBotTraffic(request)) {
            return ProtectionResult.captcha("疑似机器人流量",
                "请完成人机验证");
        }
        
        return ProtectionResult.allowed();
    }
    
    private void activateDDoSProtection(TrafficPattern pattern) {
        // 1. 启用紧急速率限制
        rateLimiter.activateEmergencyMode();
        
        // 2. 启用地理围栏
        geoFilter.activateGeoFencing(pattern.getAttackOrigins());
        
        // 3. 通知运维团队
        alertService.sendDDoSAlert(pattern);
        
        // 4. 启动流量清洗
        trafficCleaner.startCleaning();
    }
}

安全规则配置

# WAF规则配置
waf:
  rules:
    # SQL注入防护
    - id: "SQL_INJECTION_001"
      name: "SQL注入检测"
      severity: "HIGH"
      action: "BLOCK"
      conditions:
        - type: "PATTERN_MATCH"
          field: "body"
          pattern: "(?i)(union\\s+select|or\\s+\\d+=\\d+|;\\s*drop)"
        - type: "PATTERN_MATCH"
          field: "params"
          pattern: "(?i)(\\bselect\\b.*\\bfrom\\b|\\binsert\\b.*\\binto\\b)"
    
    # XSS防护
    - id: "XSS_001"
      name: "XSS攻击检测"
      severity: "HIGH"
      action: "BLOCK"
      conditions:
        - type: "PATTERN_MATCH"
          field: "body"
          pattern: "(<script|javascript:|onerror=|onload=)"
        - type: "HTML_ENCODE_CHECK"
          field: "params"
          threshold: 0.3
    
    # 路径遍历防护
    - id: "PATH_TRAVERSAL_001"
      name: "路径遍历检测"
      severity: "MEDIUM"
      action: "BLOCK"
      conditions:
        - type: "PATTERN_MATCH"
          field: "url"
          pattern: "(\\.\\./|\\.\\.\\\\|%2e%2e)"
    
    # 机器人检测
    - id: "BOT_DETECTION_001"
      name: "机器人流量检测"
      severity: "LOW"
      action: "CHALLENGE"
      conditions:
        - type: "USER_AGENT_CHECK"
          patterns: ["bot", "crawler", "spider"]
        - type: "BEHAVIOR_ANALYSIS"
          request_rate: 100
          time_window: 60
  
  # 默认动作
  default_action: "ALLOW"
  
  # 监控配置
  monitoring:
    log_level: "INFO"
    alert_threshold: 10
    metrics_interval: 60

WAF架构通过规则引擎、ML智能检测和DDoS防护的多层次机制,为Web应用提供全面的安全保护。