From 5bde17eaaeaf22a0cda9962c22d3379fbaecf00f Mon Sep 17 00:00:00 2001 From: nimK1987 Date: Mon, 11 Aug 2025 14:11:30 +0300 Subject: [PATCH] Add file path manipulations rule --- secure-dev-c-sharp.mdc | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/secure-dev-c-sharp.mdc b/secure-dev-c-sharp.mdc index e4021d8..3d9e193 100644 --- a/secure-dev-c-sharp.mdc +++ b/secure-dev-c-sharp.mdc @@ -76,4 +76,31 @@ For file validation, tilize MIME Type Validation libraries, like `MimeDetective` PropertyNameCaseInsensitive = true }; return JsonSerializer.Deserialize(json, options) // Type-safe - ``` \ No newline at end of file + ``` + +## 7. Validate and Normalize File Paths +- **Rule:** To prevent file path manipulations, normalize and validate input file paths to prevent access to sensitive files. + +- **Unsafe:** + ```cs + string basePath = "/home/files/"; + // Dangerous - filename can contain "../../etc/passwd" + string fullPath = Path.Combine(basePath, filename); + string content = System.IO.File.ReadAllText(fullPath); + ``` +- **Safe:** + ```cs + string basePath = "/home/files/"; + // Absolute path is resolved and normalized + string fullPath = Path.GetFullPath(Path.Combine(basePath, filename)); + // Ensure the resolved path starts with the base path + if (!fullPath.StartsWith(basePath, StringComparison.Ordinal)) + { + return BadRequest("Invalid file path."); + } + if (!System.IO.File.Exists(fullPath)) + { + return NotFound(); + } + string content = System.IO.File.ReadAllText(fullPath); + ```