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