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