russellallen/self-webserver — pull request #3 by doublec (2014-10-02 11:03:44+00:00)
Title: Prevent directory traversal attacks in fileServlet

The fileServlet example suffers from a [directory traversal attack](http://en.wikipedia.org/wiki/Directory_traversal_attack).

It can be demonstrated by having a file ~/Site/index.html. Starting the webserver with the fileServlet as the registered servlet, the following HTTP request initiated using 'nc' retrieves it:

nc 127.0.0.1 8080
GET /index.html HTTP/1.1

...contents of index.html...

The attack though is if there is a file outside the servlets baseDirectory, say ~/bad.html, then this request retrieves it:

nc 127.0.0.1 8080
GET /../old.html HTTP/1.1

...contents of old.html...

The fix for this is to canonicalize the requested URL such that `..` and `.` are resolved to the correct locations then compare this to the `baseDirectory`. There is a posix call `realpath` that does this but to be portable I implemented a Self function to do it. The alternative, and maybe it could be done as well, is to make `realpath` used in the C++ VM. I can do a patch for that if desired. For this example servlet I wanted to avoid changing the VM though.