Is this method of static file serving safe in node.js? (potential security hole?)

Posted by MikeC8 on Stack Overflow See other posts from Stack Overflow or by MikeC8
Published on 2012-06-01T16:36:56Z Indexed on 2012/06/01 16:40 UTC
Read the original article Hit count: 190

Filed under:

I want to create the simplest node.js server to serve static files.

Here's what I came up with:

fs = require('fs');
server = require('http').createServer(function(req, res) {
    res.end(fs.readFileSync(__dirname + '/public/' + req.url));
});
server.listen(8080);

Clearly this would map http://localhost:8080/index.html to project_dir/public/index.html, and similarly so for all other files.

My one concern is that someone could abuse this to access files outside of project_dir/public. Something like this, for example:

http://localhost:8080/../../sensitive_file.txt

I tried this a little bit, and it wasn't working. But, it seems like my browser was removing the ".." itself. Which leads me to believe that someone could abuse my poor little node.js server.

I know there are npm packages that do static file serving. But I'm actually curious to write my own here. So my questions are:

  1. Is this safe?

  2. If so, why? If not, why not?

  3. And, if further, if not, what is the "right" way to do this? My one constraint is I don't want to have to have an if clause for each possible file, I want the server to serve whatever files I throw in a directory.

© Stack Overflow or respective owner

Related posts about node.js