node.js - secure image file upload

2019-08-08 17:10发布

问题:

We had to implement an image uploader for a node.js project. As framework we are using express.js We did it like described here: http://howtonode.org/really-simple-file-uploads

But we are not sure how to secure this image uploader. What we did so far is:

  • checking the file size
  • checking extension and header
  • rename the file
  • file is only accessible over a special route and is not in the root folder

Is this enough? We don't feel very comfortable with the following line:

    // CHECKING FOR FILESIZE, EXTENSION, HEADERS
    fs.readFile(req.files.displayImage.path, function (err, data) {
        ...
        ...
        ...
        // RENAMING FILE
        // SAVE FILE
        ...
        ...
        ...
    }

Is it save to read the image this way? We are afraid, there could be malicious code in req.files.displayImage.path. Do we need to add more checks or are our checks sufficient? What attack vectors do we offer an attacker if we use the code as described?

Thank you for your advices Tschoartschi

回答1:

If you are concerned for opening malicious images on client side as posted in your comments. Try opening third party scripts and untrusted files inside a sandboxed iframe this will protect your users.