Skip to content

Commit e641505

Browse files
committed
Fix partial path traversal Java example Again
The original wouldn't compile, and the fix made by github#11899 is sub-optimal. This keeps the entire comparision using the Java `Path` object, which is optimal. Signed-off-by: Jonathan Leitschuh <[email protected]>
1 parent 2b9daed commit e641505

File tree

3 files changed

+8
-7
lines changed

3 files changed

+8
-7
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
public class PartialPathTraversalBad {
22
public void example(File dir, File parent) throws IOException {
33
if (!dir.getCanonicalPath().startsWith(parent.getCanonicalPath())) {
4-
throw new IOException("Invalid directory: " + dir.getCanonicalPath());
4+
throw new IOException("Path traversal attempt: " + dir.getCanonicalPath());
55
}
66
}
77
}
Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import java.io.File;
2+
13
public class PartialPathTraversalGood {
24
public void example(File dir, File parent) throws IOException {
3-
if (!dir.getCanonicalPath().startsWith(parent.getCanonicalPath() + File.separator)) {
4-
throw new IOException("Invalid directory: " + dir.getCanonicalPath());
5+
if (!dir.toPath().normalize().startsWith(parent.toPath())) {
6+
throw new IOException("Path traversal attempt: " + dir.getCanonicalPath());
57
}
68
}
79
}

java/ql/src/Security/CWE/CWE-023/PartialPathTraversalRemainder.inc.qhelp

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,9 @@ and not just children of <code>parent</code>, which is a security issue.
2626

2727
<p>
2828

29-
In this example, the <code>if</code> statement checks if <code>parent.getCanonicalPath() + File.separator </code>
30-
is a prefix of <code>dir.getCanonicalPath()</code>. Because <code>parent.getCanonicalPath() + File.separator</code> is
31-
indeed slash-terminated, the user supplying <code>dir</code> can only access children of
32-
<code>parent</code>, as desired.
29+
In this example, the <code>if</code> statement checks if <code>parent.toPath()</code>
30+
is a prefix of <code>dir.normalize()</code>. Because <code>Path#startsWith</code> will do the correct check that
31+
<code>dir</code> is ia child children of <code>parent</code>, as desired.
3332

3433
</p>
3534

0 commit comments

Comments
 (0)