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.ByteBufInputStream;
22  import io.netty.channel.ChannelInitializer;
23  import io.netty.channel.ChannelPipeline;
24  import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
25  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
26  import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
27  import io.netty.handler.ssl.util.BouncyCastleUtil;
28  import io.netty.util.AttributeMap;
29  import io.netty.util.DefaultAttributeMap;
30  import io.netty.util.SecureObjectIdentityHash;
31  import io.netty.util.concurrent.ImmediateExecutor;
32  import io.netty.util.internal.EmptyArrays;
33  import io.netty.util.internal.SystemPropertyUtil;
34  import io.netty.util.internal.UnstableApi;
35  import io.netty.util.internal.logging.InternalLogger;
36  import io.netty.util.internal.logging.InternalLoggerFactory;
37  
38  import javax.crypto.Cipher;
39  import javax.crypto.EncryptedPrivateKeyInfo;
40  import javax.crypto.NoSuchPaddingException;
41  import javax.crypto.SecretKey;
42  import javax.crypto.SecretKeyFactory;
43  import javax.crypto.spec.PBEKeySpec;
44  import javax.net.ssl.KeyManager;
45  import javax.net.ssl.KeyManagerFactory;
46  import javax.net.ssl.SNIServerName;
47  import javax.net.ssl.SSLContext;
48  import javax.net.ssl.SSLEngine;
49  import javax.net.ssl.SSLException;
50  import javax.net.ssl.SSLSessionContext;
51  import javax.net.ssl.TrustManager;
52  import javax.net.ssl.TrustManagerFactory;
53  import java.io.BufferedInputStream;
54  import java.io.File;
55  import java.io.IOException;
56  import java.io.InputStream;
57  import java.security.AlgorithmParameters;
58  import java.security.InvalidAlgorithmParameterException;
59  import java.security.InvalidKeyException;
60  import java.security.KeyException;
61  import java.security.KeyFactory;
62  import java.security.KeyStore;
63  import java.security.KeyStoreException;
64  import java.security.NoSuchAlgorithmException;
65  import java.security.PrivateKey;
66  import java.security.Provider;
67  import java.security.SecureRandom;
68  import java.security.UnrecoverableKeyException;
69  import java.security.cert.CertificateException;
70  import java.security.cert.CertificateFactory;
71  import java.security.cert.X509Certificate;
72  import java.security.spec.InvalidKeySpecException;
73  import java.security.spec.PKCS8EncodedKeySpec;
74  import java.util.Collections;
75  import java.util.List;
76  import java.util.Map;
77  import java.util.concurrent.Executor;
78  
79  /**
80   * A secure socket protocol implementation which acts as a factory for {@link SSLEngine} and {@link SslHandler}.
81   * Internally, it is implemented via JDK's {@link SSLContext} or OpenSSL's {@code SSL_CTX}.
82   *
83   * <h3>Making your server support SSL/TLS</h3>
84   * <pre>
85   * // In your {@link ChannelInitializer}:
86   * {@link ChannelPipeline} p = channel.pipeline();
87   * {@link SslContext} sslCtx = {@link SslContextBuilder#forServer(File, File) SslContextBuilder.forServer(...)}.build();
88   * p.addLast("ssl", {@link #newHandler(ByteBufAllocator) sslCtx.newHandler(channel.alloc())});
89   * ...
90   * </pre>
91   *
92   * <h3>Making your client support SSL/TLS</h3>
93   * <pre>
94   * // In your {@link ChannelInitializer}:
95   * {@link ChannelPipeline} p = channel.pipeline();
96   * {@link SslContext} sslCtx = {@link SslContextBuilder#forClient() SslContextBuilder.forClient()}.build();
97   * p.addLast("ssl", {@link #newHandler(ByteBufAllocator, String, int) sslCtx.newHandler(channel.alloc(), host, port)});
98   * ...
99   * </pre>
100  */
101 public abstract class SslContext {
102     private static final InternalLogger logger = InternalLoggerFactory.getInstance(SslContext.class);
103 
104     private static final String DEFAULT_ENDPOINT_VERIFICATION_ALGORITHM_PROPERTY =
105             "io.netty.handler.ssl.defaultEndpointVerificationAlgorithm";
106 
107     /**
108      * Endpoint verification is enabled by default from Netty 4.2 onward, but it wasn't in Netty 4.1 and earlier.
109      * The {@value #DEFAULT_ENDPOINT_VERIFICATION_ALGORITHM_PROPERTY} can be set to one of the following
110      * values to control this behavior:
111      * <ul>
112      *     <li>{@code "HTTPS"} — verify subject by DNS hostnames; this is the Netty 4.2 default.</li>
113      *     <li>{@code "LDAP"} — verify subject by LDAP identity.</li>
114      *     <li>{@code "NONE"} — don't enable endpoint verification by default; this is the Netty 4.1 behavior.</li>
115      * </ul>
116      */
117     protected static final String defaultEndpointVerificationAlgorithm;
118 
119     static final String ALIAS = "key";
120 
121     static final CertificateFactory X509_CERT_FACTORY;
122     static {
123         try {
124             X509_CERT_FACTORY = CertificateFactory.getInstance("X.509");
125         } catch (CertificateException e) {
126             throw new IllegalStateException("unable to instance X.509 CertificateFactory", e);
127         }
128 
129         String defaultEndpointVerification = SystemPropertyUtil.get(DEFAULT_ENDPOINT_VERIFICATION_ALGORITHM_PROPERTY);
130         if ("LDAP".equalsIgnoreCase(defaultEndpointVerification)) {
131             defaultEndpointVerificationAlgorithm = "LDAP";
132         } else if ("NONE".equalsIgnoreCase(defaultEndpointVerification)) {
133             logger.info("Default SSL endpoint verification has been disabled:  -D{}=\"{}\"",
134                     DEFAULT_ENDPOINT_VERIFICATION_ALGORITHM_PROPERTY, defaultEndpointVerification);
135             defaultEndpointVerificationAlgorithm = null;
136         } else {
137             if (defaultEndpointVerification != null && !"HTTPS".equalsIgnoreCase(defaultEndpointVerification)) {
138                 logger.warn("Unknown default SSL endpoint verification algorithm: -D{}=\"{}\", " +
139                                 "will use \"HTTPS\" instead.",
140                         DEFAULT_ENDPOINT_VERIFICATION_ALGORITHM_PROPERTY, defaultEndpointVerification);
141             }
142             defaultEndpointVerificationAlgorithm = "HTTPS";
143         }
144     }
145 
146     private final boolean startTls;
147     private final AttributeMap attributes = new DefaultAttributeMap();
148     final ResumptionController resumptionController;
149     private static final String OID_PKCS5_PBES2 = "1.2.840.113549.1.5.13";
150     private static final String PBES2 = "PBES2";
151 
152     /**
153      * Returns the default server-side implementation provider currently in use.
154      *
155      * @return {@link SslProvider#OPENSSL} if OpenSSL is available. {@link SslProvider#JDK} otherwise.
156      */
157     public static SslProvider defaultServerProvider() {
158         return defaultProvider();
159     }
160 
161     /**
162      * Returns the default client-side implementation provider currently in use.
163      *
164      * @return {@link SslProvider#OPENSSL} if OpenSSL is available. {@link SslProvider#JDK} otherwise.
165      */
166     public static SslProvider defaultClientProvider() {
167         return defaultProvider();
168     }
169 
170     private static SslProvider defaultProvider() {
171         if (OpenSsl.isAvailable()) {
172             return SslProvider.OPENSSL;
173         } else {
174             return SslProvider.JDK;
175         }
176     }
177 
178     /**
179      * Creates a new server-side {@link SslContext}.
180      *
181      * @param certChainFile an X.509 certificate chain file in PEM format
182      * @param keyFile a PKCS#8 private key file in PEM format
183      * @return a new server-side {@link SslContext}
184      * @deprecated Replaced by {@link SslContextBuilder}
185      */
186     @Deprecated
187     public static SslContext newServerContext(File certChainFile, File keyFile) throws SSLException {
188         return newServerContext(certChainFile, keyFile, null);
189     }
190 
191     /**
192      * Creates a new server-side {@link SslContext}.
193      *
194      * @param certChainFile an X.509 certificate chain file in PEM format
195      * @param keyFile a PKCS#8 private key file in PEM format
196      * @param keyPassword the password of the {@code keyFile}.
197      *                    {@code null} if it's not password-protected.
198      * @return a new server-side {@link SslContext}
199      * @deprecated Replaced by {@link SslContextBuilder}
200      */
201     @Deprecated
202     public static SslContext newServerContext(
203             File certChainFile, File keyFile, String keyPassword) throws SSLException {
204         return newServerContext(null, certChainFile, keyFile, keyPassword);
205     }
206 
207     /**
208      * Creates a new server-side {@link SslContext}.
209      *
210      * @param certChainFile an X.509 certificate chain file in PEM format
211      * @param keyFile a PKCS#8 private key file in PEM format
212      * @param keyPassword the password of the {@code keyFile}.
213      *                    {@code null} if it's not password-protected.
214      * @param ciphers the cipher suites to enable, in the order of preference.
215      *                {@code null} to use the default cipher suites.
216      * @param nextProtocols the application layer protocols to accept, in the order of preference.
217      *                      {@code null} to disable TLS NPN/ALPN extension.
218      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
219      *                         {@code 0} to use the default value.
220      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
221      *                       {@code 0} to use the default value.
222      * @return a new server-side {@link SslContext}
223      * @deprecated Replaced by {@link SslContextBuilder}
224      */
225     @Deprecated
226     public static SslContext newServerContext(
227             File certChainFile, File keyFile, String keyPassword,
228             Iterable<String> ciphers, Iterable<String> nextProtocols,
229             long sessionCacheSize, long sessionTimeout) throws SSLException {
230 
231         return newServerContext(
232                 null, certChainFile, keyFile, keyPassword,
233                 ciphers, nextProtocols, sessionCacheSize, sessionTimeout);
234     }
235 
236     /**
237      * Creates a new server-side {@link SslContext}.
238      *
239      * @param certChainFile an X.509 certificate chain file in PEM format
240      * @param keyFile a PKCS#8 private key file in PEM format
241      * @param keyPassword the password of the {@code keyFile}.
242      *                    {@code null} if it's not password-protected.
243      * @param ciphers the cipher suites to enable, in the order of preference.
244      *                {@code null} to use the default cipher suites.
245      * @param cipherFilter a filter to apply over the supplied list of ciphers
246      * @param apn Provides a means to configure parameters related to application protocol negotiation.
247      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
248      *                         {@code 0} to use the default value.
249      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
250      *                       {@code 0} to use the default value.
251      * @return a new server-side {@link SslContext}
252      * @deprecated Replaced by {@link SslContextBuilder}
253      */
254     @Deprecated
255     public static SslContext newServerContext(
256             File certChainFile, File keyFile, String keyPassword,
257             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
258             long sessionCacheSize, long sessionTimeout) throws SSLException {
259         return newServerContext(
260                 null, certChainFile, keyFile, keyPassword,
261                 ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout);
262     }
263 
264     /**
265      * Creates a new server-side {@link SslContext}.
266      *
267      * @param provider the {@link SslContext} implementation to use.
268      *                 {@code null} to use the current default one.
269      * @param certChainFile an X.509 certificate chain file in PEM format
270      * @param keyFile a PKCS#8 private key file in PEM format
271      * @return a new server-side {@link SslContext}
272      * @deprecated Replaced by {@link SslContextBuilder}
273      */
274     @Deprecated
275     public static SslContext newServerContext(
276             SslProvider provider, File certChainFile, File keyFile) throws SSLException {
277         return newServerContext(provider, certChainFile, keyFile, null);
278     }
279 
280     /**
281      * Creates a new server-side {@link SslContext}.
282      *
283      * @param provider the {@link SslContext} implementation to use.
284      *                 {@code null} to use the current default one.
285      * @param certChainFile an X.509 certificate chain file in PEM format
286      * @param keyFile a PKCS#8 private key file in PEM format
287      * @param keyPassword the password of the {@code keyFile}.
288      *                    {@code null} if it's not password-protected.
289      * @return a new server-side {@link SslContext}
290      * @deprecated Replaced by {@link SslContextBuilder}
291      */
292     @Deprecated
293     public static SslContext newServerContext(
294             SslProvider provider, File certChainFile, File keyFile, String keyPassword) throws SSLException {
295         return newServerContext(provider, certChainFile, keyFile, keyPassword, null, IdentityCipherSuiteFilter.INSTANCE,
296                                 null, 0, 0);
297     }
298 
299     /**
300      * Creates a new server-side {@link SslContext}.
301      *
302      * @param provider the {@link SslContext} implementation to use.
303      *                 {@code null} to use the current default one.
304      * @param certChainFile an X.509 certificate chain file in PEM format
305      * @param keyFile a PKCS#8 private key file in PEM format
306      * @param keyPassword the password of the {@code keyFile}.
307      *                    {@code null} if it's not password-protected.
308      * @param ciphers the cipher suites to enable, in the order of preference.
309      *                {@code null} to use the default cipher suites.
310      * @param nextProtocols the application layer protocols to accept, in the order of preference.
311      *                      {@code null} to disable TLS NPN/ALPN extension.
312      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
313      *                         {@code 0} to use the default value.
314      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
315      *                       {@code 0} to use the default value.
316      * @return a new server-side {@link SslContext}
317      * @deprecated Replaced by {@link SslContextBuilder}
318      */
319     @Deprecated
320     public static SslContext newServerContext(
321             SslProvider provider,
322             File certChainFile, File keyFile, String keyPassword,
323             Iterable<String> ciphers, Iterable<String> nextProtocols,
324             long sessionCacheSize, long sessionTimeout) throws SSLException {
325         return newServerContext(provider, certChainFile, keyFile, keyPassword,
326                                 ciphers, IdentityCipherSuiteFilter.INSTANCE,
327                                 toApplicationProtocolConfig(nextProtocols), sessionCacheSize, sessionTimeout);
328     }
329 
330     /**
331      * Creates a new server-side {@link SslContext}.
332      *
333      * @param provider the {@link SslContext} implementation to use.
334      *                 {@code null} to use the current default one.
335      * @param certChainFile an X.509 certificate chain file in PEM format
336      * @param keyFile a PKCS#8 private key file in PEM format
337      * @param keyPassword the password of the {@code keyFile}.
338      *                    {@code null} if it's not password-protected.
339      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
340      *                            that verifies the certificates sent from servers.
341      *                            {@code null} to use the default.
342      * @param ciphers the cipher suites to enable, in the order of preference.
343      *                {@code null} to use the default cipher suites.
344      * @param nextProtocols the application layer protocols to accept, in the order of preference.
345      *                      {@code null} to disable TLS NPN/ALPN extension.
346      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
347      *                         {@code 0} to use the default value.
348      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
349      *                       {@code 0} to use the default value.
350      * @return a new server-side {@link SslContext}
351      * @deprecated Replaced by {@link SslContextBuilder}
352      */
353     @Deprecated
354     public static SslContext newServerContext(
355             SslProvider provider,
356             File certChainFile, File keyFile, String keyPassword, TrustManagerFactory trustManagerFactory,
357             Iterable<String> ciphers, Iterable<String> nextProtocols,
358             long sessionCacheSize, long sessionTimeout) throws SSLException {
359 
360         return newServerContext(
361                 provider, null, trustManagerFactory, certChainFile, keyFile, keyPassword,
362                 null, ciphers, IdentityCipherSuiteFilter.INSTANCE,
363                 toApplicationProtocolConfig(nextProtocols), sessionCacheSize, sessionTimeout);
364     }
365 
366     /**
367      * Creates a new server-side {@link SslContext}.
368      *
369      * @param provider the {@link SslContext} implementation to use.
370      *                 {@code null} to use the current default one.
371      * @param certChainFile an X.509 certificate chain file in PEM format
372      * @param keyFile a PKCS#8 private key file in PEM format
373      * @param keyPassword the password of the {@code keyFile}.
374      *                    {@code null} if it's not password-protected.
375      * @param ciphers the cipher suites to enable, in the order of preference.
376      *                {@code null} to use the default cipher suites.
377      * @param cipherFilter a filter to apply over the supplied list of ciphers
378      *                Only required if {@code provider} is {@link SslProvider#JDK}
379      * @param apn Provides a means to configure parameters related to application protocol negotiation.
380      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
381      *                         {@code 0} to use the default value.
382      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
383      *                       {@code 0} to use the default value.
384      * @return a new server-side {@link SslContext}
385      * @deprecated Replaced by {@link SslContextBuilder}
386      */
387     @Deprecated
388     public static SslContext newServerContext(SslProvider provider,
389             File certChainFile, File keyFile, String keyPassword,
390             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
391             long sessionCacheSize, long sessionTimeout) throws SSLException {
392         return newServerContext(provider, null, null, certChainFile, keyFile, keyPassword, null,
393                 ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, KeyStore.getDefaultType(),
394                 SessionIdContextBuilder.randomSessionIdContext());
395     }
396 
397     /**
398      * Creates a new server-side {@link SslContext}.
399      * @param provider the {@link SslContext} implementation to use.
400      *                 {@code null} to use the current default one.
401      * @param trustCertCollectionFile an X.509 certificate collection file in PEM format.
402      *                      This provides the certificate collection used for mutual authentication.
403      *                      {@code null} to use the system default
404      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
405      *                            that verifies the certificates sent from clients.
406      *                            {@code null} to use the default or the results of parsing
407      *                            {@code trustCertCollectionFile}.
408      *                            This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}.
409      * @param keyCertChainFile an X.509 certificate chain file in PEM format
410      * @param keyFile a PKCS#8 private key file in PEM format
411      * @param keyPassword the password of the {@code keyFile}.
412      *                    {@code null} if it's not password-protected.
413      * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s
414      *                          that is used to encrypt data being sent to clients.
415      *                          {@code null} to use the default or the results of parsing
416      *                          {@code keyCertChainFile} and {@code keyFile}.
417      *                          This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}.
418      * @param ciphers the cipher suites to enable, in the order of preference.
419      *                {@code null} to use the default cipher suites.
420      * @param cipherFilter a filter to apply over the supplied list of ciphers
421      *                Only required if {@code provider} is {@link SslProvider#JDK}
422      * @param apn Provides a means to configure parameters related to application protocol negotiation.
423      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
424      *                         {@code 0} to use the default value.
425      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
426      *                       {@code 0} to use the default value.
427      * @return a new server-side {@link SslContext}
428      * @deprecated Replaced by {@link SslContextBuilder}
429      */
430     @Deprecated
431     public static SslContext newServerContext(
432             SslProvider provider,
433             File trustCertCollectionFile, TrustManagerFactory trustManagerFactory,
434             File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory,
435             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
436             long sessionCacheSize, long sessionTimeout) throws SSLException {
437         return newServerContext(provider, trustCertCollectionFile, trustManagerFactory, keyCertChainFile,
438                 keyFile, keyPassword, keyManagerFactory, ciphers, cipherFilter, apn,
439                 sessionCacheSize, sessionTimeout, KeyStore.getDefaultType(),
440                 SessionIdContextBuilder.randomSessionIdContext());
441     }
442 
443     /**
444      * Creates a new server-side {@link SslContext}.
445      * @param provider the {@link SslContext} implementation to use.
446      *                 {@code null} to use the current default one.
447      * @param trustCertCollectionFile an X.509 certificate collection file in PEM format.
448      *                      This provides the certificate collection used for mutual authentication.
449      *                      {@code null} to use the system default
450      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
451      *                            that verifies the certificates sent from clients.
452      *                            {@code null} to use the default or the results of parsing
453      *                            {@code trustCertCollectionFile}.
454      *                            This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}.
455      * @param keyCertChainFile an X.509 certificate chain file in PEM format
456      * @param keyFile a PKCS#8 private key file in PEM format
457      * @param keyPassword the password of the {@code keyFile}.
458      *                    {@code null} if it's not password-protected.
459      * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s
460      *                          that is used to encrypt data being sent to clients.
461      *                          {@code null} to use the default or the results of parsing
462      *                          {@code keyCertChainFile} and {@code keyFile}.
463      *                          This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}.
464      * @param ciphers the cipher suites to enable, in the order of preference.
465      *                {@code null} to use the default cipher suites.
466      * @param cipherFilter a filter to apply over the supplied list of ciphers
467      *                Only required if {@code provider} is {@link SslProvider#JDK}
468      * @param apn Provides a means to configure parameters related to application protocol negotiation.
469      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
470      *                         {@code 0} to use the default value.
471      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
472      *                       {@code 0} to use the default value.
473      * @param keyStore the keystore type that should  be used
474      * @return a new server-side {@link SslContext}
475      */
476     static SslContext newServerContext(
477             SslProvider provider,
478             File trustCertCollectionFile, TrustManagerFactory trustManagerFactory,
479             File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory,
480             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
481             long sessionCacheSize, long sessionTimeout, String keyStore,
482             SessionIdContextBuilder sessionIdContextBuilder) throws SSLException {
483         try {
484             return newServerContextInternal(provider, null, toX509Certificates(trustCertCollectionFile),
485                                             trustManagerFactory, toX509Certificates(keyCertChainFile),
486                                             toPrivateKey(keyFile, keyPassword),
487                                             keyPassword, keyManagerFactory, ciphers, cipherFilter, apn,
488                                             sessionCacheSize, sessionTimeout, ClientAuth.NONE, null,
489                                             false, false, null, keyStore, null, null, sessionIdContextBuilder);
490         } catch (Exception e) {
491             if (e instanceof SSLException) {
492                 throw (SSLException) e;
493             }
494             throw new SSLException("failed to initialize the server-side SSL context", e);
495         }
496     }
497 
498     static SslContext newServerContextInternal(
499             SslProvider provider,
500             Provider sslContextProvider,
501             X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
502             X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
503             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
504             long sessionCacheSize, long sessionTimeout, ClientAuth clientAuth, String[] protocols, boolean startTls,
505             boolean enableOcsp, SecureRandom secureRandom, String keyStoreType,
506             Map.Entry<SslContextOption<?>, Object>[] ctxOptions,
507             List<OpenSslCredential> credentials, SessionIdContextBuilder sessionIdContextBuilder)
508             throws SSLException {
509 
510         if (provider == null) {
511             provider = defaultServerProvider();
512         }
513 
514         ResumptionController resumptionController = new ResumptionController();
515 
516         switch (provider) {
517         case JDK:
518             if (enableOcsp) {
519                 throw new IllegalArgumentException("OCSP is not supported with this SslProvider: " + provider);
520             }
521             if (credentials != null && !credentials.isEmpty()) {
522                 throw new IllegalArgumentException(
523                         "OpenSslCredential is not supported with SslProvider.JDK. " +
524                                 "Use SslProvider.OPENSSL or SslProvider.OPENSSL_REFCNT instead.");
525             }
526             return new JdkSslServerContext(sslContextProvider,
527                     trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword,
528                     keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout,
529                     clientAuth, protocols, startTls, secureRandom, keyStoreType, resumptionController);
530         case OPENSSL:
531             verifyNullSslContextProvider(provider, sslContextProvider);
532             return new OpenSslServerContext(
533                     trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword,
534                     keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout,
535                     clientAuth, protocols, startTls, enableOcsp, keyStoreType, resumptionController,
536                     sessionIdContextBuilder, ctxOptions, credentials);
537         case OPENSSL_REFCNT:
538             verifyNullSslContextProvider(provider, sslContextProvider);
539             return new ReferenceCountedOpenSslServerContext(
540                     trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword,
541                     keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout,
542                     clientAuth, protocols, startTls, enableOcsp, keyStoreType, resumptionController,
543                     sessionIdContextBuilder, ctxOptions, credentials);
544         default:
545             throw new Error("Unexpected provider: " + provider);
546         }
547     }
548 
549     private static void verifyNullSslContextProvider(SslProvider provider, Provider sslContextProvider) {
550         if (sslContextProvider != null) {
551             throw new IllegalArgumentException("Java Security Provider unsupported for SslProvider: " + provider);
552         }
553     }
554 
555     /**
556      * Creates a new client-side {@link SslContext}.
557      *
558      * @return a new client-side {@link SslContext}
559      * @deprecated Replaced by {@link SslContextBuilder}
560      */
561     @Deprecated
562     public static SslContext newClientContext() throws SSLException {
563         return newClientContext(null, null, null);
564     }
565 
566     /**
567      * Creates a new client-side {@link SslContext}.
568      *
569      * @param certChainFile an X.509 certificate chain file in PEM format
570      *
571      * @return a new client-side {@link SslContext}
572      * @deprecated Replaced by {@link SslContextBuilder}
573      */
574     @Deprecated
575     public static SslContext newClientContext(File certChainFile) throws SSLException {
576         return newClientContext(null, certChainFile);
577     }
578 
579     /**
580      * Creates a new client-side {@link SslContext}.
581      *
582      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
583      *                            that verifies the certificates sent from servers.
584      *                            {@code null} to use the default.
585      *
586      * @return a new client-side {@link SslContext}
587      * @deprecated Replaced by {@link SslContextBuilder}
588      */
589     @Deprecated
590     public static SslContext newClientContext(TrustManagerFactory trustManagerFactory) throws SSLException {
591         return newClientContext(null, null, trustManagerFactory);
592     }
593 
594     /**
595      * Creates a new client-side {@link SslContext}.
596      *
597      * @param certChainFile an X.509 certificate chain file in PEM format.
598      *                      {@code null} to use the system default
599      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
600      *                            that verifies the certificates sent from servers.
601      *                            {@code null} to use the default.
602      *
603      * @return a new client-side {@link SslContext}
604      * @deprecated Replaced by {@link SslContextBuilder}
605      */
606     @Deprecated
607     public static SslContext newClientContext(
608             File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException {
609         return newClientContext(null, certChainFile, trustManagerFactory);
610     }
611 
612     /**
613      * Creates a new client-side {@link SslContext}.
614      *
615      * @param certChainFile an X.509 certificate chain file in PEM format.
616      *                      {@code null} to use the system default
617      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
618      *                            that verifies the certificates sent from servers.
619      *                            {@code null} to use the default.
620      * @param ciphers the cipher suites to enable, in the order of preference.
621      *                {@code null} to use the default cipher suites.
622      * @param nextProtocols the application layer protocols to accept, in the order of preference.
623      *                      {@code null} to disable TLS NPN/ALPN extension.
624      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
625      *                         {@code 0} to use the default value.
626      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
627      *                       {@code 0} to use the default value.
628      *
629      * @return a new client-side {@link SslContext}
630      * @deprecated Replaced by {@link SslContextBuilder}
631      */
632     @Deprecated
633     public static SslContext newClientContext(
634             File certChainFile, TrustManagerFactory trustManagerFactory,
635             Iterable<String> ciphers, Iterable<String> nextProtocols,
636             long sessionCacheSize, long sessionTimeout) throws SSLException {
637         return newClientContext(
638                 null, certChainFile, trustManagerFactory,
639                 ciphers, nextProtocols, sessionCacheSize, sessionTimeout);
640     }
641 
642     /**
643      * Creates a new client-side {@link SslContext}.
644      *
645      * @param certChainFile an X.509 certificate chain file in PEM format.
646      *                      {@code null} to use the system default
647      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
648      *                            that verifies the certificates sent from servers.
649      *                            {@code null} to use the default.
650      * @param ciphers the cipher suites to enable, in the order of preference.
651      *                {@code null} to use the default cipher suites.
652      * @param cipherFilter a filter to apply over the supplied list of ciphers
653      * @param apn Provides a means to configure parameters related to application protocol negotiation.
654      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
655      *                         {@code 0} to use the default value.
656      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
657      *                       {@code 0} to use the default value.
658      *
659      * @return a new client-side {@link SslContext}
660      * @deprecated Replaced by {@link SslContextBuilder}
661      */
662     @Deprecated
663     public static SslContext newClientContext(
664             File certChainFile, TrustManagerFactory trustManagerFactory,
665             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
666             long sessionCacheSize, long sessionTimeout) throws SSLException {
667         return newClientContext(
668                 null, certChainFile, trustManagerFactory,
669                 ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout);
670     }
671 
672     /**
673      * Creates a new client-side {@link SslContext}.
674      *
675      * @param provider the {@link SslContext} implementation to use.
676      *                 {@code null} to use the current default one.
677      *
678      * @return a new client-side {@link SslContext}
679      * @deprecated Replaced by {@link SslContextBuilder}
680      */
681     @Deprecated
682     public static SslContext newClientContext(SslProvider provider) throws SSLException {
683         return newClientContext(provider, null, null);
684     }
685 
686     /**
687      * Creates a new client-side {@link SslContext}.
688      *
689      * @param provider the {@link SslContext} implementation to use.
690      *                 {@code null} to use the current default one.
691      * @param certChainFile an X.509 certificate chain file in PEM format.
692      *                      {@code null} to use the system default
693      *
694      * @return a new client-side {@link SslContext}
695      * @deprecated Replaced by {@link SslContextBuilder}
696      */
697     @Deprecated
698     public static SslContext newClientContext(SslProvider provider, File certChainFile) throws SSLException {
699         return newClientContext(provider, certChainFile, null);
700     }
701 
702     /**
703      * Creates a new client-side {@link SslContext}.
704      *
705      * @param provider the {@link SslContext} implementation to use.
706      *                 {@code null} to use the current default one.
707      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
708      *                            that verifies the certificates sent from servers.
709      *                            {@code null} to use the default.
710      *
711      * @return a new client-side {@link SslContext}
712      * @deprecated Replaced by {@link SslContextBuilder}
713      */
714     @Deprecated
715     public static SslContext newClientContext(
716             SslProvider provider, TrustManagerFactory trustManagerFactory) throws SSLException {
717         return newClientContext(provider, null, trustManagerFactory);
718     }
719 
720     /**
721      * Creates a new client-side {@link SslContext}.
722      *
723      * @param provider the {@link SslContext} implementation to use.
724      *                 {@code null} to use the current default one.
725      * @param certChainFile an X.509 certificate chain file in PEM format.
726      *                      {@code null} to use the system default
727      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
728      *                            that verifies the certificates sent from servers.
729      *                            {@code null} to use the default.
730      *
731      * @return a new client-side {@link SslContext}
732      * @deprecated Replaced by {@link SslContextBuilder}
733      */
734     @Deprecated
735     public static SslContext newClientContext(
736             SslProvider provider, File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException {
737         return newClientContext(provider, certChainFile, trustManagerFactory, null, IdentityCipherSuiteFilter.INSTANCE,
738                 null, 0, 0);
739     }
740 
741     /**
742      * Creates a new client-side {@link SslContext}.
743      *
744      * @param provider the {@link SslContext} implementation to use.
745      *                 {@code null} to use the current default one.
746      * @param certChainFile an X.509 certificate chain file in PEM format.
747      *                      {@code null} to use the system default
748      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
749      *                            that verifies the certificates sent from servers.
750      *                            {@code null} to use the default.
751      * @param ciphers the cipher suites to enable, in the order of preference.
752      *                {@code null} to use the default cipher suites.
753      * @param nextProtocols the application layer protocols to accept, in the order of preference.
754      *                      {@code null} to disable TLS NPN/ALPN extension.
755      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
756      *                         {@code 0} to use the default value.
757      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
758      *                       {@code 0} to use the default value.
759      *
760      * @return a new client-side {@link SslContext}
761      * @deprecated Replaced by {@link SslContextBuilder}
762      */
763     @Deprecated
764     public static SslContext newClientContext(
765             SslProvider provider,
766             File certChainFile, TrustManagerFactory trustManagerFactory,
767             Iterable<String> ciphers, Iterable<String> nextProtocols,
768             long sessionCacheSize, long sessionTimeout) throws SSLException {
769         return newClientContext(
770                 provider, certChainFile, trustManagerFactory, null, null, null, null,
771                 ciphers, IdentityCipherSuiteFilter.INSTANCE,
772                 toApplicationProtocolConfig(nextProtocols), sessionCacheSize, sessionTimeout);
773     }
774 
775     /**
776      * Creates a new client-side {@link SslContext}.
777      *
778      * @param provider the {@link SslContext} implementation to use.
779      *                 {@code null} to use the current default one.
780      * @param certChainFile an X.509 certificate chain file in PEM format.
781      *                      {@code null} to use the system default
782      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
783      *                            that verifies the certificates sent from servers.
784      *                            {@code null} to use the default.
785      * @param ciphers the cipher suites to enable, in the order of preference.
786      *                {@code null} to use the default cipher suites.
787      * @param cipherFilter a filter to apply over the supplied list of ciphers
788      * @param apn Provides a means to configure parameters related to application protocol negotiation.
789      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
790      *                         {@code 0} to use the default value.
791      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
792      *                       {@code 0} to use the default value.
793      *
794      * @return a new client-side {@link SslContext}
795      * @deprecated Replaced by {@link SslContextBuilder}
796      */
797     @Deprecated
798     public static SslContext newClientContext(
799             SslProvider provider,
800             File certChainFile, TrustManagerFactory trustManagerFactory,
801             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
802             long sessionCacheSize, long sessionTimeout) throws SSLException {
803 
804         return newClientContext(
805                 provider, certChainFile, trustManagerFactory, null, null, null, null,
806                 ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout);
807     }
808 
809     /**
810      * Creates a new client-side {@link SslContext}.
811      * @param provider the {@link SslContext} implementation to use.
812      *                 {@code null} to use the current default one.
813      * @param trustCertCollectionFile an X.509 certificate collection file in PEM format.
814      *                      {@code null} to use the system default
815      * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
816      *                            that verifies the certificates sent from servers.
817      *                            {@code null} to use the default or the results of parsing
818      *                            {@code trustCertCollectionFile}.
819      *                            This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}.
820      * @param keyCertChainFile an X.509 certificate chain file in PEM format.
821      *                      This provides the public key for mutual authentication.
822      *                      {@code null} to use the system default
823      * @param keyFile a PKCS#8 private key file in PEM format.
824      *                      This provides the private key for mutual authentication.
825      *                      {@code null} for no mutual authentication.
826      * @param keyPassword the password of the {@code keyFile}.
827      *                    {@code null} if it's not password-protected.
828      *                    Ignored if {@code keyFile} is {@code null}.
829      * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s
830      *                          that is used to encrypt data being sent to servers.
831      *                          {@code null} to use the default or the results of parsing
832      *                          {@code keyCertChainFile} and {@code keyFile}.
833      *                          This parameter is ignored if {@code provider} is not {@link SslProvider#JDK}.
834      * @param ciphers the cipher suites to enable, in the order of preference.
835      *                {@code null} to use the default cipher suites.
836      * @param cipherFilter a filter to apply over the supplied list of ciphers
837      * @param apn Provides a means to configure parameters related to application protocol negotiation.
838      * @param sessionCacheSize the size of the cache used for storing SSL session objects.
839      *                         {@code 0} to use the default value.
840      * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
841      *                       {@code 0} to use the default value.
842      *
843      * @return a new client-side {@link SslContext}
844      * @deprecated Replaced by {@link SslContextBuilder}
845      */
846     @Deprecated
847     public static SslContext newClientContext(
848         SslProvider provider,
849         File trustCertCollectionFile, TrustManagerFactory trustManagerFactory,
850         File keyCertChainFile, File keyFile, String keyPassword,
851         KeyManagerFactory keyManagerFactory,
852         Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
853         long sessionCacheSize, long sessionTimeout) throws SSLException {
854         try {
855             return newClientContextInternal(provider, null,
856                                             toX509Certificates(trustCertCollectionFile), trustManagerFactory,
857                                             toX509Certificates(keyCertChainFile), toPrivateKey(keyFile, keyPassword),
858                                             keyPassword, keyManagerFactory, ciphers, cipherFilter,
859                                             apn, null, sessionCacheSize, sessionTimeout, false,
860                                             null, KeyStore.getDefaultType(),
861                                             defaultEndpointVerificationAlgorithm,
862                                             Collections.emptyList(), null, null,
863                                             SessionIdContextBuilder.randomSessionIdContext());
864         } catch (Exception e) {
865             if (e instanceof SSLException) {
866                 throw (SSLException) e;
867             }
868             throw new SSLException("failed to initialize the client-side SSL context", e);
869         }
870     }
871 
872     static SslContext newClientContextInternal(
873             SslProvider provider,
874             Provider sslContextProvider,
875             X509Certificate[] trustCert, TrustManagerFactory trustManagerFactory,
876             X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
877             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, String[] protocols,
878             long sessionCacheSize, long sessionTimeout, boolean enableOcsp,
879             SecureRandom secureRandom, String keyStoreType, String endpointIdentificationAlgorithm,
880             List<SNIServerName> serverNames,
881             Map.Entry<SslContextOption<?>, Object>[] options,
882             List<OpenSslCredential> credentials, SessionIdContextBuilder sessionIdContextBuilder) throws SSLException {
883         return newClientContextInternal(provider, sslContextProvider, trustCert, trustManagerFactory, keyCertChain, key,
884                 keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize, sessionTimeout,
885                 false, enableOcsp, secureRandom, keyStoreType, endpointIdentificationAlgorithm, serverNames, options,
886                 credentials, sessionIdContextBuilder);
887     }
888 
889     static SslContext newClientContextInternal(
890             SslProvider provider,
891             Provider sslContextProvider,
892             X509Certificate[] trustCert, TrustManagerFactory trustManagerFactory,
893             X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
894             Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, String[] protocols,
895             long sessionCacheSize, long sessionTimeout, boolean startTls, boolean enableOcsp,
896             SecureRandom secureRandom, String keyStoreType, String endpointIdentificationAlgorithm,
897             List<SNIServerName> serverNames,
898             Map.Entry<SslContextOption<?>, Object>[] options,
899             List<OpenSslCredential> credentials, SessionIdContextBuilder sessionIdContextBuilder) throws SSLException {
900         if (provider == null) {
901             provider = defaultClientProvider();
902         }
903 
904         ResumptionController resumptionController = new ResumptionController();
905 
906         switch (provider) {
907             case JDK:
908                 if (enableOcsp) {
909                     throw new IllegalArgumentException("OCSP is not supported with this SslProvider: " + provider);
910                 }
911                 if (credentials != null && !credentials.isEmpty()) {
912                     throw new IllegalArgumentException(
913                             "OpenSslCredential is not supported with SslProvider.JDK. " +
914                                     "Use SslProvider.OPENSSL or SslProvider.OPENSSL_REFCNT instead.");
915                 }
916                 return new JdkSslClientContext(sslContextProvider,
917                         trustCert, trustManagerFactory, keyCertChain, key, keyPassword,
918                         keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize,
919                         sessionTimeout, secureRandom, keyStoreType, endpointIdentificationAlgorithm,
920                         serverNames, resumptionController);
921             case OPENSSL:
922                 verifyNullSslContextProvider(provider, sslContextProvider);
923                 OpenSsl.ensureAvailability();
924                 return new OpenSslClientContext(
925                         trustCert, trustManagerFactory, keyCertChain, key, keyPassword,
926                         keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize, sessionTimeout,
927                         startTls, enableOcsp, keyStoreType, endpointIdentificationAlgorithm, serverNames,
928                         resumptionController, options, credentials);
929             case OPENSSL_REFCNT:
930                 verifyNullSslContextProvider(provider, sslContextProvider);
931                 OpenSsl.ensureAvailability();
932                 return new ReferenceCountedOpenSslClientContext(
933                         trustCert, trustManagerFactory, keyCertChain, key, keyPassword,
934                         keyManagerFactory, ciphers, cipherFilter, apn, protocols, sessionCacheSize, sessionTimeout,
935                         startTls, enableOcsp, keyStoreType, endpointIdentificationAlgorithm, serverNames,
936                         resumptionController, options, credentials);
937             default:
938                 throw new Error("Unexpected provider: " + provider);
939         }
940     }
941 
942     static ApplicationProtocolConfig toApplicationProtocolConfig(Iterable<String> nextProtocols) {
943         ApplicationProtocolConfig apn;
944         if (nextProtocols == null) {
945             apn = ApplicationProtocolConfig.DISABLED;
946         } else {
947             apn = new ApplicationProtocolConfig(
948                     Protocol.NPN_AND_ALPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
949                     SelectedListenerFailureBehavior.ACCEPT, nextProtocols);
950         }
951         return apn;
952     }
953 
954     /**
955      * Creates a new instance (startTls set to {@code false}).
956      */
957     protected SslContext() {
958         this(false);
959     }
960 
961     /**
962      * Creates a new instance.
963      */
964     protected SslContext(boolean startTls) {
965         this(startTls, null);
966     }
967 
968     SslContext(boolean startTls, ResumptionController resumptionController) {
969         this.startTls = startTls;
970         this.resumptionController = resumptionController;
971     }
972 
973     /**
974      * Returns the {@link AttributeMap} that belongs to this {@link SslContext} .
975      */
976     public final AttributeMap attributes() {
977         return attributes;
978     }
979 
980     /**
981      * Returns {@code true} if and only if this context is for server-side.
982      */
983     public final boolean isServer() {
984         return !isClient();
985     }
986 
987     /**
988      * Returns the {@code true} if and only if this context is for client-side.
989      */
990     public abstract boolean isClient();
991 
992     /**
993      * Returns the list of enabled cipher suites, in the order of preference.
994      */
995     public abstract List<String> cipherSuites();
996 
997     /**
998      * Returns the size of the cache used for storing SSL session objects.
999      */
1000     public long sessionCacheSize() {
1001         return sessionContext().getSessionCacheSize();
1002     }
1003 
1004     /**
1005      * Returns the timeout for the cached SSL session objects, in seconds.
1006      */
1007     public long sessionTimeout() {
1008         return sessionContext().getSessionTimeout();
1009     }
1010 
1011     /**
1012      * @deprecated Use {@link #applicationProtocolNegotiator()} instead.
1013      */
1014     @Deprecated
1015     public final List<String> nextProtocols() {
1016         return applicationProtocolNegotiator().protocols();
1017     }
1018 
1019     /**
1020      * Returns the object responsible for negotiating application layer protocols for the TLS NPN/ALPN extensions.
1021      */
1022     public abstract ApplicationProtocolNegotiator applicationProtocolNegotiator();
1023 
1024     /**
1025      * Creates a new {@link SSLEngine}.
1026      * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the object must be released. One way to do this is to
1027      * wrap in a {@link SslHandler} and insert it into a pipeline. See {@link #newHandler(ByteBufAllocator)}.
1028      * @return a new {@link SSLEngine}
1029      */
1030     public abstract SSLEngine newEngine(ByteBufAllocator alloc);
1031 
1032     /**
1033      * Creates a new {@link SSLEngine} using advisory peer information.
1034      * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the object must be released. One way to do this is to
1035      * wrap in a {@link SslHandler} and insert it into a pipeline.
1036      * See {@link #newHandler(ByteBufAllocator, String, int)}.
1037      * @param peerHost the non-authoritative name of the host
1038      * @param peerPort the non-authoritative port
1039      *
1040      * @return a new {@link SSLEngine}
1041      */
1042     public abstract SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort);
1043 
1044     /**
1045      * Returns the {@link SSLSessionContext} object held by this context.
1046      */
1047     public abstract SSLSessionContext sessionContext();
1048 
1049     /**
1050      * Create a new SslHandler.
1051      * @see #newHandler(ByteBufAllocator, Executor)
1052      */
1053     public final SslHandler newHandler(ByteBufAllocator alloc) {
1054         return newHandler(alloc, startTls);
1055     }
1056 
1057     /**
1058      * Create a new SslHandler.
1059      * @see #newHandler(ByteBufAllocator)
1060      */
1061     protected SslHandler newHandler(ByteBufAllocator alloc, boolean startTls) {
1062         return new SslHandler(newEngine(alloc), startTls, ImmediateExecutor.INSTANCE, resumptionController);
1063     }
1064 
1065     /**
1066      * Creates a new {@link SslHandler}.
1067      * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the returned {@link SslHandler} will release the engine
1068      * that is wrapped. If the returned {@link SslHandler} is not inserted into a pipeline then you may leak native
1069      * memory!
1070      * <p><b>Beware</b>: the underlying generated {@link SSLEngine} won't have
1071      * <a href="https://wiki.openssl.org/index.php/Hostname_validation">hostname verification</a> enabled by default.
1072      * If you create {@link SslHandler} for the client side and want proper security, we advice that you configure
1073      * the {@link SSLEngine} (see {@link javax.net.ssl.SSLParameters#setEndpointIdentificationAlgorithm(String)}):
1074      * <pre>
1075      * SSLEngine sslEngine = sslHandler.engine();
1076      * SSLParameters sslParameters = sslEngine.getSSLParameters();
1077      * // only available since Java 7
1078      * sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
1079      * sslEngine.setSSLParameters(sslParameters);
1080      * </pre>
1081      * <p>
1082      * The underlying {@link SSLEngine} may not follow the restrictions imposed by the
1083      * <a href="https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html">SSLEngine javadocs</a> which
1084      * limits wrap/unwrap to operate on a single SSL/TLS packet.
1085      * @param alloc If supported by the SSLEngine then the SSLEngine will use this to allocate ByteBuf objects.
1086      * @param delegatedTaskExecutor the {@link Executor} that will be used to execute tasks that are returned by
1087      *                              {@link SSLEngine#getDelegatedTask()}.
1088      * @return a new {@link SslHandler}
1089      */
1090     public SslHandler newHandler(ByteBufAllocator alloc, Executor delegatedTaskExecutor) {
1091         return newHandler(alloc, startTls, delegatedTaskExecutor);
1092     }
1093 
1094     /**
1095      * Create a new SslHandler.
1096      * @see #newHandler(ByteBufAllocator, String, int, boolean, Executor)
1097      */
1098     protected SslHandler newHandler(ByteBufAllocator alloc, boolean startTls, Executor executor) {
1099         return new SslHandler(newEngine(alloc), startTls, executor, resumptionController);
1100     }
1101 
1102     /**
1103      * Creates a new {@link SslHandler}
1104      *
1105      * @see #newHandler(ByteBufAllocator, String, int, Executor)
1106      */
1107     public final SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort) {
1108         return newHandler(alloc, peerHost, peerPort, startTls);
1109     }
1110 
1111     /**
1112      * Create a new SslHandler.
1113      * @see #newHandler(ByteBufAllocator, String, int, boolean, Executor)
1114      */
1115     protected SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, boolean startTls) {
1116         return new SslHandler(newEngine(alloc, peerHost, peerPort), startTls, ImmediateExecutor.INSTANCE,
1117                 resumptionController);
1118     }
1119 
1120     /**
1121      * Creates a new {@link SslHandler} with advisory peer information.
1122      * <p>If {@link SslProvider#OPENSSL_REFCNT} is used then the returned {@link SslHandler} will release the engine
1123      * that is wrapped. If the returned {@link SslHandler} is not inserted into a pipeline then you may leak native
1124      * memory!
1125      * <p><b>Beware</b>: the underlying generated {@link SSLEngine} won't have
1126      * <a href="https://wiki.openssl.org/index.php/Hostname_validation">hostname verification</a> enabled by default.
1127      * If you create {@link SslHandler} for the client side and want proper security, we advice that you configure
1128      * the {@link SSLEngine} (see {@link javax.net.ssl.SSLParameters#setEndpointIdentificationAlgorithm(String)}):
1129      * <pre>
1130      * SSLEngine sslEngine = sslHandler.engine();
1131      * SSLParameters sslParameters = sslEngine.getSSLParameters();
1132      * // only available since Java 7
1133      * sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
1134      * sslEngine.setSSLParameters(sslParameters);
1135      * </pre>
1136      * <p>
1137      * The underlying {@link SSLEngine} may not follow the restrictions imposed by the
1138      * <a href="https://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html">SSLEngine javadocs</a> which
1139      * limits wrap/unwrap to operate on a single SSL/TLS packet.
1140      * @param alloc If supported by the SSLEngine then the SSLEngine will use this to allocate ByteBuf objects.
1141      * @param peerHost the non-authoritative name of the host
1142      * @param peerPort the non-authoritative port
1143      * @param delegatedTaskExecutor the {@link Executor} that will be used to execute tasks that are returned by
1144      *                              {@link SSLEngine#getDelegatedTask()}.
1145      *
1146      * @return a new {@link SslHandler}
1147      */
1148     public SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort,
1149                                  Executor delegatedTaskExecutor) {
1150         return newHandler(alloc, peerHost, peerPort, startTls, delegatedTaskExecutor);
1151     }
1152 
1153     protected SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, boolean startTls,
1154                                     Executor delegatedTaskExecutor) {
1155         return new SslHandler(newEngine(alloc, peerHost, peerPort), startTls, delegatedTaskExecutor,
1156                 resumptionController);
1157     }
1158 
1159     /**
1160      * Generates a key specification for an (encrypted) private key.
1161      *
1162      * @param password characters, if {@code null} an unencrypted key is assumed
1163      * @param key bytes of the DER encoded private key
1164      *
1165      * @return a key specification
1166      *
1167      * @throws IOException if parsing {@code key} fails
1168      * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unknown
1169      * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unknown
1170      * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
1171      * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
1172      *                             {@code key}
1173      * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
1174      */
1175     @Deprecated
1176     protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
1177             throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
1178             InvalidKeyException, InvalidAlgorithmParameterException {
1179 
1180         if (password == null) {
1181             return new PKCS8EncodedKeySpec(key);
1182         }
1183 
1184         EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
1185         String pbeAlgorithm = getPBEAlgorithm(encryptedPrivateKeyInfo);
1186         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(pbeAlgorithm);
1187         PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
1188         SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
1189 
1190         Cipher cipher = Cipher.getInstance(pbeAlgorithm);
1191         cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());
1192 
1193         return encryptedPrivateKeyInfo.getKeySpec(cipher);
1194     }
1195 
1196     private static String getPBEAlgorithm(EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) {
1197         AlgorithmParameters parameters = encryptedPrivateKeyInfo.getAlgParameters();
1198         String algName = encryptedPrivateKeyInfo.getAlgName();
1199         // Java 8 ~ 16 returns OID_PKCS5_PBES2
1200         // Java 17+ returns PBES2
1201         if (parameters != null && (OID_PKCS5_PBES2.equals(algName) || PBES2.equals(algName))) {
1202             /*
1203              * This should be "PBEWith<prf>And<encryption>".
1204              * Relying on the toString() implementation is potentially
1205              * fragile but acceptable in this case since the JRE depends on
1206              * the toString() implementation as well.
1207              * In the future, if necessary, we can parse the value of
1208              * parameters.getEncoded() but the associated complexity and
1209              * unlikeliness of the JRE implementation changing means that
1210              * Tomcat will use to toString() approach for now.
1211              */
1212             return parameters.toString();
1213         }
1214         return encryptedPrivateKeyInfo.getAlgName();
1215     }
1216 
1217     /**
1218      * Generates a new {@link KeyStore}.
1219      *
1220      * @param certChain an X.509 certificate chain
1221      * @param key a PKCS#8 private key
1222      * @param keyPasswordChars the password of the {@code keyFile}.
1223      *                    {@code null} if it's not password-protected.
1224      * @param keyStoreType The KeyStore Type you want to use
1225      * @return generated {@link KeyStore}.
1226      */
1227     protected static KeyStore buildKeyStore(X509Certificate[] certChain, PrivateKey key,
1228                                   char[] keyPasswordChars, String keyStoreType)
1229             throws KeyStoreException, NoSuchAlgorithmException,
1230                    CertificateException, IOException {
1231         if (keyStoreType == null) {
1232             keyStoreType = KeyStore.getDefaultType();
1233         }
1234         KeyStore ks = KeyStore.getInstance(keyStoreType);
1235         ks.load(null, null);
1236         ks.setKeyEntry(ALIAS, key, keyPasswordChars, certChain);
1237         return ks;
1238     }
1239 
1240     protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException,
1241                                                                 NoSuchPaddingException, InvalidKeySpecException,
1242                                                                 InvalidAlgorithmParameterException,
1243                                                                 KeyException, IOException {
1244         return toPrivateKey(keyFile, keyPassword, true);
1245     }
1246 
1247     static PrivateKey toPrivateKey(File keyFile, String keyPassword, boolean tryBouncyCastle)
1248             throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
1249             InvalidAlgorithmParameterException,
1250             KeyException, IOException {
1251         if (keyFile == null) {
1252             return null;
1253         }
1254 
1255         // try BC first, if this fail fallback to original key extraction process
1256         if (tryBouncyCastle && BouncyCastleUtil.isBcPkixAvailable()) {
1257             PrivateKey pk = BouncyCastlePemReader.getPrivateKey(keyFile, keyPassword);
1258             if (pk != null) {
1259                 return pk;
1260             }
1261         }
1262 
1263         return getPrivateKeyFromByteBuffer(PemReader.readPrivateKey(keyFile), keyPassword);
1264     }
1265 
1266     protected static PrivateKey toPrivateKey(InputStream keyInputStream, String keyPassword)
1267                                                                 throws NoSuchAlgorithmException,
1268                                                                 NoSuchPaddingException, InvalidKeySpecException,
1269                                                                 InvalidAlgorithmParameterException,
1270                                                                 KeyException, IOException {
1271         if (keyInputStream == null) {
1272             return null;
1273         }
1274 
1275         // try BC first, if this fail fallback to original key extraction process
1276         if (BouncyCastleUtil.isBcPkixAvailable()) {
1277             if (!keyInputStream.markSupported()) {
1278                 // We need an input stream that supports resetting, in case BouncyCastle fails to read.
1279                 keyInputStream = new BufferedInputStream(keyInputStream);
1280             }
1281             keyInputStream.mark(1048576); // Be able to reset up to 1 MiB of data.
1282             PrivateKey pk = BouncyCastlePemReader.getPrivateKey(keyInputStream, keyPassword);
1283             if (pk != null) {
1284                 return pk;
1285             }
1286             // BouncyCastle could not read the key. Reset the input stream in case the input position changed.
1287             keyInputStream.reset();
1288         }
1289 
1290         return getPrivateKeyFromByteBuffer(PemReader.readPrivateKey(keyInputStream), keyPassword);
1291     }
1292 
1293     private static PrivateKey getPrivateKeyFromByteBuffer(ByteBuf encodedKeyBuf, String keyPassword)
1294             throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
1295             InvalidAlgorithmParameterException, KeyException, IOException {
1296 
1297         byte[] encodedKey = new byte[encodedKeyBuf.readableBytes()];
1298         encodedKeyBuf.readBytes(encodedKey).release();
1299 
1300         PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec(
1301                 keyPassword == null ? null : keyPassword.toCharArray(), encodedKey);
1302         try {
1303             return KeyFactory.getInstance("RSA").generatePrivate(encodedKeySpec);
1304         } catch (InvalidKeySpecException ignore) {
1305             try {
1306                 return KeyFactory.getInstance("DSA").generatePrivate(encodedKeySpec);
1307             } catch (InvalidKeySpecException ignore2) {
1308                 try {
1309                     return KeyFactory.getInstance("EC").generatePrivate(encodedKeySpec);
1310                 } catch (InvalidKeySpecException e) {
1311                     throw new InvalidKeySpecException("Neither RSA, DSA nor EC worked", e);
1312                 }
1313             }
1314         }
1315     }
1316 
1317     /**
1318      * Build a {@link TrustManagerFactory} from a certificate chain file.
1319      * @param certChainFile The certificate file to build from.
1320      * @param trustManagerFactory The existing {@link TrustManagerFactory} that will be used if not {@code null}.
1321      * @return A {@link TrustManagerFactory} which contains the certificates in {@code certChainFile}
1322      */
1323     @Deprecated
1324     protected static TrustManagerFactory buildTrustManagerFactory(
1325             File certChainFile, TrustManagerFactory trustManagerFactory)
1326             throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
1327         return buildTrustManagerFactory(certChainFile, trustManagerFactory, null);
1328     }
1329 
1330     /**
1331      * Build a {@link TrustManagerFactory} from a certificate chain file.
1332      * @param certChainFile The certificate file to build from.
1333      * @param trustManagerFactory The existing {@link TrustManagerFactory} that will be used if not {@code null}.
1334      * @param keyType The KeyStore Type you want to use
1335      * @return A {@link TrustManagerFactory} which contains the certificates in {@code certChainFile}
1336      */
1337     protected static TrustManagerFactory buildTrustManagerFactory(
1338             File certChainFile, TrustManagerFactory trustManagerFactory, String keyType)
1339             throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
1340         X509Certificate[] x509Certs = toX509Certificates(certChainFile);
1341 
1342         return buildTrustManagerFactory(x509Certs, trustManagerFactory, keyType);
1343     }
1344 
1345     protected static X509Certificate[] toX509Certificates(File file) throws CertificateException {
1346         if (file == null) {
1347             return null;
1348         }
1349         return getCertificatesFromBuffers(PemReader.readCertificates(file));
1350     }
1351 
1352     protected static X509Certificate[] toX509Certificates(InputStream in) throws CertificateException {
1353         if (in == null) {
1354             return null;
1355         }
1356         return getCertificatesFromBuffers(PemReader.readCertificates(in));
1357     }
1358 
1359     private static X509Certificate[] getCertificatesFromBuffers(ByteBuf[] certs) throws CertificateException {
1360         CertificateFactory cf = CertificateFactory.getInstance("X.509");
1361         X509Certificate[] x509Certs = new X509Certificate[certs.length];
1362 
1363         try {
1364             for (int i = 0; i < certs.length; i++) {
1365                 try (InputStream is = new ByteBufInputStream(certs[i], false)) {
1366                     x509Certs[i] = (X509Certificate) cf.generateCertificate(is);
1367                 } catch (IOException e) {
1368                     // This is not expected to happen, but re-throw in case it does.
1369                     throw new RuntimeException(e);
1370                 }
1371             }
1372         } finally {
1373             for (ByteBuf buf: certs) {
1374                 buf.release();
1375             }
1376         }
1377         return x509Certs;
1378     }
1379 
1380     protected static TrustManagerFactory buildTrustManagerFactory(
1381             X509Certificate[] certCollection, TrustManagerFactory trustManagerFactory, String keyStoreType)
1382             throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
1383         if (keyStoreType == null) {
1384             keyStoreType = KeyStore.getDefaultType();
1385         }
1386         final KeyStore ks = KeyStore.getInstance(keyStoreType);
1387         ks.load(null, null);
1388 
1389         int i = 1;
1390         for (X509Certificate cert: certCollection) {
1391             String alias = Integer.toString(i);
1392             ks.setCertificateEntry(alias, cert);
1393             i++;
1394         }
1395 
1396         // Set up trust manager factory to use our key store.
1397         if (trustManagerFactory == null) {
1398             trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
1399         }
1400         trustManagerFactory.init(ks);
1401 
1402         return trustManagerFactory;
1403     }
1404 
1405     static PrivateKey toPrivateKeyInternal(File keyFile, String keyPassword) throws SSLException {
1406         try {
1407             return toPrivateKey(keyFile, keyPassword);
1408         } catch (Exception e) {
1409             throw new SSLException(e);
1410         }
1411     }
1412 
1413     static X509Certificate[] toX509CertificatesInternal(File file) throws SSLException {
1414         try {
1415             return toX509Certificates(file);
1416         } catch (CertificateException e) {
1417             throw new SSLException(e);
1418         }
1419     }
1420 
1421     protected static KeyManagerFactory buildKeyManagerFactory(X509Certificate[] certChainFile,
1422                                                     String keyAlgorithm, PrivateKey key,
1423                                                     String keyPassword, KeyManagerFactory kmf,
1424                                                     String keyStore)
1425             throws KeyStoreException, NoSuchAlgorithmException, IOException,
1426             CertificateException, UnrecoverableKeyException {
1427         if (keyAlgorithm == null) {
1428             keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
1429         }
1430         char[] keyPasswordChars = keyStorePassword(keyPassword);
1431         KeyStore ks = buildKeyStore(certChainFile, key, keyPasswordChars, keyStore);
1432         return buildKeyManagerFactory(ks, keyAlgorithm, keyPasswordChars, kmf);
1433     }
1434 
1435     static KeyManagerFactory buildKeyManagerFactory(KeyStore ks,
1436                                                     String keyAlgorithm,
1437                                                     char[] keyPasswordChars, KeyManagerFactory kmf)
1438             throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
1439         // Set up key manager factory to use our key store
1440         if (kmf == null) {
1441             if (keyAlgorithm == null) {
1442                 keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
1443             }
1444             kmf = KeyManagerFactory.getInstance(keyAlgorithm);
1445         }
1446         kmf.init(ks, keyPasswordChars);
1447 
1448         return kmf;
1449     }
1450 
1451     static char[] keyStorePassword(String keyPassword) {
1452         return keyPassword == null ? EmptyArrays.EMPTY_CHARS : keyPassword.toCharArray();
1453     }
1454 
1455     /**
1456      * Derives the {@code session_id_context} for a server context from the material that determines which clients
1457      * it accepts: the {@link ClientAuth} mode, the certificate chain it presents and the certificates it trusts.
1458      * <p>
1459      * The {@code session_id_context} scopes session resumption: a session (and therefore its client-authentication
1460      * state) can only be resumed by a context that uses the same {@code session_id_context}. It must hence differ
1461      * between contexts which, when sharing a session cache or session-ticket keys, must not accept each others
1462      * sessions (for example because they use a different {@link ClientAuth} mode or trust configuration), but it
1463      * should be the same for contexts that are configured identically (for example on different nodes of a cluster
1464      * that share session-ticket keys), so resumption keeps working between them.
1465      * See <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_session_id_context.html">
1466      * SSL_CTX_set_session_id_context</a> and
1467      * <a href="https://github.com/netty/netty/security/advisories/GHSA-6xv6-9mgg-mfvc">GHSA-6xv6-9mgg-mfvc</a>.
1468      *
1469      * @param clientAuth         the {@link ClientAuth} mode of the context.
1470      * @param keyCertChain       the certificate chain the context presents, or {@code null} if unknown.
1471      * @param trustCertCollection the certificates the context trusts, or {@code null} if it uses the default.
1472      * @param opaque             {@code true} if parts of the configuration (like a custom
1473      *                           {@link TrustManagerFactory}) can not be digested. As we then can not tell if two
1474      *                           contexts behave the same, a random salt is mixed in so the result is unique to the
1475      *                           context.
1476      * @return                   at most 32 bytes that are suitable to be used as {@code session_id_context}.
1477      * @deprecated               Deprecated in favor of the {@link SessionIdContextBuilder}.
1478      */
1479     @Deprecated
1480     @UnstableApi
1481     protected static byte[] deriveSessionIdContext(ClientAuth clientAuth, X509Certificate[] keyCertChain,
1482                                                    X509Certificate[] trustCertCollection, boolean opaque) {
1483         if (opaque) {
1484             return SessionIdContextBuilder.randomSessionIdContext().build();
1485         }
1486         return new SessionIdContextBuilder(new SecureObjectIdentityHash())
1487             .setClientAuth(clientAuth)
1488             .setKeyCertificateChain(keyCertChain)
1489             .setTrustedCertificates(trustCertCollection)
1490             .build();
1491     }
1492 }