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