本文僅供安全研究、防禦加固與教學目的。嚴禁用於攻擊生產系統、未授權測試或任何非法行為。請遵守當地法律法規與網絡安全道德規範。
PHP 陣列底層使用雜湊表儲存鍵值對。雜湊函數將字串鍵映射為整數索引。若大量鍵產生相同雜湊值 (碰撞),雜湊表退化為鏈表,插入/查找時間複雜度從 O(1) 惡化為 O(n²),導致 CPU 100% 佔用。
// 簡化版 PHP 字串雜湊 (Zend/zend_string.h)
static zend_always_inline zend_ulong zend_string_hash_val(const char *str, size_t len) {
zend_ulong h = 5381;
for (size_t i = 0; i < len; i++) {
h = ((h << 5) + h) + (unsigned char)str[i]; // h * 33 + c
}
return h;
}
利用 h * 33 + c 的線性特性,可構造大量碰撞鍵。例如 EzEz、FYFY 等特定字串組合會產生相同雜湊值。
<?php
// 生成碰撞鍵陣列 (概念演示,實際攻擊載荷更複雜)
function generateCollidingKeys(int $count = 10000): array
{
$keys = [];
// 利用 DJBX33A 特性構造碰撞 (簡化示例)
$base = 'EzEz'; // 已知碰撞前綴
for ($i = 0; $i < $count; $i++) {
$keys[] = $base . str_pad($i, 8, '0', STR_PAD_LEFT);
}
return $keys;
}
// 模擬 POST 請求構造
$postData = '';
foreach (generateCollidingKeys(5000) as $key) {
$postData .= "&array[$key]=0";
}
$postData = ltrim($postData, '&');
// 注意:現代 PHP (5.4+) 已引入 max_input_vars 限制,單次請求無法直接發送超大量參數
?>
| PHP 版本 | 防禦機制 | 配置指令 | 預設值 |
|---|---|---|---|
| 5.3.9+ | 限制最大輸入變數數 | max_input_vars | 1000 |
| 5.4.0+ | 限制最大巢狀層級 | max_input_nesting_level | 64 |
| 7.0.0+ | 改進雜湊函數 (SipHash) | --enable-siphash (編譯時) | 隨機種子 |
| 7.4+ | Fiber/協程限制 | max_execution_time | 30s |
; === 輸入限制 ===
max_input_vars = 3000 ; 根據業務需求調整,API 介面可適當放寬
max_input_nesting_level = 32 ; 降低巢狀深度限制
max_input_time = 30 ; 解析輸入最大秒數
post_max_size = 8M ; POST 資料體積限制
upload_max_filesize = 2M ; 上傳檔案限制
; === 執行限制 ===
max_execution_time = 30 ; 腳本最大執行時間
memory_limit = 128M ; 記憶體限制
; === Session 保護 ===
session.use_strict_mode = 1 ; 防 Session Fixation
session.cookie_httponly = 1 ; 防 XSS 竊取 Session
session.cookie_secure = 1 ; 僅 HTTPS 傳輸 (需 HTTPS 環境)
session.cookie_samesite = Strict ; CSRF 防護
; === 禁用危險函數 ===
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
<?php
// Laravel/Middleware 或通用前置腳本
function validateInputSize(array $input, int $maxKeys = 1000, int $maxDepth = 10): void
{
$count = countInputKeys($input);
if ($count > $maxKeys) {
throw new HttpException(413, "輸入參數過多: $count > $maxKeys");
}
$depth = calculateArrayDepth($input);
if ($depth > $maxDepth) {
throw new HttpException(413, "輸入巢狀層級過深: $depth > $maxDepth");
}
}
function countInputKeys(array $arr): int
{
$count = 0;
foreach ($arr as $value) {
$count++;
if (is_array($value)) {
$count += countInputKeys($value);
}
}
return $count;
}
?>
<?php
// 避免直接操作 $_POST/$_GET 陣列
class CreateOrderDTO
{
public function __construct(
public readonly int $userId,
public readonly array $items, // 結構固定,非任意鍵
public readonly string $currency = 'TWD',
) {}
public static function fromRequest(array $data): self
{
// 嚴格驗證結構,拒絕額外欄位
return new self(
userId: (int)($data['user_id'] ?? 0),
items: array_map(fn($i) => new OrderItemDTO(...), $data['items'] ?? []),
);
}
}
?>
<?php
// Redis 滑動窗口限流
function checkRateLimit(string $key, int $limit, int $windowSeconds): bool
{
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$now = time();
$windowStart = $now - $windowSeconds;
// 移除過期記錄
$redis->zRemRangeByScore($key, 0, $windowStart);
// 當前計數
$count = $redis->zCard($key);
if ($count >= $limit) {
return false;
}
// 記錄本次請求
$redis->zAdd($key, $now, uniqid('', true));
$redis->expire($key, $windowSeconds + 1);
return true;
}
// 使用
if (!checkRateLimit('api:post:user_' . $userId, 60, 60)) {
http_response_code(429);
exit('請求過於頻繁,請稍後再試');
}
?>
| 版本 | 雜湊演算法 | 隨機種子 | 預設 max_input_vars | 安全性評級 |
|---|---|---|---|---|
| 5.3 - 5.3.8 | DJBX33A (固定) | 無 | 無限制 | ⚠️ 極高風險 |
| 5.3.9 - 5.6 | DJBX33A (固定) | 無 | 1000 | ⚠️ 高風險 (需配置) |
| 7.0 - 7.3 | DJBX33A + 隨機種子 | 啟動時隨機 | 1000 | ✅ 中等 (種子保護) |
| 7.4+ | SipHash-2-4 (加密級) | 每進程隨機 | 1000 | ✅✅ 高 (抗碰撞) |
| 8.0+ | SipHash-2-4 + Fiber 隔離 | 每進程隨機 | 1000 | ✅✅✅ 最高 |
HashDoS 攻擊利用雜湊表碰撞特性耗盡 CPU。現代防禦採取多層次纵深防禦:
max_input_vars、max_execution_time、memory_limit定期進行壓力測試與安全掃描,確保防禦措施有效性。