微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring boot ResourceUtils 读取文件内容存在路径遍历漏洞

如何解决Spring boot ResourceUtils 读取文件内容存在路径遍历漏洞

我正在构建一个 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
 }
 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。