防止用户指定的文件名在Node.JS应用程序中使用相对路径元素的防弹方法



我正在创建一个Node.JS应用程序,允许用户编辑各种文档。使用每个用户的用户ID作为子目录名,在服务器上为每个用户创建一个子目录。我现在不想使用数据库,因为我在一个紧迫的最后期限内创建原型,所以我现在使用基于文件的系统来快速完成任务。

请注意,用户可以从我的一个网页的web浏览器访问系统。

当用户创建文档时,他们会指定文档名称。现在,在服务器端,文档名称已清除了操作系统(Linux)不支持的任何字符,但仅此而已。我担心的是,用户可能会试图使用插入到文档名称中的相对路径组件来访问不属于他们的目录,试图"上下走动"目录树,以突破为他们保留的子目录。

我读过一些可怕的故事,用户通过奇异的UTF-8代码等想出了聪明的方法来实现这一点,所以我正在寻找一个Node.JS代码示例或库,它具有一个功能,可以彻底而稳健地消除文件名中的所有相对路径元素。

在服务器端,我如何确保在浏览器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" });
}
}

最新更新