Fix partial path traversal Java example Again

The original wouldn't compile, and the fix made by #11899 is sub-optimal.
This keeps the entire comparision using the Java `Path` object, which is optimal.

Signed-off-by: Jonathan Leitschuh <Jonathan.Leitschuh@gmail.com>
This commit is contained in:
Jonathan Leitschuh
2023-03-31 11:05:28 -04:00
committed by Jonathan Leitschuh
parent 2b9daed26a
commit e641505361
3 changed files with 8 additions and 7 deletions

View File

@@ -1,7 +1,7 @@
public class PartialPathTraversalBad {
public void example(File dir, File parent) throws IOException {
if (!dir.getCanonicalPath().startsWith(parent.getCanonicalPath())) {
throw new IOException("Invalid directory: " + dir.getCanonicalPath());
throw new IOException("Path traversal attempt: " + dir.getCanonicalPath());
}
}
}

View File

@@ -1,7 +1,9 @@
import java.io.File;
public class PartialPathTraversalGood {
public void example(File dir, File parent) throws IOException {
if (!dir.getCanonicalPath().startsWith(parent.getCanonicalPath() + File.separator)) {
throw new IOException("Invalid directory: " + dir.getCanonicalPath());
if (!dir.toPath().normalize().startsWith(parent.toPath())) {
throw new IOException("Path traversal attempt: " + dir.getCanonicalPath());
}
}
}

View File

@@ -26,10 +26,9 @@ and not just children of <code>parent</code>, which is a security issue.
<p>
In this example, the <code>if</code> statement checks if <code>parent.getCanonicalPath() + File.separator </code>
is a prefix of <code>dir.getCanonicalPath()</code>. Because <code>parent.getCanonicalPath() + File.separator</code> is
indeed slash-terminated, the user supplying <code>dir</code> can only access children of
<code>parent</code>, as desired.
In this example, the <code>if</code> statement checks if <code>parent.toPath()</code>
is a prefix of <code>dir.normalize()</code>. Because <code>Path#startsWith</code> will do the correct check that
<code>dir</code> is ia child children of <code>parent</code>, as desired.
</p>