Contents

Avoid Untrusted Input for File Names

Avoid writing code that accepts file or path input from the caller and instead use fixed file names and locations when reading and writing data. This ensures your code cannot be coerced into accessing arbitrary files.

Do Not Trust Environment Variables

Validate Input File Names

If you do need to receive input file names from the caller, make sure that the filename is strictly formed so that you can determine whether it is valid. Specifically, there are two aspects to validating input file paths. You need to:

* Check for valid file system names.
* Check for a valid location, as defined by your application's context. For example, are they within the directory hierarchy of your application?

To validate the path and file name, use the System.IO.Path.GetFullPath method as shown in the following code sample. This method also canonicalizes the supplied file name.

using System.IO;
public static string ReadFile(string filename)
{
// Obtain a canonicalized and valid filename
string name = Path.GetFullPath(filename);
// Now open the file
}

As part of the canonicalization process, GetFullPath performs the following checks:

* It checks that the file name does not contain any invalid characters, as defined by Path.InvalidPathChars.
* It checks that the file name represents a file and not an another device type such as a physical drive, a named pipe, a mail slot or a DOS device such as LPT1, COM1, AUX, and other devices.
* It checks that the combined path and file name is not too long.
* It removes redundant characters such as trailing dots.
* It rejects file names that use the //?/ format.

Constrain File I/O Within Your Application's Context

After you know you have a valid file system file name, you often need to check that it is valid in your application's context. For example, you may need to check that it is within the directory hierarchy of your application and to make sure your code cannot access arbitrary files on the file system. For more information about how to use code access security to constrain file I/O, see "File I/O" in Chapter 8, "Code Access Security in Practice." at http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh08.asp