How to determine if a relative path is outside a given path

I have the following script (C #, WinForms). I have some kind of project file that is saved in some directory. The project file contains a link to another file. This link is relative to where the project file was saved.

Example: a project file is saved in the c: \ projects \ project.xyz directory. Another file is referenced as "\ someotherdir \ file.abc".

This works fine, but it could be that someone tried to manipulate this relative path with something like ".. \ Windows \ System32 \ file.abc". Therefore, it is necessary to check whether the relative path is outside the path where the project is saved (this is a specific requirement that all referenced files are inside the path to the project).

How to identify this scenario?

+3
source share
3 answers

You can try using the following extension method:

public static bool IsChildOf(this string path, string parentPath)
{
    return Path.GetFullPath(path).StartsWith(Path.GetFullPath(parentPath),
           StringComparison.InvariantCultureIgnoreCase);
}
+4
source

Not very pretty, but I think it should work.

if (System.IO.Path.GetFullPath(path).IndexOf(projectPath, StringComparison.CurrentCultureIgnoreCase) == -1)
{
  // naughty
}

Edited as a good global citizen.

+2
source

Windows posix: ln -s c:\windows\system32\mshtml.dll c:\projects\project.xyz\innocent.txt. c:\projects\project.xyz\innocent.txt, c:\windows\system32\mshtml.dll. System.IO.Path.GetFullPath()?

POSIX . ( ), , , , . " ", , .

Windows . .

You can solve this problem with file system permissions: create a new user for your application. Grant access rights to your project path. Do not grant users (or all or any groups that are a member of the user) privileges to anyone else in any file system. Let the Microsoft kernel team solve your problem for you.

+1
source

Source: https://habr.com/ru/post/1752060/


All Articles