javascript - nodejs 默认情况下会阻止目录/路径遍历吗?
问题描述
Expressjs 的 "express.static()" 默认情况下会阻止目录/路径遍历,但我认为 Nodejs 默认情况下对目录/路径遍历没有任何保护?最近尝试学习一些 Web 开发安全性(目录/路径遍历),我创建了这个:
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] 的文档,您提供的目录是根目录,这意味着它故意使其无法访问它之外的任何内容。
要提供静态文件,例如图像、CSS 文件和 JavaScript 文件,请使用 Express 中的 express.static 内置中间件函数。
函数签名是:
express.static(根,[选项])
root 参数指定提供静态资产的根目录。有关 options 参数的更多信息,请参阅 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) {
}
这使得路径相对于您尝试访问它的当前文件的目录,这是您所期望的。
推荐阅读
- python - 为 pyplot 轴刻度标签设置小数位
- java - 带有火花的 Cassandra:java.io.IOException:无法在 {127.0.0.1:9042} 打开到 Cassandra 的本机连接 ::
- python - pygame中的.quit和.QUIT有什么区别
- oracle - 过程中的光标并调用过程
- python - xhtml2pdf django-cms 'sekizai.context_processors.sekizai' 或使用 'sekizai.context.SekizaiContext'
- javascript - 从 Firebase Functions 和 puppeteer 下载 PDF
- c++ - 我无法编译 SimGrid - S4U
- html - 带有flexbox的div底部的定位按钮
- jspdf - 如何在jspdf中以粗体显示文本?
- python - 获取 k 个排序数组的交集的最有效方法是什么?