Skip to content

Resolve vulnerability: Relative Path Traversal

MR created from vulnerability: Relative Path Traversal

AI GENERATED FIX

The suggested code changes were generated by GitLab Duo Vulnerability Resolution, an AI feature. Use this feature with caution. Before you run a pipeline or apply the code changes, carefully review and test them, to ensure that they solve the vulnerability.

The large language model that generated the suggested code changes was provided with the entire file that contains the vulnerable lines of code. It is not aware of any functionality outside of this context.

Please see our documentation for more information about this feature.

Description:

Detected user input controlling a file path. An attacker could control the location of this file, to include going backwards in the directory with '../'.

To address this, ensure that user-controlled variables in file paths are sanitized. You may also consider using a utility method such as org.apache.commons.io.FilenameUtils.getName(...) to only retrieve the file name from the path.

Example of using org.apache.commons.io.FilenameUtils.getName(...) to only retrieve the file name from the path

String fileName = org.apache.commons.io.FilenameUtils.getName(userControlledInput);
File file = new File("/path/to/directory/" + fileName);

Analysis:

根据漏洞报告和源代码分析,这是一个真实的路径遍历漏洞(CWE-23),属于OWASP A01:2021和A5:2017中的"Broken Access Control"类别。

漏洞点在于直接使用用户输入的file参数创建File对象,攻击者可以通过构造包含../的相对路径访问系统上的任意文件。虽然代码中有对脚本内容的白名单检查(ALLOWED_EXPRESSIONS),但对文件路径没有进行任何验证或清理。

需要修复的点包括:

  1. 使用FilenameUtils.getName()清理文件名
  2. 限制文件只能从特定目录读取
  3. 添加路径规范化检查

这不是一个误报(false positive),需要修复。

Summary:

  1. 报告的漏洞:相对路径遍历漏洞(CWE-23),攻击者可以通过构造包含../的路径访问系统任意文件。

  2. 修复方案

    • 使用FilenameUtils.getName()提取安全的文件名
    • 将文件限制在特定目录(/safe/directory/path/)下
    • 添加规范化路径检查,防止目录遍历
    • 对每个使用用户输入文件路径的地方都进行了相同处理
  3. 安全改进

    String safeFileName = FilenameUtils.getName(file);
    File safeFile = new File("/safe/directory/path/" + safeFileName);
    if (!safeFile.getCanonicalPath().startsWith("/safe/directory/path")) {
        throw new SecurityException("非法文件路径");
    }

    这种修复方式既防止了路径遍历,又保持了原有功能,同时通过规范化路径检查提供了额外保护层。

Identifiers:

  • A5:2017 - Broken Access Control
  • java_traversal_rule-RelativePathTraversal
  • A01:2021 - Broken Access Control
  • CWE-23

合并请求报告

加载中