CCM support.
[openssl.git] / ssl / ssl_ciph.c
1 /* ssl/ssl_ciph.c */
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 #include <openssl/objects.h>
145 #ifndef OPENSSL_NO_COMP
146 # include <openssl/comp.h>
147 #endif
148 #ifndef OPENSSL_NO_ENGINE
149 # include <openssl/engine.h>
150 #endif
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_RC2_IDX         3
157 #define SSL_ENC_IDEA_IDX        4
158 #define SSL_ENC_NULL_IDX        5
159 #define SSL_ENC_AES128_IDX      6
160 #define SSL_ENC_AES256_IDX      7
161 #define SSL_ENC_CAMELLIA128_IDX 8
162 #define SSL_ENC_CAMELLIA256_IDX 9
163 #define SSL_ENC_GOST89_IDX      10
164 #define SSL_ENC_SEED_IDX        11
165 #define SSL_ENC_AES128GCM_IDX   12
166 #define SSL_ENC_AES256GCM_IDX   13
167 #define SSL_ENC_AES128CCM_IDX   14
168 #define SSL_ENC_AES256CCM_IDX   15
169 #define SSL_ENC_NUM_IDX         16
170
171 /* NB: make sure indices in these tables match values above */
172
173 typedef struct {
174     unsigned long mask;
175     int nid;
176 } ssl_cipher_table;
177
178 /* Table of NIDs for each cipher */
179 static const ssl_cipher_table ssl_cipher_table_cipher[SSL_ENC_NUM_IDX] = {
180     {SSL_DES, NID_des_cbc},     /* SSL_ENC_DES_IDX 0 */
181     {SSL_3DES, NID_des_ede3_cbc}, /* SSL_ENC_3DES_IDX 1 */
182     {SSL_RC4, NID_rc4},         /* SSL_ENC_RC4_IDX 2 */
183     {SSL_RC2, NID_rc2_cbc},     /* SSL_ENC_RC2_IDX 3 */
184     {SSL_IDEA, NID_idea_cbc},   /* SSL_ENC_IDEA_IDX 4 */
185     {SSL_eNULL, NID_undef},     /* SSL_ENC_NULL_IDX 5 */
186     {SSL_AES128, NID_aes_128_cbc}, /* SSL_ENC_AES128_IDX 6 */
187     {SSL_AES256, NID_aes_256_cbc}, /* SSL_ENC_AES256_IDX 7 */
188     {SSL_CAMELLIA128, NID_camellia_128_cbc}, /* SSL_ENC_CAMELLIA128_IDX 8 */
189     {SSL_CAMELLIA256, NID_camellia_256_cbc}, /* SSL_ENC_CAMELLIA256_IDX 9 */
190     {SSL_eGOST2814789CNT, NID_gost89_cnt}, /* SSL_ENC_GOST89_IDX 10 */
191     {SSL_SEED, NID_seed_cbc},   /* SSL_ENC_SEED_IDX 11 */
192     {SSL_AES128GCM, NID_aes_128_gcm}, /* SSL_ENC_AES128GCM_IDX 12 */
193     {SSL_AES256GCM, NID_aes_256_gcm}, /* SSL_ENC_AES256GCM_IDX 13 */
194     {SSL_AES128CCM, NID_aes_128_ccm}, /* SSL_ENC_AES128CCM_IDX 14 */
195     {SSL_AES256CCM, NID_aes_256_ccm} /* SSL_ENC_AES256CCM_IDX 15 */
196 };
197
198 static const EVP_CIPHER *ssl_cipher_methods[SSL_ENC_NUM_IDX] = {
199     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
200     NULL, NULL
201 };
202
203 #define SSL_COMP_NULL_IDX       0
204 #define SSL_COMP_ZLIB_IDX       1
205 #define SSL_COMP_NUM_IDX        2
206
207 static STACK_OF(SSL_COMP) *ssl_comp_methods = NULL;
208
209 #define SSL_MD_MD5_IDX  0
210 #define SSL_MD_SHA1_IDX 1
211 #define SSL_MD_GOST94_IDX 2
212 #define SSL_MD_GOST89MAC_IDX 3
213 #define SSL_MD_SHA256_IDX 4
214 #define SSL_MD_SHA384_IDX 5
215 /*
216  * Constant SSL_MAX_DIGEST equal to size of digests array should be defined
217  * in the ssl_locl.h
218  */
219
220 #define SSL_MD_NUM_IDX  SSL_MAX_DIGEST
221
222 /* NB: make sure indices in this table matches values above */
223 static const ssl_cipher_table ssl_cipher_table_mac[SSL_MD_NUM_IDX] = {
224     {SSL_MD5, NID_md5},         /* SSL_MD_MD5_IDX 0 */
225     {SSL_SHA1, NID_sha1},       /* SSL_MD_SHA1_IDX 1 */
226     {SSL_GOST94, NID_id_GostR3411_94}, /* SSL_MD_GOST94_IDX 2 */
227     {SSL_GOST89MAC, NID_id_Gost28147_89_MAC}, /* SSL_MD_GOST89MAC_IDX 3 */
228     {SSL_SHA256, NID_sha256},   /* SSL_MD_SHA256_IDX 4 */
229     {SSL_SHA384, NID_sha384}    /* SSL_MD_SHA384_IDX 5 */
230 };
231
232 static const EVP_MD *ssl_digest_methods[SSL_MD_NUM_IDX] = {
233     NULL, NULL, NULL, NULL, NULL, NULL
234 };
235
236 /* Utility function for table lookup */
237 static int ssl_cipher_info_find(const ssl_cipher_table * table,
238                                 size_t table_cnt, unsigned long mask)
239 {
240     size_t i;
241     for (i = 0; i < table_cnt; i++, table++) {
242         if (table->mask == mask)
243             return i;
244     }
245     return -1;
246 }
247
248 #define ssl_cipher_info_lookup(table, x) \
249     ssl_cipher_info_find(table, OSSL_NELEM(table), x)
250
251 /*
252  * PKEY_TYPE for GOST89MAC is known in advance, but, because implementation
253  * is engine-provided, we'll fill it only if corresponding EVP_PKEY_METHOD is
254  * found
255  */
256 static int ssl_mac_pkey_id[SSL_MD_NUM_IDX] = {
257     EVP_PKEY_HMAC, EVP_PKEY_HMAC, EVP_PKEY_HMAC, NID_undef,
258     EVP_PKEY_HMAC, EVP_PKEY_HMAC
259 };
260
261 static int ssl_mac_secret_size[SSL_MD_NUM_IDX] = {
262     0, 0, 0, 0, 0, 0
263 };
264
265 static const int ssl_handshake_digest_flag[SSL_MD_NUM_IDX] = {
266     SSL_HANDSHAKE_MAC_MD5, SSL_HANDSHAKE_MAC_SHA,
267     SSL_HANDSHAKE_MAC_GOST94, 0, SSL_HANDSHAKE_MAC_SHA256,
268     SSL_HANDSHAKE_MAC_SHA384
269 };
270
271 #define CIPHER_ADD      1
272 #define CIPHER_KILL     2
273 #define CIPHER_DEL      3
274 #define CIPHER_ORD      4
275 #define CIPHER_SPECIAL  5
276
277 typedef struct cipher_order_st {
278     const SSL_CIPHER *cipher;
279     int active;
280     int dead;
281     struct cipher_order_st *next, *prev;
282 } CIPHER_ORDER;
283
284 static const SSL_CIPHER cipher_aliases[] = {
285     /* "ALL" doesn't include eNULL (must be specifically enabled) */
286     {0, SSL_TXT_ALL, 0, 0, 0, ~SSL_eNULL, 0, 0, 0, 0, 0, 0},
287     /* "COMPLEMENTOFALL" */
288     {0, SSL_TXT_CMPALL, 0, 0, 0, SSL_eNULL, 0, 0, 0, 0, 0, 0},
289
290     /*
291      * "COMPLEMENTOFDEFAULT" (does *not* include ciphersuites not found in
292      * ALL!)
293      */
294     {0, SSL_TXT_CMPDEF, 0, SSL_kDHE | SSL_kECDHE, SSL_aNULL, ~SSL_eNULL, 0, 0,
295      0, 0, 0, 0},
296
297     /*
298      * key exchange aliases (some of those using only a single bit here
299      * combine multiple key exchange algs according to the RFCs, e.g. kDHE
300      * combines DHE_DSS and DHE_RSA)
301      */
302     {0, SSL_TXT_kRSA, 0, SSL_kRSA, 0, 0, 0, 0, 0, 0, 0, 0},
303
304     {0, SSL_TXT_kDHr, 0, SSL_kDHr, 0, 0, 0, 0, 0, 0, 0, 0},
305     {0, SSL_TXT_kDHd, 0, SSL_kDHd, 0, 0, 0, 0, 0, 0, 0, 0},
306     {0, SSL_TXT_kDH, 0, SSL_kDHr | SSL_kDHd, 0, 0, 0, 0, 0, 0, 0, 0},
307     {0, SSL_TXT_kEDH, 0, SSL_kDHE, 0, 0, 0, 0, 0, 0, 0, 0},
308     {0, SSL_TXT_kDHE, 0, SSL_kDHE, 0, 0, 0, 0, 0, 0, 0, 0},
309     {0, SSL_TXT_DH, 0, SSL_kDHr | SSL_kDHd | SSL_kDHE, 0, 0, 0, 0, 0, 0, 0,
310      0},
311
312     {0, SSL_TXT_kECDHr, 0, SSL_kECDHr, 0, 0, 0, 0, 0, 0, 0, 0},
313     {0, SSL_TXT_kECDHe, 0, SSL_kECDHe, 0, 0, 0, 0, 0, 0, 0, 0},
314     {0, SSL_TXT_kECDH, 0, SSL_kECDHr | SSL_kECDHe, 0, 0, 0, 0, 0, 0, 0, 0},
315     {0, SSL_TXT_kEECDH, 0, SSL_kECDHE, 0, 0, 0, 0, 0, 0, 0, 0},
316     {0, SSL_TXT_kECDHE, 0, SSL_kECDHE, 0, 0, 0, 0, 0, 0, 0, 0},
317     {0, SSL_TXT_ECDH, 0, SSL_kECDHr | SSL_kECDHe | SSL_kECDHE, 0, 0, 0, 0, 0,
318      0, 0, 0},
319
320     {0, SSL_TXT_kPSK, 0, SSL_kPSK, 0, 0, 0, 0, 0, 0, 0, 0},
321     {0, SSL_TXT_kRSAPSK, 0, SSL_kRSAPSK, 0, 0, 0, 0, 0, 0, 0, 0},
322     {0, SSL_TXT_kECDHEPSK, 0, SSL_kECDHEPSK, 0, 0, 0, 0, 0, 0, 0, 0},
323     {0, SSL_TXT_kDHEPSK, 0, SSL_kDHEPSK, 0, 0, 0, 0, 0, 0, 0, 0},
324     {0, SSL_TXT_kSRP, 0, SSL_kSRP, 0, 0, 0, 0, 0, 0, 0, 0},
325     {0, SSL_TXT_kGOST, 0, SSL_kGOST, 0, 0, 0, 0, 0, 0, 0, 0},
326
327     /* server authentication aliases */
328     {0, SSL_TXT_aRSA, 0, 0, SSL_aRSA, 0, 0, 0, 0, 0, 0, 0},
329     {0, SSL_TXT_aDSS, 0, 0, SSL_aDSS, 0, 0, 0, 0, 0, 0, 0},
330     {0, SSL_TXT_DSS, 0, 0, SSL_aDSS, 0, 0, 0, 0, 0, 0, 0},
331     {0, SSL_TXT_aNULL, 0, 0, SSL_aNULL, 0, 0, 0, 0, 0, 0, 0},
332     /* no such ciphersuites supported! */
333     {0, SSL_TXT_aDH, 0, 0, SSL_aDH, 0, 0, 0, 0, 0, 0, 0},
334     {0, SSL_TXT_aECDH, 0, 0, SSL_aECDH, 0, 0, 0, 0, 0, 0, 0},
335     {0, SSL_TXT_aECDSA, 0, 0, SSL_aECDSA, 0, 0, 0, 0, 0, 0, 0},
336     {0, SSL_TXT_ECDSA, 0, 0, SSL_aECDSA, 0, 0, 0, 0, 0, 0, 0},
337     {0, SSL_TXT_aPSK, 0, 0, SSL_aPSK, 0, 0, 0, 0, 0, 0, 0},
338     {0, SSL_TXT_aGOST01, 0, 0, SSL_aGOST01, 0, 0, 0, 0, 0, 0, 0},
339     {0, SSL_TXT_aGOST, 0, 0, SSL_aGOST01, 0, 0, 0, 0, 0, 0, 0},
340     {0, SSL_TXT_aSRP, 0, 0, SSL_aSRP, 0, 0, 0, 0, 0, 0, 0},
341
342     /* aliases combining key exchange and server authentication */
343     {0, SSL_TXT_EDH, 0, SSL_kDHE, ~SSL_aNULL, 0, 0, 0, 0, 0, 0, 0},
344     {0, SSL_TXT_DHE, 0, SSL_kDHE, ~SSL_aNULL, 0, 0, 0, 0, 0, 0, 0},
345     {0, SSL_TXT_EECDH, 0, SSL_kECDHE, ~SSL_aNULL, 0, 0, 0, 0, 0, 0, 0},
346     {0, SSL_TXT_ECDHE, 0, SSL_kECDHE, ~SSL_aNULL, 0, 0, 0, 0, 0, 0, 0},
347     {0, SSL_TXT_NULL, 0, 0, 0, SSL_eNULL, 0, 0, 0, 0, 0, 0},
348     {0, SSL_TXT_RSA, 0, SSL_kRSA, SSL_aRSA, 0, 0, 0, 0, 0, 0, 0},
349     {0, SSL_TXT_ADH, 0, SSL_kDHE, SSL_aNULL, 0, 0, 0, 0, 0, 0, 0},
350     {0, SSL_TXT_AECDH, 0, SSL_kECDHE, SSL_aNULL, 0, 0, 0, 0, 0, 0, 0},
351     {0, SSL_TXT_PSK, 0, SSL_PSK, 0, 0, 0, 0, 0, 0, 0, 0},
352     {0, SSL_TXT_SRP, 0, SSL_kSRP, 0, 0, 0, 0, 0, 0, 0, 0},
353
354     /* symmetric encryption aliases */
355     {0, SSL_TXT_DES, 0, 0, 0, SSL_DES, 0, 0, 0, 0, 0, 0},
356     {0, SSL_TXT_3DES, 0, 0, 0, SSL_3DES, 0, 0, 0, 0, 0, 0},
357     {0, SSL_TXT_RC4, 0, 0, 0, SSL_RC4, 0, 0, 0, 0, 0, 0},
358     {0, SSL_TXT_RC2, 0, 0, 0, SSL_RC2, 0, 0, 0, 0, 0, 0},
359     {0, SSL_TXT_IDEA, 0, 0, 0, SSL_IDEA, 0, 0, 0, 0, 0, 0},
360     {0, SSL_TXT_SEED, 0, 0, 0, SSL_SEED, 0, 0, 0, 0, 0, 0},
361     {0, SSL_TXT_eNULL, 0, 0, 0, SSL_eNULL, 0, 0, 0, 0, 0, 0},
362     {0, SSL_TXT_AES128, 0, 0, 0, SSL_AES128 | SSL_AES128GCM | SSL_AES128CCM, 0,
363      0, 0, 0, 0, 0},
364     {0, SSL_TXT_AES256, 0, 0, 0, SSL_AES256 | SSL_AES256GCM | SSL_AES256CCM, 0,
365      0, 0, 0, 0, 0},
366     {0, SSL_TXT_AES, 0, 0, 0, SSL_AES, 0, 0, 0, 0, 0, 0},
367     {0, SSL_TXT_AES_GCM, 0, 0, 0, SSL_AES128GCM | SSL_AES256GCM, 0, 0, 0, 0,
368      0, 0},
369     {0, SSL_TXT_AES_CCM, 0, 0, 0, SSL_AES128CCM | SSL_AES256CCM, 0, 0, 0, 0,
370      0, 0},
371     {0, SSL_TXT_CAMELLIA128, 0, 0, 0, SSL_CAMELLIA128, 0, 0, 0, 0, 0, 0},
372     {0, SSL_TXT_CAMELLIA256, 0, 0, 0, SSL_CAMELLIA256, 0, 0, 0, 0, 0, 0},
373     {0, SSL_TXT_CAMELLIA, 0, 0, 0, SSL_CAMELLIA128 | SSL_CAMELLIA256, 0, 0, 0,
374      0, 0, 0},
375
376     /* MAC aliases */
377     {0, SSL_TXT_MD5, 0, 0, 0, 0, SSL_MD5, 0, 0, 0, 0, 0},
378     {0, SSL_TXT_SHA1, 0, 0, 0, 0, SSL_SHA1, 0, 0, 0, 0, 0},
379     {0, SSL_TXT_SHA, 0, 0, 0, 0, SSL_SHA1, 0, 0, 0, 0, 0},
380     {0, SSL_TXT_GOST94, 0, 0, 0, 0, SSL_GOST94, 0, 0, 0, 0, 0},
381     {0, SSL_TXT_GOST89MAC, 0, 0, 0, 0, SSL_GOST89MAC, 0, 0, 0, 0, 0},
382     {0, SSL_TXT_SHA256, 0, 0, 0, 0, SSL_SHA256, 0, 0, 0, 0, 0},
383     {0, SSL_TXT_SHA384, 0, 0, 0, 0, SSL_SHA384, 0, 0, 0, 0, 0},
384
385     /* protocol version aliases */
386     {0, SSL_TXT_SSLV3, 0, 0, 0, 0, 0, SSL_SSLV3, 0, 0, 0, 0},
387     {0, SSL_TXT_TLSV1, 0, 0, 0, 0, 0, SSL_TLSV1, 0, 0, 0, 0},
388     {0, SSL_TXT_TLSV1_2, 0, 0, 0, 0, 0, SSL_TLSV1_2, 0, 0, 0, 0},
389
390     /* export flag */
391     {0, SSL_TXT_EXP, 0, 0, 0, 0, 0, 0, SSL_EXPORT, 0, 0, 0},
392     {0, SSL_TXT_EXPORT, 0, 0, 0, 0, 0, 0, SSL_EXPORT, 0, 0, 0},
393
394     /* strength classes */
395     {0, SSL_TXT_EXP40, 0, 0, 0, 0, 0, 0, SSL_EXP40, 0, 0, 0},
396     {0, SSL_TXT_EXP56, 0, 0, 0, 0, 0, 0, SSL_EXP56, 0, 0, 0},
397     {0, SSL_TXT_LOW, 0, 0, 0, 0, 0, 0, SSL_LOW, 0, 0, 0},
398     {0, SSL_TXT_MEDIUM, 0, 0, 0, 0, 0, 0, SSL_MEDIUM, 0, 0, 0},
399     {0, SSL_TXT_HIGH, 0, 0, 0, 0, 0, 0, SSL_HIGH, 0, 0, 0},
400     /* FIPS 140-2 approved ciphersuite */
401     {0, SSL_TXT_FIPS, 0, 0, 0, ~SSL_eNULL, 0, 0, SSL_FIPS, 0, 0, 0},
402
403     /* "EDH-" aliases to "DHE-" labels (for backward compatibility) */
404     {0, SSL3_TXT_EDH_DSS_DES_40_CBC_SHA, 0,
405      SSL_kDHE, SSL_aDSS, SSL_DES, SSL_SHA1, SSL_SSLV3, SSL_EXPORT | SSL_EXP40,
406      0, 0, 0,},
407     {0, SSL3_TXT_EDH_DSS_DES_64_CBC_SHA, 0,
408      SSL_kDHE, SSL_aDSS, SSL_DES, SSL_SHA1, SSL_SSLV3, SSL_NOT_EXP | SSL_LOW,
409      0, 0, 0,},
410     {0, SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA, 0,
411      SSL_kDHE, SSL_aDSS, SSL_3DES, SSL_SHA1, SSL_SSLV3,
412      SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, 0, 0, 0,},
413     {0, SSL3_TXT_EDH_RSA_DES_40_CBC_SHA, 0,
414      SSL_kDHE, SSL_aRSA, SSL_DES, SSL_SHA1, SSL_SSLV3, SSL_EXPORT | SSL_EXP40,
415      0, 0, 0,},
416     {0, SSL3_TXT_EDH_RSA_DES_64_CBC_SHA, 0,
417      SSL_kDHE, SSL_aRSA, SSL_DES, SSL_SHA1, SSL_SSLV3, SSL_NOT_EXP | SSL_LOW,
418      0, 0, 0,},
419     {0, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA, 0,
420      SSL_kDHE, SSL_aRSA, SSL_3DES, SSL_SHA1, SSL_SSLV3,
421      SSL_NOT_EXP | SSL_HIGH | SSL_FIPS, 0, 0, 0,},
422
423 };
424
425 /*
426  * Search for public key algorithm with given name and return its pkey_id if
427  * it is available. Otherwise return 0
428  */
429 #ifdef OPENSSL_NO_ENGINE
430
431 static int get_optional_pkey_id(const char *pkey_name)
432 {
433     const EVP_PKEY_ASN1_METHOD *ameth;
434     int pkey_id = 0;
435     ameth = EVP_PKEY_asn1_find_str(NULL, pkey_name, -1);
436     if (ameth) {
437         EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth);
438     }
439     return pkey_id;
440 }
441
442 #else
443
444 static int get_optional_pkey_id(const char *pkey_name)
445 {
446     const EVP_PKEY_ASN1_METHOD *ameth;
447     ENGINE *tmpeng = NULL;
448     int pkey_id = 0;
449     ameth = EVP_PKEY_asn1_find_str(&tmpeng, pkey_name, -1);
450     if (ameth) {
451         EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth);
452     }
453     if (tmpeng)
454         ENGINE_finish(tmpeng);
455     return pkey_id;
456 }
457
458 #endif
459
460 /* masks of disabled algorithms */
461 static unsigned long disabled_enc_mask;
462 static unsigned long disabled_mac_mask;
463 static unsigned long disabled_mkey_mask;
464 static unsigned long disabled_auth_mask;
465
466 void ssl_load_ciphers(void)
467 {
468     size_t i;
469     const ssl_cipher_table *t;
470     disabled_enc_mask = 0;
471     for (i = 0, t = ssl_cipher_table_cipher; i < SSL_ENC_NUM_IDX; i++, t++) {
472         if (t->nid == NID_undef) {
473             ssl_cipher_methods[i] = NULL;
474         } else {
475             const EVP_CIPHER *cipher = EVP_get_cipherbynid(t->nid);
476             ssl_cipher_methods[i] = cipher;
477             if (cipher == NULL)
478                 disabled_enc_mask |= t->mask;
479         }
480     }
481 #ifdef SSL_FORBID_ENULL
482     disabled_enc_mask |= SSL_eNULL;
483 #endif
484     disabled_mac_mask = 0;
485     for (i = 0, t = ssl_cipher_table_mac; i < SSL_MD_NUM_IDX; i++, t++) {
486         const EVP_MD *md = EVP_get_digestbynid(t->nid);
487         ssl_digest_methods[i] = md;
488         if (md == NULL) {
489             disabled_mac_mask |= t->mask;
490         } else {
491             ssl_mac_secret_size[i] = EVP_MD_size(md);
492             OPENSSL_assert(ssl_mac_secret_size[i] >= 0);
493         }
494     }
495     /* Make sure we can access MD5 and SHA1 */
496     OPENSSL_assert(ssl_digest_methods[SSL_MD_MD5_IDX] != NULL);
497     OPENSSL_assert(ssl_digest_methods[SSL_MD_SHA1_IDX] != NULL);
498
499     disabled_mkey_mask = 0;
500     disabled_auth_mask = 0;
501
502 #ifdef OPENSSL_NO_RSA
503     disabled_mkey_mask |= SSL_kRSA | SSL_kRSAPSK;
504     disabled_auth_mask |= SSL_aRSA;
505 #endif
506 #ifdef OPENSSL_NO_DSA
507     disabled_auth_mask |= SSL_aDSS;
508 #endif
509 #ifdef OPENSSL_NO_DH
510     disabled_mkey_mask |= SSL_kDHr | SSL_kDHd | SSL_kDHE | SSL_kDHEPSK;
511     disabled_auth_mask |= SSL_aDH;
512 #endif
513 #ifdef OPENSSL_NO_EC
514     disabled_mkey_mask |= SSL_kECDHe | SSL_kECDHr | SSL_kECDHEPSK;
515     disabled_auth_mask |= SSL_aECDSA | SSL_aECDH;
516 #endif
517 #ifdef OPENSSL_NO_PSK
518     disabled_mkey_mask |= SSL_PSK;
519     disabled_auth_mask |= SSL_aPSK;
520 #endif
521 #ifdef OPENSSL_NO_SRP
522     disabled_mkey_mask |= SSL_kSRP;
523 #endif
524
525     /*
526      * Check for presence of GOST 34.10 algorithms, and if they are not
527      * present, disable appropriate auth and key exchange
528      */
529     ssl_mac_pkey_id[SSL_MD_GOST89MAC_IDX] = get_optional_pkey_id("gost-mac");
530     if (ssl_mac_pkey_id[SSL_MD_GOST89MAC_IDX]) {
531         ssl_mac_secret_size[SSL_MD_GOST89MAC_IDX] = 32;
532     } else {
533         disabled_mac_mask |= SSL_GOST89MAC;
534     }
535
536     if (!get_optional_pkey_id("gost2001"))
537         disabled_auth_mask |= SSL_aGOST01;
538     /*
539      * Disable GOST key exchange if no GOST signature algs are available *
540      */
541     if ((disabled_auth_mask & SSL_aGOST01) == SSL_aGOST01)
542         disabled_mkey_mask |= SSL_kGOST;
543 }
544
545 #ifndef OPENSSL_NO_COMP
546
547 static int sk_comp_cmp(const SSL_COMP *const *a, const SSL_COMP *const *b)
548 {
549     return ((*a)->id - (*b)->id);
550 }
551
552 static void load_builtin_compressions(void)
553 {
554     int got_write_lock = 0;
555
556     CRYPTO_r_lock(CRYPTO_LOCK_SSL);
557     if (ssl_comp_methods == NULL) {
558         CRYPTO_r_unlock(CRYPTO_LOCK_SSL);
559         CRYPTO_w_lock(CRYPTO_LOCK_SSL);
560         got_write_lock = 1;
561
562         if (ssl_comp_methods == NULL) {
563             SSL_COMP *comp = NULL;
564             COMP_METHOD *method = COMP_zlib();
565
566             MemCheck_off();
567             ssl_comp_methods = sk_SSL_COMP_new(sk_comp_cmp);
568             if (COMP_get_type(method) != NID_undef
569                 && ssl_comp_methods != NULL) {
570                 comp = OPENSSL_malloc(sizeof(*comp));
571                 if (comp != NULL) {
572                     comp->method = method;
573                     comp->id = SSL_COMP_ZLIB_IDX;
574                     comp->name = COMP_get_name(method);
575                     sk_SSL_COMP_push(ssl_comp_methods, comp);
576                     sk_SSL_COMP_sort(ssl_comp_methods);
577                 }
578             }
579             MemCheck_on();
580         }
581     }
582
583     if (got_write_lock)
584         CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
585     else
586         CRYPTO_r_unlock(CRYPTO_LOCK_SSL);
587 }
588 #endif
589
590 int ssl_cipher_get_evp(const SSL_SESSION *s, const EVP_CIPHER **enc,
591                        const EVP_MD **md, int *mac_pkey_type,
592                        int *mac_secret_size, SSL_COMP **comp, int use_etm)
593 {
594     int i;
595     const SSL_CIPHER *c;
596
597     c = s->cipher;
598     if (c == NULL)
599         return (0);
600     if (comp != NULL) {
601         SSL_COMP ctmp;
602 #ifndef OPENSSL_NO_COMP
603         load_builtin_compressions();
604 #endif
605
606         *comp = NULL;
607         ctmp.id = s->compress_meth;
608         if (ssl_comp_methods != NULL) {
609             i = sk_SSL_COMP_find(ssl_comp_methods, &ctmp);
610             if (i >= 0)
611                 *comp = sk_SSL_COMP_value(ssl_comp_methods, i);
612             else
613                 *comp = NULL;
614         }
615         /* If were only interested in comp then return success */
616         if ((enc == NULL) && (md == NULL))
617             return 1;
618     }
619
620     if ((enc == NULL) || (md == NULL))
621         return 0;
622
623     i = ssl_cipher_info_lookup(ssl_cipher_table_cipher, c->algorithm_enc);
624
625     if (i == -1)
626         *enc = NULL;
627     else {
628         if (i == SSL_ENC_NULL_IDX)
629             *enc = EVP_enc_null();
630         else
631             *enc = ssl_cipher_methods[i];
632     }
633
634     i = ssl_cipher_info_lookup(ssl_cipher_table_mac, c->algorithm_mac);
635     if (i == -1) {
636         *md = NULL;
637         if (mac_pkey_type != NULL)
638             *mac_pkey_type = NID_undef;
639         if (mac_secret_size != NULL)
640             *mac_secret_size = 0;
641         if (c->algorithm_mac == SSL_AEAD)
642             mac_pkey_type = NULL;
643     } else {
644         *md = ssl_digest_methods[i];
645         if (mac_pkey_type != NULL)
646             *mac_pkey_type = ssl_mac_pkey_id[i];
647         if (mac_secret_size != NULL)
648             *mac_secret_size = ssl_mac_secret_size[i];
649     }
650
651     if ((*enc != NULL) &&
652         (*md != NULL || (EVP_CIPHER_flags(*enc) & EVP_CIPH_FLAG_AEAD_CIPHER))
653         && (!mac_pkey_type || *mac_pkey_type != NID_undef)) {
654         const EVP_CIPHER *evp;
655
656         if (use_etm)
657             return 1;
658
659         if (s->ssl_version >> 8 != TLS1_VERSION_MAJOR ||
660             s->ssl_version < TLS1_VERSION)
661             return 1;
662
663         if (FIPS_mode())
664             return 1;
665
666         if (c->algorithm_enc == SSL_RC4 &&
667             c->algorithm_mac == SSL_MD5 &&
668             (evp = EVP_get_cipherbyname("RC4-HMAC-MD5")))
669             *enc = evp, *md = NULL;
670         else if (c->algorithm_enc == SSL_AES128 &&
671                  c->algorithm_mac == SSL_SHA1 &&
672                  (evp = EVP_get_cipherbyname("AES-128-CBC-HMAC-SHA1")))
673             *enc = evp, *md = NULL;
674         else if (c->algorithm_enc == SSL_AES256 &&
675                  c->algorithm_mac == SSL_SHA1 &&
676                  (evp = EVP_get_cipherbyname("AES-256-CBC-HMAC-SHA1")))
677             *enc = evp, *md = NULL;
678         else if (c->algorithm_enc == SSL_AES128 &&
679                  c->algorithm_mac == SSL_SHA256 &&
680                  (evp = EVP_get_cipherbyname("AES-128-CBC-HMAC-SHA256")))
681             *enc = evp, *md = NULL;
682         else if (c->algorithm_enc == SSL_AES256 &&
683                  c->algorithm_mac == SSL_SHA256 &&
684                  (evp = EVP_get_cipherbyname("AES-256-CBC-HMAC-SHA256")))
685             *enc = evp, *md = NULL;
686         return (1);
687     } else
688         return (0);
689 }
690
691 int ssl_get_handshake_digest(int idx, long *mask, const EVP_MD **md)
692 {
693     if (idx < 0 || idx >= SSL_MD_NUM_IDX) {
694         return 0;
695     }
696     *mask = ssl_handshake_digest_flag[idx];
697     if (*mask)
698         *md = ssl_digest_methods[idx];
699     else
700         *md = NULL;
701     return 1;
702 }
703
704 #define ITEM_SEP(a) \
705         (((a) == ':') || ((a) == ' ') || ((a) == ';') || ((a) == ','))
706
707 static void ll_append_tail(CIPHER_ORDER **head, CIPHER_ORDER *curr,
708                            CIPHER_ORDER **tail)
709 {
710     if (curr == *tail)
711         return;
712     if (curr == *head)
713         *head = curr->next;
714     if (curr->prev != NULL)
715         curr->prev->next = curr->next;
716     if (curr->next != NULL)
717         curr->next->prev = curr->prev;
718     (*tail)->next = curr;
719     curr->prev = *tail;
720     curr->next = NULL;
721     *tail = curr;
722 }
723
724 static void ll_append_head(CIPHER_ORDER **head, CIPHER_ORDER *curr,
725                            CIPHER_ORDER **tail)
726 {
727     if (curr == *head)
728         return;
729     if (curr == *tail)
730         *tail = curr->prev;
731     if (curr->next != NULL)
732         curr->next->prev = curr->prev;
733     if (curr->prev != NULL)
734         curr->prev->next = curr->next;
735     (*head)->prev = curr;
736     curr->next = *head;
737     curr->prev = NULL;
738     *head = curr;
739 }
740
741 static void ssl_cipher_collect_ciphers(const SSL_METHOD *ssl_method,
742                                        int num_of_ciphers,
743                                        unsigned long disabled_mkey,
744                                        unsigned long disabled_auth,
745                                        unsigned long disabled_enc,
746                                        unsigned long disabled_mac,
747                                        unsigned long disabled_ssl,
748                                        CIPHER_ORDER *co_list,
749                                        CIPHER_ORDER **head_p,
750                                        CIPHER_ORDER **tail_p)
751 {
752     int i, co_list_num;
753     const SSL_CIPHER *c;
754
755     /*
756      * We have num_of_ciphers descriptions compiled in, depending on the
757      * method selected (SSLv3, TLSv1 etc).
758      * These will later be sorted in a linked list with at most num
759      * entries.
760      */
761
762     /* Get the initial list of ciphers */
763     co_list_num = 0;            /* actual count of ciphers */
764     for (i = 0; i < num_of_ciphers; i++) {
765         c = ssl_method->get_cipher(i);
766         /* drop those that use any of that is not available */
767         if ((c != NULL) && c->valid &&
768             (!FIPS_mode() || (c->algo_strength & SSL_FIPS)) &&
769             !(c->algorithm_mkey & disabled_mkey) &&
770             !(c->algorithm_auth & disabled_auth) &&
771             !(c->algorithm_enc & disabled_enc) &&
772             !(c->algorithm_mac & disabled_mac) &&
773             !(c->algorithm_ssl & disabled_ssl)) {
774             co_list[co_list_num].cipher = c;
775             co_list[co_list_num].next = NULL;
776             co_list[co_list_num].prev = NULL;
777             co_list[co_list_num].active = 0;
778             co_list_num++;
779             /*
780              * if (!sk_push(ca_list,(char *)c)) goto err;
781              */
782         }
783     }
784
785     /*
786      * Prepare linked list from list entries
787      */
788     if (co_list_num > 0) {
789         co_list[0].prev = NULL;
790
791         if (co_list_num > 1) {
792             co_list[0].next = &co_list[1];
793
794             for (i = 1; i < co_list_num - 1; i++) {
795                 co_list[i].prev = &co_list[i - 1];
796                 co_list[i].next = &co_list[i + 1];
797             }
798
799             co_list[co_list_num - 1].prev = &co_list[co_list_num - 2];
800         }
801
802         co_list[co_list_num - 1].next = NULL;
803
804         *head_p = &co_list[0];
805         *tail_p = &co_list[co_list_num - 1];
806     }
807 }
808
809 static void ssl_cipher_collect_aliases(const SSL_CIPHER **ca_list,
810                                        int num_of_group_aliases,
811                                        unsigned long disabled_mkey,
812                                        unsigned long disabled_auth,
813                                        unsigned long disabled_enc,
814                                        unsigned long disabled_mac,
815                                        unsigned long disabled_ssl,
816                                        CIPHER_ORDER *head)
817 {
818     CIPHER_ORDER *ciph_curr;
819     const SSL_CIPHER **ca_curr;
820     int i;
821     unsigned long mask_mkey = ~disabled_mkey;
822     unsigned long mask_auth = ~disabled_auth;
823     unsigned long mask_enc = ~disabled_enc;
824     unsigned long mask_mac = ~disabled_mac;
825     unsigned long mask_ssl = ~disabled_ssl;
826
827     /*
828      * First, add the real ciphers as already collected
829      */
830     ciph_curr = head;
831     ca_curr = ca_list;
832     while (ciph_curr != NULL) {
833         *ca_curr = ciph_curr->cipher;
834         ca_curr++;
835         ciph_curr = ciph_curr->next;
836     }
837
838     /*
839      * Now we add the available ones from the cipher_aliases[] table.
840      * They represent either one or more algorithms, some of which
841      * in any affected category must be supported (set in enabled_mask),
842      * or represent a cipher strength value (will be added in any case because algorithms=0).
843      */
844     for (i = 0; i < num_of_group_aliases; i++) {
845         unsigned long algorithm_mkey = cipher_aliases[i].algorithm_mkey;
846         unsigned long algorithm_auth = cipher_aliases[i].algorithm_auth;
847         unsigned long algorithm_enc = cipher_aliases[i].algorithm_enc;
848         unsigned long algorithm_mac = cipher_aliases[i].algorithm_mac;
849         unsigned long algorithm_ssl = cipher_aliases[i].algorithm_ssl;
850
851         if (algorithm_mkey)
852             if ((algorithm_mkey & mask_mkey) == 0)
853                 continue;
854
855         if (algorithm_auth)
856             if ((algorithm_auth & mask_auth) == 0)
857                 continue;
858
859         if (algorithm_enc)
860             if ((algorithm_enc & mask_enc) == 0)
861                 continue;
862
863         if (algorithm_mac)
864             if ((algorithm_mac & mask_mac) == 0)
865                 continue;
866
867         if (algorithm_ssl)
868             if ((algorithm_ssl & mask_ssl) == 0)
869                 continue;
870
871         *ca_curr = (SSL_CIPHER *)(cipher_aliases + i);
872         ca_curr++;
873     }
874
875     *ca_curr = NULL;            /* end of list */
876 }
877
878 static void ssl_cipher_apply_rule(unsigned long cipher_id,
879                                   unsigned long alg_mkey,
880                                   unsigned long alg_auth,
881                                   unsigned long alg_enc,
882                                   unsigned long alg_mac,
883                                   unsigned long alg_ssl,
884                                   unsigned long algo_strength, int rule,
885                                   int strength_bits, CIPHER_ORDER **head_p,
886                                   CIPHER_ORDER **tail_p)
887 {
888     CIPHER_ORDER *head, *tail, *curr, *next, *last;
889     const SSL_CIPHER *cp;
890     int reverse = 0;
891
892 #ifdef CIPHER_DEBUG
893     fprintf(stderr,
894             "Applying rule %d with %08lx/%08lx/%08lx/%08lx/%08lx %08lx (%d)\n",
895             rule, alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl,
896             algo_strength, strength_bits);
897 #endif
898
899     if (rule == CIPHER_DEL)
900         reverse = 1;            /* needed to maintain sorting between
901                                  * currently deleted ciphers */
902
903     head = *head_p;
904     tail = *tail_p;
905
906     if (reverse) {
907         next = tail;
908         last = head;
909     } else {
910         next = head;
911         last = tail;
912     }
913
914     curr = NULL;
915     for (;;) {
916         if (curr == last)
917             break;
918
919         curr = next;
920
921         if (curr == NULL)
922             break;
923
924         next = reverse ? curr->prev : curr->next;
925
926         cp = curr->cipher;
927
928         /*
929          * Selection criteria is either the value of strength_bits
930          * or the algorithms used.
931          */
932         if (strength_bits >= 0) {
933             if (strength_bits != cp->strength_bits)
934                 continue;
935         } else {
936 #ifdef CIPHER_DEBUG
937             fprintf(stderr,
938                     "\nName: %s:\nAlgo = %08lx/%08lx/%08lx/%08lx/%08lx Algo_strength = %08lx\n",
939                     cp->name, cp->algorithm_mkey, cp->algorithm_auth,
940                     cp->algorithm_enc, cp->algorithm_mac, cp->algorithm_ssl,
941                     cp->algo_strength);
942 #endif
943 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
944             if (cipher_id && cipher_id != cp->id)
945                 continue;
946 #endif
947             if (alg_mkey && !(alg_mkey & cp->algorithm_mkey))
948                 continue;
949             if (alg_auth && !(alg_auth & cp->algorithm_auth))
950                 continue;
951             if (alg_enc && !(alg_enc & cp->algorithm_enc))
952                 continue;
953             if (alg_mac && !(alg_mac & cp->algorithm_mac))
954                 continue;
955             if (alg_ssl && !(alg_ssl & cp->algorithm_ssl))
956                 continue;
957             if ((algo_strength & SSL_EXP_MASK)
958                 && !(algo_strength & SSL_EXP_MASK & cp->algo_strength))
959                 continue;
960             if ((algo_strength & SSL_STRONG_MASK)
961                 && !(algo_strength & SSL_STRONG_MASK & cp->algo_strength))
962                 continue;
963         }
964
965 #ifdef CIPHER_DEBUG
966         fprintf(stderr, "Action = %d\n", rule);
967 #endif
968
969         /* add the cipher if it has not been added yet. */
970         if (rule == CIPHER_ADD) {
971             /* reverse == 0 */
972             if (!curr->active) {
973                 ll_append_tail(&head, curr, &tail);
974                 curr->active = 1;
975             }
976         }
977         /* Move the added cipher to this location */
978         else if (rule == CIPHER_ORD) {
979             /* reverse == 0 */
980             if (curr->active) {
981                 ll_append_tail(&head, curr, &tail);
982             }
983         } else if (rule == CIPHER_DEL) {
984             /* reverse == 1 */
985             if (curr->active) {
986                 /*
987                  * most recently deleted ciphersuites get best positions for
988                  * any future CIPHER_ADD (note that the CIPHER_DEL loop works
989                  * in reverse to maintain the order)
990                  */
991                 ll_append_head(&head, curr, &tail);
992                 curr->active = 0;
993             }
994         } else if (rule == CIPHER_KILL) {
995             /* reverse == 0 */
996             if (head == curr)
997                 head = curr->next;
998             else
999                 curr->prev->next = curr->next;
1000             if (tail == curr)
1001                 tail = curr->prev;
1002             curr->active = 0;
1003             if (curr->next != NULL)
1004                 curr->next->prev = curr->prev;
1005             if (curr->prev != NULL)
1006                 curr->prev->next = curr->next;
1007             curr->next = NULL;
1008             curr->prev = NULL;
1009         }
1010     }
1011
1012     *head_p = head;
1013     *tail_p = tail;
1014 }
1015
1016 static int ssl_cipher_strength_sort(CIPHER_ORDER **head_p,
1017                                     CIPHER_ORDER **tail_p)
1018 {
1019     int max_strength_bits, i, *number_uses;
1020     CIPHER_ORDER *curr;
1021
1022     /*
1023      * This routine sorts the ciphers with descending strength. The sorting
1024      * must keep the pre-sorted sequence, so we apply the normal sorting
1025      * routine as '+' movement to the end of the list.
1026      */
1027     max_strength_bits = 0;
1028     curr = *head_p;
1029     while (curr != NULL) {
1030         if (curr->active && (curr->cipher->strength_bits > max_strength_bits))
1031             max_strength_bits = curr->cipher->strength_bits;
1032         curr = curr->next;
1033     }
1034
1035     number_uses = OPENSSL_malloc(sizeof(int) * (max_strength_bits + 1));
1036     if (!number_uses) {
1037         SSLerr(SSL_F_SSL_CIPHER_STRENGTH_SORT, ERR_R_MALLOC_FAILURE);
1038         return (0);
1039     }
1040     memset(number_uses, 0, sizeof(int) * (max_strength_bits + 1));
1041
1042     /*
1043      * Now find the strength_bits values actually used
1044      */
1045     curr = *head_p;
1046     while (curr != NULL) {
1047         if (curr->active)
1048             number_uses[curr->cipher->strength_bits]++;
1049         curr = curr->next;
1050     }
1051     /*
1052      * Go through the list of used strength_bits values in descending
1053      * order.
1054      */
1055     for (i = max_strength_bits; i >= 0; i--)
1056         if (number_uses[i] > 0)
1057             ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ORD, i, head_p,
1058                                   tail_p);
1059
1060     OPENSSL_free(number_uses);
1061     return (1);
1062 }
1063
1064 static int ssl_cipher_process_rulestr(const char *rule_str,
1065                                       CIPHER_ORDER **head_p,
1066                                       CIPHER_ORDER **tail_p,
1067                                       const SSL_CIPHER **ca_list, CERT *c)
1068 {
1069     unsigned long alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl,
1070         algo_strength;
1071     const char *l, *buf;
1072     int j, multi, found, rule, retval, ok, buflen;
1073     unsigned long cipher_id = 0;
1074     char ch;
1075
1076     retval = 1;
1077     l = rule_str;
1078     for (;;) {
1079         ch = *l;
1080
1081         if (ch == '\0')
1082             break;              /* done */
1083         if (ch == '-') {
1084             rule = CIPHER_DEL;
1085             l++;
1086         } else if (ch == '+') {
1087             rule = CIPHER_ORD;
1088             l++;
1089         } else if (ch == '!') {
1090             rule = CIPHER_KILL;
1091             l++;
1092         } else if (ch == '@') {
1093             rule = CIPHER_SPECIAL;
1094             l++;
1095         } else {
1096             rule = CIPHER_ADD;
1097         }
1098
1099         if (ITEM_SEP(ch)) {
1100             l++;
1101             continue;
1102         }
1103
1104         alg_mkey = 0;
1105         alg_auth = 0;
1106         alg_enc = 0;
1107         alg_mac = 0;
1108         alg_ssl = 0;
1109         algo_strength = 0;
1110
1111         for (;;) {
1112             ch = *l;
1113             buf = l;
1114             buflen = 0;
1115 #ifndef CHARSET_EBCDIC
1116             while (((ch >= 'A') && (ch <= 'Z')) ||
1117                    ((ch >= '0') && (ch <= '9')) ||
1118                    ((ch >= 'a') && (ch <= 'z')) ||
1119                    (ch == '-') || (ch == '.') || (ch == '='))
1120 #else
1121             while (isalnum(ch) || (ch == '-') || (ch == '.') || (ch == '='))
1122 #endif
1123             {
1124                 ch = *(++l);
1125                 buflen++;
1126             }
1127
1128             if (buflen == 0) {
1129                 /*
1130                  * We hit something we cannot deal with,
1131                  * it is no command or separator nor
1132                  * alphanumeric, so we call this an error.
1133                  */
1134                 SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR,
1135                        SSL_R_INVALID_COMMAND);
1136                 retval = found = 0;
1137                 l++;
1138                 break;
1139             }
1140
1141             if (rule == CIPHER_SPECIAL) {
1142                 found = 0;      /* unused -- avoid compiler warning */
1143                 break;          /* special treatment */
1144             }
1145
1146             /* check for multi-part specification */
1147             if (ch == '+') {
1148                 multi = 1;
1149                 l++;
1150             } else
1151                 multi = 0;
1152
1153             /*
1154              * Now search for the cipher alias in the ca_list. Be careful
1155              * with the strncmp, because the "buflen" limitation
1156              * will make the rule "ADH:SOME" and the cipher
1157              * "ADH-MY-CIPHER" look like a match for buflen=3.
1158              * So additionally check whether the cipher name found
1159              * has the correct length. We can save a strlen() call:
1160              * just checking for the '\0' at the right place is
1161              * sufficient, we have to strncmp() anyway. (We cannot
1162              * use strcmp(), because buf is not '\0' terminated.)
1163              */
1164             j = found = 0;
1165             cipher_id = 0;
1166             while (ca_list[j]) {
1167                 if (strncmp(buf, ca_list[j]->name, buflen) == 0
1168                     && (ca_list[j]->name[buflen] == '\0')) {
1169                     found = 1;
1170                     break;
1171                 } else
1172                     j++;
1173             }
1174
1175             if (!found)
1176                 break;          /* ignore this entry */
1177
1178             if (ca_list[j]->algorithm_mkey) {
1179                 if (alg_mkey) {
1180                     alg_mkey &= ca_list[j]->algorithm_mkey;
1181                     if (!alg_mkey) {
1182                         found = 0;
1183                         break;
1184                     }
1185                 } else
1186                     alg_mkey = ca_list[j]->algorithm_mkey;
1187             }
1188
1189             if (ca_list[j]->algorithm_auth) {
1190                 if (alg_auth) {
1191                     alg_auth &= ca_list[j]->algorithm_auth;
1192                     if (!alg_auth) {
1193                         found = 0;
1194                         break;
1195                     }
1196                 } else
1197                     alg_auth = ca_list[j]->algorithm_auth;
1198             }
1199
1200             if (ca_list[j]->algorithm_enc) {
1201                 if (alg_enc) {
1202                     alg_enc &= ca_list[j]->algorithm_enc;
1203                     if (!alg_enc) {
1204                         found = 0;
1205                         break;
1206                     }
1207                 } else
1208                     alg_enc = ca_list[j]->algorithm_enc;
1209             }
1210
1211             if (ca_list[j]->algorithm_mac) {
1212                 if (alg_mac) {
1213                     alg_mac &= ca_list[j]->algorithm_mac;
1214                     if (!alg_mac) {
1215                         found = 0;
1216                         break;
1217                     }
1218                 } else
1219                     alg_mac = ca_list[j]->algorithm_mac;
1220             }
1221
1222             if (ca_list[j]->algo_strength & SSL_EXP_MASK) {
1223                 if (algo_strength & SSL_EXP_MASK) {
1224                     algo_strength &=
1225                         (ca_list[j]->algo_strength & SSL_EXP_MASK) |
1226                         ~SSL_EXP_MASK;
1227                     if (!(algo_strength & SSL_EXP_MASK)) {
1228                         found = 0;
1229                         break;
1230                     }
1231                 } else
1232                     algo_strength |= ca_list[j]->algo_strength & SSL_EXP_MASK;
1233             }
1234
1235             if (ca_list[j]->algo_strength & SSL_STRONG_MASK) {
1236                 if (algo_strength & SSL_STRONG_MASK) {
1237                     algo_strength &=
1238                         (ca_list[j]->algo_strength & SSL_STRONG_MASK) |
1239                         ~SSL_STRONG_MASK;
1240                     if (!(algo_strength & SSL_STRONG_MASK)) {
1241                         found = 0;
1242                         break;
1243                     }
1244                 } else
1245                     algo_strength |=
1246                         ca_list[j]->algo_strength & SSL_STRONG_MASK;
1247             }
1248
1249             if (ca_list[j]->valid) {
1250                 /*
1251                  * explicit ciphersuite found; its protocol version does not
1252                  * become part of the search pattern!
1253                  */
1254
1255                 cipher_id = ca_list[j]->id;
1256             } else {
1257                 /*
1258                  * not an explicit ciphersuite; only in this case, the
1259                  * protocol version is considered part of the search pattern
1260                  */
1261
1262                 if (ca_list[j]->algorithm_ssl) {
1263                     if (alg_ssl) {
1264                         alg_ssl &= ca_list[j]->algorithm_ssl;
1265                         if (!alg_ssl) {
1266                             found = 0;
1267                             break;
1268                         }
1269                     } else
1270                         alg_ssl = ca_list[j]->algorithm_ssl;
1271                 }
1272             }
1273
1274             if (!multi)
1275                 break;
1276         }
1277
1278         /*
1279          * Ok, we have the rule, now apply it
1280          */
1281         if (rule == CIPHER_SPECIAL) { /* special command */
1282             ok = 0;
1283             if ((buflen == 8) && strncmp(buf, "STRENGTH", 8) == 0)
1284                 ok = ssl_cipher_strength_sort(head_p, tail_p);
1285             else if (buflen == 10 && strncmp(buf, "SECLEVEL=", 9) == 0) {
1286                 int level = buf[9] - '0';
1287                 if (level < 0 || level > 5) {
1288                     SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR,
1289                            SSL_R_INVALID_COMMAND);
1290                 } else {
1291                     c->sec_level = level;
1292                     ok = 1;
1293                 }
1294             } else
1295                 SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR,
1296                        SSL_R_INVALID_COMMAND);
1297             if (ok == 0)
1298                 retval = 0;
1299             /*
1300              * We do not support any "multi" options
1301              * together with "@", so throw away the
1302              * rest of the command, if any left, until
1303              * end or ':' is found.
1304              */
1305             while ((*l != '\0') && !ITEM_SEP(*l))
1306                 l++;
1307         } else if (found) {
1308             ssl_cipher_apply_rule(cipher_id,
1309                                   alg_mkey, alg_auth, alg_enc, alg_mac,
1310                                   alg_ssl, algo_strength, rule, -1, head_p,
1311                                   tail_p);
1312         } else {
1313             while ((*l != '\0') && !ITEM_SEP(*l))
1314                 l++;
1315         }
1316         if (*l == '\0')
1317             break;              /* done */
1318     }
1319
1320     return (retval);
1321 }
1322
1323 #ifndef OPENSSL_NO_EC
1324 static int check_suiteb_cipher_list(const SSL_METHOD *meth, CERT *c,
1325                                     const char **prule_str)
1326 {
1327     unsigned int suiteb_flags = 0, suiteb_comb2 = 0;
1328     if (strcmp(*prule_str, "SUITEB128") == 0)
1329         suiteb_flags = SSL_CERT_FLAG_SUITEB_128_LOS;
1330     else if (strcmp(*prule_str, "SUITEB128ONLY") == 0)
1331         suiteb_flags = SSL_CERT_FLAG_SUITEB_128_LOS_ONLY;
1332     else if (strcmp(*prule_str, "SUITEB128C2") == 0) {
1333         suiteb_comb2 = 1;
1334         suiteb_flags = SSL_CERT_FLAG_SUITEB_128_LOS;
1335     } else if (strcmp(*prule_str, "SUITEB192") == 0)
1336         suiteb_flags = SSL_CERT_FLAG_SUITEB_192_LOS;
1337
1338     if (suiteb_flags) {
1339         c->cert_flags &= ~SSL_CERT_FLAG_SUITEB_128_LOS;
1340         c->cert_flags |= suiteb_flags;
1341     } else
1342         suiteb_flags = c->cert_flags & SSL_CERT_FLAG_SUITEB_128_LOS;
1343
1344     if (!suiteb_flags)
1345         return 1;
1346     /* Check version: if TLS 1.2 ciphers allowed we can use Suite B */
1347
1348     if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_TLS1_2_CIPHERS)) {
1349         if (meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS)
1350             SSLerr(SSL_F_CHECK_SUITEB_CIPHER_LIST,
1351                    SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1352         else
1353             SSLerr(SSL_F_CHECK_SUITEB_CIPHER_LIST,
1354                    SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
1355         return 0;
1356     }
1357 # ifndef OPENSSL_NO_EC
1358     switch (suiteb_flags) {
1359     case SSL_CERT_FLAG_SUITEB_128_LOS:
1360         if (suiteb_comb2)
1361             *prule_str = "ECDHE-ECDSA-AES256-GCM-SHA384";
1362         else
1363             *prule_str =
1364                 "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384";
1365         break;
1366     case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
1367         *prule_str = "ECDHE-ECDSA-AES128-GCM-SHA256";
1368         break;
1369     case SSL_CERT_FLAG_SUITEB_192_LOS:
1370         *prule_str = "ECDHE-ECDSA-AES256-GCM-SHA384";
1371         break;
1372     }
1373     /* Set auto ECDH parameter determination */
1374     c->ecdh_tmp_auto = 1;
1375     return 1;
1376 # else
1377     SSLerr(SSL_F_CHECK_SUITEB_CIPHER_LIST,
1378            SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE);
1379     return 0;
1380 # endif
1381 }
1382 #endif
1383
1384 STACK_OF(SSL_CIPHER) *ssl_create_cipher_list(const SSL_METHOD *ssl_method, STACK_OF(SSL_CIPHER)
1385                                              **cipher_list, STACK_OF(SSL_CIPHER)
1386                                              **cipher_list_by_id,
1387                                              const char *rule_str, CERT *c)
1388 {
1389     int ok, num_of_ciphers, num_of_alias_max, num_of_group_aliases;
1390     unsigned long disabled_mkey, disabled_auth, disabled_enc, disabled_mac,
1391         disabled_ssl;
1392     STACK_OF(SSL_CIPHER) *cipherstack, *tmp_cipher_list;
1393     const char *rule_p;
1394     CIPHER_ORDER *co_list = NULL, *head = NULL, *tail = NULL, *curr;
1395     const SSL_CIPHER **ca_list = NULL;
1396
1397     /*
1398      * Return with error if nothing to do.
1399      */
1400     if (rule_str == NULL || cipher_list == NULL || cipher_list_by_id == NULL)
1401         return NULL;
1402 #ifndef OPENSSL_NO_EC
1403     if (!check_suiteb_cipher_list(ssl_method, c, &rule_str))
1404         return NULL;
1405 #endif
1406
1407     /*
1408      * To reduce the work to do we only want to process the compiled
1409      * in algorithms, so we first get the mask of disabled ciphers.
1410      */
1411
1412     disabled_mkey = disabled_mkey_mask;
1413     disabled_auth = disabled_auth_mask;
1414     disabled_enc = disabled_enc_mask;
1415     disabled_mac = disabled_mac_mask;
1416     disabled_ssl = 0;
1417
1418     /*
1419      * Now we have to collect the available ciphers from the compiled
1420      * in ciphers. We cannot get more than the number compiled in, so
1421      * it is used for allocation.
1422      */
1423     num_of_ciphers = ssl_method->num_ciphers();
1424
1425     co_list = OPENSSL_malloc(sizeof(*co_list) * num_of_ciphers);
1426     if (co_list == NULL) {
1427         SSLerr(SSL_F_SSL_CREATE_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
1428         return (NULL);          /* Failure */
1429     }
1430
1431     ssl_cipher_collect_ciphers(ssl_method, num_of_ciphers,
1432                                disabled_mkey, disabled_auth, disabled_enc,
1433                                disabled_mac, disabled_ssl, co_list, &head,
1434                                &tail);
1435
1436     /* Now arrange all ciphers by preference: */
1437
1438     /*
1439      * Everything else being equal, prefer ephemeral ECDH over other key
1440      * exchange mechanisms
1441      */
1442     ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head,
1443                           &tail);
1444     ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head,
1445                           &tail);
1446
1447     /* AES is our preferred symmetric cipher */
1448     ssl_cipher_apply_rule(0, 0, 0, SSL_AES, 0, 0, 0, CIPHER_ADD, -1, &head,
1449                           &tail);
1450
1451     /* Temporarily enable everything else for sorting */
1452     ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail);
1453
1454     /* Low priority for MD5 */
1455     ssl_cipher_apply_rule(0, 0, 0, 0, SSL_MD5, 0, 0, CIPHER_ORD, -1, &head,
1456                           &tail);
1457
1458     /*
1459      * Move anonymous ciphers to the end.  Usually, these will remain
1460      * disabled. (For applications that allow them, they aren't too bad, but
1461      * we prefer authenticated ciphers.)
1462      */
1463     ssl_cipher_apply_rule(0, 0, SSL_aNULL, 0, 0, 0, 0, CIPHER_ORD, -1, &head,
1464                           &tail);
1465
1466     /* Move ciphers without forward secrecy to the end */
1467     ssl_cipher_apply_rule(0, 0, SSL_aECDH, 0, 0, 0, 0, CIPHER_ORD, -1, &head,
1468                           &tail);
1469     /*
1470      * ssl_cipher_apply_rule(0, 0, SSL_aDH, 0, 0, 0, 0, CIPHER_ORD, -1,
1471      * &head, &tail);
1472      */
1473     ssl_cipher_apply_rule(0, SSL_kRSA, 0, 0, 0, 0, 0, CIPHER_ORD, -1, &head,
1474                           &tail);
1475     ssl_cipher_apply_rule(0, SSL_kPSK, 0, 0, 0, 0, 0, CIPHER_ORD, -1, &head,
1476                           &tail);
1477
1478     /* RC4 is sort-of broken -- move the the end */
1479     ssl_cipher_apply_rule(0, 0, 0, SSL_RC4, 0, 0, 0, CIPHER_ORD, -1, &head,
1480                           &tail);
1481
1482     /*
1483      * Now sort by symmetric encryption strength.  The above ordering remains
1484      * in force within each class
1485      */
1486     if (!ssl_cipher_strength_sort(&head, &tail)) {
1487         OPENSSL_free(co_list);
1488         return NULL;
1489     }
1490
1491     /* Now disable everything (maintaining the ordering!) */
1492     ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail);
1493
1494     /*
1495      * We also need cipher aliases for selecting based on the rule_str.
1496      * There might be two types of entries in the rule_str: 1) names
1497      * of ciphers themselves 2) aliases for groups of ciphers.
1498      * For 1) we need the available ciphers and for 2) the cipher
1499      * groups of cipher_aliases added together in one list (otherwise
1500      * we would be happy with just the cipher_aliases table).
1501      */
1502     num_of_group_aliases = OSSL_NELEM(cipher_aliases);
1503     num_of_alias_max = num_of_ciphers + num_of_group_aliases + 1;
1504     ca_list = OPENSSL_malloc(sizeof(*ca_list) * num_of_alias_max);
1505     if (ca_list == NULL) {
1506         OPENSSL_free(co_list);
1507         SSLerr(SSL_F_SSL_CREATE_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
1508         return (NULL);          /* Failure */
1509     }
1510     ssl_cipher_collect_aliases(ca_list, num_of_group_aliases,
1511                                disabled_mkey, disabled_auth, disabled_enc,
1512                                disabled_mac, disabled_ssl, head);
1513
1514     /*
1515      * If the rule_string begins with DEFAULT, apply the default rule
1516      * before using the (possibly available) additional rules.
1517      */
1518     ok = 1;
1519     rule_p = rule_str;
1520     if (strncmp(rule_str, "DEFAULT", 7) == 0) {
1521         ok = ssl_cipher_process_rulestr(SSL_DEFAULT_CIPHER_LIST,
1522                                         &head, &tail, ca_list, c);
1523         rule_p += 7;
1524         if (*rule_p == ':')
1525             rule_p++;
1526     }
1527
1528     if (ok && (strlen(rule_p) > 0))
1529         ok = ssl_cipher_process_rulestr(rule_p, &head, &tail, ca_list, c);
1530
1531     OPENSSL_free(ca_list); /* Not needed anymore */
1532
1533     if (!ok) {                  /* Rule processing failure */
1534         OPENSSL_free(co_list);
1535         return (NULL);
1536     }
1537
1538     /*
1539      * Allocate new "cipherstack" for the result, return with error
1540      * if we cannot get one.
1541      */
1542     if ((cipherstack = sk_SSL_CIPHER_new_null()) == NULL) {
1543         OPENSSL_free(co_list);
1544         return (NULL);
1545     }
1546
1547     /*
1548      * The cipher selection for the list is done. The ciphers are added
1549      * to the resulting precedence to the STACK_OF(SSL_CIPHER).
1550      */
1551     for (curr = head; curr != NULL; curr = curr->next) {
1552         if (curr->active
1553             && (!FIPS_mode() || curr->cipher->algo_strength & SSL_FIPS)) {
1554             if (!sk_SSL_CIPHER_push(cipherstack, curr->cipher)) {
1555                 OPENSSL_free(co_list);
1556                 sk_SSL_CIPHER_free(cipherstack);
1557                 return NULL;
1558             }
1559 #ifdef CIPHER_DEBUG
1560             fprintf(stderr, "<%s>\n", curr->cipher->name);
1561 #endif
1562         }
1563     }
1564     OPENSSL_free(co_list);      /* Not needed any longer */
1565
1566     tmp_cipher_list = sk_SSL_CIPHER_dup(cipherstack);
1567     if (tmp_cipher_list == NULL) {
1568         sk_SSL_CIPHER_free(cipherstack);
1569         return NULL;
1570     }
1571     sk_SSL_CIPHER_free(*cipher_list);
1572     *cipher_list = cipherstack;
1573     if (*cipher_list_by_id != NULL)
1574         sk_SSL_CIPHER_free(*cipher_list_by_id);
1575     *cipher_list_by_id = tmp_cipher_list;
1576     (void)sk_SSL_CIPHER_set_cmp_func(*cipher_list_by_id,
1577                                      ssl_cipher_ptr_id_cmp);
1578
1579     sk_SSL_CIPHER_sort(*cipher_list_by_id);
1580     return (cipherstack);
1581 }
1582
1583 char *SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int len)
1584 {
1585     int is_export, pkl, kl;
1586     const char *ver, *exp_str;
1587     const char *kx, *au, *enc, *mac;
1588     unsigned long alg_mkey, alg_auth, alg_enc, alg_mac, alg_ssl;
1589     static const char *format =
1590         "%-23s %s Kx=%-8s Au=%-4s Enc=%-9s Mac=%-4s%s\n";
1591
1592     alg_mkey = cipher->algorithm_mkey;
1593     alg_auth = cipher->algorithm_auth;
1594     alg_enc = cipher->algorithm_enc;
1595     alg_mac = cipher->algorithm_mac;
1596     alg_ssl = cipher->algorithm_ssl;
1597
1598     is_export = SSL_C_IS_EXPORT(cipher);
1599     pkl = SSL_C_EXPORT_PKEYLENGTH(cipher);
1600     kl = SSL_C_EXPORT_KEYLENGTH(cipher);
1601     exp_str = is_export ? " export" : "";
1602
1603     if (alg_ssl & SSL_SSLV3)
1604         ver = "SSLv3";
1605     else if (alg_ssl & SSL_TLSV1_2)
1606         ver = "TLSv1.2";
1607     else
1608         ver = "unknown";
1609
1610     switch (alg_mkey) {
1611     case SSL_kRSA:
1612         kx = is_export ? (pkl == 512 ? "RSA(512)" : "RSA(1024)") : "RSA";
1613         break;
1614     case SSL_kDHr:
1615         kx = "DH/RSA";
1616         break;
1617     case SSL_kDHd:
1618         kx = "DH/DSS";
1619         break;
1620     case SSL_kDHE:
1621         kx = is_export ? (pkl == 512 ? "DH(512)" : "DH(1024)") : "DH";
1622         break;
1623     case SSL_kECDHr:
1624         kx = "ECDH/RSA";
1625         break;
1626     case SSL_kECDHe:
1627         kx = "ECDH/ECDSA";
1628         break;
1629     case SSL_kECDHE:
1630         kx = "ECDH";
1631         break;
1632     case SSL_kPSK:
1633         kx = "PSK";
1634         break;
1635     case SSL_kRSAPSK:
1636         kx = "RSAPSK";
1637         break;
1638     case SSL_kECDHEPSK:
1639         kx = "ECDHEPSK";
1640         break;
1641     case SSL_kDHEPSK:
1642         kx = "DHEPSK";
1643         break;
1644     case SSL_kSRP:
1645         kx = "SRP";
1646         break;
1647     case SSL_kGOST:
1648         kx = "GOST";
1649         break;
1650     default:
1651         kx = "unknown";
1652     }
1653
1654     switch (alg_auth) {
1655     case SSL_aRSA:
1656         au = "RSA";
1657         break;
1658     case SSL_aDSS:
1659         au = "DSS";
1660         break;
1661     case SSL_aDH:
1662         au = "DH";
1663         break;
1664     case SSL_aECDH:
1665         au = "ECDH";
1666         break;
1667     case SSL_aNULL:
1668         au = "None";
1669         break;
1670     case SSL_aECDSA:
1671         au = "ECDSA";
1672         break;
1673     case SSL_aPSK:
1674         au = "PSK";
1675         break;
1676     case SSL_aSRP:
1677         au = "SRP";
1678         break;
1679     case SSL_aGOST01:
1680         au = "GOST01";
1681         break;
1682     default:
1683         au = "unknown";
1684         break;
1685     }
1686
1687     switch (alg_enc) {
1688     case SSL_DES:
1689         enc = (is_export && kl == 5) ? "DES(40)" : "DES(56)";
1690         break;
1691     case SSL_3DES:
1692         enc = "3DES(168)";
1693         break;
1694     case SSL_RC4:
1695         enc = is_export ? (kl == 5 ? "RC4(40)" : "RC4(56)") : "RC4(128)";
1696         break;
1697     case SSL_RC2:
1698         enc = is_export ? (kl == 5 ? "RC2(40)" : "RC2(56)") : "RC2(128)";
1699         break;
1700     case SSL_IDEA:
1701         enc = "IDEA(128)";
1702         break;
1703     case SSL_eNULL:
1704         enc = "None";
1705         break;
1706     case SSL_AES128:
1707         enc = "AES(128)";
1708         break;
1709     case SSL_AES256:
1710         enc = "AES(256)";
1711         break;
1712     case SSL_AES128GCM:
1713         enc = "AESGCM(128)";
1714         break;
1715     case SSL_AES256GCM:
1716         enc = "AESGCM(256)";
1717         break;
1718     case SSL_AES128CCM:
1719         enc = "AESCCM(128)";
1720         break;
1721     case SSL_AES256CCM:
1722         enc = "AESCCM(256)";
1723         break;
1724     case SSL_CAMELLIA128:
1725         enc = "Camellia(128)";
1726         break;
1727     case SSL_CAMELLIA256:
1728         enc = "Camellia(256)";
1729         break;
1730     case SSL_SEED:
1731         enc = "SEED(128)";
1732         break;
1733     case SSL_eGOST2814789CNT:
1734         enc = "GOST89(256)";
1735         break;
1736     default:
1737         enc = "unknown";
1738         break;
1739     }
1740
1741     switch (alg_mac) {
1742     case SSL_MD5:
1743         mac = "MD5";
1744         break;
1745     case SSL_SHA1:
1746         mac = "SHA1";
1747         break;
1748     case SSL_SHA256:
1749         mac = "SHA256";
1750         break;
1751     case SSL_SHA384:
1752         mac = "SHA384";
1753         break;
1754     case SSL_AEAD:
1755         mac = "AEAD";
1756         break;
1757     case SSL_GOST89MAC:
1758         mac = "GOST89";
1759         break;
1760     case SSL_GOST94:
1761         mac = "GOST94";
1762         break;
1763     default:
1764         mac = "unknown";
1765         break;
1766     }
1767
1768     if (buf == NULL) {
1769         len = 128;
1770         buf = OPENSSL_malloc(len);
1771         if (buf == NULL)
1772             return ("OPENSSL_malloc Error");
1773     } else if (len < 128)
1774         return ("Buffer too small");
1775
1776     BIO_snprintf(buf, len, format, cipher->name, ver, kx, au, enc, mac,
1777                  exp_str);
1778
1779     return (buf);
1780 }
1781
1782 char *SSL_CIPHER_get_version(const SSL_CIPHER *c)
1783 {
1784     int i;
1785
1786     if (c == NULL)
1787         return ("(NONE)");
1788     i = (int)(c->id >> 24L);
1789     if (i == 3)
1790         return ("TLSv1/SSLv3");
1791     else
1792         return ("unknown");
1793 }
1794
1795 /* return the actual cipher being used */
1796 const char *SSL_CIPHER_get_name(const SSL_CIPHER *c)
1797 {
1798     if (c != NULL)
1799         return (c->name);
1800     return ("(NONE)");
1801 }
1802
1803 /* number of bits for symmetric cipher */
1804 int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits)
1805 {
1806     int ret = 0;
1807
1808     if (c != NULL) {
1809         if (alg_bits != NULL)
1810             *alg_bits = c->alg_bits;
1811         ret = c->strength_bits;
1812     }
1813     return (ret);
1814 }
1815
1816 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER *c)
1817 {
1818     return c->id;
1819 }
1820
1821 SSL_COMP *ssl3_comp_find(STACK_OF(SSL_COMP) *sk, int n)
1822 {
1823     SSL_COMP *ctmp;
1824     int i, nn;
1825
1826     if ((n == 0) || (sk == NULL))
1827         return (NULL);
1828     nn = sk_SSL_COMP_num(sk);
1829     for (i = 0; i < nn; i++) {
1830         ctmp = sk_SSL_COMP_value(sk, i);
1831         if (ctmp->id == n)
1832             return (ctmp);
1833     }
1834     return (NULL);
1835 }
1836
1837 #ifdef OPENSSL_NO_COMP
1838 STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void)
1839 {
1840     return NULL;
1841 }
1842 STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP)
1843                                                       *meths)
1844 {
1845     return meths;
1846 }
1847 void SSL_COMP_free_compression_methods(void)
1848 {
1849 }
1850 int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm)
1851 {
1852     return 1;
1853 }
1854
1855 #else
1856 STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void)
1857 {
1858     load_builtin_compressions();
1859     return (ssl_comp_methods);
1860 }
1861
1862 STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP)
1863                                                       *meths)
1864 {
1865     STACK_OF(SSL_COMP) *old_meths = ssl_comp_methods;
1866     ssl_comp_methods = meths;
1867     return old_meths;
1868 }
1869
1870 static void cmeth_free(SSL_COMP *cm)
1871 {
1872     OPENSSL_free(cm);
1873 }
1874
1875 void SSL_COMP_free_compression_methods(void)
1876 {
1877     STACK_OF(SSL_COMP) *old_meths = ssl_comp_methods;
1878     ssl_comp_methods = NULL;
1879     sk_SSL_COMP_pop_free(old_meths, cmeth_free);
1880 }
1881
1882 int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm)
1883 {
1884     SSL_COMP *comp;
1885
1886     if (cm == NULL || COMP_get_type(cm) == NID_undef)
1887         return 1;
1888
1889     /*-
1890      * According to draft-ietf-tls-compression-04.txt, the
1891      * compression number ranges should be the following:
1892      *
1893      *   0 to  63:  methods defined by the IETF
1894      *  64 to 192:  external party methods assigned by IANA
1895      * 193 to 255:  reserved for private use
1896      */
1897     if (id < 193 || id > 255) {
1898         SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD,
1899                SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE);
1900         return 0;
1901     }
1902
1903     MemCheck_off();
1904     comp = OPENSSL_malloc(sizeof(*comp));
1905     if (comp == NULL) {
1906         MemCheck_on();
1907         SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD, ERR_R_MALLOC_FAILURE);
1908         return (1);
1909     }
1910
1911     comp->id = id;
1912     comp->method = cm;
1913     load_builtin_compressions();
1914     if (ssl_comp_methods && sk_SSL_COMP_find(ssl_comp_methods, comp) >= 0) {
1915         OPENSSL_free(comp);
1916         MemCheck_on();
1917         SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD,
1918                SSL_R_DUPLICATE_COMPRESSION_ID);
1919         return (1);
1920     } else if ((ssl_comp_methods == NULL)
1921                || !sk_SSL_COMP_push(ssl_comp_methods, comp)) {
1922         OPENSSL_free(comp);
1923         MemCheck_on();
1924         SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD, ERR_R_MALLOC_FAILURE);
1925         return (1);
1926     } else {
1927         MemCheck_on();
1928         return (0);
1929     }
1930 }
1931 #endif
1932
1933 const char *SSL_COMP_get_name(const COMP_METHOD *comp)
1934 {
1935 #ifndef OPENSSL_NO_COMP
1936     return comp ? COMP_get_name(comp) : NULL;
1937 #else
1938     return NULL;
1939 #endif
1940 }
1941
1942 /* For a cipher return the index corresponding to the certificate type */
1943 int ssl_cipher_get_cert_index(const SSL_CIPHER *c)
1944 {
1945     unsigned long alg_k, alg_a;
1946
1947     alg_k = c->algorithm_mkey;
1948     alg_a = c->algorithm_auth;
1949
1950     if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
1951         /*
1952          * we don't need to look at SSL_kECDHE since no certificate is needed
1953          * for anon ECDH and for authenticated ECDHE, the check for the auth
1954          * algorithm will set i correctly NOTE: For ECDH-RSA, we need an ECC
1955          * not an RSA cert but for ECDHE-RSA we need an RSA cert. Placing the
1956          * checks for SSL_kECDH before RSA checks ensures the correct cert is
1957          * chosen.
1958          */
1959         return SSL_PKEY_ECC;
1960     } else if (alg_a & SSL_aECDSA)
1961         return SSL_PKEY_ECC;
1962     else if (alg_k & SSL_kDHr)
1963         return SSL_PKEY_DH_RSA;
1964     else if (alg_k & SSL_kDHd)
1965         return SSL_PKEY_DH_DSA;
1966     else if (alg_a & SSL_aDSS)
1967         return SSL_PKEY_DSA_SIGN;
1968     else if (alg_a & SSL_aRSA)
1969         return SSL_PKEY_RSA_ENC;
1970     else if (alg_a & SSL_aGOST01)
1971         return SSL_PKEY_GOST01;
1972     return -1;
1973 }
1974
1975 const SSL_CIPHER *ssl_get_cipher_by_char(SSL *ssl, const unsigned char *ptr)
1976 {
1977     const SSL_CIPHER *c;
1978     c = ssl->method->get_cipher_by_char(ptr);
1979     if (c == NULL || c->valid == 0)
1980         return NULL;
1981     return c;
1982 }
1983
1984 const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr)
1985 {
1986     return ssl->method->get_cipher_by_char(ptr);
1987 }
1988
1989 int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c)
1990 {
1991     int i;
1992     if (c == NULL)
1993         return -1;
1994     i = ssl_cipher_info_lookup(ssl_cipher_table_cipher, c->algorithm_enc);
1995     if (i == -1)
1996         return -1;
1997     return ssl_cipher_table_cipher[i].nid;
1998 }
1999
2000 int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c)
2001 {
2002     int i;
2003     if (c == NULL)
2004         return -1;
2005     i = ssl_cipher_info_lookup(ssl_cipher_table_mac, c->algorithm_mac);
2006     if (i == -1)
2007         return -1;
2008     return ssl_cipher_table_mac[i].nid;
2009 }