I know the solid security recommendation of avoiding accepting user input that you then use to choose a path to read/write a file. However, assuming you have a base directory you want to keep within (such as the root of an ftp folder), how do you best ensure that a given user input keeps us within that folder?
For instance,
Path.Combine(_myRootFolder, _myUserInput)
could still take us outside of _myRootFolder. And this could also be dodgy
newPath = Path.Combine(_myRootFolder, _myUserInput)
if (newPath.StartsWith(_myRootFolder))
...
given something like “/back/to/myrootfolder/../../and/out/again” from the user. What are the strategies for this? Am I missing a blindingly obvious .NET method I can use?
Within ASP.NET applications you can use
Server.MapPath(filename)which will throw an exception if the path generated goes outside of your application root.If all you want is a safe file name and you just want all files in there it becomes simpler;
If you’re outside of ASP.NET like you indicate then you could use
Path.GetFullPath.Or you call Path.GetFullPath and then check the start of it matches the directory you want locked to.