Search code examples
c++linuxunixpathsanitization

Path sanitization in C++


I'm writing a small read-only FTP-like server. Client says "give me that file" and my server sends it.

Is there any standard way (a library function?!?) to make sure that the file requested is not "../../../../../etc/passwd" or any other bad thing? It would be great if I could limit all queries to a directory (and its subdirectories).

Thank you!


Solution

  • Get the inode of the root (/) directory, and that of the serving directory (say /ftp/pub). For the files they request, make sure that:

    1. The file exists.
    2. The parents of the file (accessed using multiple "/.." on the file path) hit the serving directory inode before it hits the root directory inode.

    You can use stat to find the inode of any directory. Put this in one function, and call it before serving the file.

    Of course using a user/group with appropriate privilege will work as well.