ASP.NET - Path Traversel exploit when downloading a File

681 views Asked by At

How could I solve this problem in that code. I've tried some approaches, but I couldn't pass the checkmarx test (system used to perform the scan)

FinalUploadFolder comes from the WebConfig file, which is where the files are saved

public FileResult Index(string attachedFile)
   {
       string rootPath = System.Configuration.ConfigurationManager.AppSettings.Get("FinalUploadFolder");
       byte[] file= System.IO.File.ReadAllBytes(string.Format(Path.Combine(rootPath, attachedFile.ToString())));
       return File(file, System.Net.Mime.MediaTypeNames.Application.Octet, attachedFile.ToString());         
   }
1

There are 1 answers

0
securecodeninja On

Validating and sanitizing input is a secure coding best practice. There are plenty of "sanitizers" that Checkmarx looks out for and Path.GetFilename is one of them.

Also, I believe the attachedFile is what Checkmarx is more likely concerned at, and it is possible that malicious input could be passed into the parameter. So try to change your code with the following:

public FileResult Index(string attachedFile)
   {
       attachedFile = Path.GetFileName(attachedFile);
       string rootPath = System.Configuration.ConfigurationManager.AppSettings.Get("FinalUploadFolder");
       byte[] file= System.IO.File.ReadAllBytes(string.Format(Path.Combine(rootPath, attachedFile.ToString())));
       return File(file, System.Net.Mime.MediaTypeNames.Application.Octet, attachedFile.ToString());         
   }