Is Path Traversal Vulnerabilities possible in my below code?

笑着哭i 提交于 2021-02-07 14:52:49

问题


Can anyone please confirm, is Path Traversal Vulnerabilities is possible in my below code snippet? if yes then what changes I should make.

[RedirectingAction]
public ActionResult Download(string fileName)
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

回答1:


Yes, it is vulnerable.

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);
}

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.




回答2:


In concept what you should do to alleviate a Path Traversal vulnerability is to evaluate your basePath to its real path, and likewise do the same to your basePath plus the fileName. If the resulting file of the second operation is still within the folder from your basePath, you know that Path Traversial has not taken place.

I'm using a much later version of .NET so Server.MapPath is not valid. As a result, I'm not sure if this will run for you; but this at least demonstrates how to fix it in concept:

[RedirectingAction]
public ActionResult Download(string fileName)
{
    var baseFolder = Path.GetFullPath(Server.MapPath("~/ClientDocument/"));
    var targetFile = Path.GetFullPath(Path.Combine(baseFolder, fileName));
    if(targetFile.StartsWith(baseFolder){
      byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName);
      return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    } else {
      //Don't do the download and do something else.
    }  
}


来源:https://stackoverflow.com/questions/37383143/is-path-traversal-vulnerabilities-possible-in-my-below-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!