There is the following false positive raised for javasecurity:S2083 when a user-controlled parameter is used with Class.getResource(String userControlledParam).
This can be seen in SonarQube Cloud with the open source project at GitHub - Netcentric/accesscontroltool: Rights and roles management for AEM made easy · GitHub.
The problematic line is
final URL url = getClass().getResource(resourcePath);
Where resource path is “only” sanitized like this
String resourcePath = req.getRequestURI().substring(basePath.length());
if (resourcePath.startsWith("/res/")) {
... code calling getClass().getResource(resourcePath)
}
I would argue that since path traversal is not possible in the String method argument of Class (Java Platform SE 8 ) the prefix checking should suffice here.
The rule description for javasecurity:S2083 explicitly mentions path traversal as attack vector:
A user with malicious intent would inject specially crafted values, such as
../, to change the initial intended path. The resulting path would resolve somewhere in the filesystem where the user should not normally have access to.
Also the “How would I fix this” section does not apply here as it is not a filesystem path but just a resource name!
Compliant code:
File file = new File(targetPath + filename);
if (!file.toPath().normalize().startsWith(targetPath)) {
throw new IOException("Entry is outside of the target directory");
}