node.js - Nodejs : Is it secure to retrieve a file by express param?

标签 node.js express code-injection

下面的代码安全吗?或者我是否需要保护参数免遭注入(inject)?是否可以访问 /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);
});

最佳答案

只需将 ../ 添加到 slug 路径,就可以访问 /content/includes 之外的文件。您可以使用 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

关于node.js - Nodejs : Is it secure to retrieve a file by express param?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50394219/

相关文章:

javascript - 如何使用 ajax 和 Node 从表单中获取请求

javascript - Node.js 进程未检测到端口已被使用

javascript - 为什么在使用 sendFile() 方法为 node.js 中的两条路由提供静态文件时出现错误

node.js - 无法使用 express 处理 node.js 域的异常

node.js - Sendgrid 更改链接的 href

php - PHP PDO 的 Mysql 转义 % 和 _

javascript - unhandledRejection 不可分配给信号类型的参数

javascript - Node : How to make spawn function synchronous instead of using spawnSync?

javascript - 如何间接使用ContentScripts中网页定义的函数?

javascript - 构建 bash 命令时如何防止注入(inject)攻击?