From d7f2e93e1afa96fdb01d8fbc30fee537fb882fda Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:49:38 +0000 Subject: [PATCH] feat(provider): accept a SpiffeIdVerifier in SslContextOptions SpiffeTrustManager can verify peer SPIFFE IDs with a SpiffeIdVerifier callback, which lets an application accept peers by rule (a trust domain, a path prefix, a lookup in another system) instead of from a fixed set of IDs. SpiffeSslContextFactory, the documented way to build an SSLContext backed by the Workload API, only accepted a Supplier of accepted SPIFFE IDs or acceptAnySpiffeId, so using a verifier meant creating the key and trust managers and initializing the SSLContext by hand. Add a spiffeIdVerifier option to SslContextOptions, with a builder method, a getter and a constructor that takes it. getSslContext creates the SpiffeTrustManager with the verifier when it is set. A verifier is a complete authorization decision on its own, so combining it with acceptedSpiffeIdsSupplier or acceptAnySpiffeId is rejected with an IllegalArgumentException instead of letting one silently override the other. The existing behavior of the supplier and acceptAnySpiffeId options is unchanged, and the error raised when no option is configured now also mentions the verifier. Document the option in the provider README with an example that accepts any workload in a trust domain, and add a changelog entry. Signed-off-by: NopeCharon <115794254+NopeCharon@users.noreply.github.com> --- CHANGELOG.md | 1 + java-spiffe-provider/README.md | 31 +++ .../provider/SpiffeSslContextFactory.java | 62 ++++- .../provider/SpiffeSslContextFactoryTest.java | 215 +++++++++++++++++- 4 files changed, 298 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b71e0f97..eedf0ed3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ * Add `X509Bundle.marshal()` and `JwtBundle.marshal()` to serialize bundles as PEM certificates and as a JWKS document, the formats read by `parse` * Publish a `java-spiffe-bom` Bill of Materials to align the versions of the java-spiffe modules. * Add `X509Svid.marshalCertificates()` and `X509Svid.marshalPrivateKey()` to serialize an X.509-SVID as PEM certificates and a PEM PKCS#8 private key, the formats read by `parse` and `load`, and `marshalRawCertificates()` and `marshalRawPrivateKey()` for the ASN.1 DER formats read by `parseRaw` (#515) +* Add a `spiffeIdVerifier` option to `SpiffeSslContextFactory.SslContextOptions`, so an `SSLContext` can verify peer SPIFFE IDs with a custom `SpiffeIdVerifier` instead of a fixed set of accepted SPIFFE IDs ### Fixed diff --git a/java-spiffe-provider/README.md b/java-spiffe-provider/README.md index 2b523302..2e8a8e21 100644 --- a/java-spiffe-provider/README.md +++ b/java-spiffe-provider/README.md @@ -46,6 +46,37 @@ Alternatively, a different Workload API address can be used by passing it to the See [HttpsClient example](src/test/java/io/spiffe/provider/examples/mtls/HttpsClient.java) that defines a Supplier for providing the list of SPIFFE IDs from a file. +### Verify peer SPIFFE IDs with a custom verifier + +When the accepted SPIFFE IDs are not known in advance as a fixed set, configure a `SpiffeIdVerifier` instead of a +Supplier of SPIFFE IDs. The verifier is called during each TLS handshake, after the peer's certificate chain has been +verified against the X.509 bundles, with the peer's SPIFFE ID and certificate chain. Throwing a +`SpiffeVerificationException` rejects the peer and fails the handshake. For example, to accept any workload in the +`example.org` trust domain: + +``` + TrustDomain trustDomain = TrustDomain.parse("example.org"); + SpiffeIdVerifier memberOfTrustDomain = (spiffeId, verifiedChain) -> { + if (!spiffeId.memberOf(trustDomain)) { + throw new SpiffeVerificationException( + String.format("SPIFFE ID %s is not a member of trust domain %s", spiffeId, trustDomain)); + } + }; + + SslContextOptions options = SslContextOptions + .builder() + .x509Source(source) + .spiffeIdVerifier(memberOfTrustDomain) + .build(); + + SSLContext sslContext = SpiffeSslContextFactory.getSslContext(options); +``` + +A `spiffeIdVerifier` cannot be combined with `acceptedSpiffeIdsSupplier` or `acceptAnySpiffeId`: `getSslContext` +throws an `IllegalArgumentException` if the options configure either of them together with a verifier. A +`SpiffeTrustManager` can also be created directly with a `SpiffeIdVerifier`, see +[Configure it programmatically](#configure-it-programmatically). + ## Plug Java SPIFFE Provider into Java Security architecture Java Security Providers are configured in the master security properties file `/jre/lib/security/java.security`. diff --git a/java-spiffe-provider/src/main/java/io/spiffe/provider/SpiffeSslContextFactory.java b/java-spiffe-provider/src/main/java/io/spiffe/provider/SpiffeSslContextFactory.java index 7708e208..0241cddd 100644 --- a/java-spiffe-provider/src/main/java/io/spiffe/provider/SpiffeSslContextFactory.java +++ b/java-spiffe-provider/src/main/java/io/spiffe/provider/SpiffeSslContextFactory.java @@ -30,11 +30,16 @@ private SpiffeSslContextFactory() { * that are backed by the Workload API via an {@link DefaultX509Source}. * * @param options {@link SslContextOptions}. The option {@link DefaultX509Source} must be not null. - * If the option acceptedSpiffeIdsSupplier is not provided, the Set of accepted SPIFFE IDs - * is read from the Security or System Property ssl.spiffe.accept. + * The SPIFFE IDs of the peers are verified with the spiffeIdVerifier, checked + * against the acceptedSpiffeIdsSupplier, or accepted if acceptAnySpiffeId + * is set. One of them must be configured. * If the sslProtocol is not provided, the default TLSv1.2 is used. * @return an initialized {@link SSLContext} - * @throws IllegalArgumentException if the {@link DefaultX509Source} is not provided in the options + * @throws IllegalArgumentException if the {@link DefaultX509Source} is not provided in the options, + * if neither a spiffeIdVerifier, an + * acceptedSpiffeIdsSupplier nor acceptAnySpiffeId + * is configured, or if a spiffeIdVerifier is configured together + * with an acceptedSpiffeIdsSupplier or acceptAnySpiffeId * @throws NoSuchAlgorithmException if there is a problem creating the SSL context * @throws KeyManagementException if there is a problem initializing the SSL context */ @@ -46,9 +51,16 @@ public static SSLContext getSslContext(SslContextOptions options) throw new IllegalArgumentException("x509Source option must not be null, an X.509 Source must be provided"); } - if (!options.acceptAnySpiffeId && options.acceptedSpiffeIdsSupplier == null) { - throw new IllegalArgumentException("SSL context should be configured either with a Supplier " + - "of accepted SPIFFE IDs or with acceptAnySpiffeId=true"); + if (options.spiffeIdVerifier != null + && (options.acceptAnySpiffeId || options.acceptedSpiffeIdsSupplier != null)) { + throw new IllegalArgumentException("SSL context should not be configured with a SPIFFE ID verifier " + + "together with a Supplier of accepted SPIFFE IDs or with acceptAnySpiffeId=true"); + } + + if (options.spiffeIdVerifier == null + && !options.acceptAnySpiffeId && options.acceptedSpiffeIdsSupplier == null) { + throw new IllegalArgumentException("SSL context should be configured either with a SPIFFE ID verifier, " + + "with a Supplier of accepted SPIFFE IDs or with acceptAnySpiffeId=true"); } final SSLContext sslContext = newSslContext(options); @@ -60,6 +72,10 @@ public static SSLContext getSslContext(SslContextOptions options) } private static TrustManager[] newTrustManager(final SslContextOptions options) { + if (options.spiffeIdVerifier != null) { + return new TrustManager[]{new SpiffeTrustManager(options.x509Source, options.spiffeIdVerifier)}; + } + if (options.acceptAnySpiffeId) { return new SpiffeTrustManagerFactory().engineGetTrustManagersAcceptAnySpiffeId(options.x509Source); } @@ -95,6 +111,10 @@ private static SSLContext newSslContext(final SslContextOptions options) throws *

* acceptAnySpiffeId Flag that indicates that any {@link SpiffeId} will be accepted for a * secure socket connection. This config overrules the acceptedSpiffeIdsSupplier property. + *

+ * spiffeIdVerifier A {@link SpiffeIdVerifier} that decides whether the {@link SpiffeId} of a peer + * is accepted for a secure socket connection. It cannot be combined with acceptedSpiffeIdsSupplier + * or acceptAnySpiffeId. */ public static class SslContextOptions { @@ -102,16 +122,27 @@ public static class SslContextOptions { private X509Source x509Source; private Supplier> acceptedSpiffeIdsSupplier; private boolean acceptAnySpiffeId; + private SpiffeIdVerifier spiffeIdVerifier; public SslContextOptions( final String sslProtocol, final X509Source x509Source, final Supplier> acceptedSpiffeIdsSupplier, final boolean acceptAnySpiffeId) { + this(sslProtocol, x509Source, acceptedSpiffeIdsSupplier, acceptAnySpiffeId, null); + } + + public SslContextOptions( + final String sslProtocol, + final X509Source x509Source, + final Supplier> acceptedSpiffeIdsSupplier, + final boolean acceptAnySpiffeId, + final SpiffeIdVerifier spiffeIdVerifier) { this.x509Source = x509Source; this.acceptedSpiffeIdsSupplier = acceptedSpiffeIdsSupplier; this.sslProtocol = sslProtocol; this.acceptAnySpiffeId = acceptAnySpiffeId; + this.spiffeIdVerifier = spiffeIdVerifier; } public String getSslProtocol() { @@ -130,6 +161,10 @@ public boolean isAcceptAnySpiffeId() { return acceptAnySpiffeId; } + public SpiffeIdVerifier getSpiffeIdVerifier() { + return spiffeIdVerifier; + } + public static SslContextOptionsBuilder builder() { return new SslContextOptionsBuilder(); } @@ -139,6 +174,7 @@ public static class SslContextOptionsBuilder { private X509Source x509Source; private Supplier> acceptedSpiffeIdsSupplier; private boolean acceptAnySpiffeId; + private SpiffeIdVerifier spiffeIdVerifier; SslContextOptionsBuilder() { } @@ -164,12 +200,18 @@ public SslContextOptionsBuilder acceptAnySpiffeId() { return this; } + public SslContextOptionsBuilder spiffeIdVerifier(SpiffeIdVerifier spiffeIdVerifier) { + this.spiffeIdVerifier = spiffeIdVerifier; + return this; + } + public SslContextOptions build() { return new SslContextOptions( sslProtocol, x509Source, acceptedSpiffeIdsSupplier, - acceptAnySpiffeId + acceptAnySpiffeId, + spiffeIdVerifier ); } } @@ -182,12 +224,13 @@ public boolean equals(Object o) { return acceptAnySpiffeId == that.acceptAnySpiffeId && Objects.equals(sslProtocol, that.sslProtocol) && Objects.equals(x509Source, that.x509Source) - && Objects.equals(acceptedSpiffeIdsSupplier, that.acceptedSpiffeIdsSupplier); + && Objects.equals(acceptedSpiffeIdsSupplier, that.acceptedSpiffeIdsSupplier) + && Objects.equals(spiffeIdVerifier, that.spiffeIdVerifier); } @Override public int hashCode() { - return Objects.hash(sslProtocol, x509Source, acceptedSpiffeIdsSupplier, acceptAnySpiffeId); + return Objects.hash(sslProtocol, x509Source, acceptedSpiffeIdsSupplier, acceptAnySpiffeId, spiffeIdVerifier); } @Override @@ -197,6 +240,7 @@ public String toString() { ", x509Source=" + x509Source + ", acceptedSpiffeIdsSupplier=" + acceptedSpiffeIdsSupplier + ", acceptAnySpiffeId=" + acceptAnySpiffeId + + ", spiffeIdVerifier=" + spiffeIdVerifier + ')'; } } diff --git a/java-spiffe-provider/src/test/java/io/spiffe/provider/SpiffeSslContextFactoryTest.java b/java-spiffe-provider/src/test/java/io/spiffe/provider/SpiffeSslContextFactoryTest.java index 7a5cfe63..bd0d2715 100644 --- a/java-spiffe-provider/src/test/java/io/spiffe/provider/SpiffeSslContextFactoryTest.java +++ b/java-spiffe-provider/src/test/java/io/spiffe/provider/SpiffeSslContextFactoryTest.java @@ -1,15 +1,35 @@ package io.spiffe.provider; +import io.spiffe.bundle.x509bundle.X509Bundle; +import io.spiffe.exception.BundleNotFoundException; +import io.spiffe.spiffeid.SpiffeId; +import io.spiffe.spiffeid.TrustDomain; +import io.spiffe.svid.x509svid.X509Svid; +import io.spiffe.utils.CertAndKeyPair; import io.spiffe.workloadapi.X509Source; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLEngineResult.HandshakeStatus; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +import java.nio.ByteBuffer; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import static io.spiffe.utils.X509CertificateTestUtils.createCertificate; +import static io.spiffe.utils.X509CertificateTestUtils.createRootCA; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; class SpiffeSslContextFactoryTest { @@ -118,8 +138,199 @@ void getSslContext_noSupplierAndAcceptAnyNotSet() { } catch (NoSuchAlgorithmException | KeyManagementException e) { fail(e); } catch (IllegalArgumentException e) { - assertEquals("SSL context should be configured either with a Supplier " + - "of accepted SPIFFE IDs or with acceptAnySpiffeId=true", e.getMessage()); + assertEquals("SSL context should be configured either with a SPIFFE ID verifier, " + + "with a Supplier of accepted SPIFFE IDs or with acceptAnySpiffeId=true", e.getMessage()); + } + } + + @Test + void getSslContext_withSpiffeIdVerifier() { + SpiffeIdVerifier spiffeIdVerifier = (spiffeId, verifiedChain) -> { + }; + SpiffeSslContextFactory.SslContextOptions options = + SpiffeSslContextFactory.SslContextOptions + .builder() + .x509Source(x509Source) + .spiffeIdVerifier(spiffeIdVerifier) + .build(); + + assertSame(spiffeIdVerifier, options.getSpiffeIdVerifier()); + try { + assertNotNull(SpiffeSslContextFactory.getSslContext(options)); + } catch (NoSuchAlgorithmException | KeyManagementException e) { + fail(e); + } + } + + @Test + void getSslContext_spiffeIdVerifierAndSupplierOfSpiffeIds() { + SpiffeSslContextFactory.SslContextOptions options = + SpiffeSslContextFactory.SslContextOptions + .builder() + .x509Source(x509Source) + .spiffeIdVerifier((spiffeId, verifiedChain) -> { + }) + .acceptedSpiffeIdsSupplier(Collections::emptySet) + .build(); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> SpiffeSslContextFactory.getSslContext(options)); + assertEquals("SSL context should not be configured with a SPIFFE ID verifier " + + "together with a Supplier of accepted SPIFFE IDs or with acceptAnySpiffeId=true", e.getMessage()); + } + + @Test + void getSslContext_spiffeIdVerifierAndAcceptAny() { + SpiffeSslContextFactory.SslContextOptions options = + SpiffeSslContextFactory.SslContextOptions + .builder() + .x509Source(x509Source) + .spiffeIdVerifier((spiffeId, verifiedChain) -> { + }) + .acceptAnySpiffeId() + .build(); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> SpiffeSslContextFactory.getSslContext(options)); + assertEquals("SSL context should not be configured with a SPIFFE ID verifier " + + "together with a Supplier of accepted SPIFFE IDs or with acceptAnySpiffeId=true", e.getMessage()); + } + + @Test + void getSslContext_spiffeIdVerifierIsCalledWithPeerSpiffeIdAndChain() throws Exception { + TrustDomain trustDomain = TrustDomain.parse("example.org"); + CertAndKeyPair rootCa = createRootCA("C = US, O = SPIFFE", trustDomain.toIdString()); + X509Source clientSource = newX509Source(trustDomain, rootCa, "client"); + X509Source serverSource = newX509Source(trustDomain, rootCa, "server"); + + Map verifiedPeers = new HashMap<>(); + SpiffeIdVerifier recordingVerifier = verifiedPeers::put; + + SSLContext clientContext = SpiffeSslContextFactory.getSslContext( + SpiffeSslContextFactory.SslContextOptions.builder() + .x509Source(clientSource) + .spiffeIdVerifier(recordingVerifier) + .build()); + SSLContext serverContext = SpiffeSslContextFactory.getSslContext( + SpiffeSslContextFactory.SslContextOptions.builder() + .x509Source(serverSource) + .spiffeIdVerifier(recordingVerifier) + .build()); + + handshake(clientContext, serverContext); + + assertEquals(2, verifiedPeers.size()); + assertArrayEquals(serverSource.getX509Svid().getChainArray(), + verifiedPeers.get(SpiffeId.parse("spiffe://example.org/server"))); + assertArrayEquals(clientSource.getX509Svid().getChainArray(), + verifiedPeers.get(SpiffeId.parse("spiffe://example.org/client"))); + } + + @Test + void getSslContext_spiffeIdVerifierRejectsPeer() throws Exception { + TrustDomain trustDomain = TrustDomain.parse("example.org"); + CertAndKeyPair rootCa = createRootCA("C = US, O = SPIFFE", trustDomain.toIdString()); + X509Source clientSource = newX509Source(trustDomain, rootCa, "client"); + X509Source serverSource = newX509Source(trustDomain, rootCa, "server"); + + SSLContext clientContext = SpiffeSslContextFactory.getSslContext( + SpiffeSslContextFactory.SslContextOptions.builder() + .x509Source(clientSource) + .spiffeIdVerifier((spiffeId, verifiedChain) -> { + throw new SpiffeVerificationException( + String.format("SPIFFE ID %s is not authorized", spiffeId)); + }) + .build()); + SSLContext serverContext = SpiffeSslContextFactory.getSslContext( + SpiffeSslContextFactory.SslContextOptions.builder() + .x509Source(serverSource) + .acceptAnySpiffeId() + .build()); + + SSLHandshakeException e = assertThrows(SSLHandshakeException.class, + () -> handshake(clientContext, serverContext)); + Throwable cause = e; + while (cause != null && !(cause instanceof SpiffeVerificationException)) { + cause = cause.getCause(); + } + assertNotNull(cause, "the handshake should fail because the SPIFFE ID verifier rejects the server"); + assertEquals("SPIFFE ID spiffe://example.org/server is not authorized", cause.getMessage()); + } + + private static X509Source newX509Source(TrustDomain trustDomain, CertAndKeyPair rootCa, String path) + throws Exception { + CertAndKeyPair leaf = createCertificate("C = US, O = SPIRE", "C = US, O = SPIFFE", + SpiffeId.fromSegments(trustDomain, path).toString(), rootCa, false); + X509Svid svid = X509Svid.parseRaw( + leaf.getCertificate().getEncoded(), + leaf.getKeyPair().getPrivate().getEncoded()); + X509Bundle bundle = new X509Bundle(trustDomain, Collections.singleton(rootCa.getCertificate())); + + return new X509Source() { + @Override + public X509Svid getX509Svid() { + return svid; + } + + @Override + public X509Bundle getBundleForTrustDomain(TrustDomain bundleTrustDomain) + throws BundleNotFoundException { + return bundle.getBundleForTrustDomain(bundleTrustDomain); + } + + @Override + public void close() { + } + }; + } + + // Runs a mutual TLS handshake between two in-memory SSLEngines. + private static void handshake(SSLContext clientContext, SSLContext serverContext) throws SSLException { + SSLEngine client = clientContext.createSSLEngine(); + client.setUseClientMode(true); + SSLEngine server = serverContext.createSSLEngine(); + server.setUseClientMode(false); + server.setNeedClientAuth(true); + + int packetBufferSize = client.getSession().getPacketBufferSize(); + int applicationBufferSize = client.getSession().getApplicationBufferSize(); + ByteBuffer clientToServer = ByteBuffer.allocate(packetBufferSize); + ByteBuffer serverToClient = ByteBuffer.allocate(packetBufferSize); + ByteBuffer clientIn = ByteBuffer.allocate(applicationBufferSize); + ByteBuffer serverIn = ByteBuffer.allocate(applicationBufferSize); + ByteBuffer empty = ByteBuffer.allocate(0); + + client.beginHandshake(); + server.beginHandshake(); + for (int i = 0; i < 100 && (isHandshaking(client) || isHandshaking(server)); i++) { + client.wrap(empty, clientToServer); + runDelegatedTasks(client); + server.wrap(empty, serverToClient); + runDelegatedTasks(server); + + clientToServer.flip(); + serverToClient.flip(); + client.unwrap(serverToClient, clientIn); + runDelegatedTasks(client); + server.unwrap(clientToServer, serverIn); + runDelegatedTasks(server); + clientToServer.compact(); + serverToClient.compact(); + } + + if (isHandshaking(client) || isHandshaking(server)) { + fail("TLS handshake did not complete"); + } + } + + private static boolean isHandshaking(SSLEngine engine) { + return engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING; + } + + private static void runDelegatedTasks(SSLEngine engine) { + Runnable task; + while ((task = engine.getDelegatedTask()) != null) { + task.run(); } } } \ No newline at end of file