自救必看三大準則

Path Traversal

成因
       Path Traversal的成因是指當存取檔案的路徑是透過使用者輸入或是組合字串而成,即可能讓使用者任意決定檔案路徑,進而可對任意路徑的檔案進行存取或刪除等攻擊。
       一個簡單的範例程式如下所示
public ActionResult TestFile(string fileName)
{
    //App_Data目錄
    string dirPath = Server.MapPath("~/App_Data");
    //組路徑字串
    string filePath = Path.Combine(dirPath, fileName);
    if (System.IO.File.Exists(filePath))//檔案存在的話
    {
        //原本預期下載Excel檔
        return File(filePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); 
    }
    else
    {
        return Content("not exists");
    }
}
        由前端輸入的fileName參數,在未過濾的情況下,可透過輸入fileName=../Web.config來取得Web.config。示範結果如下:

解決方法
       簡單的解決方法,是對檔案路徑的斜線及點符號進行過濾,將fileNameReplace對斜線及點符號過濾,程式碼如下
public ActionResult TestFile(string fileName)
{
    fileName = fileName.Replace("/", "").Replace("..", "");
    string dirPath = Server.MapPath("~/App_Data");
    string filePath = Path.Combine(dirPath, fileName);
    if (System.IO.File.Exists(filePath))
    {
        return File(filePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); 
    }
    else
    {
        return Content("not exists");
    }
}
       再重新執行,結果如下

留言

這個網誌中的熱門文章

IIS - ASP.NET 網站基本優化設定

Node.js 部署至 IIS 站台

遇見 Parameters 參數上限之大量資料寫入方法