diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java
index 4636bdaf30..fab3db7ea0 100644
--- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java
+++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResource.java
@@ -27,10 +27,10 @@
package org.apache.hc.client5.http.impl.cache;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.hc.client5.http.cache.Resource;
@@ -42,6 +42,10 @@
/**
* Cache resource backed by a file.
+ *
+ * The cache directory must be writable only by the application; the symlink check on
+ * read is defense in depth, not a security boundary.
+ *
*
* @since 4.1
*/
@@ -70,7 +74,7 @@ public byte[] get() throws ResourceIOException {
if (file == null) {
throw new ResourceIOException("Resource already disposed");
}
- try (final InputStream in = new FileInputStream(file)) {
+ try (final InputStream in = openStream(file)) {
final ByteArrayBuffer buf = new ByteArrayBuffer(1024);
final byte[] tmp = new byte[2048];
int len;
@@ -88,14 +92,21 @@ public InputStream getInputStream() throws ResourceIOException {
final File file = this.fileRef.get();
if (file != null) {
try {
- return new FileInputStream(file);
- } catch (final FileNotFoundException ex) {
+ return openStream(file);
+ } catch (final IOException ex) {
throw new ResourceIOException(ex.getMessage(), ex);
}
}
throw new ResourceIOException("Resource already disposed");
}
+ /**
+ * Opens the file without following a symbolic link planted at its path.
+ */
+ private static InputStream openStream(final File file) throws IOException {
+ return Files.newInputStream(file.toPath(), LinkOption.NOFOLLOW_LINKS);
+ }
+
@Override
public long length() {
return len;
diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/PostCreationSymlinkSwapTest.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/PostCreationSymlinkSwapTest.java
new file mode 100644
index 0000000000..dd3ef8778d
--- /dev/null
+++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/PostCreationSymlinkSwapTest.java
@@ -0,0 +1,164 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.cache;
+
+import java.net.InetAddress;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
+import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap;
+import org.apache.hc.core5.http.io.HttpRequestHandler;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.hc.core5.http.io.entity.StringEntity;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.io.CloseMode;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+/**
+ * Tests that a symlinked cache directory still serves hits, and that a cache file swapped
+ * for a symbolic link after creation is not read through.
+ */
+class PostCreationSymlinkSwapTest {
+
+ private HttpServer server;
+
+ @AfterEach
+ void shutDown() {
+ if (server != null) {
+ server.close(CloseMode.GRACEFUL);
+ }
+ }
+
+ // Regression test: passes with or without NOFOLLOW_LINKS, which applies to the cache file, not a symlinked parent directory.
+ @Test
+ void testCacheHitsAreServedNormallyThroughASymlinkedCacheDirectory(
+ @TempDir final Path parentDir) throws Exception {
+ Assumptions.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
+
+ final Path realCacheDir = Files.createDirectory(parentDir.resolve("real-cache"));
+ final Path cacheDirLink = parentDir.resolve("cache-link");
+ Files.createSymbolicLink(cacheDirLink, realCacheDir);
+
+ final String path = "/report";
+ final String body = "CACHED RESPONSE";
+ final AtomicInteger requestCount = new AtomicInteger();
+ server = ServerBootstrap.bootstrap()
+ .setLocalAddress(InetAddress.getLoopbackAddress())
+ .setRequestRouter((method, requestPath) -> (HttpRequestHandler) (request, response, context) -> {
+ requestCount.incrementAndGet();
+ response.setCode(HttpStatus.SC_OK);
+ response.setHeader("Cache-Control", "public, max-age=3600");
+ response.setHeader("ETag", "\"v1\"");
+ response.setEntity(new StringEntity(body, StandardCharsets.US_ASCII));
+ })
+ .create();
+ server.start();
+ final HttpHost target = new HttpHost(URIScheme.HTTP.id, "localhost", server.getLocalPort());
+
+ try (CloseableHttpClient client = CachingHttpClients.createFileBound(cacheDirLink.toFile())) {
+ try (ClassicHttpResponse response = client.executeOpen(target, new HttpGet(path), HttpCoreContext.create())) {
+ Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
+ Assertions.assertEquals(body, EntityUtils.toString(response.getEntity()));
+ }
+ Assertions.assertEquals(1, requestCount.get());
+
+ try (ClassicHttpResponse response = client.executeOpen(target, new HttpGet(path), HttpCoreContext.create())) {
+ Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
+ Assertions.assertEquals(body, EntityUtils.toString(response.getEntity()),
+ "a cache hit through a symlinked cache directory must still be served from cache");
+ }
+ Assertions.assertEquals(1, requestCount.get(), "the second request must be served from cache, not re-fetched");
+ }
+ }
+
+ @Test
+ void testCacheFileSwappedForSymlinkAfterCreationDoesNotLeakTargetOnSecondRead(
+ @TempDir final Path cacheDir, @TempDir final Path otherDir) throws Exception {
+ Assumptions.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
+
+ final String path = "/report";
+ final String originalBody = "ORIGINAL CACHED RESPONSE";
+ final Path secretFile = otherDir.resolve("secret.txt");
+ final String secretContent = "attacker-controlled-content-outside-the-cache-directory";
+ Files.write(secretFile, secretContent.getBytes(StandardCharsets.US_ASCII));
+
+ final AtomicInteger requestCount = new AtomicInteger();
+ server = ServerBootstrap.bootstrap()
+ .setLocalAddress(InetAddress.getLoopbackAddress())
+ .setRequestRouter((method, requestPath) -> (HttpRequestHandler) (request, response, context) -> {
+ requestCount.incrementAndGet();
+ response.setCode(HttpStatus.SC_OK);
+ response.setHeader("Cache-Control", "public, max-age=3600");
+ response.setHeader("ETag", "\"v1\"");
+ response.setEntity(new StringEntity(originalBody, StandardCharsets.US_ASCII));
+ })
+ .create();
+ server.start();
+ final HttpHost target = new HttpHost(URIScheme.HTTP.id, "localhost", server.getLocalPort());
+
+ try (CloseableHttpClient client = CachingHttpClients.createFileBound(cacheDir.toFile())) {
+ try (ClassicHttpResponse response = client.executeOpen(target, new HttpGet(path), HttpCoreContext.create())) {
+ Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
+ Assertions.assertEquals(originalBody, EntityUtils.toString(response.getEntity()));
+ }
+ Assertions.assertEquals(1, requestCount.get());
+
+ final Path[] cacheFiles;
+ try (Stream list = Files.list(cacheDir)) {
+ cacheFiles = list.toArray(Path[]::new);
+ }
+ Assertions.assertEquals(1, cacheFiles.length, "expected exactly one cache file after the first request");
+ final Path cacheFile = cacheFiles[0];
+
+ // Swap the cache file for a symlink to a file outside the cache directory.
+ Files.delete(cacheFile);
+ Files.createSymbolicLink(cacheFile, secretFile);
+
+ try (ClassicHttpResponse response = client.executeOpen(target, new HttpGet(path), HttpCoreContext.create())) {
+ Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
+ Assertions.assertEquals(originalBody, EntityUtils.toString(response.getEntity()),
+ "the read must not follow the symlink; a failed cache read must fall back to the origin");
+ }
+ Assertions.assertEquals(2, requestCount.get(), "a failed cache read must re-fetch from the origin");
+ }
+ }
+}