How to fix this code so that it does not accuse this type of vulnerability?
I'm using checkmarx to scan, and he encountered this problem when downloading a file
Error reported by checkmarx:
Method Index at line 13 of src\BR.Rve.UI.Site\Controllers\DownloadFileController.cs gets dynamic data from the fileName element. This element’s value then flows through the code and is eventually used in a file path for local disk access in Index at line 13 of src\BR.Rve.UI.Site\Controllers\DownloadFileController.cs. This may cause a Path Traversal vulnerability." and I'm having a little trouble solving this
and I'm having a little trouble solving this
My original code:
public FileResult Index(string fileName)
{
string rootPath = System.Configuration.ConfigurationManager.AppSettings.Get("FinalUploadFolder");
byte[] fileBytes = System.IO.File.ReadAllBytes(string.Format("{0}/{1}", rootPath,fileName));
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
I've tried this solution below, but it didn't work
private static readonly char[] InvalidFilenameChars = Path.GetInvalidFileNameChars();
public ActionResult Index(string fileName)
{
if (fileName.IndexOfAny(InvalidFilenameChars) >= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
string rootPath = System.Configuration.ConfigurationManager.AppSettings.Get("FinalUploadFolder");
byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(rootPath,fileName))));
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
What could I do in the code to avoid this type of problem when scanning