2023-03-02 18:22:24 +01:00

80 lines
2.1 KiB
Plaintext

=== How to fix it in .NET
:canonicalization_function: System.IO.Path.GetFullPath
include::../../common/fix/code-rationale.adoc[]
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public class ExampleController : Controller
{
private static string TargetDirectory = "/path/to/target/directory/";
public void Example(string filename)
{
string path = Path.Combine(TargetDirectory, filename);
System.IO.File.Delete(path);
}
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
public class ExampleController : Controller
{
private static string TargetDirectory = "/path/to/target/directory/";
public void Example(string filename)
{
string path = Path.Combine(TargetDirectory, filename);
string canonicalDestinationPath = Path.GetFullPath(path);
if (canonicalDestinationPath.StartsWith(TargetDirectory, StringComparison.Ordinal))
{
System.IO.File.Delete(canonicalDestinationPath);
}
}
}
----
=== How does this work?
include::../../common/fix/how-does-this-work.adoc[]
=== Pitfalls
include::../../common/pitfalls/partial-path-traversal.adoc[]
For example, the following code is vulnerable to partial path injection. Note
that the string `TargetDirectory` does not end with a path separator:
[source, csharp]
----
private static string TargetDirectory = "/Users/John";
public void Example(string filename)
{
string canonicalDestinationPath = Path.GetFullPath(filename);
if (canonicalDestinationPath.StartsWith(TargetDirectory, StringComparison.Ordinal))
{
System.IO.File.Delete(canonicalDestinationPath);
}
}
----
This check can be bypassed because `"/Users/Johnny/file".startsWith("/Users/John")`
returns `true`. Thus, for validation, `"/Users/John"` should actually be
`"/Users/John/"`.
**Warning**: Some functions remove the terminating path separator in their
return value. +
The validation code should be tested to ensure that it cannot be impacted by this
issue.
https://github.com/aws/aws-sdk-java/security/advisories/GHSA-c28r-hw5m-5gv3[Here is a real-life example of this vulnerability.]