Objective: The batch application needs to read a file from the server. The exact directory might change in future and so we should make it dynamic.
Approach taken: The file path (directories) and the file name will be provided in the application yaml file as follows:
file path: /application/directory
file name: test.csv
Code for the same: Initial version:
File file = new File(filePath,filename);
SonarQube showed it vulnerable by suggesting this: A file is opened to read its content. The filename comes from an input parameter. If an unfiltered parameter is passed to this file API, files from an arbitrary filesystem location could be read. This rule identifies potential path traversal vulnerabilities. In many cases, the constructed file path cannot be controlled by the user. If that is the case, the reported instance is a false positive.
Vulnerable Code:
@GET
@Path("/images/{image}")
@Produces("images/*")
public Response getImage(@javax.ws.rs.PathParam("image") String image) {
File file = new File("resources/images/", image); //Weak point
if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok().entity(new FileInputStream(file)).build();
}
Solution:
import org.apache.commons.io.FilenameUtils;
@GET
@Path("/images/{image}")
@Produces("images/*")
public Response getImage(@javax.ws.rs.PathParam("image") String image) {
File file = new File("resources/images/", FilenameUtils.getName(image)); //Fix
if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok().entity(new FileInputStream(file)).build();
}
I have changed my code accordingly:
File file = new File(filePath,FilenameUtils.getName(fileName));
Still I am getting the same error message.
Yes it is a False Positive.
I removed this by using //NOSONAR at the end of the statement
File file = new File("resources/images/", FilenameUtils.getName(image)); //NOSONAR
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments