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 A5:2017和A01:2021中的访问控制问题。报告指出用户输入控制了文件路径,攻击者可能通过../
等方式访问非预期目录。
在源代码中,shell.parse(new File(file));
这一行被标记为易受攻击,其中file
参数来自用户输入(通过@RequestParam
注解)。这确实存在安全风险,因为攻击者可以构造恶意路径(如../../etc/passwd
)来访问系统敏感文件。
然而,需要注意的是,漏洞报告主要关注路径遍历,但代码中还存在Groovy脚本执行的安全问题(代码注入风险)。不过本次修复应专注于路径遍历问题。
修复方案:使用FilenameUtils.getName()
来提取文件名,防止路径遍历。但需要注意:
- 需要确保Apache Commons IO库可用
- 需要验证文件名是否在允许的范围内
- 需要设置安全的基目录
由于代码中没有明显的基目录设置,我假设文件应该存储在某个固定目录下。
Summary:
-
报告的漏洞:相对路径遍历漏洞(CWE-23),用户输入控制文件路径,攻击者可通过
../
访问系统敏感文件 -
修复方案:
- 使用
org.apache.commons.io.FilenameUtils.getName()
提取安全的文件名 - 将文件限制在固定的安全基目录中(
/safe/base/directory/
) - 添加路径验证,确保文件路径不会逃逸出基目录
- 使用
修复后的代码:
String safeFileName = org.apache.commons.io.FilenameUtils.getName(file);
File safeFile = new File("/safe/base/directory/" + safeFileName);
if (!safeFile.getCanonicalPath().startsWith("/safe/base/directory/")) {
throw new SecurityException("Invalid file path");
}
shell.parse(safeFile);
这个修复通过文件名净化和路径验证,有效防止了路径遍历攻击,同时保持了原有的功能。
Identifiers:
- A5:2017 - Broken Access Control
- java_traversal_rule-RelativePathTraversal
- A01:2021 - Broken Access Control
- CWE-23