萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP CC 攻擊防禦與防刷新限流:Session 基礎實現與最佳實踐

威脅模型

  • CC 攻擊 (Challenge Collapsar):攻擊者控制大量代理/殭屍網絡,模擬正常用戶高頻請求,耗盡服務器資源(CPU/記憶體/連接數/帶寬)
  • 惡意刷新:單用戶短時間內瘋狂 F5,導致後端邏輯重複執行、數據庫壓力驟增

基礎版:Session 計數限流(原始代碼改良)

<?php
// anti_cc.php - 在所有需保護腳本頂部 require_once
session_start();

// 配置
$config = [
    'window_sec'    => 3,    // 時間窗口(秒)
    'max_requests'  => 5,    // 窗口內最大請求數
    'ban_duration'  => 300,  // 觸發封禁時長(秒)
    'whitelist_ips' => ['127.0.0.1', '::1'], // 白名單
    'log_file'      => __DIR__ . '/logs/cc_block.log',
];

// 代理 IP 直接拒絕(可選,視業務)
if (!empty($_SERVER['HTTP_VIA']) || !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    // 更嚴格:檢測知名代理頭
    // error_log("Proxy access denied: {$_SERVER['REMOTE_ADDR']}");
    // exit('Access Denied: Proxy not allowed');
}

$ip = $_SERVER['REMOTE_ADDR'];
if (in_array($ip, $config['whitelist_ips'], true)) return; // 白名單放行

$now = time();
$key = "cc_limit:$ip";

// 初始化/重置窗口
if (!isset($_SESSION[$key]['window_start']) || $now - $_SESSION[$key]['window_start'] >= $config['window_sec']) {
    $_SESSION[$key] = ['window_start' => $now, 'count' => 0];
}

$_SESSION[$key]['count']++;

if ($_SESSION[$key]['count'] > $config['max_requests']) {
    // 觸發封禁
    $_SESSION['banned_until'] = $now + $config['ban_duration'];
    error_log(sprintf("[%s] CC Block: IP=%s Count=%d UA=%s\n", date('c'), $ip, $_SESSION[$key]['count'], $_SERVER['HTTP_USER_AGENT'] ?? ''), 3, $config['log_file']);
    
    // 返回 429 Too Many Requests
    http_response_code(429);
    header('Content-Type: text/plain; charset=utf-8');
    exit("請求過於頻繁,請 {$config['ban_duration']} 秒後重試。");
}

// 可選:將剩餘配額傳給前端
header('X-RateLimit-Limit: ' . $config['max_requests']);
header('X-RateLimit-Remaining: ' . max(0, $config['max_requests'] - $_SESSION[$key]['count']));
header('X-RateLimit-Reset: ' . ($_SESSION[$key]['window_start'] + $config['window_sec']));

進階版:Redis 滑動窗口 + Token Bucket(分佈式、高效能)

<?php
// 依賴 predis/predis 或 phpredis 擴展
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

function checkRateLimit(Redis $redis, string $key, int $limit, int $windowSec): bool {
    $now = microtime(true);
    $windowStart = $now - $windowSec;
    
    $pipe = $redis->pipeline();
    // 移除過期記錄
    $pipe->zRemRangeByScore($key, 0, $windowStart);
    // 當前計數
    $pipe->zCard($key);
    // 添加本次請求
    $pipe->zAdd($key, $now, "$now:" . uniqid('', true));
    // 設置過期時間(窗口結束後自動清理)
    $pipe->expire($key, $windowSec + 1);
    $results = $pipe->execute();
    
    $currentCount = $results[1];
    return $currentCount < $limit;
}

// 使用
$ip = $_SERVER['REMOTE_ADDR'];
$limitKey = "ratelimit:api:$ip";
if (!checkRateLimit($redis, $limitKey, 100, 60)) { // 100 req/min
    http_response_code(429);
    exit(json_encode(['error' => 'Rate limit exceeded', 'retry_after' => 60]));
}

多層防禦體系

層級技術特點
邊緣/CDNCloudflare/阿里云 WAF、速率限制規則攔截 90%+ 攻擊流量,不觸達源站
Web ServerNginx limit_req_zone、Apache mod_ratelimit高效能、支援突發、可白名單
應用層 (PHP)Session/Redis 計數、Token Bucket、行為分析業務感知強、可精細控制
業務邏輯驗證碼、設備指紋、行為風控、人機驗證針對性強、用戶體驗權衡

Nginx 限流配置範例(推薦作為第一道防線)

# http 區塊
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;

# server/location 區塊
location /api/ {
    limit_req zone=api_limit burst=20 nodelay;
    limit_req_status 429;
    proxy_pass https://php_backend;
}

location /login {
    limit_req zone=login_limit burst=3 nodelay;
    limit_req_status 429;
    proxy_pass https://php_backend;
}

常見誤區與避坑

  1. 僅依賴 Session:Session 預設檔案存儲,高併發下 I/O 瓶頸大、集群不共享 → 必須用 Redis/Memcached。
  2. 固定窗口邊界突刺:窗口邊界瞬間雙倍流量 → 改用滑動窗口或漏桶/令牌桶。
  3. 攔截後直接 exit 無日誌:無法事後分析攻擊源、調整策略 → 結構化日誌入 ELK/Loki。
  4. 誤傷正常用戶:爬蟲/聚合器/預測性預載可能觸發 → 白名單、User-Agent 識別、驗證碼而非硬封禁。
  5. 忽略 IPv6:$_SERVER['REMOTE_ADDR'] 可能是 IPv6,儲存/比較需統一格式。

完整中間件類(可直接接入框架)

<?php
class RateLimiter {
    private Redis $redis;
    private array $rules = []; // ['route_pattern' => [limit, window, burst]]

    public function __construct(Redis $redis) { $this->redis = $redis; }

    public function addRule(string $pattern, int $limit, int $window, int $burst = 0): self {
        $this->rules[$pattern] = [$limit, $window, $burst];
        return $this;
    }

    public function handle(string $route, string $identifier = ''): bool {
        $identifier = $identifier ?: $_SERVER['REMOTE_ADDR'];
        foreach ($this->rules as $pattern => [$limit, $window, $burst]) {
            if (fnmatch($pattern, $route)) {
                return $this->check($identifier, $limit, $window, $burst);
            }
        }
        return true; // 無規則放行
    }

    private function check(string $id, int $limit, int $window, int $burst): bool {
        $key = "rl:$id";
        $now = microtime(true);
        $pipe = $this->redis->pipeline();
        $pipe->zRemRangeByScore($key, 0, $now - $window);
        $pipe->zCard($key);
        $pipe->zAdd($key, $now, "$now:" . random_bytes(4));
        $pipe->expire($key, $window + 1);
        [$_, $count] = $pipe->execute();
        
        $effectiveLimit = $limit + $burst;
        if ($count >= $effectiveLimit) {
            $this->logBlock($id, $count, $limit);
            return false;
        }
        return true;
    }

    private function logBlock(string $id, int $count, int $limit) {
        error_log(json_encode([
            'time' => date('c'),
            'type' => 'rate_limit',
            'identifier' => $id,
            'count' => $count,
            'limit' => $limit,
            'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        ]));
    }
}

// 使用
$limiter = new RateLimiter($redis);
$limiter->addRule('/api/*', 100, 60, 20)
        ->addRule('/login', 5, 300, 2)
        ->addRule('/register', 3, 3600, 1);

if (!$limiter->handle($_SERVER['REQUEST_URI'])) {
    http_response_code(429);
    exit('Too Many Requests');
}

核心原則:邊緣攔截 > 伺服器限流 > 應用限流 > 業務風控。PHP 層面作為「最後一道防線」與「業務感知控制」,核心邏輯用 Redis 滑動窗口,配置下發化、日誌結構化、監控告警化。

copyright © 萬盛學電腦網 all rights reserved