代码之家  ›  专栏  ›  技术社区  ›  BCS

Path.Combine的安全版本

  •  2
  • BCS  · 技术社区  · 16 年前

    我有一个 rootPath 这是我信任的 relativePath 我不知道。我想以这样一种方式将它们结合起来,这样我就可以确保结果是正确的 根路径 而且用户不能使用 .. 回到起点。我 希望相对路径允许以下操作: hello\..\world == world

    3 回复  |  直到 16 年前
        1
  •  6
  •   technophile    16 年前

    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");
    }
    
        2
  •  2
  •   Daniel Brückner    16 年前

    你可以打个电话 Path.GetFullPath() 并检查它是否从您信任的 rootPath . 如果你有妄想症,也要检查一下 根路径

    public Boolean IsPathSafe(String rootPath, String relativePath)
    {
      return rootPath.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
        Path.IsPathRooted(rootPath) &&
        Patch.Combine(rootPath, relativePath).GetFullPath().StartsWith(rootPath);
    }
    

    有关第一次测试的解释,请参阅Alex Martelli对技术爱好者答案的评论。

        3
  •  -1
  •   Tomas Aschan    16 年前

    你可以做的一件事是计算反斜杠的数量( \ .. rootPath 在你的文件夹结构中,你需要至少和双点一样多的反斜杠——因此,如果你只允许的话 relativePath 如果再加上至少一个反斜杠,您应该是安全的。