3

I'm trying to understand how to deal(in a secure way) with Path Traversal.

For example an application receives from a client a file name via REST API in JSON, look for it in the non-accessible(by outside) directory and retrieve a response with the file:

app.get('/', (req, res) => {
  const fileName = req.body.fileName;
  // some code...
  fs.stat(`./nonAccessibleDir/${fileName}`, async function(err, stat) {
    // some code...
  });
  // some code...
}

The problem with the above approach is that a client can send something like "../" in the fileName request and it will "eat" it without an issue. How can one deal with this kind of scenarios, what and how I should fix this vulnerability, please?

Update: Sorry, but I forgot to mention that I know I should check the input I receive, but what if I need to pass the "/" and "." in the input? Also, if I don't need this characters, is that all I need to check to remove the Path Traversal vulnerability?

cobofe
  • 33
  • 1
  • 4

1 Answers1

2

An easy way would be to validate the fileName through a regex that detects any ../ segments and returns an error if any are present.

if (fileName.match(/\.\.\//g) !== null) {
    // return an api error
}

You could have quite a tight validation rule that prevents any forward slashes in fileName at all, making it only possible to point to a file directly in your desired directory.

Ezequiel Muns
  • 7,492
  • 33
  • 57
  • Thanks Ezequil, I thought about that as well, but wasn't sure if this is enough. Just updated my question – cobofe Jan 31 '21 at 15:23
  • So just to make sure, if I remove "." and "/" entirely from the request, then I should remove the Path Traversal vulnerability completely, is this correct? – cobofe Jan 31 '21 at 15:27
  • As far as I know, eliminating any forward slashes in the input is sufficient to eliminate the Path Traversal vulnerability as there is no changing of path “level” without them. – Ezequiel Muns Jan 31 '21 at 15:33
  • Eliminating . would get you in trouble as most files have an extension that is delimited by a single dot. – Ezequiel Muns Jan 31 '21 at 15:34
  • You're absolutely right, thanks a lot for your help, Ezequiel! – cobofe Jan 31 '21 at 15:35