How to prevent of path traversal in Asp.net core

Sumanth Babu 21 Reputation points
2022-07-20T07:17:41.333+00:00

How to prevent of path traversal in my code below

Var filePath= Path.Combine(contentRootPath, fileName);

using (FileStream stream = System.IO.File.Create(filePath))
{
xxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxx
}

FileInfo file = new FileInfo(filePath);

if (file.Exists) and file.Delete() --> Path traversal attack

Please help to my code . If got let me know

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-07-21T02:20:08.467+00:00

    Hi @Sumanth Babu

    We can process the user's input filename. You can use filePath.Replace("..", "") before using the filePath to access the filesystem.

    Var filePath= Path.Combine(contentRootPath, fileName);  
    filePath = filePath.Replace("..", "");  
    

    If you host your app in IIS, using either one of the RequestFilteringModule or UrlRoutingModule modules in IIS does effectively prevent my path traversal attack, provided the module(s) are fully-enabled.


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Jason

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-07-20T10:01:39.267+00:00

    The answer is the same as your previous post, authorization.

    Move the file outside of the wwwroot and use an action to fetch the file. The user must be authentication and authorized to invoke the HTTP action. There also the general design where the user is only able to access data related to the user's identity, role, or claim.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.