如何确定相对路径是否在虚拟路径之外

时间:2012-11-29 19:55:35

标签: asp.net

我正在使用以下函数将路径转换为有效的虚拟路径:

public string GetFullPath(string path)
{
    Ensure.Argument.NotNullOrEmpty(path, "path");

    if (path[0] == '~') // a virtual path e.g. ~/assets/style.less
    {
        return path;
    }

    if (VirtualPathUtility.IsAbsolute(path)) // an absolute path e.g. /assets/style.less
    {
        return VirtualPathUtility.ToAppRelative(path,
            HostingEnvironment.IsHosted ? HostingEnvironment.ApplicationVirtualPath : "/");
    }

    // otherwise, assume relative e.g. style.less or ../../variables.less
    return VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(currentFileDirectory), path);
}

除了输入path是相对路径 网站目录之外,这传递了我的所有测试。

例如,如果currentFileDirectory~/foo/bar且相对路径为../../../,我想检测此情况并尝试修复路径。

2 个答案:

答案 0 :(得分:1)

Server.MapPath是验证虚拟路径或dos样式路径的简便方法。出于安全原因,验证受限于验证网站外的任何物理路径。请参阅上面的评论。

答案 1 :(得分:0)

为了详细说明迈克的回答,我们可以通过以下方式验证相对路径是否试图超出物理网站目录:

  1. 使用Path.GetFullPath
  2. 获取当前路径和相对路径的组合路径
  3. 使用Server.MapPath
  4. 获取尝试路径的文件系统路径
  5. 获取应用程序根目录的文件系统路径
  6. 验证尝试的路径是否存在于根路径中
  7. 示例:

    var currentFileDirectory = "~/foo/bar";
    var relativePath = "../../../";
    var attemptedPath = Path.GetFullPath(Path.Combine(Server.MapPath(currentFileDirectory), relativePath)); // 1 + 2
    var rootPath = Server.MapPath("~/"); // 3
    
    if (attemptedPath.IndexOf(rootPath, StringComparison.InvariantCultureIgnoreCase) == -1) // 4
    {
        throw new Exception(string.Format("Path {0} is outside path {1}", 
            rootPath, HostingEnvironment.ApplicationPhysicalPath));
    }