Path.Combine的安全版本

BCS*_*BCS 2 .net relative-path path-manipulation

我有一个rootPath我信任的relativePath,而我不信任.我希望以这样的方式组合它们,以确保结果不足rootPath并且用户不能使用它..来回到起点.我确实希望相对路径允许以下内容:hello\..\world==world

tec*_*ile 6

System.IO.Path.GetFullPath

要展开:使用Path.Combine,然后对结果调用GetFullPath并检查该结果是否以rootPath开头.

它不会保护你免受硬链接,但它应该捕捉简单的事情,如双点.

以上代码:

string Resolve(string fileName)
{
    string root = FileRoot();
    string ret = Path.GetFullPath(Path.Combine(root, fileName));
    if (ret.StartsWith(root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar)) return ret;
    throw new ArgumentException("path resolved to out of accesable directroy");
}
Run Code Online (Sandbox Code Playgroud)

  • 但是,如果root不以\结尾,它仍然可以播放一个有限的技巧 - 最终在另一个目录中,一个根目录的兄弟,以它作为前缀开始.例如,root可能是\ zip\zop,相对路径..\zopper\zup,你最终在\ zip\zopper\zup中,在@ zip\zop的树之外,但仍然满足StartsWith测试.风险小,但不是零. (4认同)