SonarCloud How to fix change this code to not construct the path from user-controlled data

71 views Asked by At

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;
}

But still get warning enter image description here

Pls help/advise

1

There are 1 answers

0
Dilermando Lima On

This issue comes to avoid path changing in file name like passing ../file.aaa or directory/file.aaa

Try verifing parent folder changing before instance a stream

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);

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 )

 try(FileInputStream input = new FileInputStream("any-file")) {
    // code ... 
 }