View Javadoc
1   /*
2    * Copyright 2014 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  
17  package io.netty.handler.ssl;
18  
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.util.internal.EmptyArrays;
21  import io.netty.util.internal.logging.InternalLogger;
22  import io.netty.util.internal.logging.InternalLoggerFactory;
23  
24  import java.io.File;
25  import java.io.IOException;
26  import java.security.InvalidAlgorithmParameterException;
27  import java.security.KeyException;
28  import java.security.KeyStore;
29  import java.security.KeyStoreException;
30  import java.security.NoSuchAlgorithmException;
31  import java.security.PrivateKey;
32  import java.security.Security;
33  import java.security.UnrecoverableKeyException;
34  import java.security.cert.CertificateException;
35  import java.security.cert.X509Certificate;
36  import java.security.spec.InvalidKeySpecException;
37  import java.util.ArrayList;
38  import java.util.Arrays;
39  import java.util.Collections;
40  import java.util.HashSet;
41  import java.util.List;
42  import java.util.Set;
43  
44  import javax.crypto.NoSuchPaddingException;
45  import javax.net.ssl.KeyManagerFactory;
46  import javax.net.ssl.SSLContext;
47  import javax.net.ssl.SSLEngine;
48  import javax.net.ssl.SSLSessionContext;
49  
50  import static io.netty.handler.ssl.SslUtils.DEFAULT_CIPHER_SUITES;
51  import static io.netty.handler.ssl.SslUtils.addIfSupported;
52  import static io.netty.handler.ssl.SslUtils.useFallbackCiphersIfDefaultIsEmpty;
53  import static io.netty.util.internal.ObjectUtil.checkNotNull;
54  
55  /**
56   * An {@link SslContext} which uses JDK's SSL/TLS implementation.
57   */
58  public class JdkSslContext extends SslContext {
59  
60      private static final InternalLogger logger = InternalLoggerFactory.getInstance(JdkSslContext.class);
61  
62      static final String PROTOCOL = "TLS";
63      private static final String[] DEFAULT_PROTOCOLS;
64      private static final List<String> DEFAULT_CIPHERS;
65      private static final Set<String> SUPPORTED_CIPHERS;
66  
67      static {
68          SSLContext context;
69          int i;
70          try {
71              context = SSLContext.getInstance(PROTOCOL);
72              context.init(null, null, null);
73          } catch (Exception e) {
74              throw new Error("failed to initialize the default SSL context", e);
75          }
76  
77          SSLEngine engine = context.createSSLEngine();
78  
79          // Choose the sensible default list of protocols.
80          final String[] supportedProtocols = engine.getSupportedProtocols();
81          Set<String> supportedProtocolsSet = new HashSet<String>(supportedProtocols.length);
82          for (i = 0; i < supportedProtocols.length; ++i) {
83              supportedProtocolsSet.add(supportedProtocols[i]);
84          }
85          List<String> protocols = new ArrayList<String>();
86          addIfSupported(
87                  supportedProtocolsSet, protocols,
88                  "TLSv1.2", "TLSv1.1", "TLSv1");
89  
90          if (!protocols.isEmpty()) {
91              DEFAULT_PROTOCOLS = protocols.toArray(new String[protocols.size()]);
92          } else {
93              DEFAULT_PROTOCOLS = engine.getEnabledProtocols();
94          }
95  
96          // Choose the sensible default list of cipher suites.
97          final String[] supportedCiphers = engine.getSupportedCipherSuites();
98          SUPPORTED_CIPHERS = new HashSet<String>(supportedCiphers.length);
99          for (i = 0; i < supportedCiphers.length; ++i) {
100             String supportedCipher = supportedCiphers[i];
101             SUPPORTED_CIPHERS.add(supportedCipher);
102             // IBM's J9 JVM utilizes a custom naming scheme for ciphers and only returns ciphers with the "SSL_"
103             // prefix instead of the "TLS_" prefix (as defined in the JSSE cipher suite names [1]). According to IBM's
104             // documentation [2] the "SSL_" prefix is "interchangeable" with the "TLS_" prefix.
105             // See the IBM forum discussion [3] and issue on IBM's JVM [4] for more details.
106             //[1] http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites
107             //[2] https://www.ibm.com/support/knowledgecenter/en/SSYKE2_8.0.0/com.ibm.java.security.component.80.doc/
108             // security-component/jsse2Docs/ciphersuites.html
109             //[3] https://www.ibm.com/developerworks/community/forums/html/topic?id=9b5a56a9-fa46-4031-b33b-df91e28d77c2
110             //[4] https://www.ibm.com/developerworks/rfe/execute?use_case=viewRfe&CR_ID=71770
111             if (supportedCipher.startsWith("SSL_")) {
112                 SUPPORTED_CIPHERS.add("TLS_" + supportedCipher.substring("SSL_".length()));
113             }
114         }
115         List<String> ciphers = new ArrayList<String>();
116         addIfSupported(SUPPORTED_CIPHERS, ciphers, DEFAULT_CIPHER_SUITES);
117         useFallbackCiphersIfDefaultIsEmpty(ciphers, engine.getEnabledCipherSuites());
118         DEFAULT_CIPHERS = Collections.unmodifiableList(ciphers);
119 
120         if (logger.isDebugEnabled()) {
121             logger.debug("Default protocols (JDK): {} ", Arrays.asList(DEFAULT_PROTOCOLS));
122             logger.debug("Default cipher suites (JDK): {}", DEFAULT_CIPHERS);
123         }
124     }
125 
126     private final String[] protocols;
127     private final String[] cipherSuites;
128     private final List<String> unmodifiableCipherSuites;
129     @SuppressWarnings("deprecation")
130     private final JdkApplicationProtocolNegotiator apn;
131     private final ClientAuth clientAuth;
132     private final SSLContext sslContext;
133     private final boolean isClient;
134 
135     /**
136      * Creates a new {@link JdkSslContext} from a pre-configured {@link SSLContext}.
137      *
138      * @param sslContext the {@link SSLContext} to use.
139      * @param isClient {@code true} if this context should create {@link SSLEngine}s for client-side usage.
140      * @param clientAuth the {@link ClientAuth} to use. This will only be used when {@param isClient} is {@code false}.
141      */
142     public JdkSslContext(SSLContext sslContext, boolean isClient,
143                          ClientAuth clientAuth) {
144         this(sslContext, isClient, null, IdentityCipherSuiteFilter.INSTANCE,
145                 JdkDefaultApplicationProtocolNegotiator.INSTANCE, clientAuth, null, false);
146     }
147 
148     /**
149      * Creates a new {@link JdkSslContext} from a pre-configured {@link SSLContext}.
150      *
151      * @param sslContext the {@link SSLContext} to use.
152      * @param isClient {@code true} if this context should create {@link SSLEngine}s for client-side usage.
153      * @param ciphers the ciphers to use or {@code null} if the standard should be used.
154      * @param cipherFilter the filter to use.
155      * @param apn the {@link ApplicationProtocolConfig} to use.
156      * @param clientAuth the {@link ClientAuth} to use. This will only be used when {@param isClient} is {@code false}.
157      */
158     public JdkSslContext(SSLContext sslContext, boolean isClient, Iterable<String> ciphers,
159                          CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
160                          ClientAuth clientAuth) {
161         this(sslContext, isClient, ciphers, cipherFilter, toNegotiator(apn, !isClient), clientAuth, null, false);
162     }
163 
164     @SuppressWarnings("deprecation")
165     JdkSslContext(SSLContext sslContext, boolean isClient, Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
166                   JdkApplicationProtocolNegotiator apn, ClientAuth clientAuth, String[] protocols, boolean startTls) {
167         super(startTls);
168         this.apn = checkNotNull(apn, "apn");
169         this.clientAuth = checkNotNull(clientAuth, "clientAuth");
170         cipherSuites = checkNotNull(cipherFilter, "cipherFilter").filterCipherSuites(
171                 ciphers, DEFAULT_CIPHERS, SUPPORTED_CIPHERS);
172         this.protocols = protocols == null ? DEFAULT_PROTOCOLS : protocols;
173         unmodifiableCipherSuites = Collections.unmodifiableList(Arrays.asList(cipherSuites));
174         this.sslContext = checkNotNull(sslContext, "sslContext");
175         this.isClient = isClient;
176     }
177 
178     /**
179      * Returns the JDK {@link SSLContext} object held by this context.
180      */
181     public final SSLContext context() {
182         return sslContext;
183     }
184 
185     @Override
186     public final boolean isClient() {
187         return isClient;
188     }
189 
190     /**
191      * Returns the JDK {@link SSLSessionContext} object held by this context.
192      */
193     @Override
194     public final SSLSessionContext sessionContext() {
195         if (isServer()) {
196             return context().getServerSessionContext();
197         } else {
198             return context().getClientSessionContext();
199         }
200     }
201 
202     @Override
203     public final List<String> cipherSuites() {
204         return unmodifiableCipherSuites;
205     }
206 
207     @Override
208     public final long sessionCacheSize() {
209         return sessionContext().getSessionCacheSize();
210     }
211 
212     @Override
213     public final long sessionTimeout() {
214         return sessionContext().getSessionTimeout();
215     }
216 
217     @Override
218     public final SSLEngine newEngine(ByteBufAllocator alloc) {
219         return configureAndWrapEngine(context().createSSLEngine(), alloc);
220     }
221 
222     @Override
223     public final SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
224         return configureAndWrapEngine(context().createSSLEngine(peerHost, peerPort), alloc);
225     }
226 
227     @SuppressWarnings("deprecation")
228     private SSLEngine configureAndWrapEngine(SSLEngine engine, ByteBufAllocator alloc) {
229         engine.setEnabledCipherSuites(cipherSuites);
230         engine.setEnabledProtocols(protocols);
231         engine.setUseClientMode(isClient());
232         if (isServer()) {
233             switch (clientAuth) {
234                 case OPTIONAL:
235                     engine.setWantClientAuth(true);
236                     break;
237                 case REQUIRE:
238                     engine.setNeedClientAuth(true);
239                     break;
240                 case NONE:
241                     break; // exhaustive cases
242                 default:
243                     throw new Error("Unknown auth " + clientAuth);
244             }
245         }
246         JdkApplicationProtocolNegotiator.SslEngineWrapperFactory factory = apn.wrapperFactory();
247         if (factory instanceof JdkApplicationProtocolNegotiator.AllocatorAwareSslEngineWrapperFactory) {
248             return ((JdkApplicationProtocolNegotiator.AllocatorAwareSslEngineWrapperFactory) factory)
249                     .wrapSslEngine(engine, alloc, apn, isServer());
250         }
251         return factory.wrapSslEngine(engine, apn, isServer());
252     }
253 
254     @Override
255     public final JdkApplicationProtocolNegotiator applicationProtocolNegotiator() {
256         return apn;
257     }
258 
259     /**
260      * Translate a {@link ApplicationProtocolConfig} object to a {@link JdkApplicationProtocolNegotiator} object.
261      * @param config The configuration which defines the translation
262      * @param isServer {@code true} if a server {@code false} otherwise.
263      * @return The results of the translation
264      */
265     @SuppressWarnings("deprecation")
266     static JdkApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config, boolean isServer) {
267         if (config == null) {
268             return JdkDefaultApplicationProtocolNegotiator.INSTANCE;
269         }
270 
271         switch(config.protocol()) {
272         case NONE:
273             return JdkDefaultApplicationProtocolNegotiator.INSTANCE;
274         case ALPN:
275             if (isServer) {
276                 switch(config.selectorFailureBehavior()) {
277                 case FATAL_ALERT:
278                     return new JdkAlpnApplicationProtocolNegotiator(true, config.supportedProtocols());
279                 case NO_ADVERTISE:
280                     return new JdkAlpnApplicationProtocolNegotiator(false, config.supportedProtocols());
281                 default:
282                     throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
283                     .append(config.selectorFailureBehavior()).append(" failure behavior").toString());
284                 }
285             } else {
286                 switch(config.selectedListenerFailureBehavior()) {
287                 case ACCEPT:
288                     return new JdkAlpnApplicationProtocolNegotiator(false, config.supportedProtocols());
289                 case FATAL_ALERT:
290                     return new JdkAlpnApplicationProtocolNegotiator(true, config.supportedProtocols());
291                 default:
292                     throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
293                     .append(config.selectedListenerFailureBehavior()).append(" failure behavior").toString());
294                 }
295             }
296         case NPN:
297             if (isServer) {
298                 switch(config.selectedListenerFailureBehavior()) {
299                 case ACCEPT:
300                     return new JdkNpnApplicationProtocolNegotiator(false, config.supportedProtocols());
301                 case FATAL_ALERT:
302                     return new JdkNpnApplicationProtocolNegotiator(true, config.supportedProtocols());
303                 default:
304                     throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
305                     .append(config.selectedListenerFailureBehavior()).append(" failure behavior").toString());
306                 }
307             } else {
308                 switch(config.selectorFailureBehavior()) {
309                 case FATAL_ALERT:
310                     return new JdkNpnApplicationProtocolNegotiator(true, config.supportedProtocols());
311                 case NO_ADVERTISE:
312                     return new JdkNpnApplicationProtocolNegotiator(false, config.supportedProtocols());
313                 default:
314                     throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
315                     .append(config.selectorFailureBehavior()).append(" failure behavior").toString());
316                 }
317             }
318         default:
319             throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
320             .append(config.protocol()).append(" protocol").toString());
321         }
322     }
323 
324     /**
325      * Build a {@link KeyManagerFactory} based upon a key file, key file password, and a certificate chain.
326      * @param certChainFile a X.509 certificate chain file in PEM format
327      * @param keyFile a PKCS#8 private key file in PEM format
328      * @param keyPassword the password of the {@code keyFile}.
329      *                    {@code null} if it's not password-protected.
330      * @param kmf The existing {@link KeyManagerFactory} that will be used if not {@code null}
331      * @return A {@link KeyManagerFactory} based upon a key file, key file password, and a certificate chain.
332      * @deprecated will be removed.
333      */
334     @Deprecated
335     protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword,
336             KeyManagerFactory kmf)
337                     throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
338                     NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,
339                     CertificateException, KeyException, IOException {
340         String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
341         if (algorithm == null) {
342             algorithm = "SunX509";
343         }
344         return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf);
345     }
346 
347     /**
348      * Build a {@link KeyManagerFactory} based upon a key algorithm, key file, key file password,
349      * and a certificate chain.
350      * @param certChainFile a X.509 certificate chain file in PEM format
351      * @param keyAlgorithm the standard name of the requested algorithm. See the Java Secure Socket Extension
352      * Reference Guide for information about standard algorithm names.
353      * @param keyFile a PKCS#8 private key file in PEM format
354      * @param keyPassword the password of the {@code keyFile}.
355      *                    {@code null} if it's not password-protected.
356      * @param kmf The existing {@link KeyManagerFactory} that will be used if not {@code null}
357      * @return A {@link KeyManagerFactory} based upon a key algorithm, key file, key file password,
358      * and a certificate chain.
359      * @deprecated will be removed.
360      */
361     @Deprecated
362     protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile,
363             String keyAlgorithm, File keyFile, String keyPassword, KeyManagerFactory kmf)
364                     throws KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException,
365                     InvalidKeySpecException, InvalidAlgorithmParameterException, IOException,
366                     CertificateException, KeyException, UnrecoverableKeyException {
367         return buildKeyManagerFactory(toX509Certificates(certChainFile), keyAlgorithm,
368                                       toPrivateKey(keyFile, keyPassword), keyPassword, kmf);
369     }
370 }