Skip to content

Java: false negative in java/path-injection when prefix and .. checks apply to different values #23281

In review

Description

@wildoranges

Description of the issue

In java/path-injection, the trusted-prefix check and the .. check that together sanitize a path do not have to apply to the same value. dotDotCheckGuard is documented as a guard that "considers a path safe because it is checked for .. components, having previously been checked for a trusted prefix", but it only requires that some prefix check controls the .. check, not that it checks the same value. So an unrelated startsWith, for example routing on request.getRequestURI(), turns a ..-only check into a complete sanitizer, although an absolute path contains no .. and Path.resolve returns it unchanged.

Affected sanitizer

  • dotDotCheckGuard relates the .. check to the sanitized expression, but its other condition, previousGuard.(AllowedPrefixGuard).controls(g.getBasicBlock(), true), does not relate previousGuard to it. allowedPrefixGuard and blockListGuard have the same shape in the other direction.
  • The library test says "dot dot check by itself is not enough", and all its safe cases check the same value in both guards, as does the example in the comment of pathTraversalGuard.

Steps to reproduce

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {
    static final Path BASE = Paths.get(System.getProperty("files.dir", "/srv/app/files"));

    // Only a `..` check: reported by java/path-injection.
    void downloadA(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        if (name.contains("..")) {
            resp.sendError(400);
            return;
        }
        resp.getOutputStream().write(Files.readAllBytes(BASE.resolve(name)));
    }

    // Same code, plus a routing check on the request URI: not reported.
    void downloadB(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if (!req.getRequestURI().startsWith("/download/")) {
            resp.sendError(404);
            return;
        }
        String name = req.getParameter("name");
        if (name.contains("..")) {
            resp.sendError(400);
            return;
        }
        resp.getOutputStream().write(Files.readAllBytes(BASE.resolve(name)));
    }

    // Prefix check on `name`, `..` check on the request URI: not reported.
    void downloadC(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        if (!req.getRequestURI().contains("..") && name.startsWith(BASE + "/")) {
            resp.getOutputStream().write(Files.readAllBytes(Paths.get(name)));
            return;
        }
        resp.sendError(400);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if (req.getServletPath().equals("/a")) downloadA(req, resp);
        else if (req.getServletPath().equals("/c")) downloadC(req, resp);
        else downloadB(req, resp);
    }
}

With CodeQL 2.27.6 (database built with javac against tomcat-embed-core), TaintedPath.ql and java-security-extended.qls report only line 19 (downloadA). Line 33 (downloadB) differs from it only by the routing check at lines 24-27 and is not reported; line 40 (downloadC), where the .. check is on the request URI, is not reported either.

Served unchanged with embedded Tomcat, with files.dir set to a temporary directory and outside.txt next to it:

Request Response
/download/file?name=../outside.txt 400
/download/file?name=<tmp>/outside.txt (absolute path) 200, the content of outside.txt
/c?name=<files.dir>/../../../outside.txt 200, the content of outside.txt

Checks on two different values combined like this also occur in well-known code. In TestArtifactResource.java of theonedev/onedev, reportName is checked for .. (line 51) and artifactPath, built from other request path segments, is checked with startsWith (line 75) before Paths.get(artifactPath) (line 83); 2.27.6 treats line 83 as sanitized because of the check on reportName. The code itself is safe (line 69 checks each path segment for .. in a loop) and does not alert either way, as Wicket parameters are not modeled as sources.

Question

Is it intended that the complementary guard in dotDotCheckGuard, allowedPrefixGuard and blockListGuard may check a value unrelated to the sanitized expression? If not, would it be reasonable to require a related value, for example as below?

Possible change

One possible change, against current main: in those three places, also require the complementary guard to check a value connected to the sanitized expression by local taint flow, in either direction.

--- a/java/ql/lib/semmle/code/java/security/PathSanitizer.qll
+++ b/java/ql/lib/semmle/code/java/security/PathSanitizer.qll
@@ -58,6 +58,16 @@ private predicate localTaintFlowToPathGuard(Expr e, PathGuard g) {
   TaintTracking::LocalTaintFlow<anyNode/1, pathGuardNode/1>::hasExprFlow(e, g.getCheckedExpr())
 }
 
+/**
+ * Holds if `e` and the expression checked by `g` are connected by local taint flow,
+ * in either direction, so that `g` checks the same value as the guard on `e`.
+ */
+private predicate checksRelatedValue(Expr e, PathGuard g) {
+  localTaintFlowToPathGuard(e, g)
+  or
+  TaintTracking::LocalTaintFlow<pathGuardNode/1, anyNode/1>::hasExprFlow(g.getCheckedExpr(), e)
+}
+
 private class AllowedPrefixGuard extends PathGuard instanceof MethodCall {
   AllowedPrefixGuard() {
     (isStringPrefixMatch(this) or isPathPrefixMatch(this)) and
@@ -87,7 +97,9 @@ private predicate allowedPrefixGuard(Guard g, Expr e, boolean branch) {
     or
     previousGuard
         .(PathTraversalGuard)
-        .controls(g.getBasicBlock(), previousGuard.(PathTraversalGuard).getBranch())
+        .controls(g.getBasicBlock(), previousGuard.(PathTraversalGuard).getBranch()) and
+    // the `..` check must be on the same value
+    checksRelatedValue(e, previousGuard)
   )
 }
 
@@ -114,6 +126,9 @@ private predicate dotDotCheckGuard(Guard g, Expr e, boolean branch) {
     previousGuard
         .(BlockListGuard)
         .controls(g.getBasicBlock(), previousGuard.(BlockListGuard).getBranch())
+  |
+    // the prefix or block-list check must be on the same value
+    checksRelatedValue(e, previousGuard)
   )
   or
   // `File.getName` strips any directory prefix, returning only the final path
@@ -177,7 +192,9 @@ private predicate blockListGuard(Guard g, Expr e, boolean branch) {
     or
     previousGuard
         .(PathTraversalGuard)
-        .controls(g.getBasicBlock(), previousGuard.(PathTraversalGuard).getBranch())
+        .controls(g.getBasicBlock(), previousGuard.(PathTraversalGuard).getBranch()) and
+    // the `..` check must be on the same value
+    checksRelatedValue(e, previousGuard)
   )
 }
 

With this change, lines 33 and 40 of the example are reported, the onedev line above is no longer treated as sanitized, and the tests in java/ql/test/query-tests/security/ (CWE-022, CWE-552, CWE-441), the experimental CWE-022, CWE-073 and CWE-200 tests and the Java part of java/ql/test/library-tests/pathsanitizer/ still pass with unchanged .expected files (I could not run TestKt.kt, which needs a Kotlin compiler). Some trade-offs:

  • Flow in one direction only is not enough: a .. check on name followed by a prefix check on BASE.resolve(name), or a prefix check on name followed by a .. check on name.trim(), would become new alerts. Tests for such derived values may be worth adding.
  • PathInjectionSanitizer is shared by java/path-injection, java/zipslip, java/unvalidated-url-forward, java/android/unsafe-content-uri-resolution and two experimental queries, so new alerts would appear in all of them where the two checks are on unrelated values.

Environment

  • CodeQL CLI 2.27.6 (codeql/java-queries 1.12.2, codeql/java-all 9.3.6)
  • CodeQL main 2b879ca71d44ac5b9b12df13eead87530ed83ee2 (commit for the links above)
  • OpenJDK 17.0.20.1, Apache Tomcat 9.0.123 (embedded), Linux/amd64

Activity

  1. added
    question
    on Nov 27, 2026
  2. jketema commented on Nov 27, 2026

    @jketema
    Contributor

    Hi @wildoranges,

    Thanks for your report.

  3. added a commit that references this issue on Nov 27, 2026
    a558c62
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions