Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2026 OkHttp Authors
*
* 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 datadog.communication.http;

import static java.util.Arrays.asList;

import java.security.cert.Certificate;
import java.util.HashSet;
import java.util.Set;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import okhttp3.internal.tls.OkHostnameVerifier;
import okio.ByteString;

/**
* Rejects the compromised eMudhra keys from CVE-2026-111943 before sending HTTP data.
*
* <p>Adapted from Jesse Wilson's corrected mitigation:
* https://gist.github.com/swankjesse/de8828e357a4d3fc8ebe1ca14ec2bc9f
*/
public final class ForbiddenCertificatesHostnameVerifier implements HostnameVerifier {
public static final ForbiddenCertificatesHostnameVerifier INSTANCE =
new ForbiddenCertificatesHostnameVerifier(
new HashSet<>(
asList(
ByteString.decodeHex(
"43bffa19d6ef651451f6841e019931e96f6f2eaeff28ab4b6f1ce4576de2717b"),
ByteString.decodeHex(
"49dd353dc2b919a3770645117d0e60c16115e7d1bc259eefe734b00ea434fe5f"),
ByteString.decodeHex(
"5c0660a2b164910d8ff589c18e14552e9e0ec237dcefe2cb736d41a4811f81a0"),
ByteString.decodeHex(
"63ecefee431d49523bc1136c4e72d0206a477086caf606cd5cf025686c109cf8"),
ByteString.decodeHex(
"92c063d67e8f14db71d288e11266ffdaf69cbf115f7bab14f3bc2f68d25e0e30"),
ByteString.decodeHex(
"e0254c7fcdc265e2f0f8a428dabb75ab4ae039b4872d62f5ee57f0877d5a8a41"),
ByteString.decodeHex(
"ebed6475c2c2d80fcb199f3fe8dd6e6b3ce60b77eb15d4e42c3dec0c6f5b5105"),
ByteString.decodeHex(
"ec4ffa1ad0ac88081314b7aaffef6a91f97cd57291bb5ba686c5415f5eb4f6b6"))));

private final Set<ByteString> forbiddenSpkiSha256s;

ForbiddenCertificatesHostnameVerifier(Set<ByteString> forbiddenSpkiSha256s) {
this.forbiddenSpkiSha256s = forbiddenSpkiSha256s;
}

@Override
public boolean verify(String hostname, SSLSession session) {
if (!OkHostnameVerifier.INSTANCE.verify(hostname, session)) {
return false;
}

try {
// Match keys throughout the chain, including cross-signed certificates.
for (Certificate certificate : session.getPeerCertificates()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Check the validated certificate path for forbidden keys

With -Dcom.sun.security.enableAIAcaIssuers=true, an attacker can present a hostname-matching leaf signed by a compromised intermediate and serve that omitted intermediate through the leaf's AIA URI. SunJSSE can fetch the issuer to validate the connection, but SSLSession.getPeerCertificates() retains only the server-supplied chain. This loop therefore checks only the fresh leaf key and permits sensitive headers and bodies to reach the attacker. Check the validated certificate path, including fetched issuers, before transmission and cover an omitted-intermediate handshake; this requires broader changes than a local replacement.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Confirmed with a local omitted-intermediate regression on Java 8 and 25. SunJSSE validates leaf -> AIA-fetched intermediate -> trusted root, while SSLSession.getPeerCertificates() contains only the leaf. This verifier hashes the fresh leaf key and accepts it. The test API-key header and body then reach the server.

AIA issuer retrieval must be enabled. On the tested Java 25 runtime, com.sun.security.allowedAIALocations must also permit the issuer URI. AIA retrieval is disabled by default (Oracle documentation).

A prototype added SPKI-based AlgorithmConstraints to each SSLSocket through SSLParameters before the handshake, retaining the default trust manager. SunJSSE then rejected the fetched issuer during PKIX path validation, before HTTP data was sent. The regression passed on both JVMs. This requires an SSLSocketFactory wrapper and explicit TLS setup, so I kept that broader change out of this quick patch and documented the remaining bypass in the PR description.

ByteString spkiSha256 = ByteString.of(certificate.getPublicKey().getEncoded()).sha256();
if (forbiddenSpkiSha256s.contains(spkiSha256)) {
return false;
}
}
return true;
} catch (SSLPeerUnverifiedException e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ private static OkHttpClient buildHttpClient(
}

builder
.hostnameVerifier(ForbiddenCertificatesHostnameVerifier.INSTANCE)
.connectTimeout(timeoutMillis, MILLISECONDS)
.writeTimeout(timeoutMillis, MILLISECONDS)
.readTimeout(timeoutMillis, MILLISECONDS)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package datadog.communication.http;

import static java.util.Collections.singleton;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.InputStream;
import java.lang.reflect.Proxy;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.stream.Stream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okio.ByteString;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

class ForbiddenCertificatesHostnameVerifierTest {
private static HostnameVerifier hostnameVerifier;
private static X509Certificate localhostCertificate;
private static SSLContext sslContext;
private static X509TrustManager trustManager;

@BeforeAll
static void setUpTls() throws Exception {
hostnameVerifier = OkHttpUtils.buildHttpClient(false, null, null, 5000).hostnameVerifier();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
char[] password = "datadog".toCharArray();
try (InputStream input = resource("localhost.p12")) {
keyStore.load(input, password);
}
localhostCertificate = (X509Certificate) keyStore.getCertificate("localhost");

KeyManagerFactory keyManagers =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagers.init(keyStore, password);
TrustManagerFactory trustManagers =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagers.init(keyStore);
trustManager = (X509TrustManager) trustManagers.getTrustManagers()[0];
sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers.getKeyManagers(), trustManagers.getTrustManagers(), null);
}

@ParameterizedTest
@MethodSource("compromisedCertificates")
void rejectsCompromisedIntermediateKeysIncludingCrossSignatures(X509Certificate compromised) {
assertFalse(hostnameVerifier.verify("localhost", session(localhostCertificate, compromised)));
assertFalse(
hostnameVerifier.verify(
"localhost", session(localhostCertificate, localhostCertificate, compromised)));
}

@Test
void preservesHostnameVerification() {
assertTrue(hostnameVerifier.verify("localhost", session(localhostCertificate)));
assertFalse(hostnameVerifier.verify("different.example", session(localhostCertificate)));
}

@Test
void rejectsUnverifiedPeer() {
assertFalse(hostnameVerifier.verify("localhost", session()));
}

static Stream<X509Certificate> compromisedCertificates() throws Exception {
try (InputStream input = resource("emudhra-compromised-certificates.pem")) {
return CertificateFactory.getInstance("X.509").generateCertificates(input).stream()
.map(X509Certificate.class::cast);
}
}

private static InputStream resource(String name) {
return ForbiddenCertificatesHostnameVerifierTest.class.getResourceAsStream("/" + name);
}

private static SSLSession session(Certificate... certificates) {
return (SSLSession)
Proxy.newProxyInstance(
SSLSession.class.getClassLoader(),
new Class<?>[] {SSLSession.class},
(proxy, method, args) -> {
if (!method.getName().equals("getPeerCertificates")) {
throw new UnsupportedOperationException(method.getName());
}
if (certificates.length == 0) {
throw new SSLPeerUnverifiedException("no peer");
}
return certificates;
});
}

@Nested
class HttpConnections {
private MockWebServer server;
private OkHttpClient client;

@BeforeEach
void setUp() {
server = new MockWebServer();
}

@AfterEach
void tearDown() throws Exception {
if (client != null) {
client.connectionPool().evictAll();
client.dispatcher().executorService().shutdownNow();
}
server.shutdown();
}

@Test
void acceptsTrustedHttps() throws Exception {
startHttpsServer();
server.enqueue(new MockResponse().setBody("accepted"));

try (Response response = client.newCall(secretRequest()).execute()) {
assertEquals("accepted", response.body().string());
}

RecordedRequest request = server.takeRequest();
assertEquals("secret-api-key", request.getHeader("DD-API-KEY"));
assertEquals("secret-body", request.getBody().readUtf8());
}

@Test
void rejectsForbiddenKeyBeforeSendingHeadersOrBody() throws Exception {
startHttpsServer();
// Block our test key to exercise real TLS without using compromised private keys.
ByteString forbiddenKey =
ByteString.of(localhostCertificate.getPublicKey().getEncoded()).sha256();
client =
client
.newBuilder()
.hostnameVerifier(new ForbiddenCertificatesHostnameVerifier(singleton(forbiddenKey)))
.build();

assertThrows(
SSLPeerUnverifiedException.class, () -> client.newCall(secretRequest()).execute());
assertEquals(0, server.getRequestCount());
}

@Test
void acceptsCleartextHttp() throws Exception {
server.start();
server.enqueue(new MockResponse().setBody("accepted"));
client = OkHttpUtils.buildHttpClient(server.url("/"), 5000);

try (Response response = client.newCall(secretRequest()).execute()) {
assertEquals("accepted", response.body().string());
}
}

private void startHttpsServer() throws Exception {
server.useHttps(sslContext.getSocketFactory(), false);
server.start();
client =
OkHttpUtils.buildHttpClient(server.url("/"), 5000)
.newBuilder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build();
}

private Request secretRequest() {
return new Request.Builder()
.url(server.url("/intake"))
.header("DD-API-KEY", "secret-api-key")
.post(RequestBody.create(null, "secret-body"))
.build();
}
}
}
Loading
Loading