checkmarx: Stored Absolute Path Traversal for Files.readAllBytes and Files.readAllLines

444 Views Asked by At

I catch "Stored Absolute Path Traversal" for 2 operations in my Java code:

 byte[] buffer = Files.readAllBytes(dir);
                 Files.readAllLines(dir)   

Argument dir is created as follows:

 Path dir = Paths.get(Paths.get(base, parts).normalize().toString().replace(" ", "_"));

So, I tried to sanitize path creation, by normalization and replace of empty characters, but this does not work.

Also I tried to apply File(path).getCanonicalPath():

 String canonicalPath;
 String path = Paths.get(base, parts)
    .normalize()
    .toString().replace(" ", "_");
try {
    canonicalPath = new File(path).getCanonicalPath();
} catch (Exception e) {
    throw new RuntimeExceptione);
 }

But with the same effect.

2

There are 2 best solutions below

2
Dhandu Prem Kumar On
  1. Use the File.getCanonicalPath method to resolve any symbolic links, relative paths, or redundant components in the parts parameter.
  2. Use the File.getAbsolutePath method to get the absolute path of the base parameter.
0
lrmrt On

You can try this function to sanitize the path

private static String sanitizePathTraversal(String filename) {
 Path p = Paths.get(filename);
 return p.getFileName().toString();
}

It worked in my case.

Add this function and modify your code like this:

canonicalPath = new File(sanitizePathTraversal(path));