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.PlatformDependent;
20  import io.netty.util.internal.logging.InternalLogger;
21  import io.netty.util.internal.logging.InternalLoggerFactory;
22  
23  import java.util.HashMap;
24  import java.util.Map;
25  import java.util.concurrent.ConcurrentMap;
26  import java.util.regex.Matcher;
27  import java.util.regex.Pattern;
28  
29  /**
30   * Converts a Java cipher suite string to an OpenSSL cipher suite string and vice versa.
31   *
32   * @see <a href="http://en.wikipedia.org/wiki/Cipher_suite">Wikipedia page about cipher suite</a>
33   */
34  final class CipherSuiteConverter {
35  
36      private static final InternalLogger logger = InternalLoggerFactory.getInstance(CipherSuiteConverter.class);
37  
38      /**
39       * A_B_WITH_C_D, where:
40       *
41       * A - TLS or SSL (protocol)
42       * B - handshake algorithm (key exchange and authentication algorithms to be precise)
43       * C - bulk cipher
44       * D - HMAC algorithm
45       *
46       * This regular expression assumees that:
47       *
48       * 1) A is always TLS or SSL, and
49       * 2) D is always a single word.
50       */
51      private static final Pattern JAVA_CIPHERSUITE_PATTERN =
52              Pattern.compile("^(?:TLS|SSL)_((?:(?!_WITH_).)+)_WITH_(.*)_(.*)$");
53  
54      /**
55       * A-B-C, where:
56       *
57       * A - handshake algorithm (key exchange and authentication algorithms to be precise)
58       * B - bulk cipher
59       * C - HMAC algorithm
60       *
61       * This regular expression assumes that:
62       *
63       * 1) A has some deterministic pattern as shown below, and
64       * 2) C is always a single word
65       */
66      private static final Pattern OPENSSL_CIPHERSUITE_PATTERN =
67              // Be very careful not to break the indentation while editing.
68              Pattern.compile(
69                      "^(?:(" + // BEGIN handshake algorithm
70                          "(?:(?:EXP-)?" +
71                              "(?:" +
72                                  "(?:DHE|EDH|ECDH|ECDHE|SRP)-(?:DSS|RSA|ECDSA)|" +
73                                  "(?:ADH|AECDH|KRB5|PSK|SRP)" +
74                              ')' +
75                          ")|" +
76                          "EXP" +
77                      ")-)?" +  // END handshake algorithm
78                      "(.*)-(.*)$");
79  
80      private static final Pattern JAVA_AES_CBC_PATTERN = Pattern.compile("^(AES)_([0-9]+)_CBC$");
81      private static final Pattern JAVA_AES_PATTERN = Pattern.compile("^(AES)_([0-9]+)_(.*)$");
82      private static final Pattern OPENSSL_AES_CBC_PATTERN = Pattern.compile("^(AES)([0-9]+)$");
83      private static final Pattern OPENSSL_AES_PATTERN = Pattern.compile("^(AES)([0-9]+)-(.*)$");
84  
85      /**
86       * Java-to-OpenSSL cipher suite conversion map
87       * Note that the Java cipher suite has the protocol prefix (TLS_, SSL_)
88       */
89      private static final ConcurrentMap<String, String> j2o = PlatformDependent.newConcurrentHashMap();
90  
91      /**
92       * OpenSSL-to-Java cipher suite conversion map.
93       * Note that one OpenSSL cipher suite can be converted to more than one Java cipher suites because
94       * a Java cipher suite has the protocol name prefix (TLS_, SSL_)
95       */
96      private static final ConcurrentMap<String, Map<String, String>> o2j = PlatformDependent.newConcurrentHashMap();
97  
98      /**
99       * Clears the cache for testing purpose.
100      */
101     static void clearCache() {
102         j2o.clear();
103         o2j.clear();
104     }
105 
106     /**
107      * Tests if the specified key-value pair has been cached in Java-to-OpenSSL cache.
108      */
109     static boolean isJ2OCached(String key, String value) {
110         return value.equals(j2o.get(key));
111     }
112 
113     /**
114      * Tests if the specified key-value pair has been cached in OpenSSL-to-Java cache.
115      */
116     static boolean isO2JCached(String key, String protocol, String value) {
117         Map<String, String> p2j = o2j.get(key);
118         if (p2j == null) {
119             return false;
120         } else {
121             return value.equals(p2j.get(protocol));
122         }
123     }
124 
125     /**
126      * Converts the specified Java cipher suites to the colon-separated OpenSSL cipher suite specification.
127      */
128     static String toOpenSsl(Iterable<String> javaCipherSuites) {
129         final StringBuilder buf = new StringBuilder();
130         for (String c: javaCipherSuites) {
131             if (c == null) {
132                 break;
133             }
134 
135             String converted = toOpenSsl(c);
136             if (converted != null) {
137                 c = converted;
138             }
139 
140             buf.append(c);
141             buf.append(':');
142         }
143 
144         if (buf.length() > 0) {
145             buf.setLength(buf.length() - 1);
146             return buf.toString();
147         } else {
148             return "";
149         }
150     }
151 
152     /**
153      * Converts the specified Java cipher suite to its corresponding OpenSSL cipher suite name.
154      *
155      * @return {@code null} if the conversion has failed
156      */
157     static String toOpenSsl(String javaCipherSuite) {
158         String converted = j2o.get(javaCipherSuite);
159         if (converted != null) {
160             return converted;
161         } else {
162             return cacheFromJava(javaCipherSuite);
163         }
164     }
165 
166     private static String cacheFromJava(String javaCipherSuite) {
167         String openSslCipherSuite = toOpenSslUncached(javaCipherSuite);
168         if (openSslCipherSuite == null) {
169             return null;
170         }
171 
172         // Cache the mapping.
173         j2o.putIfAbsent(javaCipherSuite, openSslCipherSuite);
174 
175         // Cache the reverse mapping after stripping the protocol prefix (TLS_ or SSL_)
176         final String javaCipherSuiteSuffix = javaCipherSuite.substring(4);
177         Map<String, String> p2j = new HashMap<String, String>(4);
178         p2j.put("", javaCipherSuiteSuffix);
179         p2j.put("SSL", "SSL_" + javaCipherSuiteSuffix);
180         p2j.put("TLS", "TLS_" + javaCipherSuiteSuffix);
181         o2j.put(openSslCipherSuite, p2j);
182 
183         logger.debug("Cipher suite mapping: {} => {}", javaCipherSuite, openSslCipherSuite);
184 
185         return openSslCipherSuite;
186     }
187 
188     static String toOpenSslUncached(String javaCipherSuite) {
189         Matcher m = JAVA_CIPHERSUITE_PATTERN.matcher(javaCipherSuite);
190         if (!m.matches()) {
191             return null;
192         }
193 
194         String handshakeAlgo = toOpenSslHandshakeAlgo(m.group(1));
195         String bulkCipher = toOpenSslBulkCipher(m.group(2));
196         String hmacAlgo = toOpenSslHmacAlgo(m.group(3));
197         if (handshakeAlgo.length() == 0) {
198             return bulkCipher + '-' + hmacAlgo;
199         } else {
200             return handshakeAlgo + '-' + bulkCipher + '-' + hmacAlgo;
201         }
202     }
203 
204     private static String toOpenSslHandshakeAlgo(String handshakeAlgo) {
205         final boolean export = handshakeAlgo.endsWith("_EXPORT");
206         if (export) {
207             handshakeAlgo = handshakeAlgo.substring(0, handshakeAlgo.length() - 7);
208         }
209 
210         if ("RSA".equals(handshakeAlgo)) {
211             handshakeAlgo = "";
212         } else if (handshakeAlgo.endsWith("_anon")) {
213             handshakeAlgo = 'A' + handshakeAlgo.substring(0, handshakeAlgo.length() - 5);
214         }
215 
216         if (export) {
217             if (handshakeAlgo.length() == 0) {
218                 handshakeAlgo = "EXP";
219             } else {
220                 handshakeAlgo = "EXP-" + handshakeAlgo;
221             }
222         }
223 
224         return handshakeAlgo.replace('_', '-');
225     }
226 
227     private static String toOpenSslBulkCipher(String bulkCipher) {
228         if (bulkCipher.startsWith("AES_")) {
229             Matcher m = JAVA_AES_CBC_PATTERN.matcher(bulkCipher);
230             if (m.matches()) {
231                 return m.replaceFirst("$1$2");
232             }
233 
234             m = JAVA_AES_PATTERN.matcher(bulkCipher);
235             if (m.matches()) {
236                 return m.replaceFirst("$1$2-$3");
237             }
238         }
239 
240         if ("3DES_EDE_CBC".equals(bulkCipher)) {
241             return "DES-CBC3";
242         }
243 
244         if ("RC4_128".equals(bulkCipher) || "RC4_40".equals(bulkCipher)) {
245             return "RC4";
246         }
247 
248         if ("DES40_CBC".equals(bulkCipher) || "DES_CBC_40".equals(bulkCipher)) {
249             return "DES-CBC";
250         }
251 
252         if ("RC2_CBC_40".equals(bulkCipher)) {
253             return "RC2-CBC";
254         }
255 
256         return bulkCipher.replace('_', '-');
257     }
258 
259     private static String toOpenSslHmacAlgo(String hmacAlgo) {
260         // Java and OpenSSL use the same algorithm names for:
261         //
262         //   * SHA
263         //   * SHA256
264         //   * MD5
265         //
266         return hmacAlgo;
267     }
268 
269     /**
270      * Convert from OpenSSL cipher suite name convention to java cipher suite name convention.
271      * @param openSslCipherSuite An OpenSSL cipher suite name.
272      * @param protocol The cryptographic protocol (i.e. SSL, TLS, ...).
273      * @return The translated cipher suite name according to java conventions. This will not be {@code null}.
274      */
275     static String toJava(String openSslCipherSuite, String protocol) {
276         Map<String, String> p2j = o2j.get(openSslCipherSuite);
277         if (p2j == null) {
278             p2j = cacheFromOpenSsl(openSslCipherSuite);
279         }
280 
281         String javaCipherSuite = p2j.get(protocol);
282         if (javaCipherSuite == null) {
283             javaCipherSuite = protocol + '_' + p2j.get("");
284         }
285 
286         return javaCipherSuite;
287     }
288 
289     private static Map<String, String> cacheFromOpenSsl(String openSslCipherSuite) {
290         String javaCipherSuiteSuffix = toJavaUncached(openSslCipherSuite);
291         if (javaCipherSuiteSuffix == null) {
292             return null;
293         }
294 
295         final String javaCipherSuiteSsl = "SSL_" + javaCipherSuiteSuffix;
296         final String javaCipherSuiteTls = "TLS_" + javaCipherSuiteSuffix;
297 
298         // Cache the mapping.
299         final Map<String, String> p2j = new HashMap<String, String>(4);
300         p2j.put("", javaCipherSuiteSuffix);
301         p2j.put("SSL", javaCipherSuiteSsl);
302         p2j.put("TLS", javaCipherSuiteTls);
303         o2j.putIfAbsent(openSslCipherSuite, p2j);
304 
305         // Cache the reverse mapping after adding the protocol prefix (TLS_ or SSL_)
306         j2o.putIfAbsent(javaCipherSuiteTls, openSslCipherSuite);
307         j2o.putIfAbsent(javaCipherSuiteSsl, openSslCipherSuite);
308 
309         logger.debug("Cipher suite mapping: {} => {}", javaCipherSuiteTls, openSslCipherSuite);
310         logger.debug("Cipher suite mapping: {} => {}", javaCipherSuiteSsl, openSslCipherSuite);
311 
312         return p2j;
313     }
314 
315     static String toJavaUncached(String openSslCipherSuite) {
316         Matcher m = OPENSSL_CIPHERSUITE_PATTERN.matcher(openSslCipherSuite);
317         if (!m.matches()) {
318             return null;
319         }
320 
321         String handshakeAlgo = m.group(1);
322         final boolean export;
323         if (handshakeAlgo == null) {
324             handshakeAlgo = "";
325             export = false;
326         } else if (handshakeAlgo.startsWith("EXP-")) {
327             handshakeAlgo = handshakeAlgo.substring(4);
328             export = true;
329         } else if ("EXP".equals(handshakeAlgo)) {
330             handshakeAlgo = "";
331             export = true;
332         } else {
333             export = false;
334         }
335 
336         handshakeAlgo = toJavaHandshakeAlgo(handshakeAlgo, export);
337         String bulkCipher = toJavaBulkCipher(m.group(2), export);
338         String hmacAlgo = toJavaHmacAlgo(m.group(3));
339 
340         return handshakeAlgo + "_WITH_" + bulkCipher + '_' + hmacAlgo;
341     }
342 
343     private static String toJavaHandshakeAlgo(String handshakeAlgo, boolean export) {
344         if (handshakeAlgo.length() == 0) {
345             handshakeAlgo = "RSA";
346         } else if ("ADH".equals(handshakeAlgo)) {
347             handshakeAlgo = "DH_anon";
348         } else if ("AECDH".equals(handshakeAlgo)) {
349             handshakeAlgo = "ECDH_anon";
350         }
351 
352         handshakeAlgo = handshakeAlgo.replace('-', '_');
353         if (export) {
354             return handshakeAlgo + "_EXPORT";
355         } else {
356             return handshakeAlgo;
357         }
358     }
359 
360     private static String toJavaBulkCipher(String bulkCipher, boolean export) {
361         if (bulkCipher.startsWith("AES")) {
362             Matcher m = OPENSSL_AES_CBC_PATTERN.matcher(bulkCipher);
363             if (m.matches()) {
364                 return m.replaceFirst("$1_$2_CBC");
365             }
366 
367             m = OPENSSL_AES_PATTERN.matcher(bulkCipher);
368             if (m.matches()) {
369                 return m.replaceFirst("$1_$2_$3");
370             }
371         }
372 
373         if ("DES-CBC3".equals(bulkCipher)) {
374             return "3DES_EDE_CBC";
375         }
376 
377         if ("RC4".equals(bulkCipher)) {
378             if (export) {
379                 return "RC4_40";
380             } else {
381                 return "RC4_128";
382             }
383         }
384 
385         if ("DES-CBC".equals(bulkCipher)) {
386             if (export) {
387                 return "DES_CBC_40";
388             } else {
389                 return "DES_CBC";
390             }
391         }
392 
393         if ("RC2-CBC".equals(bulkCipher)) {
394             if (export) {
395                 return "RC2_CBC_40";
396             } else {
397                 return "RC2_CBC";
398             }
399         }
400 
401         return bulkCipher.replace('-', '_');
402     }
403 
404     private static String toJavaHmacAlgo(String hmacAlgo) {
405         // Java and OpenSSL use the same algorithm names for:
406         //
407         //   * SHA
408         //   * SHA256
409         //   * MD5
410         //
411         return hmacAlgo;
412     }
413 
414     private CipherSuiteConverter() { }
415 }