NodeJS默认阻止目录/路径遍历吗?

Jus*_*der 6 javascript security node.js

Expressjs 的“express.static()”默认情况下会阻止目录/路径遍历,但我认为 Nodejs 默认情况下对目录/路径遍历没有任何保护?最近尝试学习一些网络开发安全性(目录/路径遍历),我创建了这个:

const http = require("http");
const fs = require("fs");

http
  .createServer(function (req, res) {
    if (req.url === "/") {
      fs.readFile("./public/index.html", "UTF-8", function (err, data) {
        if (err) throw err;
        res.writeHead(200, { "Content-Type": "text/html" });
        res.end(data);
      });
    } else {
      if (req.url === "/favicon.ico") {
        res.writeHead(200, { "Content-Type": "image/ico" });
        res.end("404 file not found");
      } else {  
        fs.readFile(req.url, "utf8", function (err, data) {
          if (err) throw err;
          res.writeHead(200, { "Content-Type": "text/plain" });
          res.end(data);
        });
      }
    }
  })
  .listen(3000);

console.log("The server is running on port 3000");

Run Code Online (Sandbox Code Playgroud)

模拟目录/路径遍历安全漏洞,但我尝试使用“../../../secret.txt”,当我检查“req.url”时,它显示“/secret.txt”而不是“.. /../../secret.txt”,我也尝试使用“%2e”和“%2f”,它仍然不起作用,我仍然无法获取“secret.txt”


(我的文件夹结构)

- node_modules
- public
  - css
    - style.css
  - images
    - dog.jpeg
  - js
    - script.js
  index.html
- package.json
- README.md
- server.js
- secret.txt
Run Code Online (Sandbox Code Playgroud)

Kip*_*vas 3

根据express.static [1]的文档(它导致了serve-static模块[2]的文档),您提供的目录是根目录这意味着故意使其无法访问其之外的任何内容。

要提供静态文件(例如图像、CSS 文件和 JavaScript 文件),请使用 Express 中的express.static 内置中间件函数。

函数签名是:

express.static(root, [选项])

root 参数指定提供静态资源的根目录。有关选项参数的更多信息,请参阅express.static。[3]

[1] https://expressjs.com/en/starter/static-files.html

[2] https://expressjs.com/en/resources/middleware/serve-static.html#API

[3] https://expressjs.com/en/4x/api.html#express.static


fs不相关,但仅供参考:您提供给等的路径与调用脚本的位置相关。

例如,如果您node server.js从应用程序的根文件夹调用,该路径"./public/index.html"应该可以正常工作,但如果您从不同的路径调用它,它将失败,例如node /home/user/projects/this-project/server.js

因此,您应该始终使用 加入路径__dirname,如下所示:

+const path = require("path");

-fs.readFile("./public/index.html", "UTF-8", function (err, data) {
+fs.readFile(path.join(__dirname, "./public/index.html"), "UTF-8", function (err, data) {
}
Run Code Online (Sandbox Code Playgroud)

这使得路径相对于您尝试从中访问的当前文件的目录,这正是您所期望的。