Avoid user-supplied file name and path input
J.D. Meier, Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen
Where possible, avoid writing code that accepts user-supplied file or path input. Failure to do this can result in attackers coercing your application into accessing arbitrary files and resources. If your application must accept input file names, file paths, or URL paths, validate that the path is in the correct format and that it points to a valid location within the context of your application.File Names
Ensure that file paths only refer to files within your application's virtual directory hierarchy if that is appropriate. When checking file names, obtain the full name of the file by using the System.IO.Path.GetFullPath
method. File Paths
If you use MapPath
to map a supplied virtual path to a physical path on the server, use the overloaded Request.MapPath
method that accepts a bool
parameter so that you can prevent cross-application mapping. The following code example shows this technique.
string mappedPath = Request.MapPath( inputPath.Text,
// Cross-application mapping attempted
The final false parameter in Request.MapPath() prevents cross-application mapping. This means that a user cannot successfully supply a path that contains ".." to traverse outside of your application's virtual directory hierarchy.