首页 > 解决方案 > 如何在 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('../')只是部分解决方案

标签: javascriptnode.jssecurity

解决方案


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
    }
}

推荐阅读