1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114  */
115 /* ====================================================================
116  * Copyright 2005 Nokia. All rights reserved.
117  *
118  * The portions of the attached software ("Contribution") is developed by
119  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
120  * license.
121  *
122  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
123  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
124  * support (see RFC 4279) to OpenSSL.
125  *
126  * No patent licenses or other rights except those expressly stated in
127  * the OpenSSL open source license shall be deemed granted or received
128  * expressly, by implication, estoppel, or otherwise.
129  *
130  * No assurances are provided by Nokia that the Contribution does not
131  * infringe the patent or other intellectual property rights of any third
132  * party or that the license provides you with all the necessary rights
133  * to make use of the Contribution.
134  *
135  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
136  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
137  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
138  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139  * OTHERWISE. */
140 
141 #include <openssl/ssl.h>
142 
143 #include <assert.h>
144 #include <string.h>
145 
146 #include <openssl/buf.h>
147 #include <openssl/err.h>
148 #include <openssl/md5.h>
149 #include <openssl/mem.h>
150 #include <openssl/sha.h>
151 #include <openssl/stack.h>
152 
153 #include "internal.h"
154 #include "../crypto/internal.h"
155 
156 
157 BSSL_NAMESPACE_BEGIN
158 
159 static constexpr SSL_CIPHER kCiphers[] = {
160     // The RSA ciphers
161     // Cipher 02
162     {
163      SSL3_TXT_RSA_NULL_SHA,
164      "TLS_RSA_WITH_NULL_SHA",
165      SSL3_CK_RSA_NULL_SHA,
166      SSL_kRSA,
167      SSL_aRSA,
168      SSL_eNULL,
169      SSL_SHA1,
170      SSL_HANDSHAKE_MAC_DEFAULT,
171     },
172 
173     // Cipher 0A
174     {
175      SSL3_TXT_RSA_DES_192_CBC3_SHA,
176      "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
177      SSL3_CK_RSA_DES_192_CBC3_SHA,
178      SSL_kRSA,
179      SSL_aRSA,
180      SSL_3DES,
181      SSL_SHA1,
182      SSL_HANDSHAKE_MAC_DEFAULT,
183     },
184 
185 
186     // New AES ciphersuites
187 
188     // Cipher 2F
189     {
190      TLS1_TXT_RSA_WITH_AES_128_SHA,
191      "TLS_RSA_WITH_AES_128_CBC_SHA",
192      TLS1_CK_RSA_WITH_AES_128_SHA,
193      SSL_kRSA,
194      SSL_aRSA,
195      SSL_AES128,
196      SSL_SHA1,
197      SSL_HANDSHAKE_MAC_DEFAULT,
198     },
199 
200     // Cipher 35
201     {
202      TLS1_TXT_RSA_WITH_AES_256_SHA,
203      "TLS_RSA_WITH_AES_256_CBC_SHA",
204      TLS1_CK_RSA_WITH_AES_256_SHA,
205      SSL_kRSA,
206      SSL_aRSA,
207      SSL_AES256,
208      SSL_SHA1,
209      SSL_HANDSHAKE_MAC_DEFAULT,
210     },
211 
212     // PSK cipher suites.
213 
214     // Cipher 8C
215     {
216      TLS1_TXT_PSK_WITH_AES_128_CBC_SHA,
217      "TLS_PSK_WITH_AES_128_CBC_SHA",
218      TLS1_CK_PSK_WITH_AES_128_CBC_SHA,
219      SSL_kPSK,
220      SSL_aPSK,
221      SSL_AES128,
222      SSL_SHA1,
223      SSL_HANDSHAKE_MAC_DEFAULT,
224     },
225 
226     // Cipher 8D
227     {
228      TLS1_TXT_PSK_WITH_AES_256_CBC_SHA,
229      "TLS_PSK_WITH_AES_256_CBC_SHA",
230      TLS1_CK_PSK_WITH_AES_256_CBC_SHA,
231      SSL_kPSK,
232      SSL_aPSK,
233      SSL_AES256,
234      SSL_SHA1,
235      SSL_HANDSHAKE_MAC_DEFAULT,
236     },
237 
238     // GCM ciphersuites from RFC5288
239 
240     // Cipher 9C
241     {
242      TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256,
243      "TLS_RSA_WITH_AES_128_GCM_SHA256",
244      TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
245      SSL_kRSA,
246      SSL_aRSA,
247      SSL_AES128GCM,
248      SSL_AEAD,
249      SSL_HANDSHAKE_MAC_SHA256,
250     },
251 
252     // Cipher 9D
253     {
254      TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384,
255      "TLS_RSA_WITH_AES_256_GCM_SHA384",
256      TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
257      SSL_kRSA,
258      SSL_aRSA,
259      SSL_AES256GCM,
260      SSL_AEAD,
261      SSL_HANDSHAKE_MAC_SHA384,
262     },
263 
264     // TLS 1.3 suites.
265 
266     // Cipher 1301
267     {
268       TLS1_TXT_AES_128_GCM_SHA256,
269       "TLS_AES_128_GCM_SHA256",
270       TLS1_CK_AES_128_GCM_SHA256,
271       SSL_kGENERIC,
272       SSL_aGENERIC,
273       SSL_AES128GCM,
274       SSL_AEAD,
275       SSL_HANDSHAKE_MAC_SHA256,
276     },
277 
278     // Cipher 1302
279     {
280       TLS1_TXT_AES_256_GCM_SHA384,
281       "TLS_AES_256_GCM_SHA384",
282       TLS1_CK_AES_256_GCM_SHA384,
283       SSL_kGENERIC,
284       SSL_aGENERIC,
285       SSL_AES256GCM,
286       SSL_AEAD,
287       SSL_HANDSHAKE_MAC_SHA384,
288     },
289 
290     // Cipher 1303
291     {
292       TLS1_TXT_CHACHA20_POLY1305_SHA256,
293       "TLS_CHACHA20_POLY1305_SHA256",
294       TLS1_CK_CHACHA20_POLY1305_SHA256,
295       SSL_kGENERIC,
296       SSL_aGENERIC,
297       SSL_CHACHA20POLY1305,
298       SSL_AEAD,
299       SSL_HANDSHAKE_MAC_SHA256,
300     },
301 
302     // Cipher C009
303     {
304      TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
305      "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
306      TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
307      SSL_kECDHE,
308      SSL_aECDSA,
309      SSL_AES128,
310      SSL_SHA1,
311      SSL_HANDSHAKE_MAC_DEFAULT,
312     },
313 
314     // Cipher C00A
315     {
316      TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
317      "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
318      TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
319      SSL_kECDHE,
320      SSL_aECDSA,
321      SSL_AES256,
322      SSL_SHA1,
323      SSL_HANDSHAKE_MAC_DEFAULT,
324     },
325 
326     // Cipher C013
327     {
328      TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA,
329      "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
330      TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
331      SSL_kECDHE,
332      SSL_aRSA,
333      SSL_AES128,
334      SSL_SHA1,
335      SSL_HANDSHAKE_MAC_DEFAULT,
336     },
337 
338     // Cipher C014
339     {
340      TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA,
341      "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
342      TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
343      SSL_kECDHE,
344      SSL_aRSA,
345      SSL_AES256,
346      SSL_SHA1,
347      SSL_HANDSHAKE_MAC_DEFAULT,
348     },
349 
350     // GCM based TLS v1.2 ciphersuites from RFC5289
351 
352     // Cipher C02B
353     {
354      TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
355      "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
356      TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
357      SSL_kECDHE,
358      SSL_aECDSA,
359      SSL_AES128GCM,
360      SSL_AEAD,
361      SSL_HANDSHAKE_MAC_SHA256,
362     },
363 
364     // Cipher C02C
365     {
366      TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
367      "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
368      TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
369      SSL_kECDHE,
370      SSL_aECDSA,
371      SSL_AES256GCM,
372      SSL_AEAD,
373      SSL_HANDSHAKE_MAC_SHA384,
374     },
375 
376     // Cipher C02F
377     {
378      TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
379      "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
380      TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
381      SSL_kECDHE,
382      SSL_aRSA,
383      SSL_AES128GCM,
384      SSL_AEAD,
385      SSL_HANDSHAKE_MAC_SHA256,
386     },
387 
388     // Cipher C030
389     {
390      TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
391      "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
392      TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
393      SSL_kECDHE,
394      SSL_aRSA,
395      SSL_AES256GCM,
396      SSL_AEAD,
397      SSL_HANDSHAKE_MAC_SHA384,
398     },
399 
400     // ECDHE-PSK cipher suites.
401 
402     // Cipher C035
403     {
404      TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA,
405      "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
406      TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA,
407      SSL_kECDHE,
408      SSL_aPSK,
409      SSL_AES128,
410      SSL_SHA1,
411      SSL_HANDSHAKE_MAC_DEFAULT,
412     },
413 
414     // Cipher C036
415     {
416      TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA,
417      "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
418      TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA,
419      SSL_kECDHE,
420      SSL_aPSK,
421      SSL_AES256,
422      SSL_SHA1,
423      SSL_HANDSHAKE_MAC_DEFAULT,
424     },
425 
426     // ChaCha20-Poly1305 cipher suites.
427 
428     // Cipher CCA8
429     {
430      TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
431      "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
432      TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
433      SSL_kECDHE,
434      SSL_aRSA,
435      SSL_CHACHA20POLY1305,
436      SSL_AEAD,
437      SSL_HANDSHAKE_MAC_SHA256,
438     },
439 
440     // Cipher CCA9
441     {
442      TLS1_TXT_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
443      "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
444      TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
445      SSL_kECDHE,
446      SSL_aECDSA,
447      SSL_CHACHA20POLY1305,
448      SSL_AEAD,
449      SSL_HANDSHAKE_MAC_SHA256,
450     },
451 
452     // Cipher CCAB
453     {
454      TLS1_TXT_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
455      "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256",
456      TLS1_CK_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
457      SSL_kECDHE,
458      SSL_aPSK,
459      SSL_CHACHA20POLY1305,
460      SSL_AEAD,
461      SSL_HANDSHAKE_MAC_SHA256,
462     },
463 
464 };
465 
AllCiphers()466 Span<const SSL_CIPHER> AllCiphers() {
467   return MakeConstSpan(kCiphers, OPENSSL_ARRAY_SIZE(kCiphers));
468 }
469 
470 #define CIPHER_ADD 1
471 #define CIPHER_KILL 2
472 #define CIPHER_DEL 3
473 #define CIPHER_ORD 4
474 #define CIPHER_SPECIAL 5
475 
476 typedef struct cipher_order_st {
477   const SSL_CIPHER *cipher;
478   bool active;
479   bool in_group;
480   struct cipher_order_st *next, *prev;
481 } CIPHER_ORDER;
482 
483 typedef struct cipher_alias_st {
484   // name is the name of the cipher alias.
485   const char *name;
486 
487   // The following fields are bitmasks for the corresponding fields on
488   // |SSL_CIPHER|. A cipher matches a cipher alias iff, for each bitmask, the
489   // bit corresponding to the cipher's value is set to 1. If any bitmask is
490   // all zeroes, the alias matches nothing. Use |~0u| for the default value.
491   uint32_t algorithm_mkey;
492   uint32_t algorithm_auth;
493   uint32_t algorithm_enc;
494   uint32_t algorithm_mac;
495 
496   // min_version, if non-zero, matches all ciphers which were added in that
497   // particular protocol version.
498   uint16_t min_version;
499 } CIPHER_ALIAS;
500 
501 static const CIPHER_ALIAS kCipherAliases[] = {
502     // "ALL" doesn't include eNULL. It must be explicitly enabled.
503     {"ALL", ~0u, ~0u, ~0u, ~0u, 0},
504 
505     // The "COMPLEMENTOFDEFAULT" rule is omitted. It matches nothing.
506 
507     // key exchange aliases
508     // (some of those using only a single bit here combine
509     // multiple key exchange algs according to the RFCs.
510     {"kRSA", SSL_kRSA, ~0u, ~0u, ~0u, 0},
511 
512     {"kECDHE", SSL_kECDHE, ~0u, ~0u, ~0u, 0},
513     {"kEECDH", SSL_kECDHE, ~0u, ~0u, ~0u, 0},
514     {"ECDH", SSL_kECDHE, ~0u, ~0u, ~0u, 0},
515 
516     {"kPSK", SSL_kPSK, ~0u, ~0u, ~0u, 0},
517 
518     // server authentication aliases
519     {"aRSA", ~0u, SSL_aRSA, ~0u, ~0u, 0},
520     {"aECDSA", ~0u, SSL_aECDSA, ~0u, ~0u, 0},
521     {"ECDSA", ~0u, SSL_aECDSA, ~0u, ~0u, 0},
522     {"aPSK", ~0u, SSL_aPSK, ~0u, ~0u, 0},
523 
524     // aliases combining key exchange and server authentication
525     {"ECDHE", SSL_kECDHE, ~0u, ~0u, ~0u, 0},
526     {"EECDH", SSL_kECDHE, ~0u, ~0u, ~0u, 0},
527     {"RSA", SSL_kRSA, SSL_aRSA, ~0u, ~0u, 0},
528     {"PSK", SSL_kPSK, SSL_aPSK, ~0u, ~0u, 0},
529 
530     // symmetric encryption aliases
531     {"3DES", ~0u, ~0u, SSL_3DES, ~0u, 0},
532     {"AES128", ~0u, ~0u, SSL_AES128 | SSL_AES128GCM, ~0u, 0},
533     {"AES256", ~0u, ~0u, SSL_AES256 | SSL_AES256GCM, ~0u, 0},
534     {"AES", ~0u, ~0u, SSL_AES, ~0u, 0},
535     {"AESGCM", ~0u, ~0u, SSL_AES128GCM | SSL_AES256GCM, ~0u, 0},
536     {"CHACHA20", ~0u, ~0u, SSL_CHACHA20POLY1305, ~0u, 0},
537 
538     // MAC aliases
539     {"SHA1", ~0u, ~0u, ~0u, SSL_SHA1, 0},
540     {"SHA", ~0u, ~0u, ~0u, SSL_SHA1, 0},
541 
542     // Legacy protocol minimum version aliases. "TLSv1" is intentionally the
543     // same as "SSLv3".
544     {"SSLv3", ~0u, ~0u, ~0u, ~0u, SSL3_VERSION},
545     {"TLSv1", ~0u, ~0u, ~0u, ~0u, SSL3_VERSION},
546     {"TLSv1.2", ~0u, ~0u, ~0u, ~0u, TLS1_2_VERSION},
547 
548     // Legacy strength classes.
549     {"HIGH", ~0u, ~0u, ~0u, ~0u, 0},
550     {"FIPS", ~0u, ~0u, ~0u, ~0u, 0},
551 
552     // Temporary no-op aliases corresponding to removed SHA-2 legacy CBC
553     // ciphers. These should be removed after 2018-05-14.
554     {"SHA256", 0, 0, 0, 0, 0},
555     {"SHA384", 0, 0, 0, 0, 0},
556 };
557 
558 static const size_t kCipherAliasesLen = OPENSSL_ARRAY_SIZE(kCipherAliases);
559 
ssl_cipher_get_evp_aead(const EVP_AEAD ** out_aead,size_t * out_mac_secret_len,size_t * out_fixed_iv_len,const SSL_CIPHER * cipher,uint16_t version,bool is_dtls)560 bool ssl_cipher_get_evp_aead(const EVP_AEAD **out_aead,
561                              size_t *out_mac_secret_len,
562                              size_t *out_fixed_iv_len, const SSL_CIPHER *cipher,
563                              uint16_t version, bool is_dtls) {
564   *out_aead = NULL;
565   *out_mac_secret_len = 0;
566   *out_fixed_iv_len = 0;
567 
568   const bool is_tls12 = version == TLS1_2_VERSION && !is_dtls;
569   const bool is_tls13 = version == TLS1_3_VERSION && !is_dtls;
570 
571   if (cipher->algorithm_mac == SSL_AEAD) {
572     if (cipher->algorithm_enc == SSL_AES128GCM) {
573       if (is_tls12) {
574         *out_aead = EVP_aead_aes_128_gcm_tls12();
575       } else if (is_tls13) {
576         *out_aead = EVP_aead_aes_128_gcm_tls13();
577       } else {
578         *out_aead = EVP_aead_aes_128_gcm();
579       }
580       *out_fixed_iv_len = 4;
581     } else if (cipher->algorithm_enc == SSL_AES256GCM) {
582       if (is_tls12) {
583         *out_aead = EVP_aead_aes_256_gcm_tls12();
584       } else if (is_tls13) {
585         *out_aead = EVP_aead_aes_256_gcm_tls13();
586       } else {
587         *out_aead = EVP_aead_aes_256_gcm();
588       }
589       *out_fixed_iv_len = 4;
590     } else if (cipher->algorithm_enc == SSL_CHACHA20POLY1305) {
591       *out_aead = EVP_aead_chacha20_poly1305();
592       *out_fixed_iv_len = 12;
593     } else {
594       return false;
595     }
596 
597     // In TLS 1.3, the iv_len is equal to the AEAD nonce length whereas the code
598     // above computes the TLS 1.2 construction.
599     if (version >= TLS1_3_VERSION) {
600       *out_fixed_iv_len = EVP_AEAD_nonce_length(*out_aead);
601     }
602   } else if (cipher->algorithm_mac == SSL_SHA1) {
603     if (cipher->algorithm_enc == SSL_eNULL) {
604       *out_aead = EVP_aead_null_sha1_tls();
605     } else if (cipher->algorithm_enc == SSL_3DES) {
606       if (version == TLS1_VERSION) {
607         *out_aead = EVP_aead_des_ede3_cbc_sha1_tls_implicit_iv();
608         *out_fixed_iv_len = 8;
609       } else {
610         *out_aead = EVP_aead_des_ede3_cbc_sha1_tls();
611       }
612     } else if (cipher->algorithm_enc == SSL_AES128) {
613       if (version == TLS1_VERSION) {
614         *out_aead = EVP_aead_aes_128_cbc_sha1_tls_implicit_iv();
615         *out_fixed_iv_len = 16;
616       } else {
617         *out_aead = EVP_aead_aes_128_cbc_sha1_tls();
618       }
619     } else if (cipher->algorithm_enc == SSL_AES256) {
620       if (version == TLS1_VERSION) {
621         *out_aead = EVP_aead_aes_256_cbc_sha1_tls_implicit_iv();
622         *out_fixed_iv_len = 16;
623       } else {
624         *out_aead = EVP_aead_aes_256_cbc_sha1_tls();
625       }
626     } else {
627       return false;
628     }
629 
630     *out_mac_secret_len = SHA_DIGEST_LENGTH;
631   } else {
632     return false;
633   }
634 
635   return true;
636 }
637 
ssl_get_handshake_digest(uint16_t version,const SSL_CIPHER * cipher)638 const EVP_MD *ssl_get_handshake_digest(uint16_t version,
639                                        const SSL_CIPHER *cipher) {
640   switch (cipher->algorithm_prf) {
641     case SSL_HANDSHAKE_MAC_DEFAULT:
642       return version >= TLS1_2_VERSION ? EVP_sha256() : EVP_md5_sha1();
643     case SSL_HANDSHAKE_MAC_SHA256:
644       return EVP_sha256();
645     case SSL_HANDSHAKE_MAC_SHA384:
646       return EVP_sha384();
647     default:
648       assert(0);
649       return NULL;
650   }
651 }
652 
is_cipher_list_separator(char c,bool is_strict)653 static bool is_cipher_list_separator(char c, bool is_strict) {
654   if (c == ':') {
655     return true;
656   }
657   return !is_strict && (c == ' ' || c == ';' || c == ',');
658 }
659 
660 // rule_equals returns whether the NUL-terminated string |rule| is equal to the
661 // |buf_len| bytes at |buf|.
rule_equals(const char * rule,const char * buf,size_t buf_len)662 static bool rule_equals(const char *rule, const char *buf, size_t buf_len) {
663   // |strncmp| alone only checks that |buf| is a prefix of |rule|.
664   return strncmp(rule, buf, buf_len) == 0 && rule[buf_len] == '\0';
665 }
666 
ll_append_tail(CIPHER_ORDER ** head,CIPHER_ORDER * curr,CIPHER_ORDER ** tail)667 static void ll_append_tail(CIPHER_ORDER **head, CIPHER_ORDER *curr,
668                            CIPHER_ORDER **tail) {
669   if (curr == *tail) {
670     return;
671   }
672   if (curr == *head) {
673     *head = curr->next;
674   }
675   if (curr->prev != NULL) {
676     curr->prev->next = curr->next;
677   }
678   if (curr->next != NULL) {
679     curr->next->prev = curr->prev;
680   }
681   (*tail)->next = curr;
682   curr->prev = *tail;
683   curr->next = NULL;
684   *tail = curr;
685 }
686 
ll_append_head(CIPHER_ORDER ** head,CIPHER_ORDER * curr,CIPHER_ORDER ** tail)687 static void ll_append_head(CIPHER_ORDER **head, CIPHER_ORDER *curr,
688                            CIPHER_ORDER **tail) {
689   if (curr == *head) {
690     return;
691   }
692   if (curr == *tail) {
693     *tail = curr->prev;
694   }
695   if (curr->next != NULL) {
696     curr->next->prev = curr->prev;
697   }
698   if (curr->prev != NULL) {
699     curr->prev->next = curr->next;
700   }
701   (*head)->prev = curr;
702   curr->next = *head;
703   curr->prev = NULL;
704   *head = curr;
705 }
706 
ssl_cipher_collect_ciphers(Array<CIPHER_ORDER> * out_co_list,CIPHER_ORDER ** out_head,CIPHER_ORDER ** out_tail)707 static bool ssl_cipher_collect_ciphers(Array<CIPHER_ORDER> *out_co_list,
708                                        CIPHER_ORDER **out_head,
709                                        CIPHER_ORDER **out_tail) {
710   Array<CIPHER_ORDER> co_list;
711   if (!co_list.Init(OPENSSL_ARRAY_SIZE(kCiphers))) {
712     return false;
713   }
714 
715   size_t co_list_num = 0;
716   for (const SSL_CIPHER &cipher : kCiphers) {
717     // TLS 1.3 ciphers do not participate in this mechanism.
718     if (cipher.algorithm_mkey != SSL_kGENERIC) {
719       co_list[co_list_num].cipher = &cipher;
720       co_list[co_list_num].next = NULL;
721       co_list[co_list_num].prev = NULL;
722       co_list[co_list_num].active = false;
723       co_list[co_list_num].in_group = false;
724       co_list_num++;
725     }
726   }
727 
728   // Prepare linked list from list entries.
729   if (co_list_num > 0) {
730     co_list[0].prev = NULL;
731 
732     if (co_list_num > 1) {
733       co_list[0].next = &co_list[1];
734 
735       for (size_t i = 1; i < co_list_num - 1; i++) {
736         co_list[i].prev = &co_list[i - 1];
737         co_list[i].next = &co_list[i + 1];
738       }
739 
740       co_list[co_list_num - 1].prev = &co_list[co_list_num - 2];
741     }
742 
743     co_list[co_list_num - 1].next = NULL;
744 
745     *out_head = &co_list[0];
746     *out_tail = &co_list[co_list_num - 1];
747   } else {
748     *out_head = nullptr;
749     *out_tail = nullptr;
750   }
751   *out_co_list = std::move(co_list);
752   return true;
753 }
754 
~SSLCipherPreferenceList()755 SSLCipherPreferenceList::~SSLCipherPreferenceList() {
756   OPENSSL_free(in_group_flags);
757 }
758 
Init(UniquePtr<STACK_OF (SSL_CIPHER)> ciphers_arg,Span<const bool> in_group_flags_arg)759 bool SSLCipherPreferenceList::Init(UniquePtr<STACK_OF(SSL_CIPHER)> ciphers_arg,
760                                    Span<const bool> in_group_flags_arg) {
761   if (sk_SSL_CIPHER_num(ciphers_arg.get()) != in_group_flags_arg.size()) {
762     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
763     return false;
764   }
765 
766   Array<bool> copy;
767   if (!copy.CopyFrom(in_group_flags_arg)) {
768     return false;
769   }
770   ciphers = std::move(ciphers_arg);
771   size_t unused_len;
772   copy.Release(&in_group_flags, &unused_len);
773   return true;
774 }
775 
Init(const SSLCipherPreferenceList & other)776 bool SSLCipherPreferenceList::Init(const SSLCipherPreferenceList& other) {
777   size_t size = sk_SSL_CIPHER_num(other.ciphers.get());
778   Span<const bool> other_flags(other.in_group_flags, size);
779   UniquePtr<STACK_OF(SSL_CIPHER)> other_ciphers(sk_SSL_CIPHER_dup(
780       other.ciphers.get()));
781   if (!other_ciphers) {
782     return false;
783   }
784   return Init(std::move(other_ciphers), other_flags);
785 }
786 
Remove(const SSL_CIPHER * cipher)787 void SSLCipherPreferenceList::Remove(const SSL_CIPHER *cipher) {
788   size_t index;
789   if (!sk_SSL_CIPHER_find(ciphers.get(), &index, cipher)) {
790     return;
791   }
792   if (!in_group_flags[index] /* last element of group */ && index > 0) {
793     in_group_flags[index-1] = false;
794   }
795   for (size_t i = index; i < sk_SSL_CIPHER_num(ciphers.get()) - 1; ++i) {
796     in_group_flags[i] = in_group_flags[i+1];
797   }
798   sk_SSL_CIPHER_delete(ciphers.get(), index);
799 }
800 
801 // ssl_cipher_apply_rule applies the rule type |rule| to ciphers matching its
802 // parameters in the linked list from |*head_p| to |*tail_p|. It writes the new
803 // head and tail of the list to |*head_p| and |*tail_p|, respectively.
804 //
805 // - If |cipher_id| is non-zero, only that cipher is selected.
806 // - Otherwise, if |strength_bits| is non-negative, it selects ciphers
807 //   of that strength.
808 // - Otherwise, it selects ciphers that match each bitmasks in |alg_*| and
809 //   |min_version|.
ssl_cipher_apply_rule(uint32_t cipher_id,uint32_t alg_mkey,uint32_t alg_auth,uint32_t alg_enc,uint32_t alg_mac,uint16_t min_version,int rule,int strength_bits,bool in_group,CIPHER_ORDER ** head_p,CIPHER_ORDER ** tail_p)810 static void ssl_cipher_apply_rule(
811     uint32_t cipher_id, uint32_t alg_mkey, uint32_t alg_auth,
812     uint32_t alg_enc, uint32_t alg_mac, uint16_t min_version, int rule,
813     int strength_bits, bool in_group, CIPHER_ORDER **head_p,
814     CIPHER_ORDER **tail_p) {
815   CIPHER_ORDER *head, *tail, *curr, *next, *last;
816   const SSL_CIPHER *cp;
817   bool reverse = false;
818 
819   if (cipher_id == 0 && strength_bits == -1 && min_version == 0 &&
820       (alg_mkey == 0 || alg_auth == 0 || alg_enc == 0 || alg_mac == 0)) {
821     // The rule matches nothing, so bail early.
822     return;
823   }
824 
825   if (rule == CIPHER_DEL) {
826     // needed to maintain sorting between currently deleted ciphers
827     reverse = true;
828   }
829 
830   head = *head_p;
831   tail = *tail_p;
832 
833   if (reverse) {
834     next = tail;
835     last = head;
836   } else {
837     next = head;
838     last = tail;
839   }
840 
841   curr = NULL;
842   for (;;) {
843     if (curr == last) {
844       break;
845     }
846 
847     curr = next;
848     if (curr == NULL) {
849       break;
850     }
851 
852     next = reverse ? curr->prev : curr->next;
853     cp = curr->cipher;
854 
855     // Selection criteria is either a specific cipher, the value of
856     // |strength_bits|, or the algorithms used.
857     if (cipher_id != 0) {
858       if (cipher_id != cp->id) {
859         continue;
860       }
861     } else if (strength_bits >= 0) {
862       if (strength_bits != SSL_CIPHER_get_bits(cp, NULL)) {
863         continue;
864       }
865     } else {
866       if (!(alg_mkey & cp->algorithm_mkey) ||
867           !(alg_auth & cp->algorithm_auth) ||
868           !(alg_enc & cp->algorithm_enc) ||
869           !(alg_mac & cp->algorithm_mac) ||
870           (min_version != 0 && SSL_CIPHER_get_min_version(cp) != min_version) ||
871           // The NULL cipher must be selected explicitly.
872           cp->algorithm_enc == SSL_eNULL) {
873         continue;
874       }
875     }
876 
877     // add the cipher if it has not been added yet.
878     if (rule == CIPHER_ADD) {
879       // reverse == false
880       if (!curr->active) {
881         ll_append_tail(&head, curr, &tail);
882         curr->active = true;
883         curr->in_group = in_group;
884       }
885     }
886 
887     // Move the added cipher to this location
888     else if (rule == CIPHER_ORD) {
889       // reverse == false
890       if (curr->active) {
891         ll_append_tail(&head, curr, &tail);
892         curr->in_group = false;
893       }
894     } else if (rule == CIPHER_DEL) {
895       // reverse == true
896       if (curr->active) {
897         // most recently deleted ciphersuites get best positions
898         // for any future CIPHER_ADD (note that the CIPHER_DEL loop
899         // works in reverse to maintain the order)
900         ll_append_head(&head, curr, &tail);
901         curr->active = false;
902         curr->in_group = false;
903       }
904     } else if (rule == CIPHER_KILL) {
905       // reverse == false
906       if (head == curr) {
907         head = curr->next;
908       } else {
909         curr->prev->next = curr->next;
910       }
911 
912       if (tail == curr) {
913         tail = curr->prev;
914       }
915       curr->active = false;
916       if (curr->next != NULL) {
917         curr->next->prev = curr->prev;
918       }
919       if (curr->prev != NULL) {
920         curr->prev->next = curr->next;
921       }
922       curr->next = NULL;
923       curr->prev = NULL;
924     }
925   }
926 
927   *head_p = head;
928   *tail_p = tail;
929 }
930 
ssl_cipher_strength_sort(CIPHER_ORDER ** head_p,CIPHER_ORDER ** tail_p)931 static bool ssl_cipher_strength_sort(CIPHER_ORDER **head_p,
932                                      CIPHER_ORDER **tail_p) {
933   // This routine sorts the ciphers with descending strength. The sorting must
934   // keep the pre-sorted sequence, so we apply the normal sorting routine as
935   // '+' movement to the end of the list.
936   int max_strength_bits = 0;
937   CIPHER_ORDER *curr = *head_p;
938   while (curr != NULL) {
939     if (curr->active &&
940         SSL_CIPHER_get_bits(curr->cipher, NULL) > max_strength_bits) {
941       max_strength_bits = SSL_CIPHER_get_bits(curr->cipher, NULL);
942     }
943     curr = curr->next;
944   }
945 
946   Array<int> number_uses;
947   if (!number_uses.Init(max_strength_bits + 1)) {
948     return false;
949   }
950   OPENSSL_memset(number_uses.data(), 0, (max_strength_bits + 1) * sizeof(int));
951 
952   // Now find the strength_bits values actually used.
953   curr = *head_p;
954   while (curr != NULL) {
955     if (curr->active) {
956       number_uses[SSL_CIPHER_get_bits(curr->cipher, NULL)]++;
957     }
958     curr = curr->next;
959   }
960 
961   // Go through the list of used strength_bits values in descending order.
962   for (int i = max_strength_bits; i >= 0; i--) {
963     if (number_uses[i] > 0) {
964       ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, CIPHER_ORD, i, false, head_p,
965                             tail_p);
966     }
967   }
968 
969   return true;
970 }
971 
ssl_cipher_process_rulestr(const char * rule_str,CIPHER_ORDER ** head_p,CIPHER_ORDER ** tail_p,bool strict)972 static bool ssl_cipher_process_rulestr(const char *rule_str,
973                                        CIPHER_ORDER **head_p,
974                                        CIPHER_ORDER **tail_p, bool strict) {
975   uint32_t alg_mkey, alg_auth, alg_enc, alg_mac;
976   uint16_t min_version;
977   const char *l, *buf;
978   int rule;
979   bool multi, skip_rule, in_group = false, has_group = false;
980   size_t j, buf_len;
981   uint32_t cipher_id;
982   char ch;
983 
984   l = rule_str;
985   for (;;) {
986     ch = *l;
987 
988     if (ch == '\0') {
989       break;  // done
990     }
991 
992     if (in_group) {
993       if (ch == ']') {
994         if (*tail_p) {
995           (*tail_p)->in_group = false;
996         }
997         in_group = false;
998         l++;
999         continue;
1000       }
1001 
1002       if (ch == '|') {
1003         rule = CIPHER_ADD;
1004         l++;
1005         continue;
1006       } else if (!(ch >= 'a' && ch <= 'z') && !(ch >= 'A' && ch <= 'Z') &&
1007                  !(ch >= '0' && ch <= '9')) {
1008         OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_OPERATOR_IN_GROUP);
1009         return false;
1010       } else {
1011         rule = CIPHER_ADD;
1012       }
1013     } else if (ch == '-') {
1014       rule = CIPHER_DEL;
1015       l++;
1016     } else if (ch == '+') {
1017       rule = CIPHER_ORD;
1018       l++;
1019     } else if (ch == '!') {
1020       rule = CIPHER_KILL;
1021       l++;
1022     } else if (ch == '@') {
1023       rule = CIPHER_SPECIAL;
1024       l++;
1025     } else if (ch == '[') {
1026       assert(!in_group);
1027       in_group = true;
1028       has_group = true;
1029       l++;
1030       continue;
1031     } else {
1032       rule = CIPHER_ADD;
1033     }
1034 
1035     // If preference groups are enabled, the only legal operator is +.
1036     // Otherwise the in_group bits will get mixed up.
1037     if (has_group && rule != CIPHER_ADD) {
1038       OPENSSL_PUT_ERROR(SSL, SSL_R_MIXED_SPECIAL_OPERATOR_WITH_GROUPS);
1039       return false;
1040     }
1041 
1042     if (is_cipher_list_separator(ch, strict)) {
1043       l++;
1044       continue;
1045     }
1046 
1047     multi = false;
1048     cipher_id = 0;
1049     alg_mkey = ~0u;
1050     alg_auth = ~0u;
1051     alg_enc = ~0u;
1052     alg_mac = ~0u;
1053     min_version = 0;
1054     skip_rule = false;
1055 
1056     for (;;) {
1057       ch = *l;
1058       buf = l;
1059       buf_len = 0;
1060       while ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') ||
1061              (ch >= 'a' && ch <= 'z') || ch == '-' || ch == '.' || ch == '_') {
1062         ch = *(++l);
1063         buf_len++;
1064       }
1065 
1066       if (buf_len == 0) {
1067         // We hit something we cannot deal with, it is no command or separator
1068         // nor alphanumeric, so we call this an error.
1069         OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMMAND);
1070         return false;
1071       }
1072 
1073       if (rule == CIPHER_SPECIAL) {
1074         break;
1075       }
1076 
1077       // Look for a matching exact cipher. These aren't allowed in multipart
1078       // rules.
1079       if (!multi && ch != '+') {
1080         for (j = 0; j < OPENSSL_ARRAY_SIZE(kCiphers); j++) {
1081           const SSL_CIPHER *cipher = &kCiphers[j];
1082           if (rule_equals(cipher->name, buf, buf_len) ||
1083               rule_equals(cipher->standard_name, buf, buf_len)) {
1084             cipher_id = cipher->id;
1085             break;
1086           }
1087         }
1088       }
1089       if (cipher_id == 0) {
1090         // If not an exact cipher, look for a matching cipher alias.
1091         for (j = 0; j < kCipherAliasesLen; j++) {
1092           if (rule_equals(kCipherAliases[j].name, buf, buf_len)) {
1093             alg_mkey &= kCipherAliases[j].algorithm_mkey;
1094             alg_auth &= kCipherAliases[j].algorithm_auth;
1095             alg_enc &= kCipherAliases[j].algorithm_enc;
1096             alg_mac &= kCipherAliases[j].algorithm_mac;
1097 
1098             if (min_version != 0 &&
1099                 min_version != kCipherAliases[j].min_version) {
1100               skip_rule = true;
1101             } else {
1102               min_version = kCipherAliases[j].min_version;
1103             }
1104             break;
1105           }
1106         }
1107         if (j == kCipherAliasesLen) {
1108           skip_rule = true;
1109           if (strict) {
1110             OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMMAND);
1111             return false;
1112           }
1113         }
1114       }
1115 
1116       // Check for a multipart rule.
1117       if (ch != '+') {
1118         break;
1119       }
1120       l++;
1121       multi = true;
1122     }
1123 
1124     // Ok, we have the rule, now apply it.
1125     if (rule == CIPHER_SPECIAL) {
1126       if (buf_len != 8 || strncmp(buf, "STRENGTH", 8) != 0) {
1127         OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMMAND);
1128         return false;
1129       }
1130       if (!ssl_cipher_strength_sort(head_p, tail_p)) {
1131         return false;
1132       }
1133 
1134       // We do not support any "multi" options together with "@", so throw away
1135       // the rest of the command, if any left, until end or ':' is found.
1136       while (*l != '\0' && !is_cipher_list_separator(*l, strict)) {
1137         l++;
1138       }
1139     } else if (!skip_rule) {
1140       ssl_cipher_apply_rule(cipher_id, alg_mkey, alg_auth, alg_enc, alg_mac,
1141                             min_version, rule, -1, in_group, head_p, tail_p);
1142     }
1143   }
1144 
1145   if (in_group) {
1146     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMMAND);
1147     return false;
1148   }
1149 
1150   return true;
1151 }
1152 
ssl_create_cipher_list(UniquePtr<SSLCipherPreferenceList> * out_cipher_list,const char * rule_str,bool strict)1153 bool ssl_create_cipher_list(UniquePtr<SSLCipherPreferenceList> *out_cipher_list,
1154                             const char *rule_str, bool strict) {
1155   // Return with error if nothing to do.
1156   if (rule_str == NULL || out_cipher_list == NULL) {
1157     return false;
1158   }
1159 
1160   // Now we have to collect the available ciphers from the compiled in ciphers.
1161   // We cannot get more than the number compiled in, so it is used for
1162   // allocation.
1163   Array<CIPHER_ORDER> co_list;
1164   CIPHER_ORDER *head = nullptr, *tail = nullptr;
1165   if (!ssl_cipher_collect_ciphers(&co_list, &head, &tail)) {
1166     return false;
1167   }
1168 
1169   // Now arrange all ciphers by preference:
1170   // TODO(davidben): Compute this order once and copy it.
1171 
1172   // Everything else being equal, prefer ECDHE_ECDSA and ECDHE_RSA over other
1173   // key exchange mechanisms
1174   ssl_cipher_apply_rule(0, SSL_kECDHE, SSL_aECDSA, ~0u, ~0u, 0, CIPHER_ADD, -1,
1175                         false, &head, &tail);
1176   ssl_cipher_apply_rule(0, SSL_kECDHE, ~0u, ~0u, ~0u, 0, CIPHER_ADD, -1, false,
1177                         &head, &tail);
1178   ssl_cipher_apply_rule(0, ~0u, ~0u, ~0u, ~0u, 0, CIPHER_DEL, -1, false, &head,
1179                         &tail);
1180 
1181   // Order the bulk ciphers. First the preferred AEAD ciphers. We prefer
1182   // CHACHA20 unless there is hardware support for fast and constant-time
1183   // AES_GCM. Of the two CHACHA20 variants, the new one is preferred over the
1184   // old one.
1185   if (EVP_has_aes_hardware()) {
1186     ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_AES128GCM, ~0u, 0, CIPHER_ADD, -1,
1187                           false, &head, &tail);
1188     ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_AES256GCM, ~0u, 0, CIPHER_ADD, -1,
1189                           false, &head, &tail);
1190     ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_CHACHA20POLY1305, ~0u, 0, CIPHER_ADD,
1191                           -1, false, &head, &tail);
1192   } else {
1193     ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_CHACHA20POLY1305, ~0u, 0, CIPHER_ADD,
1194                           -1, false, &head, &tail);
1195     ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_AES128GCM, ~0u, 0, CIPHER_ADD, -1,
1196                           false, &head, &tail);
1197     ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_AES256GCM, ~0u, 0, CIPHER_ADD, -1,
1198                           false, &head, &tail);
1199   }
1200 
1201   // Then the legacy non-AEAD ciphers: AES_128_CBC, AES_256_CBC,
1202   // 3DES_EDE_CBC_SHA.
1203   ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_AES128, ~0u, 0, CIPHER_ADD, -1, false,
1204                         &head, &tail);
1205   ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_AES256, ~0u, 0, CIPHER_ADD, -1, false,
1206                         &head, &tail);
1207   ssl_cipher_apply_rule(0, ~0u, ~0u, SSL_3DES, ~0u, 0, CIPHER_ADD, -1, false,
1208                         &head, &tail);
1209 
1210   // Temporarily enable everything else for sorting
1211   ssl_cipher_apply_rule(0, ~0u, ~0u, ~0u, ~0u, 0, CIPHER_ADD, -1, false, &head,
1212                         &tail);
1213 
1214   // Move ciphers without forward secrecy to the end.
1215   ssl_cipher_apply_rule(0, (SSL_kRSA | SSL_kPSK), ~0u, ~0u, ~0u, 0, CIPHER_ORD,
1216                         -1, false, &head, &tail);
1217 
1218   // Now disable everything (maintaining the ordering!)
1219   ssl_cipher_apply_rule(0, ~0u, ~0u, ~0u, ~0u, 0, CIPHER_DEL, -1, false, &head,
1220                         &tail);
1221 
1222   // If the rule_string begins with DEFAULT, apply the default rule before
1223   // using the (possibly available) additional rules.
1224   const char *rule_p = rule_str;
1225   if (strncmp(rule_str, "DEFAULT", 7) == 0) {
1226     if (!ssl_cipher_process_rulestr(SSL_DEFAULT_CIPHER_LIST, &head, &tail,
1227                                     strict)) {
1228       return false;
1229     }
1230     rule_p += 7;
1231     if (*rule_p == ':') {
1232       rule_p++;
1233     }
1234   }
1235 
1236   if (*rule_p != '\0' &&
1237       !ssl_cipher_process_rulestr(rule_p, &head, &tail, strict)) {
1238     return false;
1239   }
1240 
1241   // Allocate new "cipherstack" for the result, return with error
1242   // if we cannot get one.
1243   UniquePtr<STACK_OF(SSL_CIPHER)> cipherstack(sk_SSL_CIPHER_new_null());
1244   Array<bool> in_group_flags;
1245   if (cipherstack == nullptr ||
1246       !in_group_flags.Init(OPENSSL_ARRAY_SIZE(kCiphers))) {
1247     return false;
1248   }
1249 
1250   // The cipher selection for the list is done. The ciphers are added
1251   // to the resulting precedence to the STACK_OF(SSL_CIPHER).
1252   size_t num_in_group_flags = 0;
1253   for (CIPHER_ORDER *curr = head; curr != NULL; curr = curr->next) {
1254     if (curr->active) {
1255       if (!sk_SSL_CIPHER_push(cipherstack.get(), curr->cipher)) {
1256         return false;
1257       }
1258       in_group_flags[num_in_group_flags++] = curr->in_group;
1259     }
1260   }
1261 
1262   UniquePtr<SSLCipherPreferenceList> pref_list =
1263       MakeUnique<SSLCipherPreferenceList>();
1264   if (!pref_list ||
1265       !pref_list->Init(
1266           std::move(cipherstack),
1267           MakeConstSpan(in_group_flags).subspan(0, num_in_group_flags))) {
1268     return false;
1269   }
1270 
1271   *out_cipher_list = std::move(pref_list);
1272 
1273   // Configuring an empty cipher list is an error but still updates the
1274   // output.
1275   if (sk_SSL_CIPHER_num((*out_cipher_list)->ciphers.get()) == 0) {
1276     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHER_MATCH);
1277     return false;
1278   }
1279 
1280   return true;
1281 }
1282 
ssl_cipher_get_value(const SSL_CIPHER * cipher)1283 uint16_t ssl_cipher_get_value(const SSL_CIPHER *cipher) {
1284   uint32_t id = cipher->id;
1285   // All OpenSSL cipher IDs are prefaced with 0x03. Historically this referred
1286   // to SSLv2 vs SSLv3.
1287   assert((id & 0xff000000) == 0x03000000);
1288   return id & 0xffff;
1289 }
1290 
ssl_cipher_auth_mask_for_key(const EVP_PKEY * key)1291 uint32_t ssl_cipher_auth_mask_for_key(const EVP_PKEY *key) {
1292   switch (EVP_PKEY_id(key)) {
1293     case EVP_PKEY_RSA:
1294       return SSL_aRSA;
1295     case EVP_PKEY_EC:
1296     case EVP_PKEY_ED25519:
1297       // Ed25519 keys in TLS 1.2 repurpose the ECDSA ciphers.
1298       return SSL_aECDSA;
1299     default:
1300       return 0;
1301   }
1302 }
1303 
ssl_cipher_uses_certificate_auth(const SSL_CIPHER * cipher)1304 bool ssl_cipher_uses_certificate_auth(const SSL_CIPHER *cipher) {
1305   return (cipher->algorithm_auth & SSL_aCERT) != 0;
1306 }
1307 
ssl_cipher_requires_server_key_exchange(const SSL_CIPHER * cipher)1308 bool ssl_cipher_requires_server_key_exchange(const SSL_CIPHER *cipher) {
1309   // Ephemeral Diffie-Hellman key exchanges require a ServerKeyExchange. It is
1310   // optional or omitted in all others.
1311   return (cipher->algorithm_mkey & SSL_kECDHE) != 0;
1312 }
1313 
ssl_cipher_get_record_split_len(const SSL_CIPHER * cipher)1314 size_t ssl_cipher_get_record_split_len(const SSL_CIPHER *cipher) {
1315   size_t block_size;
1316   switch (cipher->algorithm_enc) {
1317     case SSL_3DES:
1318       block_size = 8;
1319       break;
1320     case SSL_AES128:
1321     case SSL_AES256:
1322       block_size = 16;
1323       break;
1324     default:
1325       return 0;
1326   }
1327 
1328   // All supported TLS 1.0 ciphers use SHA-1.
1329   assert(cipher->algorithm_mac == SSL_SHA1);
1330   size_t ret = 1 + SHA_DIGEST_LENGTH;
1331   ret += block_size - (ret % block_size);
1332   return ret;
1333 }
1334 
1335 BSSL_NAMESPACE_END
1336 
1337 using namespace bssl;
1338 
ssl_cipher_id_cmp_inner(const SSL_CIPHER * a,const SSL_CIPHER * b)1339 static constexpr int ssl_cipher_id_cmp_inner(const SSL_CIPHER *a,
1340                                              const SSL_CIPHER *b) {
1341   // C++11's constexpr functions must have a body consisting of just a
1342   // return-statement.
1343   return (a->id > b->id) ? 1 : ((a->id < b->id) ? -1 : 0);
1344 }
1345 
ssl_cipher_id_cmp(const void * in_a,const void * in_b)1346 static int ssl_cipher_id_cmp(const void *in_a, const void *in_b) {
1347   return ssl_cipher_id_cmp_inner(reinterpret_cast<const SSL_CIPHER *>(in_a),
1348                                  reinterpret_cast<const SSL_CIPHER *>(in_b));
1349 }
1350 
1351 template <typename T, size_t N>
countof(T const (&)[N])1352 static constexpr size_t countof(T const (&)[N]) {
1353   return N;
1354 }
1355 
1356 template <typename T, size_t I>
check_order(const T (& arr)[I],size_t N)1357 static constexpr int check_order(const T (&arr)[I], size_t N) {
1358   // C++11's constexpr functions must have a body consisting of just a
1359   // return-statement.
1360   return N > 1 ? ((ssl_cipher_id_cmp_inner(&arr[N - 2], &arr[N - 1]) < 0)
1361                       ? check_order(arr, N - 1)
1362                       : 0)
1363                : 1;
1364 }
1365 
1366 static_assert(check_order(kCiphers, countof(kCiphers)) == 1,
1367               "Ciphers are not sorted, bsearch won't work");
1368 
SSL_get_cipher_by_value(uint16_t value)1369 const SSL_CIPHER *SSL_get_cipher_by_value(uint16_t value) {
1370   SSL_CIPHER c;
1371 
1372   c.id = 0x03000000L | value;
1373   return reinterpret_cast<const SSL_CIPHER *>(bsearch(
1374       &c, kCiphers, OPENSSL_ARRAY_SIZE(kCiphers), sizeof(SSL_CIPHER),
1375       ssl_cipher_id_cmp));
1376 }
1377 
SSL_CIPHER_get_id(const SSL_CIPHER * cipher)1378 uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *cipher) { return cipher->id; }
1379 
SSL_CIPHER_is_aead(const SSL_CIPHER * cipher)1380 int SSL_CIPHER_is_aead(const SSL_CIPHER *cipher) {
1381   return (cipher->algorithm_mac & SSL_AEAD) != 0;
1382 }
1383 
SSL_CIPHER_get_cipher_nid(const SSL_CIPHER * cipher)1384 int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *cipher) {
1385   switch (cipher->algorithm_enc) {
1386     case SSL_eNULL:
1387       return NID_undef;
1388     case SSL_3DES:
1389       return NID_des_ede3_cbc;
1390     case SSL_AES128:
1391       return NID_aes_128_cbc;
1392     case SSL_AES256:
1393       return NID_aes_256_cbc;
1394     case SSL_AES128GCM:
1395       return NID_aes_128_gcm;
1396     case SSL_AES256GCM:
1397       return NID_aes_256_gcm;
1398     case SSL_CHACHA20POLY1305:
1399       return NID_chacha20_poly1305;
1400   }
1401   assert(0);
1402   return NID_undef;
1403 }
1404 
SSL_CIPHER_get_digest_nid(const SSL_CIPHER * cipher)1405 int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *cipher) {
1406   switch (cipher->algorithm_mac) {
1407     case SSL_AEAD:
1408       return NID_undef;
1409     case SSL_SHA1:
1410       return NID_sha1;
1411   }
1412   assert(0);
1413   return NID_undef;
1414 }
1415 
SSL_CIPHER_get_kx_nid(const SSL_CIPHER * cipher)1416 int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *cipher) {
1417   switch (cipher->algorithm_mkey) {
1418     case SSL_kRSA:
1419       return NID_kx_rsa;
1420     case SSL_kECDHE:
1421       return NID_kx_ecdhe;
1422     case SSL_kPSK:
1423       return NID_kx_psk;
1424     case SSL_kGENERIC:
1425       return NID_kx_any;
1426   }
1427   assert(0);
1428   return NID_undef;
1429 }
1430 
SSL_CIPHER_get_auth_nid(const SSL_CIPHER * cipher)1431 int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *cipher) {
1432   switch (cipher->algorithm_auth) {
1433     case SSL_aRSA:
1434       return NID_auth_rsa;
1435     case SSL_aECDSA:
1436       return NID_auth_ecdsa;
1437     case SSL_aPSK:
1438       return NID_auth_psk;
1439     case SSL_aGENERIC:
1440       return NID_auth_any;
1441   }
1442   assert(0);
1443   return NID_undef;
1444 }
1445 
SSL_CIPHER_get_prf_nid(const SSL_CIPHER * cipher)1446 int SSL_CIPHER_get_prf_nid(const SSL_CIPHER *cipher) {
1447   switch (cipher->algorithm_prf) {
1448     case SSL_HANDSHAKE_MAC_DEFAULT:
1449       return NID_md5_sha1;
1450     case SSL_HANDSHAKE_MAC_SHA256:
1451       return NID_sha256;
1452     case SSL_HANDSHAKE_MAC_SHA384:
1453       return NID_sha384;
1454   }
1455   assert(0);
1456   return NID_undef;
1457 }
1458 
SSL_CIPHER_is_block_cipher(const SSL_CIPHER * cipher)1459 int SSL_CIPHER_is_block_cipher(const SSL_CIPHER *cipher) {
1460   return (cipher->algorithm_enc & SSL_eNULL) == 0 &&
1461       cipher->algorithm_mac != SSL_AEAD;
1462 }
1463 
SSL_CIPHER_get_min_version(const SSL_CIPHER * cipher)1464 uint16_t SSL_CIPHER_get_min_version(const SSL_CIPHER *cipher) {
1465   if (cipher->algorithm_mkey == SSL_kGENERIC ||
1466       cipher->algorithm_auth == SSL_aGENERIC) {
1467     return TLS1_3_VERSION;
1468   }
1469 
1470   if (cipher->algorithm_prf != SSL_HANDSHAKE_MAC_DEFAULT) {
1471     // Cipher suites before TLS 1.2 use the default PRF, while all those added
1472     // afterwards specify a particular hash.
1473     return TLS1_2_VERSION;
1474   }
1475   return SSL3_VERSION;
1476 }
1477 
SSL_CIPHER_get_max_version(const SSL_CIPHER * cipher)1478 uint16_t SSL_CIPHER_get_max_version(const SSL_CIPHER *cipher) {
1479   if (cipher->algorithm_mkey == SSL_kGENERIC ||
1480       cipher->algorithm_auth == SSL_aGENERIC) {
1481     return TLS1_3_VERSION;
1482   }
1483   return TLS1_2_VERSION;
1484 }
1485 
1486 // return the actual cipher being used
SSL_CIPHER_get_name(const SSL_CIPHER * cipher)1487 const char *SSL_CIPHER_get_name(const SSL_CIPHER *cipher) {
1488   if (cipher != NULL) {
1489     return cipher->name;
1490   }
1491 
1492   return "(NONE)";
1493 }
1494 
SSL_CIPHER_standard_name(const SSL_CIPHER * cipher)1495 const char *SSL_CIPHER_standard_name(const SSL_CIPHER *cipher) {
1496   return cipher->standard_name;
1497 }
1498 
SSL_CIPHER_get_kx_name(const SSL_CIPHER * cipher)1499 const char *SSL_CIPHER_get_kx_name(const SSL_CIPHER *cipher) {
1500   if (cipher == NULL) {
1501     return "";
1502   }
1503 
1504   switch (cipher->algorithm_mkey) {
1505     case SSL_kRSA:
1506       return "RSA";
1507 
1508     case SSL_kECDHE:
1509       switch (cipher->algorithm_auth) {
1510         case SSL_aECDSA:
1511           return "ECDHE_ECDSA";
1512         case SSL_aRSA:
1513           return "ECDHE_RSA";
1514         case SSL_aPSK:
1515           return "ECDHE_PSK";
1516         default:
1517           assert(0);
1518           return "UNKNOWN";
1519       }
1520 
1521     case SSL_kPSK:
1522       assert(cipher->algorithm_auth == SSL_aPSK);
1523       return "PSK";
1524 
1525     case SSL_kGENERIC:
1526       assert(cipher->algorithm_auth == SSL_aGENERIC);
1527       return "GENERIC";
1528 
1529     default:
1530       assert(0);
1531       return "UNKNOWN";
1532   }
1533 }
1534 
SSL_CIPHER_get_rfc_name(const SSL_CIPHER * cipher)1535 char *SSL_CIPHER_get_rfc_name(const SSL_CIPHER *cipher) {
1536   if (cipher == NULL) {
1537     return NULL;
1538   }
1539 
1540   return OPENSSL_strdup(SSL_CIPHER_standard_name(cipher));
1541 }
1542 
SSL_CIPHER_get_bits(const SSL_CIPHER * cipher,int * out_alg_bits)1543 int SSL_CIPHER_get_bits(const SSL_CIPHER *cipher, int *out_alg_bits) {
1544   if (cipher == NULL) {
1545     return 0;
1546   }
1547 
1548   int alg_bits, strength_bits;
1549   switch (cipher->algorithm_enc) {
1550     case SSL_AES128:
1551     case SSL_AES128GCM:
1552       alg_bits = 128;
1553       strength_bits = 128;
1554       break;
1555 
1556     case SSL_AES256:
1557     case SSL_AES256GCM:
1558     case SSL_CHACHA20POLY1305:
1559       alg_bits = 256;
1560       strength_bits = 256;
1561       break;
1562 
1563     case SSL_3DES:
1564       alg_bits = 168;
1565       strength_bits = 112;
1566       break;
1567 
1568     case SSL_eNULL:
1569       alg_bits = 0;
1570       strength_bits = 0;
1571       break;
1572 
1573     default:
1574       assert(0);
1575       alg_bits = 0;
1576       strength_bits = 0;
1577   }
1578 
1579   if (out_alg_bits != NULL) {
1580     *out_alg_bits = alg_bits;
1581   }
1582   return strength_bits;
1583 }
1584 
SSL_CIPHER_description(const SSL_CIPHER * cipher,char * buf,int len)1585 const char *SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf,
1586                                    int len) {
1587   const char *kx, *au, *enc, *mac;
1588   uint32_t alg_mkey, alg_auth, alg_enc, alg_mac;
1589 
1590   alg_mkey = cipher->algorithm_mkey;
1591   alg_auth = cipher->algorithm_auth;
1592   alg_enc = cipher->algorithm_enc;
1593   alg_mac = cipher->algorithm_mac;
1594 
1595   switch (alg_mkey) {
1596     case SSL_kRSA:
1597       kx = "RSA";
1598       break;
1599 
1600     case SSL_kECDHE:
1601       kx = "ECDH";
1602       break;
1603 
1604     case SSL_kPSK:
1605       kx = "PSK";
1606       break;
1607 
1608     case SSL_kGENERIC:
1609       kx = "GENERIC";
1610       break;
1611 
1612     default:
1613       kx = "unknown";
1614   }
1615 
1616   switch (alg_auth) {
1617     case SSL_aRSA:
1618       au = "RSA";
1619       break;
1620 
1621     case SSL_aECDSA:
1622       au = "ECDSA";
1623       break;
1624 
1625     case SSL_aPSK:
1626       au = "PSK";
1627       break;
1628 
1629     case SSL_aGENERIC:
1630       au = "GENERIC";
1631       break;
1632 
1633     default:
1634       au = "unknown";
1635       break;
1636   }
1637 
1638   switch (alg_enc) {
1639     case SSL_3DES:
1640       enc = "3DES(168)";
1641       break;
1642 
1643     case SSL_AES128:
1644       enc = "AES(128)";
1645       break;
1646 
1647     case SSL_AES256:
1648       enc = "AES(256)";
1649       break;
1650 
1651     case SSL_AES128GCM:
1652       enc = "AESGCM(128)";
1653       break;
1654 
1655     case SSL_AES256GCM:
1656       enc = "AESGCM(256)";
1657       break;
1658 
1659     case SSL_CHACHA20POLY1305:
1660       enc = "ChaCha20-Poly1305";
1661       break;
1662 
1663     case SSL_eNULL:
1664       enc="None";
1665       break;
1666 
1667     default:
1668       enc = "unknown";
1669       break;
1670   }
1671 
1672   switch (alg_mac) {
1673     case SSL_SHA1:
1674       mac = "SHA1";
1675       break;
1676 
1677     case SSL_AEAD:
1678       mac = "AEAD";
1679       break;
1680 
1681     default:
1682       mac = "unknown";
1683       break;
1684   }
1685 
1686   if (buf == NULL) {
1687     len = 128;
1688     buf = (char *)OPENSSL_malloc(len);
1689     if (buf == NULL) {
1690       return NULL;
1691     }
1692   } else if (len < 128) {
1693     return "Buffer too small";
1694   }
1695 
1696   BIO_snprintf(buf, len, "%-23s Kx=%-8s Au=%-4s Enc=%-9s Mac=%-4s\n",
1697                cipher->name, kx, au, enc, mac);
1698   return buf;
1699 }
1700 
SSL_CIPHER_get_version(const SSL_CIPHER * cipher)1701 const char *SSL_CIPHER_get_version(const SSL_CIPHER *cipher) {
1702   return "TLSv1/SSLv3";
1703 }
1704 
STACK_OF(SSL_COMP)1705 STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) { return NULL; }
1706 
SSL_COMP_add_compression_method(int id,COMP_METHOD * cm)1707 int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm) { return 1; }
1708 
SSL_COMP_get_name(const COMP_METHOD * comp)1709 const char *SSL_COMP_get_name(const COMP_METHOD *comp) { return NULL; }
1710 
SSL_COMP_get0_name(const SSL_COMP * comp)1711 const char *SSL_COMP_get0_name(const SSL_COMP *comp) { return comp->name; }
1712 
SSL_COMP_get_id(const SSL_COMP * comp)1713 int SSL_COMP_get_id(const SSL_COMP *comp) { return comp->id; }
1714 
SSL_COMP_free_compression_methods(void)1715 void SSL_COMP_free_compression_methods(void) {}
1716