I already tried these solutions
Does my code prevent directory traversal in C#?
Is Path Traversal Vulnerabilities possible in my below code?
How to prevent Path Traversal in .NET
How to avoid Directory Traversal in my code
But still, Checkmarx scanning giving a security issue, below is the code
public FileContentResult GetImageFromFilePath(string filePath)
{
byte[] image = null;
if (!string.IsNullOrEmpty(filePath))
{
image = System.IO.File.ReadAllBytes(filePath);
}
if (image == null)
return null;
return File(image, "image/jpeg");
}
The issue is on this line of code image = System.IO.File.ReadAllBytes(filePath);
Please let me known how to solve this security issue.
Thanks in advance.
Path Traversal is about you building a path from the user input, mainly you have an assumption about the user input, for example, the user gives you the year
and the index
, and you return the right image: $"App/Photos/${year}/${index}.png"
.
The traversal is that the user gives you a relative part, for example, for year
- ../private
so that the path will be App/private/1.png
.
To sanitize this example (and you need to think about more cases, and don't make any assumptions), you need to use filePath.Replace("..", "")
. before using the filePath
to access the filesystem.