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:
漏洞报告指出存在相对路径遍历漏洞(Relative Path Traversal),属于CWE-23和OWASP A01:2021/A5:2017中的"Broken Access Control"类别。问题出现在直接使用用户控制的输入(file
参数)来构造文件路径,可能导致攻击者通过../
等方式访问系统上的任意文件。
在源代码中,确实有多处直接使用用户输入的file
参数来创建File
对象,例如:
shell.parse(new File(file));
这是一个真实的安全漏洞,因为:
- 用户可以通过构造恶意路径访问系统敏感文件
- 没有对输入进行任何验证或清理
- 即使有
ALLOWED_EXPRESSIONS
检查,文件路径仍然不受控制
这不是误报,需要修复。
Summary:
-
报告的漏洞:相对路径遍历漏洞(CWE-23),用户控制的文件路径可能导致任意文件访问。
-
修复方案:
- 使用
org.apache.commons.io.FilenameUtils.getName()
提取安全的文件名 - 将文件限制在特定目录(如
/safe/directory/path/
) - 所有使用用户输入作为文件路径的地方都进行了清理
- 使用
-
修复示例:
// 修复前 - 直接使用用户输入
shell.parse(new File(file));
// 修复后 - 使用安全路径
String safeFileName = org.apache.commons.io.FilenameUtils.getName(file);
File safeFile = new File("/safe/directory/path/" + safeFileName);
shell.parse(safeFile);
修复方案确保了用户无法通过路径遍历访问系统其他目录,同时保持了原有功能。
Identifiers:
- A5:2017 - Broken Access Control
- java_traversal_rule-RelativePathTraversal
- A01:2021 - Broken Access Control
- CWE-23