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