Path Traversal High

The application dynamically constructs file or path information. If the path information comes from user input, it could be abused to read sensitive files, access other users data, or aid in exploitation to gain further system access.

Detector ID
csharp/path-traversal@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1public static byte[] PathTraversalNoncompliant(string filename)
2{
3    if (string.IsNullOrEmpty(filename)) 
4    {   
5        throw new ArgumentNullException("error"); 
6    }
7    string filepath = Path.Combine("/pathToMyImage/images/", filename); 
8    // Noncompliant: Reading data from a file without sanitization.
9    return File.ReadAllBytes(filepath);
10}

Compliant example

1public static byte[] PathTraversalCompliant(string filename)
2{
3    if (string.IsNullOrEmpty(filename)) 
4    {   
5        throw new ArgumentNullException("error"); 
6    }
7    filename = Path.GetFileName(filename);
8    // Compliant: `Path.GetFileName` used for sanitization.
9    string filepath = Path.Combine("/pathToMyImage/images/", filename); 
10    return File.ReadAllBytes(filepath);
11}