Skip to content
Open
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 @@

### Fixed

* Replace the Helper's complete trust bundle set with one TrustStore write per update, remove authorities for absent trust domains, and preserve the live store when preparing a replacement fails. Only certificate aliases of the form `<trust-domain>.<ASCII numeric index>` are Helper-managed (#492)
* 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)
Expand Down
15 changes: 13 additions & 2 deletions java-spiffe-helper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,16 @@ Issuer: O=SPIFFE, C=US
...
```

The aliases for the trusted certs are generated using the Trust Domain of the SPIFFE ID in the SAN URI, and adding a
correlative number suffix.
Trusted certificate aliases have the form `<trust-domain>.<numeric-index>`, for example `example.org.0`.
The index consists entirely of ASCII digits. Certificate entries matching this format are managed by the Helper;
reserve these aliases for Workload API bundles. Other aliases and private key entries are preserved.
If a private-key entry uses an alias needed by a bundle, the trust update fails and preserves the key. The identity
KeyStore may already have been written when this failure occurs.

Each X.509 context update replaces all Helper-managed authorities with the complete bundle set, removing stale indexes
and authorities for trust domains no longer present. The replacement is prepared in a separate in-memory KeyStore and
the TrustStore is written once per update. If preparing or serializing the replacement fails, the live in-memory
TrustStore and existing file remain unchanged. The replacement becomes the live store only after the write succeeds.

Files are still written in place, so an I/O failure or crash during writing can leave a partial file. The KeyStore and
TrustStore are written separately; the two files are not updated atomically together.
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package io.spiffe.helper.keystore;

import io.spiffe.exception.InvalidSpiffeIdException;
import io.spiffe.spiffeid.TrustDomain;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
Expand All @@ -25,7 +29,7 @@ class KeyStore {
private final Path keyStoreFilePath;
private final KeyStoreType keyStoreType;
private final String keyStorePassword;
private final java.security.KeyStore javaKeyStore;
private java.security.KeyStore javaKeyStore;

KeyStore(
Path keyStoreFilePath,
Expand Down Expand Up @@ -126,29 +130,79 @@ void storeAuthorityEntry(final AuthorityEntry authorityEntry) throws KeyStoreExc
this.flush();
}

void deleteEntriesByAliasPrefix(final String aliasPrefix) throws KeyStoreException {
/**
* Replaces all helper-managed authorities with the complete bundle set, including removing absent trust domains.
* Changes are staged in a separate KeyStore and flushed once before becoming the live in-memory store.
* File writes remain in place, so an I/O failure can still leave a partial file.
*/
void replaceAuthorityEntries(final List<AuthorityEntry> authorityEntries) throws KeyStoreException {
java.security.KeyStore replacement = copyKeyStore();
List<String> aliasesToDelete = new ArrayList<>();
Enumeration<String> aliases = javaKeyStore.aliases();
Enumeration<String> aliases = replacement.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (alias.startsWith(aliasPrefix)) {
if (replacement.isCertificateEntry(alias) && isAuthorityAlias(alias)) {
aliasesToDelete.add(alias);
}
}

for (String alias : aliasesToDelete) {
javaKeyStore.deleteEntry(alias);
replacement.deleteEntry(alias);
}

this.flush();
for (AuthorityEntry authorityEntry : authorityEntries) {
Comment thread
maxlambrecht marked this conversation as resolved.
Resolved
replacement.setCertificateEntry(
authorityEntry.getAlias(),
authorityEntry.getCertificate()
);
}

flush(replacement);
javaKeyStore = replacement;
}

private java.security.KeyStore copyKeyStore() throws KeyStoreException {
try {
ByteArrayOutputStream content = new ByteArrayOutputStream();
javaKeyStore.store(content, keyStorePassword.toCharArray());
java.security.KeyStore copy = java.security.KeyStore.getInstance(javaKeyStore.getType(), javaKeyStore.getProvider());
copy.load(new ByteArrayInputStream(content.toByteArray()), keyStorePassword.toCharArray());
return copy;
} catch (IOException | GeneralSecurityException e) {
throw new KeyStoreException("KeyStore cannot be copied", e);
}
}

private boolean isAuthorityAlias(final String alias) {
int separator = alias.lastIndexOf('.');
if (separator <= 0 || separator == alias.length() - 1) {
return false;
}

for (int i = separator + 1; i < alias.length(); i++) {
char character = alias.charAt(i);
if (character < '0' || character > '9') {
return false;
}
}
try {
String trustDomain = alias.substring(0, separator);
return TrustDomain.parse(trustDomain).getName().equals(trustDomain);
} catch (InvalidSpiffeIdException | IllegalArgumentException e) {
return false;
}
}

// 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 {
flush(javaKeyStore);
}

private void flush(final java.security.KeyStore keyStore) throws KeyStoreException {
try {
KeyStoreFileWriter.write(keyStoreFilePath, outputStream -> javaKeyStore.store(outputStream, keyStorePassword.toCharArray()));
KeyStoreFileWriter.write(keyStoreFilePath, outputStream -> keyStore.store(outputStream, keyStorePassword.toCharArray()));
} catch (KeyStoreException e) {
throw e;
} catch (IOException | GeneralSecurityException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,28 +212,24 @@ private void storeX509ContextUpdate(final X509Context update) throws KeyStoreExc

keyStore.storePrivateKeyEntry(privateKeyEntry);

List<AuthorityEntry> authorityEntries = new ArrayList<>();
for (final Map.Entry<TrustDomain, X509Bundle> entry : update.getX509BundleSet().getBundles().entrySet()) {
TrustDomain trustDomain = entry.getKey();
X509Bundle bundle = entry.getValue();
storeBundle(trustDomain, bundle);
List<X509Certificate> authorities = sortedAuthorities(bundle);
int index = 0;
for (X509Certificate certificate : authorities) {
authorityEntries.add(AuthorityEntry.builder()
.alias(generateAlias(trustDomain, index))
.certificate(certificate)
.build());
index++;
}
}

log.log(Level.INFO, "Stored X.509 context update in Java KeyStore");
}
trustStore.replaceAuthorityEntries(authorityEntries);

private void storeBundle(TrustDomain trustDomain, X509Bundle bundle) throws KeyStoreException {
List<X509Certificate> authorities = sortedAuthorities(bundle);
trustStore.deleteEntriesByAliasPrefix(generateAliasPrefix(trustDomain));

int index = 0;
for (X509Certificate certificate : authorities) {
final AuthorityEntry authorityEntry = AuthorityEntry.builder()
.alias(generateAlias(trustDomain, index))
.certificate(certificate)
.build();
trustStore.storeAuthorityEntry(authorityEntry);
index++;
}
log.log(Level.INFO, "Stored X.509 context update in Java KeyStore");
}

private List<X509Certificate> sortedAuthorities(X509Bundle bundle) throws KeyStoreException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.mockito.MockedStatic;
import uk.org.webcompere.systemstubs.environment.EnvironmentVariables;

import java.io.InputStream;
Expand All @@ -32,14 +36,22 @@
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.withSettings;

class KeyStoreHelperTest {

Expand All @@ -48,6 +60,9 @@ class KeyStoreHelperTest {
private Path keyStoreFilePath;
private Path trustStoreFilePath;

@TempDir
Path tempDirectory;

@BeforeEach
void setUp() {
workloadApiClient = new WorkloadApiClientStub();
Expand Down Expand Up @@ -261,6 +276,65 @@ public void watchX509Context(Watcher<X509Context> watcher) {
assertEquals(1, trustStore.size());
}

@ParameterizedTest
@EnumSource(KeyStoreType.class)
void testRun_replacesCompleteBundleSetWithOneWritePerUpdate(KeyStoreType type) throws Exception {
keyStoreFilePath = tempDirectory.resolve("keystore");
trustStoreFilePath = tempDirectory.resolve("truststore");
String password = "truststore123";
X509Context context = workloadApiClient.fetchX509Context();
X509Bundle localBundle = context.getX509BundleSet().getBundleForTrustDomain(TrustDomain.parse("example.org"));
X509Certificate federatedAuthority = X509CertificateTestUtils
.createRootCA("CN=Federated CA", "spiffe://example.org.uk").getCertificate();
X509Bundle federatedBundle = new X509Bundle(TrustDomain.parse("example.org.uk"),
Collections.singleton(federatedAuthority));
AtomicReference<X509BundleSet> bundles = new AtomicReference<>(
X509BundleSet.of(Arrays.asList(localBundle, federatedBundle)));
WorkloadApiClient client = new WorkloadApiClientStub() {
@Override
public void watchX509Context(Watcher<X509Context> watcher) {
watcher.onUpdate(X509Context.of(context.getX509Svids(), bundles.get()));
}
};
KeyStoreHelper.KeyStoreOptions options = KeyStoreHelper.KeyStoreOptions.builder()
.keyStoreType(type).keyStorePath(keyStoreFilePath).keyStorePass(password)
.trustStorePath(trustStoreFilePath).trustStorePass(password).keyPass(password)
.workloadApiClient(client).build();

try (MockedStatic<KeyStoreFileWriter> writes = mockStatic(KeyStoreFileWriter.class,
withSettings().defaultAnswer(CALLS_REAL_METHODS).mockMaker("mock-maker-inline"));
KeyStoreHelper helper = KeyStoreHelper.create(options)) {
helper.run(false);
KeyStore stored = loadTrustStore(type, password);
assertEquals(localBundle.getX509Authorities().iterator().next(), stored.getCertificate("example.org.0"));
assertEquals(federatedAuthority, stored.getCertificate("example.org.uk.0"));
assertEquals(2, stored.size());
writes.verify(() -> KeyStoreFileWriter.write(eq(trustStoreFilePath), any()), times(1));

// Removing the shorter trust domain must preserve the longer trust domain's authorities.
bundles.set(X509BundleSet.of(Collections.singleton(federatedBundle)));
helper.run(false);
stored = loadTrustStore(type, password);
assertNull(stored.getCertificate("example.org.0"));
assertEquals(federatedAuthority, stored.getCertificate("example.org.uk.0"));
assertEquals(1, stored.size());
writes.verify(() -> KeyStoreFileWriter.write(eq(trustStoreFilePath), any()), times(2));

bundles.set(X509BundleSet.emptySet());
helper.run(false);
assertEquals(0, loadTrustStore(type, password).size());
writes.verify(() -> KeyStoreFileWriter.write(eq(trustStoreFilePath), any()), times(3));
}
}

private KeyStore loadTrustStore(KeyStoreType type, String password) throws Exception {
KeyStore stored = KeyStore.getInstance(type.value());
try (InputStream input = Files.newInputStream(trustStoreFilePath)) {
stored.load(input, password.toCharArray());
}
return stored;
}

@Test
void testCreateHelper_keyStore_trustStore_same_file_throwsException() throws SocketEndpointAddressException {

Expand Down Expand Up @@ -547,4 +621,4 @@ private void deleteFile(Path file) {
//ignore
}
}
}
}
Loading
Loading