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