View Javadoc
1   /*
2    * Copyright 2016 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    *   http://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;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.internal.tcnative.CertificateVerifier;
21  import io.netty.internal.tcnative.SSL;
22  import io.netty.internal.tcnative.SSLContext;
23  import io.netty.util.AbstractReferenceCounted;
24  import io.netty.util.ReferenceCounted;
25  import io.netty.util.ResourceLeakDetector;
26  import io.netty.util.ResourceLeakDetectorFactory;
27  import io.netty.util.ResourceLeakTracker;
28  import io.netty.util.internal.PlatformDependent;
29  import io.netty.util.internal.StringUtil;
30  import io.netty.util.internal.SystemPropertyUtil;
31  import io.netty.util.internal.logging.InternalLogger;
32  import io.netty.util.internal.logging.InternalLoggerFactory;
33  
34  import java.security.AccessController;
35  import java.security.PrivateKey;
36  import java.security.PrivilegedAction;
37  import java.security.cert.CertPathValidatorException;
38  import java.security.cert.Certificate;
39  import java.security.cert.CertificateExpiredException;
40  import java.security.cert.CertificateNotYetValidException;
41  import java.security.cert.CertificateRevokedException;
42  import java.security.cert.X509Certificate;
43  import java.util.Arrays;
44  import java.util.Collections;
45  import java.util.List;
46  import java.util.Map;
47  import java.util.concurrent.locks.Lock;
48  import java.util.concurrent.locks.ReadWriteLock;
49  import java.util.concurrent.locks.ReentrantReadWriteLock;
50  
51  import javax.net.ssl.KeyManager;
52  import javax.net.ssl.SSLEngine;
53  import javax.net.ssl.SSLException;
54  import javax.net.ssl.SSLHandshakeException;
55  import javax.net.ssl.TrustManager;
56  import javax.net.ssl.X509ExtendedKeyManager;
57  import javax.net.ssl.X509ExtendedTrustManager;
58  import javax.net.ssl.X509KeyManager;
59  import javax.net.ssl.X509TrustManager;
60  
61  import static io.netty.handler.ssl.OpenSsl.DEFAULT_CIPHERS;
62  import static io.netty.handler.ssl.OpenSsl.availableJavaCipherSuites;
63  import static io.netty.util.internal.ObjectUtil.checkNotNull;
64  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
65  
66  /**
67   * An implementation of {@link SslContext} which works with libraries that support the
68   * <a href="https://www.openssl.org/">OpenSsl</a> C library API.
69   * <p>Instances of this class must be {@link #release() released} or else native memory will leak!
70   *
71   * <p>Instances of this class <strong>must not</strong> be released before any {@link ReferenceCountedOpenSslEngine}
72   * which depends upon the instance of this class is released. Otherwise if any method of
73   * {@link ReferenceCountedOpenSslEngine} is called which uses this class's JNI resources the JVM may crash.
74   */
75  public abstract class ReferenceCountedOpenSslContext extends SslContext implements ReferenceCounted {
76      private static final InternalLogger logger =
77              InternalLoggerFactory.getInstance(ReferenceCountedOpenSslContext.class);
78  
79      private static final int DEFAULT_BIO_NON_APPLICATION_BUFFER_SIZE =
80              AccessController.doPrivileged(new PrivilegedAction<Integer>() {
81                  @Override
82                  public Integer run() {
83                      return Math.max(1,
84                              SystemPropertyUtil.getInt("io.netty.handler.ssl.openssl.bioNonApplicationBufferSize",
85                                                        2048));
86                  }
87              });
88  
89      private static final Integer DH_KEY_LENGTH;
90      private static final ResourceLeakDetector<ReferenceCountedOpenSslContext> leakDetector =
91              ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ReferenceCountedOpenSslContext.class);
92  
93      // TODO: Maybe make configurable ?
94      protected static final int VERIFY_DEPTH = 10;
95  
96      /**
97       * The OpenSSL SSL_CTX object.
98       *
99       * <strong>{@link #ctxLock} must be hold while using ctx!</strong>
100      */
101     protected long ctx;
102     private final List<String> unmodifiableCiphers;
103     private final long sessionCacheSize;
104     private final long sessionTimeout;
105     private final OpenSslApplicationProtocolNegotiator apn;
106     private final int mode;
107 
108     // Reference Counting
109     private final ResourceLeakTracker<ReferenceCountedOpenSslContext> leak;
110     private final AbstractReferenceCounted refCnt = new AbstractReferenceCounted() {
111         @Override
112         public ReferenceCounted touch(Object hint) {
113             if (leak != null) {
114                 leak.record(hint);
115             }
116 
117             return ReferenceCountedOpenSslContext.this;
118         }
119 
120         @Override
121         protected void deallocate() {
122             destroy();
123             if (leak != null) {
124                 boolean closed = leak.close(ReferenceCountedOpenSslContext.this);
125                 assert closed;
126             }
127         }
128     };
129 
130     final Certificate[] keyCertChain;
131     final ClientAuth clientAuth;
132     final String[] protocols;
133     final boolean enableOcsp;
134     final OpenSslEngineMap engineMap = new DefaultOpenSslEngineMap();
135     final ReadWriteLock ctxLock = new ReentrantReadWriteLock();
136 
137     private volatile int bioNonApplicationBufferSize = DEFAULT_BIO_NON_APPLICATION_BUFFER_SIZE;
138 
139     @SuppressWarnings("deprecation")
140     static final OpenSslApplicationProtocolNegotiator NONE_PROTOCOL_NEGOTIATOR =
141             new OpenSslApplicationProtocolNegotiator() {
142                 @Override
143                 public ApplicationProtocolConfig.Protocol protocol() {
144                     return ApplicationProtocolConfig.Protocol.NONE;
145                 }
146 
147                 @Override
148                 public List<String> protocols() {
149                     return Collections.emptyList();
150                 }
151 
152                 @Override
153                 public ApplicationProtocolConfig.SelectorFailureBehavior selectorFailureBehavior() {
154                     return ApplicationProtocolConfig.SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL;
155                 }
156 
157                 @Override
158                 public ApplicationProtocolConfig.SelectedListenerFailureBehavior selectedListenerFailureBehavior() {
159                     return ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT;
160                 }
161             };
162 
163     static {
164         Integer dhLen = null;
165 
166         try {
167             String dhKeySize = AccessController.doPrivileged(new PrivilegedAction<String>() {
168                 @Override
169                 public String run() {
170                     return SystemPropertyUtil.get("jdk.tls.ephemeralDHKeySize");
171                 }
172             });
173             if (dhKeySize != null) {
174                 try {
175                     dhLen = Integer.valueOf(dhKeySize);
176                 } catch (NumberFormatException e) {
177                     logger.debug("ReferenceCountedOpenSslContext supports -Djdk.tls.ephemeralDHKeySize={int}, but got: "
178                             + dhKeySize);
179                 }
180             }
181         } catch (Throwable ignore) {
182             // ignore
183         }
184         DH_KEY_LENGTH = dhLen;
185     }
186 
187     ReferenceCountedOpenSslContext(Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
188                                    ApplicationProtocolConfig apnCfg, long sessionCacheSize, long sessionTimeout,
189                                    int mode, Certificate[] keyCertChain, ClientAuth clientAuth, String[] protocols,
190                                    boolean startTls, boolean enableOcsp, boolean leakDetection) throws SSLException {
191         this(ciphers, cipherFilter, toNegotiator(apnCfg), sessionCacheSize, sessionTimeout, mode, keyCertChain,
192                 clientAuth, protocols, startTls, enableOcsp, leakDetection);
193     }
194 
195     ReferenceCountedOpenSslContext(Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
196                                    OpenSslApplicationProtocolNegotiator apn, long sessionCacheSize,
197                                    long sessionTimeout, int mode, Certificate[] keyCertChain,
198                                    ClientAuth clientAuth, String[] protocols, boolean startTls, boolean enableOcsp,
199                                    boolean leakDetection) throws SSLException {
200         super(startTls);
201 
202         OpenSsl.ensureAvailability();
203 
204         if (enableOcsp && !OpenSsl.isOcspSupported()) {
205             throw new IllegalStateException("OCSP is not supported.");
206         }
207 
208         if (mode != SSL.SSL_MODE_SERVER && mode != SSL.SSL_MODE_CLIENT) {
209             throw new IllegalArgumentException("mode most be either SSL.SSL_MODE_SERVER or SSL.SSL_MODE_CLIENT");
210         }
211         leak = leakDetection ? leakDetector.track(this) : null;
212         this.mode = mode;
213         this.clientAuth = isServer() ? checkNotNull(clientAuth, "clientAuth") : ClientAuth.NONE;
214         this.protocols = protocols;
215         this.enableOcsp = enableOcsp;
216 
217         this.keyCertChain = keyCertChain == null ? null : keyCertChain.clone();
218 
219         unmodifiableCiphers = Arrays.asList(checkNotNull(cipherFilter, "cipherFilter").filterCipherSuites(
220                 ciphers, DEFAULT_CIPHERS, availableJavaCipherSuites()));
221 
222         this.apn = checkNotNull(apn, "apn");
223 
224         // Create a new SSL_CTX and configure it.
225         boolean success = false;
226         try {
227             try {
228                 ctx = SSLContext.make(SSL.SSL_PROTOCOL_ALL, mode);
229             } catch (Exception e) {
230                 throw new SSLException("failed to create an SSL_CTX", e);
231             }
232 
233             SSLContext.setOptions(ctx, SSLContext.getOptions(ctx) |
234                     SSL.SSL_OP_NO_SSLv2 |
235                     SSL.SSL_OP_NO_SSLv3 |
236                     SSL.SSL_OP_CIPHER_SERVER_PREFERENCE |
237 
238                     // We do not support compression at the moment so we should explicitly disable it.
239                     SSL.SSL_OP_NO_COMPRESSION |
240 
241                     // Disable ticket support by default to be more inline with SSLEngineImpl of the JDK.
242                     // This also let SSLSession.getId() work the same way for the JDK implementation and the
243                     // OpenSSLEngine. If tickets are supported SSLSession.getId() will only return an ID on the
244                     // server-side if it could make use of tickets.
245                     SSL.SSL_OP_NO_TICKET);
246 
247             // We need to enable SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER as the memory address may change between
248             // calling OpenSSLEngine.wrap(...).
249             // See https://github.com/netty/netty-tcnative/issues/100
250             SSLContext.setMode(ctx, SSLContext.getMode(ctx) | SSL.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
251 
252             if (DH_KEY_LENGTH != null) {
253                 SSLContext.setTmpDHLength(ctx, DH_KEY_LENGTH);
254             }
255 
256                 /* List the ciphers that are permitted to negotiate. */
257             try {
258                 SSLContext.setCipherSuite(ctx, CipherSuiteConverter.toOpenSsl(unmodifiableCiphers));
259             } catch (SSLException e) {
260                 throw e;
261             } catch (Exception e) {
262                 throw new SSLException("failed to set cipher suite: " + unmodifiableCiphers, e);
263             }
264 
265             List<String> nextProtoList = apn.protocols();
266                 /* Set next protocols for next protocol negotiation extension, if specified */
267             if (!nextProtoList.isEmpty()) {
268                 String[] appProtocols = nextProtoList.toArray(new String[nextProtoList.size()]);
269                 int selectorBehavior = opensslSelectorFailureBehavior(apn.selectorFailureBehavior());
270 
271                 switch (apn.protocol()) {
272                     case NPN:
273                         SSLContext.setNpnProtos(ctx, appProtocols, selectorBehavior);
274                         break;
275                     case ALPN:
276                         SSLContext.setAlpnProtos(ctx, appProtocols, selectorBehavior);
277                         break;
278                     case NPN_AND_ALPN:
279                         SSLContext.setNpnProtos(ctx, appProtocols, selectorBehavior);
280                         SSLContext.setAlpnProtos(ctx, appProtocols, selectorBehavior);
281                         break;
282                     default:
283                         throw new Error();
284                 }
285             }
286 
287             /* Set session cache size, if specified */
288             if (sessionCacheSize > 0) {
289                 this.sessionCacheSize = sessionCacheSize;
290                 SSLContext.setSessionCacheSize(ctx, sessionCacheSize);
291             } else {
292                 // Get the default session cache size using SSLContext.setSessionCacheSize()
293                 this.sessionCacheSize = sessionCacheSize = SSLContext.setSessionCacheSize(ctx, 20480);
294                 // Revert the session cache size to the default value.
295                 SSLContext.setSessionCacheSize(ctx, sessionCacheSize);
296             }
297 
298             /* Set session timeout, if specified */
299             if (sessionTimeout > 0) {
300                 this.sessionTimeout = sessionTimeout;
301                 SSLContext.setSessionCacheTimeout(ctx, sessionTimeout);
302             } else {
303                 // Get the default session timeout using SSLContext.setSessionCacheTimeout()
304                 this.sessionTimeout = sessionTimeout = SSLContext.setSessionCacheTimeout(ctx, 300);
305                 // Revert the session timeout to the default value.
306                 SSLContext.setSessionCacheTimeout(ctx, sessionTimeout);
307             }
308 
309             if (enableOcsp) {
310                 SSLContext.enableOcsp(ctx, isClient());
311             }
312             success = true;
313         } finally {
314             if (!success) {
315                 release();
316             }
317         }
318     }
319 
320     private static int opensslSelectorFailureBehavior(ApplicationProtocolConfig.SelectorFailureBehavior behavior) {
321         switch (behavior) {
322             case NO_ADVERTISE:
323                 return SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE;
324             case CHOOSE_MY_LAST_PROTOCOL:
325                 return SSL.SSL_SELECTOR_FAILURE_CHOOSE_MY_LAST_PROTOCOL;
326             default:
327                 throw new Error();
328         }
329     }
330 
331     @Override
332     public final List<String> cipherSuites() {
333         return unmodifiableCiphers;
334     }
335 
336     @Override
337     public final long sessionCacheSize() {
338         return sessionCacheSize;
339     }
340 
341     @Override
342     public final long sessionTimeout() {
343         return sessionTimeout;
344     }
345 
346     @Override
347     public ApplicationProtocolNegotiator applicationProtocolNegotiator() {
348         return apn;
349     }
350 
351     @Override
352     public final boolean isClient() {
353         return mode == SSL.SSL_MODE_CLIENT;
354     }
355 
356     @Override
357     public final SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
358         return newEngine0(alloc, peerHost, peerPort, true);
359     }
360 
361     @Override
362     protected final SslHandler newHandler(ByteBufAllocator alloc, boolean startTls) {
363         return new SslHandler(newEngine0(alloc, null, -1, false), startTls);
364     }
365 
366     @Override
367     protected final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, boolean startTls) {
368         return new SslHandler(newEngine0(alloc, peerHost, peerPort, false), startTls);
369     }
370 
371     SSLEngine newEngine0(ByteBufAllocator alloc, String peerHost, int peerPort, boolean jdkCompatibilityMode) {
372         return new ReferenceCountedOpenSslEngine(this, alloc, peerHost, peerPort, jdkCompatibilityMode, true);
373     }
374 
375     abstract OpenSslKeyMaterialManager keyMaterialManager();
376 
377     /**
378      * Returns a new server-side {@link SSLEngine} with the current configuration.
379      */
380     @Override
381     public final SSLEngine newEngine(ByteBufAllocator alloc) {
382         return newEngine(alloc, null, -1);
383     }
384 
385     /**
386      * Returns the pointer to the {@code SSL_CTX} object for this {@link ReferenceCountedOpenSslContext}.
387      * Be aware that it is freed as soon as the {@link #finalize()}  method is called.
388      * At this point {@code 0} will be returned.
389      *
390      * @deprecated this method is considered unsafe as the returned pointer may be released later. Dont use it!
391      */
392     @Deprecated
393     public final long context() {
394         Lock readerLock = ctxLock.readLock();
395         readerLock.lock();
396         try {
397             return ctx;
398         } finally {
399             readerLock.unlock();
400         }
401     }
402 
403     /**
404      * Returns the stats of this context.
405      *
406      * @deprecated use {@link #sessionContext#stats()}
407      */
408     @Deprecated
409     public final OpenSslSessionStats stats() {
410         return sessionContext().stats();
411     }
412 
413     /**
414      * {@deprecated Renegotiation is not supported}
415      * Specify if remote initiated renegotiation is supported or not. If not supported and the remote side tries
416      * to initiate a renegotiation a {@link SSLHandshakeException} will be thrown during decoding.
417      */
418     @Deprecated
419     public void setRejectRemoteInitiatedRenegotiation(boolean rejectRemoteInitiatedRenegotiation) {
420         if (!rejectRemoteInitiatedRenegotiation) {
421             throw new UnsupportedOperationException("Renegotiation is not supported");
422         }
423     }
424 
425     /**
426      * {@deprecated Renegotiation is not supported}
427      * @return {@code true} because renegotiation is not supported.
428      */
429     @Deprecated
430     public boolean getRejectRemoteInitiatedRenegotiation() {
431         return true;
432     }
433 
434     /**
435      * Set the size of the buffer used by the BIO for non-application based writes
436      * (e.g. handshake, renegotiation, etc...).
437      */
438     public void setBioNonApplicationBufferSize(int bioNonApplicationBufferSize) {
439         this.bioNonApplicationBufferSize =
440                 checkPositiveOrZero(bioNonApplicationBufferSize, "bioNonApplicationBufferSize");
441     }
442 
443     /**
444      * Returns the size of the buffer used by the BIO for non-application based writes
445      */
446     public int getBioNonApplicationBufferSize() {
447         return bioNonApplicationBufferSize;
448     }
449 
450     /**
451      * Sets the SSL session ticket keys of this context.
452      *
453      * @deprecated use {@link OpenSslSessionContext#setTicketKeys(byte[])}
454      */
455     @Deprecated
456     public final void setTicketKeys(byte[] keys) {
457         sessionContext().setTicketKeys(keys);
458     }
459 
460     @Override
461     public abstract OpenSslSessionContext sessionContext();
462 
463     /**
464      * Returns the pointer to the {@code SSL_CTX} object for this {@link ReferenceCountedOpenSslContext}.
465      * Be aware that it is freed as soon as the {@link #release()} method is called.
466      * At this point {@code 0} will be returned.
467      *
468      * @deprecated this method is considered unsafe as the returned pointer may be released later. Dont use it!
469      */
470     @Deprecated
471     public final long sslCtxPointer() {
472         Lock readerLock = ctxLock.readLock();
473         readerLock.lock();
474         try {
475             return ctx;
476         } finally {
477             readerLock.unlock();
478         }
479     }
480 
481     // IMPORTANT: This method must only be called from either the constructor or the finalizer as a user MUST never
482     //            get access to an OpenSslSessionContext after this method was called to prevent the user from
483     //            producing a segfault.
484     private void destroy() {
485         Lock writerLock = ctxLock.writeLock();
486         writerLock.lock();
487         try {
488             if (ctx != 0) {
489                 if (enableOcsp) {
490                     SSLContext.disableOcsp(ctx);
491                 }
492 
493                 SSLContext.free(ctx);
494                 ctx = 0;
495             }
496         } finally {
497             writerLock.unlock();
498         }
499     }
500 
501     protected static X509Certificate[] certificates(byte[][] chain) {
502         X509Certificate[] peerCerts = new X509Certificate[chain.length];
503         for (int i = 0; i < peerCerts.length; i++) {
504             peerCerts[i] = new OpenSslX509Certificate(chain[i]);
505         }
506         return peerCerts;
507     }
508 
509     protected static X509TrustManager chooseTrustManager(TrustManager[] managers) {
510         for (TrustManager m : managers) {
511             if (m instanceof X509TrustManager) {
512                 return (X509TrustManager) m;
513             }
514         }
515         throw new IllegalStateException("no X509TrustManager found");
516     }
517 
518     protected static X509KeyManager chooseX509KeyManager(KeyManager[] kms) {
519         for (KeyManager km : kms) {
520             if (km instanceof X509KeyManager) {
521                 return (X509KeyManager) km;
522             }
523         }
524         throw new IllegalStateException("no X509KeyManager found");
525     }
526 
527     /**
528      * Translate a {@link ApplicationProtocolConfig} object to a
529      * {@link OpenSslApplicationProtocolNegotiator} object.
530      *
531      * @param config The configuration which defines the translation
532      * @return The results of the translation
533      */
534     @SuppressWarnings("deprecation")
535     static OpenSslApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config) {
536         if (config == null) {
537             return NONE_PROTOCOL_NEGOTIATOR;
538         }
539 
540         switch (config.protocol()) {
541             case NONE:
542                 return NONE_PROTOCOL_NEGOTIATOR;
543             case ALPN:
544             case NPN:
545             case NPN_AND_ALPN:
546                 switch (config.selectedListenerFailureBehavior()) {
547                     case CHOOSE_MY_LAST_PROTOCOL:
548                     case ACCEPT:
549                         switch (config.selectorFailureBehavior()) {
550                             case CHOOSE_MY_LAST_PROTOCOL:
551                             case NO_ADVERTISE:
552                                 return new OpenSslDefaultApplicationProtocolNegotiator(
553                                         config);
554                             default:
555                                 throw new UnsupportedOperationException(
556                                         new StringBuilder("OpenSSL provider does not support ")
557                                                 .append(config.selectorFailureBehavior())
558                                                 .append(" behavior").toString());
559                         }
560                     default:
561                         throw new UnsupportedOperationException(
562                                 new StringBuilder("OpenSSL provider does not support ")
563                                         .append(config.selectedListenerFailureBehavior())
564                                         .append(" behavior").toString());
565                 }
566             default:
567                 throw new Error();
568         }
569     }
570 
571     static boolean useExtendedTrustManager(X509TrustManager trustManager) {
572         return PlatformDependent.javaVersion() >= 7 && trustManager instanceof X509ExtendedTrustManager;
573     }
574 
575     static boolean useExtendedKeyManager(X509KeyManager keyManager) {
576         return PlatformDependent.javaVersion() >= 7 && keyManager instanceof X509ExtendedKeyManager;
577     }
578 
579     @Override
580     public final int refCnt() {
581         return refCnt.refCnt();
582     }
583 
584     @Override
585     public final ReferenceCounted retain() {
586         refCnt.retain();
587         return this;
588     }
589 
590     @Override
591     public final ReferenceCounted retain(int increment) {
592         refCnt.retain(increment);
593         return this;
594     }
595 
596     @Override
597     public final ReferenceCounted touch() {
598         refCnt.touch();
599         return this;
600     }
601 
602     @Override
603     public final ReferenceCounted touch(Object hint) {
604         refCnt.touch(hint);
605         return this;
606     }
607 
608     @Override
609     public final boolean release() {
610         return refCnt.release();
611     }
612 
613     @Override
614     public final boolean release(int decrement) {
615         return refCnt.release(decrement);
616     }
617 
618     abstract static class AbstractCertificateVerifier extends CertificateVerifier {
619         private final OpenSslEngineMap engineMap;
620 
621         AbstractCertificateVerifier(OpenSslEngineMap engineMap) {
622             this.engineMap = engineMap;
623         }
624 
625         @Override
626         public final int verify(long ssl, byte[][] chain, String auth) {
627             X509Certificate[] peerCerts = certificates(chain);
628             final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
629             try {
630                 verify(engine, peerCerts, auth);
631                 return CertificateVerifier.X509_V_OK;
632             } catch (Throwable cause) {
633                 logger.debug("verification of certificate failed", cause);
634                 SSLHandshakeException e = new SSLHandshakeException("General OpenSslEngine problem");
635                 e.initCause(cause);
636                 engine.handshakeException = e;
637 
638                 // Try to extract the correct error code that should be used.
639                 if (cause instanceof OpenSslCertificateException) {
640                     // This will never return a negative error code as its validated when constructing the
641                     // OpenSslCertificateException.
642                     return ((OpenSslCertificateException) cause).errorCode();
643                 }
644                 if (cause instanceof CertificateExpiredException) {
645                     return CertificateVerifier.X509_V_ERR_CERT_HAS_EXPIRED;
646                 }
647                 if (cause instanceof CertificateNotYetValidException) {
648                     return CertificateVerifier.X509_V_ERR_CERT_NOT_YET_VALID;
649                 }
650                 if (PlatformDependent.javaVersion() >= 7) {
651                     if (cause instanceof CertificateRevokedException) {
652                         return CertificateVerifier.X509_V_ERR_CERT_REVOKED;
653                     }
654 
655                     // The X509TrustManagerImpl uses a Validator which wraps a CertPathValidatorException into
656                     // an CertificateException. So we need to handle the wrapped CertPathValidatorException to be
657                     // able to send the correct alert.
658                     Throwable wrapped = cause.getCause();
659                     while (wrapped != null) {
660                         if (wrapped instanceof CertPathValidatorException) {
661                             CertPathValidatorException ex = (CertPathValidatorException) wrapped;
662                             CertPathValidatorException.Reason reason = ex.getReason();
663                             if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
664                                 return CertificateVerifier.X509_V_ERR_CERT_HAS_EXPIRED;
665                             }
666                             if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
667                                 return CertificateVerifier.X509_V_ERR_CERT_NOT_YET_VALID;
668                             }
669                             if (reason == CertPathValidatorException.BasicReason.REVOKED) {
670                                 return CertificateVerifier.X509_V_ERR_CERT_REVOKED;
671                             }
672                         }
673                         wrapped = wrapped.getCause();
674                     }
675                 }
676 
677                 // Could not detect a specific error code to use, so fallback to a default code.
678                 return CertificateVerifier.X509_V_ERR_UNSPECIFIED;
679             }
680         }
681 
682         abstract void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts,
683                              String auth) throws Exception;
684     }
685 
686     private static final class DefaultOpenSslEngineMap implements OpenSslEngineMap {
687         private final Map<Long, ReferenceCountedOpenSslEngine> engines = PlatformDependent.newConcurrentHashMap();
688 
689         @Override
690         public ReferenceCountedOpenSslEngine remove(long ssl) {
691             return engines.remove(ssl);
692         }
693 
694         @Override
695         public void add(ReferenceCountedOpenSslEngine engine) {
696             engines.put(engine.sslPointer(), engine);
697         }
698 
699         @Override
700         public ReferenceCountedOpenSslEngine get(long ssl) {
701             return engines.get(ssl);
702         }
703     }
704 
705     static void setKeyMaterial(long ctx, X509Certificate[] keyCertChain, PrivateKey key, String keyPassword)
706             throws SSLException {
707          /* Load the certificate file and private key. */
708         long keyBio = 0;
709         long keyCertChainBio = 0;
710         long keyCertChainBio2 = 0;
711         PemEncoded encoded = null;
712         try {
713             // Only encode one time
714             encoded = PemX509Certificate.toPEM(ByteBufAllocator.DEFAULT, true, keyCertChain);
715             keyCertChainBio = toBIO(ByteBufAllocator.DEFAULT, encoded.retain());
716             keyCertChainBio2 = toBIO(ByteBufAllocator.DEFAULT, encoded.retain());
717 
718             if (key != null) {
719                 keyBio = toBIO(key);
720             }
721 
722             SSLContext.setCertificateBio(
723                     ctx, keyCertChainBio, keyBio,
724                     keyPassword == null ? StringUtil.EMPTY_STRING : keyPassword);
725             // We may have more then one cert in the chain so add all of them now.
726             SSLContext.setCertificateChainBio(ctx, keyCertChainBio2, true);
727         } catch (SSLException e) {
728             throw e;
729         } catch (Exception e) {
730             throw new SSLException("failed to set certificate and key", e);
731         } finally {
732             freeBio(keyBio);
733             freeBio(keyCertChainBio);
734             freeBio(keyCertChainBio2);
735             if (encoded != null) {
736                 encoded.release();
737             }
738         }
739     }
740 
741     static void freeBio(long bio) {
742         if (bio != 0) {
743             SSL.freeBIO(bio);
744         }
745     }
746 
747     /**
748      * Return the pointer to a <a href="https://www.openssl.org/docs/crypto/BIO_get_mem_ptr.html">in-memory BIO</a>
749      * or {@code 0} if the {@code key} is {@code null}. The BIO contains the content of the {@code key}.
750      */
751     static long toBIO(PrivateKey key) throws Exception {
752         if (key == null) {
753             return 0;
754         }
755 
756         ByteBufAllocator allocator = ByteBufAllocator.DEFAULT;
757         PemEncoded pem = PemPrivateKey.toPEM(allocator, true, key);
758         try {
759             return toBIO(allocator, pem.retain());
760         } finally {
761             pem.release();
762         }
763     }
764 
765     /**
766      * Return the pointer to a <a href="https://www.openssl.org/docs/crypto/BIO_get_mem_ptr.html">in-memory BIO</a>
767      * or {@code 0} if the {@code certChain} is {@code null}. The BIO contains the content of the {@code certChain}.
768      */
769     static long toBIO(X509Certificate... certChain) throws Exception {
770         if (certChain == null) {
771             return 0;
772         }
773 
774         if (certChain.length == 0) {
775             throw new IllegalArgumentException("certChain can't be empty");
776         }
777 
778         ByteBufAllocator allocator = ByteBufAllocator.DEFAULT;
779         PemEncoded pem = PemX509Certificate.toPEM(allocator, true, certChain);
780         try {
781             return toBIO(allocator, pem.retain());
782         } finally {
783             pem.release();
784         }
785     }
786 
787     static long toBIO(ByteBufAllocator allocator, PemEncoded pem) throws Exception {
788         try {
789             // We can turn direct buffers straight into BIOs. No need to
790             // make a yet another copy.
791             ByteBuf content = pem.content();
792 
793             if (content.isDirect()) {
794                 return newBIO(content.retainedSlice());
795             }
796 
797             ByteBuf buffer = allocator.directBuffer(content.readableBytes());
798             try {
799                 buffer.writeBytes(content, content.readerIndex(), content.readableBytes());
800                 return newBIO(buffer.retainedSlice());
801             } finally {
802                 try {
803                     // If the contents of the ByteBuf is sensitive (e.g. a PrivateKey) we
804                     // need to zero out the bytes of the copy before we're releasing it.
805                     if (pem.isSensitive()) {
806                         SslUtils.zeroout(buffer);
807                     }
808                 } finally {
809                     buffer.release();
810                 }
811             }
812         } finally {
813             pem.release();
814         }
815     }
816 
817     private static long newBIO(ByteBuf buffer) throws Exception {
818         try {
819             long bio = SSL.newMemBIO();
820             int readable = buffer.readableBytes();
821             if (SSL.bioWrite(bio, OpenSsl.memoryAddress(buffer) + buffer.readerIndex(), readable) != readable) {
822                 SSL.freeBIO(bio);
823                 throw new IllegalStateException("Could not write data to memory BIO");
824             }
825             return bio;
826         } finally {
827             buffer.release();
828         }
829     }
830 }