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  package io.netty.handler.ssl;
17  
18  import io.netty.buffer.ByteBufAllocator;
19  import io.netty.util.internal.PlatformDependent;
20  import io.netty.util.internal.logging.InternalLogger;
21  import io.netty.util.internal.logging.InternalLoggerFactory;
22  import org.apache.tomcat.jni.Pool;
23  import org.apache.tomcat.jni.SSL;
24  import org.apache.tomcat.jni.SSLContext;
25  
26  import javax.net.ssl.SSLEngine;
27  import javax.net.ssl.SSLException;
28  import javax.net.ssl.TrustManager;
29  import javax.net.ssl.X509TrustManager;
30  import java.security.cert.X509Certificate;
31  import java.util.ArrayList;
32  import java.util.Collections;
33  import java.util.List;
34  import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
35  
36  import static io.netty.util.internal.ObjectUtil.checkNotNull;
37  
38  public abstract class OpenSslContext extends SslContext {
39  
40      private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSslContext.class);
41      private static final List<String> DEFAULT_CIPHERS;
42      private static final AtomicIntegerFieldUpdater<OpenSslContext> DESTROY_UPDATER;
43  
44      // TODO: Maybe make configurable ?
45      protected static final int VERIFY_DEPTH = 10;
46  
47      private final long aprPool;
48      @SuppressWarnings("unused")
49      private volatile int aprPoolDestroyed;
50      private final List<String> ciphers = new ArrayList<String>();
51      private final List<String> unmodifiableCiphers = Collections.unmodifiableList(ciphers);
52      private final long sessionCacheSize;
53      private final long sessionTimeout;
54      private final OpenSslApplicationProtocolNegotiator apn;
55      /** The OpenSSL SSL_CTX object */
56      protected final long ctx;
57      private final int mode;
58  
59      static {
60          List<String> ciphers = new ArrayList<String>();
61          // XXX: Make sure to sync this list with JdkSslEngineFactory.
62          Collections.addAll(
63                  ciphers,
64                  "ECDHE-RSA-AES128-GCM-SHA256",
65                  "ECDHE-RSA-AES128-SHA",
66                  "ECDHE-RSA-AES256-SHA",
67                  "AES128-GCM-SHA256",
68                  "AES128-SHA",
69                  "AES256-SHA",
70                  "DES-CBC3-SHA",
71                  "RC4-SHA");
72          DEFAULT_CIPHERS = Collections.unmodifiableList(ciphers);
73  
74          if (logger.isDebugEnabled()) {
75              logger.debug("Default cipher suite (OpenSSL): " + ciphers);
76          }
77  
78          AtomicIntegerFieldUpdater<OpenSslContext> updater =
79                  PlatformDependent.newAtomicIntegerFieldUpdater(OpenSslContext.class, "aprPoolDestroyed");
80          if (updater == null) {
81              updater = AtomicIntegerFieldUpdater.newUpdater(OpenSslContext.class, "aprPoolDestroyed");
82          }
83          DESTROY_UPDATER = updater;
84      }
85  
86      OpenSslContext(Iterable<String> ciphers, ApplicationProtocolConfig apnCfg, long sessionCacheSize,
87                     long sessionTimeout, int mode) throws SSLException {
88          this(ciphers, toNegotiator(apnCfg, mode == SSL.SSL_MODE_SERVER), sessionCacheSize, sessionTimeout, mode);
89      }
90  
91      OpenSslContext(Iterable<String> ciphers, OpenSslApplicationProtocolNegotiator apn, long sessionCacheSize,
92                     long sessionTimeout, int mode) throws SSLException {
93          OpenSsl.ensureAvailability();
94  
95          if (mode != SSL.SSL_MODE_SERVER && mode != SSL.SSL_MODE_CLIENT) {
96              throw new IllegalArgumentException("mode most be either SSL.SSL_MODE_SERVER or SSL.SSL_MODE_CLIENT");
97          }
98          this.mode = mode;
99  
100         if (ciphers == null) {
101             ciphers = DEFAULT_CIPHERS;
102         }
103 
104         for (String c: ciphers) {
105             if (c == null) {
106                 break;
107             }
108 
109             String converted = CipherSuiteConverter.toOpenSsl(c);
110             if (converted != null) {
111                 c = converted;
112             }
113 
114             this.ciphers.add(c);
115         }
116 
117         this.apn = checkNotNull(apn, "apn");
118 
119         // Allocate a new APR pool.
120         aprPool = Pool.create(0);
121 
122         // Create a new SSL_CTX and configure it.
123         boolean success = false;
124         try {
125             synchronized (OpenSslContext.class) {
126                 try {
127                     ctx = SSLContext.make(aprPool, SSL.SSL_PROTOCOL_ALL, mode);
128                 } catch (Exception e) {
129                     throw new SSLException("failed to create an SSL_CTX", e);
130                 }
131 
132                 SSLContext.setOptions(ctx, SSL.SSL_OP_ALL);
133                 SSLContext.setOptions(ctx, SSL.SSL_OP_NO_SSLv2);
134                 SSLContext.setOptions(ctx, SSL.SSL_OP_NO_SSLv3);
135                 SSLContext.setOptions(ctx, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
136                 SSLContext.setOptions(ctx, SSL.SSL_OP_SINGLE_ECDH_USE);
137                 SSLContext.setOptions(ctx, SSL.SSL_OP_SINGLE_DH_USE);
138                 SSLContext.setOptions(ctx, SSL.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
139 
140                 /* List the ciphers that are permitted to negotiate. */
141                 try {
142                     SSLContext.setCipherSuite(ctx, CipherSuiteConverter.toOpenSsl(this.ciphers));
143                 } catch (SSLException e) {
144                     throw e;
145                 } catch (Exception e) {
146                     throw new SSLException("failed to set cipher suite: " + this.ciphers, e);
147                 }
148 
149                 List<String> nextProtoList = apn.protocols();
150                 /* Set next protocols for next protocol negotiation extension, if specified */
151                 if (!nextProtoList.isEmpty()) {
152                     // Convert the protocol list into a comma-separated string.
153                     StringBuilder nextProtocolBuf = new StringBuilder();
154                     for (String p: nextProtoList) {
155                         nextProtocolBuf.append(p);
156                         nextProtocolBuf.append(',');
157                     }
158                     nextProtocolBuf.setLength(nextProtocolBuf.length() - 1);
159 
160                     SSLContext.setNextProtos(ctx, nextProtocolBuf.toString());
161                 }
162 
163                 /* Set session cache size, if specified */
164                 if (sessionCacheSize > 0) {
165                     this.sessionCacheSize = sessionCacheSize;
166                     SSLContext.setSessionCacheSize(ctx, sessionCacheSize);
167                 } else {
168                     // Get the default session cache size using SSLContext.setSessionCacheSize()
169                     this.sessionCacheSize = sessionCacheSize = SSLContext.setSessionCacheSize(ctx, 20480);
170                     // Revert the session cache size to the default value.
171                     SSLContext.setSessionCacheSize(ctx, sessionCacheSize);
172                 }
173 
174                 /* Set session timeout, if specified */
175                 if (sessionTimeout > 0) {
176                     this.sessionTimeout = sessionTimeout;
177                     SSLContext.setSessionCacheTimeout(ctx, sessionTimeout);
178                 } else {
179                     // Get the default session timeout using SSLContext.setSessionCacheTimeout()
180                     this.sessionTimeout = sessionTimeout = SSLContext.setSessionCacheTimeout(ctx, 300);
181                     // Revert the session timeout to the default value.
182                     SSLContext.setSessionCacheTimeout(ctx, sessionTimeout);
183                 }
184             }
185             success = true;
186         } finally {
187             if (!success) {
188                 destroyPools();
189             }
190         }
191     }
192 
193     @Override
194     public final List<String> cipherSuites() {
195         return unmodifiableCiphers;
196     }
197 
198     @Override
199     public final long sessionCacheSize() {
200         return sessionCacheSize;
201     }
202 
203     @Override
204     public final long sessionTimeout() {
205         return sessionTimeout;
206     }
207 
208     @Override
209     public ApplicationProtocolNegotiator applicationProtocolNegotiator() {
210         return apn;
211     }
212 
213     @Override
214     public final boolean isClient() {
215         return mode == SSL.SSL_MODE_CLIENT;
216     }
217 
218     @Override
219     public final SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
220         throw new UnsupportedOperationException();
221     }
222 
223     /**
224      * Returns a new server-side {@link javax.net.ssl.SSLEngine} with the current configuration.
225      */
226     @Override
227     public final SSLEngine newEngine(ByteBufAllocator alloc) {
228         List<String> protos = applicationProtocolNegotiator().protocols();
229         if (protos.isEmpty()) {
230             return new OpenSslEngine(ctx, alloc, null, isClient(), sessionContext());
231         } else {
232             return new OpenSslEngine(ctx, alloc, protos.get(protos.size() - 1), isClient(), sessionContext());
233         }
234     }
235 
236     /**
237      * Returns the {@code SSL_CTX} object of this context.
238      */
239     public final long context() {
240         return ctx;
241     }
242 
243     /**
244      * Returns the stats of this context.
245      * @deprecated use {@link #sessionContext#stats()}
246      */
247     @Deprecated
248     public final OpenSslSessionStats stats() {
249         return sessionContext().stats();
250     }
251 
252     @Override
253     @SuppressWarnings("FinalizeDeclaration")
254     protected final void finalize() throws Throwable {
255         super.finalize();
256         synchronized (OpenSslContext.class) {
257             if (ctx != 0) {
258                 SSLContext.free(ctx);
259             }
260         }
261 
262         destroyPools();
263     }
264 
265     /**
266      * Sets the SSL session ticket keys of this context.
267      * @deprecated use {@link OpenSslSessionContext#setTicketKeys(byte[])}
268      */
269     @Deprecated
270     public final void setTicketKeys(byte[] keys) {
271         sessionContext().setTicketKeys(keys);
272     }
273 
274     @Override
275     public abstract OpenSslSessionContext sessionContext();
276 
277     protected final void destroyPools() {
278         // Guard against multiple destroyPools() calls triggered by construction exception and finalize() later
279         if (aprPool != 0 && DESTROY_UPDATER.compareAndSet(this, 0, 1)) {
280             Pool.destroy(aprPool);
281         }
282     }
283 
284     protected static X509Certificate[] certificates(byte[][] chain) {
285         X509Certificate[] peerCerts = new X509Certificate[chain.length];
286         for (int i = 0; i < peerCerts.length; i++) {
287             peerCerts[i] = new OpenSslX509Certificate(chain[i]);
288         }
289         return peerCerts;
290     }
291 
292     protected static X509TrustManager chooseTrustManager(TrustManager[] managers) {
293         for (TrustManager m: managers) {
294             if (m instanceof X509TrustManager) {
295                 return (X509TrustManager) m;
296             }
297         }
298         throw new IllegalStateException("no X509TrustManager found");
299     }
300 
301     /**
302      * Translate a {@link ApplicationProtocolConfig} object to a
303      * {@link OpenSslApplicationProtocolNegotiator} object.
304      * @param config The configuration which defines the translation
305      * @param isServer {@code true} if a server {@code false} otherwise.
306      * @return The results of the translation
307      */
308     static OpenSslApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config,
309                                                              boolean isServer) {
310         if (config == null) {
311             return OpenSslDefaultApplicationProtocolNegotiator.INSTANCE;
312         }
313 
314         switch (config.protocol()) {
315             case NONE:
316                 return OpenSslDefaultApplicationProtocolNegotiator.INSTANCE;
317             case NPN:
318                 if (isServer) {
319                     switch (config.selectedListenerFailureBehavior()) {
320                         case CHOOSE_MY_LAST_PROTOCOL:
321                             return new OpenSslNpnApplicationProtocolNegotiator(config.supportedProtocols());
322                         default:
323                             throw new UnsupportedOperationException(
324                                     new StringBuilder("OpenSSL provider does not support ")
325                                             .append(config.selectedListenerFailureBehavior())
326                                             .append(" behavior").toString());
327                     }
328                 } else {
329                     throw new UnsupportedOperationException("OpenSSL provider does not support client mode");
330                 }
331             default:
332                 throw new UnsupportedOperationException(new StringBuilder("OpenSSL provider does not support ")
333                         .append(config.protocol()).append(" protocol").toString());
334         }
335     }
336 }