Synopsis coverity still return Filesystem path, filename, or URI manipulation in java dispite making the recommended fix.

While these two following questions give a explaination of what todo they fail to fix the alert generated by the tool.

Coverity issues for Filesystem path, filename, or URI manipulation in java

How to fix "Path Manipulation Vulnerability" in some Java Code?

To be clear before someone close this has duplicate, these two answers don't fix the problem completly. Here the code that had the alert originaly followed be the correction that still have the coverity alert for Filesystem path, filename, or URI manipulation.

Original code:

    public String deleteFiles(List<String> filesToDelete){
    filesToDelete.forEach(file -> {
        logger.info("Deleting file " + file);
        Path path = Paths.get(file).normalize();
        new File(path).delete();
    });
}

Code correction that still return the coverity alert:

private static boolean doesFilenameTryPatternTraversal(String filename) {
  return Pattern.compile("\\.\\.|\\|/").matcher(filename).find();
}

private void deleteFiles(List<String> filesToDelete) {
  filesToDelete.forEach(file -> {
    logger.info("Deleting file {}", file);
    if (doesFilenameTryPatternTraversal(file)) {
      throw new RuntimeException(
          "filename: '" + file + "' attempting to access a file outside of expected directory.");
    }

    Path canonicalPath = basePath.resolve(Paths.get(file).toAbsolutePath().normalize());
    if (canonicalPath.startsWith(basePath.toString())) {
      try {
        Files.delete(canonicalPath);
      } catch (IOException e) {
        throw new RuntimeException("Could not delete file '" + file + "'.", e);
      }
    } else {
      throw new SecurityException("File '" + file + "' is outside the allowed directory");
    }
  });
}
0

There are 0 answers