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.util.internal.NativeLibraryLoader;
20  import io.netty.util.internal.logging.InternalLogger;
21  import io.netty.util.internal.logging.InternalLoggerFactory;
22  import org.apache.tomcat.jni.Library;
23  import org.apache.tomcat.jni.Pool;
24  import org.apache.tomcat.jni.SSL;
25  import org.apache.tomcat.jni.SSLContext;
26  
27  import java.util.Collections;
28  import java.util.LinkedHashSet;
29  import java.util.Set;
30  
31  /**
32   * Tells if <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
33   * are available.
34   */
35  public final class OpenSsl {
36  
37      private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class);
38      private static final Throwable UNAVAILABILITY_CAUSE;
39  
40      private static final Set<String> AVAILABLE_CIPHER_SUITES;
41  
42      static {
43          Throwable cause = null;
44  
45          // Test if netty-tcnative is in the classpath first.
46          try {
47              Class.forName("org.apache.tomcat.jni.SSL", false, OpenSsl.class.getClassLoader());
48          } catch (ClassNotFoundException t) {
49              cause = t;
50              logger.debug(
51                      "netty-tcnative not in the classpath; " +
52                      OpenSslEngine.class.getSimpleName() + " will be unavailable.");
53          }
54  
55          // If in the classpath, try to load the native library and initialize netty-tcnative.
56          if (cause == null) {
57              try {
58                  NativeLibraryLoader.load("netty-tcnative", SSL.class.getClassLoader());
59                  Library.initialize("provided");
60                  SSL.initialize(null);
61              } catch (Throwable t) {
62                  cause = t;
63                  logger.debug(
64                          "Failed to load netty-tcnative; " +
65                          OpenSslEngine.class.getSimpleName() + " will be unavailable. " +
66                          "See http://netty.io/wiki/forked-tomcat-native.html for more information.", t);
67              }
68          }
69  
70          UNAVAILABILITY_CAUSE = cause;
71  
72          if (cause == null) {
73              final Set<String> availableCipherSuites = new LinkedHashSet<String>(128);
74              final long aprPool = Pool.create(0);
75              try {
76                  final long sslCtx = SSLContext.make(aprPool, SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER);
77                  try {
78                      SSLContext.setOptions(sslCtx, SSL.SSL_OP_ALL);
79                      SSLContext.setCipherSuite(sslCtx, "ALL");
80                      final long ssl = SSL.newSSL(sslCtx, true);
81                      try {
82                          for (String c: SSL.getCiphers(ssl)) {
83                              // Filter out bad input.
84                              if (c == null || c.length() == 0 || availableCipherSuites.contains(c)) {
85                                  continue;
86                              }
87                              availableCipherSuites.add(c);
88                          }
89                      } finally {
90                          SSL.freeSSL(ssl);
91                      }
92                  } finally {
93                      SSLContext.free(sslCtx);
94                  }
95              } catch (Exception e) {
96                  logger.warn("Failed to get the list of available OpenSSL cipher suites.", e);
97              } finally {
98                  Pool.destroy(aprPool);
99              }
100 
101             AVAILABLE_CIPHER_SUITES = Collections.unmodifiableSet(availableCipherSuites);
102         } else {
103             AVAILABLE_CIPHER_SUITES = Collections.emptySet();
104         }
105     }
106 
107     /**
108      * Returns {@code true} if and only if
109      * <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
110      * are available.
111      */
112     public static boolean isAvailable() {
113         return UNAVAILABILITY_CAUSE == null;
114     }
115 
116     /**
117      * Ensure that <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and
118      * its OpenSSL support are available.
119      *
120      * @throws UnsatisfiedLinkError if unavailable
121      */
122     public static void ensureAvailability() {
123         if (UNAVAILABILITY_CAUSE != null) {
124             throw (Error) new UnsatisfiedLinkError(
125                     "failed to load the required native library").initCause(UNAVAILABILITY_CAUSE);
126         }
127     }
128 
129     /**
130      * Returns the cause of unavailability of
131      * <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support.
132      *
133      * @return the cause if unavailable. {@code null} if available.
134      */
135     public static Throwable unavailabilityCause() {
136         return UNAVAILABILITY_CAUSE;
137     }
138 
139     /**
140      * Returns all the available OpenSSL cipher suites.
141      * Please note that the returned array may include the cipher suites that are insecure or non-functional.
142      */
143     public static Set<String> availableCipherSuites() {
144         return AVAILABLE_CIPHER_SUITES;
145     }
146 
147     /**
148      * Returns {@code true} if and only if the specified cipher suite is available in OpenSSL.
149      * Both Java-style cipher suite and OpenSSL-style cipher suite are accepted.
150      */
151     public static boolean isCipherSuiteAvailable(String cipherSuite) {
152         String converted = CipherSuiteConverter.toOpenSsl(cipherSuite);
153         if (converted != null) {
154             cipherSuite = converted;
155         }
156         return AVAILABLE_CIPHER_SUITES.contains(cipherSuite);
157     }
158 
159     static boolean isError(long errorCode) {
160         return errorCode != SSL.SSL_ERROR_NONE;
161     }
162 
163     private OpenSsl() { }
164 }