xref: /freebsd/crypto/openssl/ssl/t1_lib.c (revision 13ea0450a9c8742119d36f3bf8f47accdce46e54)
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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/ocsp.h>
16 #include <openssl/conf.h>
17 #include <openssl/x509v3.h>
18 #include <openssl/dh.h>
19 #include <openssl/bn.h>
20 #include "internal/nelem.h"
21 #include "ssl_locl.h"
22 #include <openssl/ct.h>
23 
24 SSL3_ENC_METHOD const TLSv1_enc_data = {
25     tls1_enc,
26     tls1_mac,
27     tls1_setup_key_block,
28     tls1_generate_master_secret,
29     tls1_change_cipher_state,
30     tls1_final_finish_mac,
31     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
32     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
33     tls1_alert_code,
34     tls1_export_keying_material,
35     0,
36     ssl3_set_handshake_header,
37     tls_close_construct_packet,
38     ssl3_handshake_write
39 };
40 
41 SSL3_ENC_METHOD const TLSv1_1_enc_data = {
42     tls1_enc,
43     tls1_mac,
44     tls1_setup_key_block,
45     tls1_generate_master_secret,
46     tls1_change_cipher_state,
47     tls1_final_finish_mac,
48     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
49     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
50     tls1_alert_code,
51     tls1_export_keying_material,
52     SSL_ENC_FLAG_EXPLICIT_IV,
53     ssl3_set_handshake_header,
54     tls_close_construct_packet,
55     ssl3_handshake_write
56 };
57 
58 SSL3_ENC_METHOD const TLSv1_2_enc_data = {
59     tls1_enc,
60     tls1_mac,
61     tls1_setup_key_block,
62     tls1_generate_master_secret,
63     tls1_change_cipher_state,
64     tls1_final_finish_mac,
65     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
66     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
67     tls1_alert_code,
68     tls1_export_keying_material,
69     SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
70         | SSL_ENC_FLAG_TLS1_2_CIPHERS,
71     ssl3_set_handshake_header,
72     tls_close_construct_packet,
73     ssl3_handshake_write
74 };
75 
76 SSL3_ENC_METHOD const TLSv1_3_enc_data = {
77     tls13_enc,
78     tls1_mac,
79     tls13_setup_key_block,
80     tls13_generate_master_secret,
81     tls13_change_cipher_state,
82     tls13_final_finish_mac,
83     TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
84     TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
85     tls13_alert_code,
86     tls13_export_keying_material,
87     SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF,
88     ssl3_set_handshake_header,
89     tls_close_construct_packet,
90     ssl3_handshake_write
91 };
92 
93 long tls1_default_timeout(void)
94 {
95     /*
96      * 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
97      * http, the cache would over fill
98      */
99     return (60 * 60 * 2);
100 }
101 
102 int tls1_new(SSL *s)
103 {
104     if (!ssl3_new(s))
105         return 0;
106     if (!s->method->ssl_clear(s))
107         return 0;
108 
109     return 1;
110 }
111 
112 void tls1_free(SSL *s)
113 {
114     OPENSSL_free(s->ext.session_ticket);
115     ssl3_free(s);
116 }
117 
118 int tls1_clear(SSL *s)
119 {
120     if (!ssl3_clear(s))
121         return 0;
122 
123     if (s->method->version == TLS_ANY_VERSION)
124         s->version = TLS_MAX_VERSION;
125     else
126         s->version = s->method->version;
127 
128     return 1;
129 }
130 
131 #ifndef OPENSSL_NO_EC
132 
133 /*
134  * Table of curve information.
135  * Do not delete entries or reorder this array! It is used as a lookup
136  * table: the index of each entry is one less than the TLS curve id.
137  */
138 static const TLS_GROUP_INFO nid_list[] = {
139     {NID_sect163k1, 80, TLS_CURVE_CHAR2}, /* sect163k1 (1) */
140     {NID_sect163r1, 80, TLS_CURVE_CHAR2}, /* sect163r1 (2) */
141     {NID_sect163r2, 80, TLS_CURVE_CHAR2}, /* sect163r2 (3) */
142     {NID_sect193r1, 80, TLS_CURVE_CHAR2}, /* sect193r1 (4) */
143     {NID_sect193r2, 80, TLS_CURVE_CHAR2}, /* sect193r2 (5) */
144     {NID_sect233k1, 112, TLS_CURVE_CHAR2}, /* sect233k1 (6) */
145     {NID_sect233r1, 112, TLS_CURVE_CHAR2}, /* sect233r1 (7) */
146     {NID_sect239k1, 112, TLS_CURVE_CHAR2}, /* sect239k1 (8) */
147     {NID_sect283k1, 128, TLS_CURVE_CHAR2}, /* sect283k1 (9) */
148     {NID_sect283r1, 128, TLS_CURVE_CHAR2}, /* sect283r1 (10) */
149     {NID_sect409k1, 192, TLS_CURVE_CHAR2}, /* sect409k1 (11) */
150     {NID_sect409r1, 192, TLS_CURVE_CHAR2}, /* sect409r1 (12) */
151     {NID_sect571k1, 256, TLS_CURVE_CHAR2}, /* sect571k1 (13) */
152     {NID_sect571r1, 256, TLS_CURVE_CHAR2}, /* sect571r1 (14) */
153     {NID_secp160k1, 80, TLS_CURVE_PRIME}, /* secp160k1 (15) */
154     {NID_secp160r1, 80, TLS_CURVE_PRIME}, /* secp160r1 (16) */
155     {NID_secp160r2, 80, TLS_CURVE_PRIME}, /* secp160r2 (17) */
156     {NID_secp192k1, 80, TLS_CURVE_PRIME}, /* secp192k1 (18) */
157     {NID_X9_62_prime192v1, 80, TLS_CURVE_PRIME}, /* secp192r1 (19) */
158     {NID_secp224k1, 112, TLS_CURVE_PRIME}, /* secp224k1 (20) */
159     {NID_secp224r1, 112, TLS_CURVE_PRIME}, /* secp224r1 (21) */
160     {NID_secp256k1, 128, TLS_CURVE_PRIME}, /* secp256k1 (22) */
161     {NID_X9_62_prime256v1, 128, TLS_CURVE_PRIME}, /* secp256r1 (23) */
162     {NID_secp384r1, 192, TLS_CURVE_PRIME}, /* secp384r1 (24) */
163     {NID_secp521r1, 256, TLS_CURVE_PRIME}, /* secp521r1 (25) */
164     {NID_brainpoolP256r1, 128, TLS_CURVE_PRIME}, /* brainpoolP256r1 (26) */
165     {NID_brainpoolP384r1, 192, TLS_CURVE_PRIME}, /* brainpoolP384r1 (27) */
166     {NID_brainpoolP512r1, 256, TLS_CURVE_PRIME}, /* brainpool512r1 (28) */
167     {EVP_PKEY_X25519, 128, TLS_CURVE_CUSTOM}, /* X25519 (29) */
168     {EVP_PKEY_X448, 224, TLS_CURVE_CUSTOM}, /* X448 (30) */
169 };
170 
171 static const unsigned char ecformats_default[] = {
172     TLSEXT_ECPOINTFORMAT_uncompressed,
173     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
174     TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
175 };
176 
177 /* The default curves */
178 static const uint16_t eccurves_default[] = {
179     29,                      /* X25519 (29) */
180     23,                      /* secp256r1 (23) */
181     30,                      /* X448 (30) */
182     25,                      /* secp521r1 (25) */
183     24,                      /* secp384r1 (24) */
184 };
185 
186 static const uint16_t suiteb_curves[] = {
187     TLSEXT_curve_P_256,
188     TLSEXT_curve_P_384
189 };
190 
191 const TLS_GROUP_INFO *tls1_group_id_lookup(uint16_t group_id)
192 {
193     /* ECC curves from RFC 4492 and RFC 7027 */
194     if (group_id < 1 || group_id > OSSL_NELEM(nid_list))
195         return NULL;
196     return &nid_list[group_id - 1];
197 }
198 
199 static uint16_t tls1_nid2group_id(int nid)
200 {
201     size_t i;
202     for (i = 0; i < OSSL_NELEM(nid_list); i++) {
203         if (nid_list[i].nid == nid)
204             return (uint16_t)(i + 1);
205     }
206     return 0;
207 }
208 
209 /*
210  * Set *pgroups to the supported groups list and *pgroupslen to
211  * the number of groups supported.
212  */
213 void tls1_get_supported_groups(SSL *s, const uint16_t **pgroups,
214                                size_t *pgroupslen)
215 {
216 
217     /* For Suite B mode only include P-256, P-384 */
218     switch (tls1_suiteb(s)) {
219     case SSL_CERT_FLAG_SUITEB_128_LOS:
220         *pgroups = suiteb_curves;
221         *pgroupslen = OSSL_NELEM(suiteb_curves);
222         break;
223 
224     case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
225         *pgroups = suiteb_curves;
226         *pgroupslen = 1;
227         break;
228 
229     case SSL_CERT_FLAG_SUITEB_192_LOS:
230         *pgroups = suiteb_curves + 1;
231         *pgroupslen = 1;
232         break;
233 
234     default:
235         if (s->ext.supportedgroups == NULL) {
236             *pgroups = eccurves_default;
237             *pgroupslen = OSSL_NELEM(eccurves_default);
238         } else {
239             *pgroups = s->ext.supportedgroups;
240             *pgroupslen = s->ext.supportedgroups_len;
241         }
242         break;
243     }
244 }
245 
246 /* See if curve is allowed by security callback */
247 int tls_curve_allowed(SSL *s, uint16_t curve, int op)
248 {
249     const TLS_GROUP_INFO *cinfo = tls1_group_id_lookup(curve);
250     unsigned char ctmp[2];
251 
252     if (cinfo == NULL)
253         return 0;
254 # ifdef OPENSSL_NO_EC2M
255     if (cinfo->flags & TLS_CURVE_CHAR2)
256         return 0;
257 # endif
258     ctmp[0] = curve >> 8;
259     ctmp[1] = curve & 0xff;
260     return ssl_security(s, op, cinfo->secbits, cinfo->nid, (void *)ctmp);
261 }
262 
263 /* Return 1 if "id" is in "list" */
264 static int tls1_in_list(uint16_t id, const uint16_t *list, size_t listlen)
265 {
266     size_t i;
267     for (i = 0; i < listlen; i++)
268         if (list[i] == id)
269             return 1;
270     return 0;
271 }
272 
273 /*-
274  * For nmatch >= 0, return the id of the |nmatch|th shared group or 0
275  * if there is no match.
276  * For nmatch == -1, return number of matches
277  * For nmatch == -2, return the id of the group to use for
278  * a tmp key, or 0 if there is no match.
279  */
280 uint16_t tls1_shared_group(SSL *s, int nmatch)
281 {
282     const uint16_t *pref, *supp;
283     size_t num_pref, num_supp, i;
284     int k;
285 
286     /* Can't do anything on client side */
287     if (s->server == 0)
288         return 0;
289     if (nmatch == -2) {
290         if (tls1_suiteb(s)) {
291             /*
292              * For Suite B ciphersuite determines curve: we already know
293              * these are acceptable due to previous checks.
294              */
295             unsigned long cid = s->s3->tmp.new_cipher->id;
296 
297             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
298                 return TLSEXT_curve_P_256;
299             if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
300                 return TLSEXT_curve_P_384;
301             /* Should never happen */
302             return 0;
303         }
304         /* If not Suite B just return first preference shared curve */
305         nmatch = 0;
306     }
307     /*
308      * If server preference set, our groups are the preference order
309      * otherwise peer decides.
310      */
311     if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
312         tls1_get_supported_groups(s, &pref, &num_pref);
313         tls1_get_peer_groups(s, &supp, &num_supp);
314     } else {
315         tls1_get_peer_groups(s, &pref, &num_pref);
316         tls1_get_supported_groups(s, &supp, &num_supp);
317     }
318 
319     for (k = 0, i = 0; i < num_pref; i++) {
320         uint16_t id = pref[i];
321 
322         if (!tls1_in_list(id, supp, num_supp)
323             || !tls_curve_allowed(s, id, SSL_SECOP_CURVE_SHARED))
324                     continue;
325         if (nmatch == k)
326             return id;
327          k++;
328     }
329     if (nmatch == -1)
330         return k;
331     /* Out of range (nmatch > k). */
332     return 0;
333 }
334 
335 int tls1_set_groups(uint16_t **pext, size_t *pextlen,
336                     int *groups, size_t ngroups)
337 {
338     uint16_t *glist;
339     size_t i;
340     /*
341      * Bitmap of groups included to detect duplicates: only works while group
342      * ids < 32
343      */
344     unsigned long dup_list = 0;
345 
346     if (ngroups == 0) {
347         SSLerr(SSL_F_TLS1_SET_GROUPS, SSL_R_BAD_LENGTH);
348         return 0;
349     }
350     if ((glist = OPENSSL_malloc(ngroups * sizeof(*glist))) == NULL) {
351         SSLerr(SSL_F_TLS1_SET_GROUPS, ERR_R_MALLOC_FAILURE);
352         return 0;
353     }
354     for (i = 0; i < ngroups; i++) {
355         unsigned long idmask;
356         uint16_t id;
357         /* TODO(TLS1.3): Convert for DH groups */
358         id = tls1_nid2group_id(groups[i]);
359         idmask = 1L << id;
360         if (!id || (dup_list & idmask)) {
361             OPENSSL_free(glist);
362             return 0;
363         }
364         dup_list |= idmask;
365         glist[i] = id;
366     }
367     OPENSSL_free(*pext);
368     *pext = glist;
369     *pextlen = ngroups;
370     return 1;
371 }
372 
373 # define MAX_CURVELIST   OSSL_NELEM(nid_list)
374 
375 typedef struct {
376     size_t nidcnt;
377     int nid_arr[MAX_CURVELIST];
378 } nid_cb_st;
379 
380 static int nid_cb(const char *elem, int len, void *arg)
381 {
382     nid_cb_st *narg = arg;
383     size_t i;
384     int nid;
385     char etmp[20];
386     if (elem == NULL)
387         return 0;
388     if (narg->nidcnt == MAX_CURVELIST)
389         return 0;
390     if (len > (int)(sizeof(etmp) - 1))
391         return 0;
392     memcpy(etmp, elem, len);
393     etmp[len] = 0;
394     nid = EC_curve_nist2nid(etmp);
395     if (nid == NID_undef)
396         nid = OBJ_sn2nid(etmp);
397     if (nid == NID_undef)
398         nid = OBJ_ln2nid(etmp);
399     if (nid == NID_undef)
400         return 0;
401     for (i = 0; i < narg->nidcnt; i++)
402         if (narg->nid_arr[i] == nid)
403             return 0;
404     narg->nid_arr[narg->nidcnt++] = nid;
405     return 1;
406 }
407 
408 /* Set groups based on a colon separate list */
409 int tls1_set_groups_list(uint16_t **pext, size_t *pextlen, const char *str)
410 {
411     nid_cb_st ncb;
412     ncb.nidcnt = 0;
413     if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
414         return 0;
415     if (pext == NULL)
416         return 1;
417     return tls1_set_groups(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
418 }
419 /* Return group id of a key */
420 static uint16_t tls1_get_group_id(EVP_PKEY *pkey)
421 {
422     EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
423     const EC_GROUP *grp;
424 
425     if (ec == NULL)
426         return 0;
427     grp = EC_KEY_get0_group(ec);
428     return tls1_nid2group_id(EC_GROUP_get_curve_name(grp));
429 }
430 
431 /* Check a key is compatible with compression extension */
432 static int tls1_check_pkey_comp(SSL *s, EVP_PKEY *pkey)
433 {
434     const EC_KEY *ec;
435     const EC_GROUP *grp;
436     unsigned char comp_id;
437     size_t i;
438 
439     /* If not an EC key nothing to check */
440     if (EVP_PKEY_id(pkey) != EVP_PKEY_EC)
441         return 1;
442     ec = EVP_PKEY_get0_EC_KEY(pkey);
443     grp = EC_KEY_get0_group(ec);
444 
445     /* Get required compression id */
446     if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_UNCOMPRESSED) {
447             comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
448     } else if (SSL_IS_TLS13(s)) {
449             /*
450              * ec_point_formats extension is not used in TLSv1.3 so we ignore
451              * this check.
452              */
453             return 1;
454     } else {
455         int field_type = EC_METHOD_get_field_type(EC_GROUP_method_of(grp));
456 
457         if (field_type == NID_X9_62_prime_field)
458             comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
459         else if (field_type == NID_X9_62_characteristic_two_field)
460             comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
461         else
462             return 0;
463     }
464     /*
465      * If point formats extension present check it, otherwise everything is
466      * supported (see RFC4492).
467      */
468     if (s->session->ext.ecpointformats == NULL)
469         return 1;
470 
471     for (i = 0; i < s->session->ext.ecpointformats_len; i++) {
472         if (s->session->ext.ecpointformats[i] == comp_id)
473             return 1;
474     }
475     return 0;
476 }
477 
478 /* Check a group id matches preferences */
479 int tls1_check_group_id(SSL *s, uint16_t group_id, int check_own_groups)
480     {
481     const uint16_t *groups;
482     size_t groups_len;
483 
484     if (group_id == 0)
485         return 0;
486 
487     /* Check for Suite B compliance */
488     if (tls1_suiteb(s) && s->s3->tmp.new_cipher != NULL) {
489         unsigned long cid = s->s3->tmp.new_cipher->id;
490 
491         if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
492             if (group_id != TLSEXT_curve_P_256)
493                 return 0;
494         } else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
495             if (group_id != TLSEXT_curve_P_384)
496                 return 0;
497         } else {
498             /* Should never happen */
499             return 0;
500         }
501     }
502 
503     if (check_own_groups) {
504         /* Check group is one of our preferences */
505         tls1_get_supported_groups(s, &groups, &groups_len);
506         if (!tls1_in_list(group_id, groups, groups_len))
507             return 0;
508     }
509 
510     if (!tls_curve_allowed(s, group_id, SSL_SECOP_CURVE_CHECK))
511         return 0;
512 
513     /* For clients, nothing more to check */
514     if (!s->server)
515         return 1;
516 
517     /* Check group is one of peers preferences */
518     tls1_get_peer_groups(s, &groups, &groups_len);
519 
520     /*
521      * RFC 4492 does not require the supported elliptic curves extension
522      * so if it is not sent we can just choose any curve.
523      * It is invalid to send an empty list in the supported groups
524      * extension, so groups_len == 0 always means no extension.
525      */
526     if (groups_len == 0)
527             return 1;
528     return tls1_in_list(group_id, groups, groups_len);
529 }
530 
531 void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
532                          size_t *num_formats)
533 {
534     /*
535      * If we have a custom point format list use it otherwise use default
536      */
537     if (s->ext.ecpointformats) {
538         *pformats = s->ext.ecpointformats;
539         *num_formats = s->ext.ecpointformats_len;
540     } else {
541         *pformats = ecformats_default;
542         /* For Suite B we don't support char2 fields */
543         if (tls1_suiteb(s))
544             *num_formats = sizeof(ecformats_default) - 1;
545         else
546             *num_formats = sizeof(ecformats_default);
547     }
548 }
549 
550 /*
551  * Check cert parameters compatible with extensions: currently just checks EC
552  * certificates have compatible curves and compression.
553  */
554 static int tls1_check_cert_param(SSL *s, X509 *x, int check_ee_md)
555 {
556     uint16_t group_id;
557     EVP_PKEY *pkey;
558     pkey = X509_get0_pubkey(x);
559     if (pkey == NULL)
560         return 0;
561     /* If not EC nothing to do */
562     if (EVP_PKEY_id(pkey) != EVP_PKEY_EC)
563         return 1;
564     /* Check compression */
565     if (!tls1_check_pkey_comp(s, pkey))
566         return 0;
567     group_id = tls1_get_group_id(pkey);
568     /*
569      * For a server we allow the certificate to not be in our list of supported
570      * groups.
571      */
572     if (!tls1_check_group_id(s, group_id, !s->server))
573         return 0;
574     /*
575      * Special case for suite B. We *MUST* sign using SHA256+P-256 or
576      * SHA384+P-384.
577      */
578     if (check_ee_md && tls1_suiteb(s)) {
579         int check_md;
580         size_t i;
581         CERT *c = s->cert;
582 
583         /* Check to see we have necessary signing algorithm */
584         if (group_id == TLSEXT_curve_P_256)
585             check_md = NID_ecdsa_with_SHA256;
586         else if (group_id == TLSEXT_curve_P_384)
587             check_md = NID_ecdsa_with_SHA384;
588         else
589             return 0;           /* Should never happen */
590         for (i = 0; i < c->shared_sigalgslen; i++) {
591             if (check_md == c->shared_sigalgs[i]->sigandhash)
592                 return 1;;
593         }
594         return 0;
595     }
596     return 1;
597 }
598 
599 /*
600  * tls1_check_ec_tmp_key - Check EC temporary key compatibility
601  * @s: SSL connection
602  * @cid: Cipher ID we're considering using
603  *
604  * Checks that the kECDHE cipher suite we're considering using
605  * is compatible with the client extensions.
606  *
607  * Returns 0 when the cipher can't be used or 1 when it can.
608  */
609 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
610 {
611     /* If not Suite B just need a shared group */
612     if (!tls1_suiteb(s))
613         return tls1_shared_group(s, 0) != 0;
614     /*
615      * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
616      * curves permitted.
617      */
618     if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
619         return tls1_check_group_id(s, TLSEXT_curve_P_256, 1);
620     if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
621         return tls1_check_group_id(s, TLSEXT_curve_P_384, 1);
622 
623     return 0;
624 }
625 
626 #else
627 
628 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
629 {
630     return 1;
631 }
632 
633 #endif                          /* OPENSSL_NO_EC */
634 
635 /* Default sigalg schemes */
636 static const uint16_t tls12_sigalgs[] = {
637 #ifndef OPENSSL_NO_EC
638     TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
639     TLSEXT_SIGALG_ecdsa_secp384r1_sha384,
640     TLSEXT_SIGALG_ecdsa_secp521r1_sha512,
641     TLSEXT_SIGALG_ed25519,
642     TLSEXT_SIGALG_ed448,
643 #endif
644 
645     TLSEXT_SIGALG_rsa_pss_pss_sha256,
646     TLSEXT_SIGALG_rsa_pss_pss_sha384,
647     TLSEXT_SIGALG_rsa_pss_pss_sha512,
648     TLSEXT_SIGALG_rsa_pss_rsae_sha256,
649     TLSEXT_SIGALG_rsa_pss_rsae_sha384,
650     TLSEXT_SIGALG_rsa_pss_rsae_sha512,
651 
652     TLSEXT_SIGALG_rsa_pkcs1_sha256,
653     TLSEXT_SIGALG_rsa_pkcs1_sha384,
654     TLSEXT_SIGALG_rsa_pkcs1_sha512,
655 
656 #ifndef OPENSSL_NO_EC
657     TLSEXT_SIGALG_ecdsa_sha224,
658     TLSEXT_SIGALG_ecdsa_sha1,
659 #endif
660     TLSEXT_SIGALG_rsa_pkcs1_sha224,
661     TLSEXT_SIGALG_rsa_pkcs1_sha1,
662 #ifndef OPENSSL_NO_DSA
663     TLSEXT_SIGALG_dsa_sha224,
664     TLSEXT_SIGALG_dsa_sha1,
665 
666     TLSEXT_SIGALG_dsa_sha256,
667     TLSEXT_SIGALG_dsa_sha384,
668     TLSEXT_SIGALG_dsa_sha512,
669 #endif
670 #ifndef OPENSSL_NO_GOST
671     TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256,
672     TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512,
673     TLSEXT_SIGALG_gostr34102001_gostr3411,
674 #endif
675 };
676 
677 #ifndef OPENSSL_NO_EC
678 static const uint16_t suiteb_sigalgs[] = {
679     TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
680     TLSEXT_SIGALG_ecdsa_secp384r1_sha384
681 };
682 #endif
683 
684 static const SIGALG_LOOKUP sigalg_lookup_tbl[] = {
685 #ifndef OPENSSL_NO_EC
686     {"ecdsa_secp256r1_sha256", TLSEXT_SIGALG_ecdsa_secp256r1_sha256,
687      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
688      NID_ecdsa_with_SHA256, NID_X9_62_prime256v1},
689     {"ecdsa_secp384r1_sha384", TLSEXT_SIGALG_ecdsa_secp384r1_sha384,
690      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
691      NID_ecdsa_with_SHA384, NID_secp384r1},
692     {"ecdsa_secp521r1_sha512", TLSEXT_SIGALG_ecdsa_secp521r1_sha512,
693      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
694      NID_ecdsa_with_SHA512, NID_secp521r1},
695     {"ed25519", TLSEXT_SIGALG_ed25519,
696      NID_undef, -1, EVP_PKEY_ED25519, SSL_PKEY_ED25519,
697      NID_undef, NID_undef},
698     {"ed448", TLSEXT_SIGALG_ed448,
699      NID_undef, -1, EVP_PKEY_ED448, SSL_PKEY_ED448,
700      NID_undef, NID_undef},
701     {NULL, TLSEXT_SIGALG_ecdsa_sha224,
702      NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
703      NID_ecdsa_with_SHA224, NID_undef},
704     {NULL, TLSEXT_SIGALG_ecdsa_sha1,
705      NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_EC, SSL_PKEY_ECC,
706      NID_ecdsa_with_SHA1, NID_undef},
707 #endif
708     {"rsa_pss_rsae_sha256", TLSEXT_SIGALG_rsa_pss_rsae_sha256,
709      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
710      NID_undef, NID_undef},
711     {"rsa_pss_rsae_sha384", TLSEXT_SIGALG_rsa_pss_rsae_sha384,
712      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
713      NID_undef, NID_undef},
714     {"rsa_pss_rsae_sha512", TLSEXT_SIGALG_rsa_pss_rsae_sha512,
715      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA,
716      NID_undef, NID_undef},
717     {"rsa_pss_pss_sha256", TLSEXT_SIGALG_rsa_pss_pss_sha256,
718      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
719      NID_undef, NID_undef},
720     {"rsa_pss_pss_sha384", TLSEXT_SIGALG_rsa_pss_pss_sha384,
721      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
722      NID_undef, NID_undef},
723     {"rsa_pss_pss_sha512", TLSEXT_SIGALG_rsa_pss_pss_sha512,
724      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA_PSS, SSL_PKEY_RSA_PSS_SIGN,
725      NID_undef, NID_undef},
726     {"rsa_pkcs1_sha256", TLSEXT_SIGALG_rsa_pkcs1_sha256,
727      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
728      NID_sha256WithRSAEncryption, NID_undef},
729     {"rsa_pkcs1_sha384", TLSEXT_SIGALG_rsa_pkcs1_sha384,
730      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
731      NID_sha384WithRSAEncryption, NID_undef},
732     {"rsa_pkcs1_sha512", TLSEXT_SIGALG_rsa_pkcs1_sha512,
733      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
734      NID_sha512WithRSAEncryption, NID_undef},
735     {"rsa_pkcs1_sha224", TLSEXT_SIGALG_rsa_pkcs1_sha224,
736      NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
737      NID_sha224WithRSAEncryption, NID_undef},
738     {"rsa_pkcs1_sha1", TLSEXT_SIGALG_rsa_pkcs1_sha1,
739      NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_RSA, SSL_PKEY_RSA,
740      NID_sha1WithRSAEncryption, NID_undef},
741 #ifndef OPENSSL_NO_DSA
742     {NULL, TLSEXT_SIGALG_dsa_sha256,
743      NID_sha256, SSL_MD_SHA256_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
744      NID_dsa_with_SHA256, NID_undef},
745     {NULL, TLSEXT_SIGALG_dsa_sha384,
746      NID_sha384, SSL_MD_SHA384_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
747      NID_undef, NID_undef},
748     {NULL, TLSEXT_SIGALG_dsa_sha512,
749      NID_sha512, SSL_MD_SHA512_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
750      NID_undef, NID_undef},
751     {NULL, TLSEXT_SIGALG_dsa_sha224,
752      NID_sha224, SSL_MD_SHA224_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
753      NID_undef, NID_undef},
754     {NULL, TLSEXT_SIGALG_dsa_sha1,
755      NID_sha1, SSL_MD_SHA1_IDX, EVP_PKEY_DSA, SSL_PKEY_DSA_SIGN,
756      NID_dsaWithSHA1, NID_undef},
757 #endif
758 #ifndef OPENSSL_NO_GOST
759     {NULL, TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256,
760      NID_id_GostR3411_2012_256, SSL_MD_GOST12_256_IDX,
761      NID_id_GostR3410_2012_256, SSL_PKEY_GOST12_256,
762      NID_undef, NID_undef},
763     {NULL, TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512,
764      NID_id_GostR3411_2012_512, SSL_MD_GOST12_512_IDX,
765      NID_id_GostR3410_2012_512, SSL_PKEY_GOST12_512,
766      NID_undef, NID_undef},
767     {NULL, TLSEXT_SIGALG_gostr34102001_gostr3411,
768      NID_id_GostR3411_94, SSL_MD_GOST94_IDX,
769      NID_id_GostR3410_2001, SSL_PKEY_GOST01,
770      NID_undef, NID_undef}
771 #endif
772 };
773 /* Legacy sigalgs for TLS < 1.2 RSA TLS signatures */
774 static const SIGALG_LOOKUP legacy_rsa_sigalg = {
775     "rsa_pkcs1_md5_sha1", 0,
776      NID_md5_sha1, SSL_MD_MD5_SHA1_IDX,
777      EVP_PKEY_RSA, SSL_PKEY_RSA,
778      NID_undef, NID_undef
779 };
780 
781 /*
782  * Default signature algorithm values used if signature algorithms not present.
783  * From RFC5246. Note: order must match certificate index order.
784  */
785 static const uint16_t tls_default_sigalg[] = {
786     TLSEXT_SIGALG_rsa_pkcs1_sha1, /* SSL_PKEY_RSA */
787     0, /* SSL_PKEY_RSA_PSS_SIGN */
788     TLSEXT_SIGALG_dsa_sha1, /* SSL_PKEY_DSA_SIGN */
789     TLSEXT_SIGALG_ecdsa_sha1, /* SSL_PKEY_ECC */
790     TLSEXT_SIGALG_gostr34102001_gostr3411, /* SSL_PKEY_GOST01 */
791     TLSEXT_SIGALG_gostr34102012_256_gostr34112012_256, /* SSL_PKEY_GOST12_256 */
792     TLSEXT_SIGALG_gostr34102012_512_gostr34112012_512, /* SSL_PKEY_GOST12_512 */
793     0, /* SSL_PKEY_ED25519 */
794     0, /* SSL_PKEY_ED448 */
795 };
796 
797 /* Lookup TLS signature algorithm */
798 static const SIGALG_LOOKUP *tls1_lookup_sigalg(uint16_t sigalg)
799 {
800     size_t i;
801     const SIGALG_LOOKUP *s;
802 
803     for (i = 0, s = sigalg_lookup_tbl; i < OSSL_NELEM(sigalg_lookup_tbl);
804          i++, s++) {
805         if (s->sigalg == sigalg)
806             return s;
807     }
808     return NULL;
809 }
810 /* Lookup hash: return 0 if invalid or not enabled */
811 int tls1_lookup_md(const SIGALG_LOOKUP *lu, const EVP_MD **pmd)
812 {
813     const EVP_MD *md;
814     if (lu == NULL)
815         return 0;
816     /* lu->hash == NID_undef means no associated digest */
817     if (lu->hash == NID_undef) {
818         md = NULL;
819     } else {
820         md = ssl_md(lu->hash_idx);
821         if (md == NULL)
822             return 0;
823     }
824     if (pmd)
825         *pmd = md;
826     return 1;
827 }
828 
829 /*
830  * Check if key is large enough to generate RSA-PSS signature.
831  *
832  * The key must greater than or equal to 2 * hash length + 2.
833  * SHA512 has a hash length of 64 bytes, which is incompatible
834  * with a 128 byte (1024 bit) key.
835  */
836 #define RSA_PSS_MINIMUM_KEY_SIZE(md) (2 * EVP_MD_size(md) + 2)
837 static int rsa_pss_check_min_key_size(const RSA *rsa, const SIGALG_LOOKUP *lu)
838 {
839     const EVP_MD *md;
840 
841     if (rsa == NULL)
842         return 0;
843     if (!tls1_lookup_md(lu, &md) || md == NULL)
844         return 0;
845     if (RSA_size(rsa) < RSA_PSS_MINIMUM_KEY_SIZE(md))
846         return 0;
847     return 1;
848 }
849 
850 /*
851  * Return a signature algorithm for TLS < 1.2 where the signature type
852  * is fixed by the certificate type.
853  */
854 static const SIGALG_LOOKUP *tls1_get_legacy_sigalg(const SSL *s, int idx)
855 {
856     if (idx == -1) {
857         if (s->server) {
858             size_t i;
859 
860             /* Work out index corresponding to ciphersuite */
861             for (i = 0; i < SSL_PKEY_NUM; i++) {
862                 const SSL_CERT_LOOKUP *clu = ssl_cert_lookup_by_idx(i);
863 
864                 if (clu->amask & s->s3->tmp.new_cipher->algorithm_auth) {
865                     idx = i;
866                     break;
867                 }
868             }
869 
870             /*
871              * Some GOST ciphersuites allow more than one signature algorithms
872              * */
873             if (idx == SSL_PKEY_GOST01 && s->s3->tmp.new_cipher->algorithm_auth != SSL_aGOST01) {
874                 int real_idx;
875 
876                 for (real_idx = SSL_PKEY_GOST12_512; real_idx >= SSL_PKEY_GOST01;
877                      real_idx--) {
878                     if (s->cert->pkeys[real_idx].privatekey != NULL) {
879                         idx = real_idx;
880                         break;
881                     }
882                 }
883             }
884         } else {
885             idx = s->cert->key - s->cert->pkeys;
886         }
887     }
888     if (idx < 0 || idx >= (int)OSSL_NELEM(tls_default_sigalg))
889         return NULL;
890     if (SSL_USE_SIGALGS(s) || idx != SSL_PKEY_RSA) {
891         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(tls_default_sigalg[idx]);
892 
893         if (!tls1_lookup_md(lu, NULL))
894             return NULL;
895         return lu;
896     }
897     return &legacy_rsa_sigalg;
898 }
899 /* Set peer sigalg based key type */
900 int tls1_set_peer_legacy_sigalg(SSL *s, const EVP_PKEY *pkey)
901 {
902     size_t idx;
903     const SIGALG_LOOKUP *lu;
904 
905     if (ssl_cert_lookup_by_pkey(pkey, &idx) == NULL)
906         return 0;
907     lu = tls1_get_legacy_sigalg(s, idx);
908     if (lu == NULL)
909         return 0;
910     s->s3->tmp.peer_sigalg = lu;
911     return 1;
912 }
913 
914 size_t tls12_get_psigalgs(SSL *s, int sent, const uint16_t **psigs)
915 {
916     /*
917      * If Suite B mode use Suite B sigalgs only, ignore any other
918      * preferences.
919      */
920 #ifndef OPENSSL_NO_EC
921     switch (tls1_suiteb(s)) {
922     case SSL_CERT_FLAG_SUITEB_128_LOS:
923         *psigs = suiteb_sigalgs;
924         return OSSL_NELEM(suiteb_sigalgs);
925 
926     case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
927         *psigs = suiteb_sigalgs;
928         return 1;
929 
930     case SSL_CERT_FLAG_SUITEB_192_LOS:
931         *psigs = suiteb_sigalgs + 1;
932         return 1;
933     }
934 #endif
935     /*
936      *  We use client_sigalgs (if not NULL) if we're a server
937      *  and sending a certificate request or if we're a client and
938      *  determining which shared algorithm to use.
939      */
940     if ((s->server == sent) && s->cert->client_sigalgs != NULL) {
941         *psigs = s->cert->client_sigalgs;
942         return s->cert->client_sigalgslen;
943     } else if (s->cert->conf_sigalgs) {
944         *psigs = s->cert->conf_sigalgs;
945         return s->cert->conf_sigalgslen;
946     } else {
947         *psigs = tls12_sigalgs;
948         return OSSL_NELEM(tls12_sigalgs);
949     }
950 }
951 
952 #ifndef OPENSSL_NO_EC
953 /*
954  * Called by servers only. Checks that we have a sig alg that supports the
955  * specified EC curve.
956  */
957 int tls_check_sigalg_curve(const SSL *s, int curve)
958 {
959    const uint16_t *sigs;
960    size_t siglen, i;
961 
962     if (s->cert->conf_sigalgs) {
963         sigs = s->cert->conf_sigalgs;
964         siglen = s->cert->conf_sigalgslen;
965     } else {
966         sigs = tls12_sigalgs;
967         siglen = OSSL_NELEM(tls12_sigalgs);
968     }
969 
970     for (i = 0; i < siglen; i++) {
971         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(sigs[i]);
972 
973         if (lu == NULL)
974             continue;
975         if (lu->sig == EVP_PKEY_EC
976                 && lu->curve != NID_undef
977                 && curve == lu->curve)
978             return 1;
979     }
980 
981     return 0;
982 }
983 #endif
984 
985 /*
986  * Check signature algorithm is consistent with sent supported signature
987  * algorithms and if so set relevant digest and signature scheme in
988  * s.
989  */
990 int tls12_check_peer_sigalg(SSL *s, uint16_t sig, EVP_PKEY *pkey)
991 {
992     const uint16_t *sent_sigs;
993     const EVP_MD *md = NULL;
994     char sigalgstr[2];
995     size_t sent_sigslen, i, cidx;
996     int pkeyid = EVP_PKEY_id(pkey);
997     const SIGALG_LOOKUP *lu;
998 
999     /* Should never happen */
1000     if (pkeyid == -1)
1001         return -1;
1002     if (SSL_IS_TLS13(s)) {
1003         /* Disallow DSA for TLS 1.3 */
1004         if (pkeyid == EVP_PKEY_DSA) {
1005             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS12_CHECK_PEER_SIGALG,
1006                      SSL_R_WRONG_SIGNATURE_TYPE);
1007             return 0;
1008         }
1009         /* Only allow PSS for TLS 1.3 */
1010         if (pkeyid == EVP_PKEY_RSA)
1011             pkeyid = EVP_PKEY_RSA_PSS;
1012     }
1013     lu = tls1_lookup_sigalg(sig);
1014     /*
1015      * Check sigalgs is known. Disallow SHA1/SHA224 with TLS 1.3. Check key type
1016      * is consistent with signature: RSA keys can be used for RSA-PSS
1017      */
1018     if (lu == NULL
1019         || (SSL_IS_TLS13(s) && (lu->hash == NID_sha1 || lu->hash == NID_sha224))
1020         || (pkeyid != lu->sig
1021         && (lu->sig != EVP_PKEY_RSA_PSS || pkeyid != EVP_PKEY_RSA))) {
1022         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS12_CHECK_PEER_SIGALG,
1023                  SSL_R_WRONG_SIGNATURE_TYPE);
1024         return 0;
1025     }
1026     /* Check the sigalg is consistent with the key OID */
1027     if (!ssl_cert_lookup_by_nid(EVP_PKEY_id(pkey), &cidx)
1028             || lu->sig_idx != (int)cidx) {
1029         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS12_CHECK_PEER_SIGALG,
1030                  SSL_R_WRONG_SIGNATURE_TYPE);
1031         return 0;
1032     }
1033 
1034 #ifndef OPENSSL_NO_EC
1035     if (pkeyid == EVP_PKEY_EC) {
1036 
1037         /* Check point compression is permitted */
1038         if (!tls1_check_pkey_comp(s, pkey)) {
1039             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1040                      SSL_F_TLS12_CHECK_PEER_SIGALG,
1041                      SSL_R_ILLEGAL_POINT_COMPRESSION);
1042             return 0;
1043         }
1044 
1045         /* For TLS 1.3 or Suite B check curve matches signature algorithm */
1046         if (SSL_IS_TLS13(s) || tls1_suiteb(s)) {
1047             EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
1048             int curve = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1049 
1050             if (lu->curve != NID_undef && curve != lu->curve) {
1051                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1052                          SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
1053                 return 0;
1054             }
1055         }
1056         if (!SSL_IS_TLS13(s)) {
1057             /* Check curve matches extensions */
1058             if (!tls1_check_group_id(s, tls1_get_group_id(pkey), 1)) {
1059                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1060                          SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
1061                 return 0;
1062             }
1063             if (tls1_suiteb(s)) {
1064                 /* Check sigalg matches a permissible Suite B value */
1065                 if (sig != TLSEXT_SIGALG_ecdsa_secp256r1_sha256
1066                     && sig != TLSEXT_SIGALG_ecdsa_secp384r1_sha384) {
1067                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1068                              SSL_F_TLS12_CHECK_PEER_SIGALG,
1069                              SSL_R_WRONG_SIGNATURE_TYPE);
1070                     return 0;
1071                 }
1072             }
1073         }
1074     } else if (tls1_suiteb(s)) {
1075         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS12_CHECK_PEER_SIGALG,
1076                  SSL_R_WRONG_SIGNATURE_TYPE);
1077         return 0;
1078     }
1079 #endif
1080 
1081     /* Check signature matches a type we sent */
1082     sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
1083     for (i = 0; i < sent_sigslen; i++, sent_sigs++) {
1084         if (sig == *sent_sigs)
1085             break;
1086     }
1087     /* Allow fallback to SHA1 if not strict mode */
1088     if (i == sent_sigslen && (lu->hash != NID_sha1
1089         || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
1090         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS12_CHECK_PEER_SIGALG,
1091                  SSL_R_WRONG_SIGNATURE_TYPE);
1092         return 0;
1093     }
1094     if (!tls1_lookup_md(lu, &md)) {
1095         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS12_CHECK_PEER_SIGALG,
1096                  SSL_R_UNKNOWN_DIGEST);
1097         return 0;
1098     }
1099     if (md != NULL) {
1100         /*
1101          * Make sure security callback allows algorithm. For historical
1102          * reasons we have to pass the sigalg as a two byte char array.
1103          */
1104         sigalgstr[0] = (sig >> 8) & 0xff;
1105         sigalgstr[1] = sig & 0xff;
1106         if (!ssl_security(s, SSL_SECOP_SIGALG_CHECK,
1107                     EVP_MD_size(md) * 4, EVP_MD_type(md),
1108                     (void *)sigalgstr)) {
1109             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS12_CHECK_PEER_SIGALG,
1110                      SSL_R_WRONG_SIGNATURE_TYPE);
1111             return 0;
1112         }
1113     }
1114     /* Store the sigalg the peer uses */
1115     s->s3->tmp.peer_sigalg = lu;
1116     return 1;
1117 }
1118 
1119 int SSL_get_peer_signature_type_nid(const SSL *s, int *pnid)
1120 {
1121     if (s->s3->tmp.peer_sigalg == NULL)
1122         return 0;
1123     *pnid = s->s3->tmp.peer_sigalg->sig;
1124     return 1;
1125 }
1126 
1127 int SSL_get_signature_type_nid(const SSL *s, int *pnid)
1128 {
1129     if (s->s3->tmp.sigalg == NULL)
1130         return 0;
1131     *pnid = s->s3->tmp.sigalg->sig;
1132     return 1;
1133 }
1134 
1135 /*
1136  * Set a mask of disabled algorithms: an algorithm is disabled if it isn't
1137  * supported, doesn't appear in supported signature algorithms, isn't supported
1138  * by the enabled protocol versions or by the security level.
1139  *
1140  * This function should only be used for checking which ciphers are supported
1141  * by the client.
1142  *
1143  * Call ssl_cipher_disabled() to check that it's enabled or not.
1144  */
1145 int ssl_set_client_disabled(SSL *s)
1146 {
1147     s->s3->tmp.mask_a = 0;
1148     s->s3->tmp.mask_k = 0;
1149     ssl_set_sig_mask(&s->s3->tmp.mask_a, s, SSL_SECOP_SIGALG_MASK);
1150     if (ssl_get_min_max_version(s, &s->s3->tmp.min_ver,
1151                                 &s->s3->tmp.max_ver, NULL) != 0)
1152         return 0;
1153 #ifndef OPENSSL_NO_PSK
1154     /* with PSK there must be client callback set */
1155     if (!s->psk_client_callback) {
1156         s->s3->tmp.mask_a |= SSL_aPSK;
1157         s->s3->tmp.mask_k |= SSL_PSK;
1158     }
1159 #endif                          /* OPENSSL_NO_PSK */
1160 #ifndef OPENSSL_NO_SRP
1161     if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
1162         s->s3->tmp.mask_a |= SSL_aSRP;
1163         s->s3->tmp.mask_k |= SSL_kSRP;
1164     }
1165 #endif
1166     return 1;
1167 }
1168 
1169 /*
1170  * ssl_cipher_disabled - check that a cipher is disabled or not
1171  * @s: SSL connection that you want to use the cipher on
1172  * @c: cipher to check
1173  * @op: Security check that you want to do
1174  * @ecdhe: If set to 1 then TLSv1 ECDHE ciphers are also allowed in SSLv3
1175  *
1176  * Returns 1 when it's disabled, 0 when enabled.
1177  */
1178 int ssl_cipher_disabled(SSL *s, const SSL_CIPHER *c, int op, int ecdhe)
1179 {
1180     if (c->algorithm_mkey & s->s3->tmp.mask_k
1181         || c->algorithm_auth & s->s3->tmp.mask_a)
1182         return 1;
1183     if (s->s3->tmp.max_ver == 0)
1184         return 1;
1185     if (!SSL_IS_DTLS(s)) {
1186         int min_tls = c->min_tls;
1187 
1188         /*
1189          * For historical reasons we will allow ECHDE to be selected by a server
1190          * in SSLv3 if we are a client
1191          */
1192         if (min_tls == TLS1_VERSION && ecdhe
1193                 && (c->algorithm_mkey & (SSL_kECDHE | SSL_kECDHEPSK)) != 0)
1194             min_tls = SSL3_VERSION;
1195 
1196         if ((min_tls > s->s3->tmp.max_ver) || (c->max_tls < s->s3->tmp.min_ver))
1197             return 1;
1198     }
1199     if (SSL_IS_DTLS(s) && (DTLS_VERSION_GT(c->min_dtls, s->s3->tmp.max_ver)
1200                            || DTLS_VERSION_LT(c->max_dtls, s->s3->tmp.min_ver)))
1201         return 1;
1202 
1203     return !ssl_security(s, op, c->strength_bits, 0, (void *)c);
1204 }
1205 
1206 int tls_use_ticket(SSL *s)
1207 {
1208     if ((s->options & SSL_OP_NO_TICKET))
1209         return 0;
1210     return ssl_security(s, SSL_SECOP_TICKET, 0, 0, NULL);
1211 }
1212 
1213 int tls1_set_server_sigalgs(SSL *s)
1214 {
1215     size_t i;
1216 
1217     /* Clear any shared signature algorithms */
1218     OPENSSL_free(s->cert->shared_sigalgs);
1219     s->cert->shared_sigalgs = NULL;
1220     s->cert->shared_sigalgslen = 0;
1221     /* Clear certificate validity flags */
1222     for (i = 0; i < SSL_PKEY_NUM; i++)
1223         s->s3->tmp.valid_flags[i] = 0;
1224     /*
1225      * If peer sent no signature algorithms check to see if we support
1226      * the default algorithm for each certificate type
1227      */
1228     if (s->s3->tmp.peer_cert_sigalgs == NULL
1229             && s->s3->tmp.peer_sigalgs == NULL) {
1230         const uint16_t *sent_sigs;
1231         size_t sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
1232 
1233         for (i = 0; i < SSL_PKEY_NUM; i++) {
1234             const SIGALG_LOOKUP *lu = tls1_get_legacy_sigalg(s, i);
1235             size_t j;
1236 
1237             if (lu == NULL)
1238                 continue;
1239             /* Check default matches a type we sent */
1240             for (j = 0; j < sent_sigslen; j++) {
1241                 if (lu->sigalg == sent_sigs[j]) {
1242                         s->s3->tmp.valid_flags[i] = CERT_PKEY_SIGN;
1243                         break;
1244                 }
1245             }
1246         }
1247         return 1;
1248     }
1249 
1250     if (!tls1_process_sigalgs(s)) {
1251         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1252                  SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_INTERNAL_ERROR);
1253         return 0;
1254     }
1255     if (s->cert->shared_sigalgs != NULL)
1256         return 1;
1257 
1258     /* Fatal error if no shared signature algorithms */
1259     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS1_SET_SERVER_SIGALGS,
1260              SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS);
1261     return 0;
1262 }
1263 
1264 /*-
1265  * Gets the ticket information supplied by the client if any.
1266  *
1267  *   hello: The parsed ClientHello data
1268  *   ret: (output) on return, if a ticket was decrypted, then this is set to
1269  *       point to the resulting session.
1270  */
1271 SSL_TICKET_STATUS tls_get_ticket_from_client(SSL *s, CLIENTHELLO_MSG *hello,
1272                                              SSL_SESSION **ret)
1273 {
1274     size_t size;
1275     RAW_EXTENSION *ticketext;
1276 
1277     *ret = NULL;
1278     s->ext.ticket_expected = 0;
1279 
1280     /*
1281      * If tickets disabled or not supported by the protocol version
1282      * (e.g. TLSv1.3) behave as if no ticket present to permit stateful
1283      * resumption.
1284      */
1285     if (s->version <= SSL3_VERSION || !tls_use_ticket(s))
1286         return SSL_TICKET_NONE;
1287 
1288     ticketext = &hello->pre_proc_exts[TLSEXT_IDX_session_ticket];
1289     if (!ticketext->present)
1290         return SSL_TICKET_NONE;
1291 
1292     size = PACKET_remaining(&ticketext->data);
1293 
1294     return tls_decrypt_ticket(s, PACKET_data(&ticketext->data), size,
1295                               hello->session_id, hello->session_id_len, ret);
1296 }
1297 
1298 /*-
1299  * tls_decrypt_ticket attempts to decrypt a session ticket.
1300  *
1301  * If s->tls_session_secret_cb is set and we're not doing TLSv1.3 then we are
1302  * expecting a pre-shared key ciphersuite, in which case we have no use for
1303  * session tickets and one will never be decrypted, nor will
1304  * s->ext.ticket_expected be set to 1.
1305  *
1306  * Side effects:
1307  *   Sets s->ext.ticket_expected to 1 if the server will have to issue
1308  *   a new session ticket to the client because the client indicated support
1309  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
1310  *   a session ticket or we couldn't use the one it gave us, or if
1311  *   s->ctx->ext.ticket_key_cb asked to renew the client's ticket.
1312  *   Otherwise, s->ext.ticket_expected is set to 0.
1313  *
1314  *   etick: points to the body of the session ticket extension.
1315  *   eticklen: the length of the session tickets extension.
1316  *   sess_id: points at the session ID.
1317  *   sesslen: the length of the session ID.
1318  *   psess: (output) on return, if a ticket was decrypted, then this is set to
1319  *       point to the resulting session.
1320  */
1321 SSL_TICKET_STATUS tls_decrypt_ticket(SSL *s, const unsigned char *etick,
1322                                      size_t eticklen, const unsigned char *sess_id,
1323                                      size_t sesslen, SSL_SESSION **psess)
1324 {
1325     SSL_SESSION *sess = NULL;
1326     unsigned char *sdec;
1327     const unsigned char *p;
1328     int slen, renew_ticket = 0, declen;
1329     SSL_TICKET_STATUS ret = SSL_TICKET_FATAL_ERR_OTHER;
1330     size_t mlen;
1331     unsigned char tick_hmac[EVP_MAX_MD_SIZE];
1332     HMAC_CTX *hctx = NULL;
1333     EVP_CIPHER_CTX *ctx = NULL;
1334     SSL_CTX *tctx = s->session_ctx;
1335 
1336     if (eticklen == 0) {
1337         /*
1338          * The client will accept a ticket but doesn't currently have
1339          * one (TLSv1.2 and below), or treated as a fatal error in TLSv1.3
1340          */
1341         ret = SSL_TICKET_EMPTY;
1342         goto end;
1343     }
1344     if (!SSL_IS_TLS13(s) && s->ext.session_secret_cb) {
1345         /*
1346          * Indicate that the ticket couldn't be decrypted rather than
1347          * generating the session from ticket now, trigger
1348          * abbreviated handshake based on external mechanism to
1349          * calculate the master secret later.
1350          */
1351         ret = SSL_TICKET_NO_DECRYPT;
1352         goto end;
1353     }
1354 
1355     /* Need at least keyname + iv */
1356     if (eticklen < TLSEXT_KEYNAME_LENGTH + EVP_MAX_IV_LENGTH) {
1357         ret = SSL_TICKET_NO_DECRYPT;
1358         goto end;
1359     }
1360 
1361     /* Initialize session ticket encryption and HMAC contexts */
1362     hctx = HMAC_CTX_new();
1363     if (hctx == NULL) {
1364         ret = SSL_TICKET_FATAL_ERR_MALLOC;
1365         goto end;
1366     }
1367     ctx = EVP_CIPHER_CTX_new();
1368     if (ctx == NULL) {
1369         ret = SSL_TICKET_FATAL_ERR_MALLOC;
1370         goto end;
1371     }
1372     if (tctx->ext.ticket_key_cb) {
1373         unsigned char *nctick = (unsigned char *)etick;
1374         int rv = tctx->ext.ticket_key_cb(s, nctick,
1375                                          nctick + TLSEXT_KEYNAME_LENGTH,
1376                                          ctx, hctx, 0);
1377         if (rv < 0) {
1378             ret = SSL_TICKET_FATAL_ERR_OTHER;
1379             goto end;
1380         }
1381         if (rv == 0) {
1382             ret = SSL_TICKET_NO_DECRYPT;
1383             goto end;
1384         }
1385         if (rv == 2)
1386             renew_ticket = 1;
1387     } else {
1388         /* Check key name matches */
1389         if (memcmp(etick, tctx->ext.tick_key_name,
1390                    TLSEXT_KEYNAME_LENGTH) != 0) {
1391             ret = SSL_TICKET_NO_DECRYPT;
1392             goto end;
1393         }
1394         if (HMAC_Init_ex(hctx, tctx->ext.secure->tick_hmac_key,
1395                          sizeof(tctx->ext.secure->tick_hmac_key),
1396                          EVP_sha256(), NULL) <= 0
1397             || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
1398                                   tctx->ext.secure->tick_aes_key,
1399                                   etick + TLSEXT_KEYNAME_LENGTH) <= 0) {
1400             ret = SSL_TICKET_FATAL_ERR_OTHER;
1401             goto end;
1402         }
1403         if (SSL_IS_TLS13(s))
1404             renew_ticket = 1;
1405     }
1406     /*
1407      * Attempt to process session ticket, first conduct sanity and integrity
1408      * checks on ticket.
1409      */
1410     mlen = HMAC_size(hctx);
1411     if (mlen == 0) {
1412         ret = SSL_TICKET_FATAL_ERR_OTHER;
1413         goto end;
1414     }
1415 
1416     /* Sanity check ticket length: must exceed keyname + IV + HMAC */
1417     if (eticklen <=
1418         TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx) + mlen) {
1419         ret = SSL_TICKET_NO_DECRYPT;
1420         goto end;
1421     }
1422     eticklen -= mlen;
1423     /* Check HMAC of encrypted ticket */
1424     if (HMAC_Update(hctx, etick, eticklen) <= 0
1425         || HMAC_Final(hctx, tick_hmac, NULL) <= 0) {
1426         ret = SSL_TICKET_FATAL_ERR_OTHER;
1427         goto end;
1428     }
1429 
1430     if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
1431         ret = SSL_TICKET_NO_DECRYPT;
1432         goto end;
1433     }
1434     /* Attempt to decrypt session data */
1435     /* Move p after IV to start of encrypted ticket, update length */
1436     p = etick + TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx);
1437     eticklen -= TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx);
1438     sdec = OPENSSL_malloc(eticklen);
1439     if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p,
1440                                           (int)eticklen) <= 0) {
1441         OPENSSL_free(sdec);
1442         ret = SSL_TICKET_FATAL_ERR_OTHER;
1443         goto end;
1444     }
1445     if (EVP_DecryptFinal(ctx, sdec + slen, &declen) <= 0) {
1446         OPENSSL_free(sdec);
1447         ret = SSL_TICKET_NO_DECRYPT;
1448         goto end;
1449     }
1450     slen += declen;
1451     p = sdec;
1452 
1453     sess = d2i_SSL_SESSION(NULL, &p, slen);
1454     slen -= p - sdec;
1455     OPENSSL_free(sdec);
1456     if (sess) {
1457         /* Some additional consistency checks */
1458         if (slen != 0) {
1459             SSL_SESSION_free(sess);
1460             sess = NULL;
1461             ret = SSL_TICKET_NO_DECRYPT;
1462             goto end;
1463         }
1464         /*
1465          * The session ID, if non-empty, is used by some clients to detect
1466          * that the ticket has been accepted. So we copy it to the session
1467          * structure. If it is empty set length to zero as required by
1468          * standard.
1469          */
1470         if (sesslen) {
1471             memcpy(sess->session_id, sess_id, sesslen);
1472             sess->session_id_length = sesslen;
1473         }
1474         if (renew_ticket)
1475             ret = SSL_TICKET_SUCCESS_RENEW;
1476         else
1477             ret = SSL_TICKET_SUCCESS;
1478         goto end;
1479     }
1480     ERR_clear_error();
1481     /*
1482      * For session parse failure, indicate that we need to send a new ticket.
1483      */
1484     ret = SSL_TICKET_NO_DECRYPT;
1485 
1486  end:
1487     EVP_CIPHER_CTX_free(ctx);
1488     HMAC_CTX_free(hctx);
1489 
1490     /*
1491      * If set, the decrypt_ticket_cb() is called unless a fatal error was
1492      * detected above. The callback is responsible for checking |ret| before it
1493      * performs any action
1494      */
1495     if (s->session_ctx->decrypt_ticket_cb != NULL
1496             && (ret == SSL_TICKET_EMPTY
1497                 || ret == SSL_TICKET_NO_DECRYPT
1498                 || ret == SSL_TICKET_SUCCESS
1499                 || ret == SSL_TICKET_SUCCESS_RENEW)) {
1500         size_t keyname_len = eticklen;
1501         int retcb;
1502 
1503         if (keyname_len > TLSEXT_KEYNAME_LENGTH)
1504             keyname_len = TLSEXT_KEYNAME_LENGTH;
1505         retcb = s->session_ctx->decrypt_ticket_cb(s, sess, etick, keyname_len,
1506                                                   ret,
1507                                                   s->session_ctx->ticket_cb_data);
1508         switch (retcb) {
1509         case SSL_TICKET_RETURN_ABORT:
1510             ret = SSL_TICKET_FATAL_ERR_OTHER;
1511             break;
1512 
1513         case SSL_TICKET_RETURN_IGNORE:
1514             ret = SSL_TICKET_NONE;
1515             SSL_SESSION_free(sess);
1516             sess = NULL;
1517             break;
1518 
1519         case SSL_TICKET_RETURN_IGNORE_RENEW:
1520             if (ret != SSL_TICKET_EMPTY && ret != SSL_TICKET_NO_DECRYPT)
1521                 ret = SSL_TICKET_NO_DECRYPT;
1522             /* else the value of |ret| will already do the right thing */
1523             SSL_SESSION_free(sess);
1524             sess = NULL;
1525             break;
1526 
1527         case SSL_TICKET_RETURN_USE:
1528         case SSL_TICKET_RETURN_USE_RENEW:
1529             if (ret != SSL_TICKET_SUCCESS
1530                     && ret != SSL_TICKET_SUCCESS_RENEW)
1531                 ret = SSL_TICKET_FATAL_ERR_OTHER;
1532             else if (retcb == SSL_TICKET_RETURN_USE)
1533                 ret = SSL_TICKET_SUCCESS;
1534             else
1535                 ret = SSL_TICKET_SUCCESS_RENEW;
1536             break;
1537 
1538         default:
1539             ret = SSL_TICKET_FATAL_ERR_OTHER;
1540         }
1541     }
1542 
1543     if (s->ext.session_secret_cb == NULL || SSL_IS_TLS13(s)) {
1544         switch (ret) {
1545         case SSL_TICKET_NO_DECRYPT:
1546         case SSL_TICKET_SUCCESS_RENEW:
1547         case SSL_TICKET_EMPTY:
1548             s->ext.ticket_expected = 1;
1549         }
1550     }
1551 
1552     *psess = sess;
1553 
1554     return ret;
1555 }
1556 
1557 /* Check to see if a signature algorithm is allowed */
1558 static int tls12_sigalg_allowed(SSL *s, int op, const SIGALG_LOOKUP *lu)
1559 {
1560     unsigned char sigalgstr[2];
1561     int secbits;
1562 
1563     /* See if sigalgs is recognised and if hash is enabled */
1564     if (!tls1_lookup_md(lu, NULL))
1565         return 0;
1566     /* DSA is not allowed in TLS 1.3 */
1567     if (SSL_IS_TLS13(s) && lu->sig == EVP_PKEY_DSA)
1568         return 0;
1569     /* TODO(OpenSSL1.2) fully axe DSA/etc. in ClientHello per TLS 1.3 spec */
1570     if (!s->server && !SSL_IS_DTLS(s) && s->s3->tmp.min_ver >= TLS1_3_VERSION
1571         && (lu->sig == EVP_PKEY_DSA || lu->hash_idx == SSL_MD_SHA1_IDX
1572             || lu->hash_idx == SSL_MD_MD5_IDX
1573             || lu->hash_idx == SSL_MD_SHA224_IDX))
1574         return 0;
1575 
1576     /* See if public key algorithm allowed */
1577     if (ssl_cert_is_disabled(lu->sig_idx))
1578         return 0;
1579 
1580     if (lu->sig == NID_id_GostR3410_2012_256
1581             || lu->sig == NID_id_GostR3410_2012_512
1582             || lu->sig == NID_id_GostR3410_2001) {
1583         /* We never allow GOST sig algs on the server with TLSv1.3 */
1584         if (s->server && SSL_IS_TLS13(s))
1585             return 0;
1586         if (!s->server
1587                 && s->method->version == TLS_ANY_VERSION
1588                 && s->s3->tmp.max_ver >= TLS1_3_VERSION) {
1589             int i, num;
1590             STACK_OF(SSL_CIPHER) *sk;
1591 
1592             /*
1593              * We're a client that could negotiate TLSv1.3. We only allow GOST
1594              * sig algs if we could negotiate TLSv1.2 or below and we have GOST
1595              * ciphersuites enabled.
1596              */
1597 
1598             if (s->s3->tmp.min_ver >= TLS1_3_VERSION)
1599                 return 0;
1600 
1601             sk = SSL_get_ciphers(s);
1602             num = sk != NULL ? sk_SSL_CIPHER_num(sk) : 0;
1603             for (i = 0; i < num; i++) {
1604                 const SSL_CIPHER *c;
1605 
1606                 c = sk_SSL_CIPHER_value(sk, i);
1607                 /* Skip disabled ciphers */
1608                 if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0))
1609                     continue;
1610 
1611                 if ((c->algorithm_mkey & SSL_kGOST) != 0)
1612                     break;
1613             }
1614             if (i == num)
1615                 return 0;
1616         }
1617     }
1618 
1619     if (lu->hash == NID_undef)
1620         return 1;
1621     /* Security bits: half digest bits */
1622     secbits = EVP_MD_size(ssl_md(lu->hash_idx)) * 4;
1623     /* Finally see if security callback allows it */
1624     sigalgstr[0] = (lu->sigalg >> 8) & 0xff;
1625     sigalgstr[1] = lu->sigalg & 0xff;
1626     return ssl_security(s, op, secbits, lu->hash, (void *)sigalgstr);
1627 }
1628 
1629 /*
1630  * Get a mask of disabled public key algorithms based on supported signature
1631  * algorithms. For example if no signature algorithm supports RSA then RSA is
1632  * disabled.
1633  */
1634 
1635 void ssl_set_sig_mask(uint32_t *pmask_a, SSL *s, int op)
1636 {
1637     const uint16_t *sigalgs;
1638     size_t i, sigalgslen;
1639     uint32_t disabled_mask = SSL_aRSA | SSL_aDSS | SSL_aECDSA;
1640     /*
1641      * Go through all signature algorithms seeing if we support any
1642      * in disabled_mask.
1643      */
1644     sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs);
1645     for (i = 0; i < sigalgslen; i++, sigalgs++) {
1646         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(*sigalgs);
1647         const SSL_CERT_LOOKUP *clu;
1648 
1649         if (lu == NULL)
1650             continue;
1651 
1652         clu = ssl_cert_lookup_by_idx(lu->sig_idx);
1653 	if (clu == NULL)
1654 		continue;
1655 
1656         /* If algorithm is disabled see if we can enable it */
1657         if ((clu->amask & disabled_mask) != 0
1658                 && tls12_sigalg_allowed(s, op, lu))
1659             disabled_mask &= ~clu->amask;
1660     }
1661     *pmask_a |= disabled_mask;
1662 }
1663 
1664 int tls12_copy_sigalgs(SSL *s, WPACKET *pkt,
1665                        const uint16_t *psig, size_t psiglen)
1666 {
1667     size_t i;
1668     int rv = 0;
1669 
1670     for (i = 0; i < psiglen; i++, psig++) {
1671         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(*psig);
1672 
1673         if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, lu))
1674             continue;
1675         if (!WPACKET_put_bytes_u16(pkt, *psig))
1676             return 0;
1677         /*
1678          * If TLS 1.3 must have at least one valid TLS 1.3 message
1679          * signing algorithm: i.e. neither RSA nor SHA1/SHA224
1680          */
1681         if (rv == 0 && (!SSL_IS_TLS13(s)
1682             || (lu->sig != EVP_PKEY_RSA
1683                 && lu->hash != NID_sha1
1684                 && lu->hash != NID_sha224)))
1685             rv = 1;
1686     }
1687     if (rv == 0)
1688         SSLerr(SSL_F_TLS12_COPY_SIGALGS, SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
1689     return rv;
1690 }
1691 
1692 /* Given preference and allowed sigalgs set shared sigalgs */
1693 static size_t tls12_shared_sigalgs(SSL *s, const SIGALG_LOOKUP **shsig,
1694                                    const uint16_t *pref, size_t preflen,
1695                                    const uint16_t *allow, size_t allowlen)
1696 {
1697     const uint16_t *ptmp, *atmp;
1698     size_t i, j, nmatch = 0;
1699     for (i = 0, ptmp = pref; i < preflen; i++, ptmp++) {
1700         const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(*ptmp);
1701 
1702         /* Skip disabled hashes or signature algorithms */
1703         if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SHARED, lu))
1704             continue;
1705         for (j = 0, atmp = allow; j < allowlen; j++, atmp++) {
1706             if (*ptmp == *atmp) {
1707                 nmatch++;
1708                 if (shsig)
1709                     *shsig++ = lu;
1710                 break;
1711             }
1712         }
1713     }
1714     return nmatch;
1715 }
1716 
1717 /* Set shared signature algorithms for SSL structures */
1718 static int tls1_set_shared_sigalgs(SSL *s)
1719 {
1720     const uint16_t *pref, *allow, *conf;
1721     size_t preflen, allowlen, conflen;
1722     size_t nmatch;
1723     const SIGALG_LOOKUP **salgs = NULL;
1724     CERT *c = s->cert;
1725     unsigned int is_suiteb = tls1_suiteb(s);
1726 
1727     OPENSSL_free(c->shared_sigalgs);
1728     c->shared_sigalgs = NULL;
1729     c->shared_sigalgslen = 0;
1730     /* If client use client signature algorithms if not NULL */
1731     if (!s->server && c->client_sigalgs && !is_suiteb) {
1732         conf = c->client_sigalgs;
1733         conflen = c->client_sigalgslen;
1734     } else if (c->conf_sigalgs && !is_suiteb) {
1735         conf = c->conf_sigalgs;
1736         conflen = c->conf_sigalgslen;
1737     } else
1738         conflen = tls12_get_psigalgs(s, 0, &conf);
1739     if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
1740         pref = conf;
1741         preflen = conflen;
1742         allow = s->s3->tmp.peer_sigalgs;
1743         allowlen = s->s3->tmp.peer_sigalgslen;
1744     } else {
1745         allow = conf;
1746         allowlen = conflen;
1747         pref = s->s3->tmp.peer_sigalgs;
1748         preflen = s->s3->tmp.peer_sigalgslen;
1749     }
1750     nmatch = tls12_shared_sigalgs(s, NULL, pref, preflen, allow, allowlen);
1751     if (nmatch) {
1752         if ((salgs = OPENSSL_malloc(nmatch * sizeof(*salgs))) == NULL) {
1753             SSLerr(SSL_F_TLS1_SET_SHARED_SIGALGS, ERR_R_MALLOC_FAILURE);
1754             return 0;
1755         }
1756         nmatch = tls12_shared_sigalgs(s, salgs, pref, preflen, allow, allowlen);
1757     } else {
1758         salgs = NULL;
1759     }
1760     c->shared_sigalgs = salgs;
1761     c->shared_sigalgslen = nmatch;
1762     return 1;
1763 }
1764 
1765 int tls1_save_u16(PACKET *pkt, uint16_t **pdest, size_t *pdestlen)
1766 {
1767     unsigned int stmp;
1768     size_t size, i;
1769     uint16_t *buf;
1770 
1771     size = PACKET_remaining(pkt);
1772 
1773     /* Invalid data length */
1774     if (size == 0 || (size & 1) != 0)
1775         return 0;
1776 
1777     size >>= 1;
1778 
1779     if ((buf = OPENSSL_malloc(size * sizeof(*buf))) == NULL)  {
1780         SSLerr(SSL_F_TLS1_SAVE_U16, ERR_R_MALLOC_FAILURE);
1781         return 0;
1782     }
1783     for (i = 0; i < size && PACKET_get_net_2(pkt, &stmp); i++)
1784         buf[i] = stmp;
1785 
1786     if (i != size) {
1787         OPENSSL_free(buf);
1788         return 0;
1789     }
1790 
1791     OPENSSL_free(*pdest);
1792     *pdest = buf;
1793     *pdestlen = size;
1794 
1795     return 1;
1796 }
1797 
1798 int tls1_save_sigalgs(SSL *s, PACKET *pkt, int cert)
1799 {
1800     /* Extension ignored for inappropriate versions */
1801     if (!SSL_USE_SIGALGS(s))
1802         return 1;
1803     /* Should never happen */
1804     if (s->cert == NULL)
1805         return 0;
1806 
1807     if (cert)
1808         return tls1_save_u16(pkt, &s->s3->tmp.peer_cert_sigalgs,
1809                              &s->s3->tmp.peer_cert_sigalgslen);
1810     else
1811         return tls1_save_u16(pkt, &s->s3->tmp.peer_sigalgs,
1812                              &s->s3->tmp.peer_sigalgslen);
1813 
1814 }
1815 
1816 /* Set preferred digest for each key type */
1817 
1818 int tls1_process_sigalgs(SSL *s)
1819 {
1820     size_t i;
1821     uint32_t *pvalid = s->s3->tmp.valid_flags;
1822     CERT *c = s->cert;
1823 
1824     if (!tls1_set_shared_sigalgs(s))
1825         return 0;
1826 
1827     for (i = 0; i < SSL_PKEY_NUM; i++)
1828         pvalid[i] = 0;
1829 
1830     for (i = 0; i < c->shared_sigalgslen; i++) {
1831         const SIGALG_LOOKUP *sigptr = c->shared_sigalgs[i];
1832         int idx = sigptr->sig_idx;
1833 
1834         /* Ignore PKCS1 based sig algs in TLSv1.3 */
1835         if (SSL_IS_TLS13(s) && sigptr->sig == EVP_PKEY_RSA)
1836             continue;
1837         /* If not disabled indicate we can explicitly sign */
1838         if (pvalid[idx] == 0 && !ssl_cert_is_disabled(idx))
1839             pvalid[idx] = CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
1840     }
1841     return 1;
1842 }
1843 
1844 int SSL_get_sigalgs(SSL *s, int idx,
1845                     int *psign, int *phash, int *psignhash,
1846                     unsigned char *rsig, unsigned char *rhash)
1847 {
1848     uint16_t *psig = s->s3->tmp.peer_sigalgs;
1849     size_t numsigalgs = s->s3->tmp.peer_sigalgslen;
1850     if (psig == NULL || numsigalgs > INT_MAX)
1851         return 0;
1852     if (idx >= 0) {
1853         const SIGALG_LOOKUP *lu;
1854 
1855         if (idx >= (int)numsigalgs)
1856             return 0;
1857         psig += idx;
1858         if (rhash != NULL)
1859             *rhash = (unsigned char)((*psig >> 8) & 0xff);
1860         if (rsig != NULL)
1861             *rsig = (unsigned char)(*psig & 0xff);
1862         lu = tls1_lookup_sigalg(*psig);
1863         if (psign != NULL)
1864             *psign = lu != NULL ? lu->sig : NID_undef;
1865         if (phash != NULL)
1866             *phash = lu != NULL ? lu->hash : NID_undef;
1867         if (psignhash != NULL)
1868             *psignhash = lu != NULL ? lu->sigandhash : NID_undef;
1869     }
1870     return (int)numsigalgs;
1871 }
1872 
1873 int SSL_get_shared_sigalgs(SSL *s, int idx,
1874                            int *psign, int *phash, int *psignhash,
1875                            unsigned char *rsig, unsigned char *rhash)
1876 {
1877     const SIGALG_LOOKUP *shsigalgs;
1878     if (s->cert->shared_sigalgs == NULL
1879         || idx < 0
1880         || idx >= (int)s->cert->shared_sigalgslen
1881         || s->cert->shared_sigalgslen > INT_MAX)
1882         return 0;
1883     shsigalgs = s->cert->shared_sigalgs[idx];
1884     if (phash != NULL)
1885         *phash = shsigalgs->hash;
1886     if (psign != NULL)
1887         *psign = shsigalgs->sig;
1888     if (psignhash != NULL)
1889         *psignhash = shsigalgs->sigandhash;
1890     if (rsig != NULL)
1891         *rsig = (unsigned char)(shsigalgs->sigalg & 0xff);
1892     if (rhash != NULL)
1893         *rhash = (unsigned char)((shsigalgs->sigalg >> 8) & 0xff);
1894     return (int)s->cert->shared_sigalgslen;
1895 }
1896 
1897 /* Maximum possible number of unique entries in sigalgs array */
1898 #define TLS_MAX_SIGALGCNT (OSSL_NELEM(sigalg_lookup_tbl) * 2)
1899 
1900 typedef struct {
1901     size_t sigalgcnt;
1902     /* TLSEXT_SIGALG_XXX values */
1903     uint16_t sigalgs[TLS_MAX_SIGALGCNT];
1904 } sig_cb_st;
1905 
1906 static void get_sigorhash(int *psig, int *phash, const char *str)
1907 {
1908     if (strcmp(str, "RSA") == 0) {
1909         *psig = EVP_PKEY_RSA;
1910     } else if (strcmp(str, "RSA-PSS") == 0 || strcmp(str, "PSS") == 0) {
1911         *psig = EVP_PKEY_RSA_PSS;
1912     } else if (strcmp(str, "DSA") == 0) {
1913         *psig = EVP_PKEY_DSA;
1914     } else if (strcmp(str, "ECDSA") == 0) {
1915         *psig = EVP_PKEY_EC;
1916     } else {
1917         *phash = OBJ_sn2nid(str);
1918         if (*phash == NID_undef)
1919             *phash = OBJ_ln2nid(str);
1920     }
1921 }
1922 /* Maximum length of a signature algorithm string component */
1923 #define TLS_MAX_SIGSTRING_LEN   40
1924 
1925 static int sig_cb(const char *elem, int len, void *arg)
1926 {
1927     sig_cb_st *sarg = arg;
1928     size_t i;
1929     const SIGALG_LOOKUP *s;
1930     char etmp[TLS_MAX_SIGSTRING_LEN], *p;
1931     int sig_alg = NID_undef, hash_alg = NID_undef;
1932     if (elem == NULL)
1933         return 0;
1934     if (sarg->sigalgcnt == TLS_MAX_SIGALGCNT)
1935         return 0;
1936     if (len > (int)(sizeof(etmp) - 1))
1937         return 0;
1938     memcpy(etmp, elem, len);
1939     etmp[len] = 0;
1940     p = strchr(etmp, '+');
1941     /*
1942      * We only allow SignatureSchemes listed in the sigalg_lookup_tbl;
1943      * if there's no '+' in the provided name, look for the new-style combined
1944      * name.  If not, match both sig+hash to find the needed SIGALG_LOOKUP.
1945      * Just sig+hash is not unique since TLS 1.3 adds rsa_pss_pss_* and
1946      * rsa_pss_rsae_* that differ only by public key OID; in such cases
1947      * we will pick the _rsae_ variant, by virtue of them appearing earlier
1948      * in the table.
1949      */
1950     if (p == NULL) {
1951         for (i = 0, s = sigalg_lookup_tbl; i < OSSL_NELEM(sigalg_lookup_tbl);
1952              i++, s++) {
1953             if (s->name != NULL && strcmp(etmp, s->name) == 0) {
1954                 sarg->sigalgs[sarg->sigalgcnt++] = s->sigalg;
1955                 break;
1956             }
1957         }
1958         if (i == OSSL_NELEM(sigalg_lookup_tbl))
1959             return 0;
1960     } else {
1961         *p = 0;
1962         p++;
1963         if (*p == 0)
1964             return 0;
1965         get_sigorhash(&sig_alg, &hash_alg, etmp);
1966         get_sigorhash(&sig_alg, &hash_alg, p);
1967         if (sig_alg == NID_undef || hash_alg == NID_undef)
1968             return 0;
1969         for (i = 0, s = sigalg_lookup_tbl; i < OSSL_NELEM(sigalg_lookup_tbl);
1970              i++, s++) {
1971             if (s->hash == hash_alg && s->sig == sig_alg) {
1972                 sarg->sigalgs[sarg->sigalgcnt++] = s->sigalg;
1973                 break;
1974             }
1975         }
1976         if (i == OSSL_NELEM(sigalg_lookup_tbl))
1977             return 0;
1978     }
1979 
1980     /* Reject duplicates */
1981     for (i = 0; i < sarg->sigalgcnt - 1; i++) {
1982         if (sarg->sigalgs[i] == sarg->sigalgs[sarg->sigalgcnt - 1]) {
1983             sarg->sigalgcnt--;
1984             return 0;
1985         }
1986     }
1987     return 1;
1988 }
1989 
1990 /*
1991  * Set supported signature algorithms based on a colon separated list of the
1992  * form sig+hash e.g. RSA+SHA512:DSA+SHA512
1993  */
1994 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
1995 {
1996     sig_cb_st sig;
1997     sig.sigalgcnt = 0;
1998     if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
1999         return 0;
2000     if (c == NULL)
2001         return 1;
2002     return tls1_set_raw_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
2003 }
2004 
2005 int tls1_set_raw_sigalgs(CERT *c, const uint16_t *psigs, size_t salglen,
2006                      int client)
2007 {
2008     uint16_t *sigalgs;
2009 
2010     if ((sigalgs = OPENSSL_malloc(salglen * sizeof(*sigalgs))) == NULL) {
2011         SSLerr(SSL_F_TLS1_SET_RAW_SIGALGS, ERR_R_MALLOC_FAILURE);
2012         return 0;
2013     }
2014     memcpy(sigalgs, psigs, salglen * sizeof(*sigalgs));
2015 
2016     if (client) {
2017         OPENSSL_free(c->client_sigalgs);
2018         c->client_sigalgs = sigalgs;
2019         c->client_sigalgslen = salglen;
2020     } else {
2021         OPENSSL_free(c->conf_sigalgs);
2022         c->conf_sigalgs = sigalgs;
2023         c->conf_sigalgslen = salglen;
2024     }
2025 
2026     return 1;
2027 }
2028 
2029 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
2030 {
2031     uint16_t *sigalgs, *sptr;
2032     size_t i;
2033 
2034     if (salglen & 1)
2035         return 0;
2036     if ((sigalgs = OPENSSL_malloc((salglen / 2) * sizeof(*sigalgs))) == NULL) {
2037         SSLerr(SSL_F_TLS1_SET_SIGALGS, ERR_R_MALLOC_FAILURE);
2038         return 0;
2039     }
2040     for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
2041         size_t j;
2042         const SIGALG_LOOKUP *curr;
2043         int md_id = *psig_nids++;
2044         int sig_id = *psig_nids++;
2045 
2046         for (j = 0, curr = sigalg_lookup_tbl; j < OSSL_NELEM(sigalg_lookup_tbl);
2047              j++, curr++) {
2048             if (curr->hash == md_id && curr->sig == sig_id) {
2049                 *sptr++ = curr->sigalg;
2050                 break;
2051             }
2052         }
2053 
2054         if (j == OSSL_NELEM(sigalg_lookup_tbl))
2055             goto err;
2056     }
2057 
2058     if (client) {
2059         OPENSSL_free(c->client_sigalgs);
2060         c->client_sigalgs = sigalgs;
2061         c->client_sigalgslen = salglen / 2;
2062     } else {
2063         OPENSSL_free(c->conf_sigalgs);
2064         c->conf_sigalgs = sigalgs;
2065         c->conf_sigalgslen = salglen / 2;
2066     }
2067 
2068     return 1;
2069 
2070  err:
2071     OPENSSL_free(sigalgs);
2072     return 0;
2073 }
2074 
2075 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
2076 {
2077     int sig_nid;
2078     size_t i;
2079     if (default_nid == -1)
2080         return 1;
2081     sig_nid = X509_get_signature_nid(x);
2082     if (default_nid)
2083         return sig_nid == default_nid ? 1 : 0;
2084     for (i = 0; i < c->shared_sigalgslen; i++)
2085         if (sig_nid == c->shared_sigalgs[i]->sigandhash)
2086             return 1;
2087     return 0;
2088 }
2089 
2090 /* Check to see if a certificate issuer name matches list of CA names */
2091 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
2092 {
2093     X509_NAME *nm;
2094     int i;
2095     nm = X509_get_issuer_name(x);
2096     for (i = 0; i < sk_X509_NAME_num(names); i++) {
2097         if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
2098             return 1;
2099     }
2100     return 0;
2101 }
2102 
2103 /*
2104  * Check certificate chain is consistent with TLS extensions and is usable by
2105  * server. This servers two purposes: it allows users to check chains before
2106  * passing them to the server and it allows the server to check chains before
2107  * attempting to use them.
2108  */
2109 
2110 /* Flags which need to be set for a certificate when strict mode not set */
2111 
2112 #define CERT_PKEY_VALID_FLAGS \
2113         (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
2114 /* Strict mode flags */
2115 #define CERT_PKEY_STRICT_FLAGS \
2116          (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
2117          | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
2118 
2119 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
2120                      int idx)
2121 {
2122     int i;
2123     int rv = 0;
2124     int check_flags = 0, strict_mode;
2125     CERT_PKEY *cpk = NULL;
2126     CERT *c = s->cert;
2127     uint32_t *pvalid;
2128     unsigned int suiteb_flags = tls1_suiteb(s);
2129     /* idx == -1 means checking server chains */
2130     if (idx != -1) {
2131         /* idx == -2 means checking client certificate chains */
2132         if (idx == -2) {
2133             cpk = c->key;
2134             idx = (int)(cpk - c->pkeys);
2135         } else
2136             cpk = c->pkeys + idx;
2137         pvalid = s->s3->tmp.valid_flags + idx;
2138         x = cpk->x509;
2139         pk = cpk->privatekey;
2140         chain = cpk->chain;
2141         strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
2142         /* If no cert or key, forget it */
2143         if (!x || !pk)
2144             goto end;
2145     } else {
2146         size_t certidx;
2147 
2148         if (!x || !pk)
2149             return 0;
2150 
2151         if (ssl_cert_lookup_by_pkey(pk, &certidx) == NULL)
2152             return 0;
2153         idx = certidx;
2154         pvalid = s->s3->tmp.valid_flags + idx;
2155 
2156         if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
2157             check_flags = CERT_PKEY_STRICT_FLAGS;
2158         else
2159             check_flags = CERT_PKEY_VALID_FLAGS;
2160         strict_mode = 1;
2161     }
2162 
2163     if (suiteb_flags) {
2164         int ok;
2165         if (check_flags)
2166             check_flags |= CERT_PKEY_SUITEB;
2167         ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
2168         if (ok == X509_V_OK)
2169             rv |= CERT_PKEY_SUITEB;
2170         else if (!check_flags)
2171             goto end;
2172     }
2173 
2174     /*
2175      * Check all signature algorithms are consistent with signature
2176      * algorithms extension if TLS 1.2 or later and strict mode.
2177      */
2178     if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
2179         int default_nid;
2180         int rsign = 0;
2181         if (s->s3->tmp.peer_cert_sigalgs != NULL
2182                 || s->s3->tmp.peer_sigalgs != NULL) {
2183             default_nid = 0;
2184         /* If no sigalgs extension use defaults from RFC5246 */
2185         } else {
2186             switch (idx) {
2187             case SSL_PKEY_RSA:
2188                 rsign = EVP_PKEY_RSA;
2189                 default_nid = NID_sha1WithRSAEncryption;
2190                 break;
2191 
2192             case SSL_PKEY_DSA_SIGN:
2193                 rsign = EVP_PKEY_DSA;
2194                 default_nid = NID_dsaWithSHA1;
2195                 break;
2196 
2197             case SSL_PKEY_ECC:
2198                 rsign = EVP_PKEY_EC;
2199                 default_nid = NID_ecdsa_with_SHA1;
2200                 break;
2201 
2202             case SSL_PKEY_GOST01:
2203                 rsign = NID_id_GostR3410_2001;
2204                 default_nid = NID_id_GostR3411_94_with_GostR3410_2001;
2205                 break;
2206 
2207             case SSL_PKEY_GOST12_256:
2208                 rsign = NID_id_GostR3410_2012_256;
2209                 default_nid = NID_id_tc26_signwithdigest_gost3410_2012_256;
2210                 break;
2211 
2212             case SSL_PKEY_GOST12_512:
2213                 rsign = NID_id_GostR3410_2012_512;
2214                 default_nid = NID_id_tc26_signwithdigest_gost3410_2012_512;
2215                 break;
2216 
2217             default:
2218                 default_nid = -1;
2219                 break;
2220             }
2221         }
2222         /*
2223          * If peer sent no signature algorithms extension and we have set
2224          * preferred signature algorithms check we support sha1.
2225          */
2226         if (default_nid > 0 && c->conf_sigalgs) {
2227             size_t j;
2228             const uint16_t *p = c->conf_sigalgs;
2229             for (j = 0; j < c->conf_sigalgslen; j++, p++) {
2230                 const SIGALG_LOOKUP *lu = tls1_lookup_sigalg(*p);
2231 
2232                 if (lu != NULL && lu->hash == NID_sha1 && lu->sig == rsign)
2233                     break;
2234             }
2235             if (j == c->conf_sigalgslen) {
2236                 if (check_flags)
2237                     goto skip_sigs;
2238                 else
2239                     goto end;
2240             }
2241         }
2242         /* Check signature algorithm of each cert in chain */
2243         if (!tls1_check_sig_alg(c, x, default_nid)) {
2244             if (!check_flags)
2245                 goto end;
2246         } else
2247             rv |= CERT_PKEY_EE_SIGNATURE;
2248         rv |= CERT_PKEY_CA_SIGNATURE;
2249         for (i = 0; i < sk_X509_num(chain); i++) {
2250             if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) {
2251                 if (check_flags) {
2252                     rv &= ~CERT_PKEY_CA_SIGNATURE;
2253                     break;
2254                 } else
2255                     goto end;
2256             }
2257         }
2258     }
2259     /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
2260     else if (check_flags)
2261         rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
2262  skip_sigs:
2263     /* Check cert parameters are consistent */
2264     if (tls1_check_cert_param(s, x, 1))
2265         rv |= CERT_PKEY_EE_PARAM;
2266     else if (!check_flags)
2267         goto end;
2268     if (!s->server)
2269         rv |= CERT_PKEY_CA_PARAM;
2270     /* In strict mode check rest of chain too */
2271     else if (strict_mode) {
2272         rv |= CERT_PKEY_CA_PARAM;
2273         for (i = 0; i < sk_X509_num(chain); i++) {
2274             X509 *ca = sk_X509_value(chain, i);
2275             if (!tls1_check_cert_param(s, ca, 0)) {
2276                 if (check_flags) {
2277                     rv &= ~CERT_PKEY_CA_PARAM;
2278                     break;
2279                 } else
2280                     goto end;
2281             }
2282         }
2283     }
2284     if (!s->server && strict_mode) {
2285         STACK_OF(X509_NAME) *ca_dn;
2286         int check_type = 0;
2287         switch (EVP_PKEY_id(pk)) {
2288         case EVP_PKEY_RSA:
2289             check_type = TLS_CT_RSA_SIGN;
2290             break;
2291         case EVP_PKEY_DSA:
2292             check_type = TLS_CT_DSS_SIGN;
2293             break;
2294         case EVP_PKEY_EC:
2295             check_type = TLS_CT_ECDSA_SIGN;
2296             break;
2297         }
2298         if (check_type) {
2299             const uint8_t *ctypes = s->s3->tmp.ctype;
2300             size_t j;
2301 
2302             for (j = 0; j < s->s3->tmp.ctype_len; j++, ctypes++) {
2303                 if (*ctypes == check_type) {
2304                     rv |= CERT_PKEY_CERT_TYPE;
2305                     break;
2306                 }
2307             }
2308             if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
2309                 goto end;
2310         } else {
2311             rv |= CERT_PKEY_CERT_TYPE;
2312         }
2313 
2314         ca_dn = s->s3->tmp.peer_ca_names;
2315 
2316         if (!sk_X509_NAME_num(ca_dn))
2317             rv |= CERT_PKEY_ISSUER_NAME;
2318 
2319         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
2320             if (ssl_check_ca_name(ca_dn, x))
2321                 rv |= CERT_PKEY_ISSUER_NAME;
2322         }
2323         if (!(rv & CERT_PKEY_ISSUER_NAME)) {
2324             for (i = 0; i < sk_X509_num(chain); i++) {
2325                 X509 *xtmp = sk_X509_value(chain, i);
2326                 if (ssl_check_ca_name(ca_dn, xtmp)) {
2327                     rv |= CERT_PKEY_ISSUER_NAME;
2328                     break;
2329                 }
2330             }
2331         }
2332         if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
2333             goto end;
2334     } else
2335         rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
2336 
2337     if (!check_flags || (rv & check_flags) == check_flags)
2338         rv |= CERT_PKEY_VALID;
2339 
2340  end:
2341 
2342     if (TLS1_get_version(s) >= TLS1_2_VERSION)
2343         rv |= *pvalid & (CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN);
2344     else
2345         rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
2346 
2347     /*
2348      * When checking a CERT_PKEY structure all flags are irrelevant if the
2349      * chain is invalid.
2350      */
2351     if (!check_flags) {
2352         if (rv & CERT_PKEY_VALID) {
2353             *pvalid = rv;
2354         } else {
2355             /* Preserve sign and explicit sign flag, clear rest */
2356             *pvalid &= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
2357             return 0;
2358         }
2359     }
2360     return rv;
2361 }
2362 
2363 /* Set validity of certificates in an SSL structure */
2364 void tls1_set_cert_validity(SSL *s)
2365 {
2366     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA);
2367     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_PSS_SIGN);
2368     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
2369     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
2370     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST01);
2371     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_256);
2372     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_512);
2373     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ED25519);
2374     tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ED448);
2375 }
2376 
2377 /* User level utility function to check a chain is suitable */
2378 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
2379 {
2380     return tls1_check_chain(s, x, pk, chain, -1);
2381 }
2382 
2383 #ifndef OPENSSL_NO_DH
2384 DH *ssl_get_auto_dh(SSL *s)
2385 {
2386     int dh_secbits = 80;
2387     if (s->cert->dh_tmp_auto == 2)
2388         return DH_get_1024_160();
2389     if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aPSK)) {
2390         if (s->s3->tmp.new_cipher->strength_bits == 256)
2391             dh_secbits = 128;
2392         else
2393             dh_secbits = 80;
2394     } else {
2395         if (s->s3->tmp.cert == NULL)
2396             return NULL;
2397         dh_secbits = EVP_PKEY_security_bits(s->s3->tmp.cert->privatekey);
2398     }
2399 
2400     if (dh_secbits >= 128) {
2401         DH *dhp = DH_new();
2402         BIGNUM *p, *g;
2403         if (dhp == NULL)
2404             return NULL;
2405         g = BN_new();
2406         if (g == NULL || !BN_set_word(g, 2)) {
2407             DH_free(dhp);
2408             BN_free(g);
2409             return NULL;
2410         }
2411         if (dh_secbits >= 192)
2412             p = BN_get_rfc3526_prime_8192(NULL);
2413         else
2414             p = BN_get_rfc3526_prime_3072(NULL);
2415         if (p == NULL || !DH_set0_pqg(dhp, p, NULL, g)) {
2416             DH_free(dhp);
2417             BN_free(p);
2418             BN_free(g);
2419             return NULL;
2420         }
2421         return dhp;
2422     }
2423     if (dh_secbits >= 112)
2424         return DH_get_2048_224();
2425     return DH_get_1024_160();
2426 }
2427 #endif
2428 
2429 static int ssl_security_cert_key(SSL *s, SSL_CTX *ctx, X509 *x, int op)
2430 {
2431     int secbits = -1;
2432     EVP_PKEY *pkey = X509_get0_pubkey(x);
2433     if (pkey) {
2434         /*
2435          * If no parameters this will return -1 and fail using the default
2436          * security callback for any non-zero security level. This will
2437          * reject keys which omit parameters but this only affects DSA and
2438          * omission of parameters is never (?) done in practice.
2439          */
2440         secbits = EVP_PKEY_security_bits(pkey);
2441     }
2442     if (s)
2443         return ssl_security(s, op, secbits, 0, x);
2444     else
2445         return ssl_ctx_security(ctx, op, secbits, 0, x);
2446 }
2447 
2448 static int ssl_security_cert_sig(SSL *s, SSL_CTX *ctx, X509 *x, int op)
2449 {
2450     /* Lookup signature algorithm digest */
2451     int secbits, nid, pknid;
2452     /* Don't check signature if self signed */
2453     if ((X509_get_extension_flags(x) & EXFLAG_SS) != 0)
2454         return 1;
2455     if (!X509_get_signature_info(x, &nid, &pknid, &secbits, NULL))
2456         secbits = -1;
2457     /* If digest NID not defined use signature NID */
2458     if (nid == NID_undef)
2459         nid = pknid;
2460     if (s)
2461         return ssl_security(s, op, secbits, nid, x);
2462     else
2463         return ssl_ctx_security(ctx, op, secbits, nid, x);
2464 }
2465 
2466 int ssl_security_cert(SSL *s, SSL_CTX *ctx, X509 *x, int vfy, int is_ee)
2467 {
2468     if (vfy)
2469         vfy = SSL_SECOP_PEER;
2470     if (is_ee) {
2471         if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_EE_KEY | vfy))
2472             return SSL_R_EE_KEY_TOO_SMALL;
2473     } else {
2474         if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_CA_KEY | vfy))
2475             return SSL_R_CA_KEY_TOO_SMALL;
2476     }
2477     if (!ssl_security_cert_sig(s, ctx, x, SSL_SECOP_CA_MD | vfy))
2478         return SSL_R_CA_MD_TOO_WEAK;
2479     return 1;
2480 }
2481 
2482 /*
2483  * Check security of a chain, if |sk| includes the end entity certificate then
2484  * |x| is NULL. If |vfy| is 1 then we are verifying a peer chain and not sending
2485  * one to the peer. Return values: 1 if ok otherwise error code to use
2486  */
2487 
2488 int ssl_security_cert_chain(SSL *s, STACK_OF(X509) *sk, X509 *x, int vfy)
2489 {
2490     int rv, start_idx, i;
2491     if (x == NULL) {
2492         x = sk_X509_value(sk, 0);
2493         start_idx = 1;
2494     } else
2495         start_idx = 0;
2496 
2497     rv = ssl_security_cert(s, NULL, x, vfy, 1);
2498     if (rv != 1)
2499         return rv;
2500 
2501     for (i = start_idx; i < sk_X509_num(sk); i++) {
2502         x = sk_X509_value(sk, i);
2503         rv = ssl_security_cert(s, NULL, x, vfy, 0);
2504         if (rv != 1)
2505             return rv;
2506     }
2507     return 1;
2508 }
2509 
2510 /*
2511  * For TLS 1.2 servers check if we have a certificate which can be used
2512  * with the signature algorithm "lu" and return index of certificate.
2513  */
2514 
2515 static int tls12_get_cert_sigalg_idx(const SSL *s, const SIGALG_LOOKUP *lu)
2516 {
2517     int sig_idx = lu->sig_idx;
2518     const SSL_CERT_LOOKUP *clu = ssl_cert_lookup_by_idx(sig_idx);
2519 
2520     /* If not recognised or not supported by cipher mask it is not suitable */
2521     if (clu == NULL
2522             || (clu->amask & s->s3->tmp.new_cipher->algorithm_auth) == 0
2523             || (clu->nid == EVP_PKEY_RSA_PSS
2524                 && (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kRSA) != 0))
2525         return -1;
2526 
2527     return s->s3->tmp.valid_flags[sig_idx] & CERT_PKEY_VALID ? sig_idx : -1;
2528 }
2529 
2530 /*
2531  * Returns true if |s| has a usable certificate configured for use
2532  * with signature scheme |sig|.
2533  * "Usable" includes a check for presence as well as applying
2534  * the signature_algorithm_cert restrictions sent by the peer (if any).
2535  * Returns false if no usable certificate is found.
2536  */
2537 static int has_usable_cert(SSL *s, const SIGALG_LOOKUP *sig, int idx)
2538 {
2539     const SIGALG_LOOKUP *lu;
2540     int mdnid, pknid, default_mdnid;
2541     int mandatory_md = 0;
2542     size_t i;
2543 
2544     /* TLS 1.2 callers can override lu->sig_idx, but not TLS 1.3 callers. */
2545     if (idx == -1)
2546         idx = sig->sig_idx;
2547     if (!ssl_has_cert(s, idx))
2548         return 0;
2549     /* If the EVP_PKEY reports a mandatory digest, allow nothing else. */
2550     ERR_set_mark();
2551     switch (EVP_PKEY_get_default_digest_nid(s->cert->pkeys[idx].privatekey,
2552                                             &default_mdnid)) {
2553     case 2:
2554         mandatory_md = 1;
2555         break;
2556     case 1:
2557         break;
2558     default: /* If it didn't report a mandatory NID, for whatever reasons,
2559               * just clear the error and allow all hashes to be used. */
2560         ERR_pop_to_mark();
2561     }
2562     if (s->s3->tmp.peer_cert_sigalgs != NULL) {
2563         for (i = 0; i < s->s3->tmp.peer_cert_sigalgslen; i++) {
2564             lu = tls1_lookup_sigalg(s->s3->tmp.peer_cert_sigalgs[i]);
2565             if (lu == NULL
2566                 || !X509_get_signature_info(s->cert->pkeys[idx].x509, &mdnid,
2567                                             &pknid, NULL, NULL)
2568                 || (mandatory_md && mdnid != default_mdnid))
2569                 continue;
2570             /*
2571              * TODO this does not differentiate between the
2572              * rsa_pss_pss_* and rsa_pss_rsae_* schemes since we do not
2573              * have a chain here that lets us look at the key OID in the
2574              * signing certificate.
2575              */
2576             if (mdnid == lu->hash && pknid == lu->sig)
2577                 return 1;
2578         }
2579         return 0;
2580     }
2581     return !mandatory_md || sig->hash == default_mdnid;
2582 }
2583 
2584 /*
2585  * Choose an appropriate signature algorithm based on available certificates
2586  * Sets chosen certificate and signature algorithm.
2587  *
2588  * For servers if we fail to find a required certificate it is a fatal error,
2589  * an appropriate error code is set and a TLS alert is sent.
2590  *
2591  * For clients fatalerrs is set to 0. If a certificate is not suitable it is not
2592  * a fatal error: we will either try another certificate or not present one
2593  * to the server. In this case no error is set.
2594  */
2595 int tls_choose_sigalg(SSL *s, int fatalerrs)
2596 {
2597     const SIGALG_LOOKUP *lu = NULL;
2598     int sig_idx = -1;
2599 
2600     s->s3->tmp.cert = NULL;
2601     s->s3->tmp.sigalg = NULL;
2602 
2603     if (SSL_IS_TLS13(s)) {
2604         size_t i;
2605 #ifndef OPENSSL_NO_EC
2606         int curve = -1;
2607 #endif
2608 
2609         /* Look for a certificate matching shared sigalgs */
2610         for (i = 0; i < s->cert->shared_sigalgslen; i++) {
2611             lu = s->cert->shared_sigalgs[i];
2612             sig_idx = -1;
2613 
2614             /* Skip SHA1, SHA224, DSA and RSA if not PSS */
2615             if (lu->hash == NID_sha1
2616                 || lu->hash == NID_sha224
2617                 || lu->sig == EVP_PKEY_DSA
2618                 || lu->sig == EVP_PKEY_RSA)
2619                 continue;
2620             /* Check that we have a cert, and signature_algorithms_cert */
2621             if (!tls1_lookup_md(lu, NULL) || !has_usable_cert(s, lu, -1))
2622                 continue;
2623             if (lu->sig == EVP_PKEY_EC) {
2624 #ifndef OPENSSL_NO_EC
2625                 if (curve == -1) {
2626                     EC_KEY *ec = EVP_PKEY_get0_EC_KEY(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
2627 
2628                     curve = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2629                 }
2630                 if (lu->curve != NID_undef && curve != lu->curve)
2631                     continue;
2632 #else
2633                 continue;
2634 #endif
2635             } else if (lu->sig == EVP_PKEY_RSA_PSS) {
2636                 /* validate that key is large enough for the signature algorithm */
2637                 EVP_PKEY *pkey;
2638 
2639                 pkey = s->cert->pkeys[lu->sig_idx].privatekey;
2640                 if (!rsa_pss_check_min_key_size(EVP_PKEY_get0(pkey), lu))
2641                     continue;
2642             }
2643             break;
2644         }
2645         if (i == s->cert->shared_sigalgslen) {
2646             if (!fatalerrs)
2647                 return 1;
2648             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_CHOOSE_SIGALG,
2649                      SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
2650             return 0;
2651         }
2652     } else {
2653         /* If ciphersuite doesn't require a cert nothing to do */
2654         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aCERT))
2655             return 1;
2656         if (!s->server && !ssl_has_cert(s, s->cert->key - s->cert->pkeys))
2657                 return 1;
2658 
2659         if (SSL_USE_SIGALGS(s)) {
2660             size_t i;
2661             if (s->s3->tmp.peer_sigalgs != NULL) {
2662 #ifndef OPENSSL_NO_EC
2663                 int curve;
2664 
2665                 /* For Suite B need to match signature algorithm to curve */
2666                 if (tls1_suiteb(s)) {
2667                     EC_KEY *ec = EVP_PKEY_get0_EC_KEY(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
2668                     curve = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
2669                 } else {
2670                     curve = -1;
2671                 }
2672 #endif
2673 
2674                 /*
2675                  * Find highest preference signature algorithm matching
2676                  * cert type
2677                  */
2678                 for (i = 0; i < s->cert->shared_sigalgslen; i++) {
2679                     lu = s->cert->shared_sigalgs[i];
2680 
2681                     if (s->server) {
2682                         if ((sig_idx = tls12_get_cert_sigalg_idx(s, lu)) == -1)
2683                             continue;
2684                     } else {
2685                         int cc_idx = s->cert->key - s->cert->pkeys;
2686 
2687                         sig_idx = lu->sig_idx;
2688                         if (cc_idx != sig_idx)
2689                             continue;
2690                     }
2691                     /* Check that we have a cert, and sig_algs_cert */
2692                     if (!has_usable_cert(s, lu, sig_idx))
2693                         continue;
2694                     if (lu->sig == EVP_PKEY_RSA_PSS) {
2695                         /* validate that key is large enough for the signature algorithm */
2696                         EVP_PKEY *pkey = s->cert->pkeys[sig_idx].privatekey;
2697 
2698                         if (!rsa_pss_check_min_key_size(EVP_PKEY_get0(pkey), lu))
2699                             continue;
2700                     }
2701 #ifndef OPENSSL_NO_EC
2702                     if (curve == -1 || lu->curve == curve)
2703 #endif
2704                         break;
2705                 }
2706                 if (i == s->cert->shared_sigalgslen) {
2707                     if (!fatalerrs)
2708                         return 1;
2709                     SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2710                              SSL_F_TLS_CHOOSE_SIGALG,
2711                              SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM);
2712                     return 0;
2713                 }
2714             } else {
2715                 /*
2716                  * If we have no sigalg use defaults
2717                  */
2718                 const uint16_t *sent_sigs;
2719                 size_t sent_sigslen;
2720 
2721                 if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
2722                     if (!fatalerrs)
2723                         return 1;
2724                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CHOOSE_SIGALG,
2725                              ERR_R_INTERNAL_ERROR);
2726                     return 0;
2727                 }
2728 
2729                 /* Check signature matches a type we sent */
2730                 sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs);
2731                 for (i = 0; i < sent_sigslen; i++, sent_sigs++) {
2732                     if (lu->sigalg == *sent_sigs
2733                             && has_usable_cert(s, lu, lu->sig_idx))
2734                         break;
2735                 }
2736                 if (i == sent_sigslen) {
2737                     if (!fatalerrs)
2738                         return 1;
2739                     SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2740                              SSL_F_TLS_CHOOSE_SIGALG,
2741                              SSL_R_WRONG_SIGNATURE_TYPE);
2742                     return 0;
2743                 }
2744             }
2745         } else {
2746             if ((lu = tls1_get_legacy_sigalg(s, -1)) == NULL) {
2747                 if (!fatalerrs)
2748                     return 1;
2749                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CHOOSE_SIGALG,
2750                          ERR_R_INTERNAL_ERROR);
2751                 return 0;
2752             }
2753         }
2754     }
2755     if (sig_idx == -1)
2756         sig_idx = lu->sig_idx;
2757     s->s3->tmp.cert = &s->cert->pkeys[sig_idx];
2758     s->cert->key = s->s3->tmp.cert;
2759     s->s3->tmp.sigalg = lu;
2760     return 1;
2761 }
2762 
2763 int SSL_CTX_set_tlsext_max_fragment_length(SSL_CTX *ctx, uint8_t mode)
2764 {
2765     if (mode != TLSEXT_max_fragment_length_DISABLED
2766             && !IS_MAX_FRAGMENT_LENGTH_EXT_VALID(mode)) {
2767         SSLerr(SSL_F_SSL_CTX_SET_TLSEXT_MAX_FRAGMENT_LENGTH,
2768                SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
2769         return 0;
2770     }
2771 
2772     ctx->ext.max_fragment_len_mode = mode;
2773     return 1;
2774 }
2775 
2776 int SSL_set_tlsext_max_fragment_length(SSL *ssl, uint8_t mode)
2777 {
2778     if (mode != TLSEXT_max_fragment_length_DISABLED
2779             && !IS_MAX_FRAGMENT_LENGTH_EXT_VALID(mode)) {
2780         SSLerr(SSL_F_SSL_SET_TLSEXT_MAX_FRAGMENT_LENGTH,
2781                SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH);
2782         return 0;
2783     }
2784 
2785     ssl->ext.max_fragment_len_mode = mode;
2786     return 1;
2787 }
2788 
2789 uint8_t SSL_SESSION_get_max_fragment_length(const SSL_SESSION *session)
2790 {
2791     return session->ext.max_fragment_len_mode;
2792 }
2793