檔案上傳是 Web 開發高風險功能之一,處理不當極易導致 Webshell 植入、伺服器沦陷。本文以實戰案例(.torrent 種子上傳)為切入點,系統講解上傳流程、驗證策略、框架整合(CodeIgniter)與多層防護機制。
<?php
// $_FILES 結構
[
'upload_file' => [
'name' => 'example.torrent', // 原始檔名
'type' => 'application/octet-stream', // MIME 型別(客戶端提供,不可信)
'tmp_name' => '/tmp/phpXyZ123', // 暫存路徑
'error' => 0, // 錯誤碼:0=成功
'size' => 102400 // 檔案大小(位元組)
]
]
?>
瀏覽器根據副檔名猜測 MIME,攻擊者可輕易偽造。絕不可作為安全依據。
<?php
// 錯誤示範:大小寫繞過、雙副檔名、Null Byte 注入(舊版 PHP)
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ($ext !== 'torrent') { die('禁止'); }
// 正確做法:統一小寫、白名單、多重驗證
$allowedExt = ['torrent'];
$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt, true)) { die('副檔名不允許'); }
?>
<?php
function validateUpload(array $file, array $allowedExt, int $maxSize = 2_000_000): array|false {
// 1. 檢查上傳錯誤碼
if ($file['error'] !== UPLOAD_ERR_OK) {
return ['error' => '上傳錯誤碼: ' . $file['error']];
}
// 2. 檢查檔案大小
if ($file['size'] > $maxSize) {
return ['error' => '檔案過大'];
}
// 3. 副檔名白名單(小寫比對)
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt, true)) {
return ['error' => '副檔名不允許'];
}
// 4. MIME 型別檢測(使用 finfo,讀取檔案實際內容)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
$allowedMime = ['application/x-bittorrent', 'application/octet-stream']; // torrent 常見 MIME
if (!in_array($mime, $allowedMime, true)) {
return ['error' => '檔案類型不符(MIME): ' . $mime];
}
// 5. 內容特徵檢測(針對特定格式)
if ($ext === 'torrent') {
$content = file_get_contents($file['tmp_name']);
// 簡易檢查:Bencode 格式通常以 'd' 開頭
if ($content[0] !== 'd') {
return ['error' => '非合法 Torrent 檔案'];
}
}
// 6. 產生安全檔名(避免覆蓋、路徑遍歷、特殊字元)
$safeName = bin2hex(random_bytes(16)) . '.torrent';
return ['safe_name' => $safeName, 'ext' => $ext, 'mime' => $mime];
}
?>
CI 預設透過 MIME 驗證,導致 .torrent(通常回傳 application/octet-stream)被誤擋。解決方案:
<?php
// application/config/mimes.php
$mimes = array(
// ... 原有內容
'torrent' => ['application/x-bittorrent', 'application/octet-stream'],
);
?>
<?php
// Controller
public function upload_torrent() {
$config = [
'upload_path' => FCPATH . 'uploads/torrents/',
'allowed_types' => 'torrent', // 需配合 mimes.php
'max_size' => 2048, // 2MB
'encrypt_name' => true, // 自動加密檔名
'remove_spaces' => true,
];
$this->load->library('upload', $config);
// 覆寫 is_allowed_filetype 方法(CI3 核心修改或 MY_Upload 擴充)
// 建議:建立 application/libraries/MY_Upload.php 繼承 CI_Upload
// 重寫 is_allowed_filetype() 使用 finfo 驗證
if (!$this->upload->do_upload('upload_file')) {
$error = $this->upload->display_errors();
// 處理錯誤
} else {
$data = $this->upload->data();
// 入庫、回應成功
}
}
?>
# Nginx
location /uploads/ {
# 禁止執行 PHP、腳本
location ~ \.php$ { deny all; return 403; }
}
# Apache (.htaccess)
Require all denied
readfile()、X-Sendfile),徹底隔離執行環境。
用戶提交表單
↓
前端 JS 基礎驗證(副檔名、大小)—— 使用者體驗,非安全防線
↓
PHP 接收 $_FILES
↓
1. 檢查 error 碼
2. 檢查檔案大小
3. 副檔名白名單
4. finfo 偵測真實 MIME
5. (可選) 內容特徵檢測(Magic Bytes、圖片 getimagesize())
↓
產生安全隨機檔名
↓
move_uploaded_file() 移至儲存目錄(Web Root 外)
↓
資料庫記錄:原始檔名、儲存檔名、MIME、大小、上傳者、時間
↓
回應前端結果
檔案上傳安全的核心原則是「不信任任何客戶端資料」。副檔名、MIME、檔案內容皆可偽造,必須採用白名單 + 伺服端內容檢測 + 隨機化檔名 + 執行權限隔離 + 儲存目錄非 Web 可執行的多層防禦。CodeIgniter 等框架提供便利,但關鍵驗證邏輯仍需開發者根據業務特性客製化。