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);
- Severity: critical
- Location: java-groovy-cmdi-groovyshell-taint.java:60
Analysis:
根据漏洞报告和源代码分析,这是一个真实的路径遍历漏洞(CWE-23),属于OWASP A01:2021和A5:2017中的"Broken Access Control"类别。
漏洞点在于:
- 直接使用用户输入的
file参数创建File对象 - 攻击者可以通过构造包含
../的路径访问系统任意文件 - 虽然代码中有ALLOWED_EXPRESSIONS检查,但这只验证了script参数,没有验证file参数
修复方案:
- 使用FilenameUtils.getName()来获取安全的文件名
- 将文件限制在特定目录下
- 添加对文件路径的验证
这不是一个误报(false positive),需要修复。
Summary:
-
报告的漏洞:相对路径遍历漏洞(CWE-23),攻击者可以通过构造恶意路径访问系统任意文件。
-
修复方案:
- 使用
FilenameUtils.getName()获取安全的文件名 - 将文件限制在特定目录(
/safe/directory/path/) - 修复了所有使用用户输入文件路径的地方
- 使用
-
修复效果:
// 修复前 - 不安全 shell.evaluate(new File(userInput)); // 修复后 - 安全 String safeName = FilenameUtils.getName(userInput); File safeFile = new File("/safe/directory/path/" + safeName); shell.evaluate(safeFile);现在攻击者无法通过
../遍历目录结构,文件访问被限制在指定目录内。
Identifiers:
- A5:2017 - Broken Access Control
- java_traversal_rule-RelativePathTraversal
- A01:2021 - Broken Access Control
- CWE-23