javascript - 默认情况下,nodejs 会阻止目录/路径遍历吗?

标签 javascript node.js security

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");

模拟目录/路径遍历安全漏洞,但我尝试使用“../../../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

最佳答案

根据 express.static [1] 的文档,它指向 serve-static 模块 [2] 的文档,您提供的目录是 root 目录,这意味着它是有意制作的无法访问它之外的任何东西。

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

The function signature is:

express.static(root, [options])

The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see 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) {
}

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

关于javascript - 默认情况下,nodejs 会阻止目录/路径遍历吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65860214/

相关文章:

java - 如何使用特定模式的 CSP header URL

javascript - 将 Flux 存储中的 Immutable.js 映射与内部 React 组件状态合并

node.js - 当所需文件不导出任何内容时,require() 会做什么?设置 Mongoose + express 的正确方法是什么?

javascript - 当客户端浏览器退出时如何终止node.js服务器连接?

node.js - 如何实现 SailsJS + Phonegap/Cordova 应用程序

c# - 防止SQL注入(inject)的好方法有哪些?

security - Maven 包签名或您如何信任/验证 Maven Central Artifact 的完整性和真实性?

javascript - 当 Canvas 的高度超过屏幕的高度时(当滚动条出现时),如何在 Canvas (JavaScript)上测试鼠标检测

javascript - 动态加载 jQuery 模板

javascript - jQuery 屏幕键盘在第二个输入