flawopen.com/path-traversal/Csharp

● CWE-918 · Высокий
Исследования · FlawOpen

Анализ уязвимости: Path Traversal in C#

How Path.Combine discards root paths in C#, and how to verify boundaries using Path.GetFullPath and StringComparison.OrdinalIgnoreCase.

💡 Простыми словами (ELI5)

Представьте электронный замок в отеле, запрограммированный открывать только номера на втором этаже. Если гость вводит на панели '../../master-safe', уязвимый замок выходит в коридор и открывает главный сейф управляющего.

Ключевые понятия и термины

Web Application Security
Технический термин (Web Application Security): Core architecture component affected by CWE-918.
CWE-918
Технический термин (CWE-918): Standard Common Weakness Enumeration classification for path-traversal-csharp.
Defense-in-Depth
Технический термин (Defense-in-Depth): Multi-layered engineering verification and runtime boundary isolation.

Пошаговый сценарий атаки

Step 1

Передача пути к файлу клиентом

Конечная точка принимает имя файла или путь к документу через параметр HTTP-запроса.

Step 2

Внедрение последовательностей обхода каталогов

Злоумышленник передает последовательности '../', '..%2f' или абсолютные пути для выхода из базового каталога.

Step 3

Преодоление границ файловой системы

Бэкенд конкатенирует путь без канонизации и проверки того, что результирующий путь находится внутри базовой папки.

Step 4

Несанкционированное чтение системных файлов

Сервер считывает и передает клиенту конфиденциальные файлы операционной системы (например, /etc/passwd).

Исходный код: Уязвимый vs Защищённый вариант

✕ УЯЗВИМАЯ РЕАЛИЗАЦИЯ
// VULNERABLE: Path.Combine discards baseFolder if userInput has a leading slash
using System.IO;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase {
    private readonly string _baseFolder = @"C:\App\Storage\Uploads";

    [HttpGet("download")]
    public IActionResult Download([FromQuery] string file) {
        // If file is "\Windows\System32\cmd.exe", basePath is discarded!
        // If file is "..\..\App.config", it breaks out of the folder
        string targetPath = Path.Combine(_baseFolder, file);

        if (!System.IO.File.Exists(targetPath)) return NotFound();
        return PhysicalFile(targetPath, "application/octet-stream");
    }
}
✓ БЕЗОПАСНЫЙ ИСПРАВЛЕННЫЙ ВАРИАНТ
// HARDENED: Canonicalize path and assert directory prefix containment
using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase {
    private readonly string _baseFolder;

    public FileController() {
        _baseFolder = Path.GetFullPath(@"C:\App\Storage\Uploads");
    }

    [HttpGet("download")]
    public IActionResult Download([FromQuery] string file) {
        if (string.IsNullOrWhiteSpace(file)) return BadRequest("Invalid filename");

        // 1. Strip leading slashes to prevent Path.Combine root discard
        string cleanName = file.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

        // 2. Resolve canonical full path
        string fullPath = Path.GetFullPath(Path.Combine(_baseFolder, cleanName));

        // 3. Strict boundary containment check with DirectorySeparatorChar
        string safePrefix = _baseFolder.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
        if (!fullPath.StartsWith(safePrefix, StringComparison.OrdinalIgnoreCase)) {
            return Forbid("Path traversal attempt detected");
        }

        if (!System.IO.File.Exists(fullPath)) return NotFound();
        return PhysicalFile(fullPath, "application/octet-stream");
    }
}

Чек-лист по защите системы для инженеров

References