How to make sure file path is safe in C #?

I have an asp.net mvc application with a route that allows users to request files that are stored outside the web application directory.

I will simplify the script, just tell you that it will ultimately limit them to a safe directory to which they have full access.

For example:

If the user (whose identifier is 100) requests:

http://mysite.com/Read/Image/Cool.png

then my application will add "Cool.png" to "C: \ ImageRepository \ Users \ 100 \" and write these bytes to the response. The workflow has access to this path, but the anonymous user does not. I already have this job.

But some malicious user will be able to request something like:

http://mysite.com/Read/Image/..\101\Cool.png

and allow

"C:\ImageRepository\Customers\101\Cool.png"

(another user picture ?!)

- ? , , ?

+3
5

var fileName = System.IO.Path.GetFileName(userFileName);
var targetPath = System.IO.Path.Combine(userDirectory, fileName);

, .

+4

, , ?

. "C:\ImageRepository\Customers\100\"

.

0

, ( auth), , Active Directory , , .

, , . , , , REAL .

Protecting against canalocalization is a complex business, and it’s dangerous to try to refute a potential attacker.

0
source

Using Request.MapPath overload is one way to verify this:

try
{
  string mappedPath = Request.MapPath( inputPath.Text,                                  Request.ApplicationPath, false);
}
catch (HttpException)
{
  // do exception handling
}

You can also blow up a string and split it into slashes, and also check if the username matches.

0
source

You can also include a subdirectory in a path that you can use:

string SafeCombine(string basePath, string path)
{
    string testPath = Path.GetFullPath(Path.Combine(basePath, path));
    if (testPath.startsWith(basePath))
        return testPath;
    throw new InvalidOperationException();
}
0
source

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


All Articles