G
G
gleendo2017-05-14 08:37:49
Node.js
gleendo, 2017-05-14 08:37:49

Why check the path to a file?

Why did you check

(!filePath.startsWith(`${config.publicRoot}${path.sep}`))
? It seems like the author says that supposedly this will not allow going beyond root, but `${config.publicRoot}${path.sep}` will always be equal to the same path, even if you try to go beyond, for example ../ ../../. Why then this check?
let url = require(`url`);
let fs = require("fs");
let path = require(`path`);
let config = require(`config`);
let mime = require(`mime`);

let handler = (req, res) => {
    let urlParse = url.parse(req.url);
    let pathname = urlParse.pathname;
    let filePath = path.join(config.publicRoot, pathname);

    console.log(pathname); // /page/my.html
    console.log(filePath); // C:\Users\iamevg_\Desktop\app\public\page\my.html
    console.log(`${config.publicRoot}${path.sep}`); // C:\Users\iamevg_\Desktop\app\public\

    if (!filePath.startsWith(`${config.publicRoot}${path.sep}`)) {
        res.statusCode = 400;

        res.end(`Bye-bye silly hacker!`);

        return;
    }

    let file = fs.ReadStream(filePath);

    let write = () => {
        let data = file.read();

        if (data && !res.write(data)) {
            file.removeListener(`readable`, write);

            file.once(`drain`, () => {
                file.on(`readable`, write);

                write();
            });
        }
    };

    file.on(`readable`, write);

    file.on(`error`, (err) => {
        if (err.code === `ENOENT`) {
            res.statusCode = 404;

            res.end(`404 File Not Found`);
        } else {
            res.statusCode = 500;

            res.end(`500 Server Error`);
        }

        console.log(err);
    });

    file.on(`end`, () => {
        res.end();
    });

    res.on(`close`, () => {
        file.destroy();
    });
};

module.exports = handler;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question