Input_Path_Not_Canonicalized - PathTravesal Vulnerability in checkmarx

11.4k views Asked by At

I am facing path traversal vulnerability while analyzing code through checkmarx. I am fetching path with below code:

String path  = System.getenv(variableName);

and "path" variable value is traversing through many functions and finally used in one function with below code snippet:

File file = new File(path);

Checkmarx is marking it as medium severity vulnerability.

Please help. How to resolve it to make it compatible with checkmarx?

2

There are 2 answers

0
Atul Dwivedi On

You can generate canonicalized path by calling File.getCanonicalPath().

In your case:

String path  = System.getenv(variableName);
path = new File(path).getCanonicalPath();

For more information read Java Doc

1
securecodeninja On

Other answers that I believe Checkmarx will accept as sanitizers include Path.normalize:

import java.nio.file.*;

String path  = System.getenv(variableName);
Path p = Paths.get(path);
Path normalizedPath = p.normalize();
path = new File(normalizedPath.toString());

or the FilenameUtils.normalize method:

import org.apache.commons.io.FilenameUtils;

String path  = System.getenv(variableName);
File file = new File(FilenameUtils.normalize(path));