xref: /dragonfly/crypto/libressl/ssl/ssl_ciph.c (revision 8edacedf)
1 /* $OpenBSD: ssl_ciph.c,v 1.119 2020/09/13 16:49:05 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116 /* ====================================================================
117  * Copyright 2005 Nokia. All rights reserved.
118  *
119  * The portions of the attached software ("Contribution") is developed by
120  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
121  * license.
122  *
123  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
124  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
125  * support (see RFC 4279) to OpenSSL.
126  *
127  * No patent licenses or other rights except those expressly stated in
128  * the OpenSSL open source license shall be deemed granted or received
129  * expressly, by implication, estoppel, or otherwise.
130  *
131  * No assurances are provided by Nokia that the Contribution does not
132  * infringe the patent or other intellectual property rights of any third
133  * party or that the license provides you with all the necessary rights
134  * to make use of the Contribution.
135  *
136  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
137  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
138  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
139  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
140  * OTHERWISE.
141  */
142 
143 #include <stdio.h>
144 
145 #include <openssl/objects.h>
146 
147 #ifndef OPENSSL_NO_ENGINE
148 #include <openssl/engine.h>
149 #endif
150 
151 #include "ssl_locl.h"
152 
153 #define CIPHER_ADD	1
154 #define CIPHER_KILL	2
155 #define CIPHER_DEL	3
156 #define CIPHER_ORD	4
157 #define CIPHER_SPECIAL	5
158 
159 typedef struct cipher_order_st {
160 	const SSL_CIPHER *cipher;
161 	int active;
162 	int dead;
163 	struct cipher_order_st *next, *prev;
164 } CIPHER_ORDER;
165 
166 static const SSL_CIPHER cipher_aliases[] = {
167 
168 	/* "ALL" doesn't include eNULL (must be specifically enabled) */
169 	{
170 		.name = SSL_TXT_ALL,
171 		.algorithm_enc = ~SSL_eNULL,
172 	},
173 
174 	/* "COMPLEMENTOFALL" */
175 	{
176 		.name = SSL_TXT_CMPALL,
177 		.algorithm_enc = SSL_eNULL,
178 	},
179 
180 	/*
181 	 * "COMPLEMENTOFDEFAULT"
182 	 * (does *not* include ciphersuites not found in ALL!)
183 	 */
184 	{
185 		.name = SSL_TXT_CMPDEF,
186 		.algorithm_mkey = SSL_kDHE|SSL_kECDHE,
187 		.algorithm_auth = SSL_aNULL,
188 		.algorithm_enc = ~SSL_eNULL,
189 	},
190 
191 	/*
192 	 * key exchange aliases
193 	 * (some of those using only a single bit here combine multiple key
194 	 * exchange algs according to the RFCs, e.g. kEDH combines DHE_DSS
195 	 * and DHE_RSA)
196 	 */
197 	{
198 		.name = SSL_TXT_kRSA,
199 		.algorithm_mkey = SSL_kRSA,
200 	},
201 	{
202 		.name = SSL_TXT_kEDH,
203 		.algorithm_mkey = SSL_kDHE,
204 	},
205 	{
206 		.name = SSL_TXT_DH,
207 		.algorithm_mkey = SSL_kDHE,
208 	},
209 	{
210 		.name = SSL_TXT_kEECDH,
211 		.algorithm_mkey = SSL_kECDHE,
212 	},
213 	{
214 		.name = SSL_TXT_ECDH,
215 		.algorithm_mkey = SSL_kECDHE,
216 	},
217 	{
218 		.name = SSL_TXT_kGOST,
219 		.algorithm_mkey = SSL_kGOST,
220 	},
221 
222 	/* server authentication aliases */
223 	{
224 		.name = SSL_TXT_aRSA,
225 		.algorithm_auth = SSL_aRSA,
226 	},
227 	{
228 		.name = SSL_TXT_aDSS,
229 		.algorithm_auth = SSL_aDSS,
230 	},
231 	{
232 		.name = SSL_TXT_DSS,
233 		.algorithm_auth = SSL_aDSS,
234 	},
235 	{
236 		.name = SSL_TXT_aNULL,
237 		.algorithm_auth = SSL_aNULL,
238 	},
239 	{
240 		.name = SSL_TXT_aECDSA,
241 		.algorithm_auth = SSL_aECDSA,
242 	},
243 	{
244 		.name = SSL_TXT_ECDSA,
245 		.algorithm_auth = SSL_aECDSA,
246 	},
247 	{
248 		.name = SSL_TXT_aGOST01,
249 		.algorithm_auth = SSL_aGOST01,
250 	},
251 	{
252 		.name = SSL_TXT_aGOST,
253 		.algorithm_auth = SSL_aGOST01,
254 	},
255 
256 	/* aliases combining key exchange and server authentication */
257 	{
258 		.name = SSL_TXT_DHE,
259 		.algorithm_mkey = SSL_kDHE,
260 		.algorithm_auth = ~SSL_aNULL,
261 	},
262 	{
263 		.name = SSL_TXT_EDH,
264 		.algorithm_mkey = SSL_kDHE,
265 		.algorithm_auth = ~SSL_aNULL,
266 	},
267 	{
268 		.name = SSL_TXT_ECDHE,
269 		.algorithm_mkey = SSL_kECDHE,
270 		.algorithm_auth = ~SSL_aNULL,
271 	},
272 	{
273 		.name = SSL_TXT_EECDH,
274 		.algorithm_mkey = SSL_kECDHE,
275 		.algorithm_auth = ~SSL_aNULL,
276 	},
277 	{
278 		.name = SSL_TXT_NULL,
279 		.algorithm_enc = SSL_eNULL,
280 	},
281 	{
282 		.name = SSL_TXT_RSA,
283 		.algorithm_mkey = SSL_kRSA,
284 		.algorithm_auth = SSL_aRSA,
285 	},
286 	{
287 		.name = SSL_TXT_ADH,
288 		.algorithm_mkey = SSL_kDHE,
289 		.algorithm_auth = SSL_aNULL,
290 	},
291 	{
292 		.name = SSL_TXT_AECDH,
293 		.algorithm_mkey = SSL_kECDHE,
294 		.algorithm_auth = SSL_aNULL,
295 	},
296 
297 	/* symmetric encryption aliases */
298 	{
299 		.name = SSL_TXT_3DES,
300 		.algorithm_enc = SSL_3DES,
301 	},
302 	{
303 		.name = SSL_TXT_RC4,
304 		.algorithm_enc = SSL_RC4,
305 	},
306 	{
307 		.name = SSL_TXT_eNULL,
308 		.algorithm_enc = SSL_eNULL,
309 	},
310 	{
311 		.name = SSL_TXT_AES128,
312 		.algorithm_enc = SSL_AES128|SSL_AES128GCM,
313 	},
314 	{
315 		.name = SSL_TXT_AES256,
316 		.algorithm_enc = SSL_AES256|SSL_AES256GCM,
317 	},
318 	{
319 		.name = SSL_TXT_AES,
320 		.algorithm_enc = SSL_AES,
321 	},
322 	{
323 		.name = SSL_TXT_AES_GCM,
324 		.algorithm_enc = SSL_AES128GCM|SSL_AES256GCM,
325 	},
326 	{
327 		.name = SSL_TXT_CAMELLIA128,
328 		.algorithm_enc = SSL_CAMELLIA128,
329 	},
330 	{
331 		.name = SSL_TXT_CAMELLIA256,
332 		.algorithm_enc = SSL_CAMELLIA256,
333 	},
334 	{
335 		.name = SSL_TXT_CAMELLIA,
336 		.algorithm_enc = SSL_CAMELLIA128|SSL_CAMELLIA256,
337 	},
338 	{
339 		.name = SSL_TXT_CHACHA20,
340 		.algorithm_enc = SSL_CHACHA20POLY1305,
341 	},
342 
343 	/* MAC aliases */
344 	{
345 		.name = SSL_TXT_AEAD,
346 		.algorithm_mac = SSL_AEAD,
347 	},
348 	{
349 		.name = SSL_TXT_MD5,
350 		.algorithm_mac = SSL_MD5,
351 	},
352 	{
353 		.name = SSL_TXT_SHA1,
354 		.algorithm_mac = SSL_SHA1,
355 	},
356 	{
357 		.name = SSL_TXT_SHA,
358 		.algorithm_mac = SSL_SHA1,
359 	},
360 	{
361 		.name = SSL_TXT_GOST94,
362 		.algorithm_mac = SSL_GOST94,
363 	},
364 	{
365 		.name = SSL_TXT_GOST89MAC,
366 		.algorithm_mac = SSL_GOST89MAC,
367 	},
368 	{
369 		.name = SSL_TXT_SHA256,
370 		.algorithm_mac = SSL_SHA256,
371 	},
372 	{
373 		.name = SSL_TXT_SHA384,
374 		.algorithm_mac = SSL_SHA384,
375 	},
376 	{
377 		.name = SSL_TXT_STREEBOG256,
378 		.algorithm_mac = SSL_STREEBOG256,
379 	},
380 
381 	/* protocol version aliases */
382 	{
383 		.name = SSL_TXT_SSLV3,
384 		.algorithm_ssl = SSL_SSLV3,
385 	},
386 	{
387 		.name = SSL_TXT_TLSV1,
388 		.algorithm_ssl = SSL_TLSV1,
389 	},
390 	{
391 		.name = SSL_TXT_TLSV1_2,
392 		.algorithm_ssl = SSL_TLSV1_2,
393 	},
394 	{
395 		.name = SSL_TXT_TLSV1_3,
396 		.algorithm_ssl = SSL_TLSV1_3,
397 	},
398 
399 	/* cipher suite aliases */
400 #ifdef LIBRESSL_HAS_TLS1_3
401 	{
402 		.valid = 1,
403 		.name = "TLS_AES_128_GCM_SHA256",
404 		.id = TLS1_3_CK_AES_128_GCM_SHA256,
405 		.algorithm_ssl = SSL_TLSV1_3,
406 	},
407 	{
408 		.valid = 1,
409 		.name = "TLS_AES_256_GCM_SHA384",
410 		.id = TLS1_3_CK_AES_256_GCM_SHA384,
411 		.algorithm_ssl = SSL_TLSV1_3,
412 	},
413 	{
414 		.valid = 1,
415 		.name = "TLS_CHACHA20_POLY1305_SHA256",
416 		.id = TLS1_3_CK_CHACHA20_POLY1305_SHA256,
417 		.algorithm_ssl = SSL_TLSV1_3,
418 	},
419 #endif
420 
421 	/* strength classes */
422 	{
423 		.name = SSL_TXT_LOW,
424 		.algo_strength = SSL_LOW,
425 	},
426 	{
427 		.name = SSL_TXT_MEDIUM,
428 		.algo_strength = SSL_MEDIUM,
429 	},
430 	{
431 		.name = SSL_TXT_HIGH,
432 		.algo_strength = SSL_HIGH,
433 	},
434 };
435 
436 int
437 ssl_cipher_get_evp(const SSL_SESSION *ss, const EVP_CIPHER **enc,
438     const EVP_MD **md, int *mac_pkey_type, int *mac_secret_size)
439 {
440 	*enc = NULL;
441 	*md = NULL;
442 	*mac_pkey_type = NID_undef;
443 	*mac_secret_size = 0;
444 
445 	if (ss->cipher == NULL)
446 		return 0;
447 
448 	/*
449 	 * This function does not handle EVP_AEAD.
450 	 * See ssl_cipher_get_aead_evp instead.
451 	 */
452 	if (ss->cipher->algorithm_mac & SSL_AEAD)
453 		return 0;
454 
455 	switch (ss->cipher->algorithm_enc) {
456 	case SSL_3DES:
457 		*enc = EVP_des_ede3_cbc();
458 		break;
459 	case SSL_RC4:
460 		*enc = EVP_rc4();
461 		break;
462 	case SSL_eNULL:
463 		*enc = EVP_enc_null();
464 		break;
465 	case SSL_AES128:
466 		*enc = EVP_aes_128_cbc();
467 		break;
468 	case SSL_AES256:
469 		*enc = EVP_aes_256_cbc();
470 		break;
471 	case SSL_CAMELLIA128:
472 		*enc = EVP_camellia_128_cbc();
473 		break;
474 	case SSL_CAMELLIA256:
475 		*enc = EVP_camellia_256_cbc();
476 		break;
477 	case SSL_eGOST2814789CNT:
478 		*enc = EVP_gost2814789_cnt();
479 		break;
480 	}
481 
482 	switch (ss->cipher->algorithm_mac) {
483 	case SSL_MD5:
484 		*md = EVP_md5();
485 		break;
486 	case SSL_SHA1:
487 		*md = EVP_sha1();
488 		break;
489 	case SSL_SHA256:
490 		*md = EVP_sha256();
491 		break;
492 	case SSL_SHA384:
493 		*md = EVP_sha384();
494 		break;
495 	case SSL_GOST89MAC:
496 		*md = EVP_gost2814789imit();
497 		break;
498 	case SSL_GOST94:
499 		*md = EVP_gostr341194();
500 		break;
501 	case SSL_STREEBOG256:
502 		*md = EVP_streebog256();
503 		break;
504 	}
505 
506 	if (*enc == NULL || *md == NULL)
507 		return 0;
508 
509 	/*
510 	 * EVP_CIPH_FLAG_AEAD_CIPHER and EVP_CIPH_GCM_MODE ciphers are not
511 	 * supported via EVP_CIPHER (they should be using EVP_AEAD instead).
512 	 */
513 	if (EVP_CIPHER_flags(*enc) & EVP_CIPH_FLAG_AEAD_CIPHER)
514 		return 0;
515 	if (EVP_CIPHER_mode(*enc) == EVP_CIPH_GCM_MODE)
516 		return 0;
517 
518 	if (ss->cipher->algorithm_mac == SSL_GOST89MAC) {
519 		*mac_pkey_type = EVP_PKEY_GOSTIMIT;
520 		*mac_secret_size = 32; /* XXX */
521 	} else {
522 		*mac_pkey_type = EVP_PKEY_HMAC;
523 		*mac_secret_size = EVP_MD_size(*md);
524 	}
525 
526 	return 1;
527 }
528 
529 /*
530  * ssl_cipher_get_evp_aead sets aead to point to the correct EVP_AEAD object
531  * for s->cipher. It returns 1 on success and 0 on error.
532  */
533 int
534 ssl_cipher_get_evp_aead(const SSL_SESSION *ss, const EVP_AEAD **aead)
535 {
536 	*aead = NULL;
537 
538 	if (ss->cipher == NULL)
539 		return 0;
540 	if ((ss->cipher->algorithm_mac & SSL_AEAD) == 0)
541 		return 0;
542 
543 	switch (ss->cipher->algorithm_enc) {
544 	case SSL_AES128GCM:
545 		*aead = EVP_aead_aes_128_gcm();
546 		return 1;
547 	case SSL_AES256GCM:
548 		*aead = EVP_aead_aes_256_gcm();
549 		return 1;
550 	case SSL_CHACHA20POLY1305:
551 		*aead = EVP_aead_chacha20_poly1305();
552 		return 1;
553 	default:
554 		break;
555 	}
556 	return 0;
557 }
558 
559 int
560 ssl_get_handshake_evp_md(SSL *s, const EVP_MD **md)
561 {
562 	*md = NULL;
563 
564 	switch (ssl_get_algorithm2(s) & SSL_HANDSHAKE_MAC_MASK) {
565 	case SSL_HANDSHAKE_MAC_DEFAULT:
566 		*md = EVP_md5_sha1();
567 		return 1;
568 	case SSL_HANDSHAKE_MAC_GOST94:
569 		*md = EVP_gostr341194();
570 		return 1;
571 	case SSL_HANDSHAKE_MAC_SHA256:
572 		*md = EVP_sha256();
573 		return 1;
574 	case SSL_HANDSHAKE_MAC_SHA384:
575 		*md = EVP_sha384();
576 		return 1;
577 	case SSL_HANDSHAKE_MAC_STREEBOG256:
578 		*md = EVP_streebog256();
579 		return 1;
580 	default:
581 		break;
582 	}
583 
584 	return 0;
585 }
586 
587 #define ITEM_SEP(a) \
588 	(((a) == ':') || ((a) == ' ') || ((a) == ';') || ((a) == ','))
589 
590 static void
591 ll_append_tail(CIPHER_ORDER **head, CIPHER_ORDER *curr,
592     CIPHER_ORDER **tail)
593 {
594 	if (curr == *tail)
595 		return;
596 	if (curr == *head)
597 		*head = curr->next;
598 	if (curr->prev != NULL)
599 		curr->prev->next = curr->next;
600 	if (curr->next != NULL)
601 		curr->next->prev = curr->prev;
602 	(*tail)->next = curr;
603 	curr->prev= *tail;
604 	curr->next = NULL;
605 	*tail = curr;
606 }
607 
608 static void
609 ll_append_head(CIPHER_ORDER **head, CIPHER_ORDER *curr,
610     CIPHER_ORDER **tail)
611 {
612 	if (curr == *head)
613 		return;
614 	if (curr == *tail)
615 		*tail = curr->prev;
616 	if (curr->next != NULL)
617 		curr->next->prev = curr->prev;
618 	if (curr->prev != NULL)
619 		curr->prev->next = curr->next;
620 	(*head)->prev = curr;
621 	curr->next= *head;
622 	curr->prev = NULL;
623 	*head = curr;
624 }
625 
626 static void
627 ssl_cipher_get_disabled(unsigned long *mkey, unsigned long *auth,
628     unsigned long *enc, unsigned long *mac, unsigned long *ssl)
629 {
630 	*mkey = 0;
631 	*auth = 0;
632 	*enc = 0;
633 	*mac = 0;
634 	*ssl = 0;
635 
636 	/*
637 	 * Check for the availability of GOST 34.10 public/private key
638 	 * algorithms. If they are not available disable the associated
639 	 * authentication and key exchange algorithms.
640 	 */
641 	if (EVP_PKEY_meth_find(NID_id_GostR3410_2001) == NULL) {
642 		*auth |= SSL_aGOST01;
643 		*mkey |= SSL_kGOST;
644 	}
645 
646 #ifdef SSL_FORBID_ENULL
647 	*enc |= SSL_eNULL;
648 #endif
649 }
650 
651 static void
652 ssl_cipher_collect_ciphers(const SSL_METHOD *ssl_method, int num_of_ciphers,
653     unsigned long disabled_mkey, unsigned long disabled_auth,
654     unsigned long disabled_enc, unsigned long disabled_mac,
655     unsigned long disabled_ssl, CIPHER_ORDER *co_list,
656     CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p)
657 {
658 	int i, co_list_num;
659 	const SSL_CIPHER *c;
660 
661 	/*
662 	 * We have num_of_ciphers descriptions compiled in, depending on the
663 	 * method selected (SSLv3, TLSv1, etc). These will later be sorted in
664 	 * a linked list with at most num entries.
665 	 */
666 
667 	/* Get the initial list of ciphers */
668 	co_list_num = 0;	/* actual count of ciphers */
669 	for (i = 0; i < num_of_ciphers; i++) {
670 		c = ssl_method->get_cipher(i);
671 		/* drop those that use any of that is not available */
672 		if ((c != NULL) && c->valid &&
673 		    !(c->algorithm_mkey & disabled_mkey) &&
674 		    !(c->algorithm_auth & disabled_auth) &&
675 		    !(c->algorithm_enc & disabled_enc) &&
676 		    !(c->algorithm_mac & disabled_mac) &&
677 		    !(c->algorithm_ssl & disabled_ssl)) {
678 			co_list[co_list_num].cipher = c;
679 			co_list[co_list_num].next = NULL;
680 			co_list[co_list_num].prev = NULL;
681 			co_list[co_list_num].active = 0;
682 			co_list_num++;
683 			/*
684 			if (!sk_push(ca_list,(char *)c)) goto err;
685 			*/
686 		}
687 	}
688 
689 	/*
690 	 * Prepare linked list from list entries
691 	 */
692 	if (co_list_num > 0) {
693 		co_list[0].prev = NULL;
694 
695 		if (co_list_num > 1) {
696 			co_list[0].next = &co_list[1];
697 
698 			for (i = 1; i < co_list_num - 1; i++) {
699 				co_list[i].prev = &co_list[i - 1];
700 				co_list[i].next = &co_list[i + 1];
701 			}
702 
703 			co_list[co_list_num - 1].prev =
704 			    &co_list[co_list_num - 2];
705 		}
706 
707 		co_list[co_list_num - 1].next = NULL;
708 
709 		*head_p = &co_list[0];
710 		*tail_p = &co_list[co_list_num - 1];
711 	}
712 }
713 
714 static void
715 ssl_cipher_collect_aliases(const SSL_CIPHER **ca_list, int num_of_group_aliases,
716     unsigned long disabled_mkey, unsigned long disabled_auth,
717     unsigned long disabled_enc, unsigned long disabled_mac,
718     unsigned long disabled_ssl, CIPHER_ORDER *head)
719 {
720 	CIPHER_ORDER *ciph_curr;
721 	const SSL_CIPHER **ca_curr;
722 	int i;
723 	unsigned long mask_mkey = ~disabled_mkey;
724 	unsigned long mask_auth = ~disabled_auth;
725 	unsigned long mask_enc = ~disabled_enc;
726 	unsigned long mask_mac = ~disabled_mac;
727 	unsigned long mask_ssl = ~disabled_ssl;
728 
729 	/*
730 	 * First, add the real ciphers as already collected
731 	 */
732 	ciph_curr = head;
733 	ca_curr = ca_list;
734 	while (ciph_curr != NULL) {
735 		*ca_curr = ciph_curr->cipher;
736 		ca_curr++;
737 		ciph_curr = ciph_curr->next;
738 	}
739 
740 	/*
741 	 * Now we add the available ones from the cipher_aliases[] table.
742 	 * They represent either one or more algorithms, some of which
743 	 * in any affected category must be supported (set in enabled_mask),
744 	 * or represent a cipher strength value (will be added in any case because algorithms=0).
745 	 */
746 	for (i = 0; i < num_of_group_aliases; i++) {
747 		unsigned long algorithm_mkey = cipher_aliases[i].algorithm_mkey;
748 		unsigned long algorithm_auth = cipher_aliases[i].algorithm_auth;
749 		unsigned long algorithm_enc = cipher_aliases[i].algorithm_enc;
750 		unsigned long algorithm_mac = cipher_aliases[i].algorithm_mac;
751 		unsigned long algorithm_ssl = cipher_aliases[i].algorithm_ssl;
752 
753 		if (algorithm_mkey)
754 			if ((algorithm_mkey & mask_mkey) == 0)
755 				continue;
756 
757 		if (algorithm_auth)
758 			if ((algorithm_auth & mask_auth) == 0)
759 				continue;
760 
761 		if (algorithm_enc)
762 			if ((algorithm_enc & mask_enc) == 0)
763 				continue;
764 
765 		if (algorithm_mac)
766 			if ((algorithm_mac & mask_mac) == 0)
767 				continue;
768 
769 		if (algorithm_ssl)
770 			if ((algorithm_ssl & mask_ssl) == 0)
771 				continue;
772 
773 		*ca_curr = (SSL_CIPHER *)(cipher_aliases + i);
774 		ca_curr++;
775 	}
776 
777 	*ca_curr = NULL;	/* end of list */
778 }
779 
780 static void
781 ssl_cipher_apply_rule(unsigned long cipher_id, unsigned long alg_mkey,
782     unsigned long alg_auth, unsigned long alg_enc, unsigned long alg_mac,
783     unsigned long alg_ssl, unsigned long algo_strength, int rule,
784     int strength_bits, CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p)
785 {
786 	CIPHER_ORDER *head, *tail, *curr, *next, *last;
787 	const SSL_CIPHER *cp;
788 	int reverse = 0;
789 
790 	if (rule == CIPHER_DEL)
791 		reverse = 1; /* needed to maintain sorting between currently deleted ciphers */
792 
793 	head = *head_p;
794 	tail = *tail_p;
795 
796 	if (reverse) {
797 		next = tail;
798 		last = head;
799 	} else {
800 		next = head;
801 		last = tail;
802 	}
803 
804 	curr = NULL;
805 	for (;;) {
806 		if (curr == last)
807 			break;
808 		curr = next;
809 		next = reverse ? curr->prev : curr->next;
810 
811 		cp = curr->cipher;
812 
813 		if (cipher_id && cp->id != cipher_id)
814 			continue;
815 
816 		/*
817 		 * Selection criteria is either the value of strength_bits
818 		 * or the algorithms used.
819 		 */
820 		if (strength_bits >= 0) {
821 			if (strength_bits != cp->strength_bits)
822 				continue;
823 		} else {
824 			if (alg_mkey && !(alg_mkey & cp->algorithm_mkey))
825 				continue;
826 			if (alg_auth && !(alg_auth & cp->algorithm_auth))
827 				continue;
828 			if (alg_enc && !(alg_enc & cp->algorithm_enc))
829 				continue;
830 			if (alg_mac && !(alg_mac & cp->algorithm_mac))
831 				continue;
832 			if (alg_ssl && !(alg_ssl & cp->algorithm_ssl))
833 				continue;
834 			if ((algo_strength & SSL_STRONG_MASK) && !(algo_strength & SSL_STRONG_MASK & cp->algo_strength))
835 				continue;
836 		}
837 
838 		/* add the cipher if it has not been added yet. */
839 		if (rule == CIPHER_ADD) {
840 			/* reverse == 0 */
841 			if (!curr->active) {
842 				ll_append_tail(&head, curr, &tail);
843 				curr->active = 1;
844 			}
845 		}
846 		/* Move the added cipher to this location */
847 		else if (rule == CIPHER_ORD) {
848 			/* reverse == 0 */
849 			if (curr->active) {
850 				ll_append_tail(&head, curr, &tail);
851 			}
852 		} else if (rule == CIPHER_DEL) {
853 			/* reverse == 1 */
854 			if (curr->active) {
855 				/* most recently deleted ciphersuites get best positions
856 				 * for any future CIPHER_ADD (note that the CIPHER_DEL loop
857 				 * works in reverse to maintain the order) */
858 				ll_append_head(&head, curr, &tail);
859 				curr->active = 0;
860 			}
861 		} else if (rule == CIPHER_KILL) {
862 			/* reverse == 0 */
863 			if (head == curr)
864 				head = curr->next;
865 			else
866 				curr->prev->next = curr->next;
867 			if (tail == curr)
868 				tail = curr->prev;
869 			curr->active = 0;
870 			if (curr->next != NULL)
871 				curr->next->prev = curr->prev;
872 			if (curr->prev != NULL)
873 				curr->prev->next = curr->next;
874 			curr->next = NULL;
875 			curr->prev = NULL;
876 		}
877 	}
878 
879 	*head_p = head;
880 	*tail_p = tail;
881 }
882 
883 static int
884 ssl_cipher_strength_sort(CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p)
885 {
886 	int max_strength_bits, i, *number_uses;
887 	CIPHER_ORDER *curr;
888 
889 	/*
890 	 * This routine sorts the ciphers with descending strength. The sorting
891 	 * must keep the pre-sorted sequence, so we apply the normal sorting
892 	 * routine as '+' movement to the end of the list.
893 	 */
894 	max_strength_bits = 0;
895 	curr = *head_p;
896 	while (curr != NULL) {
897 		if (curr->active &&
898 		    (curr->cipher->strength_bits > max_strength_bits))
899 			max_strength_bits = curr->cipher->strength_bits;
900 		curr = curr->next;
901 	}
902 
903 	number_uses = calloc((max_strength_bits + 1), sizeof(int));
904 	if (!number_uses) {
905 		SSLerrorx(ERR_R_MALLOC_FAILURE);
906 		return (0);
907 	}
908 
909 	/*
910 	 * Now find the strength_bits values actually used
911 	 */
912 	curr = *head_p;
913 	while (curr != NULL) {
914 		if (curr->active)
915 			number_uses[curr->cipher->strength_bits]++;
916 		curr = curr->next;
917 	}
918 	/*
919 	 * Go through the list of used strength_bits values in descending
920 	 * order.
921 	 */
922 	for (i = max_strength_bits; i >= 0; i--)
923 		if (number_uses[i] > 0)
924 			ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ORD, i, head_p, tail_p);
925 
926 	free(number_uses);
927 	return (1);
928 }
929 
930 static int
931 ssl_cipher_process_rulestr(const char *rule_str, CIPHER_ORDER **head_p,
932     CIPHER_ORDER **tail_p, const SSL_CIPHER **ca_list, int *tls13_seen)
933 {
934 	unsigned long alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl;
935 	unsigned long algo_strength;
936 	int j, multi, found, rule, retval, ok, buflen;
937 	unsigned long cipher_id = 0;
938 	const char *l, *buf;
939 	char ch;
940 
941 	*tls13_seen = 0;
942 
943 	retval = 1;
944 	l = rule_str;
945 	for (;;) {
946 		ch = *l;
947 
948 		if (ch == '\0')
949 			break;
950 
951 		if (ch == '-') {
952 			rule = CIPHER_DEL;
953 			l++;
954 		} else if (ch == '+') {
955 			rule = CIPHER_ORD;
956 			l++;
957 		} else if (ch == '!') {
958 			rule = CIPHER_KILL;
959 			l++;
960 		} else if (ch == '@') {
961 			rule = CIPHER_SPECIAL;
962 			l++;
963 		} else {
964 			rule = CIPHER_ADD;
965 		}
966 
967 		if (ITEM_SEP(ch)) {
968 			l++;
969 			continue;
970 		}
971 
972 		alg_mkey = 0;
973 		alg_auth = 0;
974 		alg_enc = 0;
975 		alg_mac = 0;
976 		alg_ssl = 0;
977 		algo_strength = 0;
978 
979 		for (;;) {
980 			ch = *l;
981 			buf = l;
982 			buflen = 0;
983 			while (((ch >= 'A') && (ch <= 'Z')) ||
984 			    ((ch >= '0') && (ch <= '9')) ||
985 			    ((ch >= 'a') && (ch <= 'z')) ||
986 			    (ch == '-') || (ch == '.') ||
987 			    (ch == '_')) {
988 				ch = *(++l);
989 				buflen++;
990 			}
991 
992 			if (buflen == 0) {
993 				/*
994 				 * We hit something we cannot deal with,
995 				 * it is no command or separator nor
996 				 * alphanumeric, so we call this an error.
997 				 */
998 				SSLerrorx(SSL_R_INVALID_COMMAND);
999 				retval = found = 0;
1000 				l++;
1001 				break;
1002 			}
1003 
1004 			if (rule == CIPHER_SPECIAL) {
1005 				 /* unused -- avoid compiler warning */
1006 				found = 0;
1007 				/* special treatment */
1008 				break;
1009 			}
1010 
1011 			/* check for multi-part specification */
1012 			if (ch == '+') {
1013 				multi = 1;
1014 				l++;
1015 			} else
1016 				multi = 0;
1017 
1018 			/*
1019 			 * Now search for the cipher alias in the ca_list.
1020 			 * Be careful with the strncmp, because the "buflen"
1021 			 * limitation will make the rule "ADH:SOME" and the
1022 			 * cipher "ADH-MY-CIPHER" look like a match for
1023 			 * buflen=3. So additionally check whether the cipher
1024 			 * name found has the correct length. We can save a
1025 			 * strlen() call: just checking for the '\0' at the
1026 			 * right place is sufficient, we have to strncmp()
1027 			 * anyway (we cannot use strcmp(), because buf is not
1028 			 * '\0' terminated.)
1029 			 */
1030 			j = found = 0;
1031 			cipher_id = 0;
1032 			while (ca_list[j]) {
1033 				if (!strncmp(buf, ca_list[j]->name, buflen) &&
1034 				    (ca_list[j]->name[buflen] == '\0')) {
1035 					found = 1;
1036 					break;
1037 				} else
1038 					j++;
1039 			}
1040 
1041 			if (!found)
1042 				break;	/* ignore this entry */
1043 
1044 			if (ca_list[j]->algorithm_mkey) {
1045 				if (alg_mkey) {
1046 					alg_mkey &= ca_list[j]->algorithm_mkey;
1047 					if (!alg_mkey) {
1048 						found = 0;
1049 						break;
1050 					}
1051 				} else
1052 					alg_mkey = ca_list[j]->algorithm_mkey;
1053 			}
1054 
1055 			if (ca_list[j]->algorithm_auth) {
1056 				if (alg_auth) {
1057 					alg_auth &= ca_list[j]->algorithm_auth;
1058 					if (!alg_auth) {
1059 						found = 0;
1060 						break;
1061 					}
1062 				} else
1063 					alg_auth = ca_list[j]->algorithm_auth;
1064 			}
1065 
1066 			if (ca_list[j]->algorithm_enc) {
1067 				if (alg_enc) {
1068 					alg_enc &= ca_list[j]->algorithm_enc;
1069 					if (!alg_enc) {
1070 						found = 0;
1071 						break;
1072 					}
1073 				} else
1074 					alg_enc = ca_list[j]->algorithm_enc;
1075 			}
1076 
1077 			if (ca_list[j]->algorithm_mac) {
1078 				if (alg_mac) {
1079 					alg_mac &= ca_list[j]->algorithm_mac;
1080 					if (!alg_mac) {
1081 						found = 0;
1082 						break;
1083 					}
1084 				} else
1085 					alg_mac = ca_list[j]->algorithm_mac;
1086 			}
1087 
1088 			if (ca_list[j]->algo_strength & SSL_STRONG_MASK) {
1089 				if (algo_strength & SSL_STRONG_MASK) {
1090 					algo_strength &=
1091 					    (ca_list[j]->algo_strength &
1092 					    SSL_STRONG_MASK) | ~SSL_STRONG_MASK;
1093 					if (!(algo_strength &
1094 					    SSL_STRONG_MASK)) {
1095 						found = 0;
1096 						break;
1097 					}
1098 				} else
1099 					algo_strength |=
1100 					    ca_list[j]->algo_strength &
1101 					    SSL_STRONG_MASK;
1102 			}
1103 
1104 			if (ca_list[j]->valid) {
1105 				/*
1106 				 * explicit ciphersuite found; its protocol
1107 				 * version does not become part of the search
1108 				 * pattern!
1109 				 */
1110 				cipher_id = ca_list[j]->id;
1111 				if (ca_list[j]->algorithm_ssl == SSL_TLSV1_3)
1112 					*tls13_seen = 1;
1113 			} else {
1114 				/*
1115 				 * not an explicit ciphersuite; only in this
1116 				 * case, the protocol version is considered
1117 				 * part of the search pattern
1118 				 */
1119 				if (ca_list[j]->algorithm_ssl) {
1120 					if (alg_ssl) {
1121 						alg_ssl &=
1122 						    ca_list[j]->algorithm_ssl;
1123 						if (!alg_ssl) {
1124 							found = 0;
1125 							break;
1126 						}
1127 					} else
1128 						alg_ssl =
1129 						    ca_list[j]->algorithm_ssl;
1130 				}
1131 			}
1132 
1133 			if (!multi)
1134 				break;
1135 		}
1136 
1137 		/*
1138 		 * Ok, we have the rule, now apply it
1139 		 */
1140 		if (rule == CIPHER_SPECIAL) {
1141 			/* special command */
1142 			ok = 0;
1143 			if ((buflen == 8) && !strncmp(buf, "STRENGTH", 8))
1144 				ok = ssl_cipher_strength_sort(head_p, tail_p);
1145 			else
1146 				SSLerrorx(SSL_R_INVALID_COMMAND);
1147 			if (ok == 0)
1148 				retval = 0;
1149 			/*
1150 			 * We do not support any "multi" options
1151 			 * together with "@", so throw away the
1152 			 * rest of the command, if any left, until
1153 			 * end or ':' is found.
1154 			 */
1155 			while ((*l != '\0') && !ITEM_SEP(*l))
1156 				l++;
1157 		} else if (found) {
1158 			if (alg_ssl == SSL_TLSV1_3)
1159 				*tls13_seen = 1;
1160 			ssl_cipher_apply_rule(cipher_id, alg_mkey, alg_auth,
1161 			    alg_enc, alg_mac, alg_ssl, algo_strength, rule,
1162 			    -1, head_p, tail_p);
1163 		} else {
1164 			while ((*l != '\0') && !ITEM_SEP(*l))
1165 				l++;
1166 		}
1167 		if (*l == '\0')
1168 			break; /* done */
1169 	}
1170 
1171 	return (retval);
1172 }
1173 
1174 static inline int
1175 ssl_aes_is_accelerated(void)
1176 {
1177 #if defined(__i386__) || defined(__x86_64__)
1178 	return ((OPENSSL_cpu_caps() & (1ULL << 57)) != 0);
1179 #else
1180 	return (0);
1181 #endif
1182 }
1183 
1184 STACK_OF(SSL_CIPHER) *
1185 ssl_create_cipher_list(const SSL_METHOD *ssl_method,
1186     STACK_OF(SSL_CIPHER) **cipher_list,
1187     STACK_OF(SSL_CIPHER) *cipher_list_tls13,
1188     const char *rule_str)
1189 {
1190 	int ok, num_of_ciphers, num_of_alias_max, num_of_group_aliases;
1191 	unsigned long disabled_mkey, disabled_auth, disabled_enc, disabled_mac, disabled_ssl;
1192 	STACK_OF(SSL_CIPHER) *cipherstack;
1193 	const char *rule_p;
1194 	CIPHER_ORDER *co_list = NULL, *head = NULL, *tail = NULL, *curr;
1195 	const SSL_CIPHER **ca_list = NULL;
1196 	const SSL_CIPHER *cipher;
1197 	int tls13_seen = 0;
1198 	int any_active;
1199 	int i;
1200 
1201 	/*
1202 	 * Return with error if nothing to do.
1203 	 */
1204 	if (rule_str == NULL || cipher_list == NULL)
1205 		return NULL;
1206 
1207 	/*
1208 	 * To reduce the work to do we only want to process the compiled
1209 	 * in algorithms, so we first get the mask of disabled ciphers.
1210 	 */
1211 	ssl_cipher_get_disabled(&disabled_mkey, &disabled_auth, &disabled_enc, &disabled_mac, &disabled_ssl);
1212 
1213 	/*
1214 	 * Now we have to collect the available ciphers from the compiled
1215 	 * in ciphers. We cannot get more than the number compiled in, so
1216 	 * it is used for allocation.
1217 	 */
1218 	num_of_ciphers = ssl_method->num_ciphers();
1219 	co_list = reallocarray(NULL, num_of_ciphers, sizeof(CIPHER_ORDER));
1220 	if (co_list == NULL) {
1221 		SSLerrorx(ERR_R_MALLOC_FAILURE);
1222 		return(NULL);	/* Failure */
1223 	}
1224 
1225 	ssl_cipher_collect_ciphers(ssl_method, num_of_ciphers,
1226 	    disabled_mkey, disabled_auth, disabled_enc, disabled_mac, disabled_ssl,
1227 	    co_list, &head, &tail);
1228 
1229 
1230 	/* Now arrange all ciphers by preference: */
1231 
1232 	/* Everything else being equal, prefer ephemeral ECDH over other key exchange mechanisms */
1233 	ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1234 	ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail);
1235 
1236 	if (ssl_aes_is_accelerated()) {
1237 		/*
1238 		 * We have hardware assisted AES - prefer AES as a symmetric
1239 		 * cipher, with CHACHA20 second.
1240 		 */
1241 		ssl_cipher_apply_rule(0, 0, 0, SSL_AES, 0, 0, 0,
1242 		    CIPHER_ADD, -1, &head, &tail);
1243 		ssl_cipher_apply_rule(0, 0, 0, SSL_CHACHA20POLY1305,
1244 		    0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1245 	} else {
1246 		/*
1247 		 * CHACHA20 is fast and safe on all hardware and is thus our
1248 		 * preferred symmetric cipher, with AES second.
1249 		 */
1250 		ssl_cipher_apply_rule(0, 0, 0, SSL_CHACHA20POLY1305,
1251 		    0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1252 		ssl_cipher_apply_rule(0, 0, 0, SSL_AES, 0, 0, 0,
1253 		    CIPHER_ADD, -1, &head, &tail);
1254 	}
1255 
1256 	/* Temporarily enable everything else for sorting */
1257 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1258 
1259 	/* Low priority for MD5 */
1260 	ssl_cipher_apply_rule(0, 0, 0, 0, SSL_MD5, 0, 0, CIPHER_ORD, -1, &head, &tail);
1261 
1262 	/* Move anonymous ciphers to the end.  Usually, these will remain disabled.
1263 	 * (For applications that allow them, they aren't too bad, but we prefer
1264 	 * authenticated ciphers.) */
1265 	ssl_cipher_apply_rule(0, 0, SSL_aNULL, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail);
1266 
1267 	/* Move ciphers without forward secrecy to the end */
1268 	ssl_cipher_apply_rule(0, SSL_kRSA, 0, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail);
1269 
1270 	/* RC4 is sort of broken - move it to the end */
1271 	ssl_cipher_apply_rule(0, 0, 0, SSL_RC4, 0, 0, 0, CIPHER_ORD, -1, &head, &tail);
1272 
1273 	/* Now sort by symmetric encryption strength.  The above ordering remains
1274 	 * in force within each class */
1275 	if (!ssl_cipher_strength_sort(&head, &tail)) {
1276 		free(co_list);
1277 		return NULL;
1278 	}
1279 
1280 	/* Now disable everything (maintaining the ordering!) */
1281 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail);
1282 
1283 	/* TLSv1.3 first. */
1284 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, SSL_TLSV1_3, 0, CIPHER_ADD, -1, &head, &tail);
1285 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, SSL_TLSV1_3, 0, CIPHER_DEL, -1, &head, &tail);
1286 
1287 	/*
1288 	 * We also need cipher aliases for selecting based on the rule_str.
1289 	 * There might be two types of entries in the rule_str: 1) names
1290 	 * of ciphers themselves 2) aliases for groups of ciphers.
1291 	 * For 1) we need the available ciphers and for 2) the cipher
1292 	 * groups of cipher_aliases added together in one list (otherwise
1293 	 * we would be happy with just the cipher_aliases table).
1294 	 */
1295 	num_of_group_aliases = sizeof(cipher_aliases) / sizeof(SSL_CIPHER);
1296 	num_of_alias_max = num_of_ciphers + num_of_group_aliases + 1;
1297 	ca_list = reallocarray(NULL, num_of_alias_max, sizeof(SSL_CIPHER *));
1298 	if (ca_list == NULL) {
1299 		free(co_list);
1300 		SSLerrorx(ERR_R_MALLOC_FAILURE);
1301 		return(NULL);	/* Failure */
1302 	}
1303 	ssl_cipher_collect_aliases(ca_list, num_of_group_aliases, disabled_mkey,
1304 	    disabled_auth, disabled_enc, disabled_mac, disabled_ssl, head);
1305 
1306 	/*
1307 	 * If the rule_string begins with DEFAULT, apply the default rule
1308 	 * before using the (possibly available) additional rules.
1309 	 */
1310 	ok = 1;
1311 	rule_p = rule_str;
1312 	if (strncmp(rule_str, "DEFAULT", 7) == 0) {
1313 		ok = ssl_cipher_process_rulestr(SSL_DEFAULT_CIPHER_LIST,
1314 		    &head, &tail, ca_list, &tls13_seen);
1315 		rule_p += 7;
1316 		if (*rule_p == ':')
1317 			rule_p++;
1318 	}
1319 
1320 	if (ok && (strlen(rule_p) > 0))
1321 		ok = ssl_cipher_process_rulestr(rule_p, &head, &tail, ca_list,
1322 		    &tls13_seen);
1323 
1324 	free((void *)ca_list);	/* Not needed anymore */
1325 
1326 	if (!ok) {
1327 		/* Rule processing failure */
1328 		free(co_list);
1329 		return (NULL);
1330 	}
1331 
1332 	/*
1333 	 * Allocate new "cipherstack" for the result, return with error
1334 	 * if we cannot get one.
1335 	 */
1336 	if ((cipherstack = sk_SSL_CIPHER_new_null()) == NULL) {
1337 		free(co_list);
1338 		return (NULL);
1339 	}
1340 
1341 	/* Prefer TLSv1.3 cipher suites. */
1342 	if (cipher_list_tls13 != NULL) {
1343 		for (i = 0; i < sk_SSL_CIPHER_num(cipher_list_tls13); i++) {
1344 			cipher = sk_SSL_CIPHER_value(cipher_list_tls13, i);
1345 			sk_SSL_CIPHER_push(cipherstack, cipher);
1346 		}
1347 		tls13_seen = 1;
1348 	}
1349 
1350 	/*
1351 	 * The cipher selection for the list is done. The ciphers are added
1352 	 * to the resulting precedence to the STACK_OF(SSL_CIPHER).
1353 	 *
1354 	 * If the rule string did not contain any references to TLSv1.3 and
1355 	 * TLSv1.3 cipher suites have not been configured separately,
1356 	 * include inactive TLSv1.3 cipher suites. This avoids attempts to
1357 	 * use TLSv1.3 with an older rule string that does not include
1358 	 * TLSv1.3 cipher suites. If the rule string resulted in no active
1359 	 * cipher suites then we return an empty stack.
1360 	 */
1361 	any_active = 0;
1362 	for (curr = head; curr != NULL; curr = curr->next) {
1363 		if (curr->active ||
1364 		    (!tls13_seen && curr->cipher->algorithm_ssl == SSL_TLSV1_3))
1365 			sk_SSL_CIPHER_push(cipherstack, curr->cipher);
1366 		any_active |= curr->active;
1367 	}
1368 	if (!any_active)
1369 		sk_SSL_CIPHER_zero(cipherstack);
1370 
1371 	free(co_list);	/* Not needed any longer */
1372 
1373 	sk_SSL_CIPHER_free(*cipher_list);
1374 	*cipher_list = cipherstack;
1375 
1376 	return (cipherstack);
1377 }
1378 
1379 const SSL_CIPHER *
1380 SSL_CIPHER_get_by_id(unsigned int id)
1381 {
1382 	return ssl3_get_cipher_by_id(id);
1383 }
1384 
1385 const SSL_CIPHER *
1386 SSL_CIPHER_get_by_value(uint16_t value)
1387 {
1388 	return ssl3_get_cipher_by_value(value);
1389 }
1390 
1391 char *
1392 SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int len)
1393 {
1394 	unsigned long alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl, alg2;
1395 	const char *ver, *kx, *au, *enc, *mac;
1396 	char *ret;
1397 	int l;
1398 
1399 	alg_mkey = cipher->algorithm_mkey;
1400 	alg_auth = cipher->algorithm_auth;
1401 	alg_enc = cipher->algorithm_enc;
1402 	alg_mac = cipher->algorithm_mac;
1403 	alg_ssl = cipher->algorithm_ssl;
1404 
1405 	alg2 = cipher->algorithm2;
1406 
1407 	if (alg_ssl & SSL_SSLV3)
1408 		ver = "SSLv3";
1409 	else if (alg_ssl & SSL_TLSV1_2)
1410 		ver = "TLSv1.2";
1411 	else if (alg_ssl & SSL_TLSV1_3)
1412 		ver = "TLSv1.3";
1413 	else
1414 		ver = "unknown";
1415 
1416 	switch (alg_mkey) {
1417 	case SSL_kRSA:
1418 		kx = "RSA";
1419 		break;
1420 	case SSL_kDHE:
1421 		kx = "DH";
1422 		break;
1423 	case SSL_kECDHE:
1424 		kx = "ECDH";
1425 		break;
1426 	case SSL_kGOST:
1427 		kx = "GOST";
1428 		break;
1429 	case SSL_kTLS1_3:
1430 		kx = "TLSv1.3";
1431 		break;
1432 	default:
1433 		kx = "unknown";
1434 	}
1435 
1436 	switch (alg_auth) {
1437 	case SSL_aRSA:
1438 		au = "RSA";
1439 		break;
1440 	case SSL_aDSS:
1441 		au = "DSS";
1442 		break;
1443 	case SSL_aNULL:
1444 		au = "None";
1445 		break;
1446 	case SSL_aECDSA:
1447 		au = "ECDSA";
1448 		break;
1449 	case SSL_aGOST01:
1450 		au = "GOST01";
1451 		break;
1452 	case SSL_aTLS1_3:
1453 		au = "TLSv1.3";
1454 		break;
1455 	default:
1456 		au = "unknown";
1457 		break;
1458 	}
1459 
1460 	switch (alg_enc) {
1461 	case SSL_3DES:
1462 		enc = "3DES(168)";
1463 		break;
1464 	case SSL_RC4:
1465 		enc = alg2 & SSL2_CF_8_BYTE_ENC ? "RC4(64)" : "RC4(128)";
1466 		break;
1467 	case SSL_eNULL:
1468 		enc = "None";
1469 		break;
1470 	case SSL_AES128:
1471 		enc = "AES(128)";
1472 		break;
1473 	case SSL_AES256:
1474 		enc = "AES(256)";
1475 		break;
1476 	case SSL_AES128GCM:
1477 		enc = "AESGCM(128)";
1478 		break;
1479 	case SSL_AES256GCM:
1480 		enc = "AESGCM(256)";
1481 		break;
1482 	case SSL_CAMELLIA128:
1483 		enc = "Camellia(128)";
1484 		break;
1485 	case SSL_CAMELLIA256:
1486 		enc = "Camellia(256)";
1487 		break;
1488 	case SSL_CHACHA20POLY1305:
1489 		enc = "ChaCha20-Poly1305";
1490 		break;
1491 	case SSL_eGOST2814789CNT:
1492 		enc = "GOST-28178-89-CNT";
1493 		break;
1494 	default:
1495 		enc = "unknown";
1496 		break;
1497 	}
1498 
1499 	switch (alg_mac) {
1500 	case SSL_MD5:
1501 		mac = "MD5";
1502 		break;
1503 	case SSL_SHA1:
1504 		mac = "SHA1";
1505 		break;
1506 	case SSL_SHA256:
1507 		mac = "SHA256";
1508 		break;
1509 	case SSL_SHA384:
1510 		mac = "SHA384";
1511 		break;
1512 	case SSL_AEAD:
1513 		mac = "AEAD";
1514 		break;
1515 	case SSL_GOST94:
1516 		mac = "GOST94";
1517 		break;
1518 	case SSL_GOST89MAC:
1519 		mac = "GOST89IMIT";
1520 		break;
1521 	case SSL_STREEBOG256:
1522 		mac = "STREEBOG256";
1523 		break;
1524 	default:
1525 		mac = "unknown";
1526 		break;
1527 	}
1528 
1529 	if (asprintf(&ret, "%-23s %s Kx=%-8s Au=%-4s Enc=%-9s Mac=%-4s\n",
1530 	    cipher->name, ver, kx, au, enc, mac) == -1)
1531 		return "OPENSSL_malloc Error";
1532 
1533 	if (buf != NULL) {
1534 		l = strlcpy(buf, ret, len);
1535 		free(ret);
1536 		ret = buf;
1537 		if (l >= len)
1538 			ret = "Buffer too small";
1539 	}
1540 
1541 	return (ret);
1542 }
1543 
1544 const char *
1545 SSL_CIPHER_get_version(const SSL_CIPHER *c)
1546 {
1547 	if (c == NULL)
1548 		return("(NONE)");
1549 	if ((c->id >> 24) == 3)
1550 		return("TLSv1/SSLv3");
1551 	else
1552 		return("unknown");
1553 }
1554 
1555 /* return the actual cipher being used */
1556 const char *
1557 SSL_CIPHER_get_name(const SSL_CIPHER *c)
1558 {
1559 	if (c != NULL)
1560 		return (c->name);
1561 	return("(NONE)");
1562 }
1563 
1564 /* number of bits for symmetric cipher */
1565 int
1566 SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits)
1567 {
1568 	int ret = 0;
1569 
1570 	if (c != NULL) {
1571 		if (alg_bits != NULL)
1572 			*alg_bits = c->alg_bits;
1573 		ret = c->strength_bits;
1574 	}
1575 	return (ret);
1576 }
1577 
1578 unsigned long
1579 SSL_CIPHER_get_id(const SSL_CIPHER *c)
1580 {
1581 	return c->id;
1582 }
1583 
1584 uint16_t
1585 SSL_CIPHER_get_value(const SSL_CIPHER *c)
1586 {
1587 	return ssl3_cipher_get_value(c);
1588 }
1589 
1590 int
1591 SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c)
1592 {
1593 	switch (c->algorithm_enc) {
1594 	case SSL_eNULL:
1595 		return NID_undef;
1596 	case SSL_3DES:
1597 		return NID_des_ede3_cbc;
1598 	case SSL_AES128:
1599 		return NID_aes_128_cbc;
1600 	case SSL_AES128GCM:
1601 		return NID_aes_128_gcm;
1602 	case SSL_AES256:
1603 		return NID_aes_256_cbc;
1604 	case SSL_AES256GCM:
1605 		return NID_aes_256_gcm;
1606 	case SSL_CAMELLIA128:
1607 		return NID_camellia_128_cbc;
1608 	case SSL_CAMELLIA256:
1609 		return NID_camellia_256_cbc;
1610 	case SSL_CHACHA20POLY1305:
1611 		return NID_chacha20_poly1305;
1612 	case SSL_DES:
1613 		return NID_des_cbc;
1614 	case SSL_RC4:
1615 		return NID_rc4;
1616 	case SSL_eGOST2814789CNT:
1617 		return NID_gost89_cnt;
1618 	default:
1619 		return NID_undef;
1620 	}
1621 }
1622 
1623 int
1624 SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c)
1625 {
1626 	switch (c->algorithm_mac) {
1627 	case SSL_AEAD:
1628 		return NID_undef;
1629 	case SSL_GOST89MAC:
1630 		return NID_id_Gost28147_89_MAC;
1631 	case SSL_GOST94:
1632 		return NID_id_GostR3411_94;
1633 	case SSL_MD5:
1634 		return NID_md5;
1635 	case SSL_SHA1:
1636 		return NID_sha1;
1637 	case SSL_SHA256:
1638 		return NID_sha256;
1639 	case SSL_SHA384:
1640 		return NID_sha384;
1641 	case SSL_STREEBOG256:
1642 		return NID_id_tc26_gost3411_2012_256;
1643 	default:
1644 		return NID_undef;
1645 	}
1646 }
1647 
1648 int
1649 SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c)
1650 {
1651 	switch (c->algorithm_mkey) {
1652 	case SSL_kDHE:
1653 		return NID_kx_dhe;
1654 	case SSL_kECDHE:
1655 		return NID_kx_ecdhe;
1656 	case SSL_kGOST:
1657 		return NID_kx_gost;
1658 	case SSL_kRSA:
1659 		return NID_kx_rsa;
1660 	default:
1661 		return NID_undef;
1662 	}
1663 }
1664 
1665 int
1666 SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c)
1667 {
1668 	switch (c->algorithm_auth) {
1669 	case SSL_aNULL:
1670 		return NID_auth_null;
1671 	case SSL_aECDSA:
1672 		return NID_auth_ecdsa;
1673 	case SSL_aGOST01:
1674 		return NID_auth_gost01;
1675 	case SSL_aRSA:
1676 		return NID_auth_rsa;
1677 	default:
1678 		return NID_undef;
1679 	}
1680 }
1681 
1682 int
1683 SSL_CIPHER_is_aead(const SSL_CIPHER *c)
1684 {
1685 	return (c->algorithm_mac & SSL_AEAD) == SSL_AEAD;
1686 }
1687 
1688 void *
1689 SSL_COMP_get_compression_methods(void)
1690 {
1691 	return NULL;
1692 }
1693 
1694 int
1695 SSL_COMP_add_compression_method(int id, void *cm)
1696 {
1697 	return 1;
1698 }
1699 
1700 const char *
1701 SSL_COMP_get_name(const void *comp)
1702 {
1703 	return NULL;
1704 }
1705