From dc7c7bf897ad1a2c92079b544e03b2c92549b34b Mon Sep 17 00:00:00 2001 From: Udit Agarwal Date: Mon, 16 Nov 2026 19:23:33 +0000 Subject: [PATCH] Validate EPP client certs and forward hostnames Validate incoming EPP client certificate chains against the JVM default truststore after TLS handshake completion and forward the result along with extracted DNS hostnames to Nomulus, preparing for hostname-based EPP login authentication while keeping existing fingerprint-pinned connections working unchanged. - Add X.509 helpers in X509Utils for PKIX chain validation (with online revocation disabled, intermediate/leaf EKU and SHA-1 checks, 32 KB chain size and path-length bounds, and checkServerTrusted so publicly trusted serverAuth-only TLS certs are accepted), ASCII non-trailing-dot SAN dNSName hostname extraction (excluding wildcards and omitting Subject CN fallback per RFC 9525 section 6.2), and 4 KB-bounded header formatting. - Run chain validation and hostname extraction in SslServerInitializer without failing handshakes on untrusted chains, and log the validation status, failure reason, and extracted hostnames in --SSL Information--. - Forward X-SSL-Certificate-Chain-Validated and X-SSL-Certificate-Hostnames from both the integrated EPP server and proxy EppServiceHandler. BUG=http://b/573176897 --- .../eppserver/handler/EppServiceHandler.java | 21 + .../handler/EppServiceHandlerTest.java | 163 ++ .../handler/SslServerInitializer.java | 204 ++- .../handler/SslInitializerTestUtils.java | 191 ++- .../handler/SslServerInitializerTest.java | 860 +++++++++- .../proxy/handler/EppServiceHandler.java | 21 + .../java/google/registry/proxy/TestUtils.java | 1 + .../proxy/handler/EppServiceHandlerTest.java | 325 ++++ .../registry/util/ProxyHttpHeaders.java | 17 + .../java/google/registry/util/X509Utils.java | 373 +++++ .../google/registry/util/X509UtilsTest.java | 1463 +++++++++++++++++ 11 files changed, 3588 insertions(+), 51 deletions(-) create mode 100644 util/src/test/java/google/registry/util/X509UtilsTest.java diff --git a/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java b/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java index d3f8f9562c5..61440773f23 100644 --- a/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java +++ b/core/src/main/java/google/registry/eppserver/handler/EppServiceHandler.java @@ -14,10 +14,14 @@ package google.registry.eppserver.handler; +import static com.google.common.base.MoreObjects.firstNonNull; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_HOSTNAMES_KEY; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_PROMISE_KEY; import static google.registry.util.GcpJsonFormatter.setCurrentRequest; import static google.registry.util.GcpJsonFormatter.setCurrentTraceId; import static google.registry.util.GcpJsonFormatter.unsetCurrentRequest; +import static google.registry.util.X509Utils.formatHostnamesHeader; import static google.registry.util.X509Utils.getCertificateHash; import static java.nio.charset.StandardCharsets.UTF_8; @@ -47,6 +51,7 @@ import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.cert.X509Certificate; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; @@ -82,6 +87,8 @@ public class EppServiceHandler extends SimpleChannelInboundHandler { private final int preLoginReadTimeoutSeconds; private String sslClientCertificateHash; + private boolean sslClientCertificateChainValidated; + private Optional sslClientCertificateHostnamesHeader = Optional.empty(); private String clientAddress; private String registrarId; // The clID extracted from login private String authenticatedRegistrarId; // The verified registrar ID after successful login @@ -158,6 +165,15 @@ private void onSslHandshakeComplete(ChannelHandlerContext ctx, X509Certificate c } ipAcquired = true; + sslClientCertificateChainValidated = + firstNonNull(ctx.channel().attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get(), false); + sslClientCertificateHostnamesHeader = + sslClientCertificateChainValidated + ? formatHostnamesHeader( + ctx.channel().attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get(), + sslClientCertificateHash) + : Optional.empty(); + // Schedule login timeout preLoginTimeoutTask = ctx.executor() @@ -241,6 +257,11 @@ private FakeHttpServletRequest buildServletRequest(String xml) { req.setRequestUri("/_dr/epp"); req.setBody(xml.getBytes(UTF_8)); req.setHeader(ProxyHttpHeaders.CERTIFICATE_HASH, sslClientCertificateHash); + req.setHeader( + ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, + Boolean.toString(sslClientCertificateChainValidated)); + sslClientCertificateHostnamesHeader.ifPresent( + header -> req.setHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, header)); req.setHeader(ProxyHttpHeaders.IP_ADDRESS, clientAddress); if (registrarId != null) { req.setHeader(ProxyHttpHeaders.REGISTRAR_ID, registrarId); diff --git a/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java b/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java index 689183743dc..e2c812c5901 100644 --- a/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java +++ b/core/src/test/java/google/registry/eppserver/handler/EppServiceHandlerTest.java @@ -14,9 +14,15 @@ package google.registry.eppserver.handler; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import static google.registry.eppserver.handler.EppServiceHandler.REMOTE_ADDRESS_KEY; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_HOSTNAMES_KEY; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_PROMISE_KEY; +import static google.registry.util.X509Utils.MAX_HOSTNAMES_HEADER_BYTES; +import static google.registry.util.X509Utils.formatHostnamesHeader; +import static google.registry.util.X509Utils.getCertificateHash; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; @@ -29,6 +35,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.common.collect.ImmutableList; import google.registry.eppserver.metric.FrontendMetrics; import google.registry.eppserver.quota.EppServerQuotaManager; import google.registry.eppserver.quota.LocalConnectionLimiter; @@ -44,6 +51,7 @@ import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.util.Attribute; +import io.netty.util.DefaultAttributeMap; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.ImmediateEventExecutor; @@ -54,6 +62,8 @@ import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import java.util.stream.IntStream; +import javax.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -81,9 +91,11 @@ class EppServiceHandlerTest { private EppServiceHandler handler; private DefaultPromise certPromise; + private DefaultAttributeMap attributeMap; @BeforeEach void setUp() { + attributeMap = new DefaultAttributeMap(); handler = new EppServiceHandler( new byte[] {'h', 'e', 'l', 'l', 'o'}, @@ -99,6 +111,9 @@ void setUp() { when(ctx.channel()).thenReturn(channel); when(ctx.executor()).thenReturn(executor); lenient().when(channel.isActive()).thenReturn(true); + lenient() + .when(channel.attr(any())) + .thenAnswer(invocation -> attributeMap.attr(invocation.getArgument(0))); doAnswer( invocation -> { @@ -449,4 +464,152 @@ void testFallbackToSocketIpAddress_fails_closesConnection() throws Exception { // Verify it logged error and closed connection verify(ctx).close(); } + + private ArgumentCaptor setUpHandshakeWithChainAttrs( + boolean chainValidated, @Nullable ImmutableList hostnames) throws Exception { + certPromise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); + attributeMap.attr(CLIENT_CERTIFICATE_PROMISE_KEY).set(certPromise); + attributeMap.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).set(chainValidated); + if (hostnames != null) { + attributeMap.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).set(hostnames); + } + + handler.channelActive(ctx); + + attributeMap.attr(REMOTE_ADDRESS_KEY).set("192.168.1.1"); + when(certificate.getEncoded()).thenReturn(new byte[] {1, 2, 3}); + when(localConnectionLimiter.acquireIp(any(String.class))).thenReturn(true); + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(FakeHttpServletRequest.class); + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.getWriter().write(""); + return null; + }) + .when(requestHandler) + .handleRequest(requestCaptor.capture(), any(FakeHttpServletResponse.class)); + + certPromise.setSuccess(certificate); + return requestCaptor; + } + + @Test + void testForwardsCertificateChainValidatedAndHostnamesHeaders() throws Exception { + ArgumentCaptor requestCaptor = + setUpHandshakeWithChainAttrs( + true, ImmutableList.of("epp1.example.tld", "epp2.example.tld")); + + String eppLoginXml = "RegistrarA"; + handler.channelRead0(ctx, Unpooled.wrappedBuffer(eppLoginXml.getBytes(UTF_8))); + + String expectedCertHash = getCertificateHash(certificate); + assertThat(requestCaptor.getAllValues()).hasSize(2); + for (FakeHttpServletRequest capturedRequest : requestCaptor.getAllValues()) { + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(expectedCertHash); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("true"); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)) + .isEqualTo("epp1.example.tld,epp2.example.tld"); + } + } + + @Test + void testOmitsCertificateHostnamesHeaderWhenEmpty() throws Exception { + ArgumentCaptor requestCaptor = + setUpHandshakeWithChainAttrs(true, ImmutableList.of()); + + FakeHttpServletRequest capturedRequest = requestCaptor.getValue(); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(getCertificateHash(certificate)); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("true"); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isNull(); + } + + @Test + void testOmitsCertificateHostnamesHeaderWhenHostnamesAttrUnset() throws Exception { + ArgumentCaptor requestCaptor = setUpHandshakeWithChainAttrs(true, null); + + FakeHttpServletRequest capturedRequest = requestCaptor.getValue(); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(getCertificateHash(certificate)); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("true"); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isNull(); + } + + @Test + void testForwardsChainValidatedFalseWhenChainNotValidated() throws Exception { + ArgumentCaptor requestCaptor = + setUpHandshakeWithChainAttrs(false, ImmutableList.of("epp.untrusted.tld")); + + String eppLoginXml = "RegistrarA"; + handler.channelRead0(ctx, Unpooled.wrappedBuffer(eppLoginXml.getBytes(UTF_8))); + + String expectedCertHash = getCertificateHash(certificate); + assertThat(requestCaptor.getAllValues()).hasSize(2); + for (FakeHttpServletRequest capturedRequest : requestCaptor.getAllValues()) { + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(expectedCertHash); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("false"); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isNull(); + } + } + + @Test + void testDefaultsChainValidatedToFalseWhenAttributesUnset() throws Exception { + when(idTokenSupplier.get()).thenReturn("fake_id_token"); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(FakeHttpServletRequest.class); + doAnswer( + invocation -> { + FakeHttpServletResponse rsp = invocation.getArgument(1); + rsp.getWriter().write(""); + return null; + }) + .when(requestHandler) + .handleRequest(requestCaptor.capture(), any(FakeHttpServletResponse.class)); + + setUpSuccessfulHandshake(); + + FakeHttpServletRequest capturedRequest = requestCaptor.getValue(); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(getCertificateHash(certificate)); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("false"); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isNull(); + } + + @Test + void testTruncatesOversizedCertificateHostnamesHeader() throws Exception { + ImmutableList oversizedHostnames = + IntStream.range(0, 200) + .mapToObj(i -> String.format("epp-host-%03d.registrar.example.tld", i)) + .collect(toImmutableList()); + ArgumentCaptor requestCaptor = + setUpHandshakeWithChainAttrs(true, oversizedHostnames); + + String eppLoginXml = "RegistrarA"; + handler.channelRead0(ctx, Unpooled.wrappedBuffer(eppLoginXml.getBytes(UTF_8))); + + String expectedCertHash = getCertificateHash(certificate); + String expectedHeader = + formatHostnamesHeader(oversizedHostnames, expectedCertHash).orElseThrow(); + assertThat(expectedHeader.length()).isAtMost(MAX_HOSTNAMES_HEADER_BYTES); + assertThat(expectedHeader.length()).isLessThan(String.join(",", oversizedHostnames).length()); + assertThat(requestCaptor.getAllValues()).hasSize(2); + for (FakeHttpServletRequest capturedRequest : requestCaptor.getAllValues()) { + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(expectedCertHash); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("true"); + assertThat(capturedRequest.getHeader(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)) + .isEqualTo(expectedHeader); + } + } } diff --git a/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java b/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java index 8348cdd4920..8d582053f89 100644 --- a/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java +++ b/networking/src/main/java/google/registry/networking/handler/SslServerInitializer.java @@ -15,10 +15,17 @@ package google.registry.networking.handler; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static google.registry.util.X509Utils.extractHostnames; import static google.registry.util.X509Utils.getCertificateHash; +import static google.registry.util.X509Utils.getDefaultTrustManager; +import static google.registry.util.X509Utils.validateCertificateChain; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.flogger.FluentLogger; +import google.registry.util.X509Utils.CertificateChainValidationResult; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler.Sharable; @@ -36,12 +43,17 @@ import io.netty.util.concurrent.Promise; import java.security.PrivateKey; import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; +import java.util.Optional; import java.util.function.Supplier; +import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; +import javax.net.ssl.X509TrustManager; /** * Adds a server side SSL handler to the channel pipeline. @@ -53,9 +65,11 @@ * *

The ssl handler added can require client authentication, but it uses an {@link * InsecureTrustManagerFactory}, which accepts any ssl certificate presented by the client, as long - * as the client uses the corresponding private key to establish SSL handshake. The client - * certificate hash will be passed along to the service as an HTTP header for verification (not - * handled by this handler). + * as the client uses the corresponding private key to establish SSL handshake. After handshake + * completion, this handler validates the presented certificate chain against the configured + * truststore (without failing the handshake for legacy hash-pinned certificates) and extracts + * canonicalized DNS hostnames when chain validation succeeds so downstream handlers can forward the + * certificate hash, chain-validation status, and hostnames as HTTP headers. */ @Sharable public class SslServerInitializer extends ChannelInitializer { @@ -67,6 +81,22 @@ public class SslServerInitializer extends ChannelInitializer< public static final AttributeKey> CLIENT_CERTIFICATE_PROMISE_KEY = AttributeKey.valueOf("CLIENT_CERTIFICATE_PROMISE_KEY"); + /** + * Attribute key to whether the client certificate chain was validated against trusted root CAs, + * set before {@link #CLIENT_CERTIFICATE_PROMISE_KEY} completes successfully. + */ + public static final AttributeKey CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY = + AttributeKey.valueOf("CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY"); + + /** + * Attribute key to the canonicalized, deduplicated DNS hostnames (excluding wildcard names) + * extracted from a validated client certificate's Subject Alternative Name {@code dNSName} + * entries, set before {@link #CLIENT_CERTIFICATE_PROMISE_KEY} completes successfully. Empty when + * chain validation fails or the certificate contains no valid hostnames. + */ + public static final AttributeKey> CLIENT_CERTIFICATE_HOSTNAMES_KEY = + AttributeKey.valueOf("CLIENT_CERTIFICATE_HOSTNAMES_KEY"); + /** * The list of cipher suites that are currently acceptable to create a successful handshake. * @@ -94,6 +124,9 @@ public class SslServerInitializer extends ChannelInitializer< private static final ImmutableList SUPPORTED_TLS_VERSIONS = ImmutableList.of("TLSv1.3", "TLSv1.2"); + private static final int MAX_LOGGED_HOSTNAMES = 10; + private static final int MAX_LOGGED_FAILURE_REASON_CHARS = 512; + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final boolean requireClientCert; // TODO(jianglai): Always validate client certs (if required). @@ -103,6 +136,7 @@ public class SslServerInitializer extends ChannelInitializer< // change when the artifacts on GCS changes. private final Supplier privateKeySupplier; private final Supplier> certificatesSupplier; + private final Optional trustManager; public SslServerInitializer( boolean requireClientCert, @@ -110,15 +144,37 @@ public SslServerInitializer( SslProvider sslProvider, Supplier privateKeySupplier, Supplier> certificatesSupplier) { + this( + requireClientCert, + validateClientCert, + sslProvider, + privateKeySupplier, + certificatesSupplier, + requireClientCert ? Optional.of(getDefaultTrustManager()) : Optional.empty()); + } + + @VisibleForTesting + SslServerInitializer( + boolean requireClientCert, + boolean validateClientCert, + SslProvider sslProvider, + Supplier privateKeySupplier, + Supplier> certificatesSupplier, + Optional trustManager) { logger.atInfo().log("Server SSL Provider: %s", sslProvider); checkArgument( requireClientCert || !validateClientCert, "Cannot validate client certificate if client certificate is not required."); + checkNotNull(trustManager, "trustManager"); + checkArgument( + !requireClientCert || trustManager.isPresent(), + "Trust manager is required when client certificates are required."); this.requireClientCert = requireClientCert; this.validateClientCert = validateClientCert; this.sslProvider = sslProvider; this.privateKeySupplier = privateKeySupplier; this.certificatesSupplier = certificatesSupplier; + this.trustManager = trustManager; } @Override @@ -146,48 +202,85 @@ protected void initChannel(C channel) throws Exception { .addListener( future -> { if (future.isSuccess()) { - SSLSession sslSession = sslHandler.engine().getSession(); - X509Certificate clientCertificate = - (X509Certificate) sslSession.getPeerCertificates()[0]; - PublicKey clientPublicKey = clientCertificate.getPublicKey(); - // Note that for non-RSA keys the length would be -1. - int clientCertificateLength = -1; - if (clientPublicKey instanceof RSAPublicKey rsaPublicKey) { - clientCertificateLength = rsaPublicKey.getModulus().bitLength(); - } - logger.atInfo().log( - """ - --SSL Information-- - Client Certificate Hash: %s - SSL Protocol: %s - Cipher Suite: %s - Not Before: %s - Not After: %s - Client Certificate Type: %s - Client Certificate Length: %s - """, - getCertificateHash(clientCertificate), - sslSession.getProtocol(), - sslSession.getCipherSuite(), - clientCertificate.getNotBefore(), - clientCertificate.getNotAfter(), - clientPublicKey.getClass().getName(), - clientCertificateLength); try { - clientCertificate.checkValidity(); - } catch (CertificateNotYetValidException | CertificateExpiredException e) { - logger.atWarning().withCause(e).log( - "Client certificate is not valid.\nHash: %s", - getCertificateHash(clientCertificate)); - if (validateClientCert) { - Promise unusedPromise = - clientCertificatePromise.setFailure(e); - ChannelFuture unusedFuture2 = channel.close(); - return; + SSLSession sslSession = sslHandler.engine().getSession(); + Certificate[] peerCertificates = sslSession.getPeerCertificates(); + X509Certificate clientCertificate = (X509Certificate) peerCertificates[0]; + String clientCertificateHash = getCertificateHash(clientCertificate); + PublicKey clientPublicKey = clientCertificate.getPublicKey(); + // Note that for non-RSA keys the length would be -1. + int clientCertificateLength = -1; + if (clientPublicKey instanceof RSAPublicKey rsaPublicKey) { + clientCertificateLength = rsaPublicKey.getModulus().bitLength(); + } + CertificateException validityException = null; + try { + clientCertificate.checkValidity(); + } catch (CertificateNotYetValidException | CertificateExpiredException e) { + validityException = e; } + // Note: initChannel builds a fresh SslContext per connection today, so + // cross-connection TLS session resumption does not occur. If SslContext is + // ever cached across connections, BoringSSL (SslProvider.OPENSSL) omits + // intermediate certificates on resumed server sessions + // (SSL_get_peer_cert_chain returns empty), which would flip chainValidated + // to false on resumed 3+ tier chains unless resumption/tickets are disabled + // for mTLS or the validation outcome is cached in SSLSession. + CertificateChainValidationResult validationResult = + validityException != null + ? CertificateChainValidationResult.failed( + validityException.toString()) + : validateCertificateChain( + peerCertificates, trustManager.orElseThrow()); + boolean chainValidated = validationResult.valid(); + ImmutableList hostnames = + chainValidated + ? extractHostnames(clientCertificate) + : ImmutableList.of(); + logger.atInfo().log( + """ + --SSL Information-- + Client Certificate Hash: %s + Client Certificate Chain Validated: %s + Client Certificate Chain Failure Reason: %s + Client Certificate Hostnames: %s + SSL Protocol: %s + Cipher Suite: %s + Not Before: %s + Not After: %s + Client Certificate Type: %s + Client Certificate Length: %s + """, + clientCertificateHash, + chainValidated, + formatFailureReasonForLog(validationResult.failureReason()), + formatHostnamesForLog(hostnames), + sslSession.getProtocol(), + sslSession.getCipherSuite(), + clientCertificate.getNotBefore(), + clientCertificate.getNotAfter(), + clientPublicKey.getClass().getName(), + clientCertificateLength); + if (validityException != null) { + logger.atWarning().withCause(validityException).log( + "Client certificate is not valid.\nHash: %s", clientCertificateHash); + if (validateClientCert) { + Promise unusedPromise = + clientCertificatePromise.setFailure(validityException); + ChannelFuture unusedFuture2 = channel.close(); + return; + } + } + channel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).set(chainValidated); + channel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).set(hostnames); + Promise unusedPromise = + clientCertificatePromise.setSuccess(clientCertificate); + } catch (SSLPeerUnverifiedException | RuntimeException e) { + logger.atWarning().withCause(e).log( + "Failed to inspect client certificate."); + boolean unusedFailed = clientCertificatePromise.tryFailure(e); + ChannelFuture unusedFuture2 = channel.close(); } - Promise unusedPromise = - clientCertificatePromise.setSuccess(clientCertificate); } else { Promise unusedPromise = clientCertificatePromise.setFailure(future.cause()); @@ -197,4 +290,31 @@ protected void initChannel(C channel) throws Exception { } channel.pipeline().addLast(sslHandler); } + + @VisibleForTesting + static String formatHostnamesForLog(ImmutableList hostnames) { + checkNotNull(hostnames, "hostnames"); + if (hostnames.size() <= MAX_LOGGED_HOSTNAMES) { + return hostnames.toString(); + } + return String.format( + "[%s, ... (%d total)]", + Joiner.on(", ").join(hostnames.subList(0, MAX_LOGGED_HOSTNAMES)), hostnames.size()); + } + + // Sanitize and bound the failure reason logged at INFO: because this handler accepts arbitrary + // unauthenticated client certificates, a crafted or malformed cert can cause JDK X.509/PKIX + // exceptions to echo long or newline-containing fields (e.g., invalid extension values during + // lazy OpenSSL parsing or large sets of unsupported critical OIDs). + @VisibleForTesting + static String formatFailureReasonForLog(Optional failureReason) { + checkNotNull(failureReason, "failureReason"); + if (failureReason.isEmpty()) { + return "none"; + } + String sanitized = failureReason.get().replace('\r', ' ').replace('\n', ' '); + return sanitized.length() <= MAX_LOGGED_FAILURE_REASON_CHARS + ? sanitized + : sanitized.substring(0, MAX_LOGGED_FAILURE_REASON_CHARS - 3) + "..."; + } } diff --git a/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java b/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java index b47997c2cf4..28b1fbefa3b 100644 --- a/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java +++ b/networking/src/test/java/google/registry/networking/handler/SslInitializerTestUtils.java @@ -17,22 +17,40 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.google.common.base.Suppliers; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; import google.registry.util.SelfSignedCaCertificate; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.handler.ssl.SslHandler; +import io.netty.handler.ssl.SslProvider; import java.math.BigInteger; +import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.PrivateKey; import java.security.SecureRandom; import java.security.cert.X509Certificate; +import java.security.spec.ECGenParameterSpec; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.Arrays; import java.util.Date; +import java.util.Optional; import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicLong; import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; @@ -49,6 +67,8 @@ public final class SslInitializerTestUtils { private static final BouncyCastleProvider PROVIDER = new BouncyCastleProvider(); private static final KeyPairGenerator KEY_PAIR_GENERATOR = getKeyPairGenerator(); + private static final KeyPairGenerator EC_KEY_PAIR_GENERATOR = getEcKeyPairGenerator(); + private static final AtomicLong SERIAL_NUMBER = new AtomicLong(1); private SslInitializerTestUtils() {} @@ -62,23 +82,58 @@ private static KeyPairGenerator getKeyPairGenerator() { } } + private static KeyPairGenerator getEcKeyPairGenerator() { + try { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", PROVIDER); + keyPairGenerator.initialize(new ECGenParameterSpec("secp256r1"), new SecureRandom()); + return keyPairGenerator; + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + public static KeyPair getKeyPair() throws Exception { return KEY_PAIR_GENERATOR.generateKeyPair(); } + public static KeyPair getEcKeyPair() { + return EC_KEY_PAIR_GENERATOR.generateKeyPair(); + } + /** - * Signs the given key pair with the given self-signed certificate to generate a certificate with - * the given validity range. + * Signs the given key pair with the given issuer key and certificate to generate a certificate + * with the given validity range. * * @return signed public key (of the key pair) certificate */ public static X509Certificate signKeyPair( - SelfSignedCaCertificate ssc, KeyPair keyPair, String hostname, Instant from, Instant to) + PrivateKey issuerKey, + X509Certificate issuerCert, + KeyPair keyPair, + String hostname, + Instant from, + Instant to, + String... dnsSans) + throws Exception { + return signKeyPair( + issuerKey, issuerCert, keyPair, hostname, from, to, Optional.empty(), dnsSans); + } + + private static X509Certificate signKeyPair( + PrivateKey issuerKey, + X509Certificate issuerCert, + KeyPair keyPair, + String hostname, + Instant from, + Instant to, + Optional eku, + String... dnsSans) throws Exception { X500Name subjectDnName = new X500Name("CN=" + hostname); - BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); - X500Name issuerDnName = new X500Name(ssc.cert().getIssuerX500Principal().getName()); - ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(ssc.key()); + BigInteger serialNumber = BigInteger.valueOf(SERIAL_NUMBER.incrementAndGet()); + X500Name issuerDnName = X500Name.getInstance(issuerCert.getSubjectX500Principal().getEncoded()); + ContentSigner sigGen = + new JcaContentSignerBuilder(signatureAlgorithmFor(issuerKey)).build(issuerKey); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder( issuerDnName, @@ -87,6 +142,17 @@ public static X509Certificate signKeyPair( Date.from(to), subjectDnName, keyPair.getPublic()); + if (eku.isPresent()) { + v3CertGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku.get())); + } + if (dnsSans.length > 0) { + GeneralName[] generalNames = + Arrays.stream(dnsSans) + .map(san -> new GeneralName(GeneralName.dNSName, san)) + .toArray(GeneralName[]::new); + v3CertGen.addExtension( + Extension.subjectAlternativeName, false, new GeneralNames(generalNames)); + } X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter() @@ -94,6 +160,47 @@ public static X509Certificate signKeyPair( .getCertificate(certificateHolder); } + /** + * Signs the given key pair with the given self-signed certificate to generate a certificate with + * the given validity range. + * + * @return signed public key (of the key pair) certificate + */ + public static X509Certificate signKeyPair( + SelfSignedCaCertificate ssc, + KeyPair keyPair, + String hostname, + Instant from, + Instant to, + String... dnsSans) + throws Exception { + return signKeyPair(ssc.key(), ssc.cert(), keyPair, hostname, from, to, dnsSans); + } + + /** Signs the given key pair as an intermediate CA certificate. */ + public static X509Certificate signIntermediateCa( + SelfSignedCaCertificate issuer, KeyPair keyPair, String cn, Instant from, Instant to) + throws Exception { + X500Name subjectDnName = new X500Name("CN=" + cn); + BigInteger serialNumber = BigInteger.valueOf(SERIAL_NUMBER.incrementAndGet()); + X500Name issuerDnName = + X500Name.getInstance(issuer.cert().getSubjectX500Principal().getEncoded()); + ContentSigner sigGen = + new JcaContentSignerBuilder(signatureAlgorithmFor(issuer.key())).build(issuer.key()); + X509v3CertificateBuilder v3CertGen = + new JcaX509v3CertificateBuilder( + issuerDnName, + serialNumber, + Date.from(from), + Date.from(to), + subjectDnName, + keyPair.getPublic()); + v3CertGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); + return new JcaX509CertificateConverter() + .setProvider(PROVIDER) + .getCertificate(v3CertGen.build(sigGen)); + } + /** * Signs the given key pair with the given self-signed certificate to generate a certificate that * is valid from yesterday to tomorrow. @@ -110,6 +217,78 @@ public static X509Certificate signKeyPair( Instant.now().plus(1, ChronoUnit.DAYS)); } + /** + * Signs the given key pair with the given self-signed certificate and DNS Subject Alternative + * Names using the issuer certificate's validity window. + */ + public static X509Certificate signKeyPairWithSans( + SelfSignedCaCertificate ssc, KeyPair keyPair, String hostname, String... dnsSans) + throws Exception { + return signKeyPair( + ssc, + keyPair, + hostname, + ssc.cert().getNotBefore().toInstant(), + ssc.cert().getNotAfter().toInstant(), + dnsSans); + } + + /** + * Signs the given key pair with the given self-signed certificate, Extended Key Usage, and DNS + * Subject Alternative Names using the issuer certificate's validity window. + */ + public static X509Certificate signKeyPairWithEku( + SelfSignedCaCertificate ssc, + KeyPair keyPair, + String hostname, + KeyPurposeId eku, + String... dnsSans) + throws Exception { + return signKeyPair( + ssc.key(), + ssc.cert(), + keyPair, + hostname, + ssc.cert().getNotBefore().toInstant(), + ssc.cert().getNotAfter().toInstant(), + Optional.of(eku), + dnsSans); + } + + private static String signatureAlgorithmFor(PrivateKey key) { + return "EC".equals(key.getAlgorithm()) ? "SHA256WithECDSA" : "SHA256WithRSAEncryption"; + } + + /** Creates a PKIX {@link X509TrustManager} trusting the given CA certificates. */ + public static X509TrustManager createTrustManager(X509Certificate... trustedCerts) + throws Exception { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, null); + for (int i = 0; i < trustedCerts.length; i++) { + keyStore.setCertificateEntry("ca-" + i, trustedCerts[i]); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); + trustManagerFactory.init(keyStore); + return (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; + } + + /** Creates an {@link SslServerInitializer} with a custom {@link X509TrustManager} for tests. */ + public static SslServerInitializer createSslServerInitializer( + boolean requireClientCert, + boolean validateClientCert, + SslProvider sslProvider, + PrivateKey serverKey, + ImmutableList serverCerts, + X509TrustManager trustManager) { + return new SslServerInitializer<>( + requireClientCert, + validateClientCert, + sslProvider, + Suppliers.ofInstance(serverKey), + Suppliers.ofInstance(serverCerts), + Optional.of(trustManager)); + } + /** * Verifies tha the SSL channel is established as expected, and also sends a message to the server * and verifies if it is echoed back correctly. diff --git a/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java b/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java index 5410eeb18a4..9b741d30c44 100644 --- a/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java +++ b/networking/src/test/java/google/registry/networking/handler/SslServerInitializerTest.java @@ -14,25 +14,45 @@ package google.registry.networking.handler; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; +import static google.registry.networking.handler.SslInitializerTestUtils.createTrustManager; +import static google.registry.networking.handler.SslInitializerTestUtils.getEcKeyPair; import static google.registry.networking.handler.SslInitializerTestUtils.getKeyPair; import static google.registry.networking.handler.SslInitializerTestUtils.setUpSslChannel; +import static google.registry.networking.handler.SslInitializerTestUtils.signIntermediateCa; import static google.registry.networking.handler.SslInitializerTestUtils.signKeyPair; +import static google.registry.networking.handler.SslInitializerTestUtils.signKeyPairWithEku; +import static google.registry.networking.handler.SslInitializerTestUtils.signKeyPairWithSans; import static google.registry.networking.handler.SslInitializerTestUtils.verifySslException; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_HOSTNAMES_KEY; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_PROMISE_KEY; +import static google.registry.networking.handler.SslServerInitializer.formatFailureReasonForLog; +import static google.registry.networking.handler.SslServerInitializer.formatHostnamesForLog; import static google.registry.util.DateTimeUtils.minusDays; import static google.registry.util.DateTimeUtils.plusDays; +import static google.registry.util.X509Utils.getCertificateHash; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import google.registry.testing.FakeClock; import google.registry.util.SelfSignedCaCertificate; +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; +import io.netty.channel.DefaultEventLoopGroup; +import io.netty.channel.EventLoopGroup; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; +import io.netty.channel.local.LocalServerChannel; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; @@ -47,12 +67,29 @@ import java.time.Instant; import java.util.Collections; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.stream.IntStream; import java.util.stream.Stream; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; +import javax.net.ssl.X509TrustManager; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -77,6 +114,43 @@ class SslServerInitializerTest { /** Fake port to test if the SSL engine gets the correct peer port. */ private static final int SSL_PORT = 12345; + private static final Instant LONG_VALID_FROM = Instant.EPOCH; + private static final Instant LONG_VALID_TO = Instant.parse("2100-01-01T00:00:00Z"); + + private static SelfSignedCaCertificate sharedServerSsc; + private static SelfSignedCaCertificate sharedRootCa; + private static X509TrustManager sharedTrustManager; + private static KeyPair sharedIntermediateKeyPair; + private static X509Certificate sharedIntermediateCa; + private static SelfSignedCaCertificate sharedUntrustedCa; + private static KeyPair sharedClientKeyPair; + private static SelfSignedCaCertificate sharedEcRootCa; + private static X509TrustManager sharedEcTrustManager; + private static KeyPair sharedEcClientKeyPair; + + @BeforeAll + static void setUpSharedFixtures() throws Exception { + sharedServerSsc = SelfSignedCaCertificate.create(SSL_HOST, new FakeClock()); + sharedRootCa = SelfSignedCaCertificate.create("root-ca.tld", LONG_VALID_FROM, LONG_VALID_TO); + sharedTrustManager = createTrustManager(sharedRootCa.cert()); + sharedIntermediateKeyPair = getKeyPair(); + sharedIntermediateCa = + signIntermediateCa( + sharedRootCa, + sharedIntermediateKeyPair, + "intermediate-ca.tld", + LONG_VALID_FROM, + LONG_VALID_TO); + sharedUntrustedCa = + SelfSignedCaCertificate.create("untrusted-ca.tld", LONG_VALID_FROM, LONG_VALID_TO); + sharedClientKeyPair = getKeyPair(); + sharedEcRootCa = + SelfSignedCaCertificate.create( + getEcKeyPair(), "ec-root-ca.tld", LONG_VALID_FROM, LONG_VALID_TO); + sharedEcTrustManager = createTrustManager(sharedEcRootCa.cert()); + sharedEcClientKeyPair = getEcKeyPair(); + } + @RegisterExtension NettyExtension nettyExtension = new NettyExtension(); @SuppressWarnings("unused") @@ -108,7 +182,7 @@ private ChannelHandler getClientHandler( SslProvider sslProvider, X509Certificate trustedCertificate, PrivateKey privateKey, - X509Certificate certificate, + X509Certificate[] certificates, String protocol, List cipher) { return new ChannelInitializer() { @@ -122,8 +196,8 @@ protected void initChannel(LocalChannel ch) throws Exception { if (protocol != null) { sslContextBuilder.protocols(protocol); } - if (privateKey != null && certificate != null) { - sslContextBuilder.keyManager(privateKey, certificate); + if (privateKey != null && certificates != null && certificates.length > 0) { + sslContextBuilder.keyManager(privateKey, certificates); } SslHandler sslHandler = sslContextBuilder.build().newHandler(ch.alloc(), SSL_HOST, SSL_PORT); @@ -139,6 +213,22 @@ protected void initChannel(LocalChannel ch) throws Exception { }; } + private ChannelHandler getClientHandler( + SslProvider sslProvider, + X509Certificate trustedCertificate, + PrivateKey privateKey, + X509Certificate certificate, + String protocol, + List cipher) { + return getClientHandler( + sslProvider, + trustedCertificate, + privateKey, + certificate == null ? null : new X509Certificate[] {certificate}, + protocol, + cipher); + } + private ChannelHandler getClientHandler( SslProvider sslProvider, X509Certificate trustedCertificate, @@ -147,6 +237,14 @@ private ChannelHandler getClientHandler( return getClientHandler(sslProvider, trustedCertificate, privateKey, certificate, null, null); } + private ChannelHandler getClientHandlerWithChain( + SslProvider sslProvider, + X509Certificate trustedCertificate, + PrivateKey privateKey, + X509Certificate... certificates) { + return getClientHandler(sslProvider, trustedCertificate, privateKey, certificates, null, null); + } + @ParameterizedTest @MethodSource("provideTestCombinations") void testSuccess_swappedInitializerWithSslHandler(SslProvider sslProvider) throws Exception { @@ -217,6 +315,9 @@ void testFailure_cipherNotAccepted(SslProvider sslProvider) throws Exception { nettyExtension.getServerChannel(), channel -> channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get(), SSLHandshakeException.class); + Channel serverChannel = nettyExtension.getServerChannel(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isNull(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isNull(); } @ParameterizedTest @@ -349,6 +450,9 @@ void testSuccess_doesNotRequireClientCert(SslProvider sslProvider) throws Except // SslSession for the server channel, and vice versa. assertThat(sslSession.getLocalCertificates()).isNull(); assertThat(sslSession.getPeerCertificates()).asList().containsExactly(serverSsc.cert()); + Channel serverChannel = nettyExtension.getServerChannel(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isNull(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isNull(); } @ParameterizedTest @@ -439,6 +543,756 @@ void testFailure_wrongHostnameInCertificate(SslProvider sslProvider) throws Exce assertThat(nettyExtension.getClientChannel().isActive()).isFalse(); } + private Channel connectMutualTls( + String addressPrefix, + SslProvider sslProvider, + boolean validateClientCert, + Optional trustManager, + PrivateKey clientKey, + X509Certificate... clientChain) + throws Exception { + return connectMutualTls( + addressPrefix, + sslProvider, + new SslServerInitializer( + true, + validateClientCert, + sslProvider, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + trustManager), + null, + clientKey, + clientChain); + } + + private Channel connectMutualTls( + String addressPrefix, + SslProvider sslProvider, + SslServerInitializer serverInitializer, + ChannelHandler extraServerHandler, + PrivateKey clientKey, + X509Certificate... clientChain) + throws Exception { + LocalAddress localAddress = new LocalAddress(addressPrefix + "_" + sslProvider); + if (extraServerHandler != null) { + nettyExtension.setUpServer(localAddress, serverInitializer, extraServerHandler); + } else { + nettyExtension.setUpServer(localAddress, serverInitializer); + } + nettyExtension.setUpClient( + localAddress, + getClientHandlerWithChain(sslProvider, sharedServerSsc.cert(), clientKey, clientChain)); + setUpSslChannel(nettyExtension.getClientChannel(), sharedServerSsc.cert()); + nettyExtension.assertThatMessagesWork(); + return nettyExtension.getServerChannel(); + } + + private static Handler captureSslInfoLogs(List loggedMessages, String expectedCertHash) { + Handler handler = + new Handler() { + @Override + public void publish(LogRecord record) { + if (record.getMessage() != null + && record.getMessage().contains("--SSL Information--") + && record.getMessage().contains("Client Certificate Hash: " + expectedCertHash)) { + loggedMessages.add(record.getMessage()); + } + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + Logger.getLogger(SslServerInitializer.class.getName()).addHandler(handler); + return handler; + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_clientCertSignedByTrustedCaWithDnsSans(SslProvider sslProvider) + throws Exception { + X509Certificate clientCert = + signKeyPairWithSans( + sharedRootCa, + sharedClientKeyPair, + "Ignored.CommonName.TLD", + "EPP1.Example.TLD", + "epp1.example.tld", + "*.Sub.Example.TLD", + "epp2.example.tld"); + + AtomicReference validatedInListener = new AtomicReference<>(); + AtomicReference> hostnamesInListener = new AtomicReference<>(); + CountDownLatch listenerFired = new CountDownLatch(1); + ChannelHandler promiseObserver = + new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + ctx.channel() + .attr(CLIENT_CERTIFICATE_PROMISE_KEY) + .get() + .addListener( + future -> { + validatedInListener.set( + ctx.channel().attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()); + hostnamesInListener.set( + ctx.channel().attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()); + listenerFired.countDown(); + }); + super.channelActive(ctx); + } + }; + + List sslInfoLogs = new CopyOnWriteArrayList<>(); + Handler logHandler = captureSslInfoLogs(sslInfoLogs, getCertificateHash(clientCert)); + try { + Channel serverChannel = + connectMutualTls( + "TRUSTED_CA_WITH_SANS", + sslProvider, + new SslServerInitializer( + true, + true, + sslProvider, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Optional.of(sharedTrustManager)), + promiseObserver, + sharedClientKeyPair.getPrivate(), + clientCert); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(clientCert); + assertThat(listenerFired.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(validatedInListener.get()).isTrue(); + assertThat(hostnamesInListener.get()) + .containsExactly("epp1.example.tld", "epp2.example.tld") + .inOrder(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isTrue(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()) + .containsExactly("epp1.example.tld", "epp2.example.tld") + .inOrder(); + assertThat(sslInfoLogs).hasSize(1); + assertThat(sslInfoLogs.get(0)).contains("Client Certificate Chain Validated: true"); + assertThat(sslInfoLogs.get(0)).contains("Client Certificate Chain Failure Reason: none"); + assertThat(sslInfoLogs.get(0)) + .contains("Client Certificate Hostnames: [epp1.example.tld, epp2.example.tld]"); + } finally { + Logger.getLogger(SslServerInitializer.class.getName()).removeHandler(logHandler); + } + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_clientCertThreeTierChainWithIntermediateCa(SslProvider sslProvider) + throws Exception { + X509Certificate clientCert = + signKeyPair( + sharedIntermediateKeyPair.getPrivate(), + sharedIntermediateCa, + sharedClientKeyPair, + "Ignored.CN.TLD", + LONG_VALID_FROM, + LONG_VALID_TO, + "epp.three-tier.example"); + + Channel serverChannel = + connectMutualTls( + "THREE_TIER_CHAIN", + sslProvider, + false, + Optional.of(sharedTrustManager), + sharedClientKeyPair.getPrivate(), + clientCert, + sharedIntermediateCa); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(clientCert); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isTrue(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()) + .containsExactly("epp.three-tier.example"); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_clientCertThreeTierChain_tls12(SslProvider sslProvider) throws Exception { + X509Certificate clientCert = + signKeyPair( + sharedIntermediateKeyPair.getPrivate(), + sharedIntermediateCa, + sharedClientKeyPair, + "Ignored.CN.TLD", + LONG_VALID_FROM, + LONG_VALID_TO, + "epp.three-tier-tls12.example"); + + LocalAddress localAddress = new LocalAddress("THREE_TIER_CHAIN_TLS12_" + sslProvider); + nettyExtension.setUpServer( + localAddress, + new SslServerInitializer( + true, + true, + sslProvider, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Optional.of(sharedTrustManager))); + nettyExtension.setUpClient( + localAddress, + getClientHandler( + sslProvider, + sharedServerSsc.cert(), + sharedClientKeyPair.getPrivate(), + new X509Certificate[] {clientCert, sharedIntermediateCa}, + "TLSv1.2", + null)); + + SSLSession sslSession = + setUpSslChannel(nettyExtension.getClientChannel(), sharedServerSsc.cert()); + nettyExtension.assertThatMessagesWork(); + + Channel serverChannel = nettyExtension.getServerChannel(); + assertThat(sslSession.getProtocol()).isEqualTo("TLSv1.2"); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(clientCert); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isTrue(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()) + .containsExactly("epp.three-tier-tls12.example"); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_throwingTrustManager_failsClosedWithChainValidatedFalse(SslProvider sslProvider) + throws Exception { + X509Certificate clientCert = + signKeyPairWithSans( + sharedRootCa, sharedClientKeyPair, "ignored.cn.example", "epp.throwing-tm.example"); + X509TrustManager throwingTrustManager = + new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException("simulated client trust failure"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException("simulated server trust failure"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }; + + Channel serverChannel = + connectMutualTls( + "THROWING_TRUST_MANAGER", + sslProvider, + true, + Optional.of(throwingTrustManager), + sharedClientKeyPair.getPrivate(), + clientCert); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(clientCert); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isFalse(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isEmpty(); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testFailure_outerCatchClosesChannelWhenPromiseAlreadyCompleted(SslProvider sslProvider) + throws Exception { + X509Certificate clientCert = + signKeyPairWithSans( + sharedRootCa, sharedClientKeyPair, "ignored.cn.example", "epp.outer-catch.example"); + CompletableFuture serverChannelFuture = new CompletableFuture<>(); + ChannelHandler promiseCanceler = + new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + ctx.channel().attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().cancel(false); + serverChannelFuture.complete(ctx.channel()); + super.channelActive(ctx); + } + }; + + List warningLogs = new CopyOnWriteArrayList<>(); + Handler logHandler = + new Handler() { + @Override + public void publish(LogRecord record) { + if (record.getMessage() != null + && record.getMessage().contains("Failed to inspect client certificate.")) { + warningLogs.add(record.getMessage()); + } + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + Logger.getLogger(SslServerInitializer.class.getName()).addHandler(logHandler); + try { + LocalAddress localAddress = new LocalAddress("OUTER_CATCH_" + sslProvider); + nettyExtension.setUpServer( + localAddress, + new SslServerInitializer( + true, + true, + sslProvider, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Optional.of(sharedTrustManager)), + promiseCanceler); + nettyExtension.setUpClient( + localAddress, + getClientHandlerWithChain( + sslProvider, sharedServerSsc.cert(), sharedClientKeyPair.getPrivate(), clientCert)); + + Channel serverChannel = serverChannelFuture.get(10, TimeUnit.SECONDS); + assertThat(serverChannel.closeFuture().await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(serverChannel.isActive()).isFalse(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().isCancelled()).isTrue(); + assertThat(warningLogs).isNotEmpty(); + } finally { + Logger.getLogger(SslServerInitializer.class.getName()).removeHandler(logHandler); + } + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_concurrentClientsOnSharedSharableInitializer(SslProvider sslProvider) + throws Exception { + X509Certificate trustedCert1 = + signKeyPairWithSans( + sharedRootCa, sharedClientKeyPair, "ignored.cn.example", "epp1.concurrent.example"); + X509Certificate trustedCert2 = + signKeyPairWithSans( + sharedRootCa, sharedClientKeyPair, "ignored.cn.example", "epp2.concurrent.example"); + X509Certificate threeTierCert = + signKeyPair( + sharedIntermediateKeyPair.getPrivate(), + sharedIntermediateCa, + sharedClientKeyPair, + "ignored.cn.example", + LONG_VALID_FROM, + LONG_VALID_TO, + "epp3.concurrent.example"); + X509Certificate untrustedCert = + signKeyPairWithSans( + sharedUntrustedCa, sharedClientKeyPair, "ignored.cn.example", "epp4.untrusted.example"); + + record ObservedClient(boolean chainValidated, ImmutableList hostnames) {} + + SslServerInitializer sharedInitializer = + new SslServerInitializer<>( + true, + true, + sslProvider, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Optional.of(sharedTrustManager)); + + Map observedByHash = new ConcurrentHashMap<>(); + CountDownLatch allRecorded = new CountDownLatch(4); + LocalAddress localAddress = new LocalAddress("CONCURRENT_SHARABLE_" + sslProvider); + EventLoopGroup eventLoopGroup = new DefaultEventLoopGroup(4); + ImmutableList.Builder channelsToClose = ImmutableList.builder(); + try { + Supplier recorderFactory = + () -> + new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + Channel ch = ctx.channel(); + ch.attr(CLIENT_CERTIFICATE_PROMISE_KEY) + .get() + .addListener( + future -> { + if (future.isSuccess()) { + X509Certificate cert = (X509Certificate) future.getNow(); + observedByHash.put( + getCertificateHash(cert), + new ObservedClient( + ch.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get(), + ch.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get())); + allRecorded.countDown(); + } + }); + super.channelActive(ctx); + } + }; + Channel serverChannel = + new ServerBootstrap() + .group(eventLoopGroup) + .channel(LocalServerChannel.class) + .childHandler( + new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) { + ch.pipeline().addLast(sharedInitializer, recorderFactory.get()); + } + }) + .bind(localAddress) + .syncUninterruptibly() + .channel(); + channelsToClose.add(serverChannel); + + ImmutableList clientChains = + ImmutableList.of( + new X509Certificate[] {trustedCert1}, + new X509Certificate[] {trustedCert2}, + new X509Certificate[] {threeTierCert, sharedIntermediateCa}, + new X509Certificate[] {untrustedCert}); + + ImmutableList clientChannels = + clientChains.stream() + .map( + chain -> { + Channel clientChannel = + new Bootstrap() + .group(eventLoopGroup) + .channel(LocalChannel.class) + .handler( + getClientHandlerWithChain( + sslProvider, + sharedServerSsc.cert(), + sharedClientKeyPair.getPrivate(), + chain)) + .connect(localAddress) + .syncUninterruptibly() + .channel(); + channelsToClose.add(clientChannel); + return clientChannel; + }) + .collect(toImmutableList()); + + for (Channel clientChannel : clientChannels) { + clientChannel.pipeline().get(SslHandler.class).handshakeFuture().get(10, TimeUnit.SECONDS); + } + assertThat(allRecorded.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(observedByHash) + .containsExactly( + getCertificateHash(trustedCert1), + new ObservedClient(true, ImmutableList.of("epp1.concurrent.example")), + getCertificateHash(trustedCert2), + new ObservedClient(true, ImmutableList.of("epp2.concurrent.example")), + getCertificateHash(threeTierCert), + new ObservedClient(true, ImmutableList.of("epp3.concurrent.example")), + getCertificateHash(untrustedCert), + new ObservedClient(false, ImmutableList.of())); + } finally { + for (Channel ch : channelsToClose.build()) { + ch.close().syncUninterruptibly(); + } + eventLoopGroup.shutdownGracefully().syncUninterruptibly(); + } + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_missingIntermediateCa_chainValidatedFalseAndEmptyHostnames( + SslProvider sslProvider) throws Exception { + X509Certificate clientCert = + signKeyPair( + sharedIntermediateKeyPair.getPrivate(), + sharedIntermediateCa, + sharedClientKeyPair, + "epp.missing-inter.example", + LONG_VALID_FROM, + LONG_VALID_TO, + "epp.missing-inter.example"); + + // Client sends leaf only, omitting the required intermediate CA. + Channel serverChannel = + connectMutualTls( + "MISSING_INTERMEDIATE_CA", + sslProvider, + true, + Optional.of(sharedTrustManager), + sharedClientKeyPair.getPrivate(), + clientCert); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(clientCert); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isFalse(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isEmpty(); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_untrustedClientCert_stillSucceedsHandshakeWithEmptyHostnames( + SslProvider sslProvider) throws Exception { + // Use the public 5-arg constructor (default JVM truststore) with an untrusted non-CA leaf so + // handshake stays open for legacy fingerprint-pinned certs while chain validation fails. + X509Certificate untrustedLeafCert = + signKeyPairWithSans( + sharedUntrustedCa, sharedClientKeyPair, "EPP.Untrusted.TLD", "epp.untrusted.tld"); + + List sslInfoLogs = new CopyOnWriteArrayList<>(); + Handler logHandler = captureSslInfoLogs(sslInfoLogs, getCertificateHash(untrustedLeafCert)); + try { + Channel serverChannel = + connectMutualTls( + "UNTRUSTED_CLIENT_EMPTY_HOSTNAMES", + sslProvider, + new SslServerInitializer( + true, + true, + sslProvider, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert()))), + null, + sharedClientKeyPair.getPrivate(), + untrustedLeafCert); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(untrustedLeafCert); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isFalse(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isEmpty(); + assertThat(sslInfoLogs).hasSize(1); + assertThat(sslInfoLogs.get(0)).contains("Client Certificate Chain Validated: false"); + assertThat(sslInfoLogs.get(0)).contains("PKIX path building failed"); + assertThat(sslInfoLogs.get(0)).contains("Client Certificate Hostnames: []"); + } finally { + Logger.getLogger(SslServerInitializer.class.getName()).removeHandler(logHandler); + } + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_ecdsaClientCertSignedByTrustedCa(SslProvider sslProvider) throws Exception { + X509Certificate ecClientCert = + signKeyPairWithSans( + sharedEcRootCa, sharedEcClientKeyPair, "ignored.cn.example", "epp.ecdsa.example"); + + Channel serverChannel = + connectMutualTls( + "ECDSA_TRUSTED_CA", + sslProvider, + false, + Optional.of(sharedEcTrustManager), + sharedEcClientKeyPair.getPrivate(), + ecClientCert); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(ecClientCert); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isTrue(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()) + .containsExactly("epp.ecdsa.example"); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_expiredClientCertWhenValidationDisabled_chainValidatedFalse( + SslProvider sslProvider) throws Exception { + X509Certificate expiredClientCert = + signKeyPair( + sharedRootCa, + sharedClientKeyPair, + "epp.expired.example", + Instant.parse("2000-01-01T00:00:00Z"), + Instant.parse("2000-01-02T00:00:00Z"), + "epp.expired.example"); + + Channel serverChannel = + connectMutualTls( + "EXPIRED_CLIENT_NO_VALIDATE", + sslProvider, + false, + Optional.of(sharedTrustManager), + sharedClientKeyPair.getPrivate(), + expiredClientCert); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(expiredClientCert); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isFalse(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isEmpty(); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testFailure_expiredTrustedClientCertWhenValidationEnabled_doesNotSetChainAttributes( + SslProvider sslProvider) throws Exception { + X509Certificate expiredClientCert = + signKeyPair( + sharedRootCa, + sharedClientKeyPair, + "epp.expired.example", + Instant.parse("2000-01-01T00:00:00Z"), + Instant.parse("2000-01-02T00:00:00Z"), + "epp.expired.example"); + LocalAddress localAddress = new LocalAddress("EXPIRED_TRUSTED_VALIDATE_" + sslProvider); + + nettyExtension.setUpServer( + localAddress, + new SslServerInitializer( + true, + true, + sslProvider, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Optional.of(sharedTrustManager))); + nettyExtension.setUpClient( + localAddress, + getClientHandler( + sslProvider, + sharedServerSsc.cert(), + sharedClientKeyPair.getPrivate(), + expiredClientCert)); + + Channel serverChannel = nettyExtension.getServerChannel(); + verifySslException( + serverChannel, + channel -> channel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get(), + CertificateExpiredException.class); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isNull(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isNull(); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_serverAuthOnlyClientCert_chainValidatedTrueAndExtractsHostnames( + SslProvider sslProvider) throws Exception { + X509Certificate serverAuthLeaf = + signKeyPairWithEku( + sharedRootCa, + sharedClientKeyPair, + "ignored.cn.example", + KeyPurposeId.id_kp_serverAuth, + "epp.serverauth.example"); + + Channel serverChannel = + connectMutualTls( + "SERVER_AUTH_ONLY_EKU", + sslProvider, + true, + Optional.of(sharedTrustManager), + sharedClientKeyPair.getPrivate(), + serverAuthLeaf); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(serverAuthLeaf); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isTrue(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()) + .containsExactly("epp.serverauth.example"); + } + + @ParameterizedTest + @MethodSource("provideTestCombinations") + void testSuccess_clientAuthOnlyClientCert_handshakeSucceedsWithChainValidatedFalse( + SslProvider sslProvider) throws Exception { + X509Certificate clientAuthLeaf = + signKeyPairWithEku( + sharedRootCa, + sharedClientKeyPair, + "epp.clientauth.example", + KeyPurposeId.id_kp_clientAuth, + "epp.clientauth.example"); + + List sslInfoLogs = new CopyOnWriteArrayList<>(); + Handler logHandler = captureSslInfoLogs(sslInfoLogs, getCertificateHash(clientAuthLeaf)); + try { + Channel serverChannel = + connectMutualTls( + "CLIENT_AUTH_ONLY_EKU", + sslProvider, + true, + Optional.of(sharedTrustManager), + sharedClientKeyPair.getPrivate(), + clientAuthLeaf); + + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_PROMISE_KEY).get().get()) + .isEqualTo(clientAuthLeaf); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get()).isFalse(); + assertThat(serverChannel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get()).isEmpty(); + assertThat(sslInfoLogs).hasSize(1); + assertThat(sslInfoLogs.get(0)).contains("Client Certificate Chain Validated: false"); + assertThat(sslInfoLogs.get(0)).contains("Extended key usage"); + assertThat(sslInfoLogs.get(0)).contains("Client Certificate Hostnames: []"); + } finally { + Logger.getLogger(SslServerInitializer.class.getName()).removeHandler(logHandler); + } + } + + @Test + void testFailure_validateClientCertWithoutRequireClientCert_throws() { + assertThrows( + IllegalArgumentException.class, + () -> + new SslServerInitializer( + false, + true, + SslProvider.JDK, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())))); + } + + @Test + void testFailure_missingTrustManagerWhenClientCertRequired_throws() { + assertThrows( + NullPointerException.class, + () -> + new SslServerInitializer( + true, + false, + SslProvider.JDK, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new SslServerInitializer( + true, + false, + SslProvider.JDK, + Suppliers.ofInstance(sharedServerSsc.key()), + Suppliers.ofInstance(ImmutableList.of(sharedServerSsc.cert())), + Optional.empty())); + } + + @Test + void testFormatHostnamesForLog_boundsOutput() { + assertThrows(NullPointerException.class, () -> formatHostnamesForLog(null)); + assertThat(formatHostnamesForLog(ImmutableList.of())).isEqualTo("[]"); + ImmutableList tenHosts = + IntStream.range(0, 10).mapToObj(i -> "h" + i + ".example.tld").collect(toImmutableList()); + assertThat(formatHostnamesForLog(tenHosts)).isEqualTo(tenHosts.toString()); + + ImmutableList elevenHosts = + IntStream.range(0, 11).mapToObj(i -> "h" + i + ".example.tld").collect(toImmutableList()); + assertThat(formatHostnamesForLog(elevenHosts)) + .isEqualTo( + "[h0.example.tld, h1.example.tld, h2.example.tld, h3.example.tld, h4.example.tld," + + " h5.example.tld, h6.example.tld, h7.example.tld, h8.example.tld," + + " h9.example.tld, ... (11 total)]"); + } + + @Test + void testFormatFailureReasonForLog_sanitizesAndBoundsOutput() { + assertThrows(NullPointerException.class, () -> formatFailureReasonForLog(null)); + assertThat(formatFailureReasonForLog(Optional.empty())).isEqualTo("none"); + assertThat(formatFailureReasonForLog(Optional.of("CertPathValidatorException: untrusted"))) + .isEqualTo("CertPathValidatorException: untrusted"); + assertThat(formatFailureReasonForLog(Optional.of("line1\r\nline2\nline3\rline4"))) + .isEqualTo("line1 line2 line3 line4"); + + String exactLimit = "a".repeat(512); + assertThat(formatFailureReasonForLog(Optional.of(exactLimit))).isEqualTo(exactLimit); + + String overLimit = "a".repeat(600); + String formatted = formatFailureReasonForLog(Optional.of(overLimit)); + assertThat(formatted).hasLength(512); + assertThat(formatted).isEqualTo("a".repeat(509) + "..."); + } + /** Returns true if v1 is larger or equals to v2. */ private static boolean compareSemanticVersion( ImmutableList v1, ImmutableList v2) { diff --git a/proxy/src/main/java/google/registry/proxy/handler/EppServiceHandler.java b/proxy/src/main/java/google/registry/proxy/handler/EppServiceHandler.java index 27065fb8c71..3c3f902bbc3 100644 --- a/proxy/src/main/java/google/registry/proxy/handler/EppServiceHandler.java +++ b/proxy/src/main/java/google/registry/proxy/handler/EppServiceHandler.java @@ -14,10 +14,14 @@ package google.registry.proxy.handler; +import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_HOSTNAMES_KEY; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_PROMISE_KEY; import static google.registry.proxy.handler.ProxyProtocolHandler.REMOTE_ADDRESS_KEY; +import static google.registry.util.X509Utils.formatHostnamesHeader; import static google.registry.util.X509Utils.getCertificateHash; import static java.nio.charset.StandardCharsets.US_ASCII; @@ -62,6 +66,8 @@ public class EppServiceHandler extends HttpsRelayServiceHandler { private final byte[] helloBytes; private String sslClientCertificateHash; + private boolean sslClientCertificateChainValidated; + private Optional sslClientCertificateHostnamesHeader = Optional.empty(); private String clientAddress; private Optional maybeRegistrarId = Optional.empty(); @@ -107,6 +113,16 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { (Promise promise) -> { if (promise.isSuccess()) { sslClientCertificateHash = getCertificateHash(promise.get()); + sslClientCertificateChainValidated = + firstNonNull( + ctx.channel().attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).get(), + false); + sslClientCertificateHostnamesHeader = + sslClientCertificateChainValidated + ? formatHostnamesHeader( + ctx.channel().attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).get(), + sslClientCertificateHash) + : Optional.empty(); // Set the client cert hash key attribute for both this channel, // used for collecting metrics on specific clients. ctx.channel().attr(CLIENT_CERTIFICATE_HASH_KEY).set(sslClientCertificateHash); @@ -133,10 +149,15 @@ protected FullHttpRequest decodeFullHttpRequest(ByteBuf byteBuf) { request .headers() .set(ProxyHttpHeaders.CERTIFICATE_HASH, sslClientCertificateHash) + .set( + ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, + Boolean.toString(sslClientCertificateChainValidated)) .set(ProxyHttpHeaders.IP_ADDRESS, clientAddress) .set(ProxyHttpHeaders.FALLBACK_IP_ADDRESS, clientAddress) .set(HttpHeaderNames.CONTENT_TYPE, EPP_CONTENT_TYPE) .set(HttpHeaderNames.ACCEPT, EPP_CONTENT_TYPE); + sslClientCertificateHostnamesHeader.ifPresent( + header -> request.headers().set(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, header)); maybeSetRegistrarIdHeader(request); diff --git a/proxy/src/test/java/google/registry/proxy/TestUtils.java b/proxy/src/test/java/google/registry/proxy/TestUtils.java index c4ae6ad9502..bad7ff4b21a 100644 --- a/proxy/src/test/java/google/registry/proxy/TestUtils.java +++ b/proxy/src/test/java/google/registry/proxy/TestUtils.java @@ -105,6 +105,7 @@ public static FullHttpRequest makeEppHttpRequest( .set("content-type", "application/epp+xml") .set("accept", "application/epp+xml") .set(ProxyHttpHeaders.CERTIFICATE_HASH, sslClientCertificateHash) + .set(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, "false") .set(ProxyHttpHeaders.IP_ADDRESS, clientAddress) .set(ProxyHttpHeaders.FALLBACK_IP_ADDRESS, clientAddress); if (cookies.length != 0) { diff --git a/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java b/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java index 8ccab79f1ae..1321400f9f1 100644 --- a/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java +++ b/proxy/src/test/java/google/registry/proxy/handler/EppServiceHandlerTest.java @@ -14,11 +14,22 @@ package google.registry.proxy.handler; +import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; +import static google.registry.networking.handler.SslInitializerTestUtils.createSslServerInitializer; +import static google.registry.networking.handler.SslInitializerTestUtils.createTrustManager; +import static google.registry.networking.handler.SslInitializerTestUtils.getKeyPair; +import static google.registry.networking.handler.SslInitializerTestUtils.signIntermediateCa; +import static google.registry.networking.handler.SslInitializerTestUtils.signKeyPair; +import static google.registry.networking.handler.SslInitializerTestUtils.signKeyPairWithSans; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY; +import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_HOSTNAMES_KEY; import static google.registry.networking.handler.SslServerInitializer.CLIENT_CERTIFICATE_PROMISE_KEY; import static google.registry.proxy.TestUtils.assertHttpRequestEquivalent; import static google.registry.proxy.TestUtils.makeEppHttpResponse; import static google.registry.proxy.handler.ProxyProtocolHandler.REMOTE_ADDRESS_KEY; +import static google.registry.util.X509Utils.MAX_HOSTNAMES_HEADER_BYTES; +import static google.registry.util.X509Utils.formatHostnamesHeader; import static google.registry.util.X509Utils.getCertificateHash; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; @@ -28,27 +39,51 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; +import google.registry.networking.handler.SslServerInitializer; import google.registry.proxy.TestUtils; import google.registry.proxy.handler.HttpsRelayServiceHandler.NonOkHttpResponseException; import google.registry.proxy.metric.FrontendMetrics; import google.registry.testing.FakeClock; import google.registry.util.ProxyHttpHeaders; import google.registry.util.SelfSignedCaCertificate; +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.DefaultChannelId; +import io.netty.channel.DefaultEventLoopGroup; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.channel.local.LocalAddress; +import io.netty.channel.local.LocalChannel; +import io.netty.channel.local.LocalServerChannel; import io.netty.handler.codec.EncoderException; +import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.DefaultCookie; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.SslHandler; +import io.netty.handler.ssl.SslProvider; import io.netty.util.concurrent.Promise; import java.io.IOException; +import java.security.KeyPair; import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; +import javax.net.ssl.X509TrustManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -438,4 +473,294 @@ void testSuccess_registrarIdHeader_isNotSetWhenClientIdIsNull() throws Exception assertThat((Object) channel.readInbound()).isNull(); assertThat(channel.isActive()).isTrue(); } + + @Test + void testSuccess_forwardsCertificateChainValidatedAndHostnamesHeaders() throws Exception { + channel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).set(true); + channel + .attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY) + .set(ImmutableList.of("epp1.example.tld", "epp2.example.tld")); + setHandshakeSuccess(); + + FullHttpRequest helloRequest = channel.readInbound(); + FullHttpRequest expectedHelloRequest = makeEppHttpRequest(HELLO); + expectedHelloRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, "true"); + expectedHelloRequest + .headers() + .set(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, "epp1.example.tld,epp2.example.tld"); + assertHttpRequestEquivalent(helloRequest, expectedHelloRequest); + + String loginContent = ""; + channel.writeInbound(Unpooled.wrappedBuffer(loginContent.getBytes(UTF_8))); + FullHttpRequest loginRequest = channel.readInbound(); + FullHttpRequest expectedLoginRequest = makeEppHttpRequest(loginContent); + expectedLoginRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, "true"); + expectedLoginRequest + .headers() + .set(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, "epp1.example.tld,epp2.example.tld"); + assertHttpRequestEquivalent(loginRequest, expectedLoginRequest); + + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testSuccess_omitsCertificateHostnamesHeaderWhenEmpty() throws Exception { + channel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).set(true); + channel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).set(ImmutableList.of()); + setHandshakeSuccess(); + + FullHttpRequest helloRequest = channel.readInbound(); + FullHttpRequest expectedRequest = makeEppHttpRequest(HELLO); + expectedRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, "true"); + + assertHttpRequestEquivalent(helloRequest, expectedRequest); + assertThat(helloRequest.headers().contains(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isFalse(); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testSuccess_omitsCertificateHostnamesHeaderWhenHostnamesAttrUnset() throws Exception { + channel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).set(true); + setHandshakeSuccess(); + + FullHttpRequest helloRequest = channel.readInbound(); + FullHttpRequest expectedRequest = makeEppHttpRequest(HELLO); + expectedRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, "true"); + + assertHttpRequestEquivalent(helloRequest, expectedRequest); + assertThat(helloRequest.headers().contains(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isFalse(); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testSuccess_forwardsChainValidatedFalseWhenChainNotValidated() throws Exception { + channel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).set(false); + channel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).set(ImmutableList.of("epp.untrusted.tld")); + setHandshakeSuccess(); + + FullHttpRequest helloRequest = channel.readInbound(); + FullHttpRequest expectedHelloRequest = makeEppHttpRequest(HELLO); + assertHttpRequestEquivalent(helloRequest, expectedHelloRequest); + assertThat(helloRequest.headers().get(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("false"); + assertThat(helloRequest.headers().contains(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isFalse(); + + String loginContent = ""; + channel.writeInbound(Unpooled.wrappedBuffer(loginContent.getBytes(UTF_8))); + FullHttpRequest loginRequest = channel.readInbound(); + FullHttpRequest expectedLoginRequest = makeEppHttpRequest(loginContent); + assertHttpRequestEquivalent(loginRequest, expectedLoginRequest); + assertThat(loginRequest.headers().get(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("false"); + assertThat(loginRequest.headers().contains(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isFalse(); + + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testSuccess_defaultsChainValidatedToFalseWhenAttributesUnset() throws Exception { + setHandshakeSuccess(); + + FullHttpRequest helloRequest = channel.readInbound(); + assertHttpRequestEquivalent(helloRequest, makeEppHttpRequest(HELLO)); + assertThat(helloRequest.headers().get(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("false"); + assertThat(helloRequest.headers().contains(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)).isFalse(); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testSuccess_truncatesOversizedCertificateHostnamesHeader() throws Exception { + ImmutableList oversizedHostnames = + IntStream.range(0, 200) + .mapToObj(i -> String.format("epp-host-%03d.registrar.example.tld", i)) + .collect(toImmutableList()); + channel.attr(CLIENT_CERTIFICATE_CHAIN_VALIDATED_KEY).set(true); + channel.attr(CLIENT_CERTIFICATE_HOSTNAMES_KEY).set(oversizedHostnames); + setHandshakeSuccess(); + + String expectedHeader = + formatHostnamesHeader(oversizedHostnames, getCertificateHash(clientCertificate)) + .orElseThrow(); + assertThat(expectedHeader.length()).isAtMost(MAX_HOSTNAMES_HEADER_BYTES); + assertThat(expectedHeader.length()).isLessThan(String.join(",", oversizedHostnames).length()); + FullHttpRequest helloRequest = channel.readInbound(); + FullHttpRequest expectedHelloRequest = makeEppHttpRequest(HELLO); + expectedHelloRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, "true"); + expectedHelloRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, expectedHeader); + assertHttpRequestEquivalent(helloRequest, expectedHelloRequest); + + String loginContent = ""; + channel.writeInbound(Unpooled.wrappedBuffer(loginContent.getBytes(UTF_8))); + FullHttpRequest loginRequest = channel.readInbound(); + FullHttpRequest expectedLoginRequest = makeEppHttpRequest(loginContent); + expectedLoginRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED, "true"); + expectedLoginRequest.headers().set(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, expectedHeader); + assertHttpRequestEquivalent(loginRequest, expectedLoginRequest); + assertThat((Object) channel.readInbound()).isNull(); + assertThat(channel.isActive()).isTrue(); + } + + @Test + void testSuccess_integratedPipelineWithSslServerInitializer() throws Exception { + Instant validFrom = Instant.EPOCH; + Instant validTo = Instant.parse("2100-01-01T00:00:00Z"); + SelfSignedCaCertificate serverSsc = + SelfSignedCaCertificate.create("www.example.tld", validFrom, validTo); + SelfSignedCaCertificate rootCa = + SelfSignedCaCertificate.create("root-ca.tld", validFrom, validTo); + SelfSignedCaCertificate untrustedCa = + SelfSignedCaCertificate.create("untrusted-ca.tld", validFrom, validTo); + KeyPair intermediateKeyPair = getKeyPair(); + X509Certificate intermediateCa = + signIntermediateCa(rootCa, intermediateKeyPair, "intermediate-ca.tld", validFrom, validTo); + KeyPair clientKeyPair = getKeyPair(); + X509Certificate trustedLeaf = + signKeyPair( + intermediateKeyPair.getPrivate(), + intermediateCa, + clientKeyPair, + "Ignored.CN.TLD", + validFrom, + validTo, + "EPP1.Example.TLD", + "epp2.example.tld", + "*.wild.example"); + X509Certificate untrustedLeaf = + signKeyPairWithSans(untrustedCa, clientKeyPair, "ignored.cn.tld", "epp.untrusted.tld"); + + X509TrustManager trustManager = createTrustManager(rootCa.cert()); + SslServerInitializer sslServerInitializer = + createSslServerInitializer( + true, + true, + SslProvider.JDK, + serverSsc.key(), + ImmutableList.of(serverSsc.cert()), + trustManager); + + record CapturedRequest(HttpHeaders headers, String body) {} + BlockingQueue capturedRequests = new LinkedBlockingQueue<>(); + LocalAddress localAddress = new LocalAddress("INTEGRATED_SSL_EPP_PIPELINE"); + EventLoopGroup eventLoopGroup = new DefaultEventLoopGroup(2); + Channel serverChannel = null; + Channel trustedClient = null; + Channel untrustedClient = null; + try { + serverChannel = + new ServerBootstrap() + .group(eventLoopGroup) + .channel(LocalServerChannel.class) + .childHandler( + new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) { + ch.attr(REMOTE_ADDRESS_KEY).set(CLIENT_ADDRESS); + ch.pipeline() + .addLast( + sslServerInitializer, + new EppServiceHandler( + RELAY_HOST, + RELAY_PATH, + false, + () -> ID_TOKEN, + HELLO.getBytes(UTF_8), + metrics), + new SimpleChannelInboundHandler() { + @Override + protected void channelRead0( + ChannelHandlerContext ctx, FullHttpRequest msg) { + HttpHeaders headersCopy = new DefaultHttpHeaders(); + headersCopy.add(msg.headers()); + capturedRequests.add( + new CapturedRequest( + headersCopy, msg.content().toString(UTF_8))); + } + }); + } + }) + .bind(localAddress) + .syncUninterruptibly() + .channel(); + + trustedClient = + connectMtlsClient( + eventLoopGroup, + localAddress, + serverSsc.cert(), + clientKeyPair, + trustedLeaf, + intermediateCa); + CapturedRequest trustedHello = capturedRequests.poll(10, TimeUnit.SECONDS); + assertThat(trustedHello).isNotNull(); + assertThat(trustedHello.body()).isEqualTo(HELLO); + assertThat(trustedHello.headers().get(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(getCertificateHash(trustedLeaf)); + assertThat(trustedHello.headers().get(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("true"); + assertThat(trustedHello.headers().get(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)) + .isEqualTo("epp1.example.tld,epp2.example.tld"); + + untrustedClient = + connectMtlsClient( + eventLoopGroup, localAddress, serverSsc.cert(), clientKeyPair, untrustedLeaf); + CapturedRequest untrustedHello = capturedRequests.poll(10, TimeUnit.SECONDS); + assertThat(untrustedHello).isNotNull(); + assertThat(untrustedHello.body()).isEqualTo(HELLO); + assertThat(untrustedHello.headers().get(ProxyHttpHeaders.CERTIFICATE_HASH)) + .isEqualTo(getCertificateHash(untrustedLeaf)); + assertThat(untrustedHello.headers().get(ProxyHttpHeaders.CERTIFICATE_CHAIN_VALIDATED)) + .isEqualTo("false"); + assertThat(untrustedHello.headers().contains(ProxyHttpHeaders.CERTIFICATE_HOSTNAMES)) + .isFalse(); + } finally { + if (trustedClient != null) { + trustedClient.close().syncUninterruptibly(); + } + if (untrustedClient != null) { + untrustedClient.close().syncUninterruptibly(); + } + if (serverChannel != null) { + serverChannel.close().syncUninterruptibly(); + } + eventLoopGroup.shutdownGracefully().syncUninterruptibly(); + } + } + + private static Channel connectMtlsClient( + EventLoopGroup eventLoopGroup, + LocalAddress localAddress, + X509Certificate serverCert, + KeyPair clientKeyPair, + X509Certificate... clientChain) + throws Exception { + Channel clientChannel = + new Bootstrap() + .group(eventLoopGroup) + .channel(LocalChannel.class) + .handler( + new ChannelInitializer() { + @Override + protected void initChannel(LocalChannel ch) throws Exception { + SslHandler sslHandler = + SslContextBuilder.forClient() + .sslProvider(SslProvider.JDK) + .trustManager(serverCert) + .keyManager(clientKeyPair.getPrivate(), clientChain) + .build() + .newHandler(ch.alloc(), "www.example.tld", 12345); + ch.pipeline().addLast(sslHandler); + } + }) + .connect(localAddress) + .syncUninterruptibly() + .channel(); + clientChannel.pipeline().get(SslHandler.class).handshakeFuture().get(10, TimeUnit.SECONDS); + return clientChannel; + } } diff --git a/util/src/main/java/google/registry/util/ProxyHttpHeaders.java b/util/src/main/java/google/registry/util/ProxyHttpHeaders.java index 471905e8c78..e78a16a8471 100644 --- a/util/src/main/java/google/registry/util/ProxyHttpHeaders.java +++ b/util/src/main/java/google/registry/util/ProxyHttpHeaders.java @@ -22,6 +22,23 @@ public final class ProxyHttpHeaders { /** HTTP header name used to pass the certificate hash from the proxy to Nomulus. */ public static final String CERTIFICATE_HASH = "X-SSL-Certificate"; + /** + * HTTP header name used to pass whether the client TLS certificate chain validated against the + * trusted root CAs ("true" or "false"). + */ + public static final String CERTIFICATE_CHAIN_VALIDATED = "X-SSL-Certificate-Chain-Validated"; + + /** + * HTTP header name used to pass the comma-separated, canonicalized, deduplicated DNS hostnames + * (excluding wildcard names) extracted from a client TLS certificate's Subject Alternative Name + * {@code dNSName} entries. {@code SslServerInitializer} populates the channel attribute only when + * chain validation succeeds, and the EPP handlers format, truncate on whole-hostname boundaries + * to at most {@link X509Utils#MAX_HOSTNAMES_HEADER_BYTES} bytes, and emit this header when + * non-empty. Consumers must still verify {@link #CERTIFICATE_CHAIN_VALIDATED} is {@code "true"} + * before trusting this header. + */ + public static final String CERTIFICATE_HOSTNAMES = "X-SSL-Certificate-Hostnames"; + /** * HTTP header name passed from Nomulus to proxy to indicate that an EPP session should be closed. */ diff --git a/util/src/main/java/google/registry/util/X509Utils.java b/util/src/main/java/google/registry/util/X509Utils.java index 51df21817b7..9babbb52ec4 100644 --- a/util/src/main/java/google/registry/util/X509Utils.java +++ b/util/src/main/java/google/registry/util/X509Utils.java @@ -15,42 +15,139 @@ package google.registry.util; import static com.google.common.base.MoreObjects.firstNonNull; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.throwIfInstanceOf; +import static com.google.common.collect.ImmutableList.toImmutableList; +import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.MoreCollectors.onlyElement; import static com.google.common.io.BaseEncoding.base64; +import static google.registry.util.DomainNameUtils.canonicalizeAndValidateHostname; import static java.nio.charset.StandardCharsets.US_ASCII; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Ascii; +import com.google.common.base.CharMatcher; +import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.flogger.FluentLogger; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; +import java.security.KeyStore; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CRLException; import java.security.cert.CRLReason; +import java.security.cert.CertPathValidatorException; +import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.CertificateRevokedException; +import java.security.cert.PKIXBuilderParameters; +import java.security.cert.PKIXCertPathChecker; +import java.security.cert.TrustAnchor; import java.security.cert.X509CRL; import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; import java.time.Instant; +import java.util.Arrays; import java.util.Base64; +import java.util.Collection; +import java.util.Collections; import java.util.Date; +import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; import javax.annotation.Nullable; import javax.annotation.Tainted; +import javax.net.ssl.CertPathTrustManagerParameters; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.KeyPurposeId; /** X.509 Public Key Infrastructure (PKI) helper functions. */ public final class X509Utils { + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); + + /** + * Maximum byte length of the {@link ProxyHttpHeaders#CERTIFICATE_HOSTNAMES} HTTP header value + * (leaving headroom below Jetty's 8 KB request header limit for cookies, OIDC bearer tokens, and + * other headers). + */ + public static final int MAX_HOSTNAMES_HEADER_BYTES = 4096; + + /** + * Maximum certificate chain length accepted for PKIX validation, matching OpenJDK's {@code + * jdk.tls.maxCertificateChainLength} default. OpenJDK already enforces this limit during the TLS + * handshake under {@code SslProvider.JDK}, while BoringSSL ({@code SslProvider.OPENSSL}) only + * bounds raw byte size ({@code max_cert_list}), so this guards against unbounded PKIX CPU work on + * untrusted chains across both providers. + */ + public static final int MAX_CERTIFICATE_CHAIN_LENGTH = 10; + + /** + * Maximum total DER-encoded byte size of a peer certificate chain (matching OpenJDK's 32 KB + * {@code jdk.tls.maxHandshakeMessageSize} default) to bound unauthenticated EventLoop work. + */ + public static final int MAX_CERTIFICATE_CHAIN_BYTES = 32 * 1024; + + // Permits up to 5-cert chains (Root -> I1 -> I2 -> I3 -> Leaf) while bounding PKIX backtracking. + private static final int MAX_PKIX_PATH_LENGTH = 3; + + private static final ImmutableSet ALLOWED_EKU_OIDS = + ImmutableSet.of( + KeyPurposeId.id_kp_serverAuth.getId(), KeyPurposeId.anyExtendedKeyUsage.getId()); + + // SHA-1 signature OIDs: sha1WithRSAEncryption, ecdsa-with-SHA1, dsa-with-sha1, sha1WithRSA (OIW). + private static final ImmutableSet SHA1_SIGNATURE_OIDS = + ImmutableSet.of( + "1.2.840.113549.1.1.5", "1.2.840.10045.4.1", "1.2.840.10040.4.3", "1.3.14.3.2.29"); + + private static final CharMatcher HEADER_SAFE_HOSTNAME_CHARS = + CharMatcher.inRange('!', '~').and(CharMatcher.isNot(',')); + + private static final String UNKNOWN_AUTH_TYPE = "UNKNOWN"; + + private static final Supplier DEFAULT_TRUST_MANAGER = + Suppliers.memoize(X509Utils::loadDefaultTrustManager); + + /** Result of validating a client TLS certificate chain against trusted root CAs. */ + public record CertificateChainValidationResult(Optional failureReason) { + + private static final CertificateChainValidationResult VALID = + new CertificateChainValidationResult(Optional.empty()); + + public CertificateChainValidationResult { + checkNotNull(failureReason, "failureReason"); + failureReason.ifPresent( + reason -> checkArgument(!reason.isBlank(), "failureReason must not be blank")); + } + + public boolean valid() { + return failureReason.isEmpty(); + } + + public static CertificateChainValidationResult ok() { + return VALID; + } + + public static CertificateChainValidationResult failed(String failureReason) { + return new CertificateChainValidationResult(Optional.of(failureReason)); + } + } + /** * Parse the encoded certificate and return a base64 encoded string (without padding) of the * SHA-256 digest of the certificate. @@ -198,5 +295,281 @@ public static String encodeX509Certificate(X509Certificate certificate) return Base64.getEncoder().encodeToString(certificate.getEncoded()); } + /** + * Returns a PKIX {@link X509TrustManager} initialized with the JVM's default truststore (loaded + * once and memoized). + */ + public static X509TrustManager getDefaultTrustManager() { + return DEFAULT_TRUST_MANAGER.get(); + } + + private static X509TrustManager loadDefaultTrustManager() { + try { + TrustManagerFactory defaultFactory = TrustManagerFactory.getInstance("PKIX"); + defaultFactory.init((KeyStore) null); + X509TrustManager defaultTrustManager = findX509TrustManager(defaultFactory); + return createPkixTrustManager(Arrays.asList(defaultTrustManager.getAcceptedIssuers())); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Failed to initialize default PKIX X509TrustManager", e); + } + } + + /** + * Creates a PKIX {@link X509TrustManager} for the given trusted root certificates with online + * revocation explicitly disabled, bounded path length, and intermediate EKU + SHA-1 enforcement. + */ + @VisibleForTesting + static X509TrustManager createPkixTrustManager(Collection trustedRoots) { + checkNotNull(trustedRoots, "trustedRoots"); + try { + ImmutableSet trustAnchors = + trustedRoots.stream().map(cert -> new TrustAnchor(cert, null)).collect(toImmutableSet()); + PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, null); + // Explicitly disable online CRL/OCSP revocation checks regardless of JVM-wide + // com.sun.net.ssl.checkRevocation so we never perform blocking network I/O on the Netty + // EventLoop thread. + pkixParams.setRevocationEnabled(false); + pkixParams.setMaxPathLength(MAX_PKIX_PATH_LENGTH); + pkixParams.addCertPathChecker(new TlsChainPolicyCertPathChecker()); + TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX"); + factory.init(new CertPathTrustManagerParameters(pkixParams)); + return findX509TrustManager(factory); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Failed to initialize PKIX X509TrustManager", e); + } + } + + /** + * Enforces TLS {@code serverAuth} EKU and rejects SHA-1 signatures on every non-anchor + * certificate (leaf and intermediates) in a PKIX path. + */ + private static final class TlsChainPolicyCertPathChecker extends PKIXCertPathChecker { + + @Override + public void init(boolean forward) {} + + @Override + public boolean isForwardCheckingSupported() { + return true; + } + + @Override + @Nullable + public Set getSupportedExtensions() { + return null; + } + + @Override + public void check(Certificate cert, Collection unresolvedCritExts) + throws CertPathValidatorException { + if (!(cert instanceof X509Certificate x509Cert)) { + throw new CertPathValidatorException("Certificate is not an X509Certificate"); + } + if (SHA1_SIGNATURE_OIDS.contains(firstNonNull(x509Cert.getSigAlgOID(), ""))) { + throw new CertPathValidatorException( + "Disallowed SHA-1 signature algorithm: " + x509Cert.getSigAlgOID()); + } + try { + List eku = x509Cert.getExtendedKeyUsage(); + if (eku != null && Collections.disjoint(eku, ALLOWED_EKU_OIDS)) { + throw new CertPathValidatorException( + "Extended key usage does not permit TLS server authentication: " + eku); + } + } catch (CertificateParsingException e) { + throw new CertPathValidatorException("Failed to parse ExtendedKeyUsage extension", e); + } + } + } + + private static X509TrustManager findX509TrustManager(TrustManagerFactory trustManagerFactory) { + return Arrays.stream(trustManagerFactory.getTrustManagers()) + .filter(X509TrustManager.class::isInstance) + .map(X509TrustManager.class::cast) + .findFirst() + .orElseThrow(() -> new IllegalStateException("No X509TrustManager found")); + } + + /** + * Validates the client TLS certificate chain against the given {@link X509TrustManager}. + * + *

Validates all chains via {@link X509TrustManager#checkServerTrusted} (with authType {@code + * "UNKNOWN"}) so publicly trusted TLS certificates (including {@code serverAuth}-only leaves such + * as Let's Encrypt post-2026-07-08, dual-EKU, {@code anyExtendedKeyUsage}, and no-EKU leaves) are + * accepted under CA/B Forum TLS Baseline Requirements while enforcing OpenJDK's {@code TLSServer} + * CA-distrust policies, intermediate/leaf EKU and SHA-1 policies, chain length and byte limits, + * and rejecting {@code clientAuth}-only and non-TLS EKUs. Validation and parsing errors from peer + * certificates are returned as failed results rather than thrown. + */ + public static CertificateChainValidationResult validateCertificateChain( + @Nullable Certificate[] peerCertificates, X509TrustManager trustManager) { + checkNotNull(trustManager, "trustManager"); + if (peerCertificates == null || peerCertificates.length == 0) { + return CertificateChainValidationResult.failed("No peer certificates presented"); + } + if (peerCertificates.length > MAX_CERTIFICATE_CHAIN_LENGTH) { + return CertificateChainValidationResult.failed( + String.format( + "Certificate chain length %d exceeds maximum of %d", + peerCertificates.length, MAX_CERTIFICATE_CHAIN_LENGTH)); + } + if (!(peerCertificates[0] instanceof X509Certificate)) { + return CertificateChainValidationResult.failed("Leaf certificate is not an X509Certificate"); + } + try { + X509Certificate[] x509Chain = materializeChain(peerCertificates); + X509Certificate leafCert = x509Chain[0]; + if (leafCert.getBasicConstraints() != -1) { + return CertificateChainValidationResult.failed("Leaf certificate must not be a CA"); + } + // Explicitly check leaf dates (PKIX builds a 0-length path if the leaf is a trust anchor). + leafCert.checkValidity(); + trustManager.checkServerTrusted(x509Chain, UNKNOWN_AUTH_TYPE); + return CertificateChainValidationResult.ok(); + } catch (CertificateException | RuntimeException e) { + logger.atFine().withCause(e).log("Certificate chain validation did not succeed."); + String reason = e.toString(); + return CertificateChainValidationResult.failed( + reason != null && !reason.isBlank() ? reason : e.getClass().getName()); + } + } + + // Enforces MAX_CERTIFICATE_CHAIN_BYTES and parses each DER certificate once via JDK's + // CertificateFactory so Netty's LazyX509Certificate isn't re-parsed during PKIX backtracking. + private static X509Certificate[] materializeChain(Certificate[] peerCertificates) + throws CertificateException { + CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + ImmutableList.Builder chain = + ImmutableList.builderWithExpectedSize(peerCertificates.length); + long totalBytes = 0; + for (Certificate cert : peerCertificates) { + if (!(cert instanceof X509Certificate x509Cert)) { + continue; + } + byte[] encoded = x509Cert.getEncoded(); + if (encoded == null) { + chain.add(x509Cert); + continue; + } + totalBytes += encoded.length; + if (totalBytes > MAX_CERTIFICATE_CHAIN_BYTES) { + throw new CertificateException( + String.format( + "Certificate chain size exceeds maximum of %d bytes", MAX_CERTIFICATE_CHAIN_BYTES)); + } + chain.add( + (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encoded))); + } + return chain.build().toArray(new X509Certificate[0]); + } + + /** + * Extracts canonicalized, deduplicated DNS hostnames (excluding wildcard names) from the + * certificate's Subject Alternative Name {@code dNSName} entries. + * + *

Per RFC 9525 section 6.2 and CA/Browser Forum TLS Baseline Requirements, Subject Common Name + * (CN) fallback is not supported (CN fallback also bypasses OpenJDK PKIX {@code NameConstraints} + * checks on multi-CN, trailing-dot, and Unicode CN values). + */ + public static ImmutableList extractHostnames(X509Certificate certificate) { + checkNotNull(certificate, "certificate"); + Collection> sanEntries; + try { + sanEntries = certificate.getSubjectAlternativeNames(); + } catch (CertificateParsingException | RuntimeException e) { + logger.atWarning().withCause(e).log( + "Failed to parse Subject Alternative Names from certificate."); + return ImmutableList.of(); + } + if (sanEntries == null) { + return ImmutableList.of(); + } + return sanEntries.stream() + .filter( + entry -> + entry != null + && entry.size() >= 2 + && Integer.valueOf(GeneralName.dNSName).equals(entry.get(0)) + && entry.get(1) instanceof String) + .map(entry -> (String) entry.get(1)) + .map(X509Utils::normalizeCertificateHostname) + .flatMap(Optional::stream) + .distinct() + .collect(toImmutableList()); + } + + /** + * Formats extracted hostnames as a comma-separated HTTP header value bounded to {@link + * #MAX_HOSTNAMES_HEADER_BYTES} bytes, truncating only on whole-hostname boundaries. Callers must + * pass pre-validated, canonicalized (ASCII) hostnames from {@link + * #extractHostnames(X509Certificate)}. Returns {@link Optional#empty()} if {@code hostnames} is + * null, empty, or no hostname fits within the limit. + */ + public static Optional formatHostnamesHeader( + @Nullable ImmutableList hostnames, @Nullable String certificateHash) { + if (hostnames == null || hostnames.isEmpty()) { + return Optional.empty(); + } + StringBuilder header = new StringBuilder(); + int includedCount = 0; + boolean truncated = false; + for (String hostname : hostnames) { + if (hostname.isEmpty() || !HEADER_SAFE_HOSTNAME_CHARS.matchesAllOf(hostname)) { + continue; + } + int separatorLength = header.isEmpty() ? 0 : 1; + if (header.length() + separatorLength + hostname.length() > MAX_HOSTNAMES_HEADER_BYTES) { + truncated = true; + break; + } + if (separatorLength > 0) { + header.append(','); + } + header.append(hostname); + includedCount++; + } + if (truncated) { + String hash = firstNonNull(certificateHash, "unknown"); + if (header.isEmpty()) { + logger.atWarning().log( + "Client certificate (hash=%s) omitted %s header: 0 of %d hostname(s) fit within %d" + + " bytes.", + hash, + ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, + hostnames.size(), + MAX_HOSTNAMES_HEADER_BYTES); + return Optional.empty(); + } + logger.atWarning().log( + "Client certificate (hash=%s) truncated %s header: kept %d of %d hostnames (%d bytes," + + " limit %d bytes).", + hash, + ProxyHttpHeaders.CERTIFICATE_HOSTNAMES, + includedCount, + hostnames.size(), + header.length(), + MAX_HOSTNAMES_HEADER_BYTES); + } + return header.isEmpty() ? Optional.empty() : Optional.of(header.toString()); + } + + // Enforce ASCII-only, no trailing dot, and exact post-canonicalization parity with OpenJDK's + // case-insensitive ASCII NameConstraints matching (OpenJDK's DNSName preserves trailing dots and + // decodes raw non-ASCII IA5String bytes >= 0x80 as U+FFFD, so stripping trailing dots or + // UTS46-rewriting non-ASCII values would bypass excludedSubtrees). + private static Optional normalizeCertificateHostname(String raw) { + if (raw == null + || raw.isEmpty() + || raw.endsWith(".") + || !CharMatcher.ascii().matchesAllOf(raw)) { + return Optional.empty(); + } + try { + String canonical = canonicalizeAndValidateHostname(raw); + return canonical.equals(Ascii.toLowerCase(raw)) ? Optional.of(canonical) : Optional.empty(); + } catch (IllegalArgumentException e) { + return Optional.empty(); + } + } + private X509Utils() {} } diff --git a/util/src/test/java/google/registry/util/X509UtilsTest.java b/util/src/test/java/google/registry/util/X509UtilsTest.java new file mode 100644 index 00000000000..cff0dec1e1b --- /dev/null +++ b/util/src/test/java/google/registry/util/X509UtilsTest.java @@ -0,0 +1,1463 @@ +// Copyright 2026 The Nomulus Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package google.registry.util; + +import static com.google.common.collect.ImmutableList.toImmutableList; +import static com.google.common.truth.Truth.assertThat; +import static google.registry.util.X509Utils.MAX_CERTIFICATE_CHAIN_BYTES; +import static google.registry.util.X509Utils.MAX_CERTIFICATE_CHAIN_LENGTH; +import static google.registry.util.X509Utils.MAX_HOSTNAMES_HEADER_BYTES; +import static google.registry.util.X509Utils.createPkixTrustManager; +import static google.registry.util.X509Utils.extractHostnames; +import static google.registry.util.X509Utils.formatHostnamesHeader; +import static google.registry.util.X509Utils.getDefaultTrustManager; +import static google.registry.util.X509Utils.validateCertificateChain; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.time.ZoneOffset.UTC; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.base.Splitter; +import com.google.common.collect.ImmutableList; +import com.google.common.testing.TestLogHandler; +import google.registry.util.X509Utils.CertificateChainValidationResult; +import java.io.ByteArrayInputStream; +import java.math.BigInteger; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.ProviderException; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.CertificateParsingException; +import java.security.cert.X509Certificate; +import java.security.spec.ECGenParameterSpec; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import java.util.stream.IntStream; +import javax.annotation.Nullable; +import javax.net.ssl.X509TrustManager; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.DERGeneralizedTime; +import org.bouncycastle.asn1.DEROctetString; +import org.bouncycastle.asn1.DERSequence; +import org.bouncycastle.asn1.DERTaggedObject; +import org.bouncycastle.asn1.DERUTCTime; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.BCStyle; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.CRLDistPoint; +import org.bouncycastle.asn1.x509.DistributionPoint; +import org.bouncycastle.asn1.x509.DistributionPointName; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.GeneralSubtree; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.asn1.x509.NameConstraints; +import org.bouncycastle.asn1.x509.Time; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Unit tests for {@link X509Utils}. */ +class X509UtilsTest { + + private static final Instant VALID_FROM = Instant.EPOCH; + private static final Instant VALID_TO = Instant.parse("2100-01-01T00:00:00Z"); + private static final Instant EXPIRED_FROM = Instant.parse("2000-01-01T00:00:00Z"); + private static final Instant EXPIRED_TO = Instant.parse("2000-01-02T00:00:00Z"); + private static final Instant FUTURE_FROM = Instant.parse("2099-01-01T00:00:00Z"); + private static final Instant FUTURE_TO = Instant.parse("2099-01-02T00:00:00Z"); + + private static final BouncyCastleProvider PROVIDER = new BouncyCastleProvider(); + private static final AtomicLong SERIAL_NUMBER = new AtomicLong(1); + private static final DateTimeFormatter UTC_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyMMddHHmmss'Z'").withZone(UTC); + private static final DateTimeFormatter GENERALIZED_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'").withZone(UTC); + + private static SelfSignedCaCertificate rootCa; + private static SelfSignedCaCertificate untrustedCa; + private static X509TrustManager rootTrustManager; + private static KeyPair leafKeyPair; + private static KeyPair intermediateKeyPair; + private static X509Certificate intermediateCa; + + @FunctionalInterface + private interface CertCustomizer { + void customize(X509v3CertificateBuilder builder) throws Exception; + } + + @BeforeAll + static void setUpSharedFixtures() throws Exception { + KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA", PROVIDER); + rsaGen.initialize(2048, new SecureRandom()); + leafKeyPair = rsaGen.generateKeyPair(); + intermediateKeyPair = rsaGen.generateKeyPair(); + + rootCa = SelfSignedCaCertificate.create("root-ca.tld", VALID_FROM, VALID_TO); + untrustedCa = SelfSignedCaCertificate.create("untrusted-ca.tld", VALID_FROM, VALID_TO); + rootTrustManager = createTrustManager(rootCa.cert()); + intermediateCa = + signCert( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + new X500Name("CN=intermediate-ca.tld"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))); + } + + // Construct ASN.1 Time directly because :runPresubmits bans legacy Date in new files. + private static Time toAsn1Time(Instant instant) { + return instant.atOffset(UTC).getYear() >= 2050 + ? new Time(new DERGeneralizedTime(GENERALIZED_TIME_FORMATTER.format(instant))) + : new Time(new DERUTCTime(UTC_TIME_FORMATTER.format(instant))); + } + + private static X509TrustManager createTrustManager(X509Certificate... trustedCerts) { + return createPkixTrustManager(Arrays.asList(trustedCerts)); + } + + private static void assertChainValid(Certificate[] certs, X509TrustManager trustManager) { + CertificateChainValidationResult result = validateCertificateChain(certs, trustManager); + assertThat(result.valid()).isTrue(); + assertThat(result.failureReason()).isEmpty(); + } + + private static CertificateChainValidationResult assertChainInvalid( + @Nullable Certificate[] certs, X509TrustManager trustManager) { + CertificateChainValidationResult result = validateCertificateChain(certs, trustManager); + assertThat(result.valid()).isFalse(); + assertThat(result.failureReason()).isPresent(); + assertThat(result.failureReason().get()).isNotEmpty(); + return result; + } + + private static X509Certificate signCert( + PrivateKey issuerKey, + X509Certificate issuerCert, + PublicKey subjectKey, + X500Name subjectDn, + Instant from, + Instant to, + @Nullable CertCustomizer customizer) + throws Exception { + String sigAlg = + "EC".equals(issuerKey.getAlgorithm()) ? "SHA256WithECDSA" : "SHA256WithRSAEncryption"; + return signCertWithAlgorithm( + issuerKey, + X500Name.getInstance(issuerCert.getSubjectX500Principal().getEncoded()), + subjectKey, + subjectDn, + from, + to, + sigAlg, + customizer); + } + + private static X509Certificate signCertWithAlgorithm( + PrivateKey issuerKey, + X500Name issuerDn, + PublicKey subjectKey, + X500Name subjectDn, + Instant from, + Instant to, + String sigAlg, + @Nullable CertCustomizer customizer) + throws Exception { + ContentSigner sigGen = new JcaContentSignerBuilder(sigAlg).build(issuerKey); + X509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuerDn, + BigInteger.valueOf(SERIAL_NUMBER.incrementAndGet()), + toAsn1Time(from), + toAsn1Time(to), + subjectDn, + subjectKey); + if (customizer != null) { + customizer.customize(builder); + } + return new JcaX509CertificateConverter() + .setProvider(PROVIDER) + .getCertificate(builder.build(sigGen)); + } + + private static X509Certificate signLeaf(SelfSignedCaCertificate ssc, String cn, String... dnsSans) + throws Exception { + return signCert( + ssc.key(), + ssc.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=" + cn), + VALID_FROM, + VALID_TO, + dnsSans.length == 0 ? null : builder -> addDnsSans(builder, dnsSans)); + } + + private static X509Certificate signLeafWithGeneralNames( + X500Name subjectDn, GeneralName... subjectAltNames) throws Exception { + return signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + subjectDn, + VALID_FROM, + VALID_TO, + subjectAltNames.length == 0 + ? null + : builder -> + builder.addExtension( + Extension.subjectAlternativeName, false, new GeneralNames(subjectAltNames))); + } + + private static void addDnsSans(X509v3CertificateBuilder builder, String... dnsSans) + throws Exception { + GeneralName[] generalNames = + Arrays.stream(dnsSans) + .map(san -> new GeneralName(GeneralName.dNSName, san)) + .toArray(GeneralName[]::new); + builder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(generalNames)); + } + + private static void addEku(X509v3CertificateBuilder builder, KeyPurposeId... purposes) + throws Exception { + builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(purposes)); + } + + private static X509Certificate signIntermediate( + PrivateKey issuerKey, + X509Certificate issuerCert, + PublicKey subjectKey, + String cn, + @Nullable CertCustomizer customizer) + throws Exception { + return signCert( + issuerKey, + issuerCert, + subjectKey, + new X500Name("CN=" + cn), + VALID_FROM, + VALID_TO, + builder -> { + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); + if (customizer != null) { + customizer.customize(builder); + } + }); + } + + private static X509Certificate toJdkCertificate(X509Certificate cert) throws Exception { + return (X509Certificate) + CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(cert.getEncoded())); + } + + @Test + void testCertificateChainValidationResult_validation() { + assertThat(CertificateChainValidationResult.ok().valid()).isTrue(); + assertThat(CertificateChainValidationResult.ok().failureReason()).isEmpty(); + assertThrows(NullPointerException.class, () -> new CertificateChainValidationResult(null)); + assertThrows(NullPointerException.class, () -> CertificateChainValidationResult.failed(null)); + assertThrows(IllegalArgumentException.class, () -> CertificateChainValidationResult.failed("")); + assertThrows( + IllegalArgumentException.class, () -> CertificateChainValidationResult.failed(" ")); + } + + @Test + void testGetDefaultTrustManager_returnsNonEmptyMemoizedInstance() throws Exception { + X509TrustManager trustManager = getDefaultTrustManager(); + assertThat(trustManager).isNotNull(); + assertThat(trustManager.getAcceptedIssuers()).isNotEmpty(); + assertThat(getDefaultTrustManager()).isSameInstanceAs(trustManager); + assertChainInvalid( + new Certificate[] {signLeaf(untrustedCa, "epp.untrusted.tld")}, trustManager); + } + + @Test + void testCreatePkixTrustManager_revocationDisabledEvenWhenSystemPropertyEnabled() + throws Exception { + X509Certificate certWithUnreachableCrl = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.crl-dp.example"), + VALID_FROM, + VALID_TO, + builder -> { + GeneralNames crlUri = + new GeneralNames( + new GeneralName( + GeneralName.uniformResourceIdentifier, + "http://127.0.0.1:1/unreachable.crl")); + CRLDistPoint crlDistPoint = + new CRLDistPoint( + new DistributionPoint[] { + new DistributionPoint(new DistributionPointName(crlUri), null, null) + }); + builder.addExtension(Extension.cRLDistributionPoints, false, crlDistPoint); + }); + + String previousCheckRevocation = System.getProperty("com.sun.net.ssl.checkRevocation"); + try { + System.setProperty("com.sun.net.ssl.checkRevocation", "true"); + X509TrustManager trustManager = createPkixTrustManager(ImmutableList.of(rootCa.cert())); + assertChainValid(new Certificate[] {certWithUnreachableCrl}, trustManager); + } finally { + if (previousCheckRevocation == null) { + System.clearProperty("com.sun.net.ssl.checkRevocation"); + } else { + System.setProperty("com.sun.net.ssl.checkRevocation", previousCheckRevocation); + } + } + } + + @Test + void testValidateCertificateChain_directAndMultiTierChains_succeed() throws Exception { + X509Certificate directLeaf = signLeaf(rootCa, "epp.direct.example"); + assertChainValid(new Certificate[] {directLeaf}, rootTrustManager); + assertChainValid(new Certificate[] {directLeaf, rootCa.cert()}, rootTrustManager); + assertChainValid(new Certificate[] {directLeaf, null}, rootTrustManager); + + // 3-tier chain (including out-of-order and extra unrelated CA). + X509Certificate threeTierLeaf = + signCert( + intermediateKeyPair.getPrivate(), + intermediateCa, + leafKeyPair.getPublic(), + new X500Name("CN=epp.three-tier.example"), + VALID_FROM, + VALID_TO, + null); + assertChainValid(new Certificate[] {threeTierLeaf, intermediateCa}, rootTrustManager); + assertChainValid( + new Certificate[] {threeTierLeaf, rootCa.cert(), intermediateCa}, rootTrustManager); + assertChainValid( + new Certificate[] {threeTierLeaf, intermediateCa, untrustedCa.cert()}, rootTrustManager); + + // Explicit critical BasicConstraints(cA=false) leaf is accepted (getBasicConstraints() == -1). + X509Certificate explicitNonCaLeaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.nonca.example"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension( + Extension.basicConstraints, true, new BasicConstraints(false))); + assertChainValid(new Certificate[] {explicitNonCaLeaf}, rootTrustManager); + + // Exact MAX_CERTIFICATE_CHAIN_LENGTH (10) succeeds. + Certificate[] exactMaxChain = new Certificate[MAX_CERTIFICATE_CHAIN_LENGTH]; + exactMaxChain[0] = directLeaf; + Arrays.fill(exactMaxChain, 1, MAX_CERTIFICATE_CHAIN_LENGTH, rootCa.cert()); + assertChainValid(exactMaxChain, rootTrustManager); + } + + @Test + void testValidateCertificateChain_ecdsaAndEd25519Chains_succeed() throws Exception { + KeyPairGenerator ecGen = KeyPairGenerator.getInstance("EC", PROVIDER); + ecGen.initialize(new ECGenParameterSpec("secp256r1"), new SecureRandom()); + SelfSignedCaCertificate ecRootCa = + SelfSignedCaCertificate.create( + ecGen.generateKeyPair(), "ec-root-ca.tld", VALID_FROM, VALID_TO); + KeyPair ecInterKeyPair = ecGen.generateKeyPair(); + X509Certificate ecIntermediateCa = + signCert( + ecRootCa.key(), + ecRootCa.cert(), + ecInterKeyPair.getPublic(), + new X500Name("CN=ec-intermediate-ca.tld"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))); + X509Certificate ecLeaf = + signCert( + ecInterKeyPair.getPrivate(), + ecIntermediateCa, + ecGen.generateKeyPair().getPublic(), + new X500Name("CN=epp.ecdsa.example"), + VALID_FROM, + VALID_TO, + builder -> addDnsSans(builder, "epp.ecdsa.example")); + assertChainValid( + new Certificate[] {ecLeaf, ecIntermediateCa}, createTrustManager(ecRootCa.cert())); + + KeyPair ed25519KeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + X509Certificate ed25519Leaf = + signCert( + rootCa.key(), + rootCa.cert(), + ed25519KeyPair.getPublic(), + new X500Name("CN=epp.ed25519.example"), + VALID_FROM, + VALID_TO, + builder -> { + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); + }); + assertChainValid(new Certificate[] {ed25519Leaf}, rootTrustManager); + } + + @Test + void testValidateCertificateChain_supportedExtendedKeyUsages_succeed() throws Exception { + for (ExtendedKeyUsage eku : + ImmutableList.of( + new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth), + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}), + new ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage))) { + X509Certificate leaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.eku.example"), + VALID_FROM, + VALID_TO, + builder -> { + builder.addExtension(Extension.extendedKeyUsage, false, eku); + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + }); + assertChainValid(new Certificate[] {leaf}, rootTrustManager); + } + } + + @Test + void testValidateCertificateChain_alwaysUsesCheckServerTrustedOnly() throws Exception { + X509Certificate leaf = signLeaf(rootCa, "epp.example"); + X509TrustManager acceptingTm = mock(X509TrustManager.class); + doNothing().when(acceptingTm).checkServerTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + assertChainValid(new Certificate[] {leaf}, acceptingTm); + verify(acceptingTm).checkServerTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + verify(acceptingTm, never()).checkClientTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + + X509TrustManager rejectingTm = mock(X509TrustManager.class); + doThrow(new CertificateException("distrusted CA")) + .when(rejectingTm) + .checkServerTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + assertThat(assertChainInvalid(new Certificate[] {leaf}, rejectingTm).failureReason().get()) + .contains("distrusted CA"); + verify(rejectingTm).checkServerTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + verify(rejectingTm, never()).checkClientTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + } + + @Test + void testValidateCertificateChain_missingNonX509OrOversizedChains_rejected() throws Exception { + X509Certificate directLeaf = signLeaf(rootCa, "epp.direct.example"); + assertThat(assertChainInvalid(null, rootTrustManager).failureReason()) + .hasValue("No peer certificates presented"); + assertThat(assertChainInvalid(new Certificate[0], rootTrustManager).failureReason()) + .hasValue("No peer certificates presented"); + assertThat(assertChainInvalid(new Certificate[] {null}, rootTrustManager).failureReason()) + .hasValue("Leaf certificate is not an X509Certificate"); + assertThat( + assertChainInvalid(new Certificate[] {mock(Certificate.class)}, rootTrustManager) + .failureReason()) + .hasValue("Leaf certificate is not an X509Certificate"); + assertThrows( + NullPointerException.class, + () -> validateCertificateChain(new Certificate[] {directLeaf}, null)); + assertThrows(NullPointerException.class, () -> validateCertificateChain(null, null)); + + // Chain exceeding MAX_CERTIFICATE_CHAIN_LENGTH is rejected before calling trustManager. + Certificate[] oversizedChain = new Certificate[MAX_CERTIFICATE_CHAIN_LENGTH + 1]; + oversizedChain[0] = directLeaf; + Arrays.fill(oversizedChain, 1, oversizedChain.length, rootCa.cert()); + X509TrustManager mockTm = mock(X509TrustManager.class); + assertThat(assertChainInvalid(oversizedChain, mockTm).failureReason()) + .hasValue( + String.format( + "Certificate chain length %d exceeds maximum of %d", + MAX_CERTIFICATE_CHAIN_LENGTH + 1, MAX_CERTIFICATE_CHAIN_LENGTH)); + verify(mockTm, never()).checkServerTrusted(any(), any()); + verify(mockTm, never()).checkClientTrusted(any(), any()); + } + + @Test + void testValidateCertificateChain_caAsLeafAndUntrustedChains_rejected() throws Exception { + assertThat( + assertChainInvalid(new Certificate[] {rootCa.cert()}, rootTrustManager).failureReason()) + .hasValue("Leaf certificate must not be a CA"); + assertThat( + assertChainInvalid(new Certificate[] {intermediateCa}, rootTrustManager) + .failureReason()) + .hasValue("Leaf certificate must not be a CA"); + // pathLenConstraint=0 returns getBasicConstraints() == 0 (not > 0); must still be rejected. + X509Certificate pathLen0Ca = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=pathlen0-ca.tld"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0))); + assertThat(assertChainInvalid(new Certificate[] {pathLen0Ca}, rootTrustManager).failureReason()) + .hasValue("Leaf certificate must not be a CA"); + + // Untrusted CA. + X509Certificate untrustedLeaf = signLeaf(untrustedCa, "epp.untrusted.example"); + assertThat( + assertChainInvalid(new Certificate[] {untrustedLeaf}, rootTrustManager) + .failureReason() + .get()) + .contains("PKIX path building failed"); + + // Missing intermediate CA. + X509Certificate threeTierLeaf = + signCert( + intermediateKeyPair.getPrivate(), + intermediateCa, + leafKeyPair.getPublic(), + new X500Name("CN=epp.three-tier.example"), + VALID_FROM, + VALID_TO, + null); + assertChainInvalid(new Certificate[] {threeTierLeaf}, rootTrustManager); + + // Non-CA leaf acting as an intermediate cannot mint valid child certificates. + X509Certificate nonCaIntermediate = + signCert( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + new X500Name("CN=epp.compromised-leaf.example"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension( + Extension.basicConstraints, true, new BasicConstraints(false))); + X509Certificate childUnderNonCa = + signCert( + intermediateKeyPair.getPrivate(), + nonCaIntermediate, + leafKeyPair.getPublic(), + new X500Name("CN=epp.forged-child.example"), + VALID_FROM, + VALID_TO, + null); + assertChainInvalid(new Certificate[] {childUnderNonCa, nonCaIntermediate}, rootTrustManager); + + // Forged signature (claims rootCa issuer DN, signed with untrustedCa's key). + X509Certificate forgedSigLeaf = + signCert( + untrustedCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.forged.example"), + VALID_FROM, + VALID_TO, + null); + assertChainInvalid(new Certificate[] {forgedSigLeaf}, rootTrustManager); + } + + @Test + void testValidateCertificateChain_expiredAndNotYetValid_rejected() throws Exception { + X509Certificate expiredLeaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.expired.example"), + EXPIRED_FROM, + EXPIRED_TO, + null); + assertThat( + assertChainInvalid(new Certificate[] {expiredLeaf}, rootTrustManager) + .failureReason() + .get()) + .contains("CertificateExpiredException:"); + + X509Certificate notYetValidLeaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.future.example"), + FUTURE_FROM, + FUTURE_TO, + null); + assertThat( + assertChainInvalid(new Certificate[] {notYetValidLeaf}, rootTrustManager) + .failureReason() + .get()) + .contains("CertificateNotYetValidException:"); + + // Expired/future leaf pinned directly as a trust anchor (0-length PKIX path) must still fail + // via our explicit leafCert.checkValidity() check. + assertThat( + assertChainInvalid(new Certificate[] {expiredLeaf}, createTrustManager(expiredLeaf)) + .failureReason() + .get()) + .contains("CertificateExpiredException:"); + assertThat( + assertChainInvalid( + new Certificate[] {notYetValidLeaf}, createTrustManager(notYetValidLeaf)) + .failureReason() + .get()) + .contains("CertificateNotYetValidException:"); + + // Expired intermediate CA with a valid leaf. + X509Certificate expiredIntermediate = + signCert( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + new X500Name("CN=expired-intermediate.tld"), + EXPIRED_FROM, + EXPIRED_TO, + builder -> + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))); + X509Certificate leafUnderExpiredInter = + signCert( + intermediateKeyPair.getPrivate(), + expiredIntermediate, + leafKeyPair.getPublic(), + new X500Name("CN=epp.expired-inter.example"), + VALID_FROM, + VALID_TO, + null); + assertChainInvalid( + new Certificate[] {leafUnderExpiredInter, expiredIntermediate}, rootTrustManager); + } + + @Test + void testValidateCertificateChain_disallowedEkuAndKeyUsage_rejected() throws Exception { + for (KeyPurposeId disallowedPurpose : + ImmutableList.of(KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_codeSigning)) { + X509Certificate leaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.disallowed-eku.example"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension( + Extension.extendedKeyUsage, false, new ExtendedKeyUsage(disallowedPurpose))); + CertificateChainValidationResult result = + assertChainInvalid(new Certificate[] {leaf}, rootTrustManager); + assertThat(result.failureReason().get()).contains("Extended key usage"); + } + + // Malformed EKU extension fails closed. + X509Certificate malformedEkuLeaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.malformed-eku.example"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension(Extension.extendedKeyUsage, false, new byte[] {1, 2, 3})); + assertChainInvalid(new Certificate[] {malformedEkuLeaf}, rootTrustManager); + + // Leaf missing digitalSignature KeyUsage (including keyEncipherment-only under "UNKNOWN") is + // rejected. + for (int disallowedKu : ImmutableList.of(KeyUsage.cRLSign, KeyUsage.keyEncipherment)) { + X509Certificate badKuLeaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.badku.example"), + VALID_FROM, + VALID_TO, + builder -> { + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); + builder.addExtension(Extension.keyUsage, true, new KeyUsage(disallowedKu)); + }); + assertChainInvalid(new Certificate[] {badKuLeaf}, rootTrustManager); + } + } + + @Test + void testValidateCertificateChain_runtimeExceptions_failClosedWithoutThrowing() throws Exception { + // LazyX509Certificate-style RuntimeException on leaf inspection fails closed. + X509Certificate brokenLeaf = mock(X509Certificate.class); + when(brokenLeaf.getBasicConstraints()) + .thenThrow(new IllegalStateException(new CertificateException("malformed DER"))); + assertThat( + assertChainInvalid(new Certificate[] {brokenLeaf}, rootTrustManager) + .failureReason() + .get()) + .contains("IllegalStateException"); + + // TrustManager RuntimeException, plus null/blank toString() fallback to class name. + X509Certificate directLeaf = signLeaf(rootCa, "epp.runtime.example"); + X509TrustManager providerExceptionTm = mock(X509TrustManager.class); + doThrow(new ProviderException("provider failure")) + .when(providerExceptionTm) + .checkServerTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + assertThat( + assertChainInvalid(new Certificate[] {directLeaf}, providerExceptionTm) + .failureReason() + .get()) + .contains("provider failure"); + + RuntimeException blankToString = + new RuntimeException() { + @Override + @SuppressWarnings("OverrideThrowableToString") + public String toString() { + return " "; + } + }; + RuntimeException nullToString = + new RuntimeException() { + @Override + @SuppressWarnings({"OverrideThrowableToString", "ToStringReturnsNull"}) + public String toString() { + return null; + } + }; + for (RuntimeException ex : ImmutableList.of(blankToString, nullToString)) { + X509TrustManager tm = mock(X509TrustManager.class); + doThrow(ex).when(tm).checkServerTrusted(any(X509Certificate[].class), eq("UNKNOWN")); + assertThat(assertChainInvalid(new Certificate[] {directLeaf}, tm).failureReason()) + .hasValue(ex.getClass().getName()); + } + } + + @Test + void testExtractHostnames_dnsSansCanonicalization() throws Exception { + // Mixed case, duplicates, punycode, rejected trailing dots, and excluded wildcards. + X509Certificate dnsSanCert = + signLeaf( + rootCa, + "Ignored.CN.Example", + "EPP1.Example.TLD.", + "epp.trailing-only.example.", + "EPP1.Example.TLD", + "epp1.example.tld", + "XN--Q9JYB4C.Example.COM", + "*.Example.COM", + "*.Sub.Example.COM"); + assertThat(extractHostnames(dnsSanCert)) + .containsExactly("epp1.example.tld", "xn--q9jyb4c.example.com") + .inOrder(); + assertThat(extractHostnames(toJdkCertificate(dnsSanCert))) + .containsExactly("epp1.example.tld", "xn--q9jyb4c.example.com") + .inOrder(); + + // Non-DNS SAN types (IP, email, URI) are ignored while DNS SANs are kept. + X509Certificate mixedSanTypesCert = + signLeafWithGeneralNames( + new X500Name("CN=ignored.cn.example"), + new GeneralName(GeneralName.iPAddress, "192.0.2.1"), + new GeneralName(GeneralName.rfc822Name, "ops@example.tld"), + new GeneralName(GeneralName.uniformResourceIdentifier, "https://epp.example.tld"), + new GeneralName(GeneralName.dNSName, "epp.mixed-types.example")); + assertThat(extractHostnames(mixedSanTypesCert)).containsExactly("epp.mixed-types.example"); + assertThat(extractHostnames(toJdkCertificate(mixedSanTypesCert))) + .containsExactly("epp.mixed-types.example"); + + // Malformed SAN list entries (null, short list, non-String value) are skipped. + X509Certificate certWithMalformedSanEntries = mock(X509Certificate.class); + List> mixedMalformedSans = + Arrays.asList( + null, + ImmutableList.of(GeneralName.dNSName), + ImmutableList.of(GeneralName.dNSName, new byte[] {1, 2, 3}), + ImmutableList.of(GeneralName.dNSName, "valid.example.tld")); + when(certWithMalformedSanEntries.getSubjectAlternativeNames()).thenReturn(mixedMalformedSans); + assertThat(extractHostnames(certWithMalformedSanEntries)).containsExactly("valid.example.tld"); + + // RFC 5280 section 4.1.2.6: empty Subject DN with critical SAN validates and extracts cleanly. + X509Certificate emptySubjectCert = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name(""), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension( + Extension.subjectAlternativeName, + true, + new GeneralNames( + new GeneralName(GeneralName.dNSName, "epp.empty-subject.example")))); + assertChainValid(new Certificate[] {emptySubjectCert}, rootTrustManager); + assertThat(extractHostnames(emptySubjectCert)).containsExactly("epp.empty-subject.example"); + } + + @Test + void testValidateCertificateChain_nameConstraints_enforcedAndCnCannotBypass() throws Exception { + X509Certificate constrainedIntermediate = + signCert( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + new X500Name("CN=constrained-intermediate.tld"), + VALID_FROM, + VALID_TO, + builder -> { + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); + builder.addExtension( + Extension.nameConstraints, + true, + new NameConstraints( + new GeneralSubtree[] { + new GeneralSubtree(new GeneralName(GeneralName.dNSName, ".allowed.example")) + }, + null)); + }); + + // Permitted DNS SAN succeeds and extracts cleanly. + X509Certificate permittedLeaf = + signCert( + intermediateKeyPair.getPrivate(), + constrainedIntermediate, + leafKeyPair.getPublic(), + new X500Name("CN=epp.allowed.example"), + VALID_FROM, + VALID_TO, + builder -> addDnsSans(builder, "epp.allowed.example")); + assertChainValid(new Certificate[] {permittedLeaf, constrainedIntermediate}, rootTrustManager); + assertThat(extractHostnames(permittedLeaf)).containsExactly("epp.allowed.example"); + + // Disallowed DNS SAN (including trailing-dot variant) is rejected by PKIX NameConstraints. + for (String disallowedSan : ImmutableList.of("epp.victim.example", "epp.victim.example.")) { + X509Certificate disallowedSanLeaf = + signCert( + intermediateKeyPair.getPrivate(), + constrainedIntermediate, + leafKeyPair.getPublic(), + new X500Name("CN=ok.allowed.example"), + VALID_FROM, + VALID_TO, + builder -> addDnsSans(builder, disallowedSan)); + assertChainInvalid( + new Certificate[] {disallowedSanLeaf, constrainedIntermediate}, rootTrustManager); + } + + // Without a SAN extension, CN-only bypass payloads (trailing dot, multi-CN with permitted or + // display-string last CN, and Unicode IDN CN) never yield extracted hostnames. + ImmutableList cnBypassSubjects = + ImmutableList.of( + new X500Name("CN=epp.victim.example."), + new X500Name("CN=epp.victim.example,CN=ok.allowed.example"), + new X500Name("CN=epp.victim.example,CN=Acme Corp"), + new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, "epp.みんな").build()); + for (X500Name subject : cnBypassSubjects) { + X509Certificate cnOnlyLeaf = + signCert( + intermediateKeyPair.getPrivate(), + constrainedIntermediate, + leafKeyPair.getPublic(), + subject, + VALID_FROM, + VALID_TO, + null); + assertThat(extractHostnames(cnOnlyLeaf)).isEmpty(); + assertThat(extractHostnames(toJdkCertificate(cnOnlyLeaf))).isEmpty(); + } + } + + @Test + void testExtractHostnames_ignoresSubjectCnAndEmptyOrMalformedSans() throws Exception { + // Per RFC 9525 section 6.2, Subject CN is never used even when no SAN extension is present. + X509Certificate cnOnlyCert = signLeafWithGeneralNames(new X500Name("CN=EPP.Fallback.Example.")); + assertThat(extractHostnames(cnOnlyCert)).isEmpty(); + assertThat(extractHostnames(toJdkCertificate(cnOnlyCert))).isEmpty(); + + // Non-DNS SANs and rejected wildcard SANs return empty without falling back to Subject CN. + assertThat( + extractHostnames( + signLeafWithGeneralNames( + new X500Name("CN=fallback.example.tld"), + new GeneralName(GeneralName.iPAddress, "192.0.2.1")))) + .isEmpty(); + assertThat( + extractHostnames( + signLeafWithGeneralNames( + new X500Name("CN=fallback.example.tld"), + new GeneralName(GeneralName.dNSName, "*.com")))) + .isEmpty(); + + // Degenerate empty-SEQUENCE SAN extension returns empty (both BC and JDK). + X509Certificate emptySanSequenceCert = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=fallback.example.tld"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension(Extension.subjectAlternativeName, false, new DERSequence())); + assertThat(extractHostnames(emptySanSequenceCert)).isEmpty(); + assertThat(extractHostnames(toJdkCertificate(emptySanSequenceCert))).isEmpty(); + + // Malformed SAN extension fails closed (both BC and JDK). + X509Certificate malformedSanCert = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=fallback.example.tld"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension( + Extension.subjectAlternativeName, false, new byte[] {0x01, 0x02, 0x03})); + assertThrows(CertificateParsingException.class, malformedSanCert::getSubjectAlternativeNames); + assertThat(extractHostnames(malformedSanCert)).isEmpty(); + assertThat(extractHostnames(toJdkCertificate(malformedSanCert))).isEmpty(); + } + + @Test + void testExtractHostnames_rejectsWildcardsAndInvalidNames() throws Exception { + ImmutableList rejectedNames = + ImmutableList.of( + "", + " ", + "localhost", + "_epp.example.tld", + "*.example.com", + "*.sub.example.com", + "*.com", + "192.0.2.1", + "a.example,b.example", + "evil.example\r\nX-Injected: 1", + "epp.example.tld\0.evil.com"); + for (String rejectedSan : rejectedNames) { + X509Certificate invalidDnsSanCert = + signLeaf(rootCa, "ignored.example", rejectedSan, "valid.example.tld"); + assertThat(extractHostnames(invalidDnsSanCert)).containsExactly("valid.example.tld"); + } + } + + @Test + void testExtractHostnames_handlesNullAndRuntimeExceptions() throws Exception { + assertThrows(NullPointerException.class, () -> extractHostnames(null)); + assertThat(extractHostnames(signLeafWithGeneralNames(new X500Name("O=Example")))).isEmpty(); + + X509Certificate emptySanCollectionCert = mock(X509Certificate.class); + when(emptySanCollectionCert.getSubjectAlternativeNames()).thenReturn(ImmutableList.of()); + assertThat(extractHostnames(emptySanCollectionCert)).isEmpty(); + + X509Certificate throwingSanCert = mock(X509Certificate.class); + when(throwingSanCert.getSubjectAlternativeNames()) + .thenThrow(new IllegalStateException("malformed DER")); + assertThat(extractHostnames(throwingSanCert)).isEmpty(); + } + + @Test + void testValidateCertificateChain_excludedSubtrees_trailingDotAndNonAsciiRejected() + throws Exception { + for (String excludedSubtree : ImmutableList.of("victim.example", ".victim.example")) { + X509Certificate excludedIntermediate = + signIntermediate( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + "excluded-intermediate.tld", + builder -> + builder.addExtension( + Extension.nameConstraints, + true, + new NameConstraints( + null, + new GeneralSubtree[] { + new GeneralSubtree( + new GeneralName(GeneralName.dNSName, excludedSubtree)) + }))); + + String excludedHostname = + excludedSubtree.startsWith(".") ? "epp" + excludedSubtree : excludedSubtree; + X509Certificate plainExcludedLeaf = + signCert( + intermediateKeyPair.getPrivate(), + excludedIntermediate, + leafKeyPair.getPublic(), + new X500Name("CN=" + excludedHostname), + VALID_FROM, + VALID_TO, + builder -> addDnsSans(builder, excludedHostname)); + assertChainInvalid( + new Certificate[] {plainExcludedLeaf, excludedIntermediate}, rootTrustManager); + + // Trailing-dot SANs may slip past OpenJDK's excludedSubtrees check, so extractHostnames() + // must reject them on both BouncyCastle and JDK X509Certificate instances. + X509Certificate trailingDotLeaf = + signCert( + intermediateKeyPair.getPrivate(), + excludedIntermediate, + leafKeyPair.getPublic(), + new X500Name("CN=ignored.example"), + VALID_FROM, + VALID_TO, + builder -> addDnsSans(builder, excludedHostname + ".")); + assertThat(extractHostnames(trailingDotLeaf)).isEmpty(); + assertThat(extractHostnames(toJdkCertificate(trailingDotLeaf))).isEmpty(); + } + + // Raw non-ASCII DER dNSName bytes (0xDF -> 'ß', 0xFC -> 'ü') decode differently in OpenJDK vs + // BouncyCastle and must be rejected by extractHostnames() on both providers. + for (byte[] rawNonAsciiDnsBytes : + ImmutableList.of( + "stra\u00dfe.example".getBytes(ISO_8859_1), + "b\u00fccher.example".getBytes(ISO_8859_1))) { + DERSequence rawSanExtension = + new DERSequence( + new DERTaggedObject( + false, GeneralName.dNSName, new DEROctetString(rawNonAsciiDnsBytes))); + X509Certificate nonAsciiSanLeaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=ignored.example"), + VALID_FROM, + VALID_TO, + builder -> + builder.addExtension( + Extension.subjectAlternativeName, false, rawSanExtension.getEncoded())); + assertThat(extractHostnames(nonAsciiSanLeaf)).isEmpty(); + assertThat(extractHostnames(toJdkCertificate(nonAsciiSanLeaf))).isEmpty(); + } + } + + @Test + void testValidateCertificateChain_intermediateAndLeafEkuPolicy() throws Exception { + KeyPurposeId msSgc = + KeyPurposeId.getInstance(new ASN1ObjectIdentifier("1.3.6.1.4.1.311.10.3.3")); + KeyPurposeId nsSgc = + KeyPurposeId.getInstance(new ASN1ObjectIdentifier("2.16.840.1.113730.4.1")); + + // Legacy MS_SGC / NS_SGC-only leaves are rejected. + for (KeyPurposeId legacySgc : ImmutableList.of(msSgc, nsSgc)) { + X509Certificate legacyLeaf = + signCert( + rootCa.key(), + rootCa.cert(), + leafKeyPair.getPublic(), + new X500Name("CN=epp.legacy-sgc.example"), + VALID_FROM, + VALID_TO, + builder -> addEku(builder, legacySgc)); + assertChainInvalid(new Certificate[] {legacyLeaf}, rootTrustManager); + } + + // Non-TLS, empty-EKU, and MS_SGC-only intermediates are rejected in both ordered and unordered + // chains even when the leaf itself has serverAuth EKU. + ImmutableList disallowedInterCustomizers = + ImmutableList.of( + b -> addEku(b, KeyPurposeId.id_kp_emailProtection), + b -> addEku(b, KeyPurposeId.id_kp_codeSigning), + b -> addEku(b, KeyPurposeId.id_kp_clientAuth), + b -> addEku(b, KeyPurposeId.id_kp_timeStamping), + b -> addEku(b, KeyPurposeId.id_kp_OCSPSigning), + b -> b.addExtension(Extension.extendedKeyUsage, false, new DERSequence()), + b -> addEku(b, msSgc)); + + for (CertCustomizer ekuCustomizer : disallowedInterCustomizers) { + X509Certificate disallowedInter = + signIntermediate( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + "disallowed-eku-inter.tld", + ekuCustomizer); + X509Certificate leaf = + signCert( + intermediateKeyPair.getPrivate(), + disallowedInter, + leafKeyPair.getPublic(), + new X500Name("CN=epp.victim.example"), + VALID_FROM, + VALID_TO, + b -> addEku(b, KeyPurposeId.id_kp_serverAuth)); + assertChainInvalid(new Certificate[] {leaf, disallowedInter}, rootTrustManager); + assertChainInvalid( + new Certificate[] {leaf, rootCa.cert(), disallowedInter}, rootTrustManager); + } + + // Allowed intermediate EKUs: serverAuth, dual-EKU, anyExtendedKeyUsage, and absent EKU. + ImmutableList allowedInterCustomizers = + ImmutableList.of( + b -> addEku(b, KeyPurposeId.id_kp_serverAuth), + b -> addEku(b, KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth), + b -> addEku(b, KeyPurposeId.anyExtendedKeyUsage), + b -> {}); + + for (CertCustomizer ekuCustomizer : allowedInterCustomizers) { + X509Certificate allowedInter = + signIntermediate( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + "allowed-eku-inter.tld", + ekuCustomizer); + X509Certificate leaf = + signCert( + intermediateKeyPair.getPrivate(), + allowedInter, + leafKeyPair.getPublic(), + new X500Name("CN=epp.allowed.example"), + VALID_FROM, + VALID_TO, + b -> addEku(b, KeyPurposeId.id_kp_serverAuth)); + assertChainValid(new Certificate[] {leaf, allowedInter}, rootTrustManager); + } + + // Cross-signed fallback: [leaf, emailProtectionInter, serverAuthInter] succeeds via the valid + // serverAuth intermediate when both share the same Subject DN and key pair. + X509Certificate emailProtectionInter = + signIntermediate( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + "cross-signed-inter.tld", + b -> addEku(b, KeyPurposeId.id_kp_emailProtection)); + X509Certificate serverAuthInter = + signIntermediate( + rootCa.key(), + rootCa.cert(), + intermediateKeyPair.getPublic(), + "cross-signed-inter.tld", + b -> addEku(b, KeyPurposeId.id_kp_serverAuth)); + X509Certificate crossSignedLeaf = + signCert( + intermediateKeyPair.getPrivate(), + emailProtectionInter, + leafKeyPair.getPublic(), + new X500Name("CN=epp.cross-signed.example"), + VALID_FROM, + VALID_TO, + b -> addEku(b, KeyPurposeId.id_kp_serverAuth)); + assertChainInvalid(new Certificate[] {crossSignedLeaf, emailProtectionInter}, rootTrustManager); + assertChainValid( + new Certificate[] {crossSignedLeaf, emailProtectionInter, serverAuthInter}, + rootTrustManager); + } + + @Test + void testValidateCertificateChain_sha1LeafAndIntermediateRejectedUnderSha1Root() + throws Exception { + KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA", PROVIDER); + rsaGen.initialize(2048, new SecureRandom()); + KeyPair sha1RootKeyPair = rsaGen.generateKeyPair(); + X500Name sha1RootDn = new X500Name("CN=sha1-root.tld"); + X509Certificate sha1RootCert = + signCertWithAlgorithm( + sha1RootKeyPair.getPrivate(), + sha1RootDn, + sha1RootKeyPair.getPublic(), + sha1RootDn, + VALID_FROM, + VALID_TO, + "SHA1WithRSAEncryption", + b -> b.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))); + X509TrustManager sha1RootTm = createTrustManager(sha1RootCert); + + // SHA-256 leaf under a self-signed SHA-1 root succeeds; SHA-1 leaf and intermediate fail. + X509Certificate sha256Leaf = + signCertWithAlgorithm( + sha1RootKeyPair.getPrivate(), + sha1RootDn, + leafKeyPair.getPublic(), + new X500Name("CN=epp.sha256-leaf.example"), + VALID_FROM, + VALID_TO, + "SHA256WithRSAEncryption", + null); + assertChainValid(new Certificate[] {sha256Leaf}, sha1RootTm); + + X509Certificate sha1Leaf = + signCertWithAlgorithm( + sha1RootKeyPair.getPrivate(), + sha1RootDn, + leafKeyPair.getPublic(), + new X500Name("CN=epp.sha1-leaf.example"), + VALID_FROM, + VALID_TO, + "SHA1WithRSAEncryption", + null); + assertChainInvalid(new Certificate[] {sha1Leaf}, sha1RootTm); + + X509Certificate sha1Inter = + signCertWithAlgorithm( + sha1RootKeyPair.getPrivate(), + sha1RootDn, + intermediateKeyPair.getPublic(), + new X500Name("CN=sha1-inter.tld"), + VALID_FROM, + VALID_TO, + "SHA1WithRSAEncryption", + b -> b.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))); + X509Certificate sha256LeafUnderSha1Inter = + signCertWithAlgorithm( + intermediateKeyPair.getPrivate(), + new X500Name("CN=sha1-inter.tld"), + leafKeyPair.getPublic(), + new X500Name("CN=epp.sha1-inter-leaf.example"), + VALID_FROM, + VALID_TO, + "SHA256WithRSAEncryption", + null); + assertChainInvalid(new Certificate[] {sha256LeafUnderSha1Inter, sha1Inter}, sha1RootTm); + } + + @Test + void testValidateCertificateChain_chainBytesCapMaterializationAndMaxPathLength() + throws Exception { + // Chain exceeding MAX_CERTIFICATE_CHAIN_BYTES is rejected before calling trustManager. + X509Certificate directLeaf = signLeaf(rootCa, "epp.size-test.example"); + X509Certificate oversizedInter = mock(X509Certificate.class); + when(oversizedInter.getEncoded()).thenReturn(new byte[MAX_CERTIFICATE_CHAIN_BYTES]); + X509TrustManager mockTm = mock(X509TrustManager.class); + CertificateChainValidationResult oversizedResult = + assertChainInvalid(new Certificate[] {directLeaf, oversizedInter}, mockTm); + assertThat(oversizedResult.failureReason().get()) + .contains( + String.format( + "Certificate chain size exceeds maximum of %d bytes", MAX_CERTIFICATE_CHAIN_BYTES)); + verify(mockTm, never()).checkServerTrusted(any(), any()); + + // Wrapped/delegating X509Certificate (simulating Netty's LazyX509Certificate) is materialized + // once before checkServerTrusted() and succeeds for valid DER. + X509Certificate wrappedLeaf = mock(X509Certificate.class); + when(wrappedLeaf.getEncoded()).thenReturn(directLeaf.getEncoded()); + assertChainValid(new Certificate[] {wrappedLeaf}, rootTrustManager); + + X509TrustManager capturingTm = mock(X509TrustManager.class); + ArgumentCaptor chainCaptor = + ArgumentCaptor.forClass(X509Certificate[].class); + assertChainValid(new Certificate[] {wrappedLeaf}, capturingTm); + verify(capturingTm).checkServerTrusted(chainCaptor.capture(), eq("UNKNOWN")); + assertThat(chainCaptor.getValue()[0]).isNotSameInstanceAs(wrappedLeaf); + assertThat(chainCaptor.getValue()[0].getEncoded()).isEqualTo(directLeaf.getEncoded()); + + // Malformed DER on a wrapped cert fails closed before calling trustManager. + X509Certificate malformedWrappedLeaf = mock(X509Certificate.class); + when(malformedWrappedLeaf.getEncoded()).thenReturn(new byte[] {0x30, 0x01, 0x02}); + assertChainInvalid(new Certificate[] {malformedWrappedLeaf}, mockTm); + verify(mockTm, never()).checkServerTrusted(any(), any()); + + // 5-certificate chain (Root -> I1 -> I2 -> I3 -> Leaf) succeeds under maxPathLength = 3; + // unordered 6-certificate chain (4 intermediates) enters SunCertPathBuilder and is rejected. + KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA", PROVIDER); + rsaGen.initialize(2048, new SecureRandom()); + KeyPair i1Key = rsaGen.generateKeyPair(); + KeyPair i2Key = rsaGen.generateKeyPair(); + KeyPair i3Key = rsaGen.generateKeyPair(); + KeyPair i4Key = rsaGen.generateKeyPair(); + X509Certificate i1 = + signIntermediate(rootCa.key(), rootCa.cert(), i1Key.getPublic(), "inter-1.tld", null); + X509Certificate i2 = + signIntermediate(i1Key.getPrivate(), i1, i2Key.getPublic(), "inter-2.tld", null); + X509Certificate i3 = + signIntermediate(i2Key.getPrivate(), i2, i3Key.getPublic(), "inter-3.tld", null); + X509Certificate leaf5 = + signCert( + i3Key.getPrivate(), + i3, + leafKeyPair.getPublic(), + new X500Name("CN=epp.five-tier.example"), + VALID_FROM, + VALID_TO, + null); + assertChainValid(new Certificate[] {leaf5, i3, i2, i1}, rootTrustManager); + assertChainValid(new Certificate[] {leaf5, i1, i3, i2}, rootTrustManager); + + X509Certificate i4 = + signIntermediate(i3Key.getPrivate(), i3, i4Key.getPublic(), "inter-4.tld", null); + X509Certificate leaf6 = + signCert( + i4Key.getPrivate(), + i4, + leafKeyPair.getPublic(), + new X500Name("CN=epp.six-tier.example"), + VALID_FROM, + VALID_TO, + null); + assertChainInvalid(new Certificate[] {leaf6, i1, i4, i2, i3}, rootTrustManager); + } + + @Test + void testFormatHostnamesHeader_nullEmptyAndBasicFormatting() { + assertThat(formatHostnamesHeader(null, "cert-hash")).isEmpty(); + assertThat(formatHostnamesHeader(ImmutableList.of(), "cert-hash")).isEmpty(); + assertThat(formatHostnamesHeader(ImmutableList.of(""), "cert-hash")).isEmpty(); + assertThat( + formatHostnamesHeader( + ImmutableList.of( + "bad,comma.example", + "bad\r\nheader.example", + "bad\u00e9.example", + "epp.example.tld"), + "cert-hash")) + .hasValue("epp.example.tld"); + assertThat(formatHostnamesHeader(ImmutableList.of("epp.example.tld"), "cert-hash")) + .hasValue("epp.example.tld"); + assertThat( + formatHostnamesHeader( + ImmutableList.of("epp1.example.tld", "epp2.example.tld"), "cert-hash")) + .hasValue("epp1.example.tld,epp2.example.tld"); + } + + @Test + void testFormatHostnamesHeader_exactBoundariesAndTruncation() { + // Exact MAX_HOSTNAMES_HEADER_BYTES (4096) fits without truncation. + // 127 * 31 + 32 + 127 commas = 4096 bytes. + ImmutableList exactMaxHostnames = + IntStream.range(0, 128) + .mapToObj( + i -> + i == 127 + ? String.format("epp-host-%03d.reg-last.example.tl", i) + : String.format("epp-host-%03d.reg-pad.example.tl", i)) + .collect(toImmutableList()); + String exactFormatted = formatHostnamesHeader(exactMaxHostnames, "cert-hash").orElseThrow(); + assertThat(exactFormatted).hasLength(MAX_HOSTNAMES_HEADER_BYTES); + + // Comma right at index 4096 truncates cleanly to the exact 4096-byte prefix. + ImmutableList commaAtLimit = + ImmutableList.builder().addAll(exactMaxHostnames).add("x.tld").build(); + assertThat(formatHostnamesHeader(commaAtLimit, "cert-hash")).hasValue(exactFormatted); + + // Mid-hostname overflow drops the overflowing hostname and stops in prefix order. + ImmutableList prefixWithMidOverflow = + ImmutableList.builder() + .addAll(exactMaxHostnames.subList(0, 127)) + .add("epp-host-127.reg-last.example.tld") // 33 bytes -> total 4097 + .add("a.tl") + .build(); + assertThat(formatHostnamesHeader(prefixWithMidOverflow, "cert-hash")) + .hasValue(String.join(",", exactMaxHostnames.subList(0, 127))); + + // Entry exceeding MAX_HOSTNAMES_HEADER_BYTES (or empty first entry before overflow) returns + // empty rather than an empty string; empty middle entry produces no trailing comma. + assertThat( + formatHostnamesHeader( + ImmutableList.of("a".repeat(MAX_HOSTNAMES_HEADER_BYTES + 1), "b.tld"), "cert-hash")) + .isEmpty(); + assertThat( + formatHostnamesHeader( + ImmutableList.of("", "a".repeat(MAX_HOSTNAMES_HEADER_BYTES + 1)), "cert-hash")) + .isEmpty(); + assertThat( + formatHostnamesHeader( + ImmutableList.of("a.example.tld", "", "b".repeat(MAX_HOSTNAMES_HEADER_BYTES)), + "cert-hash")) + .hasValue("a.example.tld"); + + // Realistic oversized multi-SAN UCC cert (300 hostnames) is capped cleanly at <= 4096 bytes. + ImmutableList oversizedHostnames = + IntStream.range(0, 300) + .mapToObj(i -> String.format("epp-host-%03d.registrar.example.tld", i)) + .collect(toImmutableList()); + String formatted = formatHostnamesHeader(oversizedHostnames, "cert-hash").orElseThrow(); + assertThat(formatted.length()).isAtMost(MAX_HOSTNAMES_HEADER_BYTES); + List included = Splitter.on(',').splitToList(formatted); + assertThat(included).hasSize(117); + assertThat(included).isEqualTo(oversizedHostnames.subList(0, included.size())); + assertThat(formatted.length() + 1 + oversizedHostnames.get(included.size()).length()) + .isGreaterThan(MAX_HOSTNAMES_HEADER_BYTES); + } + + @Test + void testFormatHostnamesHeader_truncationAndOmissionLogCertHash() { + Logger logger = Logger.getLogger(X509Utils.class.getName()); + TestLogHandler logHandler = new TestLogHandler(); + logger.addHandler(logHandler); + try { + ImmutableList oversized = + IntStream.range(0, 150) + .mapToObj(i -> String.format("epp-host-%03d.registrar.example.tld", i)) + .collect(toImmutableList()); + + String formatted = formatHostnamesHeader(oversized, "abc123hash").orElseThrow(); + assertThat(formatHostnamesHeader(oversized, null)).hasValue(formatted); + assertThat( + formatHostnamesHeader( + ImmutableList.of("a".repeat(MAX_HOSTNAMES_HEADER_BYTES + 1)), "abc123hash")) + .isEmpty(); + + ImmutableList warnings = + logHandler.getStoredLogRecords().stream() + .filter(record -> record.getLevel().equals(Level.WARNING)) + .collect(toImmutableList()); + assertThat(warnings).hasSize(3); + assertThat(warnings.get(0).getMessage()) + .isEqualTo( + String.format( + "Client certificate (hash=abc123hash) truncated X-SSL-Certificate-Hostnames" + + " header: kept 117 of 150 hostnames (%d bytes, limit 4096 bytes).", + formatted.length())); + assertThat(warnings.get(1).getMessage()) + .isEqualTo( + String.format( + "Client certificate (hash=unknown) truncated X-SSL-Certificate-Hostnames" + + " header: kept 117 of 150 hostnames (%d bytes, limit 4096 bytes).", + formatted.length())); + assertThat(warnings.get(2).getMessage()) + .isEqualTo( + "Client certificate (hash=abc123hash) omitted X-SSL-Certificate-Hostnames header: 0" + + " of 1 hostname(s) fit within 4096 bytes."); + } finally { + logger.removeHandler(logHandler); + } + } +}