且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我的以下代码中可能存在路径遍历漏洞吗?

更新时间:2023-09-11 23:24:16

是的,它很容易受到攻击.

Yes, it is vulnerable.

为了证明这一点,我建立了一个名为 WebApplication1.sln

Just to prove it, I set up a new MVC project called WebApplication1.sln

以下请求下载解决方案文件:

The following request downloads the solution file:

http://localhost:56548/Home/Download?fileName=../../WebApplication1.sln

您可以写一个幼稚的支票:

You can write a naive check:

private static readonly char[] InvalidFilenameChars = Path.GetInvalidFileNameChars();
public ActionResult Download(string fileName)
{
    if (fileName.IndexOfAny(InvalidFilenameChars) >= 0)
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    var rootPath = Server.MapPath("~/ClientDocument/");
    byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(rootPath, fileName));
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

这将检查 fileName 参数是否为有效的文件名.此排除目录分隔符,因此它们不能将路径作为文件名传递.

Which will check that the fileName argument is a valid file name. This excludes directory separator characters, so they cannot pass a path as a filename.

但是,完全安全的唯一方法是限制应用程序拥有的权限.只授予它对您的虚拟目录的权限,而没有其他权限.

However, the only way to be completely safe, is to restrict the permissions your application has. Only grant it permission to your virtual directory, and nothing else.