Path Traversal

C# path traversal

Description

Limit paths passed to File.ReadAllText, File.WriteAllText, or FileStream to the files the server intends to expose.

Potential impact

Depending on the service account’s filesystem permissions, callers may read or overwrite configuration, secrets, or source code.

Remediation

Choose files from an allow-list in a server-managed directory. If you extract a name from input, reject empty names, ., and .., and verify that the actual target is inside the base. Protect the directory from file or link replacement.

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);

Path.GetFileName extracts the last component using the platform’s path rules, and Path.Combine joins it to the base. The example does not check the allow-list or resolve links.

References