From d2528ca24c1a83c06e8a917d062352517282d1d7 Mon Sep 17 00:00:00 2001 From: Mohammed Hassan Date: Mon, 30 Nov 2026 20:00:49 +0530 Subject: [PATCH 1/2] restrict cache file mode and reject symlinks in FileResourceFactory --- .../http/impl/cache/FileResourceFactory.java | 46 +++++++++++++++++-- .../impl/cache/TestFileResourceFactory.java | 44 ++++++++++++++++++ 2 files changed, 85 insertions(+), 5 deletions(-) diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java index 9c36bfe524..f62538ecb1 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java @@ -27,8 +27,16 @@ package org.apache.hc.client5.http.impl.cache; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -49,6 +57,13 @@ @Contract(threading = ThreadingBehavior.STATELESS) public class FileResourceFactory implements ResourceFactory { + /** + * Permissions of the cache files created by this factory. A cache file holds a response + * body verbatim, so it must not be readable by other users of the system. Empty on file + * systems without POSIX file permissions, where the file inherits the directory's ACL. + */ + private static final FileAttribute[] OWNER_ONLY = ownerOnlyAttributes(); + private final File cacheDir; public FileResourceFactory(final File cacheDir) { @@ -87,16 +102,37 @@ public Resource generate( Args.notNull(requestId, "Request id"); final String filename = generateUniqueCacheFileName(requestId, eTag, content, off, len); final File file = new File(cacheDir, filename); - try (FileOutputStream outStream = new FileOutputStream(file, false)) { - if (content != null) { - outStream.write(content, off, len); - } + try { + writeCacheFile(file.toPath(), content, off, len); } catch (final IOException ex) { throw new ResourceIOException(ex.getMessage(), ex); } return new FileResource(file); } + private static FileAttribute[] ownerOnlyAttributes() { + if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { + return new FileAttribute[] { + PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")) }; + } + return new FileAttribute[0]; + } + + private static void writeCacheFile( + final Path file, final byte[] content, final int off, final int len) throws IOException { + try { + Files.createFile(file, OWNER_ONLY); + } catch (final FileAlreadyExistsException ignore) { + // The entry is being regenerated; the file is rewritten below. + } + try (OutputStream outStream = Files.newOutputStream(file, + StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, LinkOption.NOFOLLOW_LINKS)) { + if (content != null) { + outStream.write(content, off, len); + } + } + } + @Override public Resource generate(final String requestId, final byte[] content, final int off, final int len) throws ResourceIOException { if (content != null) { diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java index ba814be0c3..0bc05d82df 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java @@ -27,11 +27,20 @@ package org.apache.hc.client5.http.impl.cache; +import java.io.IOException; import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import org.apache.hc.client5.http.cache.ResourceIOException; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; class TestFileResourceFactory { @@ -66,4 +75,39 @@ void testViaValueLookup() throws Exception { FileResourceFactory.generateUniqueCacheFileName(requestId, null, null, 0, 0)); } + @Test + void testGeneratedCacheFileIsOwnerOnly(@TempDir final Path cacheDir) throws Exception { + Assumptions.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff")); + final byte[] content = "secret".getBytes(StandardCharsets.US_ASCII); + + new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length); + + final Path file = cacheDir.resolve( + FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length)); + Assertions.assertEquals("rw-------", + PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + } + + @Test + void testGenerateDoesNotFollowSymlink(@TempDir final Path cacheDir, @TempDir final Path otherDir) throws Exception { + final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff")); + final byte[] content = "response body".getBytes(StandardCharsets.US_ASCII); + final Path outside = otherDir.resolve("outside"); + Files.write(outside, "untouched".getBytes(StandardCharsets.US_ASCII)); + final Path link = cacheDir.resolve( + FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length)); + try { + Files.createSymbolicLink(link, outside); + } catch (final IOException | UnsupportedOperationException ex) { + Assumptions.abort("symbolic links are not supported here"); + } + + final FileResourceFactory factory = new FileResourceFactory(cacheDir.toFile()); + Assertions.assertThrows(ResourceIOException.class, + () -> factory.generate(requestId, "\"v1\"", content, 0, content.length)); + Assertions.assertEquals("untouched", + new String(Files.readAllBytes(outside), StandardCharsets.US_ASCII)); + } + } From 72e79838650284a08a2ecf139e47ee2af214197f Mon Sep 17 00:00:00 2001 From: Mohammed Hassan Date: Fri, 4 Dec 2026 17:07:17 +0530 Subject: [PATCH 2/2] Create cache files exclusively instead of reusing a pre-existing file --- .../http/impl/cache/FileResourceFactory.java | 27 +++++++---- .../impl/cache/TestFileResourceFactory.java | 48 +++++++++++++++++-- 2 files changed, 62 insertions(+), 13 deletions(-) diff --git a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java index f62538ecb1..45f07ca993 100644 --- a/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java +++ b/httpclient5-cache/src/main/java/org/apache/hc/client5/http/impl/cache/FileResourceFactory.java @@ -29,16 +29,18 @@ import java.io.File; import java.io.IOException; import java.io.OutputStream; -import java.nio.file.FileAlreadyExistsException; +import java.nio.channels.Channels; import java.nio.file.FileSystems; import java.nio.file.Files; -import java.nio.file.LinkOption; +import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.EnumSet; +import java.util.Set; import org.apache.hc.client5.http.cache.Resource; import org.apache.hc.client5.http.cache.ResourceFactory; @@ -64,6 +66,14 @@ public class FileResourceFactory implements ResourceFactory { */ private static final FileAttribute[] OWNER_ONLY = ownerOnlyAttributes(); + /** + * Cache files are always created anew. {@code CREATE_NEW} fails if anything, including a + * symbolic link, exists at the path, so a write can never land in a file this factory did + * not create. + */ + private static final Set CREATE_EXCLUSIVE = + EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); + private final File cacheDir; public FileResourceFactory(final File cacheDir) { @@ -120,13 +130,12 @@ private static FileAttribute[] ownerOnlyAttributes() { private static void writeCacheFile( final Path file, final byte[] content, final int off, final int len) throws IOException { - try { - Files.createFile(file, OWNER_ONLY); - } catch (final FileAlreadyExistsException ignore) { - // The entry is being regenerated; the file is rewritten below. - } - try (OutputStream outStream = Files.newOutputStream(file, - StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, LinkOption.NOFOLLOW_LINKS)) { + // Whatever is at the path is not reused: a pre-existing file keeps its own mode and may be + // a hard link to a file outside the cache directory. Remove it (a symbolic link is removed, + // not followed) and create the cache file exclusively with owner-only permissions. + Files.deleteIfExists(file); + try (OutputStream outStream = Channels.newOutputStream( + Files.newByteChannel(file, CREATE_EXCLUSIVE, OWNER_ONLY))) { if (content != null) { outStream.write(content, off, len); } diff --git a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java index 0bc05d82df..b1cd559978 100644 --- a/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java +++ b/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/TestFileResourceFactory.java @@ -35,7 +35,6 @@ import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermissions; -import org.apache.hc.client5.http.cache.ResourceIOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; @@ -103,11 +102,52 @@ void testGenerateDoesNotFollowSymlink(@TempDir final Path cacheDir, @TempDir fin Assumptions.abort("symbolic links are not supported here"); } - final FileResourceFactory factory = new FileResourceFactory(cacheDir.toFile()); - Assertions.assertThrows(ResourceIOException.class, - () -> factory.generate(requestId, "\"v1\"", content, 0, content.length)); + new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length); + + Assertions.assertEquals("untouched", + new String(Files.readAllBytes(outside), StandardCharsets.US_ASCII)); + Assertions.assertFalse(Files.isSymbolicLink(link)); + Assertions.assertEquals("response body", + new String(Files.readAllBytes(link), StandardCharsets.US_ASCII)); + } + + @Test + void testGenerateReplacesPreexistingFile(@TempDir final Path cacheDir) throws Exception { + Assumptions.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")); + final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff")); + final byte[] content = "secret".getBytes(StandardCharsets.US_ASCII); + final Path file = cacheDir.resolve( + FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length)); + Files.write(file, "planted".getBytes(StandardCharsets.US_ASCII)); + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-rw-rw-")); + + new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length); + + Assertions.assertEquals("rw-------", + PosixFilePermissions.toString(Files.getPosixFilePermissions(file))); + Assertions.assertEquals("secret", new String(Files.readAllBytes(file), StandardCharsets.US_ASCII)); + } + + @Test + void testGenerateDoesNotWriteThroughHardLink(@TempDir final Path cacheDir, @TempDir final Path otherDir) throws Exception { + final String requestId = keyGenerator.generateKey(new URI("http://localhost/stuff")); + final byte[] content = "response body".getBytes(StandardCharsets.US_ASCII); + final Path outside = otherDir.resolve("outside"); + Files.write(outside, "untouched".getBytes(StandardCharsets.US_ASCII)); + final Path link = cacheDir.resolve( + FileResourceFactory.generateUniqueCacheFileName(requestId, "\"v1\"", content, 0, content.length)); + try { + Files.createLink(link, outside); + } catch (final IOException | UnsupportedOperationException ex) { + Assumptions.abort("hard links are not supported here"); + } + + new FileResourceFactory(cacheDir.toFile()).generate(requestId, "\"v1\"", content, 0, content.length); + Assertions.assertEquals("untouched", new String(Files.readAllBytes(outside), StandardCharsets.US_ASCII)); + Assertions.assertEquals("response body", + new String(Files.readAllBytes(link), StandardCharsets.US_ASCII)); } }