Question

I'm analyzing my code (C#, desktop application) with CAT.NET Code Analysis and getting "Sanitize the file path prior to passing it to file system routines" message when dealing with file names. What I don't understand is that to ensure the file name is valid, I use:

void SomeMethod(String filename)
{
    filename = System.IO.Path.GetFullPath(filename);
    // ... Do stuff
}

Isn't it a "magic solution" to solve problems with invalid file names ? I've read something similar here (first answer), but in my case I'm dealing only with local files, well, something very basic, so...

So why I'm getting this message and how to do to avoid getting it?

Was it helpful?

Solution

I know this is an old question, but I've just come across something that may be helpful specifically related to the CAT.Net error message.

In a blog post about the CAT.Net Data Flow Rules, they have this to say about the FileCanonicalizationRule:

Description

User input used in the file handling routines can potentially lead to File Canonicalization vulnerability. Code is particularly susceptible to canonicalization issues if it makes any decisions based on the name of a resource that is passed to the program as input. Files, paths, and URLs are resource types that are vulnerable to canonicalization because in each case there are many different ways to represent the same name.

Resolution

Sanitize the file path prior to passing it to file handling routines. Use Path.GetInvalidFileNameChars or Path.GetInvalidPathChars to get the invalid characters and remove them from the input. More information can be found at http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx.

So, they suggest that you use Path.GetInvalidFileNameChars and Path.GetInvalidPathChars to validate your paths.

Note that their suggestion is to remove the invalid characters. While this will indeed make the path valid, it may cause unexpected behaviour for the user. As the comments on this question/answer suggest it's probably better to quit early and tell the user that their path is invalid, rather than doing something unexpected with their input (like removing bad characters and using the modified version).

OTHER TIPS

If the filename comes from a user, it could be something like "../../../../etc/passwd" - the error message is telling you that you need to sanitize it so that it can't get to directories it's not supposed to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top