首页 > 解决方案 > 读取位置可能由用户在 Sonar 中指定的文件

问题描述

我在下面的代码中发现了 Sonar 漏洞。我该如何解决这个漏洞?

代码

public static final String getFilePath(String configFileName) throws FileNotFoundException {
        File configFile = new File(FilenameUtils.getName(configFileName));
        if (configFile.exists()) {
            return configFile.getAbsolutePath();
        }
        URL url = ConfigHelper.class.getClassLoader().getResource(configFileName);
        if (url != null) {
            return url.getPath();
        }
        logger.error("Failed to find the file on classpath:" + configFileName);
        return null;
    }

错误

在此处输入图像描述

标签: javasonarqube

解决方案


这种方法究竟是什么意思?它的实际作用是:

  • 接受一个可能包含完整路径的输入参数,例如"/path/to/file.ext"
  • 丢弃路径(使用 FileNameUtils),只得到“file.ext”
  • 检查文件是否存在于当前目录中。

因此,如果用户这样做cd /some/dangerous/directory然后运行您的应用程序,即使您的方法已通过"/a/safe/directory/file.ext",如果文件file.ext存在,/some/dangerous/directory那么您的方法将返回"/some/dangerous/directory/file.ext"。如果用户复制病毒并在该危险目录中将其命名为“file.ext”,那么您可能会遇到麻烦。


推荐阅读