Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Path Traversal Vulnerabilities possible in my below code?

Tags:

c#

security

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);
}
like image 969
Kundan Rai Avatar asked May 23 '16 05:05

Kundan Rai


1 Answers

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.

like image 73
Rob Avatar answered Sep 29 '22 07:09

Rob