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    *   http://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.util.internal.logging.InternalLogger;
19  import io.netty.util.internal.logging.InternalLoggerFactory;
20  import io.netty.internal.tcnative.CertificateRequestedCallback;
21  import io.netty.internal.tcnative.SSL;
22  import io.netty.internal.tcnative.SSLContext;
23  
24  import java.security.KeyStore;
25  import java.security.PrivateKey;
26  import java.security.cert.X509Certificate;
27  import java.util.HashSet;
28  import java.util.Set;
29  
30  import javax.net.ssl.KeyManagerFactory;
31  import javax.net.ssl.SSLException;
32  import javax.net.ssl.SSLHandshakeException;
33  import javax.net.ssl.TrustManagerFactory;
34  import javax.net.ssl.X509ExtendedTrustManager;
35  import javax.net.ssl.X509TrustManager;
36  import javax.security.auth.x500.X500Principal;
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      private static final InternalLogger logger =
48              InternalLoggerFactory.getInstance(ReferenceCountedOpenSslClientContext.class);
49      private final OpenSslSessionContext sessionContext;
50  
51      ReferenceCountedOpenSslClientContext(X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
52                                           X509Certificate[] keyCertChain, PrivateKey key, String keyPassword,
53                                           KeyManagerFactory keyManagerFactory, Iterable<String> ciphers,
54                                           CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
55                                           String[] protocols, long sessionCacheSize, long sessionTimeout,
56                                           boolean enableOcsp) throws SSLException {
57          super(ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, SSL.SSL_MODE_CLIENT, keyCertChain,
58                ClientAuth.NONE, protocols, false, enableOcsp, true);
59          boolean success = false;
60          try {
61              sessionContext = newSessionContext(this, ctx, engineMap, trustCertCollection, trustManagerFactory,
62                                                 keyCertChain, key, keyPassword, keyManagerFactory);
63              success = true;
64          } finally {
65              if (!success) {
66                  release();
67              }
68          }
69      }
70  
71      @Override
72      OpenSslKeyMaterialManager keyMaterialManager() {
73          return null;
74      }
75  
76      @Override
77      public OpenSslSessionContext sessionContext() {
78          return sessionContext;
79      }
80  
81      static OpenSslSessionContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx,
82                                                     OpenSslEngineMap engineMap,
83                                                     X509Certificate[] trustCertCollection,
84                                                     TrustManagerFactory trustManagerFactory,
85                                                     X509Certificate[] keyCertChain, PrivateKey key, String keyPassword,
86                                                     KeyManagerFactory keyManagerFactory) throws SSLException {
87          if (key == null && keyCertChain != null || key != null && keyCertChain == null) {
88              throw new IllegalArgumentException(
89                      "Either both keyCertChain and key needs to be null or none of them");
90          }
91          OpenSslKeyMaterialProvider keyMaterialProvider = null;
92          try {
93              try {
94                  if (!OpenSsl.useKeyManagerFactory()) {
95                      if (keyManagerFactory != null) {
96                          throw new IllegalArgumentException(
97                                  "KeyManagerFactory not supported");
98                      }
99                      if (keyCertChain != null/* && key != null*/) {
100                         setKeyMaterial(ctx, keyCertChain, key, keyPassword);
101                     }
102                 } else {
103                     // javadocs state that keyManagerFactory has precedent over keyCertChain
104                     if (keyManagerFactory == null && keyCertChain != null) {
105                         char[] keyPasswordChars = keyStorePassword(keyPassword);
106                         KeyStore ks = buildKeyStore(keyCertChain, key, keyPasswordChars);
107                         if (ks.aliases().hasMoreElements()) {
108                             keyManagerFactory = new OpenSslX509KeyManagerFactory();
109                         } else {
110                             keyManagerFactory = new OpenSslCachingX509KeyManagerFactory(
111                                     KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()));
112                         }
113                         keyManagerFactory.init(ks, keyPasswordChars);
114                         keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
115                     } else if (keyManagerFactory != null) {
116                         keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
117                     }
118 
119                     if (keyMaterialProvider != null) {
120                         OpenSslKeyMaterialManager materialManager = new OpenSslKeyMaterialManager(keyMaterialProvider);
121                         SSLContext.setCertRequestedCallback(ctx, new OpenSslCertificateRequestedCallback(
122                                 engineMap, materialManager));
123                     }
124                 }
125             } catch (Exception e) {
126                 throw new SSLException("failed to set certificate and key", e);
127             }
128 
129             SSLContext.setVerify(ctx, SSL.SSL_CVERIFY_NONE, VERIFY_DEPTH);
130 
131             try {
132                 if (trustCertCollection != null) {
133                     trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory);
134                 } else if (trustManagerFactory == null) {
135                     trustManagerFactory = TrustManagerFactory.getInstance(
136                             TrustManagerFactory.getDefaultAlgorithm());
137                     trustManagerFactory.init((KeyStore) null);
138                 }
139                 final X509TrustManager manager = chooseTrustManager(trustManagerFactory.getTrustManagers());
140 
141                 // IMPORTANT: The callbacks set for verification must be static to prevent memory leak as
142                 //            otherwise the context can never be collected. This is because the JNI code holds
143                 //            a global reference to the callbacks.
144                 //
145                 //            See https://github.com/netty/netty/issues/5372
146 
147                 // Use this to prevent an error when running on java < 7
148                 if (useExtendedTrustManager(manager)) {
149                     SSLContext.setCertVerifyCallback(ctx,
150                             new ExtendedTrustManagerVerifyCallback(engineMap, (X509ExtendedTrustManager) manager));
151                 } else {
152                     SSLContext.setCertVerifyCallback(ctx, new TrustManagerVerifyCallback(engineMap, manager));
153                 }
154             } catch (Exception e) {
155                 if (keyMaterialProvider != null) {
156                     keyMaterialProvider.destroy();
157                 }
158                 throw new SSLException("unable to setup trustmanager", e);
159             }
160             OpenSslClientSessionContext context = new OpenSslClientSessionContext(thiz, keyMaterialProvider);
161             keyMaterialProvider = null;
162             return context;
163         } finally {
164             if (keyMaterialProvider != null) {
165                 keyMaterialProvider.destroy();
166             }
167         }
168     }
169 
170     // No cache is currently supported for client side mode.
171     static final class OpenSslClientSessionContext extends OpenSslSessionContext {
172         OpenSslClientSessionContext(ReferenceCountedOpenSslContext context, OpenSslKeyMaterialProvider provider) {
173             super(context, provider);
174         }
175 
176         @Override
177         public void setSessionTimeout(int seconds) {
178             if (seconds < 0) {
179                 throw new IllegalArgumentException();
180             }
181         }
182 
183         @Override
184         public int getSessionTimeout() {
185             return 0;
186         }
187 
188         @Override
189         public void setSessionCacheSize(int size)  {
190             if (size < 0) {
191                 throw new IllegalArgumentException();
192             }
193         }
194 
195         @Override
196         public int getSessionCacheSize() {
197             return 0;
198         }
199 
200         @Override
201         public void setSessionCacheEnabled(boolean enabled) {
202             // ignored
203         }
204 
205         @Override
206         public boolean isSessionCacheEnabled() {
207             return false;
208         }
209     }
210 
211     private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
212         private final X509TrustManager manager;
213 
214         TrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509TrustManager manager) {
215             super(engineMap);
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(OpenSslEngineMap engineMap, X509ExtendedTrustManager manager) {
230             super(engineMap);
231             this.manager = manager;
232         }
233 
234         @Override
235         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
236                 throws Exception {
237             manager.checkServerTrusted(peerCerts, auth, engine);
238         }
239     }
240 
241     private static final class OpenSslCertificateRequestedCallback implements CertificateRequestedCallback {
242         private final OpenSslEngineMap engineMap;
243         private final OpenSslKeyMaterialManager keyManagerHolder;
244 
245         OpenSslCertificateRequestedCallback(OpenSslEngineMap engineMap, OpenSslKeyMaterialManager keyManagerHolder) {
246             this.engineMap = engineMap;
247             this.keyManagerHolder = keyManagerHolder;
248         }
249 
250         @Override
251         public void requested(
252                 long ssl, long certOut, long keyOut, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) {
253             final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
254             try {
255                 final Set<String> keyTypesSet = supportedClientKeyTypes(keyTypeBytes);
256                 final String[] keyTypes = keyTypesSet.toArray(new String[0]);
257                 final X500Principal[] issuers;
258                 if (asn1DerEncodedPrincipals == null) {
259                     issuers = null;
260                 } else {
261                     issuers = new X500Principal[asn1DerEncodedPrincipals.length];
262                     for (int i = 0; i < asn1DerEncodedPrincipals.length; i++) {
263                         issuers[i] = new X500Principal(asn1DerEncodedPrincipals[i]);
264                     }
265                 }
266                 keyManagerHolder.setKeyMaterialClientSide(engine, certOut, keyOut, keyTypes, issuers);
267             } catch (Throwable cause) {
268                 logger.debug("request of key failed", cause);
269                 SSLHandshakeException e = new SSLHandshakeException("General OpenSslEngine problem");
270                 e.initCause(cause);
271                 engine.handshakeException = e;
272             }
273         }
274 
275         /**
276          * Gets the supported key types for client certificates.
277          *
278          * @param clientCertificateTypes {@code ClientCertificateType} values provided by the server.
279          *        See https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml.
280          * @return supported key types that can be used in {@code X509KeyManager.chooseClientAlias} and
281          *         {@code X509ExtendedKeyManager.chooseEngineClientAlias}.
282          */
283         private static Set<String> supportedClientKeyTypes(byte[] clientCertificateTypes) {
284             Set<String> result = new HashSet<String>(clientCertificateTypes.length);
285             for (byte keyTypeCode : clientCertificateTypes) {
286                 String keyType = clientKeyType(keyTypeCode);
287                 if (keyType == null) {
288                     // Unsupported client key type -- ignore
289                     continue;
290                 }
291                 result.add(keyType);
292             }
293             return result;
294         }
295 
296         private static String clientKeyType(byte clientCertificateType) {
297             // See also http://www.ietf.org/assignments/tls-parameters/tls-parameters.xml
298             switch (clientCertificateType) {
299                 case CertificateRequestedCallback.TLS_CT_RSA_SIGN:
300                     return OpenSslKeyMaterialManager.KEY_TYPE_RSA; // RFC rsa_sign
301                 case CertificateRequestedCallback.TLS_CT_RSA_FIXED_DH:
302                     return OpenSslKeyMaterialManager.KEY_TYPE_DH_RSA; // RFC rsa_fixed_dh
303                 case CertificateRequestedCallback.TLS_CT_ECDSA_SIGN:
304                     return OpenSslKeyMaterialManager.KEY_TYPE_EC; // RFC ecdsa_sign
305                 case CertificateRequestedCallback.TLS_CT_RSA_FIXED_ECDH:
306                     return OpenSslKeyMaterialManager.KEY_TYPE_EC_RSA; // RFC rsa_fixed_ecdh
307                 case CertificateRequestedCallback.TLS_CT_ECDSA_FIXED_ECDH:
308                     return OpenSslKeyMaterialManager.KEY_TYPE_EC_EC; // RFC ecdsa_fixed_ecdh
309                 default:
310                     return null;
311             }
312         }
313     }
314 }