Resolve vulnerability: Relative Path Traversal

Vulnerability finding detected in merge request: QA test - merge request (!1) • Unassigned

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);

Summary:

漏洞总结

1. 报告的漏洞

报告的漏洞是相对路径遍历(Relative Path Traversal, CWE-23),属于 OWASP A01:2021(访问控制失效)类别。攻击者可以通过控制 file 参数使用 ../ 序列遍历目录,访问系统任意位置的文件。

2. 提供的修复

针对所有使用用户输入 file 参数创建 File 对象的地方,应用了 org.apache.commons.io.FilenameUtils.getName() 方法进行修复。该方法会:

  • 去除路径中的目录部分,只保留文件名
  • 自动移除 ../ 等路径遍历序列
  • 防止攻击者通过路径遍历访问敏感文件

修复示例

// 修复前(存在路径遍历漏洞)
shell.evaluate(new File(file));
shell.parse(new File(file));

// 修复后(安全)
String safeFileName = org.apache.commons.io.FilenameUtils.getName(file);
shell.evaluate(new File(safeFileName));
shell.parse(new File(safeFileName));

3. 额外安全考虑

除了路径遍历漏洞外,该代码还存在代码注入(CWE-94)问题。用户输入的 file 路径对应的文件内容会被 Groovy 解析器执行,可能导致远程代码执行。建议:

  • 实施严格的白名单机制,只允许访问预定义的安全目录
  • 考虑使用沙箱环境限制 Groovy 脚本的执行权限
  • 完全避免将用户可控的输入用于脚本执行

Identifiers:

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

Merge request reports

Loading