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