CodeIgniter 3(CI3)雖然輕量,但內建的 xss_clean() 僅針對 XSS 攻擊,缺乏針對 SQL Injection 的專用過濾。許多開發者為了省事,嘗試直接修改核心檔案 system/core/Security.php 中的 xss_clean(),加入 SQL 關鍵字替換。這是極度危險的反模式。本文分析其弊端,並提供正確的防護架構。
select→x)極易繞過:大小寫變形、編碼、註釋插入(sel/**/ect)、字串拼接等。<?php
// CI3 Query Builder(內建預處理)
$userId = $this->input->post('user_id');
$email = $this->input->post('email');
// 安全:自動參數綁定
$this->db->where('id', $userId);
$this->db->update('users', ['email' => $email]);
// 手寫 SQL 時:使用 ? 佔位符 + 陣列綁定
$sql = "SELECT * FROM users WHERE status = ? AND created_at > ?";
$query = $this->db->query($sql, [1, '2024-01-01']);
// 絕對禁止:
// $sql = "SELECT * FROM users WHERE id = $userId"; // 字串拼接 = 漏洞
?>
<?php
// CI3 表單驗證庫
$this->load->library('form_validation');
$rules = [
['field' => 'username', 'label' => '帳號', 'rules' => 'required|alpha_numeric|min_length[3]|max_length[20]'],
['field' => 'email', 'label' => '信箱', 'rules' => 'required|valid_email|max_length[100]'],
['field' => 'age', 'label' => '年齡', 'rules' => 'integer|greater_than[0]|less_than[150]'],
['field' => 'role', 'label' => '角色', 'rules' => 'in_list[admin,editor,viewer]'], // 白名單
];
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === FALSE) {
// 處理驗證失敗
}
?>
<?php
// View 中輸出變數
// HTML 語境
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// 或 CI3 簡寫(僅適用 HTML 語境)
echo html_escape($userInput);
// JavaScript 語境
echo 'const user = ' . json_encode($userInput, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) . ';';
// URL 語境
echo '連結';
// 屬性語境
echo '';
?>
原則:xss_clean() 是輸入端的「清潔」,不如輸出端的「編碼」可靠。現代框架(Laravel Blade、Twig)預設自動轉義,CI3 需手動注意。
<?php
// application/config/config.php
$config['global_xss_filtering'] = FALSE; // 不建議開啟:效能差、破壞二進位檔案、誤判
$config['csrf_protection'] = TRUE; // 啟用 CSRF 保護
$config['csrf_token_name'] = 'csrf_token';
$config['csrf_cookie_name'] = 'csrf_cookie';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = ['api/webhook']; // 排除 API 端點
// 資料庫配置:嚴格模式
$db['default']['strict_on'] = TRUE; // 嚴格 SQL 模式
?>
若需共用邏輯,請繼承而非修改核心:
<?php
// application/libraries/MY_Security.php
class MY_Security extends CI_Security {
// 只新增方法,不覆寫 xss_clean()
/**
* 嚴格 SQL 識別碼驗證(表名、欄位名白名單)
*/
public function validate_identifier(string $identifier, array $whitelist): bool {
return in_array($identifier, $whitelist, true);
}
/**
* 危險字串檢測(僅供日誌/審計,不做過濾)
*/
public function detect_sql_keywords(string $input): array {
$keywords = ['union', 'select', 'insert', 'update', 'delete', 'drop', 'alter', 'exec', '--', ';'];
$found = [];
foreach ($keywords as $kw) {
if (stripos($input, $kw) !== false) $found[] = $kw;
}
return $found;
}
}
?>
CodeIgniter 3 的安全防護核心在於:Query Builder 預處理防 SQLi、表單驗證白名單防業務邏輯錯誤、輸出時 html_escape() 防 XSS、CSRF Token 防跨站請求偽造。切勿嘗試用字串替換「過濾」SQL 關鍵字,這不只是無效,更會製造虛假安全感。升級至 CI4 或 Laravel 可獲得更完善的內建防護機制。