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    *   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;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.handler.ssl.util.LazyX509Certificate;
21  import io.netty.internal.tcnative.AsyncSSLPrivateKeyMethod;
22  import io.netty.internal.tcnative.CertificateCompressionAlgo;
23  import io.netty.internal.tcnative.CertificateVerifier;
24  import io.netty.internal.tcnative.ResultCallback;
25  import io.netty.internal.tcnative.SSL;
26  import io.netty.internal.tcnative.SSLContext;
27  import io.netty.internal.tcnative.SSLPrivateKeyMethod;
28  import io.netty.util.AbstractReferenceCounted;
29  import io.netty.util.ReferenceCounted;
30  import io.netty.util.ResourceLeakDetector;
31  import io.netty.util.ResourceLeakDetectorFactory;
32  import io.netty.util.ResourceLeakTracker;
33  import io.netty.util.concurrent.Future;
34  import io.netty.util.concurrent.FutureListener;
35  import io.netty.util.concurrent.ImmediateExecutor;
36  import io.netty.util.internal.EmptyArrays;
37  import io.netty.util.internal.PlatformDependent;
38  import io.netty.util.internal.StringUtil;
39  import io.netty.util.internal.SuppressJava6Requirement;
40  import io.netty.util.internal.SystemPropertyUtil;
41  import io.netty.util.internal.UnstableApi;
42  import io.netty.util.internal.logging.InternalLogger;
43  import io.netty.util.internal.logging.InternalLoggerFactory;
44  
45  import java.security.PrivateKey;
46  import java.security.SignatureException;
47  import java.security.cert.CertPathValidatorException;
48  import java.security.cert.Certificate;
49  import java.security.cert.CertificateException;
50  import java.security.cert.CertificateExpiredException;
51  import java.security.cert.CertificateNotYetValidException;
52  import java.security.cert.CertificateRevokedException;
53  import java.security.cert.X509Certificate;
54  import java.util.ArrayList;
55  import java.util.Arrays;
56  import java.util.Collections;
57  import java.util.LinkedHashSet;
58  import java.util.List;
59  import java.util.Map;
60  import java.util.Set;
61  import java.util.concurrent.Executor;
62  import java.util.concurrent.locks.Lock;
63  import java.util.concurrent.locks.ReadWriteLock;
64  import java.util.concurrent.locks.ReentrantReadWriteLock;
65  
66  import javax.net.ssl.KeyManager;
67  import javax.net.ssl.KeyManagerFactory;
68  import javax.net.ssl.SSLEngine;
69  import javax.net.ssl.SSLException;
70  import javax.net.ssl.SSLHandshakeException;
71  import javax.net.ssl.TrustManager;
72  import javax.net.ssl.X509ExtendedTrustManager;
73  import javax.net.ssl.X509KeyManager;
74  import javax.net.ssl.X509TrustManager;
75  
76  import static io.netty.handler.ssl.OpenSsl.DEFAULT_CIPHERS;
77  import static io.netty.handler.ssl.OpenSsl.availableJavaCipherSuites;
78  import static io.netty.util.internal.ObjectUtil.checkNotNull;
79  import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
80  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
81  
82  /**
83   * An implementation of {@link SslContext} which works with libraries that support the
84   * <a href="https://www.openssl.org/">OpenSsl</a> C library API.
85   * <p>Instances of this class must be {@link #release() released} or else native memory will leak!
86   *
87   * <p>Instances of this class <strong>must not</strong> be released before any {@link ReferenceCountedOpenSslEngine}
88   * which depends upon the instance of this class is released. Otherwise if any method of
89   * {@link ReferenceCountedOpenSslEngine} is called which uses this class's JNI resources the JVM may crash.
90   */
91  public abstract class ReferenceCountedOpenSslContext extends SslContext implements ReferenceCounted {
92      private static final InternalLogger logger =
93              InternalLoggerFactory.getInstance(ReferenceCountedOpenSslContext.class);
94  
95      private static final int DEFAULT_BIO_NON_APPLICATION_BUFFER_SIZE = Math.max(1,
96              SystemPropertyUtil.getInt("io.netty.handler.ssl.openssl.bioNonApplicationBufferSize",
97                      2048));
98      private static final int MIN_MAX_CERTIFICATE_LIST_BYTES = 16 * 1024;
99      // Let's use tasks by default but still allow the user to disable it via system property just in case.
100     static final boolean USE_TASKS =
101             SystemPropertyUtil.getBoolean("io.netty.handler.ssl.openssl.useTasks", true);
102     private static final Integer DH_KEY_LENGTH;
103     private static final ResourceLeakDetector<ReferenceCountedOpenSslContext> leakDetector =
104             ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ReferenceCountedOpenSslContext.class);
105 
106     // TODO: Maybe make configurable ?
107     protected static final int VERIFY_DEPTH = 10;
108 
109     static final boolean CLIENT_ENABLE_SESSION_TICKET =
110             SystemPropertyUtil.getBoolean("jdk.tls.client.enableSessionTicketExtension", false);
111 
112     static final boolean CLIENT_ENABLE_SESSION_TICKET_TLSV13 =
113             SystemPropertyUtil.getBoolean("jdk.tls.client.enableSessionTicketExtension", true);
114 
115     static final boolean SERVER_ENABLE_SESSION_TICKET =
116             SystemPropertyUtil.getBoolean("jdk.tls.server.enableSessionTicketExtension", false);
117 
118     static final boolean SERVER_ENABLE_SESSION_TICKET_TLSV13 =
119             SystemPropertyUtil.getBoolean("jdk.tls.server.enableSessionTicketExtension", true);
120 
121     static final boolean SERVER_ENABLE_SESSION_CACHE =
122             SystemPropertyUtil.getBoolean("io.netty.handler.ssl.openssl.sessionCacheServer", true);
123     static final boolean CLIENT_ENABLE_SESSION_CACHE =
124             SystemPropertyUtil.getBoolean("io.netty.handler.ssl.openssl.sessionCacheClient", true);
125 
126     /**
127      * The OpenSSL SSL_CTX object.
128      *
129      * <strong>{@link #ctxLock} must be hold while using ctx!</strong>
130      */
131     protected long ctx;
132     private final List<String> unmodifiableCiphers;
133     private final OpenSslApplicationProtocolNegotiator apn;
134     private final int mode;
135 
136     // Reference Counting
137     private final ResourceLeakTracker<ReferenceCountedOpenSslContext> leak;
138     private final AbstractReferenceCounted refCnt = new AbstractReferenceCounted() {
139         @Override
140         public ReferenceCounted touch(Object hint) {
141             if (leak != null) {
142                 leak.record(hint);
143             }
144 
145             return ReferenceCountedOpenSslContext.this;
146         }
147 
148         @Override
149         protected void deallocate() {
150             try {
151                 destroy();
152             } finally {
153                 if (leak != null) {
154                     boolean closed = leak.close(ReferenceCountedOpenSslContext.this);
155                     assert closed;
156                 }
157             }
158         }
159     };
160 
161     final Certificate[] keyCertChain;
162     final ClientAuth clientAuth;
163     final String[] protocols;
164     final String endpointIdentificationAlgorithm;
165     final boolean hasTLSv13Cipher;
166     final boolean hasTmpDhKeys;
167 
168     final boolean enableOcsp;
169     final OpenSslEngineMap engines = new OpenSslEngineMap();
170     final ReadWriteLock ctxLock = new ReentrantReadWriteLock();
171 
172     private volatile int bioNonApplicationBufferSize = DEFAULT_BIO_NON_APPLICATION_BUFFER_SIZE;
173 
174     @SuppressWarnings("deprecation")
175     static final OpenSslApplicationProtocolNegotiator NONE_PROTOCOL_NEGOTIATOR =
176             new OpenSslApplicationProtocolNegotiator() {
177                 @Override
178                 public ApplicationProtocolConfig.Protocol protocol() {
179                     return ApplicationProtocolConfig.Protocol.NONE;
180                 }
181 
182                 @Override
183                 public List<String> protocols() {
184                     return Collections.emptyList();
185                 }
186 
187                 @Override
188                 public ApplicationProtocolConfig.SelectorFailureBehavior selectorFailureBehavior() {
189                     return ApplicationProtocolConfig.SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL;
190                 }
191 
192                 @Override
193                 public ApplicationProtocolConfig.SelectedListenerFailureBehavior selectedListenerFailureBehavior() {
194                     return ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT;
195                 }
196             };
197 
198     static {
199         Integer dhLen = null;
200 
201         try {
202             String dhKeySize = SystemPropertyUtil.get("jdk.tls.ephemeralDHKeySize");
203             if (dhKeySize != null) {
204                 try {
205                     dhLen = Integer.valueOf(dhKeySize);
206                 } catch (NumberFormatException e) {
207                     logger.debug("ReferenceCountedOpenSslContext supports -Djdk.tls.ephemeralDHKeySize={int}, but got: "
208                             + dhKeySize);
209                 }
210             }
211         } catch (Throwable ignore) {
212             // ignore
213         }
214         DH_KEY_LENGTH = dhLen;
215     }
216 
217     final boolean tlsFalseStart;
218 
219     ReferenceCountedOpenSslContext(Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
220                                    OpenSslApplicationProtocolNegotiator apn, int mode, Certificate[] keyCertChain,
221                                    ClientAuth clientAuth, String[] protocols, boolean startTls,
222                                    String endpointIdentificationAlgorithm, boolean enableOcsp,
223                                    boolean leakDetection, ResumptionController resumptionController,
224                                    Map.Entry<SslContextOption<?>, Object>... ctxOptions)
225             throws SSLException {
226         super(startTls, resumptionController);
227 
228         OpenSsl.ensureAvailability();
229 
230         if (enableOcsp && !OpenSsl.isOcspSupported()) {
231             throw new IllegalStateException("OCSP is not supported.");
232         }
233 
234         if (mode != SSL.SSL_MODE_SERVER && mode != SSL.SSL_MODE_CLIENT) {
235             throw new IllegalArgumentException("mode most be either SSL.SSL_MODE_SERVER or SSL.SSL_MODE_CLIENT");
236         }
237 
238         boolean tlsFalseStart = false;
239         boolean useTasks = USE_TASKS;
240         OpenSslPrivateKeyMethod privateKeyMethod = null;
241         OpenSslAsyncPrivateKeyMethod asyncPrivateKeyMethod = null;
242         OpenSslCertificateCompressionConfig certCompressionConfig = null;
243         Integer maxCertificateList = null;
244         Integer tmpDhKeyLength = null;
245         String[] groups = OpenSsl.NAMED_GROUPS;
246         if (ctxOptions != null) {
247             for (Map.Entry<SslContextOption<?>, Object> ctxOpt : ctxOptions) {
248                 SslContextOption<?> option = ctxOpt.getKey();
249 
250                 if (option == OpenSslContextOption.TLS_FALSE_START) {
251                     tlsFalseStart = (Boolean) ctxOpt.getValue();
252                 } else if (option == OpenSslContextOption.USE_TASKS) {
253                     useTasks = (Boolean) ctxOpt.getValue();
254                 } else if (option == OpenSslContextOption.PRIVATE_KEY_METHOD) {
255                     privateKeyMethod = (OpenSslPrivateKeyMethod) ctxOpt.getValue();
256                 } else if (option == OpenSslContextOption.ASYNC_PRIVATE_KEY_METHOD) {
257                     asyncPrivateKeyMethod = (OpenSslAsyncPrivateKeyMethod) ctxOpt.getValue();
258                 } else if (option == OpenSslContextOption.CERTIFICATE_COMPRESSION_ALGORITHMS) {
259                     certCompressionConfig = (OpenSslCertificateCompressionConfig) ctxOpt.getValue();
260                 } else if (option == OpenSslContextOption.MAX_CERTIFICATE_LIST_BYTES) {
261                     maxCertificateList = (Integer) ctxOpt.getValue();
262                 } else if (option == OpenSslContextOption.TMP_DH_KEYLENGTH) {
263                     tmpDhKeyLength = (Integer) ctxOpt.getValue();
264                 } else if (option == OpenSslContextOption.GROUPS) {
265                     String[] groupsArray = (String[]) ctxOpt.getValue();
266                     Set<String> groupsSet = new LinkedHashSet<String>(groupsArray.length);
267                     for (String group : groupsArray) {
268                         groupsSet.add(GroupsConverter.toOpenSsl(group));
269                     }
270                     groups = groupsSet.toArray(EmptyArrays.EMPTY_STRINGS);
271                 } else {
272                     logger.debug("Skipping unsupported " + SslContextOption.class.getSimpleName()
273                             + ": " + ctxOpt.getKey());
274                 }
275             }
276         }
277         if (privateKeyMethod != null && asyncPrivateKeyMethod != null) {
278             throw new IllegalArgumentException("You can either only use "
279                     + OpenSslAsyncPrivateKeyMethod.class.getSimpleName() + " or "
280                     + OpenSslPrivateKeyMethod.class.getSimpleName());
281         }
282 
283         this.tlsFalseStart = tlsFalseStart;
284 
285         leak = leakDetection ? leakDetector.track(this) : null;
286         this.mode = mode;
287         this.clientAuth = isServer() ? checkNotNull(clientAuth, "clientAuth") : ClientAuth.NONE;
288         this.protocols = protocols == null ? OpenSsl.defaultProtocols(mode == SSL.SSL_MODE_CLIENT) : protocols;
289         this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
290         this.enableOcsp = enableOcsp;
291 
292         this.keyCertChain = keyCertChain == null ? null : keyCertChain.clone();
293 
294         String[] suites = checkNotNull(cipherFilter, "cipherFilter").filterCipherSuites(
295                 ciphers, DEFAULT_CIPHERS, availableJavaCipherSuites());
296         // Filter out duplicates.
297         LinkedHashSet<String> suitesSet = new LinkedHashSet<String>(suites.length);
298         Collections.addAll(suitesSet, suites);
299         unmodifiableCiphers = new ArrayList<String>(suitesSet);
300 
301         this.apn = checkNotNull(apn, "apn");
302 
303         // Create a new SSL_CTX and configure it.
304         boolean success = false;
305         try {
306             boolean tlsv13Supported = OpenSsl.isTlsv13Supported();
307             boolean anyTlsv13Ciphers = false;
308             try {
309                 int protocolOpts = SSL.SSL_PROTOCOL_SSLV3 | SSL.SSL_PROTOCOL_TLSV1 |
310                         SSL.SSL_PROTOCOL_TLSV1_1 | SSL.SSL_PROTOCOL_TLSV1_2;
311                 if (tlsv13Supported) {
312                     protocolOpts |= SSL.SSL_PROTOCOL_TLSV1_3;
313                 }
314                 ctx = SSLContext.make(protocolOpts, mode);
315             } catch (Exception e) {
316                 throw new SSLException("failed to create an SSL_CTX", e);
317             }
318 
319             StringBuilder cipherBuilder = new StringBuilder();
320             StringBuilder cipherTLSv13Builder = new StringBuilder();
321 
322             /* List the ciphers that are permitted to negotiate. */
323             try {
324                 if (unmodifiableCiphers.isEmpty()) {
325                     // Set non TLSv1.3 ciphers.
326                     SSLContext.setCipherSuite(ctx, StringUtil.EMPTY_STRING, false);
327                     if (tlsv13Supported) {
328                         // Set TLSv1.3 ciphers.
329                         SSLContext.setCipherSuite(ctx, StringUtil.EMPTY_STRING, true);
330                     }
331                 } else {
332                     CipherSuiteConverter.convertToCipherStrings(
333                             unmodifiableCiphers, cipherBuilder, cipherTLSv13Builder,
334                             OpenSsl.isBoringSSL());
335 
336                     // Set non TLSv1.3 ciphers.
337                     SSLContext.setCipherSuite(ctx, cipherBuilder.toString(), false);
338                     if (tlsv13Supported) {
339                         // Set TLSv1.3 ciphers.
340                         String tlsv13Ciphers = OpenSsl.checkTls13Ciphers(logger, cipherTLSv13Builder.toString());
341                         SSLContext.setCipherSuite(ctx, tlsv13Ciphers, true);
342                         if (!tlsv13Ciphers.isEmpty()) {
343                             anyTlsv13Ciphers = true;
344                         }
345                     }
346                 }
347             } catch (SSLException e) {
348                 throw e;
349             } catch (Exception e) {
350                 throw new SSLException("failed to set cipher suite: " + unmodifiableCiphers, e);
351             }
352 
353             int options = SSLContext.getOptions(ctx) |
354                     SSL.SSL_OP_NO_SSLv2 |
355                     SSL.SSL_OP_NO_SSLv3 |
356                     // Disable TLSv1 and TLSv1.1 by default as these are not considered secure anymore
357                     // and the JDK is doing the same:
358                     // https://www.oracle.com/java/technologies/javase/8u291-relnotes.html
359                     SSL.SSL_OP_NO_TLSv1 |
360                     SSL.SSL_OP_NO_TLSv1_1 |
361 
362                     SSL.SSL_OP_CIPHER_SERVER_PREFERENCE |
363 
364                     // We do not support compression at the moment so we should explicitly disable it.
365                     SSL.SSL_OP_NO_COMPRESSION |
366 
367                     // Disable ticket support by default to be more inline with SSLEngineImpl of the JDK.
368                     // This also let SSLSession.getId() work the same way for the JDK implementation and the
369                     // OpenSSLEngine. If tickets are supported SSLSession.getId() will only return an ID on the
370                     // server-side if it could make use of tickets.
371                     SSL.SSL_OP_NO_TICKET;
372 
373             if (cipherBuilder.length() == 0) {
374                 // No ciphers that are compatible with SSLv2 / SSLv3 / TLSv1 / TLSv1.1 / TLSv1.2
375                 options |= SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_NO_SSLv3 | SSL.SSL_OP_NO_TLSv1
376                         | SSL.SSL_OP_NO_TLSv1_1 | SSL.SSL_OP_NO_TLSv1_2;
377             }
378 
379             if (!tlsv13Supported) {
380                 // Explicit disable TLSv1.3
381                 // See:
382                 //  - https://github.com/netty/netty/issues/12968
383                 options |= SSL.SSL_OP_NO_TLSv1_3;
384             }
385 
386             hasTLSv13Cipher = anyTlsv13Ciphers;
387             SSLContext.setOptions(ctx, options);
388 
389             // We need to enable SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER as the memory address may change between
390             // calling OpenSSLEngine.wrap(...).
391             // See https://github.com/netty/netty-tcnative/issues/100
392             SSLContext.setMode(ctx, SSLContext.getMode(ctx) | SSL.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
393 
394             if (tmpDhKeyLength != null) {
395                 SSLContext.setTmpDHLength(ctx, tmpDhKeyLength);
396                 hasTmpDhKeys = true;
397             } else if (DH_KEY_LENGTH != null) {
398                 SSLContext.setTmpDHLength(ctx, DH_KEY_LENGTH);
399                 hasTmpDhKeys = true;
400             } else {
401                 hasTmpDhKeys = false;
402             }
403 
404             List<String> nextProtoList = apn.protocols();
405             /* Set next protocols for next protocol negotiation extension, if specified */
406             if (!nextProtoList.isEmpty()) {
407                 String[] appProtocols = nextProtoList.toArray(EmptyArrays.EMPTY_STRINGS);
408                 int selectorBehavior = opensslSelectorFailureBehavior(apn.selectorFailureBehavior());
409 
410                 switch (apn.protocol()) {
411                     case NPN:
412                         SSLContext.setNpnProtos(ctx, appProtocols, selectorBehavior);
413                         break;
414                     case ALPN:
415                         SSLContext.setAlpnProtos(ctx, appProtocols, selectorBehavior);
416                         break;
417                     case NPN_AND_ALPN:
418                         SSLContext.setNpnProtos(ctx, appProtocols, selectorBehavior);
419                         SSLContext.setAlpnProtos(ctx, appProtocols, selectorBehavior);
420                         break;
421                     default:
422                         throw new Error();
423                 }
424             }
425 
426             if (enableOcsp) {
427                 SSLContext.enableOcsp(ctx, isClient());
428             }
429 
430             SSLContext.setUseTasks(ctx, useTasks);
431             if (privateKeyMethod != null) {
432                 SSLContext.setPrivateKeyMethod(ctx, new PrivateKeyMethod(engines, privateKeyMethod));
433             }
434             if (asyncPrivateKeyMethod != null) {
435                 SSLContext.setPrivateKeyMethod(ctx, new AsyncPrivateKeyMethod(engines, asyncPrivateKeyMethod));
436             }
437             if (certCompressionConfig != null) {
438                 for (OpenSslCertificateCompressionConfig.AlgorithmConfig configPair : certCompressionConfig) {
439                     final CertificateCompressionAlgo algo = new CompressionAlgorithm(engines, configPair.algorithm());
440                     switch (configPair.mode()) {
441                         case Decompress:
442                             SSLContext.addCertificateCompressionAlgorithm(
443                                     ctx, SSL.SSL_CERT_COMPRESSION_DIRECTION_DECOMPRESS, algo);
444                             break;
445                         case Compress:
446                             SSLContext.addCertificateCompressionAlgorithm(
447                                     ctx, SSL.SSL_CERT_COMPRESSION_DIRECTION_COMPRESS, algo);
448                             break;
449                         case Both:
450                             SSLContext.addCertificateCompressionAlgorithm(
451                                     ctx, SSL.SSL_CERT_COMPRESSION_DIRECTION_BOTH, algo);
452                             break;
453                         default:
454                             throw new IllegalStateException();
455                     }
456                 }
457             }
458             if (maxCertificateList != null) {
459                 SSLContext.setMaxCertList(ctx, maxCertificateListBytes(maxCertificateList));
460             }
461 
462             // Set the curves / groups if anything is configured.
463             if (groups.length > 0 && !SSLContext.setCurvesList(ctx, groups)) {
464                 String msg = "failed to set curves / groups suite: " + Arrays.toString(groups);
465                 int err = SSL.getLastErrorNumber();
466                 if (err != 0) {
467                     // We have some more details about why the operations failed, include these into the message.
468                     msg += ". " + SSL.getErrorString(err);
469                 }
470                 throw new SSLException(msg);
471             }
472             success = true;
473         } finally {
474             if (!success) {
475                 release();
476             }
477         }
478     }
479 
480     private static int opensslSelectorFailureBehavior(ApplicationProtocolConfig.SelectorFailureBehavior behavior) {
481         switch (behavior) {
482             case NO_ADVERTISE:
483                 return SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE;
484             case CHOOSE_MY_LAST_PROTOCOL:
485                 return SSL.SSL_SELECTOR_FAILURE_CHOOSE_MY_LAST_PROTOCOL;
486             default:
487                 throw new Error("Unexpected behavior: " + behavior);
488         }
489     }
490 
491     static int maxCertificateListBytes(int maxCertificateListBytes) {
492         return maxCertificateListBytes > 0 ?
493                 Math.max(maxCertificateListBytes, MIN_MAX_CERTIFICATE_LIST_BYTES) : maxCertificateListBytes;
494     }
495 
496     @Override
497     public final List<String> cipherSuites() {
498         return unmodifiableCiphers;
499     }
500 
501     @Override
502     public ApplicationProtocolNegotiator applicationProtocolNegotiator() {
503         return apn;
504     }
505 
506     @Override
507     public final boolean isClient() {
508         return mode == SSL.SSL_MODE_CLIENT;
509     }
510 
511     @Override
512     public final SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
513         return newEngine0(alloc, peerHost, peerPort, true);
514     }
515 
516     @Override
517     protected final SslHandler newHandler(ByteBufAllocator alloc, boolean startTls) {
518         return new SslHandler(newEngine0(alloc, null, -1, false), startTls, ImmediateExecutor.INSTANCE,
519                 resumptionController);
520     }
521 
522     @Override
523     protected final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, boolean startTls) {
524         return new SslHandler(newEngine0(alloc, peerHost, peerPort, false), startTls, ImmediateExecutor.INSTANCE,
525                 resumptionController);
526     }
527 
528     @Override
529     protected SslHandler newHandler(ByteBufAllocator alloc, boolean startTls, Executor executor) {
530         return new SslHandler(newEngine0(alloc, null, -1, false), startTls, executor, resumptionController);
531     }
532 
533     @Override
534     protected SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort,
535                                     boolean startTls, Executor executor) {
536         return new SslHandler(newEngine0(alloc, peerHost, peerPort, false), startTls, executor, resumptionController);
537     }
538 
539     SSLEngine newEngine0(ByteBufAllocator alloc, String peerHost, int peerPort, boolean jdkCompatibilityMode) {
540         return new ReferenceCountedOpenSslEngine(this, alloc, peerHost, peerPort, jdkCompatibilityMode, true,
541                 endpointIdentificationAlgorithm);
542     }
543 
544     /**
545      * Returns a new server-side {@link SSLEngine} with the current configuration.
546      */
547     @Override
548     public final SSLEngine newEngine(ByteBufAllocator alloc) {
549         return newEngine(alloc, null, -1);
550     }
551 
552     /**
553      * Returns the pointer to the {@code SSL_CTX} object for this {@link ReferenceCountedOpenSslContext}.
554      * Be aware that it is freed as soon as the {@link #finalize()}  method is called.
555      * At this point {@code 0} will be returned.
556      *
557      * @deprecated this method is considered unsafe as the returned pointer may be released later. Dont use it!
558      */
559     @Deprecated
560     public final long context() {
561         return sslCtxPointer();
562     }
563 
564     /**
565      * Returns the stats of this context.
566      *
567      * @deprecated use {@link #sessionContext#stats()}
568      */
569     @Deprecated
570     public final OpenSslSessionStats stats() {
571         return sessionContext().stats();
572     }
573 
574     /**
575      * {@deprecated Renegotiation is not supported}
576      * Specify if remote initiated renegotiation is supported or not. If not supported and the remote side tries
577      * to initiate a renegotiation a {@link SSLHandshakeException} will be thrown during decoding.
578      */
579     @Deprecated
580     public void setRejectRemoteInitiatedRenegotiation(boolean rejectRemoteInitiatedRenegotiation) {
581         if (!rejectRemoteInitiatedRenegotiation) {
582             throw new UnsupportedOperationException("Renegotiation is not supported");
583         }
584     }
585 
586     /**
587      * {@deprecated Renegotiation is not supported}
588      * @return {@code true} because renegotiation is not supported.
589      */
590     @Deprecated
591     public boolean getRejectRemoteInitiatedRenegotiation() {
592         return true;
593     }
594 
595     /**
596      * Set the size of the buffer used by the BIO for non-application based writes
597      * (e.g. handshake, renegotiation, etc...).
598      */
599     public void setBioNonApplicationBufferSize(int bioNonApplicationBufferSize) {
600         this.bioNonApplicationBufferSize =
601                 checkPositiveOrZero(bioNonApplicationBufferSize, "bioNonApplicationBufferSize");
602     }
603 
604     /**
605      * Returns the size of the buffer used by the BIO for non-application based writes
606      */
607     public int getBioNonApplicationBufferSize() {
608         return bioNonApplicationBufferSize;
609     }
610 
611     /**
612      * Sets the SSL session ticket keys of this context.
613      *
614      * @deprecated use {@link OpenSslSessionContext#setTicketKeys(byte[])}
615      */
616     @Deprecated
617     public final void setTicketKeys(byte[] keys) {
618         sessionContext().setTicketKeys(keys);
619     }
620 
621     @Override
622     public abstract OpenSslSessionContext sessionContext();
623 
624     /**
625      * Returns the pointer to the {@code SSL_CTX} object for this {@link ReferenceCountedOpenSslContext}.
626      * Be aware that it is freed as soon as the {@link #release()} method is called.
627      * At this point {@code 0} will be returned.
628      *
629      * @deprecated this method is considered unsafe as the returned pointer may be released later. Dont use it!
630      */
631     @Deprecated
632     public final long sslCtxPointer() {
633         Lock readerLock = ctxLock.readLock();
634         readerLock.lock();
635         try {
636             return SSLContext.getSslCtx(ctx);
637         } finally {
638             readerLock.unlock();
639         }
640     }
641 
642     /**
643      * Set the {@link OpenSslPrivateKeyMethod} to use. This allows to offload private-key operations
644      * if needed.
645      *
646      * This method is currently only supported when {@code BoringSSL} is used.
647      *
648      * @param        method method to use.
649      * @deprecated   use {@link SslContextBuilder#option(SslContextOption, Object)} with
650      *              {@link OpenSslContextOption#PRIVATE_KEY_METHOD}.
651      */
652     @Deprecated
653     @UnstableApi
654     public final void setPrivateKeyMethod(OpenSslPrivateKeyMethod method) {
655         checkNotNull(method, "method");
656         Lock writerLock = ctxLock.writeLock();
657         writerLock.lock();
658         try {
659             SSLContext.setPrivateKeyMethod(ctx, new PrivateKeyMethod(engines, method));
660         } finally {
661             writerLock.unlock();
662         }
663     }
664 
665     /**
666      * @deprecated   use {@link SslContextBuilder#option(SslContextOption, Object)} with
667      *              {@link OpenSslContextOption#USE_TASKS}.
668      */
669     @Deprecated
670     public final void setUseTasks(boolean useTasks) {
671         Lock writerLock = ctxLock.writeLock();
672         writerLock.lock();
673         try {
674             SSLContext.setUseTasks(ctx, useTasks);
675         } finally {
676             writerLock.unlock();
677         }
678     }
679 
680     // IMPORTANT: This method must only be called from either the constructor or the finalizer as a user MUST never
681     //            get access to an OpenSslSessionContext after this method was called to prevent the user from
682     //            producing a segfault.
683     private void destroy() {
684         Lock writerLock = ctxLock.writeLock();
685         writerLock.lock();
686         try {
687             if (ctx != 0) {
688                 if (enableOcsp) {
689                     SSLContext.disableOcsp(ctx);
690                 }
691 
692                 SSLContext.free(ctx);
693                 ctx = 0;
694 
695                 OpenSslSessionContext context = sessionContext();
696                 if (context != null) {
697                     context.destroy();
698                 }
699             }
700         } finally {
701             writerLock.unlock();
702         }
703     }
704 
705     protected static X509Certificate[] certificates(byte[][] chain) {
706         X509Certificate[] peerCerts = new X509Certificate[chain.length];
707         for (int i = 0; i < peerCerts.length; i++) {
708             peerCerts[i] = new LazyX509Certificate(chain[i]);
709         }
710         return peerCerts;
711     }
712 
713     /**
714      * @deprecated This method is kept for API backwards compatibility.
715      */
716     @Deprecated
717     protected static X509TrustManager chooseTrustManager(TrustManager[] managers) {
718         return chooseTrustManager(managers, null);
719     }
720 
721     static X509TrustManager chooseTrustManager(TrustManager[] managers,
722                                                          ResumptionController resumptionController) {
723         for (TrustManager m : managers) {
724             if (m instanceof X509TrustManager) {
725                 X509TrustManager tm = (X509TrustManager) m;
726                 if (PlatformDependent.javaVersion() >= 7) {
727                     if (resumptionController != null) {
728                         tm = (X509TrustManager) resumptionController.wrapIfNeeded(tm);
729                     }
730                     tm = OpenSslX509TrustManagerWrapper.wrapIfNeeded(tm);
731                     if (useExtendedTrustManager(tm)) {
732                         // Wrap the TrustManager to provide a better exception message for users to debug hostname
733                         // validation failures.
734                         tm = new EnhancingX509ExtendedTrustManager(tm);
735                     }
736                 }
737                 return tm;
738             }
739         }
740         throw new IllegalStateException("no X509TrustManager found");
741     }
742 
743     protected static X509KeyManager chooseX509KeyManager(KeyManager[] kms) {
744         for (KeyManager km : kms) {
745             if (km instanceof X509KeyManager) {
746                 return (X509KeyManager) km;
747             }
748         }
749         throw new IllegalStateException("no X509KeyManager found");
750     }
751 
752     /**
753      * Translate a {@link ApplicationProtocolConfig} object to a
754      * {@link OpenSslApplicationProtocolNegotiator} object.
755      *
756      * @param config The configuration which defines the translation
757      * @return The results of the translation
758      */
759     @SuppressWarnings("deprecation")
760     static OpenSslApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config) {
761         if (config == null) {
762             return NONE_PROTOCOL_NEGOTIATOR;
763         }
764 
765         switch (config.protocol()) {
766             case NONE:
767                 return NONE_PROTOCOL_NEGOTIATOR;
768             case ALPN:
769             case NPN:
770             case NPN_AND_ALPN:
771                 switch (config.selectedListenerFailureBehavior()) {
772                     case CHOOSE_MY_LAST_PROTOCOL:
773                     case ACCEPT:
774                         switch (config.selectorFailureBehavior()) {
775                             case CHOOSE_MY_LAST_PROTOCOL:
776                             case NO_ADVERTISE:
777                                 return new OpenSslDefaultApplicationProtocolNegotiator(
778                                         config);
779                             default:
780                                 throw new UnsupportedOperationException(
781                                         new StringBuilder("OpenSSL provider does not support ")
782                                                 .append(config.selectorFailureBehavior())
783                                                 .append(" behavior").toString());
784                         }
785                     default:
786                         throw new UnsupportedOperationException(
787                                 new StringBuilder("OpenSSL provider does not support ")
788                                         .append(config.selectedListenerFailureBehavior())
789                                         .append(" behavior").toString());
790                 }
791             default:
792                 throw new Error();
793         }
794     }
795 
796     @SuppressJava6Requirement(reason = "Guarded by java version check")
797     static boolean useExtendedTrustManager(X509TrustManager trustManager) {
798         return PlatformDependent.javaVersion() >= 7 && trustManager instanceof X509ExtendedTrustManager;
799     }
800 
801     @Override
802     public final int refCnt() {
803         return refCnt.refCnt();
804     }
805 
806     @Override
807     public final ReferenceCounted retain() {
808         refCnt.retain();
809         return this;
810     }
811 
812     @Override
813     public final ReferenceCounted retain(int increment) {
814         refCnt.retain(increment);
815         return this;
816     }
817 
818     @Override
819     public final ReferenceCounted touch() {
820         refCnt.touch();
821         return this;
822     }
823 
824     @Override
825     public final ReferenceCounted touch(Object hint) {
826         refCnt.touch(hint);
827         return this;
828     }
829 
830     @Override
831     public final boolean release() {
832         return refCnt.release();
833     }
834 
835     @Override
836     public final boolean release(int decrement) {
837         return refCnt.release(decrement);
838     }
839 
840     abstract static class AbstractCertificateVerifier extends CertificateVerifier {
841         private final OpenSslEngineMap engines;
842 
843         AbstractCertificateVerifier(OpenSslEngineMap engines) {
844             this.engines = engines;
845         }
846 
847         @Override
848         public final int verify(long ssl, byte[][] chain, String auth) {
849             final ReferenceCountedOpenSslEngine engine = engines.get(ssl);
850             if (engine == null) {
851                 // May be null if it was destroyed in the meantime.
852                 return CertificateVerifier.X509_V_ERR_UNSPECIFIED;
853             }
854             X509Certificate[] peerCerts = certificates(chain);
855             try {
856                 verify(engine, peerCerts, auth);
857                 return CertificateVerifier.X509_V_OK;
858             } catch (Throwable cause) {
859                 logger.debug("verification of certificate failed", cause);
860                 engine.initHandshakeException(cause);
861 
862                 // Try to extract the correct error code that should be used.
863                 if (cause instanceof OpenSslCertificateException) {
864                     // This will never return a negative error code as its validated when constructing the
865                     // OpenSslCertificateException.
866                     return ((OpenSslCertificateException) cause).errorCode();
867                 }
868                 if (cause instanceof CertificateExpiredException) {
869                     return CertificateVerifier.X509_V_ERR_CERT_HAS_EXPIRED;
870                 }
871                 if (cause instanceof CertificateNotYetValidException) {
872                     return CertificateVerifier.X509_V_ERR_CERT_NOT_YET_VALID;
873                 }
874                 if (PlatformDependent.javaVersion() >= 7) {
875                     return translateToError(cause);
876                 }
877 
878                 // Could not detect a specific error code to use, so fallback to a default code.
879                 return CertificateVerifier.X509_V_ERR_UNSPECIFIED;
880             }
881         }
882 
883         @SuppressJava6Requirement(reason = "Usage guarded by java version check")
884         private static int translateToError(Throwable cause) {
885             if (cause instanceof CertificateRevokedException) {
886                 return CertificateVerifier.X509_V_ERR_CERT_REVOKED;
887             }
888 
889             // The X509TrustManagerImpl uses a Validator which wraps a CertPathValidatorException into
890             // an CertificateException. So we need to handle the wrapped CertPathValidatorException to be
891             // able to send the correct alert.
892             Throwable wrapped = cause.getCause();
893             while (wrapped != null) {
894                 if (wrapped instanceof CertPathValidatorException) {
895                     CertPathValidatorException ex = (CertPathValidatorException) wrapped;
896                     CertPathValidatorException.Reason reason = ex.getReason();
897                     if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
898                         return CertificateVerifier.X509_V_ERR_CERT_HAS_EXPIRED;
899                     }
900                     if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
901                         return CertificateVerifier.X509_V_ERR_CERT_NOT_YET_VALID;
902                     }
903                     if (reason == CertPathValidatorException.BasicReason.REVOKED) {
904                         return CertificateVerifier.X509_V_ERR_CERT_REVOKED;
905                     }
906                 }
907                 wrapped = wrapped.getCause();
908             }
909             if (cause instanceof CertificateException) {
910                 // The certificate was rejected (for example by the TrustManager), use X509_V_ERR_CERT_UNTRUSTED so a
911                 // bad_certificate alert is sent. X509_V_ERR_UNSPECIFIED would result in an internal_error alert which
912                 // should only be used for errors that are not related to the remote peer.
913                 return CertificateVerifier.X509_V_ERR_CERT_UNTRUSTED;
914             }
915             return CertificateVerifier.X509_V_ERR_UNSPECIFIED;
916         }
917 
918         abstract void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts,
919                              String auth) throws Exception;
920     }
921 
922     static void setKeyMaterial(long ctx, X509Certificate[] keyCertChain, PrivateKey key, String keyPassword)
923             throws SSLException {
924          /* Load the certificate file and private key. */
925         long keyBio = 0;
926         long keyCertChainBio = 0;
927         long keyCertChainBio2 = 0;
928         PemEncoded encoded = null;
929         try {
930             // Only encode one time
931             encoded = PemX509Certificate.toPEM(ByteBufAllocator.DEFAULT, true, keyCertChain);
932             keyCertChainBio = toBIO(ByteBufAllocator.DEFAULT, encoded.retain());
933             keyCertChainBio2 = toBIO(ByteBufAllocator.DEFAULT, encoded.retain());
934 
935             if (key != null) {
936                 keyBio = toBIO(ByteBufAllocator.DEFAULT, key);
937             }
938 
939             SSLContext.setCertificateBio(
940                     ctx, keyCertChainBio, keyBio,
941                     keyPassword == null ? StringUtil.EMPTY_STRING : keyPassword);
942             // We may have more then one cert in the chain so add all of them now.
943             SSLContext.setCertificateChainBio(ctx, keyCertChainBio2, true);
944         } catch (SSLException e) {
945             throw e;
946         } catch (Exception e) {
947             throw new SSLException("failed to set certificate and key", e);
948         } finally {
949             freeBio(keyBio);
950             freeBio(keyCertChainBio);
951             freeBio(keyCertChainBio2);
952             if (encoded != null) {
953                 encoded.release();
954             }
955         }
956     }
957 
958     static void freeBio(long bio) {
959         if (bio != 0) {
960             SSL.freeBIO(bio);
961         }
962     }
963 
964     /**
965      * Return the pointer to a <a href="https://www.openssl.org/docs/crypto/BIO_get_mem_ptr.html">in-memory BIO</a>
966      * or {@code 0} if the {@code key} is {@code null}. The BIO contains the content of the {@code key}.
967      */
968     static long toBIO(ByteBufAllocator allocator, PrivateKey key) throws Exception {
969         if (key == null) {
970             return 0;
971         }
972 
973         PemEncoded pem = PemPrivateKey.toPEM(allocator, true, key);
974         try {
975             return toBIO(allocator, pem.retain());
976         } finally {
977             pem.release();
978         }
979     }
980 
981     /**
982      * Return the pointer to a <a href="https://www.openssl.org/docs/crypto/BIO_get_mem_ptr.html">in-memory BIO</a>
983      * or {@code 0} if the {@code certChain} is {@code null}. The BIO contains the content of the {@code certChain}.
984      */
985     static long toBIO(ByteBufAllocator allocator, X509Certificate... certChain) throws Exception {
986         if (certChain == null) {
987             return 0;
988         }
989 
990         checkNonEmpty(certChain, "certChain");
991 
992         PemEncoded pem = PemX509Certificate.toPEM(allocator, true, certChain);
993         try {
994             return toBIO(allocator, pem.retain());
995         } finally {
996             pem.release();
997         }
998     }
999 
1000     static long toBIO(ByteBufAllocator allocator, PemEncoded pem) throws Exception {
1001         try {
1002             // We can turn direct buffers straight into BIOs. No need to
1003             // make a yet another copy.
1004             ByteBuf content = pem.content();
1005 
1006             if (content.isDirect()) {
1007                 return newBIO(content.retainedSlice());
1008             }
1009 
1010             ByteBuf buffer = allocator.directBuffer(content.readableBytes());
1011             try {
1012                 buffer.writeBytes(content, content.readerIndex(), content.readableBytes());
1013                 return newBIO(buffer.retainedSlice());
1014             } finally {
1015                 try {
1016                     // If the contents of the ByteBuf is sensitive (e.g. a PrivateKey) we
1017                     // need to zero out the bytes of the copy before we're releasing it.
1018                     if (pem.isSensitive()) {
1019                         SslUtils.zeroout(buffer);
1020                     }
1021                 } finally {
1022                     buffer.release();
1023                 }
1024             }
1025         } finally {
1026             pem.release();
1027         }
1028     }
1029 
1030     private static long newBIO(ByteBuf buffer) throws Exception {
1031         try {
1032             long bio = SSL.newMemBIO();
1033             int readable = buffer.readableBytes();
1034             if (SSL.bioWrite(bio, OpenSsl.memoryAddress(buffer) + buffer.readerIndex(), readable) != readable) {
1035                 SSL.freeBIO(bio);
1036                 throw new IllegalStateException("Could not write data to memory BIO");
1037             }
1038             return bio;
1039         } finally {
1040             buffer.release();
1041         }
1042     }
1043 
1044     /**
1045      * Returns the {@link OpenSslKeyMaterialProvider} that should be used for OpenSSL. Depending on the given
1046      * {@link KeyManagerFactory} this may cache the {@link OpenSslKeyMaterial} for better performance if it can
1047      * ensure that the same material is always returned for the same alias.
1048      */
1049     static OpenSslKeyMaterialProvider providerFor(KeyManagerFactory factory, String password) {
1050         if (factory instanceof OpenSslX509KeyManagerFactory) {
1051             return ((OpenSslX509KeyManagerFactory) factory).newProvider();
1052         }
1053 
1054         if (factory instanceof OpenSslCachingX509KeyManagerFactory) {
1055             // The user explicit used OpenSslCachingX509KeyManagerFactory which signals us that its fine to cache.
1056             return ((OpenSslCachingX509KeyManagerFactory) factory).newProvider(password);
1057         }
1058         // We can not be sure if the material may change at runtime so we will not cache it.
1059         return new OpenSslKeyMaterialProvider(chooseX509KeyManager(factory.getKeyManagers()), password);
1060     }
1061 
1062     private static ReferenceCountedOpenSslEngine retrieveEngine(OpenSslEngineMap engineMap, long ssl)
1063             throws SSLException {
1064         ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
1065         if (engine == null) {
1066             throw new SSLException("Could not find a " +
1067                     StringUtil.simpleClassName(ReferenceCountedOpenSslEngine.class) + " for sslPointer " + ssl);
1068         }
1069         return engine;
1070     }
1071 
1072     private static final class PrivateKeyMethod implements SSLPrivateKeyMethod {
1073 
1074         private final OpenSslEngineMap engines;
1075         private final OpenSslPrivateKeyMethod keyMethod;
1076         PrivateKeyMethod(OpenSslEngineMap engines, OpenSslPrivateKeyMethod keyMethod) {
1077             this.engines = engines;
1078             this.keyMethod = keyMethod;
1079         }
1080 
1081         @Override
1082         public byte[] sign(long ssl, int signatureAlgorithm, byte[] digest) throws Exception {
1083             ReferenceCountedOpenSslEngine engine = retrieveEngine(engines, ssl);
1084             try {
1085                 return verifyResult(keyMethod.sign(engine, signatureAlgorithm, digest));
1086             } catch (Exception e) {
1087                 engine.initHandshakeException(e);
1088                 throw e;
1089             }
1090         }
1091 
1092         @Override
1093         public byte[] decrypt(long ssl, byte[] input) throws Exception {
1094             ReferenceCountedOpenSslEngine engine = retrieveEngine(engines, ssl);
1095             try {
1096                 return verifyResult(keyMethod.decrypt(engine, input));
1097             } catch (Exception e) {
1098                 engine.initHandshakeException(e);
1099                 throw e;
1100             }
1101         }
1102     }
1103 
1104     private static final class AsyncPrivateKeyMethod implements AsyncSSLPrivateKeyMethod {
1105 
1106         private final OpenSslEngineMap engines;
1107         private final OpenSslAsyncPrivateKeyMethod keyMethod;
1108 
1109         AsyncPrivateKeyMethod(OpenSslEngineMap engines,
1110                               OpenSslAsyncPrivateKeyMethod keyMethod) {
1111             this.engines = engines;
1112             this.keyMethod = keyMethod;
1113         }
1114 
1115         @Override
1116         public void sign(long ssl, int signatureAlgorithm, byte[] bytes, ResultCallback<byte[]> resultCallback) {
1117             try {
1118                 ReferenceCountedOpenSslEngine engine = retrieveEngine(engines, ssl);
1119                 keyMethod.sign(engine, signatureAlgorithm, bytes)
1120                         .addListener(new ResultCallbackListener(engine, ssl, resultCallback));
1121             } catch (SSLException e) {
1122                 resultCallback.onError(ssl, e);
1123             }
1124         }
1125 
1126         @Override
1127         public void decrypt(long ssl, byte[] bytes, ResultCallback<byte[]> resultCallback) {
1128             try {
1129                 ReferenceCountedOpenSslEngine engine = retrieveEngine(engines, ssl);
1130                 keyMethod.decrypt(engine, bytes)
1131                         .addListener(new ResultCallbackListener(engine, ssl, resultCallback));
1132             } catch (SSLException e) {
1133                 resultCallback.onError(ssl, e);
1134             }
1135         }
1136 
1137         private static final class ResultCallbackListener implements FutureListener<byte[]> {
1138             private final ReferenceCountedOpenSslEngine engine;
1139             private final long ssl;
1140             private final ResultCallback<byte[]> resultCallback;
1141 
1142             ResultCallbackListener(ReferenceCountedOpenSslEngine engine, long ssl,
1143                                    ResultCallback<byte[]> resultCallback) {
1144                 this.engine = engine;
1145                 this.ssl = ssl;
1146                 this.resultCallback = resultCallback;
1147             }
1148 
1149             @Override
1150             public void operationComplete(Future<byte[]> future) {
1151                 Throwable cause = future.cause();
1152                 if (cause == null) {
1153                     try {
1154                         byte[] result = verifyResult(future.getNow());
1155                         resultCallback.onSuccess(ssl, result);
1156                         return;
1157                     } catch (SignatureException e) {
1158                         cause = e;
1159                         engine.initHandshakeException(e);
1160                     }
1161                 }
1162                 resultCallback.onError(ssl, cause);
1163             }
1164         }
1165     }
1166 
1167     private static byte[] verifyResult(byte[] result) throws SignatureException {
1168         if (result == null) {
1169             throw new SignatureException();
1170         }
1171         return result;
1172     }
1173 
1174     private static final class CompressionAlgorithm implements CertificateCompressionAlgo {
1175         private final OpenSslEngineMap engines;
1176         private final OpenSslCertificateCompressionAlgorithm compressionAlgorithm;
1177 
1178         CompressionAlgorithm(OpenSslEngineMap engines,
1179                              OpenSslCertificateCompressionAlgorithm compressionAlgorithm) {
1180             this.engines = engines;
1181             this.compressionAlgorithm = compressionAlgorithm;
1182         }
1183 
1184         @Override
1185         public byte[] compress(long ssl, byte[] bytes) throws Exception {
1186             ReferenceCountedOpenSslEngine engine = retrieveEngine(engines, ssl);
1187             return compressionAlgorithm.compress(engine, bytes);
1188         }
1189 
1190         @Override
1191         public byte[] decompress(long ssl, int len, byte[] bytes) throws Exception {
1192             ReferenceCountedOpenSslEngine engine = retrieveEngine(engines, ssl);
1193             return compressionAlgorithm.decompress(engine, len, bytes);
1194         }
1195 
1196         @Override
1197         public int algorithmId() {
1198             return compressionAlgorithm.algorithmId();
1199         }
1200     }
1201 }