javasonarqubepath-traversal

Pass sonar's PT_RELATIVE_PATH_TRAVERSAL in java


I've got two issues sonar is sad about. First one in a line of code with relative path traversal issue which looks like this:

File f = new File(MY_DIR + filename);

Where filename is a parameter I've got from a request.
The second line is about an absolute path traversal issue which looks like the same except there is no MY_DIR in front.

I've added validation checks after these lines using a method which insures that the file is inside the MY_DIR directory using canonical paths, so now it looks like this:

...
File rootDirFile = new File(MY_DIR);
        if (validateFileName(rootDirFile, f)) {
...
private static boolean validateFileName(File targetDir, File fileToCheck) throws IOException {
    String targetDirPath = targetDir.getCanonicalPath() + File.separator;
    String pathToCheck = fileToCheck.getCanonicalPath();

    return pathToCheck.startsWith(targetDirPath);
}

But sonar is still saying I've got a vulnerability at those two lines. How to tell it I've found the solution?


Solution

  • Depending on your version, you can mark the issue as "Won't fix" (meaning that the debt from this issue is accepted - since 5.1) or "False positive" (meaning that you think that the analysis engine is wrong - before 5.1).