views:

321

answers:

1

Hi. 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?

A: 

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.

Annie
That's exactly why I use Path.GetFullPath, which will transform a path like "C:\SomeStuff\ChildDirectory\..\..\FileHere.txt" to "C:\FileHere.txt".
MainMa
And that is a huge security risk if the user entered the path--they could possibly access/overwrite files in directories they shouldn't be allowed to touch. In your example, you're assuming the file will be in "C:\SomeStuff\ChildDirectory", but really they're accessing a file in "C:\".
Annie
I really don't understand.Path.GetFullPath("C:\SomeStuff\ChildDirectory\..\..\FileHere.txt") gives "C:\FileHere.txt". So by calling GetFullPath() at the beginning of each method (when need) and using its result, I'm safe. Or not?
MainMa
If you just call GetFullPath with a user-supplied filename, you allow the user to access *any* path on the machine, not just the paths they are supposed to access. For example, lets say your app allows users to upload images, and stores them to c:\MyApp\Images, with the name the user specifies. They specify the name "..\..\Windows\explorer.exe" and overwrite C:\Windows\explorer.exe with a trojan. So you need to sanitize out things like "..\" instead of just accepting them into GetFullPath().
Annie