xref: /freebsd/crypto/openssl/ssl/t1_lib.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*
2  * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <openssl/objects.h>
13 #include <openssl/evp.h>
14 #include <openssl/hmac.h>
15 #include <openssl/core_names.h>
16 #include <openssl/ocsp.h>
17 #include <openssl/conf.h>
18 #include <openssl/x509v3.h>
19 #include <openssl/dh.h>
20 #include <openssl/bn.h>
21 #include <openssl/provider.h>
22 #include <openssl/param_build.h>
23 #include "internal/nelem.h"
24 #include "internal/sizes.h"
25 #include "internal/tlsgroups.h"
26 #include "internal/cryptlib.h"
27 #include "ssl_local.h"
28 #include <openssl/ct.h>
29 
30 static const SIGALG_LOOKUP *find_sig_alg(SSL *s, X509 *x, EVP_PKEY *pkey);
31 static int tls12_sigalg_allowed(const SSL *s, int op, const SIGALG_LOOKUP *lu);
32 
33 SSL3_ENC_METHOD const TLSv1_enc_data = {
34     tls1_enc,
35     tls1_mac,
36     tls1_setup_key_block,
37     tls1_generate_master_secret,
38     tls1_change_cipher_state,
39     tls1_final_finish_mac,
40     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
41     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
42     tls1_alert_code,
43     tls1_export_keying_material,
44     0,
45     ssl3_set_handshake_header,
46     tls_close_construct_packet,
47     ssl3_handshake_write
48 };
49 
50 SSL3_ENC_METHOD const TLSv1_1_enc_data = {
51     tls1_enc,
52     tls1_mac,
53     tls1_setup_key_block,
54     tls1_generate_master_secret,
55     tls1_change_cipher_state,
56     tls1_final_finish_mac,
57     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
58     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
59     tls1_alert_code,
60     tls1_export_keying_material,
61     SSL_ENC_FLAG_EXPLICIT_IV,
62     ssl3_set_handshake_header,
63     tls_close_construct_packet,
64     ssl3_handshake_write
65 };
66 
67 SSL3_ENC_METHOD const TLSv1_2_enc_data = {
68     tls1_enc,
69     tls1_mac,
70     tls1_setup_key_block,
71     tls1_generate_master_secret,
72     tls1_change_cipher_state,
73     tls1_final_finish_mac,
74     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
75     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
76     tls1_alert_code,
77     tls1_export_keying_material,
78     SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
79         | SSL_ENC_FLAG_TLS1_2_CIPHERS,
80     ssl3_set_handshake_header,
81     tls_close_construct_packet,
82     ssl3_handshake_write
83 };
84 
85 SSL3_ENC_METHOD const TLSv1_3_enc_data = {
86     tls13_enc,
87     tls1_mac,
88     tls13_setup_key_block,
89     tls13_generate_master_secret,
90     tls13_change_cipher_state,
91     tls13_final_finish_mac,
92     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
93     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
94     tls13_alert_code,
95     tls13_export_keying_material,
96     SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF,
97     ssl3_set_handshake_header,
98     tls_close_construct_packet,
99     ssl3_handshake_write
100 };
101 
102 long tls1_default_timeout(void)
103 {
104     /*
105      * 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
106      * http, the cache would over fill
107      */
108     return (60 * 60 * 2);
109 }
110 
111 int tls1_new(SSL *s)
112 {
113     if (!ssl3_new(s))
114         return 0;
115     if (!s->method->ssl_clear(s))
116         return 0;
117 
118     return 1;
119 }
120 
121 void tls1_free(SSL *s)
122 {
123     OPENSSL_free(s->ext.session_ticket);
124     ssl3_free(s);
125 }
126 
127 int tls1_clear(SSL *s)
128 {
129     if (!ssl3_clear(s))
130         return 0;
131 
132     if (s->method->version == TLS_ANY_VERSION)
133         s->version = TLS_MAX_VERSION_INTERNAL;
134     else
135         s->version = s->method->version;
136 
137     return 1;
138 }
139 
140 /* Legacy NID to group_id mapping. Only works for groups we know about */
141 static struct {
142     int nid;
143     uint16_t group_id;
144 } nid_to_group[] = {
145     {NID_sect163k1, OSSL_TLS_GROUP_ID_sect163k1},
146     {NID_sect163r1, OSSL_TLS_GROUP_ID_sect163r1},
147     {NID_sect163r2, OSSL_TLS_GROUP_ID_sect163r2},
148     {NID_sect193r1, OSSL_TLS_GROUP_ID_sect193r1},
149     {NID_sect193r2, OSSL_TLS_GROUP_ID_sect193r2},
150     {NID_sect233k1, OSSL_TLS_GROUP_ID_sect233k1},
151     {NID_sect233r1, OSSL_TLS_GROUP_ID_sect233r1},
152     {NID_sect239k1, OSSL_TLS_GROUP_ID_sect239k1},
153     {NID_sect283k1, OSSL_TLS_GROUP_ID_sect283k1},
154     {NID_sect283r1, OSSL_TLS_GROUP_ID_sect283r1},
155     {NID_sect409k1, OSSL_TLS_GROUP_ID_sect409k1},
156     {NID_sect409r1, OSSL_TLS_GROUP_ID_sect409r1},
157     {NID_sect571k1, OSSL_TLS_GROUP_ID_sect571k1},
158     {NID_sect571r1, OSSL_TLS_GROUP_ID_sect571r1},
159     {NID_secp160k1, OSSL_TLS_GROUP_ID_secp160k1},
160     {NID_secp160r1, OSSL_TLS_GROUP_ID_secp160r1},
161     {NID_secp160r2, OSSL_TLS_GROUP_ID_secp160r2},
162     {NID_secp192k1, OSSL_TLS_GROUP_ID_secp192k1},
163     {NID_X9_62_prime192v1, OSSL_TLS_GROUP_ID_secp192r1},
164     {NID_secp224k1, OSSL_TLS_GROUP_ID_secp224k1},
165     {NID_secp224r1, OSSL_TLS_GROUP_ID_secp224r1},
166     {NID_secp256k1, OSSL_TLS_GROUP_ID_secp256k1},
167     {NID_X9_62_prime256v1, OSSL_TLS_GROUP_ID_secp256r1},
168     {NID_secp384r1, OSSL_TLS_GROUP_ID_secp384r1},
169     {NID_secp521r1, OSSL_TLS_GROUP_ID_secp521r1},
170     {NID_brainpoolP256r1, OSSL_TLS_GROUP_ID_brainpoolP256r1},
171     {NID_brainpoolP384r1, OSSL_TLS_GROUP_ID_brainpoolP384r1},
172     {NID_brainpoolP512r1, OSSL_TLS_GROUP_ID_brainpoolP512r1},
173     {EVP_PKEY_X25519, OSSL_TLS_GROUP_ID_x25519},
174     {EVP_PKEY_X448, OSSL_TLS_GROUP_ID_x448},
175     {NID_id_tc26_gost_3410_2012_256_paramSetA, 0x0022},
176     {NID_id_tc26_gost_3410_2012_256_paramSetB, 0x0023},
177     {NID_id_tc26_gost_3410_2012_256_paramSetC, 0x0024},
178     {NID_id_tc26_gost_3410_2012_256_paramSetD, 0x0025},
179     {NID_id_tc26_gost_3410_2012_512_paramSetA, 0x0026},
180     {NID_id_tc26_gost_3410_2012_512_paramSetB, 0x0027},
181     {NID_id_tc26_gost_3410_2012_512_paramSetC, 0x0028},
182     {NID_ffdhe2048, OSSL_TLS_GROUP_ID_ffdhe2048},
183     {NID_ffdhe3072, OSSL_TLS_GROUP_ID_ffdhe3072},
184     {NID_ffdhe4096, OSSL_TLS_GROUP_ID_ffdhe4096},
185     {NID_ffdhe6144, OSSL_TLS_GROUP_ID_ffdhe6144},
186     {NID_ffdhe8192, OSSL_TLS_GROUP_ID_ffdhe8192}
187 };
188 
189 static const unsigned char ecformats_default[] = {
190     TLSEXT_ECPOINTFORMAT_uncompressed,
191     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
192     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
193 };
194 
195 /* The default curves */
196 static const uint16_t supported_groups_default[] = {
197     29,                      /* X25519 (29) */
198     23,                      /* secp256r1 (23) */
199     30,                      /* X448 (30) */
200     25,                      /* secp521r1 (25) */
201     24,                      /* secp384r1 (24) */
202     34,                      /* GC256A (34) */
203     35,                      /* GC256B (35) */
204     36,                      /* GC256C (36) */
205     37,                      /* GC256D (37) */
206     38,                      /* GC512A (38) */
207     39,                      /* GC512B (39) */
208     40,                      /* GC512C (40) */
209     0x100,                   /* ffdhe2048 (0x100) */
210     0x101,                   /* ffdhe3072 (0x101) */
211     0x102,                   /* ffdhe4096 (0x102) */
212     0x103,                   /* ffdhe6144 (0x103) */
213     0x104,                   /* ffdhe8192 (0x104) */
214 };
215 
216 static const uint16_t suiteb_curves[] = {
217     TLSEXT_curve_P_256,
218     TLSEXT_curve_P_384
219 };
220 
221 struct provider_group_data_st {
222     SSL_CTX *ctx;
223     OSSL_PROVIDER *provider;
224 };
225 
226 #define TLS_GROUP_LIST_MALLOC_BLOCK_SIZE        10
227 static OSSL_CALLBACK add_provider_groups;
228 static int add_provider_groups(const OSSL_PARAM params[], void *data)
229 {
230     struct provider_group_data_st *pgd = data;
231     SSL_CTX *ctx = pgd->ctx;
232     OSSL_PROVIDER *provider = pgd->provider;
233     const OSSL_PARAM *p;
234     TLS_GROUP_INFO *ginf = NULL;
235     EVP_KEYMGMT *keymgmt;
236     unsigned int gid;
237     unsigned int is_kem = 0;
238     int ret = 0;
239 
240     if (ctx->group_list_max_len == ctx->group_list_len) {
241         TLS_GROUP_INFO *tmp = NULL;
242 
243         if (ctx->group_list_max_len == 0)
244             tmp = OPENSSL_malloc(sizeof(TLS_GROUP_INFO)
245                                  * TLS_GROUP_LIST_MALLOC_BLOCK_SIZE);
246         else
247             tmp = OPENSSL_realloc(ctx->group_list,
248                                   (ctx->group_list_max_len
249                                    + TLS_GROUP_LIST_MALLOC_BLOCK_SIZE)
250                                   * sizeof(TLS_GROUP_INFO));
251         if (tmp == NULL) {
252             ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
253             return 0;
254         }
255         ctx->group_list = tmp;
256         memset(tmp + ctx->group_list_max_len,
257                0,
258                sizeof(TLS_GROUP_INFO) * TLS_GROUP_LIST_MALLOC_BLOCK_SIZE);
259         ctx->group_list_max_len += TLS_GROUP_LIST_MALLOC_BLOCK_SIZE;
260     }
261 
262     ginf = &ctx->group_list[ctx->group_list_len];
263 
264     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_NAME);
265     if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) {
266         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
267         goto err;
268     }
269     ginf->tlsname = OPENSSL_strdup(p->data);
270     if (ginf->tlsname == NULL) {
271         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
272         goto err;
273     }
274 
275     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_NAME_INTERNAL);
276     if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) {
277         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
278         goto err;
279     }
280     ginf->realname = OPENSSL_strdup(p->data);
281     if (ginf->realname == NULL) {
282         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
283         goto err;
284     }
285 
286     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_ID);
287     if (p == NULL || !OSSL_PARAM_get_uint(p, &gid) || gid > UINT16_MAX) {
288         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
289         goto err;
290     }
291     ginf->group_id = (uint16_t)gid;
292 
293     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_ALG);
294     if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) {
295         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
296         goto err;
297     }
298     ginf->algorithm = OPENSSL_strdup(p->data);
299     if (ginf->algorithm == NULL) {
300         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
301         goto err;
302     }
303 
304     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_SECURITY_BITS);
305     if (p == NULL || !OSSL_PARAM_get_uint(p, &ginf->secbits)) {
306         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
307         goto err;
308     }
309 
310     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_IS_KEM);
311     if (p != NULL && (!OSSL_PARAM_get_uint(p, &is_kem) || is_kem > 1)) {
312         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
313         goto err;
314     }
315     ginf->is_kem = 1 & is_kem;
316 
317     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MIN_TLS);
318     if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->mintls)) {
319         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
320         goto err;
321     }
322 
323     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MAX_TLS);
324     if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->maxtls)) {
325         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
326         goto err;
327     }
328 
329     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MIN_DTLS);
330     if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->mindtls)) {
331         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
332         goto err;
333     }
334 
335     p = OSSL_PARAM_locate_const(params, OSSL_CAPABILITY_TLS_GROUP_MAX_DTLS);
336     if (p == NULL || !OSSL_PARAM_get_int(p, &ginf->maxdtls)) {
337         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
338         goto err;
339     }
340     /*
341      * Now check that the algorithm is actually usable for our property query
342      * string. Regardless of the result we still return success because we have
343      * successfully processed this group, even though we may decide not to use
344      * it.
345      */
346     ret = 1;
347     ERR_set_mark();
348     keymgmt = EVP_KEYMGMT_fetch(ctx->libctx, ginf->algorithm, ctx->propq);
349     if (keymgmt != NULL) {
350         /*
351          * We have successfully fetched the algorithm - however if the provider
352          * doesn't match this one then we ignore it.
353          *
354          * Note: We're cheating a little here. Technically if the same algorithm
355          * is available from more than one provider then it is undefined which
356          * implementation you will get back. Theoretically this could be
357          * different every time...we assume here that you'll always get the
358          * same one back if you repeat the exact same fetch. Is this a reasonable
359          * assumption to make (in which case perhaps we should document this
360          * behaviour)?
361          */
362         if (EVP_KEYMGMT_get0_provider(keymgmt) == provider) {
363             /* We have a match - so we will use this group */
364             ctx->group_list_len++;
365             ginf = NULL;
366         }
367         EVP_KEYMGMT_free(keymgmt);
368     }
369     ERR_pop_to_mark();
370  err:
371     if (ginf != NULL) {
372         OPENSSL_free(ginf->tlsname);
373         OPENSSL_free(ginf->realname);
374         OPENSSL_free(ginf->algorithm);
375         ginf->algorithm = ginf->tlsname = ginf->realname = NULL;
376     }
377     return ret;
378 }
379 
380 static int discover_provider_groups(OSSL_PROVIDER *provider, void *vctx)
381 {
382     struct provider_group_data_st pgd;
383 
384     pgd.ctx = vctx;
385     pgd.provider = provider;
386     return OSSL_PROVIDER_get_capabilities(provider, "TLS-GROUP",
387                                           add_provider_groups, &pgd);
388 }
389 
390 int ssl_load_groups(SSL_CTX *ctx)
391 {
392     size_t i, j, num_deflt_grps = 0;
393     uint16_t tmp_supp_groups[OSSL_NELEM(supported_groups_default)];
394 
395     if (!OSSL_PROVIDER_do_all(ctx->libctx, discover_provider_groups, ctx))
396         return 0;
397 
398     for (i = 0; i < OSSL_NELEM(supported_groups_default); i++) {
399         for (j = 0; j < ctx->group_list_len; j++) {
400             if (ctx->group_list[j].group_id == supported_groups_default[i]) {
401                 tmp_supp_groups[num_deflt_grps++] = ctx->group_list[j].group_id;
402                 break;
403             }
404         }
405     }
406 
407     if (num_deflt_grps == 0)
408         return 1;
409 
410     ctx->ext.supported_groups_default
411         = OPENSSL_malloc(sizeof(uint16_t) * num_deflt_grps);
412 
413     if (ctx->ext.supported_groups_default == NULL) {
414         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
415         return 0;
416     }
417 
418     memcpy(ctx->ext.supported_groups_default,
419            tmp_supp_groups,
420            num_deflt_grps * sizeof(tmp_supp_groups[0]));
421     ctx->ext.supported_groups_default_len = num_deflt_grps;
422 
423     return 1;
424 }
425 
426 static uint16_t tls1_group_name2id(SSL_CTX *ctx, const char *name)
427 {
428     size_t i;
429 
430     for (i = 0; i < ctx->group_list_len; i++) {
431         if (strcmp(ctx->group_list[i].tlsname, name) == 0
432                 || strcmp(ctx->group_list[i].realname, name) == 0)
433             return ctx->group_list[i].group_id;
434     }
435 
436     return 0;
437 }
438 
439 const TLS_GROUP_INFO *tls1_group_id_lookup(SSL_CTX *ctx, uint16_t group_id)
440 {
441     size_t i;
442 
443     for (i = 0; i < ctx->group_list_len; i++) {
444         if (ctx->group_list[i].group_id == group_id)
445             return &ctx->group_list[i];
446     }
447 
448     return NULL;
449 }
450 
451 int tls1_group_id2nid(uint16_t group_id, int include_unknown)
452 {
453     size_t i;
454 
455     if (group_id == 0)
456         return NID_undef;
457 
458     /*
459      * Return well known Group NIDs - for backwards compatibility. This won't
460      * work for groups we don't know about.
461      */
462     for (i = 0; i < OSSL_NELEM(nid_to_group); i++)
463     {
464         if (nid_to_group[i].group_id == group_id)
465             return nid_to_group[i].nid;
466     }
467     if (!include_unknown)
468         return NID_undef;
469     return TLSEXT_nid_unknown | (int)group_id;
470 }
471 
472 uint16_t tls1_nid2group_id(int nid)
473 {
474     size_t i;
475 
476     /*
477      * Return well known Group ids - for backwards compatibility. This won't
478      * work for groups we don't know about.
479      */
480     for (i = 0; i < OSSL_NELEM(nid_to_group); i++)
481     {
482         if (nid_to_group[i].nid == nid)
483             return nid_to_group[i].group_id;
484     }
485 
486     return 0;
487 }
488 
489 /*
490  * Set *pgroups to the supported groups list and *pgroupslen to
491  * the number of groups supported.
492  */
493 void tls1_get_supported_groups(SSL *s, const uint16_t **pgroups,
494                                size_t *pgroupslen)
495 {
496     /* For Suite B mode only include P-256, P-384 */
497     switch (tls1_suiteb(s)) {
498     case SSL_CERT_FLAG_SUITEB_128_LOS:
499         *pgroups = suiteb_curves;
500         *pgroupslen = OSSL_NELEM(suiteb_curves);
501         break;
502 
503     case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
504         *pgroups = suiteb_curves;
505         *pgroupslen = 1;
506         break;
507 
508     case SSL_CERT_FLAG_SUITEB_192_LOS:
509         *pgroups = suiteb_curves + 1;
510         *pgroupslen = 1;
511         break;
512 
513     default:
514         if (s->ext.supportedgroups == NULL) {
515             *pgroups = s->ctx->ext.supported_groups_default;
516             *pgroupslen = s->ctx->ext.supported_groups_default_len;
517         } else {
518             *pgroups = s->ext.supportedgroups;
519             *pgroupslen = s->ext.supportedgroups_len;
520         }
521         break;
522     }
523 }
524 
525 int tls_valid_group(SSL *s, uint16_t group_id, int minversion, int maxversion,
526                     int isec, int *okfortls13)
527 {
528     const TLS_GROUP_INFO *ginfo = tls1_group_id_lookup(s->ctx, group_id);
529     int ret;
530 
531     if (okfortls13 != NULL)
532         *okfortls13 = 0;
533 
534     if (ginfo == NULL)
535         return 0;
536 
537     if (SSL_IS_DTLS(s)) {
538         if (ginfo->mindtls < 0 || ginfo->maxdtls < 0)
539             return 0;
540         if (ginfo->maxdtls == 0)
541             ret = 1;
542         else
543             ret = DTLS_VERSION_LE(minversion, ginfo->maxdtls);
544         if (ginfo->mindtls > 0)
545             ret &= DTLS_VERSION_GE(maxversion, ginfo->mindtls);
546     } else {
547         if (ginfo->mintls < 0 || ginfo->maxtls < 0)
548             return 0;
549         if (ginfo->maxtls == 0)
550             ret = 1;
551         else
552             ret = (minversion <= ginfo->maxtls);
553         if (ginfo->mintls > 0)
554             ret &= (maxversion >= ginfo->mintls);
555         if (ret && okfortls13 != NULL && maxversion == TLS1_3_VERSION)
556             *okfortls13 = (ginfo->maxtls == 0)
557                           || (ginfo->maxtls >= TLS1_3_VERSION);
558     }
559     ret &= !isec
560            || strcmp(ginfo->algorithm, "EC") == 0
561            || strcmp(ginfo->algorithm, "X25519") == 0
562            || strcmp(ginfo->algorithm, "X448") == 0;
563 
564     return ret;
565 }
566 
567 /* See if group is allowed by security callback */
568 int tls_group_allowed(SSL *s, uint16_t group, int op)
569 {
570     const TLS_GROUP_INFO *ginfo = tls1_group_id_lookup(s->ctx, group);
571     unsigned char gtmp[2];
572 
573     if (ginfo == NULL)
574         return 0;
575 
576     gtmp[0] = group >> 8;
577     gtmp[1] = group & 0xff;
578     return ssl_security(s, op, ginfo->secbits,
579                         tls1_group_id2nid(ginfo->group_id, 0), (void *)gtmp);
580 }
581 
582 /* Return 1 if "id" is in "list" */
583 static int tls1_in_list(uint16_t id, const uint16_t *list, size_t listlen)
584 {
585     size_t i;
586     for (i = 0; i < listlen; i++)
587         if (list[i] == id)
588             return 1;
589     return 0;
590 }
591 
592 /*-
593  * For nmatch >= 0, return the id of the |nmatch|th shared group or 0
594  * if there is no match.
595  * For nmatch == -1, return number of matches
596  * For nmatch == -2, return the id of the group to use for
597  * a tmp key, or 0 if there is no match.
598  */
599 uint16_t tls1_shared_group(SSL *s, int nmatch)
600 {
601     const uint16_t *pref, *supp;
602     size_t num_pref, num_supp, i;
603     int k;
604     SSL_CTX *ctx = s->ctx;
605 
606     /* Can't do anything on client side */
607     if (s->server == 0)
608         return 0;
609     if (nmatch == -2) {
610         if (tls1_suiteb(s)) {
611             /*
612              * For Suite B ciphersuite determines curve: we already know
613              * these are acceptable due to previous checks.
614              */
615             unsigned long cid = s->s3.tmp.new_cipher->id;
616 
617             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
618                 return TLSEXT_curve_P_256;
619             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
620                 return TLSEXT_curve_P_384;
621             /* Should never happen */
622             return 0;
623         }
624         /* If not Suite B just return first preference shared curve */
625         nmatch = 0;
626     }
627     /*
628      * If server preference set, our groups are the preference order
629      * otherwise peer decides.
630      */
631     if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
632         tls1_get_supported_groups(s, &pref, &num_pref);
633         tls1_get_peer_groups(s, &supp, &num_supp);
634     } else {
635         tls1_get_peer_groups(s, &pref, &num_pref);
636         tls1_get_supported_groups(s, &supp, &num_supp);
637     }
638 
639     for (k = 0, i = 0; i < num_pref; i++) {
640         uint16_t id = pref[i];
641         const TLS_GROUP_INFO *inf;
642 
643         if (!tls1_in_list(id, supp, num_supp)
644                 || !tls_group_allowed(s, id, SSL_SECOP_CURVE_SHARED))
645             continue;
646         inf = tls1_group_id_lookup(ctx, id);
647         if (!ossl_assert(inf != NULL))
648             return 0;
649         if (SSL_IS_DTLS(s)) {
650             if (inf->maxdtls == -1)
651                 continue;
652             if ((inf->mindtls != 0 && DTLS_VERSION_LT(s->version, inf->mindtls))
653                     || (inf->maxdtls != 0
654                         && DTLS_VERSION_GT(s->version, inf->maxdtls)))
655                 continue;
656         } else {
657             if (inf->maxtls == -1)
658                 continue;
659             if ((inf->mintls != 0 && s->version < inf->mintls)
660                     || (inf->maxtls != 0 && s->version > inf->maxtls))
661                 continue;
662         }
663 
664         if (nmatch == k)
665             return id;
666          k++;
667     }
668     if (nmatch == -1)
669         return k;
670     /* Out of range (nmatch > k). */
671     return 0;
672 }
673 
674 int tls1_set_groups(uint16_t **pext, size_t *pextlen,
675                     int *groups, size_t ngroups)
676 {
677     uint16_t *glist;
678     size_t i;
679     /*
680      * Bitmap of groups included to detect duplicates: two variables are added
681      * to detect duplicates as some values are more than 32.
682      */
683     unsigned long *dup_list = NULL;
684     unsigned long dup_list_egrp = 0;
685     unsigned long dup_list_dhgrp = 0;
686 
687     if (ngroups == 0) {
688         ERR_raise(ERR_LIB_SSL, SSL_R_BAD_LENGTH);
689         return 0;
690     }
691     if ((glist = OPENSSL_malloc(ngroups * sizeof(*glist))) == NULL) {
692         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
693         return 0;
694     }
695     for (i = 0; i < ngroups; i++) {
696         unsigned long idmask;
697         uint16_t id;
698         id = tls1_nid2group_id(groups[i]);
699         if ((id & 0x00FF) >= (sizeof(unsigned long) * 8))
700             goto err;
701         idmask = 1L << (id & 0x00FF);
702         dup_list = (id < 0x100) ? &dup_list_egrp : &dup_list_dhgrp;
703         if (!id || ((*dup_list) & idmask))
704             goto err;
705         *dup_list |= idmask;
706         glist[i] = id;
707     }
708     OPENSSL_free(*pext);
709     *pext = glist;
710     *pextlen = ngroups;
711     return 1;
712 err:
713     OPENSSL_free(glist);
714     return 0;
715 }
716 
717 # define GROUPLIST_INCREMENT   40
718 # define GROUP_NAME_BUFFER_LENGTH 64
719 typedef struct {
720     SSL_CTX *ctx;
721     size_t gidcnt;
722     size_t gidmax;
723     uint16_t *gid_arr;
724 } gid_cb_st;
725 
726 static int gid_cb(const char *elem, int len, void *arg)
727 {
728     gid_cb_st *garg = arg;
729     size_t i;
730     uint16_t gid = 0;
731     char etmp[GROUP_NAME_BUFFER_LENGTH];
732 
733     if (elem == NULL)
734         return 0;
735     if (garg->gidcnt == garg->gidmax) {
736         uint16_t *tmp =
737             OPENSSL_realloc(garg->gid_arr, garg->gidmax + GROUPLIST_INCREMENT);
738         if (tmp == NULL)
739             return 0;
740         garg->gidmax += GROUPLIST_INCREMENT;
741         garg->gid_arr = tmp;
742     }
743     if (len > (int)(sizeof(etmp) - 1))
744         return 0;
745     memcpy(etmp, elem, len);
746     etmp[len] = 0;
747 
748     gid = tls1_group_name2id(garg->ctx, etmp);
749     if (gid == 0) {
750         ERR_raise_data(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT,
751                        "group '%s' cannot be set", etmp);
752         return 0;
753     }
754     for (i = 0; i < garg->gidcnt; i++)
755         if (garg->gid_arr[i] == gid)
756             return 0;
757     garg->gid_arr[garg->gidcnt++] = gid;
758     return 1;
759 }
760 
761 /* Set groups based on a colon separated list */
762 int tls1_set_groups_list(SSL_CTX *ctx, uint16_t **pext, size_t *pextlen,
763                          const char *str)
764 {
765     gid_cb_st gcb;
766     uint16_t *tmparr;
767     int ret = 0;
768 
769     gcb.gidcnt = 0;
770     gcb.gidmax = GROUPLIST_INCREMENT;
771     gcb.gid_arr = OPENSSL_malloc(gcb.gidmax * sizeof(*gcb.gid_arr));
772     if (gcb.gid_arr == NULL)
773         return 0;
774     gcb.ctx = ctx;
775     if (!CONF_parse_list(str, ':', 1, gid_cb, &gcb))
776         goto end;
777     if (pext == NULL) {
778         ret = 1;
779         goto end;
780     }
781 
782     /*
783      * gid_cb ensurse there are no duplicates so we can just go ahead and set
784      * the result
785      */
786     tmparr = OPENSSL_memdup(gcb.gid_arr, gcb.gidcnt * sizeof(*tmparr));
787     if (tmparr == NULL)
788         goto end;
789     OPENSSL_free(*pext);
790     *pext = tmparr;
791     *pextlen = gcb.gidcnt;
792     ret = 1;
793  end:
794     OPENSSL_free(gcb.gid_arr);
795     return ret;
796 }
797 
798 /* Check a group id matches preferences */
799 int tls1_check_group_id(SSL *s, uint16_t group_id, int check_own_groups)
800     {
801     const uint16_t *groups;
802     size_t groups_len;
803 
804     if (group_id == 0)
805         return 0;
806 
807     /* Check for Suite B compliance */
808     if (tls1_suiteb(s) && s->s3.tmp.new_cipher != NULL) {
809         unsigned long cid = s->s3.tmp.new_cipher->id;
810 
811         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
812             if (group_id != TLSEXT_curve_P_256)
813                 return 0;
814         } else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
815             if (group_id != TLSEXT_curve_P_384)
816                 return 0;
817         } else {
818             /* Should never happen */
819             return 0;
820         }
821     }
822 
823     if (check_own_groups) {
824         /* Check group is one of our preferences */
825         tls1_get_supported_groups(s, &groups, &groups_len);
826         if (!tls1_in_list(group_id, groups, groups_len))
827             return 0;
828     }
829 
830     if (!tls_group_allowed(s, group_id, SSL_SECOP_CURVE_CHECK))
831         return 0;
832 
833     /* For clients, nothing more to check */
834     if (!s->server)
835         return 1;
836 
837     /* Check group is one of peers preferences */
838     tls1_get_peer_groups(s, &groups, &groups_len);
839 
840     /*
841      * RFC 4492 does not require the supported elliptic curves extension
842      * so if it is not sent we can just choose any curve.
843      * It is invalid to send an empty list in the supported groups
844      * extension, so groups_len == 0 always means no extension.
845      */
846     if (groups_len == 0)
847             return 1;
848     return tls1_in_list(group_id, groups, groups_len);
849 }
850 
851 void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
852                          size_t *num_formats)
853 {
854     /*
855      * If we have a custom point format list use it otherwise use default
856      */
857     if (s->ext.ecpointformats) {
858         *pformats = s->ext.ecpointformats;
859         *num_formats = s->ext.ecpointformats_len;
860     } else {
861         *pformats = ecformats_default;
862         /* For Suite B we don't support char2 fields */
863         if (tls1_suiteb(s))
864             *num_formats = sizeof(ecformats_default) - 1;
865         else
866             *num_formats = sizeof(ecformats_default);
867     }
868 }
869 
870 /* Check a key is compatible with compression extension */
871 static int tls1_check_pkey_comp(SSL *s, EVP_PKEY *pkey)
872 {
873     unsigned char comp_id;
874     size_t i;
875     int point_conv;
876 
877     /* If not an EC key nothing to check */
878     if (!EVP_PKEY_is_a(pkey, "EC"))
879         return 1;
880 
881 
882     /* Get required compression id */
883     point_conv = EVP_PKEY_get_ec_point_conv_form(pkey);
884     if (point_conv == 0)
885         return 0;
886     if (point_conv == POINT_CONVERSION_UNCOMPRESSED) {
887             comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
888     } else if (SSL_IS_TLS13(s)) {
889         /*
890          * ec_point_formats extension is not used in TLSv1.3 so we ignore
891          * this check.
892          */
893         return 1;
894     } else {
895         int field_type = EVP_PKEY_get_field_type(pkey);
896 
897         if (field_type == NID_X9_62_prime_field)
898             comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
899         else if (field_type == NID_X9_62_characteristic_two_field)
900             comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
901         else
902             return 0;
903     }
904     /*
905      * If point formats extension present check it, otherwise everything is
906      * supported (see RFC4492).
907      */
908     if (s->ext.peer_ecpointformats == NULL)
909         return 1;
910 
911     for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {
912         if (s->ext.peer_ecpointformats[i] == comp_id)
913             return 1;
914     }
915     return 0;
916 }
917 
918 /* Return group id of a key */
919 static uint16_t tls1_get_group_id(EVP_PKEY *pkey)
920 {
921     int curve_nid = ssl_get_EC_curve_nid(pkey);
922 
923     if (curve_nid == NID_undef)
924         return 0;
925     return tls1_nid2group_id(curve_nid);
926 }
927 
928 /*
929  * Check cert parameters compatible with extensions: currently just checks EC
930  * certificates have compatible curves and compression.
931  */
932 static int tls1_check_cert_param(SSL *s, X509 *x, int check_ee_md)
933 {
934     uint16_t group_id;
935     EVP_PKEY *pkey;
936     pkey = X509_get0_pubkey(x);
937     if (pkey == NULL)
938         return 0;
939     /* If not EC nothing to do */
940     if (!EVP_PKEY_is_a(pkey, "EC"))
941         return 1;
942     /* Check compression */
943     if (!tls1_check_pkey_comp(s, pkey))
944         return 0;
945     group_id = tls1_get_group_id(pkey);
946     /*
947      * For a server we allow the certificate to not be in our list of supported
948      * groups.
949      */
950     if (!tls1_check_group_id(s, group_id, !s->server))
951         return 0;
952     /*
953      * Special case for suite B. We *MUST* sign using SHA256+P-256 or
954      * SHA384+P-384.
955      */
956     if (check_ee_md && tls1_suiteb(s)) {
957         int check_md;
958         size_t i;
959 
960         /* Check to see we have necessary signing algorithm */
961         if (group_id == TLSEXT_curve_P_256)
962             check_md = NID_ecdsa_with_SHA256;
963         else if (group_id == TLSEXT_curve_P_384)
964             check_md = NID_ecdsa_with_SHA384;
965         else
966             return 0;           /* Should never happen */
967         for (i = 0; i < s->shared_sigalgslen; i++) {
968             if (check_md == s->shared_sigalgs[i]->sigandhash)
969                 return 1;;
970         }
971         return 0;
972     }
973     return 1;
974 }
975 
976 /*
977  * tls1_check_ec_tmp_key - Check EC temporary key compatibility
978  * @s: SSL connection
979  * @cid: Cipher ID we're considering using
980  *
981  * Checks that the kECDHE cipher suite we're considering using
982  * is compatible with the client extensions.
983  *
984  * Returns 0 when the cipher can't be used or 1 when it can.
985  */
986 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
987 {
988     /* If not Suite B just need a shared group */
989     if (!tls1_suiteb(s))
990         return tls1_shared_group(s, 0) != 0;
991     /*
992      * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
993      * curves permitted.
994      */
995     if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
996         return tls1_check_group_id(s, TLSEXT_curve_P_256, 1);
997     if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
998         return tls1_check_group_id(s, TLSEXT_curve_P_384, 1);
999 
1000     return 0;
1001 }
1002 
1003 /* Default sigalg schemes */
1004 static const uint16_t tls12_sigalgs[] = {
1005     TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
1006     TLSEXT_SIGALG_ecdsa_secp384r1_sha384,
1007     TLSEXT_SIGALG_ecdsa_secp521r1_sha512,
1008     TLSEXT_SIGALG_ed25519,
1009     TLSEXT_SIGALG_ed448,
1010 
1011     TLSEXT_SIGALG_rsa_pss_pss_sha256,
1012     TLSEXT_SIGALG_rsa_pss_pss_sha384,
1013     TLSEXT_SIGALG_rsa_pss_pss_sha512,
1014     TLSEXT_SIGALG_rsa_pss_rsae_sha256,
1015     TLSEXT_SIGALG_rsa_pss_rsae_sha384,
1016     TLSEXT_SIGALG_rsa_pss_rsae_sha512,
1017 
1018     TLSEXT_SIGALG_rsa_pkcs1_sha256,
1019     TLSEXT_SIGALG_rsa_pkcs1_sha384,
1020     TLSEXT_SIGALG_rsa_pkcs1_sha512,
1021 
1022     TLSEXT_SIGALG_ecdsa_sha224,
1023     TLSEXT_SIGALG_ecdsa_sha1,
1024 
1025     TLSEXT_SIGALG_rsa_pkcs1_sha224,
1026     TLSEXT_SIGALG_rsa_pkcs1_sha1,
1027 
1028     TLSEXT_SIGALG_dsa_sha224,
1029     TLSEXT_SIGALG_dsa_sha1,
1030 
1031     TLSEXT_SIGALG_dsa_sha256,
1032     TLSEXT_SIGALG_dsa_sha384,
1033     TLSEXT_SIGALG_dsa_sha512,
1034 
1035 #ifndef OPENSSL_NO_GOST
1036     TLSEXT_SIGALG_gostr34102012_256_intrinsic,
1037     TLSEXT_SIGALG_gostr34102012_512_intrinsic,
1038     TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256,
1039     TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512,
1040     TLSEXT_SIGALG_gostr34102001_gostr3411,
1041 #endif
1042 };
1043 
1044 
1045 static const uint16_t suiteb_sigalgs[] = {
1046     TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
1047     TLSEXT_SIGALG_ecdsa_secp384r1_sha384
1048 };
1049 
1050 static const SIGALG_LOOKUP sigalg_lookup_tbl[] = {
1051     {"ecdsa_secp256r1_sha256", TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
1052      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
1053      NID_ecdsa_with_SHA256, NID_X9_62_prime256v1, 1},
1054     {"ecdsa_secp384r1_sha384", TLSEXT_SIGALG_ecdsa_secp384r1_sha384,
1055      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
1056      NID_ecdsa_with_SHA384, NID_secp384r1, 1},
1057     {"ecdsa_secp521r1_sha512", TLSEXT_SIGALG_ecdsa_secp521r1_sha512,
1058      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
1059      NID_ecdsa_with_SHA512, NID_secp521r1, 1},
1060     {"ed25519", TLSEXT_SIGALG_ed25519,
1061      NID_undef, -1, EVP_PKEY_ED25519, SSL_PKEY_ED25519,
1062      NID_undef, NID_undef, 1},
1063     {"ed448", TLSEXT_SIGALG_ed448,
1064      NID_undef, -1, EVP_PKEY_ED448, SSL_PKEY_ED448,
1065      NID_undef, NID_undef, 1},
1066     {NULL, TLSEXT_SIGALG_ecdsa_sha224,
1067      NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
1068      NID_ecdsa_with_SHA224, NID_undef, 1},
1069     {NULL, TLSEXT_SIGALG_ecdsa_sha1,
1070      NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
1071      NID_ecdsa_with_SHA1, NID_undef, 1},
1072     {"rsa_pss_rsae_sha256", TLSEXT_SIGALG_rsa_pss_rsae_sha256,
1073      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
1074      NID_undef, NID_undef, 1},
1075     {"rsa_pss_rsae_sha384", TLSEXT_SIGALG_rsa_pss_rsae_sha384,
1076      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
1077      NID_undef, NID_undef, 1},
1078     {"rsa_pss_rsae_sha512", TLSEXT_SIGALG_rsa_pss_rsae_sha512,
1079      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
1080      NID_undef, NID_undef, 1},
1081     {"rsa_pss_pss_sha256", TLSEXT_SIGALG_rsa_pss_pss_sha256,
1082      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
1083      NID_undef, NID_undef, 1},
1084     {"rsa_pss_pss_sha384", TLSEXT_SIGALG_rsa_pss_pss_sha384,
1085      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
1086      NID_undef, NID_undef, 1},
1087     {"rsa_pss_pss_sha512", TLSEXT_SIGALG_rsa_pss_pss_sha512,
1088      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
1089      NID_undef, NID_undef, 1},
1090     {"rsa_pkcs1_sha256", TLSEXT_SIGALG_rsa_pkcs1_sha256,
1091      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
1092      NID_sha256WithRSAEncryption, NID_undef, 1},
1093     {"rsa_pkcs1_sha384", TLSEXT_SIGALG_rsa_pkcs1_sha384,
1094      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
1095      NID_sha384WithRSAEncryption, NID_undef, 1},
1096     {"rsa_pkcs1_sha512", TLSEXT_SIGALG_rsa_pkcs1_sha512,
1097      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
1098      NID_sha512WithRSAEncryption, NID_undef, 1},
1099     {"rsa_pkcs1_sha224", TLSEXT_SIGALG_rsa_pkcs1_sha224,
1100      NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
1101      NID_sha224WithRSAEncryption, NID_undef, 1},
1102     {"rsa_pkcs1_sha1", TLSEXT_SIGALG_rsa_pkcs1_sha1,
1103      NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
1104      NID_sha1WithRSAEncryption, NID_undef, 1},
1105     {NULL, TLSEXT_SIGALG_dsa_sha256,
1106      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
1107      NID_dsa_with_SHA256, NID_undef, 1},
1108     {NULL, TLSEXT_SIGALG_dsa_sha384,
1109      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
1110      NID_undef, NID_undef, 1},
1111     {NULL, TLSEXT_SIGALG_dsa_sha512,
1112      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
1113      NID_undef, NID_undef, 1},
1114     {NULL, TLSEXT_SIGALG_dsa_sha224,
1115      NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
1116      NID_undef, NID_undef, 1},
1117     {NULL, TLSEXT_SIGALG_dsa_sha1,
1118      NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
1119      NID_dsaWithSHA1, NID_undef, 1},
1120 #ifndef OPENSSL_NO_GOST
1121     {NULL, TLSEXT_SIGALG_gostr34102012_256_intrinsic,
1122      NID_id_GostR3411_2012_256, SSL_MD_GOST12_256_IDX,
1123      NID_id_GostR3410_2012_256, SSL_PKEY_GOST12_256,
1124      NID_undef, NID_undef, 1},
1125     {NULL, TLSEXT_SIGALG_gostr34102012_512_intrinsic,
1126      NID_id_GostR3411_2012_512, SSL_MD_GOST12_512_IDX,
1127      NID_id_GostR3410_2012_512, SSL_PKEY_GOST12_512,
1128      NID_undef, NID_undef, 1},
1129     {NULL, TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256,
1130      NID_id_GostR3411_2012_256, SSL_MD_GOST12_256_IDX,
1131      NID_id_GostR3410_2012_256, SSL_PKEY_GOST12_256,
1132      NID_undef, NID_undef, 1},
1133     {NULL, TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512,
1134      NID_id_GostR3411_2012_512, SSL_MD_GOST12_512_IDX,
1135      NID_id_GostR3410_2012_512, SSL_PKEY_GOST12_512,
1136      NID_undef, NID_undef, 1},
1137     {NULL, TLSEXT_SIGALG_gostr34102001_gostr3411,
1138      NID_id_GostR3411_94, SSL_MD_GOST94_IDX,
1139      NID_id_GostR3410_2001, SSL_PKEY_GOST01,
1140      NID_undef, NID_undef, 1}
1141 #endif
1142 };
1143 /* Legacy sigalgs for TLS < 1.2 RSA TLS signatures */
1144 static const SIGALG_LOOKUP legacy_rsa_sigalg = {
1145     "rsa_pkcs1_md5_sha1", 0,
1146      NID_md5_sha1, SSL_MD_MD5_SHA1_IDX,
1147      EVP_PKEY_RSA, SSL_PKEY_RSA,
1148      NID_undef, NID_undef, 1
1149 };
1150 
1151 /*
1152  * Default signature algorithm values used if signature algorithms not present.
1153  * From RFC5246. Note: order must match certificate index order.
1154  */
1155 static const uint16_t tls_default_sigalg[] = {
1156     TLSEXT_SIGALG_rsa_pkcs1_sha1, /* SSL_PKEY_RSA */
1157     0, /* SSL_PKEY_RSA_PSS_SIGN */
1158     TLSEXT_SIGALG_dsa_sha1, /* SSL_PKEY_DSA_SIGN */
1159     TLSEXT_SIGALG_ecdsa_sha1, /* SSL_PKEY_ECC */
1160     TLSEXT_SIGALG_gostr34102001_gostr3411, /* SSL_PKEY_GOST01 */
1161     TLSEXT_SIGALG_gostr34102012_256_intrinsic, /* SSL_PKEY_GOST12_256 */
1162     TLSEXT_SIGALG_gostr34102012_512_intrinsic, /* SSL_PKEY_GOST12_512 */
1163     0, /* SSL_PKEY_ED25519 */
1164     0, /* SSL_PKEY_ED448 */
1165 };
1166 
1167 int ssl_setup_sig_algs(SSL_CTX *ctx)
1168 {
1169     size_t i;
1170     const SIGALG_LOOKUP *lu;
1171     SIGALG_LOOKUP *cache
1172         = OPENSSL_malloc(sizeof(*lu) * OSSL_NELEM(sigalg_lookup_tbl));
1173     EVP_PKEY *tmpkey = EVP_PKEY_new();
1174     int ret = 0;
1175 
1176     if (cache == NULL || tmpkey == NULL)
1177         goto err;
1178 
1179     ERR_set_mark();
1180     for (i = 0, lu = sigalg_lookup_tbl;
1181          i < OSSL_NELEM(sigalg_lookup_tbl); lu++, i++) {
1182         EVP_PKEY_CTX *pctx;
1183 
1184         cache[i] = *lu;
1185 
1186         /*
1187          * Check hash is available.
1188          * This test is not perfect. A provider could have support
1189          * for a signature scheme, but not a particular hash. However the hash
1190          * could be available from some other loaded provider. In that case it
1191          * could be that the signature is available, and the hash is available
1192          * independently - but not as a combination. We ignore this for now.
1193          */
1194         if (lu->hash != NID_undef
1195                 && ctx->ssl_digest_methods[lu->hash_idx] == NULL) {
1196             cache[i].enabled = 0;
1197             continue;
1198         }
1199 
1200         if (!EVP_PKEY_set_type(tmpkey, lu->sig)) {
1201             cache[i].enabled = 0;
1202             continue;
1203         }
1204         pctx = EVP_PKEY_CTX_new_from_pkey(ctx->libctx, tmpkey, ctx->propq);
1205         /* If unable to create pctx we assume the sig algorithm is unavailable */
1206         if (pctx == NULL)
1207             cache[i].enabled = 0;
1208         EVP_PKEY_CTX_free(pctx);
1209     }
1210     ERR_pop_to_mark();
1211     ctx->sigalg_lookup_cache = cache;
1212     cache = NULL;
1213 
1214     ret = 1;
1215  err:
1216     OPENSSL_free(cache);
1217     EVP_PKEY_free(tmpkey);
1218     return ret;
1219 }
1220 
1221 /* Lookup TLS signature algorithm */
1222 static const SIGALG_LOOKUP *tls1_lookup_sigalg(const SSL *s, uint16_t sigalg)
1223 {
1224     size_t i;
1225     const SIGALG_LOOKUP *lu;
1226 
1227     for (i = 0, lu = s->ctx->sigalg_lookup_cache;
1228          /* cache should have the same number of elements as sigalg_lookup_tbl */
1229          i < OSSL_NELEM(sigalg_lookup_tbl);
1230          lu++, i++) {
1231         if (lu->sigalg == sigalg) {
1232             if (!lu->enabled)
1233                 return NULL;
1234             return lu;
1235         }
1236     }
1237     return NULL;
1238 }
1239 /* Lookup hash: return 0 if invalid or not enabled */
1240 int tls1_lookup_md(SSL_CTX *ctx, const SIGALG_LOOKUP *lu, const EVP_MD **pmd)
1241 {
1242     const EVP_MD *md;
1243     if (lu == NULL)
1244         return 0;
1245     /* lu->hash == NID_undef means no associated digest */
1246     if (lu->hash == NID_undef) {
1247         md = NULL;
1248     } else {
1249         md = ssl_md(ctx, lu->hash_idx);
1250         if (md == NULL)
1251             return 0;
1252     }
1253     if (pmd)
1254         *pmd = md;
1255     return 1;
1256 }
1257 
1258 /*
1259  * Check if key is large enough to generate RSA-PSS signature.
1260  *
1261  * The key must greater than or equal to 2 * hash length + 2.
1262  * SHA512 has a hash length of 64 bytes, which is incompatible
1263  * with a 128 byte (1024 bit) key.
1264  */
1265 #define RSA_PSS_MINIMUM_KEY_SIZE(md) (2 * EVP_MD_get_size(md) + 2)
1266 static int rsa_pss_check_min_key_size(SSL_CTX *ctx, const EVP_PKEY *pkey,
1267                                       const SIGALG_LOOKUP *lu)
1268 {
1269     const EVP_MD *md;
1270 
1271     if (pkey == NULL)
1272         return 0;
1273     if (!tls1_lookup_md(ctx, lu, &md) || md == NULL)
1274         return 0;
1275     if (EVP_PKEY_get_size(pkey) < RSA_PSS_MINIMUM_KEY_SIZE(md))
1276         return 0;
1277     return 1;
1278 }
1279 
1280 /*
1281  * Returns a signature algorithm when the peer did not send a list of supported
1282  * signature algorithms. The signature algorithm is fixed for the certificate
1283  * type. |idx| is a certificate type index (SSL_PKEY_*). When |idx| is -1 the
1284  * certificate type from |s| will be used.
1285  * Returns the signature algorithm to use, or NULL on error.
1286  */
1287 static const SIGALG_LOOKUP *tls1_get_legacy_sigalg(const SSL *s, int idx)
1288 {
1289     if (idx == -1) {
1290         if (s->server) {
1291             size_t i;
1292 
1293             /* Work out index corresponding to ciphersuite */
1294             for (i = 0; i < SSL_PKEY_NUM; i++) {
1295                 const SSL_CERT_LOOKUP *clu = ssl_cert_lookup_by_idx(i);
1296 
1297                 if (clu == NULL)
1298                     continue;
1299                 if (clu->amask & s->s3.tmp.new_cipher->algorithm_auth) {
1300                     idx = i;
1301                     break;
1302                 }
1303             }
1304 
1305             /*
1306              * Some GOST ciphersuites allow more than one signature algorithms
1307              * */
1308             if (idx == SSL_PKEY_GOST01 && s->s3.tmp.new_cipher->algorithm_auth != SSL_aGOST01) {
1309                 int real_idx;
1310 
1311                 for (real_idx = SSL_PKEY_GOST12_512; real_idx >= SSL_PKEY_GOST01;
1312                      real_idx--) {
1313                     if (s->cert->pkeys[real_idx].privatekey != NULL) {
1314                         idx = real_idx;
1315                         break;
1316                     }
1317                 }
1318             }
1319             /*
1320              * As both SSL_PKEY_GOST12_512 and SSL_PKEY_GOST12_256 indices can be used
1321              * with new (aGOST12-only) ciphersuites, we should find out which one is available really.
1322              */
1323             else if (idx == SSL_PKEY_GOST12_256) {
1324                 int real_idx;
1325 
1326                 for (real_idx = SSL_PKEY_GOST12_512; real_idx >= SSL_PKEY_GOST12_256;
1327                      real_idx--) {
1328                      if (s->cert->pkeys[real_idx].privatekey != NULL) {
1329                          idx = real_idx;
1330                          break;
1331                      }
1332                 }
1333             }
1334         } else {
1335             idx = s->cert->key - s->cert->pkeys;
1336         }
1337     }
1338     if (idx < 0 || idx >= (int)OSSL_NELEM(tls_default_sigalg))
1339         return NULL;
1340     if (SSL_USE_SIGALGS(s) || idx != SSL_PKEY_RSA) {
1341         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, tls_default_sigalg[idx]);
1342 
1343         if (lu == NULL)
1344             return NULL;
1345         if (!tls1_lookup_md(s->ctx, lu, NULL))
1346             return NULL;
1347         if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, lu))
1348             return NULL;
1349         return lu;
1350     }
1351     if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, &legacy_rsa_sigalg))
1352         return NULL;
1353     return &legacy_rsa_sigalg;
1354 }
1355 /* Set peer sigalg based key type */
1356 int tls1_set_peer_legacy_sigalg(SSL *s, const EVP_PKEY *pkey)
1357 {
1358     size_t idx;
1359     const SIGALG_LOOKUP *lu;
1360 
1361     if (ssl_cert_lookup_by_pkey(pkey, &idx) == NULL)
1362         return 0;
1363     lu = tls1_get_legacy_sigalg(s, idx);
1364     if (lu == NULL)
1365         return 0;
1366     s->s3.tmp.peer_sigalg = lu;
1367     return 1;
1368 }
1369 
1370 size_t tls12_get_psigalgs(SSL *s, int sent, const uint16_t **psigs)
1371 {
1372     /*
1373      * If Suite B mode use Suite B sigalgs only, ignore any other
1374      * preferences.
1375      */
1376     switch (tls1_suiteb(s)) {
1377     case SSL_CERT_FLAG_SUITEB_128_LOS:
1378         *psigs = suiteb_sigalgs;
1379         return OSSL_NELEM(suiteb_sigalgs);
1380 
1381     case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
1382         *psigs = suiteb_sigalgs;
1383         return 1;
1384 
1385     case SSL_CERT_FLAG_SUITEB_192_LOS:
1386         *psigs = suiteb_sigalgs + 1;
1387         return 1;
1388     }
1389     /*
1390      *  We use client_sigalgs (if not NULL) if we're a server
1391      *  and sending a certificate request or if we're a client and
1392      *  determining which shared algorithm to use.
1393      */
1394     if ((s->server == sent) && s->cert->client_sigalgs != NULL) {
1395         *psigs = s->cert->client_sigalgs;
1396         return s->cert->client_sigalgslen;
1397     } else if (s->cert->conf_sigalgs) {
1398         *psigs = s->cert->conf_sigalgs;
1399         return s->cert->conf_sigalgslen;
1400     } else {
1401         *psigs = tls12_sigalgs;
1402         return OSSL_NELEM(tls12_sigalgs);
1403     }
1404 }
1405 
1406 /*
1407  * Called by servers only. Checks that we have a sig alg that supports the
1408  * specified EC curve.
1409  */
1410 int tls_check_sigalg_curve(const SSL *s, int curve)
1411 {
1412    const uint16_t *sigs;
1413    size_t siglen, i;
1414 
1415     if (s->cert->conf_sigalgs) {
1416         sigs = s->cert->conf_sigalgs;
1417         siglen = s->cert->conf_sigalgslen;
1418     } else {
1419         sigs = tls12_sigalgs;
1420         siglen = OSSL_NELEM(tls12_sigalgs);
1421     }
1422 
1423     for (i = 0; i < siglen; i++) {
1424         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, sigs[i]);
1425 
1426         if (lu == NULL)
1427             continue;
1428         if (lu->sig == EVP_PKEY_EC
1429                 && lu->curve != NID_undef
1430                 && curve == lu->curve)
1431             return 1;
1432     }
1433 
1434     return 0;
1435 }
1436 
1437 /*
1438  * Return the number of security bits for the signature algorithm, or 0 on
1439  * error.
1440  */
1441 static int sigalg_security_bits(SSL_CTX *ctx, const SIGALG_LOOKUP *lu)
1442 {
1443     const EVP_MD *md = NULL;
1444     int secbits = 0;
1445 
1446     if (!tls1_lookup_md(ctx, lu, &md))
1447         return 0;
1448     if (md != NULL)
1449     {
1450         int md_type = EVP_MD_get_type(md);
1451 
1452         /* Security bits: half digest bits */
1453         secbits = EVP_MD_get_size(md) * 4;
1454         /*
1455          * SHA1 and MD5 are known to be broken. Reduce security bits so that
1456          * they're no longer accepted at security level 1. The real values don't
1457          * really matter as long as they're lower than 80, which is our
1458          * security level 1.
1459          * https://eprint.iacr.org/2020/014 puts a chosen-prefix attack for
1460          * SHA1 at 2^63.4 and MD5+SHA1 at 2^67.2
1461          * https://documents.epfl.ch/users/l/le/lenstra/public/papers/lat.pdf
1462          * puts a chosen-prefix attack for MD5 at 2^39.
1463          */
1464         if (md_type == NID_sha1)
1465             secbits = 64;
1466         else if (md_type == NID_md5_sha1)
1467             secbits = 67;
1468         else if (md_type == NID_md5)
1469             secbits = 39;
1470     } else {
1471         /* Values from https://tools.ietf.org/html/rfc8032#section-8.5 */
1472         if (lu->sigalg == TLSEXT_SIGALG_ed25519)
1473             secbits = 128;
1474         else if (lu->sigalg == TLSEXT_SIGALG_ed448)
1475             secbits = 224;
1476     }
1477     return secbits;
1478 }
1479 
1480 /*
1481  * Check signature algorithm is consistent with sent supported signature
1482  * algorithms and if so set relevant digest and signature scheme in
1483  * s.
1484  */
1485 int tls12_check_peer_sigalg(SSL *s, uint16_t sig, EVP_PKEY *pkey)
1486 {
1487     const uint16_t *sent_sigs;
1488     const EVP_MD *md = NULL;
1489     char sigalgstr[2];
1490     size_t sent_sigslen, i, cidx;
1491     int pkeyid = -1;
1492     const SIGALG_LOOKUP *lu;
1493     int secbits = 0;
1494 
1495     pkeyid = EVP_PKEY_get_id(pkey);
1496     /* Should never happen */
1497     if (pkeyid == -1)
1498         return -1;
1499     if (SSL_IS_TLS13(s)) {
1500         /* Disallow DSA for TLS 1.3 */
1501         if (pkeyid == EVP_PKEY_DSA) {
1502             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_SIGNATURE_TYPE);
1503             return 0;
1504         }
1505         /* Only allow PSS for TLS 1.3 */
1506         if (pkeyid == EVP_PKEY_RSA)
1507             pkeyid = EVP_PKEY_RSA_PSS;
1508     }
1509     lu = tls1_lookup_sigalg(s, sig);
1510     /*
1511      * Check sigalgs is known. Disallow SHA1/SHA224 with TLS 1.3. Check key type
1512      * is consistent with signature: RSA keys can be used for RSA-PSS
1513      */
1514     if (lu == NULL
1515         || (SSL_IS_TLS13(s) && (lu->hash == NID_sha1 || lu->hash == NID_sha224))
1516         || (pkeyid != lu->sig
1517         && (lu->sig != EVP_PKEY_RSA_PSS || pkeyid != EVP_PKEY_RSA))) {
1518         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_SIGNATURE_TYPE);
1519         return 0;
1520     }
1521     /* Check the sigalg is consistent with the key OID */
1522     if (!ssl_cert_lookup_by_nid(EVP_PKEY_get_id(pkey), &cidx)
1523             || lu->sig_idx != (int)cidx) {
1524         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_SIGNATURE_TYPE);
1525         return 0;
1526     }
1527 
1528     if (pkeyid == EVP_PKEY_EC) {
1529 
1530         /* Check point compression is permitted */
1531         if (!tls1_check_pkey_comp(s, pkey)) {
1532             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1533                      SSL_R_ILLEGAL_POINT_COMPRESSION);
1534             return 0;
1535         }
1536 
1537         /* For TLS 1.3 or Suite B check curve matches signature algorithm */
1538         if (SSL_IS_TLS13(s) || tls1_suiteb(s)) {
1539             int curve = ssl_get_EC_curve_nid(pkey);
1540 
1541             if (lu->curve != NID_undef && curve != lu->curve) {
1542                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);
1543                 return 0;
1544             }
1545         }
1546         if (!SSL_IS_TLS13(s)) {
1547             /* Check curve matches extensions */
1548             if (!tls1_check_group_id(s, tls1_get_group_id(pkey), 1)) {
1549                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);
1550                 return 0;
1551             }
1552             if (tls1_suiteb(s)) {
1553                 /* Check sigalg matches a permissible Suite B value */
1554                 if (sig != TLSEXT_SIGALG_ecdsa_secp256r1_sha256
1555                     && sig != TLSEXT_SIGALG_ecdsa_secp384r1_sha384) {
1556                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1557                              SSL_R_WRONG_SIGNATURE_TYPE);
1558                     return 0;
1559                 }
1560             }
1561         }
1562     } else if (tls1_suiteb(s)) {
1563         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_WRONG_SIGNATURE_TYPE);
1564         return 0;
1565     }
1566 
1567     /* Check signature matches a type we sent */
1568     sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
1569     for (i = 0; i < sent_sigslen; i++, sent_sigs++) {
1570         if (sig == *sent_sigs)
1571             break;
1572     }
1573     /* Allow fallback to SHA1 if not strict mode */
1574     if (i == sent_sigslen && (lu->hash != NID_sha1
1575         || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
1576         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_WRONG_SIGNATURE_TYPE);
1577         return 0;
1578     }
1579     if (!tls1_lookup_md(s->ctx, lu, &md)) {
1580         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_UNKNOWN_DIGEST);
1581         return 0;
1582     }
1583     /*
1584      * Make sure security callback allows algorithm. For historical
1585      * reasons we have to pass the sigalg as a two byte char array.
1586      */
1587     sigalgstr[0] = (sig >> 8) & 0xff;
1588     sigalgstr[1] = sig & 0xff;
1589     secbits = sigalg_security_bits(s->ctx, lu);
1590     if (secbits == 0 ||
1591         !ssl_security(s, SSL_SECOP_SIGALG_CHECK, secbits,
1592                       md != NULL ? EVP_MD_get_type(md) : NID_undef,
1593                       (void *)sigalgstr)) {
1594         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_WRONG_SIGNATURE_TYPE);
1595         return 0;
1596     }
1597     /* Store the sigalg the peer uses */
1598     s->s3.tmp.peer_sigalg = lu;
1599     return 1;
1600 }
1601 
1602 int SSL_get_peer_signature_type_nid(const SSL *s, int *pnid)
1603 {
1604     if (s->s3.tmp.peer_sigalg == NULL)
1605         return 0;
1606     *pnid = s->s3.tmp.peer_sigalg->sig;
1607     return 1;
1608 }
1609 
1610 int SSL_get_signature_type_nid(const SSL *s, int *pnid)
1611 {
1612     if (s->s3.tmp.sigalg == NULL)
1613         return 0;
1614     *pnid = s->s3.tmp.sigalg->sig;
1615     return 1;
1616 }
1617 
1618 /*
1619  * Set a mask of disabled algorithms: an algorithm is disabled if it isn't
1620  * supported, doesn't appear in supported signature algorithms, isn't supported
1621  * by the enabled protocol versions or by the security level.
1622  *
1623  * This function should only be used for checking which ciphers are supported
1624  * by the client.
1625  *
1626  * Call ssl_cipher_disabled() to check that it's enabled or not.
1627  */
1628 int ssl_set_client_disabled(SSL *s)
1629 {
1630     s->s3.tmp.mask_a = 0;
1631     s->s3.tmp.mask_k = 0;
1632     ssl_set_sig_mask(&s->s3.tmp.mask_a, s, SSL_SECOP_SIGALG_MASK);
1633     if (ssl_get_min_max_version(s, &s->s3.tmp.min_ver,
1634                                 &s->s3.tmp.max_ver, NULL) != 0)
1635         return 0;
1636 #ifndef OPENSSL_NO_PSK
1637     /* with PSK there must be client callback set */
1638     if (!s->psk_client_callback) {
1639         s->s3.tmp.mask_a |= SSL_aPSK;
1640         s->s3.tmp.mask_k |= SSL_PSK;
1641     }
1642 #endif                          /* OPENSSL_NO_PSK */
1643 #ifndef OPENSSL_NO_SRP
1644     if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
1645         s->s3.tmp.mask_a |= SSL_aSRP;
1646         s->s3.tmp.mask_k |= SSL_kSRP;
1647     }
1648 #endif
1649     return 1;
1650 }
1651 
1652 /*
1653  * ssl_cipher_disabled - check that a cipher is disabled or not
1654  * @s: SSL connection that you want to use the cipher on
1655  * @c: cipher to check
1656  * @op: Security check that you want to do
1657  * @ecdhe: If set to 1 then TLSv1 ECDHE ciphers are also allowed in SSLv3
1658  *
1659  * Returns 1 when it's disabled, 0 when enabled.
1660  */
1661 int ssl_cipher_disabled(const SSL *s, const SSL_CIPHER *c, int op, int ecdhe)
1662 {
1663     if (c->algorithm_mkey & s->s3.tmp.mask_k
1664         || c->algorithm_auth & s->s3.tmp.mask_a)
1665         return 1;
1666     if (s->s3.tmp.max_ver == 0)
1667         return 1;
1668     if (!SSL_IS_DTLS(s)) {
1669         int min_tls = c->min_tls;
1670 
1671         /*
1672          * For historical reasons we will allow ECHDE to be selected by a server
1673          * in SSLv3 if we are a client
1674          */
1675         if (min_tls == TLS1_VERSION && ecdhe
1676                 && (c->algorithm_mkey & (SSL_kECDHE | SSL_kECDHEPSK)) != 0)
1677             min_tls = SSL3_VERSION;
1678 
1679         if ((min_tls > s->s3.tmp.max_ver) || (c->max_tls < s->s3.tmp.min_ver))
1680             return 1;
1681     }
1682     if (SSL_IS_DTLS(s) && (DTLS_VERSION_GT(c->min_dtls, s->s3.tmp.max_ver)
1683                            || DTLS_VERSION_LT(c->max_dtls, s->s3.tmp.min_ver)))
1684         return 1;
1685 
1686     return !ssl_security(s, op, c->strength_bits, 0, (void *)c);
1687 }
1688 
1689 int tls_use_ticket(SSL *s)
1690 {
1691     if ((s->options & SSL_OP_NO_TICKET))
1692         return 0;
1693     return ssl_security(s, SSL_SECOP_TICKET, 0, 0, NULL);
1694 }
1695 
1696 int tls1_set_server_sigalgs(SSL *s)
1697 {
1698     size_t i;
1699 
1700     /* Clear any shared signature algorithms */
1701     OPENSSL_free(s->shared_sigalgs);
1702     s->shared_sigalgs = NULL;
1703     s->shared_sigalgslen = 0;
1704     /* Clear certificate validity flags */
1705     for (i = 0; i < SSL_PKEY_NUM; i++)
1706         s->s3.tmp.valid_flags[i] = 0;
1707     /*
1708      * If peer sent no signature algorithms check to see if we support
1709      * the default algorithm for each certificate type
1710      */
1711     if (s->s3.tmp.peer_cert_sigalgs == NULL
1712             && s->s3.tmp.peer_sigalgs == NULL) {
1713         const uint16_t *sent_sigs;
1714         size_t sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
1715 
1716         for (i = 0; i < SSL_PKEY_NUM; i++) {
1717             const SIGALG_LOOKUP *lu = tls1_get_legacy_sigalg(s, i);
1718             size_t j;
1719 
1720             if (lu == NULL)
1721                 continue;
1722             /* Check default matches a type we sent */
1723             for (j = 0; j < sent_sigslen; j++) {
1724                 if (lu->sigalg == sent_sigs[j]) {
1725                         s->s3.tmp.valid_flags[i] = CERT_PKEY_SIGN;
1726                         break;
1727                 }
1728             }
1729         }
1730         return 1;
1731     }
1732 
1733     if (!tls1_process_sigalgs(s)) {
1734         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1735         return 0;
1736     }
1737     if (s->shared_sigalgs != NULL)
1738         return 1;
1739 
1740     /* Fatal error if no shared signature algorithms */
1741     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1742              SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS);
1743     return 0;
1744 }
1745 
1746 /*-
1747  * Gets the ticket information supplied by the client if any.
1748  *
1749  *   hello: The parsed ClientHello data
1750  *   ret: (output) on return, if a ticket was decrypted, then this is set to
1751  *       point to the resulting session.
1752  */
1753 SSL_TICKET_STATUS tls_get_ticket_from_client(SSL *s, CLIENTHELLO_MSG *hello,
1754                                              SSL_SESSION **ret)
1755 {
1756     size_t size;
1757     RAW_EXTENSION *ticketext;
1758 
1759     *ret = NULL;
1760     s->ext.ticket_expected = 0;
1761 
1762     /*
1763      * If tickets disabled or not supported by the protocol version
1764      * (e.g. TLSv1.3) behave as if no ticket present to permit stateful
1765      * resumption.
1766      */
1767     if (s->version <= SSL3_VERSION || !tls_use_ticket(s))
1768         return SSL_TICKET_NONE;
1769 
1770     ticketext = &hello->pre_proc_exts[TLSEXT_IDX_session_ticket];
1771     if (!ticketext->present)
1772         return SSL_TICKET_NONE;
1773 
1774     size = PACKET_remaining(&ticketext->data);
1775 
1776     return tls_decrypt_ticket(s, PACKET_data(&ticketext->data), size,
1777                               hello->session_id, hello->session_id_len, ret);
1778 }
1779 
1780 /*-
1781  * tls_decrypt_ticket attempts to decrypt a session ticket.
1782  *
1783  * If s->tls_session_secret_cb is set and we're not doing TLSv1.3 then we are
1784  * expecting a pre-shared key ciphersuite, in which case we have no use for
1785  * session tickets and one will never be decrypted, nor will
1786  * s->ext.ticket_expected be set to 1.
1787  *
1788  * Side effects:
1789  *   Sets s->ext.ticket_expected to 1 if the server will have to issue
1790  *   a new session ticket to the client because the client indicated support
1791  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
1792  *   a session ticket or we couldn't use the one it gave us, or if
1793  *   s->ctx->ext.ticket_key_cb asked to renew the client's ticket.
1794  *   Otherwise, s->ext.ticket_expected is set to 0.
1795  *
1796  *   etick: points to the body of the session ticket extension.
1797  *   eticklen: the length of the session tickets extension.
1798  *   sess_id: points at the session ID.
1799  *   sesslen: the length of the session ID.
1800  *   psess: (output) on return, if a ticket was decrypted, then this is set to
1801  *       point to the resulting session.
1802  */
1803 SSL_TICKET_STATUS tls_decrypt_ticket(SSL *s, const unsigned char *etick,
1804                                      size_t eticklen, const unsigned char *sess_id,
1805                                      size_t sesslen, SSL_SESSION **psess)
1806 {
1807     SSL_SESSION *sess = NULL;
1808     unsigned char *sdec;
1809     const unsigned char *p;
1810     int slen, ivlen, renew_ticket = 0, declen;
1811     SSL_TICKET_STATUS ret = SSL_TICKET_FATAL_ERR_OTHER;
1812     size_t mlen;
1813     unsigned char tick_hmac[EVP_MAX_MD_SIZE];
1814     SSL_HMAC *hctx = NULL;
1815     EVP_CIPHER_CTX *ctx = NULL;
1816     SSL_CTX *tctx = s->session_ctx;
1817 
1818     if (eticklen == 0) {
1819         /*
1820          * The client will accept a ticket but doesn't currently have
1821          * one (TLSv1.2 and below), or treated as a fatal error in TLSv1.3
1822          */
1823         ret = SSL_TICKET_EMPTY;
1824         goto end;
1825     }
1826     if (!SSL_IS_TLS13(s) && s->ext.session_secret_cb) {
1827         /*
1828          * Indicate that the ticket couldn't be decrypted rather than
1829          * generating the session from ticket now, trigger
1830          * abbreviated handshake based on external mechanism to
1831          * calculate the master secret later.
1832          */
1833         ret = SSL_TICKET_NO_DECRYPT;
1834         goto end;
1835     }
1836 
1837     /* Need at least keyname + iv */
1838     if (eticklen < TLSEXT_KEYNAME_LENGTH + EVP_MAX_IV_LENGTH) {
1839         ret = SSL_TICKET_NO_DECRYPT;
1840         goto end;
1841     }
1842 
1843     /* Initialize session ticket encryption and HMAC contexts */
1844     hctx = ssl_hmac_new(tctx);
1845     if (hctx == NULL) {
1846         ret = SSL_TICKET_FATAL_ERR_MALLOC;
1847         goto end;
1848     }
1849     ctx = EVP_CIPHER_CTX_new();
1850     if (ctx == NULL) {
1851         ret = SSL_TICKET_FATAL_ERR_MALLOC;
1852         goto end;
1853     }
1854 #ifndef OPENSSL_NO_DEPRECATED_3_0
1855     if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
1856 #else
1857     if (tctx->ext.ticket_key_evp_cb != NULL)
1858 #endif
1859     {
1860         unsigned char *nctick = (unsigned char *)etick;
1861         int rv = 0;
1862 
1863         if (tctx->ext.ticket_key_evp_cb != NULL)
1864             rv = tctx->ext.ticket_key_evp_cb(s, nctick,
1865                                              nctick + TLSEXT_KEYNAME_LENGTH,
1866                                              ctx,
1867                                              ssl_hmac_get0_EVP_MAC_CTX(hctx),
1868                                              0);
1869 #ifndef OPENSSL_NO_DEPRECATED_3_0
1870         else if (tctx->ext.ticket_key_cb != NULL)
1871             /* if 0 is returned, write an empty ticket */
1872             rv = tctx->ext.ticket_key_cb(s, nctick,
1873                                          nctick + TLSEXT_KEYNAME_LENGTH,
1874                                          ctx, ssl_hmac_get0_HMAC_CTX(hctx), 0);
1875 #endif
1876         if (rv < 0) {
1877             ret = SSL_TICKET_FATAL_ERR_OTHER;
1878             goto end;
1879         }
1880         if (rv == 0) {
1881             ret = SSL_TICKET_NO_DECRYPT;
1882             goto end;
1883         }
1884         if (rv == 2)
1885             renew_ticket = 1;
1886     } else {
1887         EVP_CIPHER *aes256cbc = NULL;
1888 
1889         /* Check key name matches */
1890         if (memcmp(etick, tctx->ext.tick_key_name,
1891                    TLSEXT_KEYNAME_LENGTH) != 0) {
1892             ret = SSL_TICKET_NO_DECRYPT;
1893             goto end;
1894         }
1895 
1896         aes256cbc = EVP_CIPHER_fetch(s->ctx->libctx, "AES-256-CBC",
1897                                      s->ctx->propq);
1898         if (aes256cbc == NULL
1899             || ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
1900                              sizeof(tctx->ext.secure->tick_hmac_key),
1901                              "SHA256") <= 0
1902             || EVP_DecryptInit_ex(ctx, aes256cbc, NULL,
1903                                   tctx->ext.secure->tick_aes_key,
1904                                   etick + TLSEXT_KEYNAME_LENGTH) <= 0) {
1905             EVP_CIPHER_free(aes256cbc);
1906             ret = SSL_TICKET_FATAL_ERR_OTHER;
1907             goto end;
1908         }
1909         EVP_CIPHER_free(aes256cbc);
1910         if (SSL_IS_TLS13(s))
1911             renew_ticket = 1;
1912     }
1913     /*
1914      * Attempt to process session ticket, first conduct sanity and integrity
1915      * checks on ticket.
1916      */
1917     mlen = ssl_hmac_size(hctx);
1918     if (mlen == 0) {
1919         ret = SSL_TICKET_FATAL_ERR_OTHER;
1920         goto end;
1921     }
1922 
1923     ivlen = EVP_CIPHER_CTX_get_iv_length(ctx);
1924     if (ivlen < 0) {
1925         ret = SSL_TICKET_FATAL_ERR_OTHER;
1926         goto end;
1927     }
1928 
1929     /* Sanity check ticket length: must exceed keyname + IV + HMAC */
1930     if (eticklen <= TLSEXT_KEYNAME_LENGTH + ivlen + mlen) {
1931         ret = SSL_TICKET_NO_DECRYPT;
1932         goto end;
1933     }
1934     eticklen -= mlen;
1935     /* Check HMAC of encrypted ticket */
1936     if (ssl_hmac_update(hctx, etick, eticklen) <= 0
1937         || ssl_hmac_final(hctx, tick_hmac, NULL, sizeof(tick_hmac)) <= 0) {
1938         ret = SSL_TICKET_FATAL_ERR_OTHER;
1939         goto end;
1940     }
1941 
1942     if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
1943         ret = SSL_TICKET_NO_DECRYPT;
1944         goto end;
1945     }
1946     /* Attempt to decrypt session data */
1947     /* Move p after IV to start of encrypted ticket, update length */
1948     p = etick + TLSEXT_KEYNAME_LENGTH + ivlen;
1949     eticklen -= TLSEXT_KEYNAME_LENGTH + ivlen;
1950     sdec = OPENSSL_malloc(eticklen);
1951     if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p,
1952                                           (int)eticklen) <= 0) {
1953         OPENSSL_free(sdec);
1954         ret = SSL_TICKET_FATAL_ERR_OTHER;
1955         goto end;
1956     }
1957     if (EVP_DecryptFinal(ctx, sdec + slen, &declen) <= 0) {
1958         OPENSSL_free(sdec);
1959         ret = SSL_TICKET_NO_DECRYPT;
1960         goto end;
1961     }
1962     slen += declen;
1963     p = sdec;
1964 
1965     sess = d2i_SSL_SESSION(NULL, &p, slen);
1966     slen -= p - sdec;
1967     OPENSSL_free(sdec);
1968     if (sess) {
1969         /* Some additional consistency checks */
1970         if (slen != 0) {
1971             SSL_SESSION_free(sess);
1972             sess = NULL;
1973             ret = SSL_TICKET_NO_DECRYPT;
1974             goto end;
1975         }
1976         /*
1977          * The session ID, if non-empty, is used by some clients to detect
1978          * that the ticket has been accepted. So we copy it to the session
1979          * structure. If it is empty set length to zero as required by
1980          * standard.
1981          */
1982         if (sesslen) {
1983             memcpy(sess->session_id, sess_id, sesslen);
1984             sess->session_id_length = sesslen;
1985         }
1986         if (renew_ticket)
1987             ret = SSL_TICKET_SUCCESS_RENEW;
1988         else
1989             ret = SSL_TICKET_SUCCESS;
1990         goto end;
1991     }
1992     ERR_clear_error();
1993     /*
1994      * For session parse failure, indicate that we need to send a new ticket.
1995      */
1996     ret = SSL_TICKET_NO_DECRYPT;
1997 
1998  end:
1999     EVP_CIPHER_CTX_free(ctx);
2000     ssl_hmac_free(hctx);
2001 
2002     /*
2003      * If set, the decrypt_ticket_cb() is called unless a fatal error was
2004      * detected above. The callback is responsible for checking |ret| before it
2005      * performs any action
2006      */
2007     if (s->session_ctx->decrypt_ticket_cb != NULL
2008             && (ret == SSL_TICKET_EMPTY
2009                 || ret == SSL_TICKET_NO_DECRYPT
2010                 || ret == SSL_TICKET_SUCCESS
2011                 || ret == SSL_TICKET_SUCCESS_RENEW)) {
2012         size_t keyname_len = eticklen;
2013         int retcb;
2014 
2015         if (keyname_len > TLSEXT_KEYNAME_LENGTH)
2016             keyname_len = TLSEXT_KEYNAME_LENGTH;
2017         retcb = s->session_ctx->decrypt_ticket_cb(s, sess, etick, keyname_len,
2018                                                   ret,
2019                                                   s->session_ctx->ticket_cb_data);
2020         switch (retcb) {
2021         case SSL_TICKET_RETURN_ABORT:
2022             ret = SSL_TICKET_FATAL_ERR_OTHER;
2023             break;
2024 
2025         case SSL_TICKET_RETURN_IGNORE:
2026             ret = SSL_TICKET_NONE;
2027             SSL_SESSION_free(sess);
2028             sess = NULL;
2029             break;
2030 
2031         case SSL_TICKET_RETURN_IGNORE_RENEW:
2032             if (ret != SSL_TICKET_EMPTY && ret != SSL_TICKET_NO_DECRYPT)
2033                 ret = SSL_TICKET_NO_DECRYPT;
2034             /* else the value of |ret| will already do the right thing */
2035             SSL_SESSION_free(sess);
2036             sess = NULL;
2037             break;
2038 
2039         case SSL_TICKET_RETURN_USE:
2040         case SSL_TICKET_RETURN_USE_RENEW:
2041             if (ret != SSL_TICKET_SUCCESS
2042                     && ret != SSL_TICKET_SUCCESS_RENEW)
2043                 ret = SSL_TICKET_FATAL_ERR_OTHER;
2044             else if (retcb == SSL_TICKET_RETURN_USE)
2045                 ret = SSL_TICKET_SUCCESS;
2046             else
2047                 ret = SSL_TICKET_SUCCESS_RENEW;
2048             break;
2049 
2050         default:
2051             ret = SSL_TICKET_FATAL_ERR_OTHER;
2052         }
2053     }
2054 
2055     if (s->ext.session_secret_cb == NULL || SSL_IS_TLS13(s)) {
2056         switch (ret) {
2057         case SSL_TICKET_NO_DECRYPT:
2058         case SSL_TICKET_SUCCESS_RENEW:
2059         case SSL_TICKET_EMPTY:
2060             s->ext.ticket_expected = 1;
2061         }
2062     }
2063 
2064     *psess = sess;
2065 
2066     return ret;
2067 }
2068 
2069 /* Check to see if a signature algorithm is allowed */
2070 static int tls12_sigalg_allowed(const SSL *s, int op, const SIGALG_LOOKUP *lu)
2071 {
2072     unsigned char sigalgstr[2];
2073     int secbits;
2074 
2075     if (lu == NULL || !lu->enabled)
2076         return 0;
2077     /* DSA is not allowed in TLS 1.3 */
2078     if (SSL_IS_TLS13(s) && lu->sig == EVP_PKEY_DSA)
2079         return 0;
2080     /*
2081      * At some point we should fully axe DSA/etc. in ClientHello as per TLS 1.3
2082      * spec
2083      */
2084     if (!s->server && !SSL_IS_DTLS(s) && s->s3.tmp.min_ver >= TLS1_3_VERSION
2085         && (lu->sig == EVP_PKEY_DSA || lu->hash_idx == SSL_MD_SHA1_IDX
2086             || lu->hash_idx == SSL_MD_MD5_IDX
2087             || lu->hash_idx == SSL_MD_SHA224_IDX))
2088         return 0;
2089 
2090     /* See if public key algorithm allowed */
2091     if (ssl_cert_is_disabled(s->ctx, lu->sig_idx))
2092         return 0;
2093 
2094     if (lu->sig == NID_id_GostR3410_2012_256
2095             || lu->sig == NID_id_GostR3410_2012_512
2096             || lu->sig == NID_id_GostR3410_2001) {
2097         /* We never allow GOST sig algs on the server with TLSv1.3 */
2098         if (s->server && SSL_IS_TLS13(s))
2099             return 0;
2100         if (!s->server
2101                 && s->method->version == TLS_ANY_VERSION
2102                 && s->s3.tmp.max_ver >= TLS1_3_VERSION) {
2103             int i, num;
2104             STACK_OF(SSL_CIPHER) *sk;
2105 
2106             /*
2107              * We're a client that could negotiate TLSv1.3. We only allow GOST
2108              * sig algs if we could negotiate TLSv1.2 or below and we have GOST
2109              * ciphersuites enabled.
2110              */
2111 
2112             if (s->s3.tmp.min_ver >= TLS1_3_VERSION)
2113                 return 0;
2114 
2115             sk = SSL_get_ciphers(s);
2116             num = sk != NULL ? sk_SSL_CIPHER_num(sk) : 0;
2117             for (i = 0; i < num; i++) {
2118                 const SSL_CIPHER *c;
2119 
2120                 c = sk_SSL_CIPHER_value(sk, i);
2121                 /* Skip disabled ciphers */
2122                 if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0))
2123                     continue;
2124 
2125                 if ((c->algorithm_mkey & (SSL_kGOST | SSL_kGOST18)) != 0)
2126                     break;
2127             }
2128             if (i == num)
2129                 return 0;
2130         }
2131     }
2132 
2133     /* Finally see if security callback allows it */
2134     secbits = sigalg_security_bits(s->ctx, lu);
2135     sigalgstr[0] = (lu->sigalg >> 8) & 0xff;
2136     sigalgstr[1] = lu->sigalg & 0xff;
2137     return ssl_security(s, op, secbits, lu->hash, (void *)sigalgstr);
2138 }
2139 
2140 /*
2141  * Get a mask of disabled public key algorithms based on supported signature
2142  * algorithms. For example if no signature algorithm supports RSA then RSA is
2143  * disabled.
2144  */
2145 
2146 void ssl_set_sig_mask(uint32_t *pmask_a, SSL *s, int op)
2147 {
2148     const uint16_t *sigalgs;
2149     size_t i, sigalgslen;
2150     uint32_t disabled_mask = SSL_aRSA | SSL_aDSS | SSL_aECDSA;
2151     /*
2152      * Go through all signature algorithms seeing if we support any
2153      * in disabled_mask.
2154      */
2155     sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs);
2156     for (i = 0; i < sigalgslen; i++, sigalgs++) {
2157         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *sigalgs);
2158         const SSL_CERT_LOOKUP *clu;
2159 
2160         if (lu == NULL)
2161             continue;
2162 
2163         clu = ssl_cert_lookup_by_idx(lu->sig_idx);
2164         if (clu == NULL)
2165                 continue;
2166 
2167         /* If algorithm is disabled see if we can enable it */
2168         if ((clu->amask & disabled_mask) != 0
2169                 && tls12_sigalg_allowed(s, op, lu))
2170             disabled_mask &= ~clu->amask;
2171     }
2172     *pmask_a |= disabled_mask;
2173 }
2174 
2175 int tls12_copy_sigalgs(SSL *s, WPACKET *pkt,
2176                        const uint16_t *psig, size_t psiglen)
2177 {
2178     size_t i;
2179     int rv = 0;
2180 
2181     for (i = 0; i < psiglen; i++, psig++) {
2182         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *psig);
2183 
2184         if (lu == NULL
2185                 || !tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, lu))
2186             continue;
2187         if (!WPACKET_put_bytes_u16(pkt, *psig))
2188             return 0;
2189         /*
2190          * If TLS 1.3 must have at least one valid TLS 1.3 message
2191          * signing algorithm: i.e. neither RSA nor SHA1/SHA224
2192          */
2193         if (rv == 0 && (!SSL_IS_TLS13(s)
2194             || (lu->sig != EVP_PKEY_RSA
2195                 && lu->hash != NID_sha1
2196                 && lu->hash != NID_sha224)))
2197             rv = 1;
2198     }
2199     if (rv == 0)
2200         ERR_raise(ERR_LIB_SSL, SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
2201     return rv;
2202 }
2203 
2204 /* Given preference and allowed sigalgs set shared sigalgs */
2205 static size_t tls12_shared_sigalgs(SSL *s, const SIGALG_LOOKUP **shsig,
2206                                    const uint16_t *pref, size_t preflen,
2207                                    const uint16_t *allow, size_t allowlen)
2208 {
2209     const uint16_t *ptmp, *atmp;
2210     size_t i, j, nmatch = 0;
2211     for (i = 0, ptmp = pref; i < preflen; i++, ptmp++) {
2212         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *ptmp);
2213 
2214         /* Skip disabled hashes or signature algorithms */
2215         if (lu == NULL
2216                 || !tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SHARED, lu))
2217             continue;
2218         for (j = 0, atmp = allow; j < allowlen; j++, atmp++) {
2219             if (*ptmp == *atmp) {
2220                 nmatch++;
2221                 if (shsig)
2222                     *shsig++ = lu;
2223                 break;
2224             }
2225         }
2226     }
2227     return nmatch;
2228 }
2229 
2230 /* Set shared signature algorithms for SSL structures */
2231 static int tls1_set_shared_sigalgs(SSL *s)
2232 {
2233     const uint16_t *pref, *allow, *conf;
2234     size_t preflen, allowlen, conflen;
2235     size_t nmatch;
2236     const SIGALG_LOOKUP **salgs = NULL;
2237     CERT *c = s->cert;
2238     unsigned int is_suiteb = tls1_suiteb(s);
2239 
2240     OPENSSL_free(s->shared_sigalgs);
2241     s->shared_sigalgs = NULL;
2242     s->shared_sigalgslen = 0;
2243     /* If client use client signature algorithms if not NULL */
2244     if (!s->server && c->client_sigalgs && !is_suiteb) {
2245         conf = c->client_sigalgs;
2246         conflen = c->client_sigalgslen;
2247     } else if (c->conf_sigalgs && !is_suiteb) {
2248         conf = c->conf_sigalgs;
2249         conflen = c->conf_sigalgslen;
2250     } else
2251         conflen = tls12_get_psigalgs(s, 0, &conf);
2252     if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
2253         pref = conf;
2254         preflen = conflen;
2255         allow = s->s3.tmp.peer_sigalgs;
2256         allowlen = s->s3.tmp.peer_sigalgslen;
2257     } else {
2258         allow = conf;
2259         allowlen = conflen;
2260         pref = s->s3.tmp.peer_sigalgs;
2261         preflen = s->s3.tmp.peer_sigalgslen;
2262     }
2263     nmatch = tls12_shared_sigalgs(s, NULL, pref, preflen, allow, allowlen);
2264     if (nmatch) {
2265         if ((salgs = OPENSSL_malloc(nmatch * sizeof(*salgs))) == NULL) {
2266             ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
2267             return 0;
2268         }
2269         nmatch = tls12_shared_sigalgs(s, salgs, pref, preflen, allow, allowlen);
2270     } else {
2271         salgs = NULL;
2272     }
2273     s->shared_sigalgs = salgs;
2274     s->shared_sigalgslen = nmatch;
2275     return 1;
2276 }
2277 
2278 int tls1_save_u16(PACKET *pkt, uint16_t **pdest, size_t *pdestlen)
2279 {
2280     unsigned int stmp;
2281     size_t size, i;
2282     uint16_t *buf;
2283 
2284     size = PACKET_remaining(pkt);
2285 
2286     /* Invalid data length */
2287     if (size == 0 || (size & 1) != 0)
2288         return 0;
2289 
2290     size >>= 1;
2291 
2292     if ((buf = OPENSSL_malloc(size * sizeof(*buf))) == NULL)  {
2293         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
2294         return 0;
2295     }
2296     for (i = 0; i < size && PACKET_get_net_2(pkt, &stmp); i++)
2297         buf[i] = stmp;
2298 
2299     if (i != size) {
2300         OPENSSL_free(buf);
2301         return 0;
2302     }
2303 
2304     OPENSSL_free(*pdest);
2305     *pdest = buf;
2306     *pdestlen = size;
2307 
2308     return 1;
2309 }
2310 
2311 int tls1_save_sigalgs(SSL *s, PACKET *pkt, int cert)
2312 {
2313     /* Extension ignored for inappropriate versions */
2314     if (!SSL_USE_SIGALGS(s))
2315         return 1;
2316     /* Should never happen */
2317     if (s->cert == NULL)
2318         return 0;
2319 
2320     if (cert)
2321         return tls1_save_u16(pkt, &s->s3.tmp.peer_cert_sigalgs,
2322                              &s->s3.tmp.peer_cert_sigalgslen);
2323     else
2324         return tls1_save_u16(pkt, &s->s3.tmp.peer_sigalgs,
2325                              &s->s3.tmp.peer_sigalgslen);
2326 
2327 }
2328 
2329 /* Set preferred digest for each key type */
2330 
2331 int tls1_process_sigalgs(SSL *s)
2332 {
2333     size_t i;
2334     uint32_t *pvalid = s->s3.tmp.valid_flags;
2335 
2336     if (!tls1_set_shared_sigalgs(s))
2337         return 0;
2338 
2339     for (i = 0; i < SSL_PKEY_NUM; i++)
2340         pvalid[i] = 0;
2341 
2342     for (i = 0; i < s->shared_sigalgslen; i++) {
2343         const SIGALG_LOOKUP *sigptr = s->shared_sigalgs[i];
2344         int idx = sigptr->sig_idx;
2345 
2346         /* Ignore PKCS1 based sig algs in TLSv1.3 */
2347         if (SSL_IS_TLS13(s) && sigptr->sig == EVP_PKEY_RSA)
2348             continue;
2349         /* If not disabled indicate we can explicitly sign */
2350         if (pvalid[idx] == 0 && !ssl_cert_is_disabled(s->ctx, idx))
2351             pvalid[idx] = CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
2352     }
2353     return 1;
2354 }
2355 
2356 int SSL_get_sigalgs(SSL *s, int idx,
2357                     int *psign, int *phash, int *psignhash,
2358                     unsigned char *rsig, unsigned char *rhash)
2359 {
2360     uint16_t *psig = s->s3.tmp.peer_sigalgs;
2361     size_t numsigalgs = s->s3.tmp.peer_sigalgslen;
2362     if (psig == NULL || numsigalgs > INT_MAX)
2363         return 0;
2364     if (idx >= 0) {
2365         const SIGALG_LOOKUP *lu;
2366 
2367         if (idx >= (int)numsigalgs)
2368             return 0;
2369         psig += idx;
2370         if (rhash != NULL)
2371             *rhash = (unsigned char)((*psig >> 8) & 0xff);
2372         if (rsig != NULL)
2373             *rsig = (unsigned char)(*psig & 0xff);
2374         lu = tls1_lookup_sigalg(s, *psig);
2375         if (psign != NULL)
2376             *psign = lu != NULL ? lu->sig : NID_undef;
2377         if (phash != NULL)
2378             *phash = lu != NULL ? lu->hash : NID_undef;
2379         if (psignhash != NULL)
2380             *psignhash = lu != NULL ? lu->sigandhash : NID_undef;
2381     }
2382     return (int)numsigalgs;
2383 }
2384 
2385 int SSL_get_shared_sigalgs(SSL *s, int idx,
2386                            int *psign, int *phash, int *psignhash,
2387                            unsigned char *rsig, unsigned char *rhash)
2388 {
2389     const SIGALG_LOOKUP *shsigalgs;
2390     if (s->shared_sigalgs == NULL
2391         || idx < 0
2392         || idx >= (int)s->shared_sigalgslen
2393         || s->shared_sigalgslen > INT_MAX)
2394         return 0;
2395     shsigalgs = s->shared_sigalgs[idx];
2396     if (phash != NULL)
2397         *phash = shsigalgs->hash;
2398     if (psign != NULL)
2399         *psign = shsigalgs->sig;
2400     if (psignhash != NULL)
2401         *psignhash = shsigalgs->sigandhash;
2402     if (rsig != NULL)
2403         *rsig = (unsigned char)(shsigalgs->sigalg & 0xff);
2404     if (rhash != NULL)
2405         *rhash = (unsigned char)((shsigalgs->sigalg >> 8) & 0xff);
2406     return (int)s->shared_sigalgslen;
2407 }
2408 
2409 /* Maximum possible number of unique entries in sigalgs array */
2410 #define TLS_MAX_SIGALGCNT (OSSL_NELEM(sigalg_lookup_tbl) * 2)
2411 
2412 typedef struct {
2413     size_t sigalgcnt;
2414     /* TLSEXT_SIGALG_XXX values */
2415     uint16_t sigalgs[TLS_MAX_SIGALGCNT];
2416 } sig_cb_st;
2417 
2418 static void get_sigorhash(int *psig, int *phash, const char *str)
2419 {
2420     if (strcmp(str, "RSA") == 0) {
2421         *psig = EVP_PKEY_RSA;
2422     } else if (strcmp(str, "RSA-PSS") == 0 || strcmp(str, "PSS") == 0) {
2423         *psig = EVP_PKEY_RSA_PSS;
2424     } else if (strcmp(str, "DSA") == 0) {
2425         *psig = EVP_PKEY_DSA;
2426     } else if (strcmp(str, "ECDSA") == 0) {
2427         *psig = EVP_PKEY_EC;
2428     } else {
2429         *phash = OBJ_sn2nid(str);
2430         if (*phash == NID_undef)
2431             *phash = OBJ_ln2nid(str);
2432     }
2433 }
2434 /* Maximum length of a signature algorithm string component */
2435 #define TLS_MAX_SIGSTRING_LEN   40
2436 
2437 static int sig_cb(const char *elem, int len, void *arg)
2438 {
2439     sig_cb_st *sarg = arg;
2440     size_t i;
2441     const SIGALG_LOOKUP *s;
2442     char etmp[TLS_MAX_SIGSTRING_LEN], *p;
2443     int sig_alg = NID_undef, hash_alg = NID_undef;
2444     if (elem == NULL)
2445         return 0;
2446     if (sarg->sigalgcnt == TLS_MAX_SIGALGCNT)
2447         return 0;
2448     if (len > (int)(sizeof(etmp) - 1))
2449         return 0;
2450     memcpy(etmp, elem, len);
2451     etmp[len] = 0;
2452     p = strchr(etmp, '+');
2453     /*
2454      * We only allow SignatureSchemes listed in the sigalg_lookup_tbl;
2455      * if there's no '+' in the provided name, look for the new-style combined
2456      * name.  If not, match both sig+hash to find the needed SIGALG_LOOKUP.
2457      * Just sig+hash is not unique since TLS 1.3 adds rsa_pss_pss_* and
2458      * rsa_pss_rsae_* that differ only by public key OID; in such cases
2459      * we will pick the _rsae_ variant, by virtue of them appearing earlier
2460      * in the table.
2461      */
2462     if (p == NULL) {
2463         for (i = 0, s = sigalg_lookup_tbl; i < OSSL_NELEM(sigalg_lookup_tbl);
2464              i++, s++) {
2465             if (s->name != NULL && strcmp(etmp, s->name) == 0) {
2466                 sarg->sigalgs[sarg->sigalgcnt++] = s->sigalg;
2467                 break;
2468             }
2469         }
2470         if (i == OSSL_NELEM(sigalg_lookup_tbl))
2471             return 0;
2472     } else {
2473         *p = 0;
2474         p++;
2475         if (*p == 0)
2476             return 0;
2477         get_sigorhash(&sig_alg, &hash_alg, etmp);
2478         get_sigorhash(&sig_alg, &hash_alg, p);
2479         if (sig_alg == NID_undef || hash_alg == NID_undef)
2480             return 0;
2481         for (i = 0, s = sigalg_lookup_tbl; i < OSSL_NELEM(sigalg_lookup_tbl);
2482              i++, s++) {
2483             if (s->hash == hash_alg && s->sig == sig_alg) {
2484                 sarg->sigalgs[sarg->sigalgcnt++] = s->sigalg;
2485                 break;
2486             }
2487         }
2488         if (i == OSSL_NELEM(sigalg_lookup_tbl))
2489             return 0;
2490     }
2491 
2492     /* Reject duplicates */
2493     for (i = 0; i < sarg->sigalgcnt - 1; i++) {
2494         if (sarg->sigalgs[i] == sarg->sigalgs[sarg->sigalgcnt - 1]) {
2495             sarg->sigalgcnt--;
2496             return 0;
2497         }
2498     }
2499     return 1;
2500 }
2501 
2502 /*
2503  * Set supported signature algorithms based on a colon separated list of the
2504  * form sig+hash e.g. RSA+SHA512:DSA+SHA512
2505  */
2506 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
2507 {
2508     sig_cb_st sig;
2509     sig.sigalgcnt = 0;
2510     if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
2511         return 0;
2512     if (c == NULL)
2513         return 1;
2514     return tls1_set_raw_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
2515 }
2516 
2517 int tls1_set_raw_sigalgs(CERT *c, const uint16_t *psigs, size_t salglen,
2518                      int client)
2519 {
2520     uint16_t *sigalgs;
2521 
2522     if ((sigalgs = OPENSSL_malloc(salglen * sizeof(*sigalgs))) == NULL) {
2523         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
2524         return 0;
2525     }
2526     memcpy(sigalgs, psigs, salglen * sizeof(*sigalgs));
2527 
2528     if (client) {
2529         OPENSSL_free(c->client_sigalgs);
2530         c->client_sigalgs = sigalgs;
2531         c->client_sigalgslen = salglen;
2532     } else {
2533         OPENSSL_free(c->conf_sigalgs);
2534         c->conf_sigalgs = sigalgs;
2535         c->conf_sigalgslen = salglen;
2536     }
2537 
2538     return 1;
2539 }
2540 
2541 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
2542 {
2543     uint16_t *sigalgs, *sptr;
2544     size_t i;
2545 
2546     if (salglen & 1)
2547         return 0;
2548     if ((sigalgs = OPENSSL_malloc((salglen / 2) * sizeof(*sigalgs))) == NULL) {
2549         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
2550         return 0;
2551     }
2552     for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
2553         size_t j;
2554         const SIGALG_LOOKUP *curr;
2555         int md_id = *psig_nids++;
2556         int sig_id = *psig_nids++;
2557 
2558         for (j = 0, curr = sigalg_lookup_tbl; j < OSSL_NELEM(sigalg_lookup_tbl);
2559              j++, curr++) {
2560             if (curr->hash == md_id && curr->sig == sig_id) {
2561                 *sptr++ = curr->sigalg;
2562                 break;
2563             }
2564         }
2565 
2566         if (j == OSSL_NELEM(sigalg_lookup_tbl))
2567             goto err;
2568     }
2569 
2570     if (client) {
2571         OPENSSL_free(c->client_sigalgs);
2572         c->client_sigalgs = sigalgs;
2573         c->client_sigalgslen = salglen / 2;
2574     } else {
2575         OPENSSL_free(c->conf_sigalgs);
2576         c->conf_sigalgs = sigalgs;
2577         c->conf_sigalgslen = salglen / 2;
2578     }
2579 
2580     return 1;
2581 
2582  err:
2583     OPENSSL_free(sigalgs);
2584     return 0;
2585 }
2586 
2587 static int tls1_check_sig_alg(SSL *s, X509 *x, int default_nid)
2588 {
2589     int sig_nid, use_pc_sigalgs = 0;
2590     size_t i;
2591     const SIGALG_LOOKUP *sigalg;
2592     size_t sigalgslen;
2593     if (default_nid == -1)
2594         return 1;
2595     sig_nid = X509_get_signature_nid(x);
2596     if (default_nid)
2597         return sig_nid == default_nid ? 1 : 0;
2598 
2599     if (SSL_IS_TLS13(s) && s->s3.tmp.peer_cert_sigalgs != NULL) {
2600         /*
2601          * If we're in TLSv1.3 then we only get here if we're checking the
2602          * chain. If the peer has specified peer_cert_sigalgs then we use them
2603          * otherwise we default to normal sigalgs.
2604          */
2605         sigalgslen = s->s3.tmp.peer_cert_sigalgslen;
2606         use_pc_sigalgs = 1;
2607     } else {
2608         sigalgslen = s->shared_sigalgslen;
2609     }
2610     for (i = 0; i < sigalgslen; i++) {
2611         sigalg = use_pc_sigalgs
2612                  ? tls1_lookup_sigalg(s, s->s3.tmp.peer_cert_sigalgs[i])
2613                  : s->shared_sigalgs[i];
2614         if (sigalg != NULL && sig_nid == sigalg->sigandhash)
2615             return 1;
2616     }
2617     return 0;
2618 }
2619 
2620 /* Check to see if a certificate issuer name matches list of CA names */
2621 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
2622 {
2623     const X509_NAME *nm;
2624     int i;
2625     nm = X509_get_issuer_name(x);
2626     for (i = 0; i < sk_X509_NAME_num(names); i++) {
2627         if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
2628             return 1;
2629     }
2630     return 0;
2631 }
2632 
2633 /*
2634  * Check certificate chain is consistent with TLS extensions and is usable by
2635  * server. This servers two purposes: it allows users to check chains before
2636  * passing them to the server and it allows the server to check chains before
2637  * attempting to use them.
2638  */
2639 
2640 /* Flags which need to be set for a certificate when strict mode not set */
2641 
2642 #define CERT_PKEY_VALID_FLAGS \
2643         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
2644 /* Strict mode flags */
2645 #define CERT_PKEY_STRICT_FLAGS \
2646          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
2647          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
2648 
2649 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
2650                      int idx)
2651 {
2652     int i;
2653     int rv = 0;
2654     int check_flags = 0, strict_mode;
2655     CERT_PKEY *cpk = NULL;
2656     CERT *c = s->cert;
2657     uint32_t *pvalid;
2658     unsigned int suiteb_flags = tls1_suiteb(s);
2659     /* idx == -1 means checking server chains */
2660     if (idx != -1) {
2661         /* idx == -2 means checking client certificate chains */
2662         if (idx == -2) {
2663             cpk = c->key;
2664             idx = (int)(cpk - c->pkeys);
2665         } else
2666             cpk = c->pkeys + idx;
2667         pvalid = s->s3.tmp.valid_flags + idx;
2668         x = cpk->x509;
2669         pk = cpk->privatekey;
2670         chain = cpk->chain;
2671         strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
2672         /* If no cert or key, forget it */
2673         if (!x || !pk)
2674             goto end;
2675     } else {
2676         size_t certidx;
2677 
2678         if (!x || !pk)
2679             return 0;
2680 
2681         if (ssl_cert_lookup_by_pkey(pk, &certidx) == NULL)
2682             return 0;
2683         idx = certidx;
2684         pvalid = s->s3.tmp.valid_flags + idx;
2685 
2686         if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
2687             check_flags = CERT_PKEY_STRICT_FLAGS;
2688         else
2689             check_flags = CERT_PKEY_VALID_FLAGS;
2690         strict_mode = 1;
2691     }
2692 
2693     if (suiteb_flags) {
2694         int ok;
2695         if (check_flags)
2696             check_flags |= CERT_PKEY_SUITEB;
2697         ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
2698         if (ok == X509_V_OK)
2699             rv |= CERT_PKEY_SUITEB;
2700         else if (!check_flags)
2701             goto end;
2702     }
2703 
2704     /*
2705      * Check all signature algorithms are consistent with signature
2706      * algorithms extension if TLS 1.2 or later and strict mode.
2707      */
2708     if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
2709         int default_nid;
2710         int rsign = 0;
2711         if (s->s3.tmp.peer_cert_sigalgs != NULL
2712                 || s->s3.tmp.peer_sigalgs != NULL) {
2713             default_nid = 0;
2714         /* If no sigalgs extension use defaults from RFC5246 */
2715         } else {
2716             switch (idx) {
2717             case SSL_PKEY_RSA:
2718                 rsign = EVP_PKEY_RSA;
2719                 default_nid = NID_sha1WithRSAEncryption;
2720                 break;
2721 
2722             case SSL_PKEY_DSA_SIGN:
2723                 rsign = EVP_PKEY_DSA;
2724                 default_nid = NID_dsaWithSHA1;
2725                 break;
2726 
2727             case SSL_PKEY_ECC:
2728                 rsign = EVP_PKEY_EC;
2729                 default_nid = NID_ecdsa_with_SHA1;
2730                 break;
2731 
2732             case SSL_PKEY_GOST01:
2733                 rsign = NID_id_GostR3410_2001;
2734                 default_nid = NID_id_GostR3411_94_with_GostR3410_2001;
2735                 break;
2736 
2737             case SSL_PKEY_GOST12_256:
2738                 rsign = NID_id_GostR3410_2012_256;
2739                 default_nid = NID_id_tc26_signwithdigest_gost3410_2012_256;
2740                 break;
2741 
2742             case SSL_PKEY_GOST12_512:
2743                 rsign = NID_id_GostR3410_2012_512;
2744                 default_nid = NID_id_tc26_signwithdigest_gost3410_2012_512;
2745                 break;
2746 
2747             default:
2748                 default_nid = -1;
2749                 break;
2750             }
2751         }
2752         /*
2753          * If peer sent no signature algorithms extension and we have set
2754          * preferred signature algorithms check we support sha1.
2755          */
2756         if (default_nid > 0 && c->conf_sigalgs) {
2757             size_t j;
2758             const uint16_t *p = c->conf_sigalgs;
2759             for (j = 0; j < c->conf_sigalgslen; j++, p++) {
2760                 const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(s, *p);
2761 
2762                 if (lu != NULL && lu->hash == NID_sha1 && lu->sig == rsign)
2763                     break;
2764             }
2765             if (j == c->conf_sigalgslen) {
2766                 if (check_flags)
2767                     goto skip_sigs;
2768                 else
2769                     goto end;
2770             }
2771         }
2772         /* Check signature algorithm of each cert in chain */
2773         if (SSL_IS_TLS13(s)) {
2774             /*
2775              * We only get here if the application has called SSL_check_chain(),
2776              * so check_flags is always set.
2777              */
2778             if (find_sig_alg(s, x, pk) != NULL)
2779                 rv |= CERT_PKEY_EE_SIGNATURE;
2780         } else if (!tls1_check_sig_alg(s, x, default_nid)) {
2781             if (!check_flags)
2782                 goto end;
2783         } else
2784             rv |= CERT_PKEY_EE_SIGNATURE;
2785         rv |= CERT_PKEY_CA_SIGNATURE;
2786         for (i = 0; i < sk_X509_num(chain); i++) {
2787             if (!tls1_check_sig_alg(s, sk_X509_value(chain, i), default_nid)) {
2788                 if (check_flags) {
2789                     rv &= ~CERT_PKEY_CA_SIGNATURE;
2790                     break;
2791                 } else
2792                     goto end;
2793             }
2794         }
2795     }
2796     /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
2797     else if (check_flags)
2798         rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
2799  skip_sigs:
2800     /* Check cert parameters are consistent */
2801     if (tls1_check_cert_param(s, x, 1))
2802         rv |= CERT_PKEY_EE_PARAM;
2803     else if (!check_flags)
2804         goto end;
2805     if (!s->server)
2806         rv |= CERT_PKEY_CA_PARAM;
2807     /* In strict mode check rest of chain too */
2808     else if (strict_mode) {
2809         rv |= CERT_PKEY_CA_PARAM;
2810         for (i = 0; i < sk_X509_num(chain); i++) {
2811             X509 *ca = sk_X509_value(chain, i);
2812             if (!tls1_check_cert_param(s, ca, 0)) {
2813                 if (check_flags) {
2814                     rv &= ~CERT_PKEY_CA_PARAM;
2815                     break;
2816                 } else
2817                     goto end;
2818             }
2819         }
2820     }
2821     if (!s->server && strict_mode) {
2822         STACK_OF(X509_NAME) *ca_dn;
2823         int check_type = 0;
2824 
2825         if (EVP_PKEY_is_a(pk, "RSA"))
2826             check_type = TLS_CT_RSA_SIGN;
2827         else if (EVP_PKEY_is_a(pk, "DSA"))
2828             check_type = TLS_CT_DSS_SIGN;
2829         else if (EVP_PKEY_is_a(pk, "EC"))
2830             check_type = TLS_CT_ECDSA_SIGN;
2831 
2832         if (check_type) {
2833             const uint8_t *ctypes = s->s3.tmp.ctype;
2834             size_t j;
2835 
2836             for (j = 0; j < s->s3.tmp.ctype_len; j++, ctypes++) {
2837                 if (*ctypes == check_type) {
2838                     rv |= CERT_PKEY_CERT_TYPE;
2839                     break;
2840                 }
2841             }
2842             if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
2843                 goto end;
2844         } else {
2845             rv |= CERT_PKEY_CERT_TYPE;
2846         }
2847 
2848         ca_dn = s->s3.tmp.peer_ca_names;
2849 
2850         if (ca_dn == NULL
2851             || sk_X509_NAME_num(ca_dn) == 0
2852             || ssl_check_ca_name(ca_dn, x))
2853             rv |= CERT_PKEY_ISSUER_NAME;
2854         else
2855             for (i = 0; i < sk_X509_num(chain); i++) {
2856                 X509 *xtmp = sk_X509_value(chain, i);
2857 
2858                 if (ssl_check_ca_name(ca_dn, xtmp)) {
2859                     rv |= CERT_PKEY_ISSUER_NAME;
2860                     break;
2861                 }
2862             }
2863 
2864         if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
2865             goto end;
2866     } else
2867         rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
2868 
2869     if (!check_flags || (rv & check_flags) == check_flags)
2870         rv |= CERT_PKEY_VALID;
2871 
2872  end:
2873 
2874     if (TLS1_get_version(s) >= TLS1_2_VERSION)
2875         rv |= *pvalid & (CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN);
2876     else
2877         rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
2878 
2879     /*
2880      * When checking a CERT_PKEY structure all flags are irrelevant if the
2881      * chain is invalid.
2882      */
2883     if (!check_flags) {
2884         if (rv & CERT_PKEY_VALID) {
2885             *pvalid = rv;
2886         } else {
2887             /* Preserve sign and explicit sign flag, clear rest */
2888             *pvalid &= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
2889             return 0;
2890         }
2891     }
2892     return rv;
2893 }
2894 
2895 /* Set validity of certificates in an SSL structure */
2896 void tls1_set_cert_validity(SSL *s)
2897 {
2898     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA);
2899     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_PSS_SIGN);
2900     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
2901     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
2902     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST01);
2903     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_256);
2904     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_512);
2905     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ED25519);
2906     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ED448);
2907 }
2908 
2909 /* User level utility function to check a chain is suitable */
2910 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
2911 {
2912     return tls1_check_chain(s, x, pk, chain, -1);
2913 }
2914 
2915 EVP_PKEY *ssl_get_auto_dh(SSL *s)
2916 {
2917     EVP_PKEY *dhp = NULL;
2918     BIGNUM *p;
2919     int dh_secbits = 80, sec_level_bits;
2920     EVP_PKEY_CTX *pctx = NULL;
2921     OSSL_PARAM_BLD *tmpl = NULL;
2922     OSSL_PARAM *params = NULL;
2923 
2924     if (s->cert->dh_tmp_auto != 2) {
2925         if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aPSK)) {
2926             if (s->s3.tmp.new_cipher->strength_bits == 256)
2927                 dh_secbits = 128;
2928             else
2929                 dh_secbits = 80;
2930         } else {
2931             if (s->s3.tmp.cert == NULL)
2932                 return NULL;
2933             dh_secbits = EVP_PKEY_get_security_bits(s->s3.tmp.cert->privatekey);
2934         }
2935     }
2936 
2937     /* Do not pick a prime that is too weak for the current security level */
2938     sec_level_bits = ssl_get_security_level_bits(s, NULL, NULL);
2939     if (dh_secbits < sec_level_bits)
2940         dh_secbits = sec_level_bits;
2941 
2942     if (dh_secbits >= 192)
2943         p = BN_get_rfc3526_prime_8192(NULL);
2944     else if (dh_secbits >= 152)
2945         p = BN_get_rfc3526_prime_4096(NULL);
2946     else if (dh_secbits >= 128)
2947         p = BN_get_rfc3526_prime_3072(NULL);
2948     else if (dh_secbits >= 112)
2949         p = BN_get_rfc3526_prime_2048(NULL);
2950     else
2951         p = BN_get_rfc2409_prime_1024(NULL);
2952     if (p == NULL)
2953         goto err;
2954 
2955     pctx = EVP_PKEY_CTX_new_from_name(s->ctx->libctx, "DH", s->ctx->propq);
2956     if (pctx == NULL
2957             || EVP_PKEY_fromdata_init(pctx) != 1)
2958         goto err;
2959 
2960     tmpl = OSSL_PARAM_BLD_new();
2961     if (tmpl == NULL
2962             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2963             || !OSSL_PARAM_BLD_push_uint(tmpl, OSSL_PKEY_PARAM_FFC_G, 2))
2964         goto err;
2965 
2966     params = OSSL_PARAM_BLD_to_param(tmpl);
2967     if (params == NULL
2968             || EVP_PKEY_fromdata(pctx, &dhp, EVP_PKEY_KEY_PARAMETERS, params) != 1)
2969         goto err;
2970 
2971 err:
2972     OSSL_PARAM_free(params);
2973     OSSL_PARAM_BLD_free(tmpl);
2974     EVP_PKEY_CTX_free(pctx);
2975     BN_free(p);
2976     return dhp;
2977 }
2978 
2979 static int ssl_security_cert_key(SSL *s, SSL_CTX *ctx, X509 *x, int op)
2980 {
2981     int secbits = -1;
2982     EVP_PKEY *pkey = X509_get0_pubkey(x);
2983     if (pkey) {
2984         /*
2985          * If no parameters this will return -1 and fail using the default
2986          * security callback for any non-zero security level. This will
2987          * reject keys which omit parameters but this only affects DSA and
2988          * omission of parameters is never (?) done in practice.
2989          */
2990         secbits = EVP_PKEY_get_security_bits(pkey);
2991     }
2992     if (s)
2993         return ssl_security(s, op, secbits, 0, x);
2994     else
2995         return ssl_ctx_security(ctx, op, secbits, 0, x);
2996 }
2997 
2998 static int ssl_security_cert_sig(SSL *s, SSL_CTX *ctx, X509 *x, int op)
2999 {
3000     /* Lookup signature algorithm digest */
3001     int secbits, nid, pknid;
3002     /* Don't check signature if self signed */
3003     if ((X509_get_extension_flags(x) & EXFLAG_SS) != 0)
3004         return 1;
3005     if (!X509_get_signature_info(x, &nid, &pknid, &secbits, NULL))
3006         secbits = -1;
3007     /* If digest NID not defined use signature NID */
3008     if (nid == NID_undef)
3009         nid = pknid;
3010     if (s)
3011         return ssl_security(s, op, secbits, nid, x);
3012     else
3013         return ssl_ctx_security(ctx, op, secbits, nid, x);
3014 }
3015 
3016 int ssl_security_cert(SSL *s, SSL_CTX *ctx, X509 *x, int vfy, int is_ee)
3017 {
3018     if (vfy)
3019         vfy = SSL_SECOP_PEER;
3020     if (is_ee) {
3021         if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_EE_KEY | vfy))
3022             return SSL_R_EE_KEY_TOO_SMALL;
3023     } else {
3024         if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_CA_KEY | vfy))
3025             return SSL_R_CA_KEY_TOO_SMALL;
3026     }
3027     if (!ssl_security_cert_sig(s, ctx, x, SSL_SECOP_CA_MD | vfy))
3028         return SSL_R_CA_MD_TOO_WEAK;
3029     return 1;
3030 }
3031 
3032 /*
3033  * Check security of a chain, if |sk| includes the end entity certificate then
3034  * |x| is NULL. If |vfy| is 1 then we are verifying a peer chain and not sending
3035  * one to the peer. Return values: 1 if ok otherwise error code to use
3036  */
3037 
3038 int ssl_security_cert_chain(SSL *s, STACK_OF(X509) *sk, X509 *x, int vfy)
3039 {
3040     int rv, start_idx, i;
3041     if (x == NULL) {
3042         x = sk_X509_value(sk, 0);
3043         if (x == NULL)
3044             return ERR_R_INTERNAL_ERROR;
3045         start_idx = 1;
3046     } else
3047         start_idx = 0;
3048 
3049     rv = ssl_security_cert(s, NULL, x, vfy, 1);
3050     if (rv != 1)
3051         return rv;
3052 
3053     for (i = start_idx; i < sk_X509_num(sk); i++) {
3054         x = sk_X509_value(sk, i);
3055         rv = ssl_security_cert(s, NULL, x, vfy, 0);
3056         if (rv != 1)
3057             return rv;
3058     }
3059     return 1;
3060 }
3061 
3062 /*
3063  * For TLS 1.2 servers check if we have a certificate which can be used
3064  * with the signature algorithm "lu" and return index of certificate.
3065  */
3066 
3067 static int tls12_get_cert_sigalg_idx(const SSL *s, const SIGALG_LOOKUP *lu)
3068 {
3069     int sig_idx = lu->sig_idx;
3070     const SSL_CERT_LOOKUP *clu = ssl_cert_lookup_by_idx(sig_idx);
3071 
3072     /* If not recognised or not supported by cipher mask it is not suitable */
3073     if (clu == NULL
3074             || (clu->amask & s->s3.tmp.new_cipher->algorithm_auth) == 0
3075             || (clu->nid == EVP_PKEY_RSA_PSS
3076                 && (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kRSA) != 0))
3077         return -1;
3078 
3079     return s->s3.tmp.valid_flags[sig_idx] & CERT_PKEY_VALID ? sig_idx : -1;
3080 }
3081 
3082 /*
3083  * Checks the given cert against signature_algorithm_cert restrictions sent by
3084  * the peer (if any) as well as whether the hash from the sigalg is usable with
3085  * the key.
3086  * Returns true if the cert is usable and false otherwise.
3087  */
3088 static int check_cert_usable(SSL *s, const SIGALG_LOOKUP *sig, X509 *x,
3089                              EVP_PKEY *pkey)
3090 {
3091     const SIGALG_LOOKUP *lu;
3092     int mdnid, pknid, supported;
3093     size_t i;
3094     const char *mdname = NULL;
3095 
3096     /*
3097      * If the given EVP_PKEY cannot support signing with this digest,
3098      * the answer is simply 'no'.
3099      */
3100     if (sig->hash != NID_undef)
3101         mdname = OBJ_nid2sn(sig->hash);
3102     supported = EVP_PKEY_digestsign_supports_digest(pkey, s->ctx->libctx,
3103                                                     mdname,
3104                                                     s->ctx->propq);
3105     if (supported <= 0)
3106         return 0;
3107 
3108     /*
3109      * The TLS 1.3 signature_algorithms_cert extension places restrictions
3110      * on the sigalg with which the certificate was signed (by its issuer).
3111      */
3112     if (s->s3.tmp.peer_cert_sigalgs != NULL) {
3113         if (!X509_get_signature_info(x, &mdnid, &pknid, NULL, NULL))
3114             return 0;
3115         for (i = 0; i < s->s3.tmp.peer_cert_sigalgslen; i++) {
3116             lu = tls1_lookup_sigalg(s, s->s3.tmp.peer_cert_sigalgs[i]);
3117             if (lu == NULL)
3118                 continue;
3119 
3120             /*
3121              * This does not differentiate between the
3122              * rsa_pss_pss_* and rsa_pss_rsae_* schemes since we do not
3123              * have a chain here that lets us look at the key OID in the
3124              * signing certificate.
3125              */
3126             if (mdnid == lu->hash && pknid == lu->sig)
3127                 return 1;
3128         }
3129         return 0;
3130     }
3131 
3132     /*
3133      * Without signat_algorithms_cert, any certificate for which we have
3134      * a viable public key is permitted.
3135      */
3136     return 1;
3137 }
3138 
3139 /*
3140  * Returns true if |s| has a usable certificate configured for use
3141  * with signature scheme |sig|.
3142  * "Usable" includes a check for presence as well as applying
3143  * the signature_algorithm_cert restrictions sent by the peer (if any).
3144  * Returns false if no usable certificate is found.
3145  */
3146 static int has_usable_cert(SSL *s, const SIGALG_LOOKUP *sig, int idx)
3147 {
3148     /* TLS 1.2 callers can override sig->sig_idx, but not TLS 1.3 callers. */
3149     if (idx == -1)
3150         idx = sig->sig_idx;
3151     if (!ssl_has_cert(s, idx))
3152         return 0;
3153 
3154     return check_cert_usable(s, sig, s->cert->pkeys[idx].x509,
3155                              s->cert->pkeys[idx].privatekey);
3156 }
3157 
3158 /*
3159  * Returns true if the supplied cert |x| and key |pkey| is usable with the
3160  * specified signature scheme |sig|, or false otherwise.
3161  */
3162 static int is_cert_usable(SSL *s, const SIGALG_LOOKUP *sig, X509 *x,
3163                           EVP_PKEY *pkey)
3164 {
3165     size_t idx;
3166 
3167     if (ssl_cert_lookup_by_pkey(pkey, &idx) == NULL)
3168         return 0;
3169 
3170     /* Check the key is consistent with the sig alg */
3171     if ((int)idx != sig->sig_idx)
3172         return 0;
3173 
3174     return check_cert_usable(s, sig, x, pkey);
3175 }
3176 
3177 /*
3178  * Find a signature scheme that works with the supplied certificate |x| and key
3179  * |pkey|. |x| and |pkey| may be NULL in which case we additionally look at our
3180  * available certs/keys to find one that works.
3181  */
3182 static const SIGALG_LOOKUP *find_sig_alg(SSL *s, X509 *x, EVP_PKEY *pkey)
3183 {
3184     const SIGALG_LOOKUP *lu = NULL;
3185     size_t i;
3186     int curve = -1;
3187     EVP_PKEY *tmppkey;
3188 
3189     /* Look for a shared sigalgs matching possible certificates */
3190     for (i = 0; i < s->shared_sigalgslen; i++) {
3191         lu = s->shared_sigalgs[i];
3192 
3193         /* Skip SHA1, SHA224, DSA and RSA if not PSS */
3194         if (lu->hash == NID_sha1
3195             || lu->hash == NID_sha224
3196             || lu->sig == EVP_PKEY_DSA
3197             || lu->sig == EVP_PKEY_RSA)
3198             continue;
3199         /* Check that we have a cert, and signature_algorithms_cert */
3200         if (!tls1_lookup_md(s->ctx, lu, NULL))
3201             continue;
3202         if ((pkey == NULL && !has_usable_cert(s, lu, -1))
3203                 || (pkey != NULL && !is_cert_usable(s, lu, x, pkey)))
3204             continue;
3205 
3206         tmppkey = (pkey != NULL) ? pkey
3207                                  : s->cert->pkeys[lu->sig_idx].privatekey;
3208 
3209         if (lu->sig == EVP_PKEY_EC) {
3210             if (curve == -1)
3211                 curve = ssl_get_EC_curve_nid(tmppkey);
3212             if (lu->curve != NID_undef && curve != lu->curve)
3213                 continue;
3214         } else if (lu->sig == EVP_PKEY_RSA_PSS) {
3215             /* validate that key is large enough for the signature algorithm */
3216             if (!rsa_pss_check_min_key_size(s->ctx, tmppkey, lu))
3217                 continue;
3218         }
3219         break;
3220     }
3221 
3222     if (i == s->shared_sigalgslen)
3223         return NULL;
3224 
3225     return lu;
3226 }
3227 
3228 /*
3229  * Choose an appropriate signature algorithm based on available certificates
3230  * Sets chosen certificate and signature algorithm.
3231  *
3232  * For servers if we fail to find a required certificate it is a fatal error,
3233  * an appropriate error code is set and a TLS alert is sent.
3234  *
3235  * For clients fatalerrs is set to 0. If a certificate is not suitable it is not
3236  * a fatal error: we will either try another certificate or not present one
3237  * to the server. In this case no error is set.
3238  */
3239 int tls_choose_sigalg(SSL *s, int fatalerrs)
3240 {
3241     const SIGALG_LOOKUP *lu = NULL;
3242     int sig_idx = -1;
3243 
3244     s->s3.tmp.cert = NULL;
3245     s->s3.tmp.sigalg = NULL;
3246 
3247     if (SSL_IS_TLS13(s)) {
3248         lu = find_sig_alg(s, NULL, NULL);
3249         if (lu == NULL) {
3250             if (!fatalerrs)
3251                 return 1;
3252             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3253                      SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
3254             return 0;
3255         }
3256     } else {
3257         /* If ciphersuite doesn't require a cert nothing to do */
3258         if (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aCERT))
3259             return 1;
3260         if (!s->server && !ssl_has_cert(s, s->cert->key - s->cert->pkeys))
3261                 return 1;
3262 
3263         if (SSL_USE_SIGALGS(s)) {
3264             size_t i;
3265             if (s->s3.tmp.peer_sigalgs != NULL) {
3266                 int curve = -1;
3267 
3268                 /* For Suite B need to match signature algorithm to curve */
3269                 if (tls1_suiteb(s))
3270                     curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC]
3271                                                  .privatekey);
3272 
3273                 /*
3274                  * Find highest preference signature algorithm matching
3275                  * cert type
3276                  */
3277                 for (i = 0; i < s->shared_sigalgslen; i++) {
3278                     lu = s->shared_sigalgs[i];
3279 
3280                     if (s->server) {
3281                         if ((sig_idx = tls12_get_cert_sigalg_idx(s, lu)) == -1)
3282                             continue;
3283                     } else {
3284                         int cc_idx = s->cert->key - s->cert->pkeys;
3285 
3286                         sig_idx = lu->sig_idx;
3287                         if (cc_idx != sig_idx)
3288                             continue;
3289                     }
3290                     /* Check that we have a cert, and sig_algs_cert */
3291                     if (!has_usable_cert(s, lu, sig_idx))
3292                         continue;
3293                     if (lu->sig == EVP_PKEY_RSA_PSS) {
3294                         /* validate that key is large enough for the signature algorithm */
3295                         EVP_PKEY *pkey = s->cert->pkeys[sig_idx].privatekey;
3296 
3297                         if (!rsa_pss_check_min_key_size(s->ctx, pkey, lu))
3298                             continue;
3299                     }
3300                     if (curve == -1 || lu->curve == curve)
3301                         break;
3302                 }
3303 #ifndef OPENSSL_NO_GOST
3304                 /*
3305                  * Some Windows-based implementations do not send GOST algorithms indication
3306                  * in supported_algorithms extension, so when we have GOST-based ciphersuite,
3307                  * we have to assume GOST support.
3308                  */
3309                 if (i == s->shared_sigalgslen && s->s3.tmp.new_cipher->algorithm_auth & (SSL_aGOST01 | SSL_aGOST12)) {
3310                   if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
3311                     if (!fatalerrs)
3312                       return 1;
3313                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3314                              SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
3315                     return 0;
3316                   } else {
3317                     i = 0;
3318                     sig_idx = lu->sig_idx;
3319                   }
3320                 }
3321 #endif
3322                 if (i == s->shared_sigalgslen) {
3323                     if (!fatalerrs)
3324                         return 1;
3325                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3326                              SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
3327                     return 0;
3328                 }
3329             } else {
3330                 /*
3331                  * If we have no sigalg use defaults
3332                  */
3333                 const uint16_t *sent_sigs;
3334                 size_t sent_sigslen;
3335 
3336                 if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
3337                     if (!fatalerrs)
3338                         return 1;
3339                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3340                              SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
3341                     return 0;
3342                 }
3343 
3344                 /* Check signature matches a type we sent */
3345                 sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
3346                 for (i = 0; i < sent_sigslen; i++, sent_sigs++) {
3347                     if (lu->sigalg == *sent_sigs
3348                             && has_usable_cert(s, lu, lu->sig_idx))
3349                         break;
3350                 }
3351                 if (i == sent_sigslen) {
3352                     if (!fatalerrs)
3353                         return 1;
3354                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3355                              SSL_R_WRONG_SIGNATURE_TYPE);
3356                     return 0;
3357                 }
3358             }
3359         } else {
3360             if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
3361                 if (!fatalerrs)
3362                     return 1;
3363                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3364                          SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
3365                 return 0;
3366             }
3367         }
3368     }
3369     if (sig_idx == -1)
3370         sig_idx = lu->sig_idx;
3371     s->s3.tmp.cert = &s->cert->pkeys[sig_idx];
3372     s->cert->key = s->s3.tmp.cert;
3373     s->s3.tmp.sigalg = lu;
3374     return 1;
3375 }
3376 
3377 int SSL_CTX_set_tlsext_max_fragment_length(SSL_CTX *ctx, uint8_t mode)
3378 {
3379     if (mode != TLSEXT_max_fragment_length_DISABLED
3380             && !IS_MAX_FRAGMENT_LENGTH_EXT_VALID(mode)) {
3381         ERR_raise(ERR_LIB_SSL, SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
3382         return 0;
3383     }
3384 
3385     ctx->ext.max_fragment_len_mode = mode;
3386     return 1;
3387 }
3388 
3389 int SSL_set_tlsext_max_fragment_length(SSL *ssl, uint8_t mode)
3390 {
3391     if (mode != TLSEXT_max_fragment_length_DISABLED
3392             && !IS_MAX_FRAGMENT_LENGTH_EXT_VALID(mode)) {
3393         ERR_raise(ERR_LIB_SSL, SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
3394         return 0;
3395     }
3396 
3397     ssl->ext.max_fragment_len_mode = mode;
3398     return 1;
3399 }
3400 
3401 uint8_t SSL_SESSION_get_max_fragment_length(const SSL_SESSION *session)
3402 {
3403     return session->ext.max_fragment_len_mode;
3404 }
3405 
3406 /*
3407  * Helper functions for HMAC access with legacy support included.
3408  */
3409 SSL_HMAC *ssl_hmac_new(const SSL_CTX *ctx)
3410 {
3411     SSL_HMAC *ret = OPENSSL_zalloc(sizeof(*ret));
3412     EVP_MAC *mac = NULL;
3413 
3414     if (ret == NULL)
3415         return NULL;
3416 #ifndef OPENSSL_NO_DEPRECATED_3_0
3417     if (ctx->ext.ticket_key_evp_cb == NULL
3418             && ctx->ext.ticket_key_cb != NULL) {
3419         if (!ssl_hmac_old_new(ret))
3420             goto err;
3421         return ret;
3422     }
3423 #endif
3424     mac = EVP_MAC_fetch(ctx->libctx, "HMAC", ctx->propq);
3425     if (mac == NULL || (ret->ctx = EVP_MAC_CTX_new(mac)) == NULL)
3426         goto err;
3427     EVP_MAC_free(mac);
3428     return ret;
3429  err:
3430     EVP_MAC_CTX_free(ret->ctx);
3431     EVP_MAC_free(mac);
3432     OPENSSL_free(ret);
3433     return NULL;
3434 }
3435 
3436 void ssl_hmac_free(SSL_HMAC *ctx)
3437 {
3438     if (ctx != NULL) {
3439         EVP_MAC_CTX_free(ctx->ctx);
3440 #ifndef OPENSSL_NO_DEPRECATED_3_0
3441         ssl_hmac_old_free(ctx);
3442 #endif
3443         OPENSSL_free(ctx);
3444     }
3445 }
3446 
3447 EVP_MAC_CTX *ssl_hmac_get0_EVP_MAC_CTX(SSL_HMAC *ctx)
3448 {
3449     return ctx->ctx;
3450 }
3451 
3452 int ssl_hmac_init(SSL_HMAC *ctx, void *key, size_t len, char *md)
3453 {
3454     OSSL_PARAM params[2], *p = params;
3455 
3456     if (ctx->ctx != NULL) {
3457         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, md, 0);
3458         *p = OSSL_PARAM_construct_end();
3459         if (EVP_MAC_init(ctx->ctx, key, len, params))
3460             return 1;
3461     }
3462 #ifndef OPENSSL_NO_DEPRECATED_3_0
3463     if (ctx->old_ctx != NULL)
3464         return ssl_hmac_old_init(ctx, key, len, md);
3465 #endif
3466     return 0;
3467 }
3468 
3469 int ssl_hmac_update(SSL_HMAC *ctx, const unsigned char *data, size_t len)
3470 {
3471     if (ctx->ctx != NULL)
3472         return EVP_MAC_update(ctx->ctx, data, len);
3473 #ifndef OPENSSL_NO_DEPRECATED_3_0
3474     if (ctx->old_ctx != NULL)
3475         return ssl_hmac_old_update(ctx, data, len);
3476 #endif
3477     return 0;
3478 }
3479 
3480 int ssl_hmac_final(SSL_HMAC *ctx, unsigned char *md, size_t *len,
3481                    size_t max_size)
3482 {
3483     if (ctx->ctx != NULL)
3484         return EVP_MAC_final(ctx->ctx, md, len, max_size);
3485 #ifndef OPENSSL_NO_DEPRECATED_3_0
3486     if (ctx->old_ctx != NULL)
3487         return ssl_hmac_old_final(ctx, md, len);
3488 #endif
3489     return 0;
3490 }
3491 
3492 size_t ssl_hmac_size(const SSL_HMAC *ctx)
3493 {
3494     if (ctx->ctx != NULL)
3495         return EVP_MAC_CTX_get_mac_size(ctx->ctx);
3496 #ifndef OPENSSL_NO_DEPRECATED_3_0
3497     if (ctx->old_ctx != NULL)
3498         return ssl_hmac_old_size(ctx);
3499 #endif
3500     return 0;
3501 }
3502 
3503 int ssl_get_EC_curve_nid(const EVP_PKEY *pkey)
3504 {
3505     char gname[OSSL_MAX_NAME_SIZE];
3506 
3507     if (EVP_PKEY_get_group_name(pkey, gname, sizeof(gname), NULL) > 0)
3508         return OBJ_txt2nid(gname);
3509 
3510     return NID_undef;
3511 }
3512 
3513 __owur int tls13_set_encoded_pub_key(EVP_PKEY *pkey,
3514                                      const unsigned char *enckey,
3515                                      size_t enckeylen)
3516 {
3517     if (EVP_PKEY_is_a(pkey, "DH")) {
3518         int bits = EVP_PKEY_get_bits(pkey);
3519 
3520         if (bits <= 0 || enckeylen != (size_t)bits / 8)
3521             /* the encoded key must be padded to the length of the p */
3522             return 0;
3523     } else if (EVP_PKEY_is_a(pkey, "EC")) {
3524         if (enckeylen < 3 /* point format and at least 1 byte for x and y */
3525             || enckey[0] != 0x04)
3526             return 0;
3527     }
3528 
3529     return EVP_PKEY_set1_encoded_public_key(pkey, enckey, enckeylen);
3530 }
3531