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)。问题出现在直接使用用户控制的输入file参数来创建File对象,这可能导致攻击者通过构造包含../的路径来访问系统上的任意文件。
虽然代码中有对script参数进行白名单检查,但对file参数没有类似的防护措施。在test1和test2方法中,多个地方直接使用了未经验证的用户输入来访问文件系统。
修复方案应该包括:
- 使用
FilenameUtils.getName()来提取文件名,防止路径遍历 - 将文件限制在特定目录下
- 添加白名单验证或文件存在性检查
Summary:
-
报告的漏洞:相对路径遍历漏洞(CWE-23),攻击者可能通过构造包含
../的路径来访问系统上的任意文件。 -
修复方案:
- 使用
FilenameUtils.getName()提取安全的文件名 - 将文件限制在特定目录(
/safe/directory/path/)下 - 添加路径验证,确保文件不会跳出指定目录
- 对于非法路径抛出安全异常
- 使用
-
修复效果: 修复后的代码可以防止攻击者通过路径遍历访问系统上的任意文件,同时保持了原有的功能。所有文件操作都被限制在指定的安全目录下,并且路径会被规范化后进行验证。
Identifiers:
- A5:2017 - Broken Access Control
- java_traversal_rule-RelativePathTraversal
- A01:2021 - Broken Access Control
- CWE-23