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.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.logging.InternalLogger;
25  import io.netty.util.internal.logging.InternalLoggerFactory;
26  
27  import java.security.KeyStore;
28  import java.security.PrivateKey;
29  import java.security.cert.X509Certificate;
30  import java.util.Map;
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, String keyStore, ResumptionController resumptionController,
59              Map.Entry<SslContextOption<?>, Object>... options) throws SSLException {
60          this(trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, ciphers,
61                  cipherFilter, toNegotiator(apn), sessionCacheSize, sessionTimeout, clientAuth, protocols, startTls,
62                  enableOcsp, keyStore, resumptionController, options);
63      }
64  
65      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, String keyStore, ResumptionController resumptionController,
71              Map.Entry<SslContextOption<?>, Object>... options) throws SSLException {
72          super(ciphers, cipherFilter, apn, SSL.SSL_MODE_SERVER, keyCertChain,
73                  clientAuth, protocols, startTls,
74                  null, // No endpoint validation for servers.
75                  enableOcsp, true, resumptionController, options);
76          // Create a new SSL_CTX and configure it.
77          boolean success = false;
78          try {
79              sessionContext = newSessionContext(this, ctx, engineMap, trustCertCollection, trustManagerFactory,
80                      keyCertChain, key, keyPassword, keyManagerFactory, keyStore,
81                      sessionCacheSize, sessionTimeout, resumptionController);
82              if (SERVER_ENABLE_SESSION_TICKET) {
83                  sessionContext.setTicketKeys();
84              }
85              success = true;
86          } finally {
87              if (!success) {
88                  release();
89              }
90          }
91      }
92  
93      @Override
94      public OpenSslServerSessionContext sessionContext() {
95          return sessionContext;
96      }
97  
98      static OpenSslServerSessionContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx,
99                                                           OpenSslEngineMap engineMap,
100                                                          X509Certificate[] trustCertCollection,
101                                                          TrustManagerFactory trustManagerFactory,
102                                                          X509Certificate[] keyCertChain, PrivateKey key,
103                                                          String keyPassword, KeyManagerFactory keyManagerFactory,
104                                                          String keyStore, long sessionCacheSize, long sessionTimeout,
105                                                          ResumptionController resumptionController)
106             throws SSLException {
107         OpenSslKeyMaterialProvider keyMaterialProvider = null;
108         try {
109             try {
110                 SSLContext.setVerify(ctx, SSL.SSL_CVERIFY_NONE, VERIFY_DEPTH);
111                 if (!OpenSsl.useKeyManagerFactory()) {
112                     if (keyManagerFactory != null) {
113                         throw new IllegalArgumentException(
114                                 "KeyManagerFactory not supported");
115                     }
116                     checkNotNull(keyCertChain, "keyCertChain");
117 
118                     setKeyMaterial(ctx, keyCertChain, key, keyPassword);
119                 } else {
120                     // javadocs state that keyManagerFactory has precedent over keyCertChain, and we must have a
121                     // keyManagerFactory for the server so build one if it is not specified.
122                     if (keyManagerFactory == null) {
123                         char[] keyPasswordChars = keyStorePassword(keyPassword);
124                         KeyStore ks = buildKeyStore(keyCertChain, key, keyPasswordChars, keyStore);
125                         if (ks.aliases().hasMoreElements()) {
126                             keyManagerFactory = new OpenSslX509KeyManagerFactory();
127                         } else {
128                             keyManagerFactory = new OpenSslCachingX509KeyManagerFactory(
129                                     KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()));
130                         }
131                         keyManagerFactory.init(ks, keyPasswordChars);
132                     }
133                     keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
134 
135                     SSLContext.setCertificateCallback(ctx, new OpenSslServerCertificateCallback(
136                             engineMap, new OpenSslKeyMaterialManager(keyMaterialProvider)));
137                 }
138             } catch (Exception e) {
139                 throw new SSLException("failed to set certificate and key", e);
140             }
141             try {
142                 if (trustCertCollection != null) {
143                     trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory, keyStore);
144                 } else if (trustManagerFactory == null) {
145                     // Mimic the way SSLContext.getInstance(KeyManager[], null, null) works
146                     trustManagerFactory = TrustManagerFactory.getInstance(
147                             TrustManagerFactory.getDefaultAlgorithm());
148                     trustManagerFactory.init((KeyStore) null);
149                 }
150 
151                 final X509TrustManager manager = chooseTrustManager(
152                         trustManagerFactory.getTrustManagers(), resumptionController);
153 
154                 // IMPORTANT: The callbacks set for verification must be static to prevent memory leak as
155                 //            otherwise the context can never be collected. This is because the JNI code holds
156                 //            a global reference to the callbacks.
157                 //
158                 //            See https://github.com/netty/netty/issues/5372
159 
160                 setVerifyCallback(ctx, engineMap, manager);
161 
162                 X509Certificate[] issuers = manager.getAcceptedIssuers();
163                 if (issuers != null && issuers.length > 0) {
164                     long bio = 0;
165                     try {
166                         bio = toBIO(ByteBufAllocator.DEFAULT, issuers);
167                         if (!SSLContext.setCACertificateBio(ctx, bio)) {
168                             throw new SSLException("unable to setup accepted issuers for trustmanager " + manager);
169                         }
170                     } finally {
171                         freeBio(bio);
172                     }
173                 }
174 
175                 // IMPORTANT: The callbacks set for hostname matching must be static to prevent memory leak as
176                 //            otherwise the context can never be collected. This is because the JNI code holds
177                 //            a global reference to the matcher.
178                 SSLContext.setSniHostnameMatcher(ctx, new OpenSslSniHostnameMatcher(engineMap));
179             } catch (SSLException e) {
180                 throw e;
181             } catch (Exception e) {
182                 throw new SSLException("unable to setup trustmanager", e);
183             }
184 
185             OpenSslServerSessionContext sessionContext = new OpenSslServerSessionContext(thiz, keyMaterialProvider);
186             sessionContext.setSessionIdContext(ID);
187             // Enable session caching by default
188             sessionContext.setSessionCacheEnabled(SERVER_ENABLE_SESSION_CACHE);
189             if (sessionCacheSize > 0) {
190                 sessionContext.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
191             }
192             if (sessionTimeout > 0) {
193                 sessionContext.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
194             }
195 
196             keyMaterialProvider = null;
197 
198             return sessionContext;
199         } finally {
200             if (keyMaterialProvider != null) {
201                 keyMaterialProvider.destroy();
202             }
203         }
204     }
205 
206     private static void setVerifyCallback(long ctx, OpenSslEngineMap engineMap, X509TrustManager manager) {
207         // Use this to prevent an error when running on java < 7
208         if (useExtendedTrustManager(manager)) {
209             SSLContext.setCertVerifyCallback(ctx, new ExtendedTrustManagerVerifyCallback(
210                     engineMap, (X509ExtendedTrustManager) manager));
211         } else {
212             SSLContext.setCertVerifyCallback(ctx, new TrustManagerVerifyCallback(engineMap, manager));
213         }
214     }
215 
216     private static final class OpenSslServerCertificateCallback implements CertificateCallback {
217         private final OpenSslEngineMap engineMap;
218         private final OpenSslKeyMaterialManager keyManagerHolder;
219 
220         OpenSslServerCertificateCallback(OpenSslEngineMap engineMap, OpenSslKeyMaterialManager keyManagerHolder) {
221             this.engineMap = engineMap;
222             this.keyManagerHolder = keyManagerHolder;
223         }
224 
225         @Override
226         public void handle(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals) throws Exception {
227             final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
228             if (engine == null) {
229                 // Maybe null if destroyed in the meantime.
230                 return;
231             }
232             try {
233                 // For now we just ignore the asn1DerEncodedPrincipals as this is kind of inline with what the
234                 // OpenJDK SSLEngineImpl does.
235                 keyManagerHolder.setKeyMaterialServerSide(engine);
236             } catch (Throwable cause) {
237                 engine.initHandshakeException(cause);
238 
239                 if (cause instanceof Exception) {
240                     throw (Exception) cause;
241                 }
242                 throw new SSLException(cause);
243             }
244         }
245     }
246 
247     private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
248         private final X509TrustManager manager;
249 
250         TrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509TrustManager manager) {
251             super(engineMap);
252             this.manager = manager;
253         }
254 
255         @Override
256         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
257                 throws Exception {
258             manager.checkClientTrusted(peerCerts, auth);
259         }
260     }
261 
262     private static final class ExtendedTrustManagerVerifyCallback extends AbstractCertificateVerifier {
263         private final X509ExtendedTrustManager manager;
264 
265         ExtendedTrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509ExtendedTrustManager manager) {
266             super(engineMap);
267             this.manager = manager;
268         }
269 
270         @Override
271         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
272                 throws Exception {
273             manager.checkClientTrusted(peerCerts, auth, engine);
274         }
275     }
276 
277     private static final class OpenSslSniHostnameMatcher implements SniHostNameMatcher {
278         private final OpenSslEngineMap engineMap;
279 
280         OpenSslSniHostnameMatcher(OpenSslEngineMap engineMap) {
281             this.engineMap = engineMap;
282         }
283 
284         @Override
285         public boolean match(long ssl, String hostname) {
286             ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
287             if (engine != null) {
288                 // TODO: In the next release of tcnative we should pass the byte[] directly in and not use a String.
289                 return engine.checkSniHostnameMatch(hostname.getBytes(CharsetUtil.UTF_8));
290             }
291             logger.warn("No ReferenceCountedOpenSslEngine found for SSL pointer: {}", ssl);
292             return false;
293         }
294     }
295 }