Description
Concatenating request input directly into paths passed to APIs such as File.ReadAllText, File.WriteAllText, or FileStream can allow reads or writes outside the intended directory.
Potential impact
- Exposure of configuration files, secrets, or source code, or arbitrary file writes.
Remediation
Normalize the path and verify that it remains within the base directory. Where possible, accept only filenames on an allow-list.
Examples
Before
csharp
var path = Path.Combine(baseDirectory, filename);
var content = File.ReadAllText(path);
After
csharp
var safeName = Path.GetFileName(filename);
var path = Path.Combine(baseDirectory, safeName);
var content = File.ReadAllText(path);
Explanation:
- Before: User-controlled path components may direct file operations outside the intended directory.
- After:
Path.GetFileNamekeeps only the final filename component. Attackers must not be able to modify the base directory or its files and links. If access must be limited to particular files, also validate the filename against an allow-list.