xref: /openbsd-src/lib/libssl/ssl_ciph.c (revision 7c0ec4b8992567abb1e1536622dc789a9a39d9f1)
1 /* $OpenBSD: ssl_ciph.c,v 1.149 2024/08/31 12:46:55 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/evp.h>
146 #include <openssl/objects.h>
147 #include <openssl/opensslconf.h>
148 
149 #include "ssl_local.h"
150 
151 #define CIPHER_ADD	1
152 #define CIPHER_KILL	2
153 #define CIPHER_DEL	3
154 #define CIPHER_ORD	4
155 #define CIPHER_SPECIAL	5
156 
157 typedef struct cipher_order_st {
158 	const SSL_CIPHER *cipher;
159 	int active;
160 	int dead;
161 	struct cipher_order_st *next, *prev;
162 } CIPHER_ORDER;
163 
164 static const SSL_CIPHER cipher_aliases[] = {
165 
166 	/* "ALL" doesn't include eNULL (must be specifically enabled) */
167 	{
168 		.name = SSL_TXT_ALL,
169 		.algorithm_enc = ~SSL_eNULL,
170 	},
171 
172 	/* "COMPLEMENTOFALL" */
173 	{
174 		.name = SSL_TXT_CMPALL,
175 		.algorithm_enc = SSL_eNULL,
176 	},
177 
178 	/*
179 	 * "COMPLEMENTOFDEFAULT"
180 	 * (does *not* include ciphersuites not found in ALL!)
181 	 */
182 	{
183 		.name = SSL_TXT_CMPDEF,
184 		.algorithm_mkey = SSL_kDHE|SSL_kECDHE,
185 		.algorithm_auth = SSL_aNULL,
186 		.algorithm_enc = ~SSL_eNULL,
187 	},
188 
189 	/*
190 	 * key exchange aliases
191 	 * (some of those using only a single bit here combine multiple key
192 	 * exchange algs according to the RFCs, e.g. kEDH combines DHE_DSS
193 	 * and DHE_RSA)
194 	 */
195 	{
196 		.name = SSL_TXT_kRSA,
197 		.algorithm_mkey = SSL_kRSA,
198 	},
199 	{
200 		.name = SSL_TXT_kEDH,
201 		.algorithm_mkey = SSL_kDHE,
202 	},
203 	{
204 		.name = SSL_TXT_DH,
205 		.algorithm_mkey = SSL_kDHE,
206 	},
207 	{
208 		.name = SSL_TXT_kEECDH,
209 		.algorithm_mkey = SSL_kECDHE,
210 	},
211 	{
212 		.name = SSL_TXT_ECDH,
213 		.algorithm_mkey = SSL_kECDHE,
214 	},
215 
216 	/* server authentication aliases */
217 	{
218 		.name = SSL_TXT_aRSA,
219 		.algorithm_auth = SSL_aRSA,
220 	},
221 	{
222 		.name = SSL_TXT_aDSS,
223 		.algorithm_auth = SSL_aDSS,
224 	},
225 	{
226 		.name = SSL_TXT_DSS,
227 		.algorithm_auth = SSL_aDSS,
228 	},
229 	{
230 		.name = SSL_TXT_aNULL,
231 		.algorithm_auth = SSL_aNULL,
232 	},
233 	{
234 		.name = SSL_TXT_aECDSA,
235 		.algorithm_auth = SSL_aECDSA,
236 	},
237 	{
238 		.name = SSL_TXT_ECDSA,
239 		.algorithm_auth = SSL_aECDSA,
240 	},
241 
242 	/* aliases combining key exchange and server authentication */
243 	{
244 		.name = SSL_TXT_DHE,
245 		.algorithm_mkey = SSL_kDHE,
246 		.algorithm_auth = ~SSL_aNULL,
247 	},
248 	{
249 		.name = SSL_TXT_EDH,
250 		.algorithm_mkey = SSL_kDHE,
251 		.algorithm_auth = ~SSL_aNULL,
252 	},
253 	{
254 		.name = SSL_TXT_ECDHE,
255 		.algorithm_mkey = SSL_kECDHE,
256 		.algorithm_auth = ~SSL_aNULL,
257 	},
258 	{
259 		.name = SSL_TXT_EECDH,
260 		.algorithm_mkey = SSL_kECDHE,
261 		.algorithm_auth = ~SSL_aNULL,
262 	},
263 	{
264 		.name = SSL_TXT_NULL,
265 		.algorithm_enc = SSL_eNULL,
266 	},
267 	{
268 		.name = SSL_TXT_RSA,
269 		.algorithm_mkey = SSL_kRSA,
270 		.algorithm_auth = SSL_aRSA,
271 	},
272 	{
273 		.name = SSL_TXT_ADH,
274 		.algorithm_mkey = SSL_kDHE,
275 		.algorithm_auth = SSL_aNULL,
276 	},
277 	{
278 		.name = SSL_TXT_AECDH,
279 		.algorithm_mkey = SSL_kECDHE,
280 		.algorithm_auth = SSL_aNULL,
281 	},
282 
283 	/* symmetric encryption aliases */
284 	{
285 		.name = SSL_TXT_3DES,
286 		.algorithm_enc = SSL_3DES,
287 	},
288 	{
289 		.name = SSL_TXT_RC4,
290 		.algorithm_enc = SSL_RC4,
291 	},
292 	{
293 		.name = SSL_TXT_eNULL,
294 		.algorithm_enc = SSL_eNULL,
295 	},
296 	{
297 		.name = SSL_TXT_AES128,
298 		.algorithm_enc = SSL_AES128|SSL_AES128GCM,
299 	},
300 	{
301 		.name = SSL_TXT_AES256,
302 		.algorithm_enc = SSL_AES256|SSL_AES256GCM,
303 	},
304 	{
305 		.name = SSL_TXT_AES,
306 		.algorithm_enc = SSL_AES,
307 	},
308 	{
309 		.name = SSL_TXT_AES_GCM,
310 		.algorithm_enc = SSL_AES128GCM|SSL_AES256GCM,
311 	},
312 	{
313 		.name = SSL_TXT_CAMELLIA128,
314 		.algorithm_enc = SSL_CAMELLIA128,
315 	},
316 	{
317 		.name = SSL_TXT_CAMELLIA256,
318 		.algorithm_enc = SSL_CAMELLIA256,
319 	},
320 	{
321 		.name = SSL_TXT_CAMELLIA,
322 		.algorithm_enc = SSL_CAMELLIA128|SSL_CAMELLIA256,
323 	},
324 	{
325 		.name = SSL_TXT_CHACHA20,
326 		.algorithm_enc = SSL_CHACHA20POLY1305,
327 	},
328 
329 	/* MAC aliases */
330 	{
331 		.name = SSL_TXT_AEAD,
332 		.algorithm_mac = SSL_AEAD,
333 	},
334 	{
335 		.name = SSL_TXT_MD5,
336 		.algorithm_mac = SSL_MD5,
337 	},
338 	{
339 		.name = SSL_TXT_SHA1,
340 		.algorithm_mac = SSL_SHA1,
341 	},
342 	{
343 		.name = SSL_TXT_SHA,
344 		.algorithm_mac = SSL_SHA1,
345 	},
346 	{
347 		.name = SSL_TXT_SHA256,
348 		.algorithm_mac = SSL_SHA256,
349 	},
350 	{
351 		.name = SSL_TXT_SHA384,
352 		.algorithm_mac = SSL_SHA384,
353 	},
354 
355 	/* protocol version aliases */
356 	{
357 		.name = SSL_TXT_SSLV3,
358 		.algorithm_ssl = SSL_SSLV3,
359 	},
360 	{
361 		.name = SSL_TXT_TLSV1,
362 		.algorithm_ssl = SSL_TLSV1,
363 	},
364 	{
365 		.name = SSL_TXT_TLSV1_2,
366 		.algorithm_ssl = SSL_TLSV1_2,
367 	},
368 	{
369 		.name = SSL_TXT_TLSV1_3,
370 		.algorithm_ssl = SSL_TLSV1_3,
371 	},
372 
373 	/* cipher suite aliases */
374 #ifdef LIBRESSL_HAS_TLS1_3
375 	{
376 		.value = 0x1301,
377 		.name = "TLS_AES_128_GCM_SHA256",
378 		.algorithm_ssl = SSL_TLSV1_3,
379 	},
380 	{
381 		.value = 0x1302,
382 		.name = "TLS_AES_256_GCM_SHA384",
383 		.algorithm_ssl = SSL_TLSV1_3,
384 	},
385 	{
386 		.value = 0x1303,
387 		.name = "TLS_CHACHA20_POLY1305_SHA256",
388 		.algorithm_ssl = SSL_TLSV1_3,
389 	},
390 #endif
391 
392 	/* strength classes */
393 	{
394 		.name = SSL_TXT_LOW,
395 		.algo_strength = SSL_LOW,
396 	},
397 	{
398 		.name = SSL_TXT_MEDIUM,
399 		.algo_strength = SSL_MEDIUM,
400 	},
401 	{
402 		.name = SSL_TXT_HIGH,
403 		.algo_strength = SSL_HIGH,
404 	},
405 };
406 
407 int
408 ssl_cipher_get_evp(SSL *s, const EVP_CIPHER **enc, const EVP_MD **md,
409     int *mac_pkey_type, int *mac_secret_size)
410 {
411 	const SSL_CIPHER *cipher;
412 
413 	*enc = NULL;
414 	*md = NULL;
415 	*mac_pkey_type = NID_undef;
416 	*mac_secret_size = 0;
417 
418 	if ((cipher = s->s3->hs.cipher) == NULL)
419 		return 0;
420 
421 	/*
422 	 * This function does not handle EVP_AEAD.
423 	 * See ssl_cipher_get_evp_aead instead.
424 	 */
425 	if (cipher->algorithm_mac & SSL_AEAD)
426 		return 0;
427 
428 	switch (cipher->algorithm_enc) {
429 	case SSL_3DES:
430 		*enc = EVP_des_ede3_cbc();
431 		break;
432 	case SSL_RC4:
433 		*enc = EVP_rc4();
434 		break;
435 	case SSL_eNULL:
436 		*enc = EVP_enc_null();
437 		break;
438 	case SSL_AES128:
439 		*enc = EVP_aes_128_cbc();
440 		break;
441 	case SSL_AES256:
442 		*enc = EVP_aes_256_cbc();
443 		break;
444 	case SSL_CAMELLIA128:
445 		*enc = EVP_camellia_128_cbc();
446 		break;
447 	case SSL_CAMELLIA256:
448 		*enc = EVP_camellia_256_cbc();
449 		break;
450 	}
451 
452 	switch (cipher->algorithm_mac) {
453 	case SSL_MD5:
454 		*md = EVP_md5();
455 		break;
456 	case SSL_SHA1:
457 		*md = EVP_sha1();
458 		break;
459 	case SSL_SHA256:
460 		*md = EVP_sha256();
461 		break;
462 	case SSL_SHA384:
463 		*md = EVP_sha384();
464 		break;
465 	}
466 	if (*enc == NULL || *md == NULL)
467 		return 0;
468 
469 	/* XXX remove these from ssl_cipher_get_evp? */
470 	/*
471 	 * EVP_CIPH_FLAG_AEAD_CIPHER and EVP_CIPH_GCM_MODE ciphers are not
472 	 * supported via EVP_CIPHER (they should be using EVP_AEAD instead).
473 	 */
474 	if (EVP_CIPHER_flags(*enc) & EVP_CIPH_FLAG_AEAD_CIPHER)
475 		return 0;
476 	if (EVP_CIPHER_mode(*enc) == EVP_CIPH_GCM_MODE)
477 		return 0;
478 
479 	*mac_pkey_type = EVP_PKEY_HMAC;
480 	*mac_secret_size = EVP_MD_size(*md);
481 	return 1;
482 }
483 
484 /*
485  * ssl_cipher_get_evp_aead sets aead to point to the correct EVP_AEAD object
486  * for s->cipher. It returns 1 on success and 0 on error.
487  */
488 int
489 ssl_cipher_get_evp_aead(SSL *s, const EVP_AEAD **aead)
490 {
491 	const SSL_CIPHER *cipher;
492 
493 	*aead = NULL;
494 
495 	if ((cipher = s->s3->hs.cipher) == NULL)
496 		return 0;
497 	if ((cipher->algorithm_mac & SSL_AEAD) == 0)
498 		return 0;
499 
500 	switch (cipher->algorithm_enc) {
501 	case SSL_AES128GCM:
502 		*aead = EVP_aead_aes_128_gcm();
503 		return 1;
504 	case SSL_AES256GCM:
505 		*aead = EVP_aead_aes_256_gcm();
506 		return 1;
507 	case SSL_CHACHA20POLY1305:
508 		*aead = EVP_aead_chacha20_poly1305();
509 		return 1;
510 	default:
511 		break;
512 	}
513 	return 0;
514 }
515 
516 int
517 ssl_get_handshake_evp_md(SSL *s, const EVP_MD **md)
518 {
519 	const SSL_CIPHER *cipher;
520 
521 	*md = NULL;
522 
523 	if ((cipher = s->s3->hs.cipher) == NULL)
524 		return 0;
525 
526 	switch (cipher->algorithm2 & SSL_HANDSHAKE_MAC_MASK) {
527 	case SSL_HANDSHAKE_MAC_SHA256:
528 		*md = EVP_sha256();
529 		return 1;
530 	case SSL_HANDSHAKE_MAC_SHA384:
531 		*md = EVP_sha384();
532 		return 1;
533 	default:
534 		break;
535 	}
536 
537 	return 0;
538 }
539 
540 #define ITEM_SEP(a) \
541 	(((a) == ':') || ((a) == ' ') || ((a) == ';') || ((a) == ','))
542 
543 static void
544 ll_append_tail(CIPHER_ORDER **head, CIPHER_ORDER *curr,
545     CIPHER_ORDER **tail)
546 {
547 	if (curr == *tail)
548 		return;
549 	if (curr == *head)
550 		*head = curr->next;
551 	if (curr->prev != NULL)
552 		curr->prev->next = curr->next;
553 	if (curr->next != NULL)
554 		curr->next->prev = curr->prev;
555 	(*tail)->next = curr;
556 	curr->prev= *tail;
557 	curr->next = NULL;
558 	*tail = curr;
559 }
560 
561 static void
562 ll_append_head(CIPHER_ORDER **head, CIPHER_ORDER *curr,
563     CIPHER_ORDER **tail)
564 {
565 	if (curr == *head)
566 		return;
567 	if (curr == *tail)
568 		*tail = curr->prev;
569 	if (curr->next != NULL)
570 		curr->next->prev = curr->prev;
571 	if (curr->prev != NULL)
572 		curr->prev->next = curr->next;
573 	(*head)->prev = curr;
574 	curr->next= *head;
575 	curr->prev = NULL;
576 	*head = curr;
577 }
578 
579 static void
580 ssl_cipher_collect_ciphers(const SSL_METHOD *ssl_method, int num_of_ciphers,
581     unsigned long disabled_mkey, unsigned long disabled_auth,
582     unsigned long disabled_enc, unsigned long disabled_mac,
583     unsigned long disabled_ssl, CIPHER_ORDER *co_list,
584     CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p)
585 {
586 	int i, co_list_num;
587 	const SSL_CIPHER *c;
588 
589 	/*
590 	 * We have num_of_ciphers descriptions compiled in, depending on the
591 	 * method selected (SSLv3, TLSv1, etc). These will later be sorted in
592 	 * a linked list with at most num entries.
593 	 */
594 
595 	/*
596 	 * Get the initial list of ciphers, iterating backwards over the
597 	 * cipher list - the list is ordered by cipher value and we currently
598 	 * hope that ciphers with higher cipher values are preferable...
599 	 */
600 	co_list_num = 0;	/* actual count of ciphers */
601 	for (i = num_of_ciphers - 1; i >= 0; i--) {
602 		c = ssl3_get_cipher_by_index(i);
603 
604 		/*
605 		 * Drop any invalid ciphers and any which use unavailable
606 		 * algorithms.
607 		 */
608 		if ((c != NULL) &&
609 		    !(c->algorithm_mkey & disabled_mkey) &&
610 		    !(c->algorithm_auth & disabled_auth) &&
611 		    !(c->algorithm_enc & disabled_enc) &&
612 		    !(c->algorithm_mac & disabled_mac) &&
613 		    !(c->algorithm_ssl & disabled_ssl)) {
614 			co_list[co_list_num].cipher = c;
615 			co_list[co_list_num].next = NULL;
616 			co_list[co_list_num].prev = NULL;
617 			co_list[co_list_num].active = 0;
618 			co_list_num++;
619 		}
620 	}
621 
622 	/*
623 	 * Prepare linked list from list entries
624 	 */
625 	if (co_list_num > 0) {
626 		co_list[0].prev = NULL;
627 
628 		if (co_list_num > 1) {
629 			co_list[0].next = &co_list[1];
630 
631 			for (i = 1; i < co_list_num - 1; i++) {
632 				co_list[i].prev = &co_list[i - 1];
633 				co_list[i].next = &co_list[i + 1];
634 			}
635 
636 			co_list[co_list_num - 1].prev =
637 			    &co_list[co_list_num - 2];
638 		}
639 
640 		co_list[co_list_num - 1].next = NULL;
641 
642 		*head_p = &co_list[0];
643 		*tail_p = &co_list[co_list_num - 1];
644 	}
645 }
646 
647 static void
648 ssl_cipher_collect_aliases(const SSL_CIPHER **ca_list, int num_of_group_aliases,
649     unsigned long disabled_mkey, unsigned long disabled_auth,
650     unsigned long disabled_enc, unsigned long disabled_mac,
651     unsigned long disabled_ssl, CIPHER_ORDER *head)
652 {
653 	CIPHER_ORDER *ciph_curr;
654 	const SSL_CIPHER **ca_curr;
655 	int i;
656 	unsigned long mask_mkey = ~disabled_mkey;
657 	unsigned long mask_auth = ~disabled_auth;
658 	unsigned long mask_enc = ~disabled_enc;
659 	unsigned long mask_mac = ~disabled_mac;
660 	unsigned long mask_ssl = ~disabled_ssl;
661 
662 	/*
663 	 * First, add the real ciphers as already collected
664 	 */
665 	ciph_curr = head;
666 	ca_curr = ca_list;
667 	while (ciph_curr != NULL) {
668 		*ca_curr = ciph_curr->cipher;
669 		ca_curr++;
670 		ciph_curr = ciph_curr->next;
671 	}
672 
673 	/*
674 	 * Now we add the available ones from the cipher_aliases[] table.
675 	 * They represent either one or more algorithms, some of which
676 	 * in any affected category must be supported (set in enabled_mask),
677 	 * or represent a cipher strength value (will be added in any case because algorithms=0).
678 	 */
679 	for (i = 0; i < num_of_group_aliases; i++) {
680 		unsigned long algorithm_mkey = cipher_aliases[i].algorithm_mkey;
681 		unsigned long algorithm_auth = cipher_aliases[i].algorithm_auth;
682 		unsigned long algorithm_enc = cipher_aliases[i].algorithm_enc;
683 		unsigned long algorithm_mac = cipher_aliases[i].algorithm_mac;
684 		unsigned long algorithm_ssl = cipher_aliases[i].algorithm_ssl;
685 
686 		if (algorithm_mkey)
687 			if ((algorithm_mkey & mask_mkey) == 0)
688 				continue;
689 
690 		if (algorithm_auth)
691 			if ((algorithm_auth & mask_auth) == 0)
692 				continue;
693 
694 		if (algorithm_enc)
695 			if ((algorithm_enc & mask_enc) == 0)
696 				continue;
697 
698 		if (algorithm_mac)
699 			if ((algorithm_mac & mask_mac) == 0)
700 				continue;
701 
702 		if (algorithm_ssl)
703 			if ((algorithm_ssl & mask_ssl) == 0)
704 				continue;
705 
706 		*ca_curr = (SSL_CIPHER *)(cipher_aliases + i);
707 		ca_curr++;
708 	}
709 
710 	*ca_curr = NULL;	/* end of list */
711 }
712 
713 static void
714 ssl_cipher_apply_rule(uint16_t cipher_value, unsigned long alg_mkey,
715     unsigned long alg_auth, unsigned long alg_enc, unsigned long alg_mac,
716     unsigned long alg_ssl, unsigned long algo_strength, int rule,
717     int strength_bits, CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p)
718 {
719 	CIPHER_ORDER *head, *tail, *curr, *next, *last;
720 	const SSL_CIPHER *cp;
721 	int reverse = 0;
722 
723 	if (rule == CIPHER_DEL)
724 		reverse = 1; /* needed to maintain sorting between currently deleted ciphers */
725 
726 	head = *head_p;
727 	tail = *tail_p;
728 
729 	if (reverse) {
730 		next = tail;
731 		last = head;
732 	} else {
733 		next = head;
734 		last = tail;
735 	}
736 
737 	curr = NULL;
738 	for (;;) {
739 		if (curr == last)
740 			break;
741 		curr = next;
742 		next = reverse ? curr->prev : curr->next;
743 
744 		cp = curr->cipher;
745 
746 		if (cipher_value != 0 && cp->value != cipher_value)
747 			continue;
748 
749 		/*
750 		 * Selection criteria is either the value of strength_bits
751 		 * or the algorithms used.
752 		 */
753 		if (strength_bits >= 0) {
754 			if (strength_bits != cp->strength_bits)
755 				continue;
756 		} else {
757 			if (alg_mkey && !(alg_mkey & cp->algorithm_mkey))
758 				continue;
759 			if (alg_auth && !(alg_auth & cp->algorithm_auth))
760 				continue;
761 			if (alg_enc && !(alg_enc & cp->algorithm_enc))
762 				continue;
763 			if (alg_mac && !(alg_mac & cp->algorithm_mac))
764 				continue;
765 			if (alg_ssl && !(alg_ssl & cp->algorithm_ssl))
766 				continue;
767 			if ((algo_strength & SSL_STRONG_MASK) && !(algo_strength & SSL_STRONG_MASK & cp->algo_strength))
768 				continue;
769 		}
770 
771 		/* add the cipher if it has not been added yet. */
772 		if (rule == CIPHER_ADD) {
773 			/* reverse == 0 */
774 			if (!curr->active) {
775 				ll_append_tail(&head, curr, &tail);
776 				curr->active = 1;
777 			}
778 		}
779 		/* Move the added cipher to this location */
780 		else if (rule == CIPHER_ORD) {
781 			/* reverse == 0 */
782 			if (curr->active) {
783 				ll_append_tail(&head, curr, &tail);
784 			}
785 		} else if (rule == CIPHER_DEL) {
786 			/* reverse == 1 */
787 			if (curr->active) {
788 				/* most recently deleted ciphersuites get best positions
789 				 * for any future CIPHER_ADD (note that the CIPHER_DEL loop
790 				 * works in reverse to maintain the order) */
791 				ll_append_head(&head, curr, &tail);
792 				curr->active = 0;
793 			}
794 		} else if (rule == CIPHER_KILL) {
795 			/* reverse == 0 */
796 			if (head == curr)
797 				head = curr->next;
798 			else
799 				curr->prev->next = curr->next;
800 			if (tail == curr)
801 				tail = curr->prev;
802 			curr->active = 0;
803 			if (curr->next != NULL)
804 				curr->next->prev = curr->prev;
805 			if (curr->prev != NULL)
806 				curr->prev->next = curr->next;
807 			curr->next = NULL;
808 			curr->prev = NULL;
809 		}
810 	}
811 
812 	*head_p = head;
813 	*tail_p = tail;
814 }
815 
816 static int
817 ssl_cipher_strength_sort(CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p)
818 {
819 	int max_strength_bits, i, *number_uses;
820 	CIPHER_ORDER *curr;
821 
822 	/*
823 	 * This routine sorts the ciphers with descending strength. The sorting
824 	 * must keep the pre-sorted sequence, so we apply the normal sorting
825 	 * routine as '+' movement to the end of the list.
826 	 */
827 	max_strength_bits = 0;
828 	curr = *head_p;
829 	while (curr != NULL) {
830 		if (curr->active &&
831 		    (curr->cipher->strength_bits > max_strength_bits))
832 			max_strength_bits = curr->cipher->strength_bits;
833 		curr = curr->next;
834 	}
835 
836 	number_uses = calloc((max_strength_bits + 1), sizeof(int));
837 	if (!number_uses) {
838 		SSLerrorx(ERR_R_MALLOC_FAILURE);
839 		return (0);
840 	}
841 
842 	/*
843 	 * Now find the strength_bits values actually used
844 	 */
845 	curr = *head_p;
846 	while (curr != NULL) {
847 		if (curr->active)
848 			number_uses[curr->cipher->strength_bits]++;
849 		curr = curr->next;
850 	}
851 	/*
852 	 * Go through the list of used strength_bits values in descending
853 	 * order.
854 	 */
855 	for (i = max_strength_bits; i >= 0; i--)
856 		if (number_uses[i] > 0)
857 			ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ORD, i, head_p, tail_p);
858 
859 	free(number_uses);
860 	return (1);
861 }
862 
863 static int
864 ssl_cipher_process_rulestr(const char *rule_str, CIPHER_ORDER **head_p,
865     CIPHER_ORDER **tail_p, const SSL_CIPHER **ca_list, SSL_CERT *cert,
866     int *tls13_seen)
867 {
868 	unsigned long alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl;
869 	unsigned long algo_strength;
870 	int j, multi, found, rule, retval, ok, buflen;
871 	uint16_t cipher_value = 0;
872 	const char *l, *buf;
873 	char ch;
874 
875 	*tls13_seen = 0;
876 
877 	retval = 1;
878 	l = rule_str;
879 	for (;;) {
880 		ch = *l;
881 
882 		if (ch == '\0')
883 			break;
884 
885 		if (ch == '-') {
886 			rule = CIPHER_DEL;
887 			l++;
888 		} else if (ch == '+') {
889 			rule = CIPHER_ORD;
890 			l++;
891 		} else if (ch == '!') {
892 			rule = CIPHER_KILL;
893 			l++;
894 		} else if (ch == '@') {
895 			rule = CIPHER_SPECIAL;
896 			l++;
897 		} else {
898 			rule = CIPHER_ADD;
899 		}
900 
901 		if (ITEM_SEP(ch)) {
902 			l++;
903 			continue;
904 		}
905 
906 		alg_mkey = 0;
907 		alg_auth = 0;
908 		alg_enc = 0;
909 		alg_mac = 0;
910 		alg_ssl = 0;
911 		algo_strength = 0;
912 
913 		for (;;) {
914 			ch = *l;
915 			buf = l;
916 			buflen = 0;
917 			while (((ch >= 'A') && (ch <= 'Z')) ||
918 			    ((ch >= '0') && (ch <= '9')) ||
919 			    ((ch >= 'a') && (ch <= 'z')) ||
920 			    (ch == '-') || (ch == '.') ||
921 			    (ch == '_') || (ch == '=')) {
922 				ch = *(++l);
923 				buflen++;
924 			}
925 
926 			if (buflen == 0) {
927 				/*
928 				 * We hit something we cannot deal with,
929 				 * it is no command or separator nor
930 				 * alphanumeric, so we call this an error.
931 				 */
932 				SSLerrorx(SSL_R_INVALID_COMMAND);
933 				return 0;
934 			}
935 
936 			if (rule == CIPHER_SPECIAL) {
937 				 /* unused -- avoid compiler warning */
938 				found = 0;
939 				/* special treatment */
940 				break;
941 			}
942 
943 			/* check for multi-part specification */
944 			if (ch == '+') {
945 				multi = 1;
946 				l++;
947 			} else
948 				multi = 0;
949 
950 			/*
951 			 * Now search for the cipher alias in the ca_list.
952 			 * Be careful with the strncmp, because the "buflen"
953 			 * limitation will make the rule "ADH:SOME" and the
954 			 * cipher "ADH-MY-CIPHER" look like a match for
955 			 * buflen=3. So additionally check whether the cipher
956 			 * name found has the correct length. We can save a
957 			 * strlen() call: just checking for the '\0' at the
958 			 * right place is sufficient, we have to strncmp()
959 			 * anyway (we cannot use strcmp(), because buf is not
960 			 * '\0' terminated.)
961 			 */
962 			j = found = 0;
963 			cipher_value = 0;
964 			while (ca_list[j]) {
965 				if (!strncmp(buf, ca_list[j]->name, buflen) &&
966 				    (ca_list[j]->name[buflen] == '\0')) {
967 					found = 1;
968 					break;
969 				} else
970 					j++;
971 			}
972 
973 			if (!found)
974 				break;	/* ignore this entry */
975 
976 			if (ca_list[j]->algorithm_mkey) {
977 				if (alg_mkey) {
978 					alg_mkey &= ca_list[j]->algorithm_mkey;
979 					if (!alg_mkey) {
980 						found = 0;
981 						break;
982 					}
983 				} else
984 					alg_mkey = ca_list[j]->algorithm_mkey;
985 			}
986 
987 			if (ca_list[j]->algorithm_auth) {
988 				if (alg_auth) {
989 					alg_auth &= ca_list[j]->algorithm_auth;
990 					if (!alg_auth) {
991 						found = 0;
992 						break;
993 					}
994 				} else
995 					alg_auth = ca_list[j]->algorithm_auth;
996 			}
997 
998 			if (ca_list[j]->algorithm_enc) {
999 				if (alg_enc) {
1000 					alg_enc &= ca_list[j]->algorithm_enc;
1001 					if (!alg_enc) {
1002 						found = 0;
1003 						break;
1004 					}
1005 				} else
1006 					alg_enc = ca_list[j]->algorithm_enc;
1007 			}
1008 
1009 			if (ca_list[j]->algorithm_mac) {
1010 				if (alg_mac) {
1011 					alg_mac &= ca_list[j]->algorithm_mac;
1012 					if (!alg_mac) {
1013 						found = 0;
1014 						break;
1015 					}
1016 				} else
1017 					alg_mac = ca_list[j]->algorithm_mac;
1018 			}
1019 
1020 			if (ca_list[j]->algo_strength & SSL_STRONG_MASK) {
1021 				if (algo_strength & SSL_STRONG_MASK) {
1022 					algo_strength &=
1023 					    (ca_list[j]->algo_strength &
1024 					    SSL_STRONG_MASK) | ~SSL_STRONG_MASK;
1025 					if (!(algo_strength &
1026 					    SSL_STRONG_MASK)) {
1027 						found = 0;
1028 						break;
1029 					}
1030 				} else
1031 					algo_strength |=
1032 					    ca_list[j]->algo_strength &
1033 					    SSL_STRONG_MASK;
1034 			}
1035 
1036 			if (ca_list[j]->value != 0) {
1037 				/*
1038 				 * explicit ciphersuite found; its protocol
1039 				 * version does not become part of the search
1040 				 * pattern!
1041 				 */
1042 				cipher_value = ca_list[j]->value;
1043 				if (ca_list[j]->algorithm_ssl == SSL_TLSV1_3)
1044 					*tls13_seen = 1;
1045 			} else {
1046 				/*
1047 				 * not an explicit ciphersuite; only in this
1048 				 * case, the protocol version is considered
1049 				 * part of the search pattern
1050 				 */
1051 				if (ca_list[j]->algorithm_ssl) {
1052 					if (alg_ssl) {
1053 						alg_ssl &=
1054 						    ca_list[j]->algorithm_ssl;
1055 						if (!alg_ssl) {
1056 							found = 0;
1057 							break;
1058 						}
1059 					} else
1060 						alg_ssl =
1061 						    ca_list[j]->algorithm_ssl;
1062 				}
1063 			}
1064 
1065 			if (!multi)
1066 				break;
1067 		}
1068 
1069 		/*
1070 		 * Ok, we have the rule, now apply it
1071 		 */
1072 		if (rule == CIPHER_SPECIAL) {
1073 			/* special command */
1074 			ok = 0;
1075 			if (buflen == 8 && strncmp(buf, "STRENGTH", 8) == 0) {
1076 				ok = ssl_cipher_strength_sort(head_p, tail_p);
1077 			} else if (buflen == 10 &&
1078 			    strncmp(buf, "SECLEVEL=", 9) == 0) {
1079 				int level = buf[9] - '0';
1080 
1081 				if (level >= 0 && level <= 5) {
1082 					cert->security_level = level;
1083 					ok = 1;
1084 				} else {
1085 					SSLerrorx(SSL_R_INVALID_COMMAND);
1086 				}
1087 			} else {
1088 				SSLerrorx(SSL_R_INVALID_COMMAND);
1089 			}
1090 			if (ok == 0)
1091 				retval = 0;
1092 
1093 			while ((*l != '\0') && !ITEM_SEP(*l))
1094 				l++;
1095 		} else if (found) {
1096 			if (alg_ssl == SSL_TLSV1_3)
1097 				*tls13_seen = 1;
1098 			ssl_cipher_apply_rule(cipher_value, alg_mkey, alg_auth,
1099 			    alg_enc, alg_mac, alg_ssl, algo_strength, rule,
1100 			    -1, head_p, tail_p);
1101 		} else {
1102 			while ((*l != '\0') && !ITEM_SEP(*l))
1103 				l++;
1104 		}
1105 		if (*l == '\0')
1106 			break; /* done */
1107 	}
1108 
1109 	return (retval);
1110 }
1111 
1112 static inline int
1113 ssl_aes_is_accelerated(void)
1114 {
1115 	return (OPENSSL_cpu_caps() & CRYPTO_CPU_CAPS_ACCELERATED_AES) != 0;
1116 }
1117 
1118 STACK_OF(SSL_CIPHER) *
1119 ssl_create_cipher_list(const SSL_METHOD *ssl_method,
1120     STACK_OF(SSL_CIPHER) **cipher_list,
1121     STACK_OF(SSL_CIPHER) *cipher_list_tls13,
1122     const char *rule_str, SSL_CERT *cert)
1123 {
1124 	int ok, num_of_ciphers, num_of_alias_max, num_of_group_aliases;
1125 	unsigned long disabled_mkey, disabled_auth, disabled_enc, disabled_mac, disabled_ssl;
1126 	STACK_OF(SSL_CIPHER) *cipherstack = NULL, *ret = NULL;
1127 	const char *rule_p;
1128 	CIPHER_ORDER *co_list = NULL, *head = NULL, *tail = NULL, *curr;
1129 	const SSL_CIPHER **ca_list = NULL;
1130 	const SSL_CIPHER *cipher;
1131 	int tls13_seen = 0;
1132 	int any_active;
1133 	int i;
1134 
1135 	/*
1136 	 * Return with error if nothing to do.
1137 	 */
1138 	if (rule_str == NULL || cipher_list == NULL)
1139 		goto err;
1140 
1141 	disabled_mkey = 0;
1142 	disabled_auth = 0;
1143 	disabled_enc = 0;
1144 	disabled_mac = 0;
1145 	disabled_ssl = 0;
1146 
1147 #ifdef SSL_FORBID_ENULL
1148 	disabled_enc |= SSL_eNULL;
1149 #endif
1150 
1151 	/* DTLS cannot be used with stream ciphers. */
1152 	if (ssl_method->dtls)
1153 		disabled_enc |= SSL_RC4;
1154 
1155 	/*
1156 	 * Now we have to collect the available ciphers from the compiled
1157 	 * in ciphers. We cannot get more than the number compiled in, so
1158 	 * it is used for allocation.
1159 	 */
1160 	num_of_ciphers = ssl3_num_ciphers();
1161 	co_list = reallocarray(NULL, num_of_ciphers, sizeof(CIPHER_ORDER));
1162 	if (co_list == NULL) {
1163 		SSLerrorx(ERR_R_MALLOC_FAILURE);
1164 		goto err;
1165 	}
1166 
1167 	ssl_cipher_collect_ciphers(ssl_method, num_of_ciphers,
1168 	    disabled_mkey, disabled_auth, disabled_enc, disabled_mac, disabled_ssl,
1169 	    co_list, &head, &tail);
1170 
1171 
1172 	/* Now arrange all ciphers by preference: */
1173 
1174 	/* Everything else being equal, prefer ephemeral ECDH over other key exchange mechanisms */
1175 	ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1176 	ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail);
1177 
1178 	if (ssl_aes_is_accelerated()) {
1179 		/*
1180 		 * We have hardware assisted AES - prefer AES as a symmetric
1181 		 * cipher, with CHACHA20 second.
1182 		 */
1183 		ssl_cipher_apply_rule(0, 0, 0, SSL_AES, 0, 0, 0,
1184 		    CIPHER_ADD, -1, &head, &tail);
1185 		ssl_cipher_apply_rule(0, 0, 0, SSL_CHACHA20POLY1305,
1186 		    0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1187 	} else {
1188 		/*
1189 		 * CHACHA20 is fast and safe on all hardware and is thus our
1190 		 * preferred symmetric cipher, with AES second.
1191 		 */
1192 		ssl_cipher_apply_rule(0, 0, 0, SSL_CHACHA20POLY1305,
1193 		    0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1194 		ssl_cipher_apply_rule(0, 0, 0, SSL_AES, 0, 0, 0,
1195 		    CIPHER_ADD, -1, &head, &tail);
1196 	}
1197 
1198 	/* Temporarily enable everything else for sorting */
1199 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1200 
1201 	/* Low priority for MD5 */
1202 	ssl_cipher_apply_rule(0, 0, 0, 0, SSL_MD5, 0, 0, CIPHER_ORD, -1, &head, &tail);
1203 
1204 	/* Move anonymous ciphers to the end.  Usually, these will remain disabled.
1205 	 * (For applications that allow them, they aren't too bad, but we prefer
1206 	 * authenticated ciphers.) */
1207 	ssl_cipher_apply_rule(0, 0, SSL_aNULL, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail);
1208 
1209 	/* Move ciphers without forward secrecy to the end */
1210 	ssl_cipher_apply_rule(0, SSL_kRSA, 0, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail);
1211 
1212 	/* RC4 is sort of broken - move it to the end */
1213 	ssl_cipher_apply_rule(0, 0, 0, SSL_RC4, 0, 0, 0, CIPHER_ORD, -1, &head, &tail);
1214 
1215 	/* Now sort by symmetric encryption strength.  The above ordering remains
1216 	 * in force within each class */
1217 	if (!ssl_cipher_strength_sort(&head, &tail))
1218 		goto err;
1219 
1220 	/* Now disable everything (maintaining the ordering!) */
1221 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail);
1222 
1223 	/* TLSv1.3 first. */
1224 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, SSL_TLSV1_3, 0, CIPHER_ADD, -1, &head, &tail);
1225 	ssl_cipher_apply_rule(0, 0, 0, 0, 0, SSL_TLSV1_3, 0, CIPHER_DEL, -1, &head, &tail);
1226 
1227 	/*
1228 	 * We also need cipher aliases for selecting based on the rule_str.
1229 	 * There might be two types of entries in the rule_str: 1) names
1230 	 * of ciphers themselves 2) aliases for groups of ciphers.
1231 	 * For 1) we need the available ciphers and for 2) the cipher
1232 	 * groups of cipher_aliases added together in one list (otherwise
1233 	 * we would be happy with just the cipher_aliases table).
1234 	 */
1235 	num_of_group_aliases = sizeof(cipher_aliases) / sizeof(SSL_CIPHER);
1236 	num_of_alias_max = num_of_ciphers + num_of_group_aliases + 1;
1237 	ca_list = reallocarray(NULL, num_of_alias_max, sizeof(SSL_CIPHER *));
1238 	if (ca_list == NULL) {
1239 		SSLerrorx(ERR_R_MALLOC_FAILURE);
1240 		goto err;
1241 	}
1242 	ssl_cipher_collect_aliases(ca_list, num_of_group_aliases, disabled_mkey,
1243 	    disabled_auth, disabled_enc, disabled_mac, disabled_ssl, head);
1244 
1245 	/*
1246 	 * If the rule_string begins with DEFAULT, apply the default rule
1247 	 * before using the (possibly available) additional rules.
1248 	 */
1249 	ok = 1;
1250 	rule_p = rule_str;
1251 	if (strncmp(rule_str, "DEFAULT", 7) == 0) {
1252 		ok = ssl_cipher_process_rulestr(SSL_DEFAULT_CIPHER_LIST,
1253 		    &head, &tail, ca_list, cert, &tls13_seen);
1254 		rule_p += 7;
1255 		if (*rule_p == ':')
1256 			rule_p++;
1257 	}
1258 
1259 	if (ok && (strlen(rule_p) > 0))
1260 		ok = ssl_cipher_process_rulestr(rule_p, &head, &tail, ca_list,
1261 		    cert, &tls13_seen);
1262 
1263 	if (!ok) {
1264 		/* Rule processing failure */
1265 		goto err;
1266 	}
1267 
1268 	/*
1269 	 * Allocate new "cipherstack" for the result, return with error
1270 	 * if we cannot get one.
1271 	 */
1272 	if ((cipherstack = sk_SSL_CIPHER_new_null()) == NULL) {
1273 		SSLerrorx(ERR_R_MALLOC_FAILURE);
1274 		goto err;
1275 	}
1276 
1277 	/* Prefer TLSv1.3 cipher suites. */
1278 	if (cipher_list_tls13 != NULL) {
1279 		for (i = 0; i < sk_SSL_CIPHER_num(cipher_list_tls13); i++) {
1280 			cipher = sk_SSL_CIPHER_value(cipher_list_tls13, i);
1281 			if (!sk_SSL_CIPHER_push(cipherstack, cipher)) {
1282 				SSLerrorx(ERR_R_MALLOC_FAILURE);
1283 				goto err;
1284 			}
1285 		}
1286 		tls13_seen = 1;
1287 	}
1288 
1289 	/*
1290 	 * The cipher selection for the list is done. The ciphers are added
1291 	 * to the resulting precedence to the STACK_OF(SSL_CIPHER).
1292 	 *
1293 	 * If the rule string did not contain any references to TLSv1.3 and
1294 	 * TLSv1.3 cipher suites have not been configured separately,
1295 	 * include inactive TLSv1.3 cipher suites. This avoids attempts to
1296 	 * use TLSv1.3 with an older rule string that does not include
1297 	 * TLSv1.3 cipher suites. If the rule string resulted in no active
1298 	 * cipher suites then we return an empty stack.
1299 	 */
1300 	any_active = 0;
1301 	for (curr = head; curr != NULL; curr = curr->next) {
1302 		if (curr->active ||
1303 		    (!tls13_seen && curr->cipher->algorithm_ssl == SSL_TLSV1_3)) {
1304 			if (!sk_SSL_CIPHER_push(cipherstack, curr->cipher)) {
1305 				SSLerrorx(ERR_R_MALLOC_FAILURE);
1306 				goto err;
1307 			}
1308 		}
1309 		any_active |= curr->active;
1310 	}
1311 	if (!any_active)
1312 		sk_SSL_CIPHER_zero(cipherstack);
1313 
1314 	sk_SSL_CIPHER_free(*cipher_list);
1315 	*cipher_list = cipherstack;
1316 	cipherstack = NULL;
1317 
1318 	ret = *cipher_list;
1319 
1320  err:
1321 	sk_SSL_CIPHER_free(cipherstack);
1322 	free((void *)ca_list);
1323 	free(co_list);
1324 
1325 	return ret;
1326 }
1327 
1328 char *
1329 SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int len)
1330 {
1331 	unsigned long alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl;
1332 	const char *ver, *kx, *au, *enc, *mac;
1333 	char *ret;
1334 	int l;
1335 
1336 	alg_mkey = cipher->algorithm_mkey;
1337 	alg_auth = cipher->algorithm_auth;
1338 	alg_enc = cipher->algorithm_enc;
1339 	alg_mac = cipher->algorithm_mac;
1340 	alg_ssl = cipher->algorithm_ssl;
1341 
1342 	if (alg_ssl & SSL_SSLV3)
1343 		ver = "SSLv3";
1344 	else if (alg_ssl & SSL_TLSV1_2)
1345 		ver = "TLSv1.2";
1346 	else if (alg_ssl & SSL_TLSV1_3)
1347 		ver = "TLSv1.3";
1348 	else
1349 		ver = "unknown";
1350 
1351 	switch (alg_mkey) {
1352 	case SSL_kRSA:
1353 		kx = "RSA";
1354 		break;
1355 	case SSL_kDHE:
1356 		kx = "DH";
1357 		break;
1358 	case SSL_kECDHE:
1359 		kx = "ECDH";
1360 		break;
1361 	case SSL_kTLS1_3:
1362 		kx = "TLSv1.3";
1363 		break;
1364 	default:
1365 		kx = "unknown";
1366 	}
1367 
1368 	switch (alg_auth) {
1369 	case SSL_aRSA:
1370 		au = "RSA";
1371 		break;
1372 	case SSL_aDSS:
1373 		au = "DSS";
1374 		break;
1375 	case SSL_aNULL:
1376 		au = "None";
1377 		break;
1378 	case SSL_aECDSA:
1379 		au = "ECDSA";
1380 		break;
1381 	case SSL_aTLS1_3:
1382 		au = "TLSv1.3";
1383 		break;
1384 	default:
1385 		au = "unknown";
1386 		break;
1387 	}
1388 
1389 	switch (alg_enc) {
1390 	case SSL_3DES:
1391 		enc = "3DES(168)";
1392 		break;
1393 	case SSL_RC4:
1394 		enc = "RC4(128)";
1395 		break;
1396 	case SSL_eNULL:
1397 		enc = "None";
1398 		break;
1399 	case SSL_AES128:
1400 		enc = "AES(128)";
1401 		break;
1402 	case SSL_AES256:
1403 		enc = "AES(256)";
1404 		break;
1405 	case SSL_AES128GCM:
1406 		enc = "AESGCM(128)";
1407 		break;
1408 	case SSL_AES256GCM:
1409 		enc = "AESGCM(256)";
1410 		break;
1411 	case SSL_CAMELLIA128:
1412 		enc = "Camellia(128)";
1413 		break;
1414 	case SSL_CAMELLIA256:
1415 		enc = "Camellia(256)";
1416 		break;
1417 	case SSL_CHACHA20POLY1305:
1418 		enc = "ChaCha20-Poly1305";
1419 		break;
1420 	default:
1421 		enc = "unknown";
1422 		break;
1423 	}
1424 
1425 	switch (alg_mac) {
1426 	case SSL_MD5:
1427 		mac = "MD5";
1428 		break;
1429 	case SSL_SHA1:
1430 		mac = "SHA1";
1431 		break;
1432 	case SSL_SHA256:
1433 		mac = "SHA256";
1434 		break;
1435 	case SSL_SHA384:
1436 		mac = "SHA384";
1437 		break;
1438 	case SSL_AEAD:
1439 		mac = "AEAD";
1440 		break;
1441 	default:
1442 		mac = "unknown";
1443 		break;
1444 	}
1445 
1446 	if (asprintf(&ret, "%-23s %s Kx=%-8s Au=%-4s Enc=%-9s Mac=%-4s\n",
1447 	    cipher->name, ver, kx, au, enc, mac) == -1)
1448 		return "OPENSSL_malloc Error";
1449 
1450 	if (buf != NULL) {
1451 		l = strlcpy(buf, ret, len);
1452 		free(ret);
1453 		ret = buf;
1454 		if (l >= len)
1455 			ret = "Buffer too small";
1456 	}
1457 
1458 	return (ret);
1459 }
1460 LSSL_ALIAS(SSL_CIPHER_description);
1461 
1462 const char *
1463 SSL_CIPHER_get_version(const SSL_CIPHER *cipher)
1464 {
1465 	if (cipher == NULL)
1466 		return "(NONE)";
1467 
1468 	return "TLSv1/SSLv3";
1469 }
1470 LSSL_ALIAS(SSL_CIPHER_get_version);
1471 
1472 /* return the actual cipher being used */
1473 const char *
1474 SSL_CIPHER_get_name(const SSL_CIPHER *cipher)
1475 {
1476 	if (cipher == NULL)
1477 		return "(NONE)";
1478 
1479 	return cipher->name;
1480 }
1481 LSSL_ALIAS(SSL_CIPHER_get_name);
1482 
1483 /* number of bits for symmetric cipher */
1484 int
1485 SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits)
1486 {
1487 	int ret = 0;
1488 
1489 	if (c != NULL) {
1490 		if (alg_bits != NULL)
1491 			*alg_bits = c->alg_bits;
1492 		ret = c->strength_bits;
1493 	}
1494 	return (ret);
1495 }
1496 LSSL_ALIAS(SSL_CIPHER_get_bits);
1497 
1498 unsigned long
1499 SSL_CIPHER_get_id(const SSL_CIPHER *cipher)
1500 {
1501 	return SSL3_CK_ID | cipher->value;
1502 }
1503 LSSL_ALIAS(SSL_CIPHER_get_id);
1504 
1505 uint16_t
1506 SSL_CIPHER_get_value(const SSL_CIPHER *cipher)
1507 {
1508 	return cipher->value;
1509 }
1510 LSSL_ALIAS(SSL_CIPHER_get_value);
1511 
1512 const SSL_CIPHER *
1513 SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr)
1514 {
1515 	uint16_t cipher_value;
1516 	CBS cbs;
1517 
1518 	/* This API is documented with ptr being an array of length two. */
1519 	CBS_init(&cbs, ptr, 2);
1520 	if (!CBS_get_u16(&cbs, &cipher_value))
1521 		return NULL;
1522 
1523 	return ssl3_get_cipher_by_value(cipher_value);
1524 }
1525 LSSL_ALIAS(SSL_CIPHER_find);
1526 
1527 int
1528 SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c)
1529 {
1530 	switch (c->algorithm_enc) {
1531 	case SSL_eNULL:
1532 		return NID_undef;
1533 	case SSL_3DES:
1534 		return NID_des_ede3_cbc;
1535 	case SSL_AES128:
1536 		return NID_aes_128_cbc;
1537 	case SSL_AES128GCM:
1538 		return NID_aes_128_gcm;
1539 	case SSL_AES256:
1540 		return NID_aes_256_cbc;
1541 	case SSL_AES256GCM:
1542 		return NID_aes_256_gcm;
1543 	case SSL_CAMELLIA128:
1544 		return NID_camellia_128_cbc;
1545 	case SSL_CAMELLIA256:
1546 		return NID_camellia_256_cbc;
1547 	case SSL_CHACHA20POLY1305:
1548 		return NID_chacha20_poly1305;
1549 	case SSL_DES:
1550 		return NID_des_cbc;
1551 	case SSL_RC4:
1552 		return NID_rc4;
1553 	default:
1554 		return NID_undef;
1555 	}
1556 }
1557 LSSL_ALIAS(SSL_CIPHER_get_cipher_nid);
1558 
1559 int
1560 SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c)
1561 {
1562 	switch (c->algorithm_mac) {
1563 	case SSL_AEAD:
1564 		return NID_undef;
1565 	case SSL_MD5:
1566 		return NID_md5;
1567 	case SSL_SHA1:
1568 		return NID_sha1;
1569 	case SSL_SHA256:
1570 		return NID_sha256;
1571 	case SSL_SHA384:
1572 		return NID_sha384;
1573 	default:
1574 		return NID_undef;
1575 	}
1576 }
1577 LSSL_ALIAS(SSL_CIPHER_get_digest_nid);
1578 
1579 int
1580 SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c)
1581 {
1582 	switch (c->algorithm_mkey) {
1583 	case SSL_kDHE:
1584 		return NID_kx_dhe;
1585 	case SSL_kECDHE:
1586 		return NID_kx_ecdhe;
1587 	case SSL_kRSA:
1588 		return NID_kx_rsa;
1589 	default:
1590 		return NID_undef;
1591 	}
1592 }
1593 LSSL_ALIAS(SSL_CIPHER_get_kx_nid);
1594 
1595 int
1596 SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c)
1597 {
1598 	switch (c->algorithm_auth) {
1599 	case SSL_aNULL:
1600 		return NID_auth_null;
1601 	case SSL_aECDSA:
1602 		return NID_auth_ecdsa;
1603 	case SSL_aRSA:
1604 		return NID_auth_rsa;
1605 	default:
1606 		return NID_undef;
1607 	}
1608 }
1609 LSSL_ALIAS(SSL_CIPHER_get_auth_nid);
1610 
1611 const EVP_MD *
1612 SSL_CIPHER_get_handshake_digest(const SSL_CIPHER *c)
1613 {
1614 	switch (c->algorithm2 & SSL_HANDSHAKE_MAC_MASK) {
1615 	case SSL_HANDSHAKE_MAC_SHA256:
1616 		return EVP_sha256();
1617 	case SSL_HANDSHAKE_MAC_SHA384:
1618 		return EVP_sha384();
1619 	default:
1620 		return NULL;
1621 	}
1622 }
1623 LSSL_ALIAS(SSL_CIPHER_get_handshake_digest);
1624 
1625 int
1626 SSL_CIPHER_is_aead(const SSL_CIPHER *c)
1627 {
1628 	return (c->algorithm_mac & SSL_AEAD) == SSL_AEAD;
1629 }
1630 LSSL_ALIAS(SSL_CIPHER_is_aead);
1631 
1632 void *
1633 SSL_COMP_get_compression_methods(void)
1634 {
1635 	return NULL;
1636 }
1637 LSSL_ALIAS(SSL_COMP_get_compression_methods);
1638 
1639 const char *
1640 SSL_COMP_get_name(const void *comp)
1641 {
1642 	return NULL;
1643 }
1644 LSSL_ALIAS(SSL_COMP_get_name);
1645