diff --git a/CHANGELOG.md b/CHANGELOG.md index ad58a1dd..b71e0f97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * Reject X.509-SVID leaf certificates with a root SPIFFE ID path in `X509SvidValidator.verifyChain`, which `SpiffeTrustManager` uses for peer certificates (#510) * Ignore JWKs with an unsupported key type when parsing a JWT bundle instead of rejecting the whole bundle, per the SPIFFE bundle spec (#512) +* Serialize `java-spiffe-helper` KeyStore and TrustStore files to memory before writing them, so a store or encoding failure no longer leaves an empty or partial file (#490) ### Build diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java index 514ca84a..5424dd67 100644 --- a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java +++ b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStore.java @@ -4,9 +4,9 @@ import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.security.GeneralSecurityException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; @@ -143,11 +143,15 @@ void deleteEntriesByAliasPrefix(final String aliasPrefix) throws KeyStoreExcepti this.flush(); } - // Flush KeyStore to disk, to the configured keyStoreFilePath + // Flush KeyStore to disk, to the configured keyStoreFilePath. The KeyStore is serialized to memory before the file + // is opened, so a store or encoding failure leaves the existing file as it was. An I/O failure while writing the + // bytes can still leave a partial file. private void flush() throws KeyStoreException { - try (OutputStream outputStream = Files.newOutputStream(keyStoreFilePath)) { - javaKeyStore.store(outputStream, keyStorePassword.toCharArray()); - } catch (IOException | NoSuchAlgorithmException | CertificateException e) { + try { + KeyStoreFileWriter.write(keyStoreFilePath, outputStream -> javaKeyStore.store(outputStream, keyStorePassword.toCharArray())); + } catch (KeyStoreException e) { + throw e; + } catch (IOException | GeneralSecurityException e) { throw new KeyStoreException(e); } } diff --git a/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStoreFileWriter.java b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStoreFileWriter.java new file mode 100644 index 00000000..8a8763c8 --- /dev/null +++ b/java-spiffe-helper/src/main/java/io/spiffe/helper/keystore/KeyStoreFileWriter.java @@ -0,0 +1,48 @@ +package io.spiffe.helper.keystore; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; + +/** + * Writes a KeyStore file by serializing it to memory first and then writing the bytes into the file in place. + *
+ * If serializing fails, the file is not touched. Writing in place follows symbolic links and keeps the file's owner, + * group, permissions and ACLs. An I/O error or a crash while the bytes are being written can still leave the file + * partially written. + *
+ * Package private, to be used by the KeyStore.
+ */
+final class KeyStoreFileWriter {
+
+ private KeyStoreFileWriter() {
+ }
+
+ /**
+ * Writes content to an output stream.
+ */
+ @FunctionalInterface
+ interface ContentWriter {
+ void writeTo(OutputStream outputStream) throws IOException, GeneralSecurityException;
+ }
+
+ /**
+ * Serializes the content written by {@code contentWriter} to memory, then writes it to {@code path}, creating the
+ * file if it doesn't exist.
+ *
+ * @param path the file to write
+ * @param contentWriter writes the new content
+ * @throws IOException if thrown by {@code contentWriter} or the file cannot be written
+ * @throws GeneralSecurityException if thrown by {@code contentWriter}
+ */
+ static void write(final Path path, final ContentWriter contentWriter) throws IOException, GeneralSecurityException {
+ final ByteArrayOutputStream content = new ByteArrayOutputStream();
+ contentWriter.writeTo(content);
+ try (OutputStream outputStream = Files.newOutputStream(path)) {
+ content.writeTo(outputStream);
+ }
+ }
+}
diff --git a/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreFileWriterTest.java b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreFileWriterTest.java
new file mode 100644
index 00000000..1318c731
--- /dev/null
+++ b/java-spiffe-helper/src/test/java/io/spiffe/helper/keystore/KeyStoreFileWriterTest.java
@@ -0,0 +1,187 @@
+package io.spiffe.helper.keystore;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.security.GeneralSecurityException;
+import java.security.KeyStoreException;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static io.spiffe.utils.TestUtils.toUri;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+class KeyStoreFileWriterTest {
+
+ private static final byte[] OLD_CONTENT = "old content".getBytes(StandardCharsets.UTF_8);
+ private static final byte[] NEW_CONTENT = "new content".getBytes(StandardCharsets.UTF_8);
+ private static final char[] PASSWORD = "password".toCharArray();
+ private static final String ALIAS = "bundle";
+
+ @TempDir
+ Path dir;
+
+ @Test
+ void write_createsFile() throws Exception {
+ Path target = dir.resolve("keystore.p12");
+
+ KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT));
+
+ assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target));
+ assertEquals(Collections.singletonList(target), listFiles());
+ }
+
+ @Test
+ void write_replacesExistingFile() throws Exception {
+ Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT);
+
+ KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT));
+
+ assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target));
+ assertEquals(Collections.singletonList(target), listFiles());
+ }
+
+ @Test
+ void write_missingParentDirectory_throwsNoSuchFile() {
+ Path target = dir.resolve("missing").resolve("keystore.p12");
+
+ assertThrows(NoSuchFileException.class, () -> KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT)));
+
+ assertTrue(Files.notExists(dir.resolve("missing")));
+ }
+
+ @Test
+ void write_serializationFailure_keepsExistingKeyStore_thenUpdates() throws Exception {
+ Path target = dir.resolve("keystore.p12");
+ java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
+ keyStore.load(null, PASSWORD);
+ KeyStoreFileWriter.write(target, out -> keyStore.store(out, PASSWORD));
+ byte[] original = Files.readAllBytes(target);
+
+ keyStore.setCertificateEntry(ALIAS, loadCertificate());
+ KeyStoreException failure = new KeyStoreException("cannot encode entry");
+ GeneralSecurityException thrown = assertThrows(GeneralSecurityException.class, () -> KeyStoreFileWriter.write(target, out -> {
+ keyStore.store(out, PASSWORD);
+ throw failure;
+ }));
+
+ assertSame(failure, thrown);
+ assertArrayEquals(original, Files.readAllBytes(target));
+ assertFalse(load(target).containsAlias(ALIAS));
+
+ KeyStoreFileWriter.write(target, out -> keyStore.store(out, PASSWORD));
+
+ assertTrue(load(target).containsAlias(ALIAS));
+ }
+
+ @Test
+ void write_ioFailureWhileSerializing_keepsExistingFile() throws Exception {
+ Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT);
+ IOException failure = new IOException("encoding failed");
+
+ IOException thrown = assertThrows(IOException.class, () -> KeyStoreFileWriter.write(target, out -> {
+ out.write(NEW_CONTENT, 0, 3);
+ throw failure;
+ }));
+
+ assertSame(failure, thrown);
+ assertArrayEquals(OLD_CONTENT, Files.readAllBytes(target));
+ }
+
+ @Test
+ void write_failureOnNewFile_leavesNothingBehind() throws Exception {
+ Path target = dir.resolve("keystore.p12");
+
+ assertThrows(IOException.class, () -> KeyStoreFileWriter.write(target, out -> {
+ throw new IOException("encoding failed");
+ }));
+
+ assertEquals(Collections.emptyList(), listFiles());
+ }
+
+ @Test
+ void write_keepsOwnerOnlyPermissions() throws Exception {
+ assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
+
+ Path target = Files.write(dir.resolve("keystore.p12"), OLD_CONTENT);
+ Set