From 30c068af953204b8cc2d43067641e285a23c96b2 Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:45:27 +0530 Subject: [PATCH 1/3] distrusting eMudhra mentioned certificates --- advanced-examples/custom-http-client.md | 8 +- pom.xml | 6 + .../twilio/http/DistrustedIntermediates.java | 360 ++++++++++++++++++ .../com/twilio/http/NetworkHttpClient.java | 11 +- .../com/twilio/http/ValidationClient.java | 16 +- .../http/DistrustedIntermediatesTest.java | 249 ++++++++++++ 6 files changed, 647 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/twilio/http/DistrustedIntermediates.java create mode 100644 src/test/java/com/twilio/http/DistrustedIntermediatesTest.java diff --git a/advanced-examples/custom-http-client.md b/advanced-examples/custom-http-client.md index c255bd2969..75dafe5079 100644 --- a/advanced-examples/custom-http-client.md +++ b/advanced-examples/custom-http-client.md @@ -78,6 +78,7 @@ However, within the helper library, there is an implementation of `com.twilio.ht Now that we understand how all the components fit together, we can create our own `TwilioRestClient` that can connect through a proxy server. To make this reusable, here’s a class that you can use to create this `TwilioRestClient` whenever you need one: ```java +import com.twilio.http.DistrustedIntermediates; import com.twilio.http.HttpClient; import com.twilio.http.NetworkHttpClient; import com.twilio.http.TwilioRestClient; @@ -123,7 +124,8 @@ public class ProxiedTwilioClientCreator { .setConnectTimeout(Timeout.ofMilliseconds(10000)) .build(); - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + // Refuse certificate chains that contain a distrusted intermediate, as the default client does. + PoolingHttpClientConnectionManager connectionManager = DistrustedIntermediates.createConnectionManager(); connectionManager.setDefaultMaxPerRoute(10); connectionManager.setMaxTotal(10 * 2); @@ -157,6 +159,10 @@ public class ProxiedTwilioClientCreator { } ``` +### Keep the distrusted-intermediate check + +The default `NetworkHttpClient` refuses TLS connections whose certificate chain contains one of eight intermediate certificates with compromised keys (CVE-2026-111943, the same list Go distrusts as of Go 1.27.3 and 1.26.10). A client built from your own `HttpClientBuilder` only gets this check if it uses `DistrustedIntermediates.createConnectionManager()` as its connection manager, as the example above does. If you use a different HTTP stack, `DistrustedIntermediates.createSslContext()` and `DistrustedIntermediates.createTrustManager()` give you the same check. + In this example, we use some environment variables loaded at the program startup to retrieve various configuration settings: - Your Twilio Account Sid and Auth Token (found here, in the Twilio console) diff --git a/pom.xml b/pom.xml index 85e0095bfa..966270ac6f 100644 --- a/pom.xml +++ b/pom.xml @@ -348,6 +348,12 @@ 3.16.3 test + + com.squareup.okhttp3 + okhttp-tls + 5.2.2 + test + org.mockito mockito-core diff --git a/src/main/java/com/twilio/http/DistrustedIntermediates.java b/src/main/java/com/twilio/http/DistrustedIntermediates.java new file mode 100644 index 0000000000..a3669d7308 --- /dev/null +++ b/src/main/java/com/twilio/http/DistrustedIntermediates.java @@ -0,0 +1,360 @@ +package com.twilio.http; + +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedTrustManager; +import javax.net.ssl.X509TrustManager; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy; +import org.apache.hc.client5.http.ssl.HostnameVerificationPolicy; +import org.apache.hc.client5.http.ssl.HttpsSupport; +import org.apache.hc.core5.ssl.SSLInitializationException; + +/** + * Refuses TLS connections whose certificate chain contains one of eight intermediate certificates that are no + * longer trustworthy. + * + *

The private keys of these intermediates are weak, so anyone can use them to issue a certificate that a + * default trust store accepts. This is the same list Go distrusts as of Go 1.27.3 and 1.26.10 + * (CVE-2026-111943, golang/go#82345). Each certificate is identified by the SHA-256 hash of its DER-encoded + * SubjectPublicKeyInfo. + * + *

The SDK's default clients, {@link NetworkHttpClient} and {@link ValidationClient}, apply this check. A + * {@link NetworkHttpClient} built from your own {@code HttpClientBuilder} doesn't; to opt in, use + * {@link #createConnectionManager()} as its connection manager: + * + *

{@code
+ * PoolingHttpClientConnectionManager connectionManager = DistrustedIntermediates.createConnectionManager();
+ * HttpClient httpClient = new NetworkHttpClient(HttpClientBuilder.create().setConnectionManager(connectionManager));
+ * }
+ * + *

Other HTTP stacks can use {@link #createSslContext()} or {@link #createTrustManager()}. + * + *

Java's trust manager API exposes the chain the server sent rather than the path the JDK built from it, so + * the check applies to the sent chain. That is slightly stricter than Go, which accepts a connection if any + * verified chain avoids these certificates. + */ +public final class DistrustedIntermediates { + + // Copied from Go commit 7f86f957633ee31a1c17a1eb8452ca7a3d9bc141 (src/crypto/x509/verify.go). + static final Set DISTRUSTED_SPKI_SHA256 = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "ebed6475c2c2d80fcb199f3fe8dd6e6b3ce60b77eb15d4e42c3dec0c6f5b5105", + "49dd353dc2b919a3770645117d0e60c16115e7d1bc259eefe734b00ea434fe5f", + "e0254c7fcdc265e2f0f8a428dabb75ab4ae039b4872d62f5ee57f0877d5a8a41", + "5c0660a2b164910d8ff589c18e14552e9e0ec237dcefe2cb736d41a4811f81a0", + "43bffa19d6ef651451f6841e019931e96f6f2eaeff28ab4b6f1ce4576de2717b", + "63ecefee431d49523bc1136c4e72d0206a477086caf606cd5cf025686c109cf8", + "ec4ffa1ad0ac88081314b7aaffef6a91f97cd57291bb5ba686c5415f5eb4f6b6", + "92c063d67e8f14db71d288e11266ffdaf69cbf115f7bab14f3bc2f68d25e0e30" + ))); + + private static final byte[] HEX_DIGITS = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII); + + // TlsSocketStrategy arrived in httpclient5 5.4. Applications can pin an older httpclient5, so only touch it + // when it's on the classpath. + private static final boolean HAS_TLS_SOCKET_STRATEGY = isPresent("org.apache.hc.client5.http.ssl.TlsSocketStrategy"); + + private DistrustedIntermediates() { + } + + /** + * Create an Apache HttpClient connection manager with the same TLS settings as + * {@code new PoolingHttpClientConnectionManager()}, plus the distrust check. + * + * @return a connection manager that refuses distrusted intermediates + */ + public static PoolingHttpClientConnectionManager createConnectionManager() { + return createConnectionManager(createTrustManager()); + } + + /** + * Create an SSL context that trusts the JVM's default trust store, minus the distrusted intermediates. + * + * @return an initialized SSL context + */ + public static SSLContext createSslContext() { + return createSslContext(createTrustManager()); + } + + /** + * Create a trust manager that delegates to the JVM's default trust manager, then refuses chains that contain a + * distrusted intermediate. + * + * @return an X509 trust manager + */ + public static X509TrustManager createTrustManager() { + return wrap(defaultTrustManager(), DISTRUSTED_SPKI_SHA256); + } + + static PoolingHttpClientConnectionManager createConnectionManager(final X509TrustManager trustManager) { + final SSLContext sslContext = createSslContext(trustManager); + if (HAS_TLS_SOCKET_STRATEGY) { + return TlsStrategyConnectionManager.create(sslContext); + } + return SocketFactoryConnectionManager.create(sslContext); + } + + private static boolean isPresent(final String className) { + try { + Class.forName(className, false, DistrustedIntermediates.class.getClassLoader()); + return true; + } catch (final ClassNotFoundException | LinkageError e) { + return false; + } + } + + // Kept in its own class so the httpclient5 5.4+ types it uses are only loaded when they exist. + static final class TlsStrategyConnectionManager { + private TlsStrategyConnectionManager() { + } + + static PoolingHttpClientConnectionManager create(final SSLContext sslContext) { + // Matches DefaultClientTlsStrategy.createDefault(), which new PoolingHttpClientConnectionManager() uses + // on 5.4+. + return PoolingHttpClientConnectionManagerBuilder.create() + .setTlsSocketStrategy(new DefaultClientTlsStrategy( + sslContext, + HostnameVerificationPolicy.BOTH, + HttpsSupport.getDefaultHostnameVerifier() + )) + .build(); + } + } + + static final class SocketFactoryConnectionManager { + private SocketFactoryConnectionManager() { + } + + // Matches SSLConnectionSocketFactory.getSocketFactory(), which new PoolingHttpClientConnectionManager() uses + // before 5.4. The API is deprecated from 5.4 on, where this class isn't used. + @SuppressWarnings("deprecation") + static PoolingHttpClientConnectionManager create(final SSLContext sslContext) { + return PoolingHttpClientConnectionManagerBuilder.create() + .setSSLSocketFactory(new org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory( + sslContext, HttpsSupport.getDefaultHostnameVerifier())) + .build(); + } + } + + static SSLContext createSslContext(final X509TrustManager trustManager) { + try { + // Matches SSLContexts.createDefault() apart from the trust manager. + final SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, new TrustManager[] {trustManager}, null); + return sslContext; + } catch (final GeneralSecurityException e) { + throw new SSLInitializationException(e.getMessage(), e); + } + } + + static X509TrustManager defaultTrustManager() { + try { + final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init((KeyStore) null); + for (final TrustManager trustManager : factory.getTrustManagers()) { + if (trustManager instanceof X509TrustManager) { + return (X509TrustManager) trustManager; + } + } + } catch (final GeneralSecurityException e) { + throw new SSLInitializationException(e.getMessage(), e); + } + throw new SSLInitializationException("No X509TrustManager in the default TrustManagerFactory", null); + } + + static X509TrustManager wrap(final X509TrustManager delegate, final Set distrusted) { + if (delegate instanceof X509ExtendedTrustManager) { + return new ExtendedTrustManager((X509ExtendedTrustManager) delegate, distrusted); + } + // Stay a plain X509TrustManager so JSSE adds the same endpoint and algorithm checks it would have added + // around the delegate. + return new PlainTrustManager(delegate, distrusted); + } + + static void checkChain(final X509Certificate[] chain, final Set distrusted) throws CertificateException { + if (containsDistrusted(chain, distrusted)) { + throw new CertificateException("Certificate chain contains a distrusted intermediate certificate"); + } + } + + static boolean containsDistrusted(final X509Certificate[] chain, final Set distrusted) { + for (final X509Certificate certificate : chain) { + if (distrusted.contains(spkiSha256Hex(certificate))) { + return true; + } + } + return false; + } + + static String spkiSha256Hex(final X509Certificate certificate) { + final byte[] digest; + try { + digest = MessageDigest.getInstance("SHA-256").digest(subjectPublicKeyInfo(certificate)); + } catch (final NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + final byte[] hex = new byte[digest.length * 2]; + for (int i = 0; i < digest.length; i++) { + hex[i * 2] = HEX_DIGITS[(digest[i] >> 4) & 0xf]; + hex[i * 2 + 1] = HEX_DIGITS[digest[i] & 0xf]; + } + return new String(hex, StandardCharsets.US_ASCII); + } + + // Go hashes the SubjectPublicKeyInfo bytes exactly as they appear in the certificate. PublicKey.getEncoded() + // re-encodes the key, which isn't guaranteed to reproduce those bytes, so read them from the TBSCertificate. + static byte[] subjectPublicKeyInfo(final X509Certificate certificate) { + try { + return subjectPublicKeyInfo(certificate.getTBSCertificate()); + } catch (final CertificateEncodingException | IllegalArgumentException e) { + // The JDK has already parsed this certificate, so this shouldn't happen. The re-encoded key matches the + // raw bytes for any DER-conformant certificate. + return certificate.getPublicKey().getEncoded(); + } + } + + // TBSCertificate ::= SEQUENCE { version [0] EXPLICIT OPTIONAL, serialNumber, signature, issuer, validity, + // subject, subjectPublicKeyInfo, ... } + static byte[] subjectPublicKeyInfo(final byte[] tbs) { + final int[] sequence = readHeader(tbs, 0, 0x30); + int offset = sequence[0]; + if (offset < tbs.length && (tbs[offset] & 0xff) == 0xa0) { + offset = skip(tbs, offset); + } + for (int i = 0; i < 5; i++) { + offset = skip(tbs, offset); + } + final int[] spki = readHeader(tbs, offset, 0x30); + return Arrays.copyOfRange(tbs, offset, spki[0] + spki[1]); + } + + private static int skip(final byte[] der, final int offset) { + final int[] header = readHeader(der, offset, -1); + return header[0] + header[1]; + } + + // Returns {contentOffset, contentLength} for the DER element at offset. expectedTag is -1 to accept any tag. + private static int[] readHeader(final byte[] der, final int offset, final int expectedTag) { + if (offset + 2 > der.length) { + throw new IllegalArgumentException("Truncated DER element"); + } + final int tag = der[offset] & 0xff; + if ((tag & 0x1f) == 0x1f || (expectedTag != -1 && tag != expectedTag)) { + throw new IllegalArgumentException("Unexpected DER tag " + tag); + } + int length = der[offset + 1] & 0xff; + int contentOffset = offset + 2; + if (length >= 0x80) { + final int lengthBytes = length & 0x7f; + if (lengthBytes == 0 || lengthBytes > 3 || contentOffset + lengthBytes > der.length) { + throw new IllegalArgumentException("Unsupported DER length"); + } + length = 0; + for (int i = 0; i < lengthBytes; i++) { + length = (length << 8) | (der[contentOffset++] & 0xff); + } + } + if (contentOffset + length > der.length) { + throw new IllegalArgumentException("Truncated DER element"); + } + return new int[] {contentOffset, length}; + } + + private static final class ExtendedTrustManager extends X509ExtendedTrustManager { + private final X509ExtendedTrustManager delegate; + private final Set distrusted; + + ExtendedTrustManager(final X509ExtendedTrustManager delegate, final Set distrusted) { + this.delegate = delegate; + this.distrusted = distrusted; + } + + @Override + public void checkServerTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + delegate.checkServerTrusted(chain, authType); + checkChain(chain, distrusted); + } + + @Override + public void checkServerTrusted(final X509Certificate[] chain, final String authType, final Socket socket) + throws CertificateException { + delegate.checkServerTrusted(chain, authType, socket); + checkChain(chain, distrusted); + } + + @Override + public void checkServerTrusted(final X509Certificate[] chain, final String authType, final SSLEngine engine) + throws CertificateException { + delegate.checkServerTrusted(chain, authType, engine); + checkChain(chain, distrusted); + } + + @Override + public void checkClientTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + delegate.checkClientTrusted(chain, authType); + } + + @Override + public void checkClientTrusted(final X509Certificate[] chain, final String authType, final Socket socket) + throws CertificateException { + delegate.checkClientTrusted(chain, authType, socket); + } + + @Override + public void checkClientTrusted(final X509Certificate[] chain, final String authType, final SSLEngine engine) + throws CertificateException { + delegate.checkClientTrusted(chain, authType, engine); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return delegate.getAcceptedIssuers(); + } + } + + private static final class PlainTrustManager implements X509TrustManager { + private final X509TrustManager delegate; + private final Set distrusted; + + PlainTrustManager(final X509TrustManager delegate, final Set distrusted) { + this.delegate = delegate; + this.distrusted = distrusted; + } + + @Override + public void checkServerTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + delegate.checkServerTrusted(chain, authType); + checkChain(chain, distrusted); + } + + @Override + public void checkClientTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + delegate.checkClientTrusted(chain, authType); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return delegate.getAcceptedIssuers(); + } + } +} diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index 0d40e4cb8c..904d2af3d0 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -16,6 +16,7 @@ import java.util.Collection; import java.util.List; import java.util.Map.Entry; +import javax.net.ssl.X509TrustManager; import org.apache.hc.client5.http.classic.methods.HttpDelete; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPatch; @@ -70,6 +71,14 @@ public NetworkHttpClient(final RequestConfig requestConfig) { * @param socketConfig a SocketConfig. */ public NetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { + this(requestConfig, socketConfig, DistrustedIntermediates.createTrustManager()); + } + + NetworkHttpClient( + final RequestConfig requestConfig, + final SocketConfig socketConfig, + final X509TrustManager trustManager + ) { Collection headers = Arrays.asList( new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), // The Accept header is intentionally omitted to support both SCIM and JSON content types. @@ -85,7 +94,7 @@ public NetworkHttpClient(final RequestConfig requestConfig, final SocketConfig s clientBuilder.useSystemProperties(); } - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + PoolingHttpClientConnectionManager connectionManager = DistrustedIntermediates.createConnectionManager(trustManager); connectionManager.setDefaultSocketConfig(socketConfig); /* * Example: Lets say client has one server. diff --git a/src/main/java/com/twilio/http/ValidationClient.java b/src/main/java/com/twilio/http/ValidationClient.java index fe196573e0..67689e509b 100644 --- a/src/main/java/com/twilio/http/ValidationClient.java +++ b/src/main/java/com/twilio/http/ValidationClient.java @@ -37,6 +37,7 @@ import org.apache.hc.core5.http.message.BasicNameValuePair; import java.security.Key; +import javax.net.ssl.X509TrustManager; public class ValidationClient extends HttpClient { @@ -148,6 +149,18 @@ public ValidationClient(final String accountSid, final RequestConfig requestConfig, final SocketConfig socketConfig, final SecureDigestAlgorithm algorithm) { + this(accountSid, credentialSid, signingKey, privateKey, requestConfig, socketConfig, algorithm, + DistrustedIntermediates.createTrustManager()); + } + + ValidationClient(final String accountSid, + final String credentialSid, + final String signingKey, + final PrivateKey privateKey, + final RequestConfig requestConfig, + final SocketConfig socketConfig, + final SecureDigestAlgorithm algorithm, + final X509TrustManager trustManager) { Collection headers = Arrays.asList( new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), @@ -155,7 +168,8 @@ public ValidationClient(final String accountSid, new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") ); - final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + final PoolingHttpClientConnectionManager connectionManager = + DistrustedIntermediates.createConnectionManager(trustManager); connectionManager.setDefaultSocketConfig(socketConfig); /* * Example: Lets say client has one server. diff --git a/src/test/java/com/twilio/http/DistrustedIntermediatesTest.java b/src/test/java/com/twilio/http/DistrustedIntermediatesTest.java new file mode 100644 index 0000000000..05d7cf5e94 --- /dev/null +++ b/src/test/java/com/twilio/http/DistrustedIntermediatesTest.java @@ -0,0 +1,249 @@ +package com.twilio.http; + +import com.twilio.exception.ApiException; +import io.jsonwebtoken.Jwts; +import java.net.InetAddress; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.Set; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.X509ExtendedTrustManager; +import javax.net.ssl.X509TrustManager; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.tls.HandshakeCertificates; +import okhttp3.tls.HeldCertificate; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class DistrustedIntermediatesTest { + + // An IP literal rather than "localhost": when a handshake fails, Apache HttpClient moves on to the host's next + // address and reports that attempt's error, which would hide the distrust failure behind "connection refused". + private static final String HOST = "127.0.0.1"; + + private static HeldCertificate root; + private static HeldCertificate intermediate; + private static HeldCertificate leaf; + private static X509TrustManager trustsRoot; + + private MockWebServer server; + + @BeforeClass + public static void createChain() { + root = new HeldCertificate.Builder() + .commonName("Test Root") + .certificateAuthority(1) + .build(); + intermediate = new HeldCertificate.Builder() + .commonName("Test Intermediate") + .certificateAuthority(0) + .signedBy(root) + .build(); + leaf = new HeldCertificate.Builder() + .commonName(HOST) + .addSubjectAlternativeName(HOST) + .signedBy(intermediate) + .build(); + trustsRoot = new HandshakeCertificates.Builder() + .addTrustedCertificate(root.certificate()) + .build() + .trustManager(); + } + + @Before + public void startServer() throws Exception { + final HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder() + .heldCertificate(leaf, intermediate.certificate()) + .build(); + server = new MockWebServer(); + server.useHttps(serverCertificates.sslSocketFactory(), false); + server.start(InetAddress.getByName(HOST), 0); + } + + @After + public void stopServer() throws Exception { + server.shutdown(); + } + + @Test + public void testBlocklistHasEightLowercaseSha256Hashes() { + assertEquals(8, DistrustedIntermediates.DISTRUSTED_SPKI_SHA256.size()); + for (final String hash : DistrustedIntermediates.DISTRUSTED_SPKI_SHA256) { + assertTrue(hash, hash.matches("[0-9a-f]{64}")); + } + } + + @Test + public void testSubjectPublicKeyInfoMatchesEncodedKey() { + final X509Certificate ecdsa = leaf.certificate(); + final X509Certificate rsa = new HeldCertificate.Builder().rsa2048().build().certificate(); + assertArrayEquals(ecdsa.getPublicKey().getEncoded(), DistrustedIntermediates.subjectPublicKeyInfo(ecdsa)); + assertArrayEquals(rsa.getPublicKey().getEncoded(), DistrustedIntermediates.subjectPublicKeyInfo(rsa)); + } + + @Test + public void testContainsDistrusted() { + final X509Certificate[] chain = {leaf.certificate(), intermediate.certificate()}; + assertFalse(DistrustedIntermediates.containsDistrusted(chain, Collections.emptySet())); + assertFalse(DistrustedIntermediates.containsDistrusted(chain, DistrustedIntermediates.DISTRUSTED_SPKI_SHA256)); + assertTrue(DistrustedIntermediates.containsDistrusted(chain, distrust(intermediate))); + assertTrue(DistrustedIntermediates.containsDistrusted(chain, distrust(leaf))); + } + + @Test + public void testDefaultTrustManagerIsExtended() { + assertTrue(DistrustedIntermediates.createTrustManager() instanceof X509ExtendedTrustManager); + } + + @Test + public void testCleanChainIsAccepted() { + server.enqueue(new MockResponse().setBody("ok")); + final NetworkHttpClient client = networkClient(trustsRoot, Collections.emptySet()); + assertEquals(200, client.makeRequest(get()).getStatusCode()); + } + + @Test + public void testDistrustedIntermediateIsRejected() { + assertRejected(networkClient(trustsRoot, distrust(intermediate))); + } + + @Test + public void testDistrustedLeafIsRejected() { + assertRejected(networkClient(trustsRoot, distrust(leaf))); + } + + @Test + public void testPlainDelegateCleanChainIsAccepted() { + server.enqueue(new MockResponse().setBody("ok")); + final NetworkHttpClient client = networkClient(plain(trustsRoot), Collections.emptySet()); + assertEquals(200, client.makeRequest(get()).getStatusCode()); + } + + @Test + public void testPlainDelegateDistrustedIntermediateIsRejected() { + assertRejected(networkClient(plain(trustsRoot), distrust(intermediate))); + } + + @Test + public void testPre54ConnectionManagerAcceptsCleanChain() { + server.enqueue(new MockResponse().setBody("ok")); + assertEquals(200, customClient(Collections.emptySet(), true).makeRequest(get()).getStatusCode()); + } + + @Test + public void testPre54ConnectionManagerRejectsDistrustedIntermediate() { + assertRejected(customClient(distrust(intermediate), true)); + } + + @Test + public void testCustomClientConnectionManagerRejectsDistrustedIntermediate() { + assertRejected(customClient(distrust(intermediate), false)); + } + + @Test + public void testValidationClientRejectsDistrustedIntermediate() throws Exception { + final PrivateKey privateKey = KeyPairGenerator.getInstance("RSA").generateKeyPair().getPrivate(); + final ValidationClient client = new ValidationClient( + "dummy-sid1", "dummy-sid2", "dummy-signing-key", privateKey, + HttpClient.DEFAULT_REQUEST_CONFIG, HttpClient.DEFAULT_SOCKET_CONFIG, Jwts.SIG.RS256, + DistrustedIntermediates.wrap(trustsRoot, distrust(intermediate)) + ); + assertRejected(client); + } + + @Test + public void testDefaultClientStillRejectsUnknownRoot() { + try { + new NetworkHttpClient().makeRequest(get()); + fail("expected the JVM trust store to reject the test root"); + } catch (final ApiException e) { + assertTrue("unexpected failure: " + e, e.getCause() instanceof SSLHandshakeException); + assertFalse(causedByDistrust(e)); + } + assertEquals(0, server.getRequestCount()); + } + + private void assertRejected(final HttpClient client) { + try { + client.makeRequest(get()); + fail("expected the handshake to fail"); + } catch (final ApiException e) { + assertTrue("unexpected failure: " + e, causedByDistrust(e)); + } + // The request, including its Authorization header, never reached the server. + assertEquals(0, server.getRequestCount()); + } + + private static boolean causedByDistrust(final Throwable e) { + for (Throwable t = e; t != null; t = t.getCause()) { + if (t.getMessage() != null && t.getMessage().contains("distrusted intermediate")) { + return true; + } + } + return false; + } + + private Request get() { + return new Request(HttpMethod.GET, "https://" + HOST + ":" + server.getPort() + "/"); + } + + private static NetworkHttpClient networkClient(final X509TrustManager delegate, final Set distrusted) { + return new NetworkHttpClient( + HttpClient.DEFAULT_REQUEST_CONFIG, + HttpClient.DEFAULT_SOCKET_CONFIG, + DistrustedIntermediates.wrap(delegate, distrusted) + ); + } + + // Builds the client the way an application would with createConnectionManager(), using the connection manager + // for httpclient5 before 5.4 when legacy is true. + private static NetworkHttpClient customClient(final Set distrusted, final boolean legacy) { + final SSLContext sslContext = DistrustedIntermediates.createSslContext( + DistrustedIntermediates.wrap(trustsRoot, distrusted)); + final PoolingHttpClientConnectionManager connectionManager = legacy + ? DistrustedIntermediates.SocketFactoryConnectionManager.create(sslContext) + : DistrustedIntermediates.TlsStrategyConnectionManager.create(sslContext); + return new NetworkHttpClient(HttpClientBuilder.create().setConnectionManager(connectionManager)); + } + + private static Set distrust(final HeldCertificate certificate) { + return Collections.singleton(DistrustedIntermediates.spkiSha256Hex(certificate.certificate())); + } + + // Hides the X509ExtendedTrustManager methods so wrap() takes its plain-delegate path. + private static X509TrustManager plain(final X509TrustManager delegate) { + return new X509TrustManager() { + @Override + public void checkClientTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + delegate.checkClientTrusted(chain, authType); + } + + @Override + public void checkServerTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + delegate.checkServerTrusted(chain, authType); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return delegate.getAcceptedIssuers(); + } + }; + } +} From 26f0ed628dadf338d08e8e6dd3b9749cfaf75162 Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:13:38 +0530 Subject: [PATCH 2/3] add regression test showing a trusted chain issued for another host is still rejected --- README.md | 2 + advanced-examples/custom-http-client.md | 2 +- .../twilio/http/DistrustedIntermediates.java | 13 +----- .../http/DistrustedIntermediatesTest.java | 46 +++++++++++++++++++ 4 files changed, 50 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index ed6e1bbf1b..be6b4b336c 100644 --- a/README.md +++ b/README.md @@ -354,6 +354,8 @@ That will output XML that looks like this: To use a custom HTTP client with this helper library, please see the [advanced example of how to do so](./advanced-examples/custom-http-client.md). +The default HTTP client refuses TLS connections whose certificate chain contains one of eight intermediate certificates with compromised keys (CVE-2026-111943). A client built from your own `HttpClientBuilder` doesn't get this check unless you set `DistrustedIntermediates.createConnectionManager()` as its connection manager, as the [advanced example](./advanced-examples/custom-http-client.md#keep-the-distrusted-intermediate-check) shows. + ## Docker image The `Dockerfile` present in this repository and its respective `twilio/twilio-java` Docker image are currently used by Twilio for testing purposes only. diff --git a/advanced-examples/custom-http-client.md b/advanced-examples/custom-http-client.md index 75dafe5079..ba7ba0d653 100644 --- a/advanced-examples/custom-http-client.md +++ b/advanced-examples/custom-http-client.md @@ -161,7 +161,7 @@ public class ProxiedTwilioClientCreator { ### Keep the distrusted-intermediate check -The default `NetworkHttpClient` refuses TLS connections whose certificate chain contains one of eight intermediate certificates with compromised keys (CVE-2026-111943, the same list Go distrusts as of Go 1.27.3 and 1.26.10). A client built from your own `HttpClientBuilder` only gets this check if it uses `DistrustedIntermediates.createConnectionManager()` as its connection manager, as the example above does. If you use a different HTTP stack, `DistrustedIntermediates.createSslContext()` and `DistrustedIntermediates.createTrustManager()` give you the same check. +The default `NetworkHttpClient` refuses TLS connections whose certificate chain contains one of eight intermediate certificates with compromised keys (CVE-2026-111943, the same list Go distrusts as of Go 1.27.3 and 1.26.10). A client built from your own `HttpClientBuilder` only gets this check if it uses `DistrustedIntermediates.createConnectionManager()` as its connection manager, as the example above does. In this example, we use some environment variables loaded at the program startup to retrieve various configuration settings: diff --git a/src/main/java/com/twilio/http/DistrustedIntermediates.java b/src/main/java/com/twilio/http/DistrustedIntermediates.java index a3669d7308..dbd817f625 100644 --- a/src/main/java/com/twilio/http/DistrustedIntermediates.java +++ b/src/main/java/com/twilio/http/DistrustedIntermediates.java @@ -44,8 +44,6 @@ * HttpClient httpClient = new NetworkHttpClient(HttpClientBuilder.create().setConnectionManager(connectionManager)); * } * - *

Other HTTP stacks can use {@link #createSslContext()} or {@link #createTrustManager()}. - * *

Java's trust manager API exposes the chain the server sent rather than the path the JDK built from it, so * the check applies to the sent chain. That is slightly stricter than Go, which accepts a connection if any * verified chain avoids these certificates. @@ -83,22 +81,13 @@ public static PoolingHttpClientConnectionManager createConnectionManager() { return createConnectionManager(createTrustManager()); } - /** - * Create an SSL context that trusts the JVM's default trust store, minus the distrusted intermediates. - * - * @return an initialized SSL context - */ - public static SSLContext createSslContext() { - return createSslContext(createTrustManager()); - } - /** * Create a trust manager that delegates to the JVM's default trust manager, then refuses chains that contain a * distrusted intermediate. * * @return an X509 trust manager */ - public static X509TrustManager createTrustManager() { + static X509TrustManager createTrustManager() { return wrap(defaultTrustManager(), DISTRUSTED_SPKI_SHA256); } diff --git a/src/test/java/com/twilio/http/DistrustedIntermediatesTest.java b/src/test/java/com/twilio/http/DistrustedIntermediatesTest.java index 05d7cf5e94..6cb13838c4 100644 --- a/src/test/java/com/twilio/http/DistrustedIntermediatesTest.java +++ b/src/test/java/com/twilio/http/DistrustedIntermediatesTest.java @@ -10,6 +10,7 @@ import java.util.Collections; import java.util.Set; import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.X509ExtendedTrustManager; import javax.net.ssl.X509TrustManager; @@ -166,6 +167,16 @@ public void testValidationClientRejectsDistrustedIntermediate() throws Exception assertRejected(client); } + @Test + public void testHostnameMismatchIsRejected() throws Exception { + assertHostnameMismatchRejected(networkClient(trustsRoot, Collections.emptySet())); + } + + @Test + public void testPre54ConnectionManagerRejectsHostnameMismatch() throws Exception { + assertHostnameMismatchRejected(customClient(Collections.emptySet(), true)); + } + @Test public void testDefaultClientStillRejectsUnknownRoot() { try { @@ -189,6 +200,41 @@ private void assertRejected(final HttpClient client) { assertEquals(0, server.getRequestCount()); } + // The chain is trusted and nothing in it is distrusted; only the hostname is wrong, so a rejection shows that + // hostname verification survived the connection manager rebuild. + private void assertHostnameMismatchRejected(final HttpClient client) throws Exception { + final HeldCertificate otherHost = new HeldCertificate.Builder() + .commonName("example.com") + .addSubjectAlternativeName("example.com") + .signedBy(intermediate) + .build(); + final MockWebServer mismatched = new MockWebServer(); + mismatched.useHttps(new HandshakeCertificates.Builder() + .heldCertificate(otherHost, intermediate.certificate()) + .build() + .sslSocketFactory(), false); + mismatched.start(InetAddress.getByName(HOST), 0); + try { + client.makeRequest(new Request(HttpMethod.GET, "https://" + HOST + ":" + mismatched.getPort() + "/")); + fail("expected hostname verification to fail"); + } catch (final ApiException e) { + assertTrue("unexpected failure: " + e, causedBy(e, SSLException.class)); + assertFalse(causedByDistrust(e)); + } finally { + mismatched.shutdown(); + } + assertEquals(0, mismatched.getRequestCount()); + } + + private static boolean causedBy(final Throwable e, final Class type) { + for (Throwable t = e; t != null; t = t.getCause()) { + if (type.isInstance(t)) { + return true; + } + } + return false; + } + private static boolean causedByDistrust(final Throwable e) { for (Throwable t = e; t != null; t = t.getCause()) { if (t.getMessage() != null && t.getMessage().contains("distrusted intermediate")) { From af4ea473c12152bbb3b4b2b8929b57eb2edc2512 Mon Sep 17 00:00:00 2001 From: sbansla <104902068+sbansla@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:31:45 +0530 Subject: [PATCH 3/3] changed distrust certificate error message --- src/main/java/com/twilio/http/DistrustedIntermediates.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/twilio/http/DistrustedIntermediates.java b/src/main/java/com/twilio/http/DistrustedIntermediates.java index dbd817f625..8b04f7b241 100644 --- a/src/main/java/com/twilio/http/DistrustedIntermediates.java +++ b/src/main/java/com/twilio/http/DistrustedIntermediates.java @@ -178,7 +178,7 @@ static X509TrustManager wrap(final X509TrustManager delegate, final Set static void checkChain(final X509Certificate[] chain, final Set distrusted) throws CertificateException { if (containsDistrusted(chain, distrusted)) { - throw new CertificateException("Certificate chain contains a distrusted intermediate certificate"); + throw new CertificateException("Certificate chain which you are using contains a distrusted intermediate certificate"); } }