View Javadoc
1   /*
2    * Copyright 2014 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  
17  package io.netty.handler.ssl;
18  
19  import io.netty.buffer.ByteBuf;
20  import io.netty.buffer.ByteBufAllocator;
21  import io.netty.buffer.UnpooledByteBufAllocator;
22  import io.netty.internal.tcnative.Buffer;
23  import io.netty.internal.tcnative.Library;
24  import io.netty.internal.tcnative.SSL;
25  import io.netty.internal.tcnative.SSLContext;
26  import io.netty.util.CharsetUtil;
27  import io.netty.util.ReferenceCountUtil;
28  import io.netty.util.ReferenceCounted;
29  import io.netty.util.internal.EmptyArrays;
30  import io.netty.util.internal.NativeLibraryLoader;
31  import io.netty.util.internal.PlatformDependent;
32  import io.netty.util.internal.StringUtil;
33  import io.netty.util.internal.SystemPropertyUtil;
34  import io.netty.util.internal.logging.InternalLogger;
35  import io.netty.util.internal.logging.InternalLoggerFactory;
36  
37  import java.io.ByteArrayInputStream;
38  import java.security.cert.CertificateException;
39  import java.security.cert.X509Certificate;
40  import java.util.ArrayList;
41  import java.util.Arrays;
42  import java.util.Collection;
43  import java.util.Collections;
44  import java.util.HashSet;
45  import java.util.Iterator;
46  import java.util.LinkedHashSet;
47  import java.util.List;
48  import java.util.Set;
49  
50  import static io.netty.handler.ssl.SslUtils.*;
51  
52  /**
53   * Tells if <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
54   * are available.
55   */
56  public final class OpenSsl {
57  
58      private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class);
59      private static final Throwable UNAVAILABILITY_CAUSE;
60      static final List<String> DEFAULT_CIPHERS;
61      static final Set<String> AVAILABLE_CIPHER_SUITES;
62      private static final Set<String> AVAILABLE_OPENSSL_CIPHER_SUITES;
63      private static final Set<String> AVAILABLE_JAVA_CIPHER_SUITES;
64      private static final boolean SUPPORTS_KEYMANAGER_FACTORY;
65      private static final boolean USE_KEYMANAGER_FACTORY;
66      private static final boolean SUPPORTS_OCSP;
67      private static final boolean TLSV13_SUPPORTED;
68      private static final boolean IS_BORINGSSL;
69      private static final Set<String> CLIENT_DEFAULT_PROTOCOLS;
70      private static final Set<String> SERVER_DEFAULT_PROTOCOLS;
71      static final Set<String> SUPPORTED_PROTOCOLS_SET;
72      static final String[] EXTRA_SUPPORTED_TLS_1_3_CIPHERS;
73      static final String EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING;
74      static final String[] NAMED_GROUPS;
75  
76      static final boolean JAVAX_CERTIFICATE_CREATION_SUPPORTED;
77  
78      // Use default that is supported in java 11 and earlier and also in OpenSSL / BoringSSL.
79      // See https://github.com/netty/netty-tcnative/issues/567
80      // See https://www.java.com/en/configure_crypto.html for ordering
81      private static final String[] DEFAULT_NAMED_GROUPS = { "x25519", "secp256r1", "secp384r1", "secp521r1" };
82  
83      static {
84          Throwable cause = null;
85  
86          if (SystemPropertyUtil.getBoolean("io.netty.handler.ssl.noOpenSsl", false)) {
87              cause = new UnsupportedOperationException(
88                      "OpenSSL was explicit disabled with -Dio.netty.handler.ssl.noOpenSsl=true");
89  
90              logger.debug(
91                      "netty-tcnative explicit disabled; " +
92                              OpenSslEngine.class.getSimpleName() + " will be unavailable.", cause);
93          } else {
94              // Test if netty-tcnative is in the classpath first.
95              try {
96                  Class.forName("io.netty.internal.tcnative.SSLContext", false,
97                          PlatformDependent.getClassLoader(OpenSsl.class));
98              } catch (ClassNotFoundException t) {
99                  cause = t;
100                 logger.debug(
101                         "netty-tcnative not in the classpath; " +
102                                 OpenSslEngine.class.getSimpleName() + " will be unavailable.");
103             }
104 
105             // If in the classpath, try to load the native library and initialize netty-tcnative.
106             if (cause == null) {
107                 try {
108                     // The JNI library was not already loaded. Load it now.
109                     loadTcNative();
110                 } catch (Throwable t) {
111                     cause = t;
112                     logger.debug(
113                             "Failed to load netty-tcnative; " +
114                                     OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " +
115                                     "application has already loaded the symbols by some other means. " +
116                                     "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t);
117                 }
118 
119                 try {
120                     String engine = SystemPropertyUtil.get("io.netty.handler.ssl.openssl.engine", null);
121                     if (engine == null) {
122                         logger.debug("Initialize netty-tcnative using engine: 'default'");
123                     } else {
124                         logger.debug("Initialize netty-tcnative using engine: '{}'", engine);
125                     }
126                     initializeTcNative(engine);
127 
128                     // The library was initialized successfully. If loading the library failed above,
129                     // reset the cause now since it appears that the library was loaded by some other
130                     // means.
131                     cause = null;
132                 } catch (Throwable t) {
133                     if (cause == null) {
134                         cause = t;
135                     }
136                     logger.debug(
137                             "Failed to initialize netty-tcnative; " +
138                                     OpenSslEngine.class.getSimpleName() + " will be unavailable. " +
139                                     "See https://netty.io/wiki/forked-tomcat-native.html for more information.", t);
140                 }
141             }
142         }
143 
144         UNAVAILABILITY_CAUSE = cause;
145         CLIENT_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.client.protocols");
146         SERVER_DEFAULT_PROTOCOLS = defaultProtocols("jdk.tls.server.protocols");
147 
148         if (cause == null) {
149             logger.debug("netty-tcnative using native library: {}", SSL.versionString());
150 
151             final List<String> defaultCiphers = new ArrayList<String>();
152             final Set<String> availableOpenSslCipherSuites = new LinkedHashSet<String>(128);
153             boolean supportsKeyManagerFactory = false;
154             boolean useKeyManagerFactory = false;
155             boolean tlsv13Supported = false;
156             String[] namedGroups = DEFAULT_NAMED_GROUPS;
157             Set<String> defaultConvertedNamedGroups = new LinkedHashSet<String>(namedGroups.length);
158             for (int i = 0; i < namedGroups.length; i++) {
159                 defaultConvertedNamedGroups.add(GroupsConverter.toOpenSsl(namedGroups[i]));
160             }
161 
162             IS_BORINGSSL = "BoringSSL".equals(versionString());
163             if (IS_BORINGSSL) {
164                 EXTRA_SUPPORTED_TLS_1_3_CIPHERS = new String [] { "TLS_AES_128_GCM_SHA256",
165                         "TLS_AES_256_GCM_SHA384" ,
166                         "TLS_CHACHA20_POLY1305_SHA256" };
167 
168                 StringBuilder ciphersBuilder = new StringBuilder(128);
169                 for (String cipher: EXTRA_SUPPORTED_TLS_1_3_CIPHERS) {
170                     ciphersBuilder.append(cipher).append(":");
171                 }
172                 ciphersBuilder.setLength(ciphersBuilder.length() - 1);
173                 EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = ciphersBuilder.toString();
174             }  else {
175                 EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS;
176                 EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING;
177             }
178 
179             try {
180                 final long sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER);
181 
182                 // Let's filter out any group that is not supported from the default.
183                 Iterator<String> defaultGroupsIter = defaultConvertedNamedGroups.iterator();
184                 while (defaultGroupsIter.hasNext()) {
185                     if (!SSLContext.setCurvesList(sslCtx, defaultGroupsIter.next())) {
186                         // Not supported, let's remove it. This could for example be the case if we use
187                         // fips and the configure group is not supported when using FIPS.
188                         // See https://github.com/netty/netty-tcnative/issues/883
189                         defaultGroupsIter.remove();
190                     }
191                 }
192                 namedGroups = defaultConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
193 
194                 long certBio = 0;
195                 long keyBio = 0;
196                 long cert = 0;
197                 long key = 0;
198                 try {
199                     // As we delegate to the KeyManager / TrustManager of the JDK we need to ensure it can actually
200                     // handle TLSv13 as otherwise we may see runtime exceptions
201                     if (SslProvider.isTlsv13Supported(SslProvider.JDK)) {
202                         try {
203                             StringBuilder tlsv13Ciphers = new StringBuilder();
204 
205                             for (String cipher : TLSV13_CIPHERS) {
206                                 String converted = CipherSuiteConverter.toOpenSsl(cipher, IS_BORINGSSL);
207                                 if (converted != null) {
208                                     tlsv13Ciphers.append(converted).append(':');
209                                 }
210                             }
211                             if (tlsv13Ciphers.length() == 0) {
212                                 tlsv13Supported = false;
213                             } else {
214                                 tlsv13Ciphers.setLength(tlsv13Ciphers.length() - 1);
215                                 SSLContext.setCipherSuite(sslCtx, tlsv13Ciphers.toString(), true);
216                                 tlsv13Supported = true;
217                             }
218 
219                         } catch (Exception ignore) {
220                             tlsv13Supported = false;
221                         }
222                     }
223 
224                     SSLContext.setCipherSuite(sslCtx, "ALL", false);
225 
226                     final long ssl = SSL.newSSL(sslCtx, true);
227                     try {
228                         for (String c: SSL.getCiphers(ssl)) {
229                             // Filter out bad input.
230                             if (c == null || c.isEmpty() || availableOpenSslCipherSuites.contains(c) ||
231                                 // Filter out TLSv1.3 ciphers if not supported.
232                                 !tlsv13Supported && isTLSv13Cipher(c)) {
233                                 continue;
234                             }
235                             availableOpenSslCipherSuites.add(c);
236                         }
237                         if (IS_BORINGSSL) {
238                             // Currently BoringSSL does not include these when calling SSL.getCiphers() even when these
239                             // are supported.
240                             Collections.addAll(availableOpenSslCipherSuites, EXTRA_SUPPORTED_TLS_1_3_CIPHERS);
241                             Collections.addAll(availableOpenSslCipherSuites,
242                                                "AEAD-AES128-GCM-SHA256",
243                                                "AEAD-AES256-GCM-SHA384",
244                                                "AEAD-CHACHA20-POLY1305-SHA256");
245                         }
246 
247                         PemEncoded privateKey = PemPrivateKey.valueOf(PROBING_KEY.getBytes(CharsetUtil.US_ASCII));
248                         try {
249                             // Let's check if we can set a callback, which may not work if the used OpenSSL version
250                             // is to old.
251                             SSLContext.setCertificateCallback(sslCtx, null);
252 
253                             X509Certificate certificate = selfSignedCertificate();
254                             certBio = ReferenceCountedOpenSslContext.toBIO(ByteBufAllocator.DEFAULT, certificate);
255                             cert = SSL.parseX509Chain(certBio);
256 
257                             keyBio = ReferenceCountedOpenSslContext.toBIO(
258                                     UnpooledByteBufAllocator.DEFAULT, privateKey.retain());
259                             key = SSL.parsePrivateKey(keyBio, null);
260 
261                             SSL.setKeyMaterial(ssl, cert, key);
262                             supportsKeyManagerFactory = true;
263                             try {
264                                 boolean propertySet = SystemPropertyUtil.contains(
265                                         "io.netty.handler.ssl.openssl.useKeyManagerFactory");
266                                 if (!IS_BORINGSSL) {
267                                     useKeyManagerFactory = SystemPropertyUtil.getBoolean(
268                                             "io.netty.handler.ssl.openssl.useKeyManagerFactory", true);
269 
270                                     if (propertySet) {
271                                         logger.info("System property " +
272                                                 "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" +
273                                                 " is deprecated and so will be ignored in the future");
274                                     }
275                                 } else {
276                                     useKeyManagerFactory = true;
277                                     if (propertySet) {
278                                         logger.info("System property " +
279                                                 "'io.netty.handler.ssl.openssl.useKeyManagerFactory'" +
280                                                 " is deprecated and will be ignored when using BoringSSL");
281                                     }
282                                 }
283                             } catch (Throwable ignore) {
284                                 logger.debug("Failed to get useKeyManagerFactory system property.");
285                             }
286                         } catch (Exception e) {
287                             logger.debug("KeyManagerFactory not supported", e);
288                         } finally {
289                             privateKey.release();
290                         }
291                     } finally {
292                         SSL.freeSSL(ssl);
293                         if (certBio != 0) {
294                             SSL.freeBIO(certBio);
295                         }
296                         if (keyBio != 0) {
297                             SSL.freeBIO(keyBio);
298                         }
299                         if (cert != 0) {
300                             SSL.freeX509Chain(cert);
301                         }
302                         if (key != 0) {
303                             SSL.freePrivateKey(key);
304                         }
305                     }
306 
307                     String groups = SystemPropertyUtil.get("jdk.tls.namedGroups", null);
308                     if (groups != null) {
309                         String[] nGroups = groups.split(",");
310                         Set<String> supportedNamedGroups = new LinkedHashSet<String>(nGroups.length);
311                         Set<String> supportedConvertedNamedGroups = new LinkedHashSet<String>(nGroups.length);
312 
313                         Set<String> unsupportedNamedGroups = new LinkedHashSet<String>();
314                         for (String namedGroup : nGroups) {
315                             String converted = GroupsConverter.toOpenSsl(namedGroup);
316                             if (SSLContext.setCurvesList(sslCtx, converted)) {
317                                 supportedConvertedNamedGroups.add(converted);
318                                 supportedNamedGroups.add(namedGroup);
319                             } else {
320                                 unsupportedNamedGroups.add(namedGroup);
321                             }
322                         }
323 
324                         if (supportedNamedGroups.isEmpty()) {
325                             namedGroups = defaultConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
326                             logger.info("All configured namedGroups are not supported: {}. Use default: {}.",
327                                     Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)),
328                                     Arrays.toString(DEFAULT_NAMED_GROUPS));
329                         } else {
330                             String[] groupArray = supportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
331                             if (unsupportedNamedGroups.isEmpty()) {
332                                 logger.info("Using configured namedGroups -D 'jdk.tls.namedGroup': {} ",
333                                         Arrays.toString(groupArray));
334                             } else {
335                                 logger.info("Using supported configured namedGroups: {}. Unsupported namedGroups: {}. ",
336                                         Arrays.toString(groupArray),
337                                         Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)));
338                             }
339                             namedGroups =  supportedConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
340                         }
341                     } else {
342                         namedGroups = defaultConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
343                     }
344                 } finally {
345                     SSLContext.free(sslCtx);
346                 }
347             } catch (Exception e) {
348                 logger.warn("Failed to get the list of available OpenSSL cipher suites.", e);
349             }
350             NAMED_GROUPS = namedGroups;
351             AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.unmodifiableSet(availableOpenSslCipherSuites);
352             final Set<String> availableJavaCipherSuites = new LinkedHashSet<String>(
353                     AVAILABLE_OPENSSL_CIPHER_SUITES.size() * 2);
354             for (String cipher: AVAILABLE_OPENSSL_CIPHER_SUITES) {
355                 // Included converted but also openssl cipher name
356                 if (!isTLSv13Cipher(cipher)) {
357                     availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "TLS"));
358                     availableJavaCipherSuites.add(CipherSuiteConverter.toJava(cipher, "SSL"));
359                 } else {
360                     // TLSv1.3 ciphers have the correct format.
361                     availableJavaCipherSuites.add(cipher);
362                 }
363             }
364 
365             addIfSupported(availableJavaCipherSuites, defaultCiphers, DEFAULT_CIPHER_SUITES);
366             addIfSupported(availableJavaCipherSuites, defaultCiphers, TLSV13_CIPHER_SUITES);
367             // Also handle the extra supported ciphers as these will contain some more stuff on BoringSSL.
368             addIfSupported(availableJavaCipherSuites, defaultCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS);
369 
370             useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, availableJavaCipherSuites);
371             DEFAULT_CIPHERS = Collections.unmodifiableList(defaultCiphers);
372 
373             AVAILABLE_JAVA_CIPHER_SUITES = Collections.unmodifiableSet(availableJavaCipherSuites);
374 
375             final Set<String> availableCipherSuites = new LinkedHashSet<String>(
376                     AVAILABLE_OPENSSL_CIPHER_SUITES.size() + AVAILABLE_JAVA_CIPHER_SUITES.size());
377             availableCipherSuites.addAll(AVAILABLE_OPENSSL_CIPHER_SUITES);
378             availableCipherSuites.addAll(AVAILABLE_JAVA_CIPHER_SUITES);
379 
380             AVAILABLE_CIPHER_SUITES = availableCipherSuites;
381             SUPPORTS_KEYMANAGER_FACTORY = supportsKeyManagerFactory;
382             USE_KEYMANAGER_FACTORY = useKeyManagerFactory;
383 
384             Set<String> protocols = new LinkedHashSet<String>(6);
385             // Seems like there is no way to explicitly disable SSLv2Hello in openssl so it is always enabled
386             protocols.add(SslProtocols.SSL_v2_HELLO);
387             if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV2, SSL.SSL_OP_NO_SSLv2)) {
388                 protocols.add(SslProtocols.SSL_v2);
389             }
390             if (doesSupportProtocol(SSL.SSL_PROTOCOL_SSLV3, SSL.SSL_OP_NO_SSLv3)) {
391                 protocols.add(SslProtocols.SSL_v3);
392             }
393             if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1, SSL.SSL_OP_NO_TLSv1)) {
394                 protocols.add(SslProtocols.TLS_v1);
395             }
396             if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_1, SSL.SSL_OP_NO_TLSv1_1)) {
397                 protocols.add(SslProtocols.TLS_v1_1);
398             }
399             if (doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_OP_NO_TLSv1_2)) {
400                 protocols.add(SslProtocols.TLS_v1_2);
401             }
402 
403             // This is only supported by java8u272 and later.
404             if (tlsv13Supported && doesSupportProtocol(SSL.SSL_PROTOCOL_TLSV1_3, SSL.SSL_OP_NO_TLSv1_3)) {
405                 protocols.add(SslProtocols.TLS_v1_3);
406                 TLSV13_SUPPORTED = true;
407             } else {
408                 TLSV13_SUPPORTED = false;
409             }
410 
411             SUPPORTED_PROTOCOLS_SET = Collections.unmodifiableSet(protocols);
412             SUPPORTS_OCSP = doesSupportOcsp();
413 
414             if (logger.isDebugEnabled()) {
415                 logger.debug("Supported protocols (OpenSSL): {} ", SUPPORTED_PROTOCOLS_SET);
416                 logger.debug("Default cipher suites (OpenSSL): {}", DEFAULT_CIPHERS);
417             }
418 
419             // Check if we can create a javax.security.cert.X509Certificate from our cert. This might fail on
420             // JDK17 and above. In this case we will later throw an UnsupportedOperationException if someone
421             // tries to access these via SSLSession. See https://github.com/netty/netty/issues/13560.
422             boolean javaxCertificateCreationSupported;
423             try {
424                 javax.security.cert.X509Certificate.getInstance(PROBING_CERT.getBytes(CharsetUtil.US_ASCII));
425                 javaxCertificateCreationSupported = true;
426             } catch (javax.security.cert.CertificateException ex) {
427                 javaxCertificateCreationSupported = false;
428             }
429             JAVAX_CERTIFICATE_CREATION_SUPPORTED = javaxCertificateCreationSupported;
430         } else {
431             DEFAULT_CIPHERS = Collections.emptyList();
432             AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.emptySet();
433             AVAILABLE_JAVA_CIPHER_SUITES = Collections.emptySet();
434             AVAILABLE_CIPHER_SUITES = Collections.emptySet();
435             SUPPORTS_KEYMANAGER_FACTORY = false;
436             USE_KEYMANAGER_FACTORY = false;
437             SUPPORTED_PROTOCOLS_SET = Collections.emptySet();
438             SUPPORTS_OCSP = false;
439             TLSV13_SUPPORTED = false;
440             IS_BORINGSSL = false;
441             EXTRA_SUPPORTED_TLS_1_3_CIPHERS = EmptyArrays.EMPTY_STRINGS;
442             EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING = StringUtil.EMPTY_STRING;
443             NAMED_GROUPS = DEFAULT_NAMED_GROUPS;
444             JAVAX_CERTIFICATE_CREATION_SUPPORTED = false;
445         }
446     }
447 
448     static String checkTls13Ciphers(InternalLogger logger, String ciphers) {
449         if (IS_BORINGSSL && !ciphers.isEmpty()) {
450             assert EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length > 0;
451             Set<String> boringsslTlsv13Ciphers = new HashSet<String>(EXTRA_SUPPORTED_TLS_1_3_CIPHERS.length);
452             Collections.addAll(boringsslTlsv13Ciphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS);
453             boolean ciphersNotMatch = false;
454             for (String cipher: ciphers.split(":")) {
455                 if (boringsslTlsv13Ciphers.isEmpty()) {
456                     ciphersNotMatch = true;
457                     break;
458                 }
459                 if (!boringsslTlsv13Ciphers.remove(cipher) &&
460                         !boringsslTlsv13Ciphers.remove(CipherSuiteConverter.toJava(cipher, "TLS"))) {
461                     ciphersNotMatch = true;
462                     break;
463                 }
464             }
465 
466             // Also check if there are ciphers left.
467             ciphersNotMatch |= !boringsslTlsv13Ciphers.isEmpty();
468 
469             if (ciphersNotMatch) {
470                 if (logger.isInfoEnabled()) {
471                     StringBuilder javaCiphers = new StringBuilder(128);
472                     for (String cipher : ciphers.split(":")) {
473                         javaCiphers.append(CipherSuiteConverter.toJava(cipher, "TLS")).append(":");
474                     }
475                     javaCiphers.setLength(javaCiphers.length() - 1);
476                     logger.info(
477                             "BoringSSL doesn't allow to enable or disable TLSv1.3 ciphers explicitly." +
478                                     " Provided TLSv1.3 ciphers: '{}', default TLSv1.3 ciphers that will be used: '{}'.",
479                             javaCiphers, EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING);
480                 }
481                 return EXTRA_SUPPORTED_TLS_1_3_CIPHERS_STRING;
482             }
483         }
484         return ciphers;
485     }
486 
487     static boolean isSessionCacheSupported() {
488         return version() >= 0x10100000L;
489     }
490 
491     /**
492      * Returns a self-signed {@link X509Certificate} for {@code netty.io}.
493      */
494     static X509Certificate selfSignedCertificate() throws CertificateException {
495         return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate(
496                 new ByteArrayInputStream(PROBING_CERT.getBytes(CharsetUtil.US_ASCII))
497         );
498     }
499 
500     private static boolean doesSupportOcsp() {
501         boolean supportsOcsp = false;
502         if (version() >= 0x10002000L) {
503             long sslCtx = -1;
504             try {
505                 sslCtx = SSLContext.make(SSL.SSL_PROTOCOL_TLSV1_2, SSL.SSL_MODE_SERVER);
506                 SSLContext.enableOcsp(sslCtx, false);
507                 supportsOcsp = true;
508             } catch (Exception ignore) {
509                 // ignore
510             } finally {
511                 if (sslCtx != -1) {
512                     SSLContext.free(sslCtx);
513                 }
514             }
515         }
516         return supportsOcsp;
517     }
518     private static boolean doesSupportProtocol(int protocol, int opt) {
519         if (opt == 0) {
520             // If the opt is 0 the protocol is not supported. This is for example the case with BoringSSL and SSLv2.
521             return false;
522         }
523         long sslCtx = -1;
524         try {
525             sslCtx = SSLContext.make(protocol, SSL.SSL_MODE_COMBINED);
526             return true;
527         } catch (Exception ignore) {
528             return false;
529         } finally {
530             if (sslCtx != -1) {
531                 SSLContext.free(sslCtx);
532             }
533         }
534     }
535 
536     /**
537      * Returns {@code true} if and only if
538      * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
539      * are available.
540      */
541     public static boolean isAvailable() {
542         return UNAVAILABILITY_CAUSE == null;
543     }
544 
545     /**
546      * Returns {@code true} if the used version of openssl supports
547      * <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>.
548      *
549      * @deprecated use {@link SslProvider#isAlpnSupported(SslProvider)} with {@link SslProvider#OPENSSL}.
550      */
551     @Deprecated
552     public static boolean isAlpnSupported() {
553         return version() >= 0x10002000L;
554     }
555 
556     /**
557      * Returns {@code true} if the used version of OpenSSL supports OCSP stapling.
558      */
559     public static boolean isOcspSupported() {
560       return SUPPORTS_OCSP;
561     }
562 
563     /**
564      * Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()}
565      * returns {@code false}.
566      */
567     public static int version() {
568         return isAvailable() ? SSL.version() : -1;
569     }
570 
571     /**
572      * Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()}
573      * returns {@code false}.
574      */
575     public static String versionString() {
576         return isAvailable() ? SSL.versionString() : null;
577     }
578 
579     /**
580      * Ensure that <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and
581      * its OpenSSL support are available.
582      *
583      * @throws UnsatisfiedLinkError if unavailable
584      */
585     public static void ensureAvailability() {
586         if (UNAVAILABILITY_CAUSE != null) {
587             throw (Error) new UnsatisfiedLinkError(
588                     "failed to load the required native library").initCause(UNAVAILABILITY_CAUSE);
589         }
590     }
591 
592     /**
593      * Returns the cause of unavailability of
594      * <a href="https://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support.
595      *
596      * @return the cause if unavailable. {@code null} if available.
597      */
598     public static Throwable unavailabilityCause() {
599         return UNAVAILABILITY_CAUSE;
600     }
601 
602     /**
603      * @deprecated use {@link #availableOpenSslCipherSuites()}
604      */
605     @Deprecated
606     public static Set<String> availableCipherSuites() {
607         return availableOpenSslCipherSuites();
608     }
609 
610     /**
611      * Returns all the available OpenSSL cipher suites.
612      * Please note that the returned array may include the cipher suites that are insecure or non-functional.
613      */
614     public static Set<String> availableOpenSslCipherSuites() {
615         return AVAILABLE_OPENSSL_CIPHER_SUITES;
616     }
617 
618     /**
619      * Returns all the available cipher suites (Java-style).
620      * Please note that the returned array may include the cipher suites that are insecure or non-functional.
621      */
622     public static Set<String> availableJavaCipherSuites() {
623         return AVAILABLE_JAVA_CIPHER_SUITES;
624     }
625 
626     /**
627      * Returns {@code true} if and only if the specified cipher suite is available in OpenSSL.
628      * Both Java-style cipher suite and OpenSSL-style cipher suite are accepted.
629      */
630     public static boolean isCipherSuiteAvailable(String cipherSuite) {
631         String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL);
632         if (converted != null) {
633             cipherSuite = converted;
634         }
635         return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite);
636     }
637 
638     /**
639      * Returns {@code true} if {@link javax.net.ssl.KeyManagerFactory} is supported when using OpenSSL.
640      */
641     public static boolean supportsKeyManagerFactory() {
642         return SUPPORTS_KEYMANAGER_FACTORY;
643     }
644 
645     /**
646      * Always returns {@code true} if {@link #isAvailable()} returns {@code true}.
647      *
648      * @deprecated Will be removed because hostname validation is always done by a
649      * {@link javax.net.ssl.TrustManager} implementation.
650      */
651     @Deprecated
652     public static boolean supportsHostnameValidation() {
653         return isAvailable();
654     }
655 
656     static boolean useKeyManagerFactory() {
657         return USE_KEYMANAGER_FACTORY;
658     }
659 
660     static long memoryAddress(ByteBuf buf) {
661         assert buf.isDirect();
662         return buf.hasMemoryAddress() ? buf.memoryAddress() :
663                 // Use internalNioBuffer to reduce object creation.
664                 Buffer.address(buf.internalNioBuffer(0, buf.readableBytes()));
665     }
666 
667     private OpenSsl() { }
668 
669     private static void loadTcNative() throws Exception {
670         String os = PlatformDependent.normalizedOs();
671         String arch = PlatformDependent.normalizedArch();
672 
673         Set<String> libNames = new LinkedHashSet<String>(5);
674         String staticLibName = "netty_tcnative";
675 
676         // First, try loading the platform-specific library. Platform-specific
677         // libraries will be available if using a tcnative uber jar.
678         if ("linux".equals(os)) {
679             Set<String> classifiers = PlatformDependent.normalizedLinuxClassifiers();
680             for (String classifier : classifiers) {
681                 libNames.add(staticLibName + "_" + os + '_' + arch + "_" + classifier);
682             }
683             // generic arch-dependent library
684             libNames.add(staticLibName + "_" + os + '_' + arch);
685 
686             // Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0).
687             // note: should already be included from the classifiers but if not, we use this as an
688             //       additional fallback option here
689             libNames.add(staticLibName + "_" + os + '_' + arch + "_fedora");
690         } else {
691             libNames.add(staticLibName + "_" + os + '_' + arch);
692         }
693         libNames.add(staticLibName + "_" + arch);
694         libNames.add(staticLibName);
695 
696         NativeLibraryLoader.loadFirstAvailable(PlatformDependent.getClassLoader(SSLContext.class),
697             libNames.toArray(EmptyArrays.EMPTY_STRINGS));
698     }
699 
700     private static boolean initializeTcNative(String engine) throws Exception {
701         return Library.initialize("provided", engine);
702     }
703 
704     static void releaseIfNeeded(ReferenceCounted counted) {
705         if (counted.refCnt() > 0) {
706             ReferenceCountUtil.safeRelease(counted);
707         }
708     }
709 
710     static boolean isTlsv13Supported() {
711         return TLSV13_SUPPORTED;
712     }
713 
714     static boolean isOptionSupported(SslContextOption<?> option) {
715         if (isAvailable()) {
716             if (option == OpenSslContextOption.USE_TASKS) {
717                 return true;
718             }
719             // Check for options that are only supported by BoringSSL atm.
720             if (isBoringSSL()) {
721                 return option == OpenSslContextOption.ASYNC_PRIVATE_KEY_METHOD ||
722                         option == OpenSslContextOption.PRIVATE_KEY_METHOD ||
723                         option == OpenSslContextOption.CERTIFICATE_COMPRESSION_ALGORITHMS ||
724                         option == OpenSslContextOption.TLS_FALSE_START ||
725                         option == OpenSslContextOption.MAX_CERTIFICATE_LIST_BYTES;
726             }
727         }
728         return false;
729     }
730 
731     private static Set<String> defaultProtocols(String property) {
732         String protocolsString = SystemPropertyUtil.get(property, null);
733         Set<String> protocols = new HashSet<String>();
734         if (protocolsString != null) {
735             for (String proto : protocolsString.split(",")) {
736                 String p = proto.trim();
737                 protocols.add(p);
738             }
739         } else {
740             protocols.add(SslProtocols.TLS_v1_2);
741             protocols.add(SslProtocols.TLS_v1_3);
742         }
743         return protocols;
744     }
745 
746     static String[] defaultProtocols(boolean isClient) {
747         final Collection<String> defaultProtocols = isClient ? CLIENT_DEFAULT_PROTOCOLS : SERVER_DEFAULT_PROTOCOLS;
748         assert defaultProtocols != null;
749         List<String> protocols = new ArrayList<String>(defaultProtocols.size());
750         for (String proto : defaultProtocols) {
751             if (SUPPORTED_PROTOCOLS_SET.contains(proto)) {
752                 protocols.add(proto);
753             }
754         }
755         return protocols.toArray(EmptyArrays.EMPTY_STRINGS);
756     }
757 
758     static boolean isBoringSSL() {
759         return IS_BORINGSSL;
760     }
761 }