From 9ec97888822ab55b9074f4b0a7b293fe82aeecaf Mon Sep 17 00:00:00 2001 From: Scott Fauerbach Date: Tue, 30 Jan 2024 08:43:37 -0500 Subject: [PATCH] Provide implementation delegate for use by trust all trust manager, avoiding empty implementation (#1066) --- .../java/io/nats/client/support/SSLUtils.java | 38 +++++++++++++++---- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/src/main/java/io/nats/client/support/SSLUtils.java b/src/main/java/io/nats/client/support/SSLUtils.java index 1a496d692..4812407df 100644 --- a/src/main/java/io/nats/client/support/SSLUtils.java +++ b/src/main/java/io/nats/client/support/SSLUtils.java @@ -31,15 +31,37 @@ public class SSLUtils { public static final String DEFAULT_TLS_ALGORITHM = "SunX509"; public static final String DEFAULT_KEYSTORE_TYPE = "JKS"; - private static final TrustManager[] TRUST_ALL_CERTS = new TrustManager[] { new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } + private static TrustManagerDelegate TRUST_MANAGER_DELEGATE; + + public static void setDefaultTrustManagerDelegate(TrustManagerDelegate trustManagerDelegate) { + SSLUtils.TRUST_MANAGER_DELEGATE = trustManagerDelegate; + } - public void checkClientTrusted(X509Certificate[] certs, String authType) {} + public interface TrustManagerDelegate { + java.security.cert.X509Certificate[] getAcceptedIssuers(); + void checkClientTrusted(X509Certificate[] certs, String authType); + void checkServerTrusted(X509Certificate[] certs, String authType); + } - public void checkServerTrusted(X509Certificate[] certs, String authType) {} - } }; + private static final TrustManager[] DEFAULT_TRUST_MANAGERS = new TrustManager[] { + new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return TRUST_MANAGER_DELEGATE == null ? null : TRUST_MANAGER_DELEGATE.getAcceptedIssuers(); + } + + public void checkClientTrusted(X509Certificate[] certs, String authType) { + if (TRUST_MANAGER_DELEGATE != null) { + TRUST_MANAGER_DELEGATE.checkClientTrusted(certs, authType); + } + } + + public void checkServerTrusted(X509Certificate[] certs, String authType) { + if (TRUST_MANAGER_DELEGATE != null) { + TRUST_MANAGER_DELEGATE.checkServerTrusted(certs, authType); + } + } + } + }; public static SSLContext createOpenTLSContext() { try { @@ -52,7 +74,7 @@ public static SSLContext createOpenTLSContext() { public static SSLContext createTrustAllTlsContext() throws GeneralSecurityException { SSLContext context = SSLContext.getInstance(Options.DEFAULT_SSL_PROTOCOL); - context.init(null, TRUST_ALL_CERTS, SRAND); + context.init(null, DEFAULT_TRUST_MANAGERS, SRAND); return context; }