GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Backport #16079 and #17114 (#17134) · lltopk/netty@db0b460

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • handler-ssl-ocsp/src
    • main/java/io/netty/handler/ssl/ocsp
      • NoOcspResponderException.java
      • OcspClient.java
    • test/java/io/netty/handler/ssl/ocsp
      • OcspClientTest.java
      • OcspServerCertificateValidatorTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎handler-ssl-ocsp/src/main/java/io/netty/handler/ssl/ocsp/NoOcspResponderException.java‎

Copy file name to clipboard
+31Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright 2026 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.handler.ssl.ocsp;
17+
18+
/**
19+
* Thrown internally by {@link OcspClient} if the certificate being checked does not specify any OCSP Responder.
20+
* <p>
21+
* This exception extends {@link NullPointerException} for backwards compatibility reasons.
22+
*/
23+
public final class NoOcspResponderException extends NullPointerException {
24+
/**
25+
* Create a new instance with the given message.
26+
* @param message The error message.
27+
*/
28+
public NoOcspResponderException(String message) {
29+
super(message);
30+
}
31+
}
Collapse file

‎handler-ssl-ocsp/src/main/java/io/netty/handler/ssl/ocsp/OcspClient.java‎

Copy file name to clipboardExpand all lines: handler-ssl-ocsp/src/main/java/io/netty/handler/ssl/ocsp/OcspClient.java
+95-9Lines changed: 95 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
import org.bouncycastle.asn1.x509.Extension;
4646
import org.bouncycastle.asn1.x509.Extensions;
4747
import org.bouncycastle.cert.X509CertificateHolder;
48+
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
4849
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
4950
import org.bouncycastle.cert.ocsp.BasicOCSPResp;
5051
import org.bouncycastle.cert.ocsp.CertificateID;
@@ -59,10 +60,22 @@
5960

6061
import java.net.InetAddress;
6162
import java.net.URL;
63+
import java.security.InvalidAlgorithmParameterException;
64+
import java.security.NoSuchAlgorithmException;
6265
import java.security.SecureRandom;
66+
import java.security.cert.CertPathBuilder;
67+
import java.security.cert.CertPathBuilderException;
68+
import java.security.cert.CertStore;
6369
import java.security.cert.CertificateEncodingException;
6470
import java.security.cert.CertificateException;
71+
import java.security.cert.CollectionCertStoreParameters;
72+
import java.security.cert.PKIXBuilderParameters;
73+
import java.security.cert.TrustAnchor;
74+
import java.security.cert.X509CertSelector;
6575
import java.security.cert.X509Certificate;
76+
import java.util.ArrayList;
77+
import java.util.Collections;
78+
import java.util.List;
6679

6780
import static io.netty.handler.codec.http.HttpMethod.POST;
6881
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
@@ -92,7 +105,7 @@ final class OcspClient {
92105
* @param issuer {@link X509Certificate} issuer of client certificate
93106
* @param validateResponseNonce Set to {@code true} to enable OCSP response validation
94107
* @param ioTransport {@link IoTransport} to use
95-
* @return {@link Promise} of {@link BasicOCSPResp}
108+
* @param responsePromise {@link Promise} of {@link BasicOCSPResp}
96109
*/
97110
static void query(final X509Certificate x509Certificate,
98111
final X509Certificate issuer, final boolean validateResponseNonce,
@@ -298,14 +311,85 @@ private static void validateNonce(BasicOCSPResp basicResponse, DEROctetString en
298311
/**
299312
* Validate OCSP response signature
300313
*/
301-
private static void validateSignature(BasicOCSPResp resp, X509Certificate certificate) throws OCSPException {
314+
static void validateSignature(BasicOCSPResp resp, X509Certificate issuerCertificate) throws OCSPException {
302315
try {
303-
ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(certificate);
304-
if (!resp.isSignatureValid(verifier)) {
305-
throw new OCSPException("OCSP signature is not valid");
316+
X509CertificateHolder[] certs = resp.getCerts();
317+
JcaContentVerifierProviderBuilder providerBuilder = new JcaContentVerifierProviderBuilder();
318+
319+
// If responder certificate is included, validate the chain
320+
if (certs != null && certs.length > 0) {
321+
322+
// Use the first included certificate to verify the OCSP response signature.
323+
X509CertificateHolder responderCert = certs[0];
324+
325+
// Verify OCSP response signature using responder cert
326+
ContentVerifierProvider responderVerifier = providerBuilder.build(responderCert);
327+
328+
if (!resp.isSignatureValid(responderVerifier)) {
329+
throw new OCSPException("OCSP response signature is not valid");
330+
}
331+
332+
// Build chain from responder certificate to issuer using CertPathBuilder
333+
validateCertificateChain(responderCert, certs, issuerCertificate);
334+
} else {
335+
// Validate signature using issuer certificate
336+
ContentVerifierProvider issuerVerifier = providerBuilder.build(issuerCertificate);
337+
338+
if (!resp.isSignatureValid(issuerVerifier)) {
339+
throw new OCSPException("OCSP response signature is not valid");
340+
}
306341
}
307342
} catch (OperatorCreationException e) {
308343
throw new OCSPException("Error validating OCSP-Signature", e);
344+
} catch (CertificateException e) {
345+
throw new OCSPException("Error while processing certificates for OCSP signature validation", e);
346+
}
347+
}
348+
349+
/**
350+
* Validates that a certificate chain can be built from the responder certificate to the issuer.
351+
* Uses Java's CertPathBuilder to construct and validate the chain.
352+
*/
353+
private static void validateCertificateChain(X509CertificateHolder responderCert,
354+
X509CertificateHolder[] allCerts,
355+
X509Certificate issuerCertificate) throws OCSPException {
356+
try {
357+
// Convert BouncyCastle certificate holders to Java X509Certificates
358+
List<X509Certificate> certList = new ArrayList<X509Certificate>(allCerts.length);
359+
for (X509CertificateHolder certHolder : allCerts) {
360+
certList.add(new JcaX509CertificateConverter().getCertificate(certHolder));
361+
}
362+
363+
// Create a CertStore with all the certificates from the OCSP response
364+
CertStore certStore = CertStore.getInstance("Collection",
365+
new CollectionCertStoreParameters(certList));
366+
367+
// Set up the target certificate selector for the responder certificate
368+
X509CertSelector targetConstraints = new X509CertSelector();
369+
targetConstraints.setCertificate(new JcaX509CertificateConverter().getCertificate(responderCert));
370+
371+
// Set up trust anchor with the issuer certificate
372+
TrustAnchor trustAnchor = new TrustAnchor(issuerCertificate, null);
373+
374+
// Build PKIX parameters
375+
PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(
376+
Collections.singleton(trustAnchor), targetConstraints);
377+
pkixParams.addCertStore(certStore);
378+
pkixParams.setRevocationEnabled(false); // Don't check revocation when validating OCSP response
379+
380+
// Build and validate the certificate path
381+
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
382+
builder.build(pkixParams);
383+
384+
// If we reach here, the chain is valid
385+
} catch (CertPathBuilderException e) {
386+
throw new OCSPException("OCSP responder certificate is not trusted by issuer: " + e.getMessage(), e);
387+
} catch (InvalidAlgorithmParameterException e) {
388+
throw new OCSPException("Error setting up certificate path validation", e);
389+
} catch (NoSuchAlgorithmException e) {
390+
throw new OCSPException("Error setting up certificate path validation", e);
391+
} catch (CertificateException e) {
392+
throw new OCSPException("Error converting certificates for path validation", e);
309393
}
310394
}
311395

@@ -329,13 +413,15 @@ private static String parseOcspUrlFromCertificate(X509Certificate cert) {
329413
AuthorityInformationAccess aiaExtension = AuthorityInformationAccess.fromExtensions(holder.getExtensions());
330414

331415
// Lookup for OCSP responder url
332-
for (AccessDescription accessDescription : aiaExtension.getAccessDescriptions()) {
333-
if (accessDescription.getAccessMethod().equals(id_ad_ocsp)) {
334-
return accessDescription.getAccessLocation().getName().toASN1Primitive().toString();
416+
if (aiaExtension != null) {
417+
for (AccessDescription accessDescription : aiaExtension.getAccessDescriptions()) {
418+
if (accessDescription.getAccessMethod().equals(id_ad_ocsp)) {
419+
return accessDescription.getAccessLocation().getName().toASN1Primitive().toString();
420+
}
335421
}
336422
}
337423

338-
throw new NullPointerException("Unable to find OCSP responder URL in Certificate");
424+
throw new NoOcspResponderException("Unable to find OCSP responder URL in Certificate");
339425
}
340426

341427
static final class Initializer extends ChannelInitializer<SocketChannel> {
Collapse file

‎handler-ssl-ocsp/src/test/java/io/netty/handler/ssl/ocsp/OcspClientTest.java‎

Copy file name to clipboardExpand all lines: handler-ssl-ocsp/src/test/java/io/netty/handler/ssl/ocsp/OcspClientTest.java
+151-3Lines changed: 151 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,54 @@
1616
package io.netty.handler.ssl.ocsp;
1717

1818
import io.netty.util.concurrent.Promise;
19+
import org.bouncycastle.asn1.x500.X500Name;
20+
import org.bouncycastle.asn1.x509.BasicConstraints;
21+
import org.bouncycastle.asn1.x509.Extension;
22+
import org.bouncycastle.cert.X509CertificateHolder;
23+
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
24+
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
25+
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
1926
import org.bouncycastle.cert.ocsp.BasicOCSPResp;
27+
import org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder;
28+
import org.bouncycastle.cert.ocsp.CertificateID;
29+
import org.bouncycastle.cert.ocsp.CertificateStatus;
30+
import org.bouncycastle.cert.ocsp.OCSPException;
31+
import org.bouncycastle.cert.ocsp.RespID;
32+
import org.bouncycastle.operator.ContentSigner;
33+
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
34+
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
2035
import org.junit.jupiter.api.Test;
36+
import org.junit.jupiter.api.function.Executable;
37+
import org.junit.jupiter.params.ParameterizedTest;
38+
import org.junit.jupiter.params.provider.ValueSource;
2139

2240
import javax.net.ssl.HttpsURLConnection;
2341
import java.io.IOException;
42+
import java.math.BigInteger;
2443
import java.net.URL;
44+
import java.security.KeyPair;
45+
import java.security.KeyPairGenerator;
46+
import java.security.PrivateKey;
47+
import java.security.SecureRandom;
2548
import java.security.cert.X509Certificate;
49+
import java.util.Date;
2650
import java.util.concurrent.ExecutionException;
2751

2852
import static io.netty.handler.ssl.ocsp.OcspServerCertificateValidator.createDefaultResolver;
53+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
2954
import static org.junit.jupiter.api.Assertions.assertNull;
55+
import static org.junit.jupiter.api.Assertions.assertThrows;
3056

3157
class OcspClientTest {
3258

33-
@Test
34-
void simpleOcspQueryTest() throws IOException, ExecutionException, InterruptedException {
59+
private static final SecureRandom RANDOM = new SecureRandom();
60+
61+
@ParameterizedTest
62+
@ValueSource(strings = {"https://apple.com"})
63+
void simpleOcspQueryTest(String urlString) throws IOException, ExecutionException, InterruptedException {
3564
HttpsURLConnection httpsConnection = null;
3665
try {
37-
URL url = new URL("https://netty.io");
66+
URL url = new URL(urlString);
3867
httpsConnection = (HttpsURLConnection) url.openConnection();
3968
httpsConnection.connect();
4069

@@ -56,4 +85,123 @@ void simpleOcspQueryTest() throws IOException, ExecutionException, InterruptedEx
5685
}
5786
}
5887
}
88+
89+
@Test
90+
void validateSignatureWithIncludedChainSucceeds() throws Exception {
91+
final CertAndKey rootIssuer = buildCertificate("CN=SomeRootCA", true, null);
92+
CertAndKey intermediateIssuer = buildCertificate("CN=SomeIntermediateCA", true, rootIssuer);
93+
CertAndKey ocspResponder = buildCertificate("CN=SomeOCSPResponder", false, intermediateIssuer);
94+
95+
// Create actual OCSP response with the responder's certificate
96+
X509CertificateHolder responderHolder = new JcaX509CertificateHolder(ocspResponder.certificate);
97+
X509CertificateHolder intermediateHolder = new JcaX509CertificateHolder(intermediateIssuer.certificate);
98+
99+
// Create a minimal BasicOCSPResp that contains the certificate chain
100+
final BasicOCSPResp resp = createBasicOcspResponse(
101+
ocspResponder,
102+
new X509CertificateHolder[]{responderHolder, intermediateHolder}
103+
);
104+
105+
assertDoesNotThrow(new Executable() {
106+
@Override
107+
public void execute() throws Throwable {
108+
OcspClient.validateSignature(resp, rootIssuer.certificate);
109+
}
110+
});
111+
}
112+
113+
@Test
114+
void validateSignatureWithInvalidChainThrows() throws Exception {
115+
// Build an unrelated responder chain so nothing is signed by the provided issuer (using RSA)
116+
final CertAndKey issuerBundle = buildCertificate("CN=Issuer", true, null);
117+
118+
// Different CA
119+
CertAndKey otherRoot = buildCertificate("CN=SomeRootCA", true, null);
120+
CertAndKey otherIntermediate = buildCertificate("CN=SomeIntermediateCA", true, otherRoot);
121+
CertAndKey otherResponder = buildCertificate("CN=SomeResponder", false, otherIntermediate);
122+
123+
X509CertificateHolder responderHolder = new JcaX509CertificateHolder(otherResponder.certificate);
124+
X509CertificateHolder intermediateHolder = new JcaX509CertificateHolder(otherIntermediate.certificate);
125+
126+
// Create actual OCSP response with untrusted chain
127+
final BasicOCSPResp resp = createBasicOcspResponse(
128+
otherResponder,
129+
new X509CertificateHolder[]{responderHolder, intermediateHolder}
130+
);
131+
132+
assertThrows(OCSPException.class, new Executable() {
133+
@Override
134+
public void execute() throws Throwable {
135+
OcspClient.validateSignature(resp, issuerBundle.certificate);
136+
}
137+
});
138+
}
139+
140+
private static BasicOCSPResp createBasicOcspResponse(CertAndKey responderBundle,
141+
X509CertificateHolder[] certChain) throws Exception {
142+
CertAndKey dummyCert = buildCertificate("CN=DummyCert", true, null);
143+
144+
// Create certificate ID for OCSP response
145+
CertificateID certId = new CertificateID(
146+
new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1),
147+
new JcaX509CertificateHolder(dummyCert.certificate),
148+
dummyCert.certificate.getSerialNumber()
149+
);
150+
151+
// Create response builder with responder ID based on certificate
152+
X509CertificateHolder responderHolder = new JcaX509CertificateHolder(responderBundle.certificate);
153+
RespID respID = new RespID(responderHolder.getSubject());
154+
155+
BasicOCSPRespBuilder respBuilder = new BasicOCSPRespBuilder(respID);
156+
157+
// Add response for the certificate (status: good)
158+
respBuilder.addResponse(certId, CertificateStatus.GOOD);
159+
160+
// Build and sign the response with the responder's private key
161+
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA")
162+
.build(responderBundle.keyPair.getPrivate());
163+
164+
return respBuilder.build(signer, certChain, new Date());
165+
}
166+
167+
/**
168+
* Build an X.509 certificate with the given subject. If {@code issuer} is {@code null} the certificate is
169+
* self-signed, otherwise it is issued (signed) by the given issuer. Uses RSA-2048 keys.
170+
*/
171+
private static CertAndKey buildCertificate(String subjectDn, boolean isCertificateAuthority,
172+
CertAndKey issuer) throws Exception {
173+
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
174+
keyPairGenerator.initialize(2048);
175+
KeyPair keyPair = keyPairGenerator.generateKeyPair();
176+
177+
X500Name subject = new X500Name(subjectDn);
178+
boolean selfSigned = issuer == null;
179+
X500Name issuerName = selfSigned
180+
? subject
181+
: new JcaX509CertificateHolder(issuer.certificate).getSubject();
182+
PrivateKey signingKey = selfSigned ? keyPair.getPrivate() : issuer.keyPair.getPrivate();
183+
184+
Date notBefore = new Date(System.currentTimeMillis() - 86400000L);
185+
Date notAfter = new Date(System.currentTimeMillis() + 365L * 86400000L);
186+
187+
JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
188+
issuerName, new BigInteger(64, RANDOM), notBefore, notAfter, subject, keyPair.getPublic());
189+
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(isCertificateAuthority));
190+
191+
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey);
192+
X509CertificateHolder holder = builder.build(signer);
193+
X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(holder);
194+
195+
return new CertAndKey(certificate, keyPair);
196+
}
197+
198+
private static final class CertAndKey {
199+
final X509Certificate certificate;
200+
final KeyPair keyPair;
201+
202+
CertAndKey(X509Certificate certificate, KeyPair keyPair) {
203+
this.certificate = certificate;
204+
this.keyPair = keyPair;
205+
}
206+
}
59207
}
Collapse file

‎handler-ssl-ocsp/src/test/java/io/netty/handler/ssl/ocsp/OcspServerCertificateValidatorTest.java‎

Copy file name to clipboardExpand all lines: handler-ssl-ocsp/src/test/java/io/netty/handler/ssl/ocsp/OcspServerCertificateValidatorTest.java
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ void connectUsingHttpAndValidateCertificateUsingOcspTest() throws Exception {
5858
@Override
5959
protected void initChannel(SocketChannel ch) {
6060
ChannelPipeline pipeline = ch.pipeline();
61-
pipeline.addLast(sslContext.newHandler(ch.alloc(), "netty.io", 443));
61+
pipeline.addLast(sslContext.newHandler(ch.alloc(), "apple.com", 443));
6262
pipeline.addLast(new OcspServerCertificateValidator(false));
6363
pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
6464
@Override
@@ -80,7 +80,7 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
8080
}
8181
});
8282

83-
ChannelFuture channelFuture = bootstrap.connect("netty.io", 443);
83+
ChannelFuture channelFuture = bootstrap.connect("apple.com", 443);
8484
channelFuture.sync();
8585

8686
// Wait for maximum of 1 minute for Ocsp validation to happen

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.