Path Manipulation Solution?

4.5k views Asked by At

Ok, so typically if any kind of 'Path Manipulation' issues arise from your analysis software, they really seems to be only one solution, to not allow the user to select their own desired pathway.

I have generated this simple method that would do some validation in protecting against these attacks.

private const string directory = "Windows";
private static readonly string[] extensions = {".pdf", ".txt"};

string userInput = @"..\windows\..\krnl386.exe";

        private static bool Validate(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return false;
            }

            if (filePath.ToUpper().Contains(directory.ToUpper()))
            {
                return false;
            }

            string ext = Path.GetExtension(filePath);

            for (int x = 0; x < extensions.Length; x++)
            {
                if (ext.Equals(extensions[x]))
                {
                    return true;
                }
            }

            return false;
        }

Now would these two checks help prevent any kind of 'Path Manipulation'? What holes in this method do you see? The applications that this applies to would never need access to the windows directory nor would it use more than a .pdf or .txt file extension.

1

There are 1 answers

3
Jim Mischel On BEST ANSWER

So that prevents any path that contains the word "windows", regardless of case. So "MyWindowsStuff" would be excluded. You'll probably want to make the extensions check case-insensitive, too.

You'll also want to work on the full path rather than just the relative path.

Whether that's enough is kind of up to you. Do you consider it possible or likely that somebody would use short file names to get to the restricted directory? For example, if you wanted to prevent people from getting to the "Program Files" directory, you'd have to get the short name of that directory and compare against it, too. On my system, "Program Files" is "PROGRA~1" and "Program Files (x86)" is "PROGRA~2".

Regarding your comment about "MyWindowsStuff" being a rare case. What if somebody has a file named "windows.txt", which is a description of the windows that he wants to put in his house? Or a "Windows" directory that's a sub-directory of the "Documents" folder, where he's putting together a quote for windows that he is going to install for a client? Your "rare case" is not so rare is you might thing.

The only "Windows" directory you want to block is the Windows directory, which is not necessarily even called "Windows". You get the name of that directory by calling Environment.GetFolderPath:

Environment.GetFolderPath( Environment.SpecialFolder.Windows )

Any other directory called "Windows" or containing the word "windows" is not the Windows directory, and shouldn't be blocked, nor should a path name that contains the word "windows" in a file name.