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 — OCSP: TOCTOU in OcspServerCertificateValidator · netty/netty@1c7bf68

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • handler-ssl-ocsp/src/main/java
    • io/netty/handler/ssl/ocsp
      • OcspClient.java
      • OcspHttpHandler.java
      • OcspServerCertificateValidator.java
    • module-info.yml
Expand file treeCollapse file tree
Open diff view settings
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
+7-4Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import io.netty.util.concurrent.FutureListener;
3535
import io.netty.util.concurrent.GenericFutureListener;
3636
import io.netty.util.concurrent.Promise;
37+
import io.netty.util.internal.ObjectUtil;
3738
import io.netty.util.internal.SystemPropertyUtil;
3839
import io.netty.util.internal.logging.InternalLogger;
3940
import io.netty.util.internal.logging.InternalLoggerFactory;
@@ -201,7 +202,7 @@ private static Promise<OCSPResp> query(final EventLoop eventLoop, final ByteBuf
201202
.option(ChannelOption.TCP_NODELAY, true)
202203
.channelFactory(ioTransport.socketChannel())
203204
.attr(OcspServerCertificateValidator.OCSP_PIPELINE_ATTRIBUTE, Boolean.TRUE)
204-
.handler(new Initializer(responsePromise));
205+
.handler(new Initializer(responsePromise, 10 * 1000));
205206
dnsNameResolver.resolve(host).addListener((FutureListener<InetAddress>) future -> {
206207

207208
// If Future was successful then we have successfully resolved OCSP server address.
@@ -390,17 +391,19 @@ private static String parseOcspUrlFromCertificate(X509Certificate cert) {
390391
static final class Initializer extends ChannelInitializer<SocketChannel> {
391392

392393
private final Promise<OCSPResp> responsePromise;
394+
private final long timeoutMillis;
393395

394-
Initializer(Promise<OCSPResp> responsePromise) {
395-
this.responsePromise = checkNotNull(responsePromise, "ResponsePromise");
396+
Initializer(Promise<OCSPResp> responsePromise, long timeoutMillis) {
397+
this.responsePromise = checkNotNull(responsePromise, "responsePromise");
398+
this.timeoutMillis = ObjectUtil.checkPositive(timeoutMillis, "timeoutMillis");
396399
}
397400

398401
@Override
399402
protected void initChannel(SocketChannel socketChannel) {
400403
ChannelPipeline pipeline = socketChannel.pipeline();
401404
pipeline.addLast(new HttpClientCodec());
402405
pipeline.addLast(new HttpObjectAggregator(OCSP_RESPONSE_MAX_SIZE));
403-
pipeline.addLast(new OcspHttpHandler(responsePromise));
406+
pipeline.addLast(new OcspHttpHandler(responsePromise, timeoutMillis));
404407
}
405408
}
406409

Collapse file

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

Copy file name to clipboardExpand all lines: handler-ssl-ocsp/src/main/java/io/netty/handler/ssl/ocsp/OcspHttpHandler.java
+31-7Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,39 +16,51 @@
1616
package io.netty.handler.ssl.ocsp;
1717

1818
import io.netty.buffer.ByteBufUtil;
19+
import io.netty.channel.ChannelDuplexHandler;
1920
import io.netty.channel.ChannelHandlerContext;
21+
import io.netty.channel.ChannelPromise;
2022
import io.netty.channel.SimpleChannelInboundHandler;
2123
import io.netty.handler.codec.http.FullHttpResponse;
2224
import io.netty.handler.codec.http.HttpHeaderNames;
25+
import io.netty.util.concurrent.Future;
2326
import io.netty.util.concurrent.Promise;
27+
import io.netty.util.internal.ObjectUtil;
2428
import io.netty.util.internal.logging.InternalLogger;
2529
import io.netty.util.internal.logging.InternalLoggerFactory;
2630
import org.bouncycastle.cert.ocsp.OCSPException;
2731
import org.bouncycastle.cert.ocsp.OCSPResp;
2832

33+
import java.util.concurrent.TimeUnit;
34+
2935
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
3036
import static io.netty.util.internal.ObjectUtil.checkNotNull;
3137

32-
final class OcspHttpHandler extends SimpleChannelInboundHandler<FullHttpResponse> {
38+
final class OcspHttpHandler extends ChannelDuplexHandler {
3339

3440
private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(OcspHttpHandler.class);
3541
private final Promise<OCSPResp> responseFuture;
36-
42+
private final long timeoutMillis;
43+
private Future<?> timeoutFuture;
3744
static final String OCSP_REQUEST_TYPE = "application/ocsp-request";
3845
static final String OCSP_RESPONSE_TYPE = "application/ocsp-response";
3946

4047
/**
4148
* Create new {@link OcspHttpHandler} instance
4249
*
43-
* @param responsePromise {@link Promise} of {@link OCSPResp}
50+
* @param responsePromise {@link Promise} of {@link OCSPResp}
51+
* @param timeoutMillis the timeout in milliseconds how long a response can take to before we fail the promise.
4452
*/
45-
OcspHttpHandler(Promise<OCSPResp> responsePromise) {
46-
super(FullHttpResponse.class);
53+
OcspHttpHandler(Promise<OCSPResp> responsePromise, long timeoutMillis) {
4754
this.responseFuture = checkNotNull(responsePromise, "ResponsePromise");
55+
this.timeoutMillis = ObjectUtil.checkPositive(timeoutMillis, "timeoutMillis");
56+
this.responseFuture.addListener(f -> {
57+
timeoutFuture.cancel(true);
58+
});
4859
}
4960

5061
@Override
51-
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception {
62+
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
63+
FullHttpResponse response = (FullHttpResponse) msg;
5264
try {
5365
// If DEBUG is enabled then log the response
5466
if (LOGGER.isDebugEnabled()) {
@@ -75,12 +87,24 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response
7587

7688
responseFuture.trySuccess(new OCSPResp(ByteBufUtil.getBytes(response.content())));
7789
} finally {
78-
ctx.channel().close();
90+
response.release();
91+
ctx.close();
7992
}
8093
}
8194

8295
@Override
8396
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
8497
responseFuture.tryFailure(cause);
8598
}
99+
100+
@Override
101+
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
102+
super.write(ctx, msg, promise);
103+
timeoutFuture = ctx.executor().schedule(() -> {
104+
if (!responseFuture.isDone()) {
105+
responseFuture.tryFailure(new OCSPException("OCSP response was not received within "
106+
+ timeoutMillis + "ms"));
107+
}
108+
}, timeoutMillis, TimeUnit.MILLISECONDS);
109+
}
86110
}
Collapse file

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

Copy file name to clipboardExpand all lines: handler-ssl-ocsp/src/main/java/io/netty/handler/ssl/ocsp/OcspServerCertificateValidator.java
+105-37Lines changed: 105 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,12 @@
1515
*/
1616
package io.netty.handler.ssl.ocsp;
1717

18+
import io.netty.buffer.ByteBuf;
1819
import io.netty.channel.ChannelHandlerContext;
1920
import io.netty.channel.ChannelInboundHandlerAdapter;
21+
import io.netty.channel.ChannelOutboundHandler;
22+
import io.netty.channel.ChannelPromise;
23+
import io.netty.handler.codec.ByteToMessageDecoder;
2024
import io.netty.handler.ssl.SslHandler;
2125
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
2226
import io.netty.resolver.dns.DnsNameResolver;
@@ -30,9 +34,11 @@
3034
import org.bouncycastle.cert.ocsp.RevokedStatus;
3135
import org.bouncycastle.cert.ocsp.SingleResp;
3236

37+
import java.net.SocketAddress;
3338
import java.security.cert.Certificate;
3439
import java.security.cert.X509Certificate;
3540
import java.util.Date;
41+
import java.util.List;
3642

3743
import static io.netty.util.internal.ObjectUtil.checkNotNull;
3844

@@ -41,7 +47,7 @@
4147
* using OCSP. Once TLS handshake is completed, {@link SslHandshakeCompletionEvent#SUCCESS} is fired, validator
4248
* will perform certificate validation using OCSP over HTTP/1.1 with the server's certificate issuer OCSP responder.
4349
*/
44-
public class OcspServerCertificateValidator extends ChannelInboundHandlerAdapter {
50+
public class OcspServerCertificateValidator extends ByteToMessageDecoder implements ChannelOutboundHandler {
4551
/**
4652
* An attribute used to mark all channels created by the {@link OcspServerCertificateValidator}.
4753
*/
@@ -52,6 +58,8 @@ public class OcspServerCertificateValidator extends ChannelInboundHandlerAdapter
5258
private final boolean validateNonce;
5359
private final IoTransport ioTransport;
5460
private final DnsNameResolver dnsNameResolver;
61+
private boolean ocspQueryInProgress;
62+
private boolean readPending;
5563

5664
/**
5765
* Create a new {@link OcspServerCertificateValidator} instance without nonce validation
@@ -128,9 +136,12 @@ protected static DnsNameResolver createDefaultResolver(final IoTransport ioTrans
128136
}
129137

130138
@Override
131-
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
132-
ctx.fireUserEventTriggered(evt);
139+
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
140+
// Just buffer until the handler is removed which will happen once we did finish the OCSP processing.
141+
}
133142

143+
@Override
144+
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
134145
if (evt instanceof SslHandshakeCompletionEvent) {
135146
SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) evt;
136147

@@ -146,52 +157,109 @@ public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt
146157

147158
Promise<BasicOCSPResp> ocspRespPromise = OcspClient.query((X509Certificate) certificates[0],
148159
(X509Certificate) certificates[1], validateNonce, ioTransport, dnsNameResolver);
149-
160+
ocspQueryInProgress = true;
150161
ocspRespPromise.addListener((GenericFutureListener<Future<BasicOCSPResp>>) future -> {
151-
// If Future is success then we have successfully received OCSP response
152-
// from OCSP responder. We will validate it now and process.
153-
if (future.isSuccess()) {
154-
SingleResp response = future.getNow().getResponses()[0];
155-
156-
Date current = new Date();
157-
if (!(current.after(response.getThisUpdate()) &&
158-
current.before(response.getNextUpdate()))) {
159-
ctx.fireExceptionCaught(new IllegalStateException("OCSP Response is out-of-date"));
160-
}
162+
ocspQueryInProgress = false;
163+
try {
164+
// If Future is success then we have successfully received OCSP response
165+
// from OCSP responder. We will validate it now and process.
166+
if (future.isSuccess()) {
167+
SingleResp response = future.getNow().getResponses()[0];
161168

162-
OcspResponse.Status status;
163-
if (response.getCertStatus() == null) {
164-
// 'null' means certificate is valid
165-
status = OcspResponse.Status.VALID;
166-
} else if (response.getCertStatus() instanceof RevokedStatus) {
167-
status = OcspResponse.Status.REVOKED;
168-
} else {
169-
status = OcspResponse.Status.UNKNOWN;
170-
}
169+
Date current = new Date();
170+
if (!(current.after(response.getThisUpdate()) &&
171+
current.before(response.getNextUpdate()))) {
172+
ctx.fireExceptionCaught(new IllegalStateException("OCSP Response is out-of-date"));
173+
return;
174+
}
175+
176+
OcspResponse.Status status;
177+
if (response.getCertStatus() == null) {
178+
// 'null' means certificate is valid
179+
status = OcspResponse.Status.VALID;
180+
} else if (response.getCertStatus() instanceof RevokedStatus) {
181+
status = OcspResponse.Status.REVOKED;
182+
} else {
183+
status = OcspResponse.Status.UNKNOWN;
184+
}
171185

172-
ctx.fireUserEventTriggered(new OcspValidationEvent(
173-
new OcspResponse(status, response.getThisUpdate(), response.getNextUpdate())));
186+
ctx.fireUserEventTriggered(new OcspValidationEvent(
187+
new OcspResponse(status, response.getThisUpdate(), response.getNextUpdate())));
174188

175-
// If Certificate is not VALID and 'closeAndThrowIfNotValid' is set
176-
// to 'true' then close the channel and throw an exception.
177-
if (status != OcspResponse.Status.VALID && closeAndThrowIfNotValid) {
178-
ctx.channel().close();
179-
// Certificate is not valid. Throw
180-
ctx.fireExceptionCaught(new OCSPException(
181-
"Certificate not valid. Status: " + status));
189+
// If Certificate is not VALID and 'closeAndThrowIfNotValid' is set
190+
// to 'true' then close the channel and throw an exception.
191+
if (status != OcspResponse.Status.VALID && closeAndThrowIfNotValid) {
192+
// Certificate is not valid. Throw
193+
ctx.fireExceptionCaught(new OCSPException(
194+
"Certificate not valid. Status: " + status));
195+
ctx.close();
196+
}
197+
} else {
198+
ctx.fireExceptionCaught(future.cause());
199+
}
200+
} finally {
201+
ctx.fireUserEventTriggered(evt);
202+
// Lets remove ourselves from the pipeline because we are done processing validation.
203+
ctx.pipeline().remove(this);
204+
if (readPending) {
205+
readPending = false;
206+
ctx.read();
182207
}
183-
} else {
184-
ctx.fireExceptionCaught(future.cause());
185208
}
186209
});
187210
}
188-
// Lets remove ourselves from the pipeline because we are done processing validation.
189-
ctx.pipeline().remove(this);
190211
}
191212
}
192213

193214
@Override
194215
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
195-
ctx.channel().close();
216+
ctx.close();
217+
}
218+
219+
@Override
220+
public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
221+
ctx.bind(localAddress, promise);
222+
}
223+
224+
@Override
225+
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
226+
SocketAddress localAddress, ChannelPromise promise) throws Exception {
227+
ctx.connect(remoteAddress, localAddress, promise);
228+
}
229+
230+
@Override
231+
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
232+
ctx.disconnect(promise);
233+
}
234+
235+
@Override
236+
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
237+
ctx.close(promise);
238+
}
239+
240+
@Override
241+
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
242+
ctx.deregister(promise);
243+
}
244+
245+
@Override
246+
public void read(ChannelHandlerContext ctx) throws Exception {
247+
// Let's stop reading until we are done with the processing of the OCSP query.
248+
if (ocspQueryInProgress) {
249+
readPending = true;
250+
} else {
251+
readPending = false;
252+
ctx.read();
253+
}
254+
}
255+
256+
@Override
257+
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
258+
ctx.write(msg, promise);
259+
}
260+
261+
@Override
262+
public void flush(ChannelHandlerContext ctx) throws Exception {
263+
ctx.flush();
196264
}
197265
}
Collapse file

‎handler-ssl-ocsp/src/main/java/module-info.yml‎

Copy file name to clipboardExpand all lines: handler-ssl-ocsp/src/main/java/module-info.yml
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ requires:
1717
- module: io.netty.common
1818
- module: io.netty.buffer
1919
- module: io.netty.handler
20+
- module: io.netty.codec
2021
- module: io.netty.codec.http
2122
- module: io.netty.transport
2223
- module: io.netty.resolver.dns

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.