5

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?

0

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.