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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With