Get sonar warning
Change this code to not construct the path from user-controlled data. I/O function calls should not be vulnerable to path injection attacks [javasecurity:S2083] Code
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;
}
Pls help/advise
This issue comes to avoid path changing in file name like passing
../file.aaa
ordirectory/file.aaa
Try verifing parent folder changing before instance a stream
Even you are validating paths or directory before create stream this sonar issue still comes, I had to add this peace of code to avoid
javasecurity:S2083
Just to add a sugestion try to looking for
try-with-resources
to instance InputStream in order to close stream by jvm ( except your really need do it manually )