CodeQL 文档

远程部分路径遍历漏洞

ID: java/partial-path-traversal-from-remote
Kind: path-problem
Security severity: 9.3
Severity: error
Precision: high
Tags:
   - security
   - external/cwe/cwe-023
Query suites:
   - java-code-scanning.qls
   - java-security-extended.qls
   - java-security-and-quality.qls

单击以在 CodeQL 存储库中查看查询

检查用户提供的路径 SUBDIR 是否位于目录 DIR 内的一种常见方法是使用 getCanonicalPath() 删除任何路径遍历元素,然后检查 DIR 是否为前缀。但是,如果 DIR 没有以斜杠结尾,则这可能会意外允许访问 DIR 的同级目录。

另请参见 java/partial-path-traversal,它与此查询类似,但还可能标记部分路径遍历漏洞的非远程可利用实例。

建议

如果用户只能访问特定目录 DIR 中的项目,请确保在检查 DIR 是否为用户提供的路径 SUBDIR 的前缀之前,DIR 以斜杠结尾。请注意,Java 的 getCanonicalPath() 返回一个以斜杠结尾的路径字符串,因此如果使用该方法,则必须向 DIR 添加一个斜杠。

示例

在此示例中,if 语句检查 parent.getCanonicalPath() 是否是 dir.getCanonicalPath() 的前缀。但是,parent.getCanonicalPath() 没有以斜杠结尾。这意味着提供 dir 的用户可能还可以访问 parent 的同级,而不仅仅是 parent 的子级,这是一个安全问题。

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

在此示例中,if 语句检查 parent.toPath() 是否是 dir.normalize() 的前缀。因为 Path#startsWith 执行正确的检查,即 dirparent 的子级,因此用户将无法访问 parent 的同级,正如所期望的那样。

import java.io.File;

public class PartialPathTraversalGood {
    public void example(File dir, File parent) throws IOException {
        if (!dir.toPath().normalize().startsWith(parent.toPath())) {
            throw new IOException("Path traversal attempt: " + dir.getCanonicalPath());
        }
    }
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私