开发者

Make sure path doesn't go up a level

I want to make sure relativePath doesn't go up a folder past basePath. Is there any reliable way to detect this?

string basePath = "/myfolder/";
string relativePath;

// Invalid
relativePath = "../foo";
relativePath = "subfolder/../../bar";

// Valid, but if too hard this can also be invalid
relativePath = "subfolder/../subfolder2";

// Valid
relativePath = "subfolder/another..folder/";
relativePath = "subfolder/..anotherFolder/";

// There may be ways to circumvent that I haven't thought of...
// Maybe some of these would work
relativePath = " ../";
relativePath = ".. /";

// fullPath should not be above basePath
string fullPath = basePath + relativePath;

I'm thinking something like the following could work

Path.GetFullPath(basePath + relat开发者_C百科ivePath).StartsWith(basePath)

But I couldn't find a VirtualPathUtility.GetFullPath() or something similar. I could disallow ../ anywhere in the string, but there may be a way to circumvent that with strange spacing, special characters, etc.


You can use Path.GetFullPath to convert all your paths to absolute paths, and then just compare the strings. That is:

string basePath = "/myFolder/";
string relativePath = "whatever_user_inputs";

string basePathRooted = Path.GetFullPath(basePath);
string relativePathRooted = Path.GetFullPath(relativePath);

if (!relativePathRooted.StartsWith(basePathRooted))
     //Fail
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜