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