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)。漏洞报告中指出用户输入控制了文件路径,攻击者可以通过构造包含"../"的路径来访问系统上的任意文件。

在源代码中,shell.parse(new File(file))直接使用了用户输入的file参数来创建File对象,没有进行任何路径校验或清理。这确实存在安全风险,攻击者可以通过构造恶意路径访问系统敏感文件。

虽然代码中有一个ALLOWED_EXPRESSIONS的白名单检查,但它只用于检查脚本内容,而没有对文件路径进行限制。因此这不是一个误报。

建议的修复方法是使用FilenameUtils.getName()来提取文件名,并限制文件只能从特定目录加载。

Summary:

  1. 报告的漏洞:相对路径遍历漏洞(CWE-23),用户输入直接用于文件路径操作,可能导致任意文件访问。

  2. 修复方案

    • 使用org.apache.commons.io.FilenameUtils.getName()提取安全的文件名
    • 将文件限制在特定目录下访问("/path/to/safe/directory/")
    • 即使通过白名单检查的代码路径也应用相同的安全措施
  3. 修复效果

    • 防止攻击者使用"../"等路径遍历技术
    • 限制文件只能从指定目录加载
    • 保持原有功能的同时增强了安全性

修复后的代码示例:

String safeFileName = org.apache.commons.io.FilenameUtils.getName(file);
File safeFile = new File("/path/to/safe/directory/" + safeFileName);
shell.parse(safeFile);

Identifiers:

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

合并请求报告

加载中