What techniques should be used if building UNC paths dynamically, such that to constrain them to a particular root path.
string root = @"\\Blah\Share\YouStayHere\";
//pretend second string is from a query string a user could manipulate
string path = @"\\Blah\Share\YouStayHere\" + @"..\..\TresspassingQueryString";
if( ! SomeValidation(root, path) ) { throw new Exception("you dirty bastard"...
Granted this should probably be managed with permissions, but maybe the other directory is accessible in the context of another asp page within the same application so permissions wouldn’t be an option.
I know the Request.MapPath can be used to keep access within the application’s directory, but this is a share outside the virtual path of the .NET application.
I was hoping to use Path.Combine to resolve the path and then check to make sure that pathCombined begins with root, but Path.Combine will keep the ….\
Additionally, I imagine there might be other types of injections that someone could do in this situation, so I was hoping for something more generic than just doing a regex for “..\” tokens.
Use
System.IO.Path.GetFullPathto get the combined path with all the\..\removed.Then check that the path still starts with the expected prefix.
You should put this in an exception handler (if an exception would cause a problem);
GetFullPathwill access the filesystem (for paths that exist) and if your nefarious client crafts a path that points at an inaccessible folder you’ll get an exception.