3

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?

securecodeninja
  • 2,497
  • 3
  • 16
  • 22
dev29
  • 31
  • 1
  • 2

2 Answers2

2

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));
securecodeninja
  • 2,497
  • 3
  • 16
  • 22
  • 1
    giving you a +1! your first answer worked for me! although you might need to make some minor corrections, the last line returns a `File`, not a `String`, so it should be `File file = new File(normalizedPath.toString());`. Otherwise all else is fine :) – waffledood Feb 07 '23 at 06:27
0

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

Atul Dwivedi
  • 1,452
  • 16
  • 29