簡體   English   中英

防止用戶指定的文件名在 Node.JS 應用程序中使用相對路徑元素的防彈方法?

[英]Bulletproof way to prevent user specified file names from using relative path elements in a Node.JS app?

我正在創建一個允許用戶編輯各種文檔的 Node.JS 應用程序。 在服務器上為每個用戶創建一個子目錄,使用他們的用戶 ID 作為子目錄名稱。 我現在不想使用數據庫,因為我在緊迫的期限內創建原型,所以我現在使用基於文件的系統來快速完成工作。

請注意,用戶從我的 web 頁面之一的 web 瀏覽器訪問系統。

當用戶創建文檔時,他們指定文檔名稱。 現在,在服務器端,文檔名稱已清除操作系統 (Linux) 不支持的任何字符,僅此而已。 我擔心的是,用戶可能會嘗試使用插入到文檔名稱中的相對路徑組件來訪問不屬於他們的目錄,以試圖“上下走動”目錄樹以跳出子目錄從他們那里保留。

我讀過一些關於用戶通過奇異的 UTF-8 代碼等找到巧妙方法來執行此操作的恐怖故事,所以我正在尋找一個 Node.JS 代碼示例或庫,它具有 function 消除了文件中的所有相對路徑元素以徹底和健壯的方式命名。

在服務器端,我如何才能絕對確保在瀏覽器的 POST 中提交的用戶創建的文檔名稱是主文件名,而不是別的?

我正在使用 express,我不確定這是否是防彈的,但它似乎正在做我需要的事情(在處理請求之前確保文件存在)

const fs = require('fs');
const path = require('path');

checkUserSuppliedFilenameExists(req, res) {

  if(!req.body.fileName) {
    return res.status(400).json({ message: "missing required parameters" });
  }
  
  /**
   * strip any potentially harmful stuff from the start of the string
   * will return the following:
   * "foo.txt" => "foo.txt"
   * "foo" => "foo"
   * "../../foo.txt" => "foo.txt"
   * "/etc/foo.txt" => "foo.txt"
   * undefined => TypeError
   * null => TypeError
   */
  let suppliedFilename = path.basename(req.body.fileName);
  // build the path to the file in the expected directory
  // using __dirname to build relatively from the script currently executing
  let filePath = path.resolve(__dirname, `../my-specified-directory/${suppliedFilename}`);
  // check if it exists
  if(!fs.existsSync( filePath ) ) {
    return res.status(400).json({ message: "file doesn't exist stoopid" });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM