flawopen.com/path-traversal/Csharp
How Path.Combine discards root paths in C#, and how to verify boundaries using Path.GetFullPath and StringComparison.OrdinalIgnoreCase.
Stellen Sie sich ein Hotelschloss vor, das eigentlich nur Zimmer im zweiten Stock öffnen soll. Wenn ein Gast am Tastenfeld '../../master-safe' eingibt, verlässt das Schloss den Flur und öffnet den Haupttresor des Hotelmanagers.
Web Application SecurityCWE-918 betroffen ist.CWE-918Defense-in-DepthEin Endpunkt akzeptiert Dateinamen oder Ressourcenbezeichner direkt über einen HTTP-Anfrageparameter.
Der Angreifer schleust relative Pfadsequenzen wie '../', '..%2f' oder absolute Pfadüberschreibungen ein.
Das Backend verbindet die Eingabe mit dem Basispfad, ohne kanonische Pfade aufzulösen oder Grenzen zu prüfen.
Das System öffnet und übermittelt vertrauliche Systemdateien (z. B. /etc/passwd oder Konfigurationsgeheimnisse).
// 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");
}
}
Path.Combine().Path.GetFullPath() to resolve traversal dots.