Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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.
* <p>
* 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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-------");
Files.setPosixFilePermissions(target, permissions);

KeyStoreFileWriter.write(target, out -> out.write(NEW_CONTENT));

assertEquals(permissions, Files.getPosixFilePermissions(target));
assertArrayEquals(NEW_CONTENT, Files.readAllBytes(target));
}

@Test
void write_symbolicLink_writesLinkTarget() throws Exception {
Path realFile = Files.write(dir.resolve("real.p12"), OLD_CONTENT);
Path link = dir.resolve("link.p12");
createSymbolicLink(link, realFile);

KeyStoreFileWriter.write(link, out -> out.write(NEW_CONTENT));

assertTrue(Files.isSymbolicLink(link));
assertArrayEquals(NEW_CONTENT, Files.readAllBytes(realFile));
}

@Test
void write_danglingSymbolicLink_createsLinkTargetAndKeepsLink() throws Exception {
Path link = dir.resolve("link.p12");
createSymbolicLink(link, Paths.get("real.p12"));

KeyStoreFileWriter.write(link, out -> out.write(NEW_CONTENT));

assertTrue(Files.isSymbolicLink(link));
assertArrayEquals(NEW_CONTENT, Files.readAllBytes(dir.resolve("real.p12")));
}

private static void createSymbolicLink(Path link, Path target) {
try {
Files.createSymbolicLink(link, target);
} catch (IOException | UnsupportedOperationException e) {
assumeTrue(false, "symbolic links are not supported: " + e);
}
}

private static Certificate loadCertificate() throws Exception {
try (InputStream in = Files.newInputStream(Paths.get(toUri("testdata/bundle.pem")))) {
return CertificateFactory.getInstance("X.509").generateCertificate(in);
}
}

private static java.security.KeyStore load(Path path) throws Exception {
java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
try (InputStream in = Files.newInputStream(path)) {
keyStore.load(in, PASSWORD);
}
return keyStore;
}

private List<Path> listFiles() throws IOException {
try (Stream<Path> files = Files.list(dir)) {
return files.sorted().collect(Collectors.toList());
}
}
}
Loading