7

I have a root path represented by an std::filesystem::path. I want to add some user provided filename to this path and make sure the resulting path is not out of the root directory.

For example:

    std::filesystem::path root = "/foo/bar";
    std::filesystem::path userFile = "ham/spam";
    std::filesystem::path finalPath = root / userFile;

The final path is ok, it is inside /foo/bar. But if I give ../ham/spam to the userFile variable, this will result in a file outside the define rootPath.

How can I check that the resulting file keeps inside its allowed boundaries ?

RAM
  • 2,257
  • 2
  • 19
  • 41
Nicolas Appriou
  • 2,208
  • 19
  • 32

1 Answers1

11

First, you need to normalize the final path. This removes all . and ..s in the path. Then, you need to check to see if it has any mismatches in its directory iterator range, relative to root. And there's a standard library algorithm for that.

So overall, the code looks like this:

std::optional<fs::path> MakeAbsolute(const fs::path &root, const fs::path &userPath)
{
    auto finalPath = (root / userPath).lexically_normal();

    auto[rootEnd, nothing] = std::mismatch(root.begin(), root.end(), finalPath.begin());

    if(rootEnd != root.end())
        return std::nullopt;

    return finalPath;
}

Note that this only works theoretically; the user may have used symlink shenanigans within the root directory to break out of your root directory. You would need to use canonical rather than lexically_normal to ensure that this doesn't happen. However, canonical requires that the path exist, so if this is a path to a file/directory that needs to be created, it won't work.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    use `std::filesystem::weakly_canonical()` to avoid requirement of existance in `canonical` – Piotr Dec 05 '22 at 17:38