javascript - 如何在 Node.js 中验证来自 HTTP 请求的文件名?
问题描述
我有一个 node.js 应用程序,它公开一个 API 以从资产目录中删除图像。
因此用户可以执行DELETE
请求并发送指定的图像进行删除,这是当前处理的方式:
const assetsPath = '/assets'
deleteFile(file: string) {
fs.unlink(`${assetsPath}/${file}`, (err) => {})
}
问题在于用户可以像这样提交请求:
http://server.com?fileName=../../some_personal_file.exe
它会删除资产目录之外的文件
我怎样才能防止这种情况?我想检查fileName.includes('../')
只是部分解决方案
解决方案
Node.js 已经发布了关于如何缓解这种攻击的信息(称为路径遍历)。
从该咨询中获取,您可以使用该path
模块来确保此操作是安全的,如下所示:
const path = require('path');
const assetsPath = '/assets';
deleteFile(file: string) {
let deletePath = path.join(assetsPath, file);
if (deletePath.indexOf(assetsPath) === 0) {
fs.unlink(deletePath, err => {});
} else {
// Display an error to the user somehow
}
}
推荐阅读
- node.js - Azure 不将 index.html 作为可执行入口点
- javascript - 带有条件存储的 rxjs publishReplay
- c++ - Vector.push_back 问题
- jquery - 在 CSS 中删除带有动画效果的线条
- vue.js - [Vue 警告]:挂载钩子中的错误:“TypeError:this.$refs.canvas 未定义”
- android - 确定 android 设备是否是 samsung edge 设备之一
- deep-learning - 如何在使用 SSD 的对象检测中拒绝误报?
- docker - 带有 .npmrc 的 Docker 和私有包
- css - 根据其他类的存在有条件地隐藏元素
- cassandra - DSE Cassandra 审核日志未在 DML 中捕获 UDT