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