diff --git a/functions/http/http-form-data/src/main/java/functions/HttpFormData.java b/functions/http/http-form-data/src/main/java/functions/HttpFormData.java index 3831b3a8526..e7f72c6c7ef 100644 --- a/functions/http/http-form-data/src/main/java/functions/HttpFormData.java +++ b/functions/http/http-form-data/src/main/java/functions/HttpFormData.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.nio.file.Files; +import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; @@ -42,25 +43,49 @@ public void service(HttpRequest request, HttpResponse response) } // This code will process each file uploaded. - String tempDirectory = System.getProperty("java.io.tmpdir"); + Path tempDirectory = + Paths.get(System.getProperty("java.io.tmpdir")).toAbsolutePath().normalize(); for (HttpRequest.HttpPart httpPart : request.getParts().values()) { String filename = httpPart.getFileName().orElse(null); if (filename == null) { continue; } - logger.info("Processed file: " + filename); + // Strip any client-supplied path components to prevent path traversal. + Path filePath; + String sanitizedFilename; + try { + Path baseName = Paths.get(filename).getFileName(); + if (baseName == null) { + response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); + return; + } + sanitizedFilename = baseName.toString(); + filePath = tempDirectory.resolve(sanitizedFilename).normalize(); + } catch (InvalidPathException e) { + response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); + return; + } + + if (!filePath.startsWith(tempDirectory) || filePath.equals(tempDirectory)) { + response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); + return; + } + + logger.info("Processed file: " + sanitizedFilename); // Note: GCF's temp directory is an in-memory file system // Thus, any files in it must fit in the instance's memory. - Path filePath = Paths.get(tempDirectory, filename).toAbsolutePath(); // Note: files saved to a GCF instance itself may not persist across executions. // Persistent files should be stored elsewhere, e.g. a Cloud Storage bucket. - Files.copy(httpPart.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING); + try { + Files.copy(httpPart.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING); - // TODO(developer): process saved files here - Files.delete(filePath); + // TODO(developer): process saved files here + } finally { + Files.deleteIfExists(filePath); + } } // This code will process other form fields. diff --git a/functions/http/http-form-data/src/test/java/functions/HttpFormDataTest.java b/functions/http/http-form-data/src/test/java/functions/HttpFormDataTest.java index 2f3246e649f..db611036752 100644 --- a/functions/http/http-form-data/src/test/java/functions/HttpFormDataTest.java +++ b/functions/http/http-form-data/src/test/java/functions/HttpFormDataTest.java @@ -32,6 +32,9 @@ import java.io.StringWriter; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.Optional; @@ -116,4 +119,66 @@ public void functionsHttpFormData_shouldProcessFields() throws IOException { assertThat(logHandler.getStoredLogRecords().get(0).getMessage()).isEqualTo( "Processed field: foo (value: bar)"); } + + @Test + public void functionsHttpFormData_shouldPreventPathTraversal() throws IOException { + when(request.getMethod()).thenReturn("POST"); + + Path canaryDir = Files.createTempDirectory("http-form-data-canary"); + Path canary = Files.writeString(canaryDir.resolve("canary.txt"), "original"); + try { + Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).toAbsolutePath().normalize(); + String traversalFilename = tmpDir.relativize(canary.toAbsolutePath().normalize()).toString(); + + MockHttpPart mockHttpPart = new MockHttpPart(); + mockHttpPart.setFileName(traversalFilename); + mockHttpPart.setInputStream( + new ByteArrayInputStream("attacker".getBytes(StandardCharsets.UTF_8))); + + when(request.getParts()).thenReturn(Map.of("mock", mockHttpPart)); + + new HttpFormData().service(request, response); + + assertThat(Files.exists(canary)).isTrue(); + assertThat(Files.readString(canary)).isEqualTo("original"); + assertThat(logHandler.getStoredLogRecords().get(0).getMessage()) + .isEqualTo("Processed file: canary.txt"); + } finally { + Files.deleteIfExists(canary); + Files.deleteIfExists(canaryDir); + } + } + + @Test + public void functionsHttpFormData_shouldRejectDotDotFilename() throws IOException { + when(request.getMethod()).thenReturn("POST"); + + MockHttpPart mockHttpPart = new MockHttpPart(); + mockHttpPart.setFileName(".."); + mockHttpPart.setInputStream( + new ByteArrayInputStream("attacker".getBytes(StandardCharsets.UTF_8))); + + when(request.getParts()).thenReturn(Map.of("mock", mockHttpPart)); + + new HttpFormData().service(request, response); + + verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); + } + + @Test + public void functionsHttpFormData_shouldStripParentTraversalPrefix() throws IOException { + when(request.getMethod()).thenReturn("POST"); + + MockHttpPart mockHttpPart = new MockHttpPart(); + mockHttpPart.setFileName("../../escape-test.txt"); + mockHttpPart.setInputStream( + new ByteArrayInputStream("attacker".getBytes(StandardCharsets.UTF_8))); + + when(request.getParts()).thenReturn(Map.of("mock", mockHttpPart)); + + new HttpFormData().service(request, response); + + assertThat(logHandler.getStoredLogRecords().get(0).getMessage()) + .isEqualTo("Processed file: escape-test.txt"); + } }