【问题标题】:NodeJS/Formidable : secure the backend for images uploadNodeJS/Formidable : 保护图片上传的后端
【发布时间】:2017-01-13 01:42:54
【问题描述】:

我正在使用 NodeJS/Formidable,并尝试保护我的后端以上传图片。

检查文件是否为图像的经典方法是使用这样的正则表达式:

if(!file.name || file.name.match(/\.(jpg|jpeg|png)$/i)) {
    console.log("the file is an image");
}else{
    console.log("the file is not an image");
}

还有这个:

var fileType = file.type.split('/').pop();
if(fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg' ){
    console.log("the file is an image");
} else {
    console.log( 'incorrect file type: ' + fileType );
}

这是一个很好的检查,但这还不够安全;事实上,如果我将 PDF 重命名为 JPG,浏览器会根据文件的扩展名提供 MIME/type : image/jpg。 这是一个安全问题,因为您可以将 JS 文件或其他任何文件重命名为 JPG 并将其上传到后端文件系统中。

我发现这篇非常有趣的帖子:How to check file MIME type with javascript before upload?

它非常适合客户端检查,但我无法在后端重现。

我想理想的方法是动态分析流并在上传前 4 个字节后检查真正的 MIME 类型。

有什么想法吗?

谢谢!

【问题讨论】:

    标签: javascript node.js image-uploading formidable


    【解决方案1】:

    有效! 您可以安装类似readChunk 的模块来将文件转换为缓冲区并编写类似的内容:

    form.on('file', function(field, file) {
        buffer = readChunk.sync(file.path, 0, 4100);
    
        filetype = fileType(buffer);
    
        if(filetype.ext.match(/(jpg|jpeg|png)$/i)) {
            fs.rename(file.path, path.join(form.uploadDir, file.name));
        }else {
            fs.unlink(file.path);
        }
    
    });
    

    【讨论】:

      【解决方案2】:

      您可能应该使用类似file-type npm 包的东西,它需要一个缓冲区(至少前 4100 个字节)并返回 MIME 类型和文件扩展名:

      const fileType = require('file-type')
      fileType(buffer) //=> {ext: 'png', mime: 'image/png'} 
      

      【讨论】:

        猜你喜欢
        • 2021-04-25
        • 2011-07-28
        • 2020-08-04
        • 2019-11-17
        • 1970-01-01
        • 1970-01-01
        • 2012-01-13
        • 2018-11-11
        • 1970-01-01
        相关资源
        最近更新 更多