檔案上傳是 Web 應用高風險功能之一。單純檢查副檔名極易被繞過 (如將 `shell.aspx` 改名為 `shell.jpg`)。本文詳細比較三種驗證層級:副檔名檢查、MIME 型別檢查、檔案簽名 (Magic Number) 檢查,並提供完整程式碼與安全建議。
protected bool ValidateExtension(FileUpload fu)
{
if (!fu.HasFile) return false;
string ext = Path.GetExtension(fu.FileName).ToLower();
string[] allowed = { ".jpg", ".jpeg", ".png", ".gif", ".pdf", ".docx" };
return allowed.Contains(ext);
}
缺點:使用者可輕易修改副檔名繞過。僅建議作為第一層攔截,搭配其他方法使用。
protected bool ValidateMimeType(FileUpload fu)
{
if (!fu.HasFile) return false;
string mime = fu.PostedFile.ContentType.ToLower();
string[] allowedMimes = {
"image/jpeg", "image/png", "image/gif",
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" // .docx
};
return allowedMimes.Contains(mime);
}
缺點:MIME 型別由瀏覽器根據副檔名推斷,同樣可偽造。不可單獨信任。
每種檔案格式在二進位開頭都有固定的位元組特徵碼 (Magic Number)。讀取檔案前幾個位元組即可確認真實格式,無法偽造。
| 檔案類型 | 副檔名 | Magic Number (Hex) | 對應位元組 |
|---|---|---|---|
| JPEG | .jpg, .jpeg | FF D8 FF | 255, 216, 255 |
| PNG | .png | 89 50 4E 47 0D 0A 1A 0A | 137, 80, 78, 71, 13, 10, 26, 10 |
| GIF | .gif | 47 49 46 38 | 71, 73, 70, 56 (GIF8) |
| 25 50 44 46 | 37, 80, 68, 70 (%PDF) | ||
| ZIP / DOCX / XLSX | .zip, .docx, .xlsx | 50 4B 03 04 | 80, 75, 3, 4 (PK..) |
| BMP | .bmp | 42 4D | 66, 77 (BM) |
public static bool ValidateFileSignature(FileUpload fu, params byte[][] allowedSignatures)
{
if (!fu.HasFile) return false;
// 讀取檔案前 8 位元組 (足以涵蓋大多數簽名)
byte[] header = new byte[8];
using (Stream fs = fu.FileContent)
{
fs.Read(header, 0, header.Length);
fs.Position = 0; // 重置流位置,供後續 SaveAs 使用
}
foreach (byte[] sig in allowedSignatures)
{
bool match = true;
for (int i = 0; i < sig.Length; i++)
{
if (header[i] != sig[i])
{
match = false;
break;
}
}
if (match) return true;
}
return false;
}
// 使用範例:只允許 JPG, PNG, GIF, PDF
protected void btnUpload_Click(object sender, EventArgs e)
{
byte[][] allowedSigs = new byte[][]
{
new byte[] { 0xFF, 0xD8, 0xFF }, // JPEG
new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, // PNG
new byte[] { 0x47, 0x49, 0x46, 0x38 }, // GIF87a / GIF89a
new byte[] { 0x25, 0x50, 0x44, 0x46 } // PDF
};
if (ValidateFileSignature(FileUpload1, allowedSigs))
{
string savePath = Server.MapPath("~/Uploads/") + Guid.NewGuid() + Path.GetExtension(FileUpload1.FileName);
FileUpload1.SaveAs(savePath);
lblMsg.Text = "上傳成功!";
}
else
{
lblMsg.Text = "檔案格式不符或已損壞,僅允許 JPG/PNG/GIF/PDF。";
}
}
protected void UploadFile()
{
if (!FileUpload1.HasFile)
{
ShowMsg("請選擇檔案");
return;
}
// 第 1 層:副檔名白名單
string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
string[] allowedExt = { ".jpg", ".jpeg", ".png", ".gif", ".pdf" };
if (!allowedExt.Contains(ext))
{
ShowMsg("副檔名不允許");
return;
}
// 第 2 層:MIME 型別檢查
string mime = FileUpload1.PostedFile.ContentType.ToLower();
string[] allowedMime = { "image/jpeg", "image/png", "image/gif", "application/pdf" };
if (!allowedMime.Contains(mime))
{
ShowMsg("MIME 型別不符");
return;
}
// 第 3 層:檔案簽名驗證 (核心防禦)
byte[][] signatures = GetAllowedSignatures(); // 依允許類型回傳簽名陣列
if (!ValidateFileSignature(FileUpload1, signatures))
{
ShowMsg("檔案內容與副檔名不符,疑似偽裝檔案");
return;
}
// 通過所有驗證,儲存檔案
string safeName = Guid.NewGuid().ToString() + ext;
string savePath = Server.MapPath("~/SecureUploads/") + safeName;
FileUpload1.SaveAs(savePath);
// 記錄日誌、寫入資料庫...
ShowMsg("上傳成功");
}
原文提供的第三種方法程式碼存在嚴重缺陷:
// 原始碼片段
System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, ...);
// 問題:hifile.PostedFile.FileName 是「客戶端路徑」(如 C:\fakepath\test.jpg),伺服器無法讀取!
// 應改用 hifile.FileContent 或 hifile.PostedFile.InputStream
正確做法請參考上方 `ValidateFileSignature` 方法,直接讀取 `fu.FileContent` Stream。
總結:檔案上傳驗證必須採用多層防禦:副檔名白名單 (前端攔截) → MIME 型別 (粗略過濾) → 檔案簽名驗證 (核心防禦)。單靠任何單一層級都不足以防禦偽裝檔案攻擊。請務必使用 `FileUpload.FileContent` Stream 讀取真實檔案內容進行 Magic Number 比對,並配合儲存目錄執行權限控制、檔案重命名、病毒掃描,構建完整上傳安全防線。