SonarCloud 如何修复更改此代码以不从用户控制的数据构造路径

问题描述 投票:0回答:1

获取声纳警告

更改此代码以不从用户控制的数据构造路径。 I/O 函数调用不应容易受到路径注入攻击 [javasecurity:S2083] 代码

public static void storeImageToHttpResponse(String imageBasePath, String fullpath, String filename, long fileLength, HttpServletResponse response) throws IOException{
    BufferedInputStream input = null;
    BufferedOutputStream output = null;
    try {
        InputStream is = new FileInputStream(validateImagePath(imageBasePath, fullpath));

        
    }  finally {
        if (output != null) try { output.close(); output.flush(); } catch (IOException logOrIgnore) {}
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    } 
}

public static File validateImagePath(String imageBasePath, String fullPath) throws IOException {
    File file = new File(fullPath);
    return validateImagePath(imageBasePath, file);
}

public static File validateImagePath(String imageBasePath, File file) throws IOException {
    Path targetPath = new File(imageBasePath).toPath().normalize();
    if(!file.toPath().normalize().startsWith(targetPath)) {
        throw new IOException(String.format("Image %s is outside of the target directory %s", file.getAbsolutePath(), imageBasePath));
    }
    return file;
}

但仍然收到警告

请帮助/建议

security path sonarcloud
1个回答
0
投票

此问题是为了避免文件名中的路径更改,例如传递

../file.aaa
directory/file.aaa

尝试在实例流之前验证父文件夹更改

Path parentPath = Paths.get(imageBasePath);
Path filePath = parentPath.resolve(filePathInImageBasePath);

if ( !parentPath.equals(filePath.getParent()) ) { // avoid issue javasecurity:S2083
    throw new YourException("any message");
}

final InputStream inputStream = Files.newInputStream(filePath);

即使您在创建流之前验证路径或目录,这个声纳问题仍然存在,我必须添加这段代码以避免

javasecurity:S2083

© www.soinside.com 2019 - 2024. All rights reserved.