3

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.

securecodeninja
  • 2,497
  • 3
  • 16
  • 22
gaurav bhavsar
  • 2,033
  • 2
  • 22
  • 36
  • 1
    See this answer: https://stackoverflow.com/a/4535684/224370 You should never trust user input to create a file path on the server. – Ian Mercer Mar 31 '21 at 05:17
  • 1
    Looks like an MVC Controller action? The security issue would be that someone could technically pass in `C:\link\to\private\database` and you'd return them the database. Solution is to never have an endpoint that takes a file system path, better to treat any files you serve as "assets" and keep them within the solution. –  Mar 31 '21 at 05:22

1 Answers1

2

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.

baruchiro
  • 5,088
  • 5
  • 44
  • 66