Path Traversal Vulnerability in ASP.NET CORE

This post explores how Path Traversal or Directory Traversal can occur in ASP.NET Core applications, provides real-world code examples, and outlines best practices to prevent it.

Path Traversal Vulnerability in ASP.NET CORE

Getting Started

A Path Traversal Vulnerability can occur when user input is used to construct file paths without proper validation or sanitization in ASP.NET Core.

This allows attackers to access files and directories that are outside the intended directory structure, potentially exposing sensitive system files or application data.

What is Path Traversal Vulnerability?

Path Traversal Vulnerability or Directory Traversal is a security flaw that allows an attacker to access files and directories that are outside the intended directory structure of an application.

What Causes It?
This vulnerability typically occurs when:
  • An application accepts user input to specify file names or paths.
  • The input is not properly validated or sanitized.
  • The attacker manipulates the input using special path elements like ../ (dot-dot-slash) to traverse directories.

Impact
Depending on the vulnerability, an attacker might:
  • Read sensitive system files appsettings.json, etc.
  • View source code
  • Access credentials or configuration secrets
  • Potentially write files (if combined with file upload or write access)

How It Works
Let's say you have a file download endpoint like this:
 [HttpGet("download")]  
 public IActionResult DownloadFile(string filename)  
 {  
   var path = Path.Combine("wwwroot/files", filename);  
   if (!System.IO.File.Exists(path))  
   {  
     return NotFound();  
   }  
   var bytes = System.IO.File.ReadAllBytes(path);  
   return File(bytes, "application/octet-stream", filename);  
 }  
Directory Traversal Attack Example
If the user input is not sanitized, an attacker can request:
 GET /download?filename=../../../appsettings.json  
Which resolves to:
 wwwroot/files/../../../appsettings.json  
Effectively allowing them to traverse directories and read files outside wwwroot/files.

How to Prevent Directory Traversal Attack

To prevent directory traversal attacks in ASP.NET Core, you need to ensure that any file paths constructed or handled by your application do not allow attackers to access files outside the intended directory structure, e.g., using ../ sequences.

Best Practices to Prevent Directory Traversal
  1. Never Trust User Input for File Paths: Don’t allow user input to directly determine file system paths. Validate or sanitize input to prevent path manipulation.
     //Don't do this  
     string filePath = Path.Combine("wwwroot/uploads", userInput);  
    
  2. Normalize and validate the path: Compare the resolved absolute path with your intended root directory to ensure no traversal is happening.
     string rootPath = Path.GetFullPath("wwwroot/uploads");  
     string fullPath = Path.GetFullPath(Path.Combine(rootPath, userInput));  
     if (!fullPath.StartsWith(rootPath))  
     {  
       // Potential directory traversal attack  
       throw new UnauthorizedAccessException("Access denied.");  
     }  
     // Proceed to access file  
    
  3. Restrict Allowed File Names or Extensions: Use a whitelist for allowed filenames or extensions if users are allowed to upload or request files.
     var allowedExtensions = new[] { ".txt", ".jpg", ".png" };  
     var extension = Path.GetExtension(userInput);  
     if (!allowedExtensions.Contains(extension))  
     {  
       throw new InvalidOperationException("File type not allowed.");  
     }  
    
  4. Use ASP.NET Core Static Files Middleware Securely: If serving files from a directory (like wwwroot), configure it safely.
     app.UseStaticFiles(new StaticFileOptions  
     {  
       FileProvider = new PhysicalFileProvider(  
         Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/HelpDocuments")),  
       RequestPath = "/files"  
     });  
    
  5. Use Content-Disposition Headers Carefully If allowing file downloads, ensure you don’t echo untrusted input directly in Content-Disposition headers (may leak paths or mislead users).
     [HttpGet("download")]  
     public IActionResult DownloadFile(string filename)  
     {  
       var rootPath = Path.GetFullPath("wwwroot/uploads");  
       var fullPath = Path.GetFullPath(Path.Combine(rootPath, filename));  
       if (!fullPath.StartsWith(rootPath))  
       {  
         return Forbid(); // Directory traversal attempt  
       }  
       if (!System.IO.File.Exists(fullPath))  
       {  
         return NotFound();  
       }  
       var fileBytes = System.IO.File.ReadAllBytes(fullPath);  
       return File(fileBytes, "application/octet-stream", Path.GetFileName(fullPath));  
     }  
    
  6. Avoid Serving Files Based on Query Parameters: Serving files directly based on query strings or URL segments without sanitization is dangerous.

Path Traversal or Directory Traversal Vulnerability is a serious web application vulnerability that allows an attacker to access files and directories stored outside the intended directory. In the context of ASP.NET Core, if not properly handled, this vulnerability can be exploited to read sensitive files such as configuration files, source code, or even system files.

Summary

Path Traversal or Directory Traversal is a preventable yet dangerous vulnerability that can lead to sensitive data leaks in ASP.NET Core applications. Web developers must treat file paths as untrusted input and always validate and sanitize them.

Thanks

Kailash Chandra Behera

I am an IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال