萬盛學電腦網

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

ASP.NET 檔案上傳前驗證:檔案類型與大小雙重檢查

檔案上傳前驗證是系統安全的第一道防線。雖然前端可攔截,但後端驗證不可省略 (前端可繞過)。本文提供可配置、可重用的後端驗證邏輯。

核心驗證方法

using System.Configuration;
using System.IO;

public static class UploadValidator
{
    /// 驗證檔案副檔名是否在允許清單中
    public static bool IsAllowedExtension(string fileName)
    {
        if (string.IsNullOrEmpty(fileName)) return false;
        
        string ext = Path.GetExtension(fileName).ToLowerInvariant();
        string allowedExts = ConfigurationManager.AppSettings["AllowedExtensions"] ?? ".jpg|.jpeg|.png|.gif|.bmp";
        
        return allowedExts.Split('|').Contains(ext);
    }

    /// 驗證檔案大小是否超過限制
    public static bool IsAllowedSize(long contentLength)
    {
        string maxSizeStr = ConfigurationManager.AppSettings["MaxUploadSizeKB"] ?? "2048"; // 預設 2MB
        if (!int.TryParse(maxSizeStr, out int maxKB)) maxKB = 2048;
        
        long maxBytes = maxKB * 1024L;
        return contentLength > 0 && contentLength <= maxBytes;
    }

    /// 綜合驗證 (回傳錯誤訊息,null 表示通過)
    public static string Validate(HttpPostedFile file)
    {
        if (file == null || file.ContentLength == 0)
            return "請選擇要上傳的檔案";

        if (!IsAllowedExtension(file.FileName))
            return $"檔案格式不允許。允許格式:{ConfigurationManager.AppSettings["AllowedExtensions"]?.Replace("|", ", ")}";

        if (!IsAllowedSize(file.ContentLength))
            return $"檔案大小超過限制 (最大 {ConfigurationManager.AppSettings["MaxUploadSizeKB"]} KB)";

        // 進階:驗證 Magic Number (檔案真實內容) - 防止偽裝副檔名
        if (!ValidateMagicNumber(file.InputStream))
            return "檔案內容與副檔名不符,可能為偽裝檔案";

        return null; // 通過驗證
    }

    /// 驗證檔案簽名
    private static bool ValidateMagicNumber(Stream stream)
    {
        // 常見圖片 Magic Numbers
        var signatures = new Dictionary
        {
            [".jpg"] = new[] { new byte[] { 0xFF, 0xD8, 0xFF } },
            [".png"] = new[] { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A } },
            [".gif"] = new[] { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 } },
            [".bmp"] = new[] { new byte[] { 0x42, 0x4D } }
        };

        string ext = Path.GetExtension(stream.GetType().Name).ToLower(); // 注意:這裡需從檔名取得副檔名
        // 實際應用中應從 HttpPostedFile.FileName 取得副檔名
        
        if (!signatures.TryGetValue(ext, out var sigs)) return true; // 未定義簽名則跳過

        byte[] header = new byte[8];
        stream.Position = 0;
        stream.Read(header, 0, header.Length);
        stream.Position = 0;

        return sigs.Any(sig => header.Take(sig.Length).SequenceEqual(sig));
    }
}

Web.config 設定

<appSettings>
  <!-- 允許副檔名,以 | 分隔,全部小寫 -->
  <add key="AllowedExtensions" value=".jpg|.jpeg|.png|.gif|.bmp|.pdf|.doc|.docx|.xls|.xlsx" />
  <!-- 最大上傳大小 (KB) -->
  <add key="MaxUploadSizeKB" value="5120" /> <!-- 5MB -->
</appSettings>

<!-- IIS 要求大小限制 (需同步設定,否則大檔案直接被 IIS 擋下) -->
<system.web>
  <httpRuntime maxRequestLength="5120" executionTimeout="300" /> <!-- KB, 秒 -->
</system.web>
<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="5242880" /> <!-- Bytes (5MB) -->
    </requestFiltering>
  </security>
</system.webServer>

使用範例 (Web Forms / MVC 通用)

// Web Forms
protected void btnUpload_Click(object sender, EventArgs e)
{
    string error = UploadValidator.Validate(fuFile.PostedFile);
    if (error != null) { lblMsg.Text = error; return; }
    
    // 通過驗證,進行儲存邏輯...
}

// MVC Controller
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    string error = UploadValidator.Validate(file);
    if (error != null) return Json(new { success = false, message = error });
    
    // 儲存邏輯...
    return Json(new { success = true, path = savedPath });
}

安全性深度防禦清單

  1. 副檔名白名單 (已實作)
  2. 檔案大小限制 (已實作,含 IIS 層面)
  3. Magic Number 驗證 (防止 .exe 改名 .jpg)
  4. 儲存路徑隨機化:`Guid.NewGuid() + ext`,避免覆蓋、路徑遍歷
  5. 儲存目錄執行權限移除:IIS 設定上傳目錄「腳本執行權限 = 無」
  6. 病毒掃描整合:ClamAV / Windows Defender API 掃描後再落地
  7. Content-Type 二次檢查:`file.ContentType` 需與副檔名對應
  8. 檔名清理:移除特殊字元、路徑遍歷字元 (`..`, `\`, `/`)

現代化建議

  • ASP.NET Core 使用 IFormFile 介面,驗證邏輯封裝為 IFormFileValidator 服務,注入 Controller。
  • 大檔案採用 分塊上傳 (Chunked Upload),前端 Plupload/Uppy + 後端合併。
  • 生產環境嚴禁將上傳目錄設為可執行,建議使用雲端物件儲存 (Blob/S3) 完全隔離應用伺服器。

嚴謹的上傳驗證是防止惡意檔案上傳、遠端代碼執行 (RCE) 攻擊的關鍵,請務必在每個上傳入口點統一套用。

copyright © 萬盛學電腦網 all rights reserved