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