问题描述
我正在构建一个 Spring Boot 应用程序,我需要在其中读取 json 文件以进行组件测试。我有一个实用方法,它使用文件名并使用 ResourceUtils 读取内容。代码如下:
public static String getContent(String path) throws IOException {
File file = ResourceUtils.getFile(MyTest.class.getResource(path));
String content = new String(Files.readAllBytes(file.toPath()));
return content;
}
checkmarx 将上述代码报告为“这可能会导致路径 遍历漏洞。” 如何解决这个问题?
谢谢
解决方法
请参阅此示例以了解路径遍历漏洞 Path Traversal
要解决此问题,请像这样更改
private static final String BASE_PATH ="/yourbasepath/somewherewherefileisstored";
public static String getContent(String path) throws IOException {
File file = new File(BASE_PATH,path);
if (file.getCanonicalPath().startsWith(BASE_PATH)){
String content = new String(Files.readAllBytes(file.toPath()));
return content;
}
else{
//throw some error
}
}