Nodejs:通过快速参数检索文件是否安全?

Nodejs: Is it secure to retrieve a file by express param?

下面的代码是安全的还是我需要保护参数免受注入?是否可以访问 /content/includes 之外的文件?

app.get('/api/includes/:slug', (req, res) => {
  const file = __dirname + '/content/includes/' + req.params.slug + '.html';
  if (fs.existsSync(file)) res.sendFile(file);
  else res.sendStatus(404);
});

绝对可以访问 /content/includes 之外的文件,只需将 ../ 添加到 slug 路径即可。你可以使用 path.normalize 遍历路径并删除所有 ../,但这仍然会给你一个可以在你想要的目录之外的路径,所以你可以使用 path.join 来确保你的预期目录位于预期路径的开头。

// remove all `../` from the start of the slug.
const relativeSlug = req.params.slug.replace(/^(\.\.\/)+/, '');
// normalize the path
const normalizedSlug = path.normalize(relativeSlug);
const file = path.join(__dirname + '/content/includes/', normalizedSlug);

这将有助于确保 slug 路径位于您预期的目录下。

进程 运行 您的服务器也应该对文件系统具有有限的访问权限,并且一开始就不能从其他目录读取太多内容。

在此处查看更多相关信息:https://www.owasp.org/index.php/Path_Traversal