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.buffer.ByteBufAllocator;
19  import io.netty.internal.tcnative.CertificateCallback;
20  import io.netty.internal.tcnative.SSL;
21  import io.netty.internal.tcnative.SSLContext;
22  import io.netty.internal.tcnative.SniHostNameMatcher;
23  import io.netty.util.CharsetUtil;
24  import io.netty.util.internal.PlatformDependent;
25  import io.netty.util.internal.logging.InternalLogger;
26  import io.netty.util.internal.logging.InternalLoggerFactory;
27  
28  import java.security.KeyStore;
29  import java.security.PrivateKey;
30  import java.security.cert.X509Certificate;
31  import javax.net.ssl.KeyManagerFactory;
32  import javax.net.ssl.SSLException;
33  import javax.net.ssl.TrustManagerFactory;
34  import javax.net.ssl.X509ExtendedTrustManager;
35  import javax.net.ssl.X509TrustManager;
36  
37  import static io.netty.util.internal.ObjectUtil.checkNotNull;
38  
39  /**
40   * A server-side {@link SslContext} which uses OpenSSL's SSL/TLS implementation.
41   * <p>Instances of this class must be {@link #release() released} or else native memory will leak!
42   *
43   * <p>Instances of this class <strong>must not</strong> be released before any {@link ReferenceCountedOpenSslEngine}
44   * which depends upon the instance of this class is released. Otherwise if any method of
45   * {@link ReferenceCountedOpenSslEngine} is called which uses this class's JNI resources the JVM may crash.
46   */
47  public final class ReferenceCountedOpenSslServerContext extends ReferenceCountedOpenSslContext {
48      private static final InternalLogger logger =
49              InternalLoggerFactory.getInstance(ReferenceCountedOpenSslServerContext.class);
50      private static final byte[] ID = {'n', 'e', 't', 't', 'y'};
51      private final OpenSslServerSessionContext sessionContext;
52  
53      ReferenceCountedOpenSslServerContext(
54              X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
55              X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
56              Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
57              long sessionCacheSize, long sessionTimeout, ClientAuth clientAuth, String[] protocols, boolean startTls,
58              boolean enableOcsp) throws SSLException {
59          this(trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers,
60                  cipherFilter, toNegotiator(apn), sessionCacheSize, sessionTimeout, clientAuth, protocols, startTls,
61                  enableOcsp);
62      }
63  
64      private ReferenceCountedOpenSslServerContext(
65              X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
66              X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
67              Iterable<String> ciphers, CipherSuiteFilter cipherFilter, OpenSslApplicationProtocolNegotiator apn,
68              long sessionCacheSize, long sessionTimeout, ClientAuth clientAuth, String[] protocols, boolean startTls,
69              boolean enableOcsp) throws SSLException {
70          super(ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, SSL.SSL_MODE_SERVER, keyCertChain,
71                clientAuth, protocols, startTls, enableOcsp, true);
72          // Create a new SSL_CTX and configure it.
73          boolean success = false;
74          try {
75              sessionContext = newSessionContext(this, ctx, engineMap, trustCertCollection, trustManagerFactory,
76                                                        keyCertChain, key, keyPassword, keyManagerFactory);
77              success = true;
78          } finally {
79              if (!success) {
80                  release();
81              }
82          }
83      }
84  
85      @Override
86      public OpenSslServerSessionContext sessionContext() {
87          return sessionContext;
88      }
89  
90      static OpenSslServerSessionContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx,
91                                                           OpenSslEngineMap engineMap,
92                                                           X509Certificate[] trustCertCollection,
93                                                           TrustManagerFactory trustManagerFactory,
94                                                           X509Certificate[] keyCertChain, PrivateKey key,
95                                                           String keyPassword, KeyManagerFactory keyManagerFactory)
96              throws SSLException {
97          OpenSslKeyMaterialProvider keyMaterialProvider = null;
98          try {
99              try {
100                 SSLContext.setVerify(ctx, SSL.SSL_CVERIFY_NONE, VERIFY_DEPTH);
101                 if (!OpenSsl.useKeyManagerFactory()) {
102                     if (keyManagerFactory != null) {
103                         throw new IllegalArgumentException(
104                                 "KeyManagerFactory not supported");
105                     }
106                     checkNotNull(keyCertChain, "keyCertChain");
107 
108                     setKeyMaterial(ctx, keyCertChain, key, keyPassword);
109                 } else {
110                     // javadocs state that keyManagerFactory has precedent over keyCertChain, and we must have a
111                     // keyManagerFactory for the server so build one if it is not specified.
112                     if (keyManagerFactory == null) {
113                         char[] keyPasswordChars = keyStorePassword(keyPassword);
114                         KeyStore ks = buildKeyStore(keyCertChain, key, keyPasswordChars);
115                         if (ks.aliases().hasMoreElements()) {
116                             keyManagerFactory = new OpenSslX509KeyManagerFactory();
117                         } else {
118                             keyManagerFactory = new OpenSslCachingX509KeyManagerFactory(
119                                     KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()));
120                         }
121                         keyManagerFactory.init(ks, keyPasswordChars);
122                     }
123                     keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
124 
125                     SSLContext.setCertificateCallback(ctx, new OpenSslServerCertificateCallback(
126                             engineMap, new OpenSslKeyMaterialManager(keyMaterialProvider)));
127                 }
128             } catch (Exception e) {
129                 throw new SSLException("failed to set certificate and key", e);
130             }
131             try {
132                 if (trustCertCollection != null) {
133                     trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory);
134                 } else if (trustManagerFactory == null) {
135                     // Mimic the way SSLContext.getInstance(KeyManager[], null, null) works
136                     trustManagerFactory = TrustManagerFactory.getInstance(
137                             TrustManagerFactory.getDefaultAlgorithm());
138                     trustManagerFactory.init((KeyStore) null);
139                 }
140 
141                 final X509TrustManager manager = chooseTrustManager(trustManagerFactory.getTrustManagers());
142 
143                 // IMPORTANT: The callbacks set for verification must be static to prevent memory leak as
144                 //            otherwise the context can never be collected. This is because the JNI code holds
145                 //            a global reference to the callbacks.
146                 //
147                 //            See https://github.com/netty/netty/issues/5372
148 
149                 // Use this to prevent an error when running on java < 7
150                 if (useExtendedTrustManager(manager)) {
151                     SSLContext.setCertVerifyCallback(ctx, new ExtendedTrustManagerVerifyCallback(
152                             engineMap, (X509ExtendedTrustManager) manager));
153                 } else {
154                     SSLContext.setCertVerifyCallback(ctx, new TrustManagerVerifyCallback(engineMap, manager));
155                 }
156 
157                 X509Certificate[] issuers = manager.getAcceptedIssuers();
158                 if (issuers != null && issuers.length > 0) {
159                     long bio = 0;
160                     try {
161                         bio = toBIO(ByteBufAllocator.DEFAULT, issuers);
162                         if (!SSLContext.setCACertificateBio(ctx, bio)) {
163                             throw new SSLException("unable to setup accepted issuers for trustmanager " + manager);
164                         }
165                     } finally {
166                         freeBio(bio);
167                     }
168                 }
169 
170                 if (PlatformDependent.javaVersion() >= 8) {
171                     // Only do on Java8+ as SNIMatcher is not supported in earlier releases.
172                     // IMPORTANT: The callbacks set for hostname matching must be static to prevent memory leak as
173                     //            otherwise the context can never be collected. This is because the JNI code holds
174                     //            a global reference to the matcher.
175                     SSLContext.setSniHostnameMatcher(ctx, new OpenSslSniHostnameMatcher(engineMap));
176                 }
177             } catch (SSLException e) {
178                 throw e;
179             } catch (Exception e) {
180                 throw new SSLException("unable to setup trustmanager", e);
181             }
182 
183             OpenSslServerSessionContext sessionContext = new OpenSslServerSessionContext(thiz, keyMaterialProvider);
184             sessionContext.setSessionIdContext(ID);
185 
186             keyMaterialProvider = null;
187 
188             return sessionContext;
189         } finally {
190             if (keyMaterialProvider != null) {
191                 keyMaterialProvider.destroy();
192             }
193         }
194     }
195 
196     private static final class OpenSslServerCertificateCallback implements CertificateCallback {
197         private final OpenSslEngineMap engineMap;
198         private final OpenSslKeyMaterialManager keyManagerHolder;
199 
200         OpenSslServerCertificateCallback(OpenSslEngineMap engineMap, OpenSslKeyMaterialManager keyManagerHolder) {
201             this.engineMap = engineMap;
202             this.keyManagerHolder = keyManagerHolder;
203         }
204 
205         @Override
206         public void handle(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) throws Exception {
207             final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
208             try {
209                 // For now we just ignore the asn1DerEncodedPrincipals as this is kind of inline with what the
210                 // OpenJDK SSLEngineImpl does.
211                 keyManagerHolder.setKeyMaterialServerSide(engine);
212             } catch (Throwable cause) {
213                 logger.debug("Failed to set the server-side key material", cause);
214                 engine.initHandshakeException(cause);
215             }
216         }
217     }
218 
219     private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
220         private final X509TrustManager manager;
221 
222         TrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509TrustManager manager) {
223             super(engineMap);
224             this.manager = manager;
225         }
226 
227         @Override
228         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
229                 throws Exception {
230             manager.checkClientTrusted(peerCerts, auth);
231         }
232     }
233 
234     private static final class ExtendedTrustManagerVerifyCallback extends AbstractCertificateVerifier {
235         private final X509ExtendedTrustManager manager;
236 
237         ExtendedTrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509ExtendedTrustManager manager) {
238             super(engineMap);
239             this.manager = OpenSslTlsv13X509ExtendedTrustManager.wrap(manager, false);
240         }
241 
242         @Override
243         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
244                 throws Exception {
245             manager.checkClientTrusted(peerCerts, auth, engine);
246         }
247     }
248 
249     private static final class OpenSslSniHostnameMatcher implements SniHostNameMatcher {
250         private final OpenSslEngineMap engineMap;
251 
252         OpenSslSniHostnameMatcher(OpenSslEngineMap engineMap) {
253             this.engineMap = engineMap;
254         }
255 
256         @Override
257         public boolean match(long ssl, String hostname) {
258             ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
259             if (engine != null) {
260                 // TODO: In the next release of tcnative we should pass the byte[] directly in and not use a String.
261                 return engine.checkSniHostnameMatch(hostname.getBytes(CharsetUtil.UTF_8));
262             }
263             logger.warn("No ReferenceCountedOpenSslEngine found for SSL pointer: {}", ssl);
264             return false;
265         }
266     }
267 }