View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.ssl;
17  
18  import io.netty.internal.tcnative.CertificateCallback;
19  import io.netty.internal.tcnative.SSL;
20  import io.netty.internal.tcnative.SSLContext;
21  import io.netty.util.internal.EmptyArrays;
22  
23  import javax.net.ssl.KeyManagerFactory;
24  import javax.net.ssl.SNIServerName;
25  import javax.net.ssl.SSLException;
26  import javax.net.ssl.TrustManagerFactory;
27  import javax.net.ssl.X509ExtendedTrustManager;
28  import javax.net.ssl.X509TrustManager;
29  import javax.security.auth.x500.X500Principal;
30  import java.security.KeyStore;
31  import java.security.PrivateKey;
32  import java.security.cert.X509Certificate;
33  import java.util.HashSet;
34  import java.util.List;
35  import java.util.Map;
36  import java.util.Set;
37  
38  /**
39   * A client-side {@link SslContext} which uses OpenSSL's SSL/TLS implementation.
40   * <p>Instances of this class must be {@link #release() released} or else native memory will leak!
41   *
42   * <p>Instances of this class <strong>must not</strong> be released before any {@link ReferenceCountedOpenSslEngine}
43   * which depends upon the instance of this class is released. Otherwise if any method of
44   * {@link ReferenceCountedOpenSslEngine} is called which uses this class's JNI resources the JVM may crash.
45   */
46  public final class ReferenceCountedOpenSslClientContext extends ReferenceCountedOpenSslContext {
47  
48      private static final String[] SUPPORTED_KEY_TYPES = {
49              OpenSslKeyMaterialManager.KEY_TYPE_RSA,
50              OpenSslKeyMaterialManager.KEY_TYPE_DH_RSA,
51              OpenSslKeyMaterialManager.KEY_TYPE_EC,
52              OpenSslKeyMaterialManager.KEY_TYPE_EC_RSA,
53              OpenSslKeyMaterialManager.KEY_TYPE_EC_EC
54      };
55  
56      private final OpenSslSessionContext sessionContext;
57  
58      ReferenceCountedOpenSslClientContext(X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
59                                           X509Certificate[] keyCertChain, PrivateKey key, String keyPassword,
60                                           KeyManagerFactory keyManagerFactory, Iterable<String> ciphers,
61                                           CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
62                                           String[] protocols, long sessionCacheSize, long sessionTimeout,
63                                           boolean enableOcsp, String keyStore, String endpointIdentificationAlgorithm,
64                                           List<SNIServerName> serverNames, ResumptionController resumptionController,
65                                           Map.Entry<SslContextOption<?>, Object>... options) throws SSLException {
66          super(ciphers, cipherFilter, toNegotiator(apn), SSL.SSL_MODE_CLIENT, keyCertChain,
67                ClientAuth.NONE, protocols, false, endpointIdentificationAlgorithm, enableOcsp, true,
68                  serverNames, resumptionController, options);
69          boolean success = false;
70          try {
71              sessionContext = newSessionContext(this, ctx, engines, trustCertCollection, trustManagerFactory,
72                                                 keyCertChain, key, keyPassword, keyManagerFactory, keyStore,
73                                                 sessionCacheSize, sessionTimeout, resumptionController);
74              success = true;
75          } finally {
76              if (!success) {
77                  release();
78              }
79          }
80      }
81  
82      @Override
83      public OpenSslSessionContext sessionContext() {
84          return sessionContext;
85      }
86  
87      static OpenSslSessionContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx,
88                                                     Map<Long, ReferenceCountedOpenSslEngine> engines,
89                                                     X509Certificate[] trustCertCollection,
90                                                     TrustManagerFactory trustManagerFactory,
91                                                     X509Certificate[] keyCertChain, PrivateKey key,
92                                                     String keyPassword, KeyManagerFactory keyManagerFactory,
93                                                     String keyStore, long sessionCacheSize, long sessionTimeout,
94                                                     ResumptionController resumptionController)
95              throws SSLException {
96          if (key == null && keyCertChain != null || key != null && keyCertChain == null) {
97              throw new IllegalArgumentException(
98                      "Either both keyCertChain and key needs to be null or none of them");
99          }
100         OpenSslKeyMaterialProvider keyMaterialProvider = null;
101         try {
102             try {
103                 if (!OpenSsl.useKeyManagerFactory()) {
104                     if (keyManagerFactory != null) {
105                         throw new IllegalArgumentException(
106                                 "KeyManagerFactory not supported");
107                     }
108                     if (keyCertChain != null/* && key != null*/) {
109                         setKeyMaterial(ctx, keyCertChain, key, keyPassword);
110                     }
111                 } else {
112                     // javadocs state that keyManagerFactory has precedent over keyCertChain
113                     if (keyManagerFactory == null && keyCertChain != null) {
114                         char[] keyPasswordChars = keyStorePassword(keyPassword);
115                         KeyStore ks = buildKeyStore(keyCertChain, key, keyPasswordChars, keyStore);
116                         if (ks.aliases().hasMoreElements()) {
117                             keyManagerFactory = new OpenSslX509KeyManagerFactory();
118                         } else {
119                             keyManagerFactory = new OpenSslCachingX509KeyManagerFactory(
120                                     KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()));
121                         }
122                         keyManagerFactory.init(ks, keyPasswordChars);
123                         keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
124                     } else if (keyManagerFactory != null) {
125                         keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
126                     }
127 
128                     if (keyMaterialProvider != null) {
129                         OpenSslKeyMaterialManager materialManager =
130                                 new OpenSslKeyMaterialManager(keyMaterialProvider, thiz.hasTmpDhKeys);
131                         SSLContext.setCertificateCallback(ctx, new OpenSslClientCertificateCallback(
132                                 engines, materialManager));
133                     }
134                 }
135             } catch (Exception e) {
136                 throw new SSLException("failed to set certificate and key", e);
137             }
138 
139             // On the client side we always need to use SSL_CVERIFY_OPTIONAL (which will translate to SSL_VERIFY_PEER)
140             // to ensure that when the TrustManager throws we will produce the correct alert back to the server.
141             //
142             // See:
143             //   - https://www.openssl.org/docs/man1.0.2/man3/SSL_CTX_set_verify.html
144             //   - https://github.com/netty/netty/issues/8942
145             SSLContext.setVerify(ctx, SSL.SSL_CVERIFY_OPTIONAL, VERIFY_DEPTH);
146 
147             try {
148                 if (trustCertCollection != null) {
149                     trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory, keyStore);
150                 } else if (trustManagerFactory == null) {
151                     trustManagerFactory = TrustManagerFactory.getInstance(
152                             TrustManagerFactory.getDefaultAlgorithm());
153                     trustManagerFactory.init((KeyStore) null);
154                 }
155                 final X509TrustManager manager = chooseTrustManager(
156                         trustManagerFactory.getTrustManagers(), resumptionController);
157 
158                 // IMPORTANT: The callbacks set for verification must be static to prevent memory leak as
159                 //            otherwise the context can never be collected. This is because the JNI code holds
160                 //            a global reference to the callbacks.
161                 //
162                 //            See https://github.com/netty/netty/issues/5372
163 
164                 setVerifyCallback(ctx, engines, manager);
165             } catch (Exception e) {
166                 if (keyMaterialProvider != null) {
167                     keyMaterialProvider.destroy();
168                 }
169                 throw new SSLException("unable to setup trustmanager", e);
170             }
171             OpenSslClientSessionContext context = new OpenSslClientSessionContext(thiz, keyMaterialProvider);
172             context.setSessionCacheEnabled(CLIENT_ENABLE_SESSION_CACHE);
173             if (sessionCacheSize > 0) {
174                 context.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
175             }
176             if (sessionTimeout > 0) {
177                 context.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
178             }
179 
180             if (CLIENT_ENABLE_SESSION_TICKET) {
181                 context.setTicketKeys();
182             }
183 
184             keyMaterialProvider = null;
185             return context;
186         } finally {
187             if (keyMaterialProvider != null) {
188                 keyMaterialProvider.destroy();
189             }
190         }
191     }
192 
193     private static void setVerifyCallback(long ctx,
194                                           Map<Long, ReferenceCountedOpenSslEngine> engines,
195                                           X509TrustManager manager) {
196         // Use this to prevent an error when running on java < 7
197         if (useExtendedTrustManager(manager)) {
198             SSLContext.setCertVerifyCallback(ctx,
199                     new ExtendedTrustManagerVerifyCallback(engines, (X509ExtendedTrustManager) manager));
200         } else {
201             SSLContext.setCertVerifyCallback(ctx, new TrustManagerVerifyCallback(engines, manager));
202         }
203     }
204 
205     static final class OpenSslClientSessionContext extends OpenSslSessionContext {
206         OpenSslClientSessionContext(ReferenceCountedOpenSslContext context, OpenSslKeyMaterialProvider provider) {
207             super(context, provider, SSL.SSL_SESS_CACHE_CLIENT, new OpenSslClientSessionCache(context.engines));
208         }
209     }
210 
211     private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
212         private final X509TrustManager manager;
213 
214         TrustManagerVerifyCallback(Map<Long, ReferenceCountedOpenSslEngine> engines, X509TrustManager manager) {
215             super(engines);
216             this.manager = manager;
217         }
218 
219         @Override
220         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
221                 throws Exception {
222             manager.checkServerTrusted(peerCerts, auth);
223         }
224     }
225 
226     private static final class ExtendedTrustManagerVerifyCallback extends AbstractCertificateVerifier {
227         private final X509ExtendedTrustManager manager;
228 
229         ExtendedTrustManagerVerifyCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
230                                            X509ExtendedTrustManager manager) {
231             super(engines);
232             this.manager = manager;
233         }
234 
235         @Override
236         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
237                 throws Exception {
238             manager.checkServerTrusted(peerCerts, auth, engine);
239         }
240     }
241 
242     private static final class OpenSslClientCertificateCallback implements CertificateCallback {
243         private final Map<Long, ReferenceCountedOpenSslEngine> engines;
244         private final OpenSslKeyMaterialManager keyManagerHolder;
245 
246         OpenSslClientCertificateCallback(Map<Long, ReferenceCountedOpenSslEngine> engines,
247                                          OpenSslKeyMaterialManager keyManagerHolder) {
248             this.engines = engines;
249             this.keyManagerHolder = keyManagerHolder;
250         }
251 
252         @Override
253         public void handle(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) throws Exception {
254             final ReferenceCountedOpenSslEngine engine = engines.get(ssl);
255             // May be null if it was destroyed in the meantime.
256             if (engine == null) {
257                 return;
258             }
259             try {
260                 final String[] keyTypes = supportedClientKeyTypes(keyTypeBytes);
261                 final X500Principal[] issuers;
262                 if (asn1DerEncodedPrincipals == null) {
263                     issuers = null;
264                 } else {
265                     issuers = new X500Principal[asn1DerEncodedPrincipals.length];
266                     for (int i = 0; i < asn1DerEncodedPrincipals.length; i++) {
267                         issuers[i] = new X500Principal(asn1DerEncodedPrincipals[i]);
268                     }
269                 }
270                 keyManagerHolder.setKeyMaterialClientSide(engine, keyTypes, issuers);
271             } catch (Throwable cause) {
272                 engine.initHandshakeException(cause);
273                 if (cause instanceof Exception) {
274                     throw (Exception) cause;
275                 }
276                 throw new SSLException(cause);
277             }
278         }
279 
280         /**
281          * Gets the supported key types for client certificates.
282          *
283          * @param clientCertificateTypes {@code ClientCertificateType} values provided by the server.
284          *        See https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml.
285          * @return supported key types that can be used in {@code X509KeyManager.chooseClientAlias} and
286          *         {@code X509ExtendedKeyManager.chooseEngineClientAlias}.
287          */
288         private static String[] supportedClientKeyTypes(byte[] clientCertificateTypes) {
289             if (clientCertificateTypes == null) {
290                 // Try all of the supported key types.
291                 return SUPPORTED_KEY_TYPES.clone();
292             }
293             Set<String> result = new HashSet<>(clientCertificateTypes.length);
294             for (byte keyTypeCode : clientCertificateTypes) {
295                 String keyType = clientKeyType(keyTypeCode);
296                 if (keyType == null) {
297                     // Unsupported client key type -- ignore
298                     continue;
299                 }
300                 result.add(keyType);
301             }
302             return result.toArray(EmptyArrays.EMPTY_STRINGS);
303         }
304 
305         private static String clientKeyType(byte clientCertificateType) {
306             // See also https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml
307             switch (clientCertificateType) {
308                 case CertificateCallback.TLS_CT_RSA_SIGN:
309                     return OpenSslKeyMaterialManager.KEY_TYPE_RSA; // RFC rsa_sign
310                 case CertificateCallback.TLS_CT_RSA_FIXED_DH:
311                     return OpenSslKeyMaterialManager.KEY_TYPE_DH_RSA; // RFC rsa_fixed_dh
312                 case CertificateCallback.TLS_CT_ECDSA_SIGN:
313                     return OpenSslKeyMaterialManager.KEY_TYPE_EC; // RFC ecdsa_sign
314                 case CertificateCallback.TLS_CT_RSA_FIXED_ECDH:
315                     return OpenSslKeyMaterialManager.KEY_TYPE_EC_RSA; // RFC rsa_fixed_ecdh
316                 case CertificateCallback.TLS_CT_ECDSA_FIXED_ECDH:
317                     return OpenSslKeyMaterialManager.KEY_TYPE_EC_EC; // RFC ecdsa_fixed_ecdh
318                 default:
319                     return null;
320             }
321         }
322     }
323 }