Spring boot Spring boot ResourceUtils读取文件内容存在路径遍历漏洞
我正在构建一个spring引导应用程序,在这里我需要为组件测试读取json文件。我有一个实用方法,它使用文件名并使用ResourceUtils读取内容。代码如下:Spring boot Spring boot ResourceUtils读取文件内容存在路径遍历漏洞,spring-boot,spring-mvc,checkmarx,Spring Boot,Spring Mvc,Checkmarx,我正在构建一个spring引导应用程序,在这里我需要为组件测试读取json文件。我有一个实用方法,它使用文件名并使用ResourceUtils读取内容。代码如下: public static String getContent(String path) throws IOException { File file = ResourceUtils.getFile(MyTest.class.getResource(path)); String content = new String
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将上述代码报告为“这可能导致路径错误”
遍历漏洞。”
如何解决这个问题
感谢有关路径遍历漏洞,请参见此示例 要修复此更改,请执行以下操作
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
}
}
谢谢我通过谷歌搜索发现了这一点,但我想知道有没有更好的方法。