Potential Path Traversal (file read)

Bug Pattern: PATH_TRAVERSAL_IN

白盒检测规则(逻辑)

  • 污染传播:用户可控的路径,未经过滤就到了new File。

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:

  1. @GET
  2. @Path("/images/{image}")
  3. @Produces("images/*")
  4. public Response getImage(@javax.ws.rs.PathParam("image") String image) {
  5. File file = new File("resources/images/", image); //Weak point
  6. if (!file.exists()) {
  7. return Response.status(Status.NOT_FOUND).build();
  8. }
  9. return Response.ok().entity(new FileInputStream(file)).build();
  10. }

Solution:

  1. import org.apache.commons.io.FilenameUtils;
  2. @GET
  3. @Path("/images/{image}")
  4. @Produces("images/*")
  5. public Response getImage(@javax.ws.rs.PathParam("image") String image) {
  6. File file = new File("resources/images/", FilenameUtils.getName(image)); //Fix
  7. if (!file.exists()) {
  8. return Response.status(Status.NOT_FOUND).build();
  9. }
  10. return Response.ok().entity(new FileInputStream(file)).build();
  11. }

References
WASC: Path Traversal
OWASP: Path Traversal
CAPEC-126: Path Traversal
CWE-22: Improper Limitation of a Pathname to a Restricted Directory (‘Path Traversal’)