# Path Traversal

**Example 1: Java**

**Vulnerable Code:**

```java
javaCopy codeString fileName = request.getParameter("fileName");
File file = new File("/var/www/html/" + fileName);
```

**Reason for vulnerability:** User input can contain path traversal sequences to access restricted files.

**Fixed Code:**

{% code overflow="wrap" %}

```java
javaCopy codeString fileName = request.getParameter("fileName");
File file = new File("/var/www/html/" + Paths.get(fileName).normalize().toString());
if (!file.getCanonicalPath().startsWith("/var/www/html/")) {
    throw new SecurityException("Invalid file path");
}
```

{% endcode %}

**Reason for fix:** Normalize the file path and check it is within the allowed directory.

**Example 2: Python**

**Vulnerable Code:**

```python
pythonCopy code@app.route('/read_file')
def read_file():
    file_name = request.args.get('file_name')
    with open('/var/www/html/' + file_name, 'r') as f:
        return f.read()
```

**Reason for vulnerability:** User input can contain path traversal sequences to access restricted files.

**Fixed Code:**

```python
pythonCopy code@app.route('/read_file')
def read_file():
    file_name = request.args.get('file_name')
    file_path = os.path.join('/var/www/html/', os.path.normpath(file_name))
    if not file_path.startswith('/var/www/html/'):
        abort(403)
    with open(file_path, 'r') as f:
        return f.read()
```

**Reason for fix:** Normalize the file path and check it is within the allowed directory.

***

### Python Example

#### Vulnerable Code:

```python
pythonCopyfrom flask import Flask, request, send_file

app = Flask(__name__)

@app.route('/get-file')
def get_file():
    filename = request.args.get('filename')
    return send_file('/var/www/files/' + filename)
```

#### Reason for Vulnerability:

This code allows an attacker to access files outside the intended directory using path traversal sequences.

#### Fixed Code:

```python
pythonCopyfrom flask import Flask, request, send_file, abort
import os

app = Flask(__name__)

ALLOWED_DIRECTORY = '/var/www/files'

@app.route('/get-file')
def get_file():
    filename = request.args.get('filename')
    if '..' in filename or filename.startswith('/'):
        abort(400)
    
    file_path = os.path.join(ALLOWED_DIRECTORY, filename)
    if not os.path.abspath(file_path).startswith(ALLOWED_DIRECTORY):
        abort(400)
    
    if os.path.isfile(file_path):
        return send_file(file_path)
    else:
        abort(404)
```

#### Reason for Fix:

The fixed code validates the filename, uses `os.path.join()`, and checks if the resulting path is within the allowed directory.

***

### Java Example

#### Vulnerable Code:

```java
javaCopyimport java.io.File;
import java.nio.file.Files;

@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam String filename) throws IOException {
    File file = new File("/var/www/files/" + filename);
    byte[] content = Files.readAllBytes(file.toPath());
    return ResponseEntity.ok()
            .contentLength(content.length)
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(new ByteArrayResource(content));
}
```

#### Reason for Vulnerability:

This code allows an attacker to access files outside the intended directory using path traversal sequences.

#### Fixed Code:

```java
javaCopyimport org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.nio.file.Path;
import java.nio.file.Paths;

@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam String filename) throws IOException {
    Path basePath = Paths.get("/var/www/files").toAbsolutePath().normalize();
    Path filePath = basePath.resolve(filename).normalize();
    
    if (!filePath.startsWith(basePath)) {
        throw new SecurityException("Access to file is not allowed");
    }
    
    Resource resource = new UrlResource(filePath.toUri());
    if (!resource.exists()) {
        throw new FileNotFoundException("File not found: " + filename);
    }
    
    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
}
```

#### Reason for Fix:

The fixed code normalizes paths and checks if the resulting path is within the allowed directory to prevent path traversal.

### C# Example

#### Vulnerable Code:

```csharp
csharpCopyusing System.IO;
using Microsoft.AspNetCore.Mvc;

public class FileController : Controller
{
    [HttpGet("file")]
    public IActionResult GetFile(string filename)
    {
        var path = Path.Combine("C:\\files", filename);
        var fileBytes = System.IO.File.ReadAllBytes(path);
        return File(fileBytes, "application/octet-stream", filename);
    }
}
```

#### Reason for Vulnerability:

This code allows an attacker to access files outside the intended directory using path traversal sequences.

#### Fixed Code:

```csharp
csharpCopyusing System.IO;
using Microsoft.AspNetCore.Mvc;

public class FileController : Controller
{
    private readonly string _baseDirectory = Path.GetFullPath("C:\\files");

    [HttpGet("file")]
    public IActionResult GetFile(string filename)
    {
        if (string.IsNullOrEmpty(filename) || filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
        {
            return BadRequest("Invalid filename");
        }

        var fullPath = Path.GetFullPath(Path.Combine(_baseDirectory, filename));

        if (!fullPath.StartsWith(_baseDirectory))
        {
            return BadRequest("Access to file is not allowed");
        }

        if (!System.IO.File.Exists(fullPath))
        {
            return NotFound();
        }

        var fileBytes = System.IO.File.ReadAllBytes(fullPath);
        return File(fileBytes, "application/octet-stream", filename);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://playbook.sidthoviti.com/devsecops/secure-coding/code-review-examples/path-traversal.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
