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.SSL;
20  import io.netty.internal.tcnative.SSLContext;
21  import io.netty.internal.tcnative.SniHostNameMatcher;
22  import io.netty.util.CharsetUtil;
23  import io.netty.util.internal.PlatformDependent;
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 javax.net.ssl.KeyManagerFactory;
31  import javax.net.ssl.SSLException;
32  import javax.net.ssl.TrustManagerFactory;
33  import javax.net.ssl.X509ExtendedTrustManager;
34  import javax.net.ssl.X509TrustManager;
35  
36  import static io.netty.util.internal.ObjectUtil.checkNotNull;
37  
38  /**
39   * A server-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 ReferenceCountedOpenSslServerContext extends ReferenceCountedOpenSslContext {
47      private static final InternalLogger logger =
48              InternalLoggerFactory.getInstance(ReferenceCountedOpenSslServerContext.class);
49      private static final byte[] ID = {'n', 'e', 't', 't', 'y'};
50      private final OpenSslServerSessionContext sessionContext;
51      private final OpenSslKeyMaterialManager keyMaterialManager;
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              ServerContext context = newSessionContext(this, ctx, engineMap, trustCertCollection, trustManagerFactory,
76                                                        keyCertChain, key, keyPassword, keyManagerFactory);
77              sessionContext = context.sessionContext;
78              keyMaterialManager = context.keyMaterialManager;
79              success = true;
80          } finally {
81              if (!success) {
82                  release();
83              }
84          }
85      }
86  
87      @Override
88      public OpenSslServerSessionContext sessionContext() {
89          return sessionContext;
90      }
91  
92      @Override
93      OpenSslKeyMaterialManager keyMaterialManager() {
94          return keyMaterialManager;
95      }
96  
97      static final class ServerContext {
98          OpenSslServerSessionContext sessionContext;
99          OpenSslKeyMaterialManager keyMaterialManager;
100     }
101 
102     static ServerContext newSessionContext(ReferenceCountedOpenSslContext thiz, long ctx, OpenSslEngineMap engineMap,
103                                            X509Certificate[] trustCertCollection,
104                                            TrustManagerFactory trustManagerFactory,
105                                            X509Certificate[] keyCertChain, PrivateKey key,
106                                            String keyPassword, KeyManagerFactory keyManagerFactory)
107             throws SSLException {
108         ServerContext result = new ServerContext();
109         OpenSslKeyMaterialProvider keyMaterialProvider = null;
110         try {
111             try {
112                 SSLContext.setVerify(ctx, SSL.SSL_CVERIFY_NONE, VERIFY_DEPTH);
113                 if (!OpenSsl.useKeyManagerFactory()) {
114                     if (keyManagerFactory != null) {
115                         throw new IllegalArgumentException(
116                                 "KeyManagerFactory not supported");
117                     }
118                     checkNotNull(keyCertChain, "keyCertChain");
119 
120                     setKeyMaterial(ctx, keyCertChain, key, keyPassword);
121                 } else {
122                     // javadocs state that keyManagerFactory has precedent over keyCertChain, and we must have a
123                     // keyManagerFactory for the server so build one if it is not specified.
124                     if (keyManagerFactory == null) {
125                         char[] keyPasswordChars = keyStorePassword(keyPassword);
126                         KeyStore ks = buildKeyStore(keyCertChain, key, keyPasswordChars);
127                         if (ks.aliases().hasMoreElements()) {
128                             keyManagerFactory = new OpenSslX509KeyManagerFactory();
129                         } else {
130                             keyManagerFactory = new OpenSslCachingX509KeyManagerFactory(
131                                     KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()));
132                         }
133                         keyManagerFactory.init(ks, keyPasswordChars);
134                     }
135                     keyMaterialProvider = providerFor(keyManagerFactory, keyPassword);
136 
137                     result.keyMaterialManager = new OpenSslKeyMaterialManager(keyMaterialProvider);
138                 }
139             } catch (Exception e) {
140                 throw new SSLException("failed to set certificate and key", e);
141             }
142             try {
143                 if (trustCertCollection != null) {
144                     trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory);
145                 } else if (trustManagerFactory == null) {
146                     // Mimic the way SSLContext.getInstance(KeyManager[], null, null) works
147                     trustManagerFactory = TrustManagerFactory.getInstance(
148                             TrustManagerFactory.getDefaultAlgorithm());
149                     trustManagerFactory.init((KeyStore) null);
150                 }
151 
152                 final X509TrustManager manager = chooseTrustManager(trustManagerFactory.getTrustManagers());
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                 // Use this to prevent an error when running on java < 7
161                 if (useExtendedTrustManager(manager)) {
162                     SSLContext.setCertVerifyCallback(ctx,
163                             new ExtendedTrustManagerVerifyCallback(engineMap, (X509ExtendedTrustManager) manager));
164                 } else {
165                     SSLContext.setCertVerifyCallback(ctx, new TrustManagerVerifyCallback(engineMap, manager));
166                 }
167 
168                 X509Certificate[] issuers = manager.getAcceptedIssuers();
169                 if (issuers != null && issuers.length > 0) {
170                     long bio = 0;
171                     try {
172                         bio = toBIO(ByteBufAllocator.DEFAULT, issuers);
173                         if (!SSLContext.setCACertificateBio(ctx, bio)) {
174                             throw new SSLException("unable to setup accepted issuers for trustmanager " + manager);
175                         }
176                     } finally {
177                         freeBio(bio);
178                     }
179                 }
180 
181                 if (PlatformDependent.javaVersion() >= 8) {
182                     // Only do on Java8+ as SNIMatcher is not supported in earlier releases.
183                     // IMPORTANT: The callbacks set for hostname matching must be static to prevent memory leak as
184                     //            otherwise the context can never be collected. This is because the JNI code holds
185                     //            a global reference to the matcher.
186                     SSLContext.setSniHostnameMatcher(ctx, new OpenSslSniHostnameMatcher(engineMap));
187                 }
188             } catch (SSLException e) {
189                 throw e;
190             } catch (Exception e) {
191                 throw new SSLException("unable to setup trustmanager", e);
192             }
193 
194             result.sessionContext = new OpenSslServerSessionContext(thiz, keyMaterialProvider);
195             result.sessionContext.setSessionIdContext(ID);
196 
197             keyMaterialProvider = null;
198 
199             return result;
200         } finally {
201             if (keyMaterialProvider != null) {
202                 keyMaterialProvider.destroy();
203             }
204         }
205     }
206 
207     private static final class TrustManagerVerifyCallback extends AbstractCertificateVerifier {
208         private final X509TrustManager manager;
209 
210         TrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509TrustManager manager) {
211             super(engineMap);
212             this.manager = manager;
213         }
214 
215         @Override
216         void verify(ReferenceCountedOpenSslEngine engine, X509Certificate[] peerCerts, String auth)
217                 throws Exception {
218             manager.checkClientTrusted(peerCerts, auth);
219         }
220     }
221 
222     private static final class ExtendedTrustManagerVerifyCallback extends AbstractCertificateVerifier {
223         private final X509ExtendedTrustManager manager;
224 
225         ExtendedTrustManagerVerifyCallback(OpenSslEngineMap engineMap, X509ExtendedTrustManager 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, engine);
234         }
235     }
236 
237     private static final class OpenSslSniHostnameMatcher implements SniHostNameMatcher {
238         private final OpenSslEngineMap engineMap;
239 
240         OpenSslSniHostnameMatcher(OpenSslEngineMap engineMap) {
241             this.engineMap = engineMap;
242         }
243 
244         @Override
245         public boolean match(long ssl, String hostname) {
246             ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
247             if (engine != null) {
248                 // TODO: In the next release of tcnative we should pass the byte[] directly in and not use a String.
249                 return engine.checkSniHostnameMatch(hostname.getBytes(CharsetUtil.UTF_8));
250             }
251             logger.warn("No ReferenceCountedOpenSslEngine found for SSL pointer: {}", ssl);
252             return false;
253         }
254     }
255 }