1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.ssl.ocsp;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.channel.ChannelOutboundHandler;
21 import io.netty.channel.ChannelPromise;
22 import io.netty.handler.codec.ByteToMessageDecoder;
23 import io.netty.handler.ssl.SslHandler;
24 import io.netty.handler.ssl.SslHandshakeCompletionEvent;
25 import io.netty.resolver.dns.DnsNameResolver;
26 import io.netty.resolver.dns.DnsNameResolverBuilder;
27 import io.netty.util.AttributeKey;
28 import io.netty.util.ReferenceCountUtil;
29 import io.netty.util.concurrent.Future;
30 import io.netty.util.concurrent.GenericFutureListener;
31 import io.netty.util.concurrent.Promise;
32 import io.netty.util.internal.SystemPropertyUtil;
33 import org.bouncycastle.cert.ocsp.BasicOCSPResp;
34 import org.bouncycastle.cert.ocsp.OCSPException;
35 import org.bouncycastle.cert.ocsp.RevokedStatus;
36 import org.bouncycastle.cert.ocsp.SingleResp;
37
38 import java.net.SocketAddress;
39 import java.security.cert.Certificate;
40 import java.security.cert.X509Certificate;
41 import java.util.Date;
42 import java.util.List;
43 import java.util.concurrent.TimeUnit;
44
45 import static io.netty.util.internal.ObjectUtil.checkNotNull;
46
47
48
49
50
51
52 public class OcspServerCertificateValidator extends ByteToMessageDecoder implements ChannelOutboundHandler {
53
54
55
56 public static final AttributeKey<Boolean> OCSP_PIPELINE_ATTRIBUTE =
57 AttributeKey.newInstance("io.netty.handler.ssl.ocsp.pipeline");
58
59
60
61
62 private static final long CLOCK_SKEW_TOLERANCE_MILLIS = getClockSkewTolerance();
63
64 private static long getClockSkewTolerance() {
65 long defaultToleranceSeconds = TimeUnit.MINUTES.toSeconds(15);
66 long maxToleranceSeconds = TimeUnit.DAYS.toSeconds(2);
67 long configuredToleranceSeconds = SystemPropertyUtil.getLong("io.netty.handler.ssl.ocsp.clockSkew",
68 SystemPropertyUtil.getLong("com.sun.security.ocsp.clockSkew", defaultToleranceSeconds));
69 if (configuredToleranceSeconds < 0 || configuredToleranceSeconds > maxToleranceSeconds) {
70
71 configuredToleranceSeconds = defaultToleranceSeconds;
72 }
73 return TimeUnit.SECONDS.toMillis(configuredToleranceSeconds);
74 }
75
76 private final boolean closeAndThrowIfNotValid;
77 private final boolean validateNonce;
78 private final IoTransport ioTransport;
79 private final DnsNameResolver dnsNameResolver;
80 private boolean ocspQueryInProgress;
81 private boolean readPending;
82 private boolean discardInbound;
83
84
85
86
87
88
89
90 public OcspServerCertificateValidator() {
91 this(false);
92 }
93
94
95
96
97
98
99
100
101
102 public OcspServerCertificateValidator(boolean validateNonce) {
103 this(validateNonce, IoTransport.DEFAULT);
104 }
105
106
107
108
109
110
111
112
113 public OcspServerCertificateValidator(boolean validateNonce, IoTransport ioTransport) {
114 this(validateNonce, ioTransport, createDefaultResolver(ioTransport));
115 }
116
117
118
119
120
121
122
123
124
125 public OcspServerCertificateValidator(boolean validateNonce, IoTransport ioTransport,
126 DnsNameResolver dnsNameResolver) {
127 this(true, validateNonce, ioTransport, dnsNameResolver);
128 }
129
130
131
132
133
134
135
136
137
138
139
140
141
142 public OcspServerCertificateValidator(boolean closeAndThrowIfNotValid, boolean validateNonce,
143 IoTransport ioTransport, DnsNameResolver dnsNameResolver) {
144 this.closeAndThrowIfNotValid = closeAndThrowIfNotValid;
145 this.validateNonce = validateNonce;
146 this.ioTransport = checkNotNull(ioTransport, "IoTransport");
147 this.dnsNameResolver = checkNotNull(dnsNameResolver, "DnsNameResolver");
148 }
149
150 protected static DnsNameResolver createDefaultResolver(final IoTransport ioTransport) {
151 return new DnsNameResolverBuilder()
152 .eventLoop(ioTransport.eventLoop())
153 .datagramChannelFactory(ioTransport.datagramChannel())
154 .socketChannelFactory(ioTransport.socketChannel())
155 .build();
156 }
157
158 @Override
159 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
160
161 }
162
163 @Override
164 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
165 if (discardInbound) {
166 ReferenceCountUtil.release(msg);
167 return;
168 }
169 super.channelRead(ctx, msg);
170 }
171
172 @Override
173 public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
174 if (evt instanceof SslHandshakeCompletionEvent) {
175 SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) evt;
176
177
178
179 if (sslHandshakeCompletionEvent.isSuccess()) {
180 Certificate[] certificates = ctx.pipeline().get(SslHandler.class)
181 .engine()
182 .getSession()
183 .getPeerCertificates();
184
185 assert certificates.length >= 2 : "There must an end-entity certificate and issuer certificate";
186
187 Promise<BasicOCSPResp> ocspRespPromise = ctx.executor().newPromise();
188 OcspClient.query((X509Certificate) certificates[0], (X509Certificate) certificates[1],
189 validateNonce, ioTransport, dnsNameResolver, ocspRespPromise);
190 ocspQueryInProgress = true;
191 ocspRespPromise.addListener(new GenericFutureListener<Future<BasicOCSPResp>>() {
192 @Override
193 public void operationComplete(Future<BasicOCSPResp> future) throws Exception {
194 ocspQueryInProgress = false;
195
196 OcspResponse.Status status = OcspResponse.Status.REVOKED;
197 try {
198
199
200 if (future.isSuccess()) {
201 SingleResp response = future.getNow().getResponses()[0];
202
203 Date thisUpdate = response.getThisUpdate();
204 Date nextUpdate = response.getNextUpdate();
205 long now = System.currentTimeMillis();
206 Date nowLower = new Date(now - CLOCK_SKEW_TOLERANCE_MILLIS);
207 Date nowUpper = new Date(now + CLOCK_SKEW_TOLERANCE_MILLIS);
208 if (thisUpdate == null || nowUpper.before(thisUpdate) ||
209 nowLower.after(nextUpdate == null ? thisUpdate : nextUpdate)) {
210 ctx.fireExceptionCaught(new IllegalStateException("OCSP Response is out-of-date"));
211 if (closeAndThrowIfNotValid) {
212 ctx.close();
213 }
214 return;
215 }
216
217 if (response.getCertStatus() == null) {
218
219 status = OcspResponse.Status.VALID;
220 } else if (response.getCertStatus() instanceof RevokedStatus) {
221 status = OcspResponse.Status.REVOKED;
222 } else {
223 status = OcspResponse.Status.UNKNOWN;
224 }
225
226 ctx.fireUserEventTriggered(new OcspValidationEvent(
227 new OcspResponse(status, thisUpdate, nextUpdate)));
228
229
230
231 if (status != OcspResponse.Status.VALID && closeAndThrowIfNotValid) {
232
233 ctx.fireExceptionCaught(new OCSPException(
234 "Certificate not valid. Status: " + status));
235 ctx.close();
236 }
237 } else {
238 ctx.fireExceptionCaught(future.cause());
239 if (closeAndThrowIfNotValid) {
240 ctx.close();
241 }
242 }
243 } catch (Throwable th) {
244 ctx.fireExceptionCaught(th);
245 if (closeAndThrowIfNotValid) {
246 ctx.close();
247 }
248 } finally {
249 if (status != OcspResponse.Status.VALID && closeAndThrowIfNotValid) {
250
251
252
253
254 discardInbound = true;
255 internalBuffer().clear();
256 ctx.fireUserEventTriggered(evt);
257 } else {
258 ctx.fireUserEventTriggered(evt);
259
260
261 ctx.pipeline().remove(OcspServerCertificateValidator.this);
262 }
263 if (readPending) {
264 readPending = false;
265 ctx.read();
266 }
267 }
268 }
269 });
270 } else {
271 ctx.fireUserEventTriggered(evt);
272 }
273 } else {
274 ctx.fireUserEventTriggered(evt);
275 }
276 }
277
278 @Override
279 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
280 ctx.close();
281 }
282
283 @Override
284 public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
285 ctx.bind(localAddress, promise);
286 }
287
288 @Override
289 public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
290 SocketAddress localAddress, ChannelPromise promise) throws Exception {
291 ctx.connect(remoteAddress, localAddress, promise);
292 }
293
294 @Override
295 public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
296 ctx.disconnect(promise);
297 }
298
299 @Override
300 public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
301 ctx.close(promise);
302 }
303
304 @Override
305 public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
306 ctx.deregister(promise);
307 }
308
309 @Override
310 public void read(ChannelHandlerContext ctx) throws Exception {
311
312 if (ocspQueryInProgress) {
313 readPending = true;
314 } else {
315 readPending = false;
316 ctx.read();
317 }
318 }
319
320 @Override
321 public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
322 ctx.write(msg, promise);
323 }
324
325 @Override
326 public void flush(ChannelHandlerContext ctx) throws Exception {
327 ctx.flush();
328 }
329 }