在 Java 中使用文件 class 时的 SonarQube 漏洞
SonarQube Vulnerability while using File class in Java
Objective:批处理应用程序需要从服务器读取一个文件。确切的目录将来可能会改变,所以我们应该让它动态化。
采取的方法:文件路径(目录)和文件名将在应用程序yaml文件中提供如下:
文件路径: /application/directory
文件名: test.csv
代码相同:
初始版本:
File file = new File(filePath,filename);
SonarQube 通过建议显示它易受攻击:
打开文件以读取其内容。文件名来自输入参数。如果将未过滤的参数传递给此文件 API,则可以读取来自任意文件系统位置的文件。
此规则识别潜在的路径遍历漏洞。在很多情况下,构造的文件路径是用户无法控制的。如果是这样,则报告的实例是误报。
漏洞代码:
@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();
}
解法:
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();
}
我已经相应地更改了我的代码:
File file = new File(filePath,FilenameUtils.getName(fileName));
我仍然收到相同的错误消息。
是的,这是误报。
我通过在语句末尾使用 //NOSONAR 删除了它
File file = new File("resources/images/", FilenameUtils.getName(image)); //NOSONAR
Objective:批处理应用程序需要从服务器读取一个文件。确切的目录将来可能会改变,所以我们应该让它动态化。
采取的方法:文件路径(目录)和文件名将在应用程序yaml文件中提供如下:
文件路径: /application/directory
文件名: test.csv
代码相同: 初始版本:
File file = new File(filePath,filename);
SonarQube 通过建议显示它易受攻击: 打开文件以读取其内容。文件名来自输入参数。如果将未过滤的参数传递给此文件 API,则可以读取来自任意文件系统位置的文件。 此规则识别潜在的路径遍历漏洞。在很多情况下,构造的文件路径是用户无法控制的。如果是这样,则报告的实例是误报。
漏洞代码:
@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();
}
解法:
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();
}
我已经相应地更改了我的代码:
File file = new File(filePath,FilenameUtils.getName(fileName));
我仍然收到相同的错误消息。
是的,这是误报。
我通过在语句末尾使用 //NOSONAR 删除了它
File file = new File("resources/images/", FilenameUtils.getName(image)); //NOSONAR