Partial path traversal vulnerability¶
ID: java/partial-path-traversalKind: problemSecurity severity: 9.3Severity: errorPrecision: mediumTags: - security - external/cwe/cwe-023Query suites: - java-security-extended.qls - java-security-and-quality.qls
Click to see the query in the CodeQL repository
A common way to check that a user-supplied pathSUBDIR falls inside a directoryDIR is to usegetCanonicalPath() to remove any path-traversal elements and then check thatDIR is a prefix. However, ifDIR is not slash-terminated, this can unexpectedly allow access to siblings ofDIR.
See alsojava/partial-path-traversal-from-remote, which is similar to this query but only flags instances with evidence of remote exploitability.
Recommendation¶
If the user should only access items within a certain directoryDIR, ensure thatDIR is slash-terminated before checking thatDIR is a prefix of the user-provided path,SUBDIR. Note, Java’sgetCanonicalPath() returns anon-slash-terminated path string, so a slash must be added toDIR if that method is used.
Example¶
In this example, theif statement checks ifparent.getCanonicalPath() is a prefix ofdir.getCanonicalPath(). However,parent.getCanonicalPath() is not slash-terminated. This means that users that supplydir may be also allowed to access siblings ofparent and not just children ofparent, which is a security issue.
publicclassPartialPathTraversalBad{publicvoidexample(Filedir,Fileparent)throwsIOException{// BAD: dir.getCanonicalPath() not slash-terminatedif(!dir.getCanonicalPath().startsWith(parent.getCanonicalPath())){thrownewIOException("Path traversal attempt: "+dir.getCanonicalPath());}}}
In this example, theif statement checks ifparent.toPath() is a prefix ofdir.normalize(). BecausePath#startsWith does the correct check thatdir is a child ofparent, users will not be able to access siblings ofparent, as desired.
importjava.io.File;publicclassPartialPathTraversalGood{publicvoidexample(Filedir,Fileparent)throwsIOException{// GOOD: Check if dir.Path() is normalisedif(!dir.toPath().normalize().startsWith(parent.toPath())){thrownewIOException("Path traversal attempt: "+dir.getCanonicalPath());}}}
References¶
OWASP:Partial Path Traversal.
CVE-2022-23457: ESAPI Vulnerability Report.
Common Weakness Enumeration:CWE-23.