cserverdocument-root

How do I make sure nobody gets access to files out of my document root in my websever


I'm currently working on a webserver in C. I want to make sure that it's impossible to access files that are outside of my document root and I need to write a function that checks the request file / path to that file (for example /index.html) and makes sure there is no way to get out of my document root(for example /../ would make it go out of document root). I was thinking about just checking for ../ and removing that, but then somebody could request ....//, which would be ../ again if we remove ../ out of it. Is there some clever way to do this that I'm not thinking about?


Solution

  • Use realpath:

    realpath - return the canonicalized absolute pathname

    It will return the absolute pathname, with all symlinks, all ./ and all /../ resolved. Store your "document root" after resolving it with realpath too. After that you can simply memcmp or strcmp resolved path to document root with the resolved pathname to the path you want to test..