1bc01e1d25594979878b73812c81d2fd5120de92
[openssl.git] / ssl / statem / statem_lib.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include <limits.h>
12 #include <string.h>
13 #include <stdio.h>
14 #include "../ssl_local.h"
15 #include "statem_local.h"
16 #include "internal/cryptlib.h"
17 #include <openssl/buffer.h>
18 #include <openssl/objects.h>
19 #include <openssl/evp.h>
20 #include <openssl/rsa.h>
21 #include <openssl/x509.h>
22 #include <openssl/trace.h>
23
24 /*
25  * Map error codes to TLS/SSL alart types.
26  */
27 typedef struct x509err2alert_st {
28     int x509err;
29     int alert;
30 } X509ERR2ALERT;
31
32 /* Fixed value used in the ServerHello random field to identify an HRR */
33 const unsigned char hrrrandom[] = {
34     0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
35     0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
36     0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
37 };
38
39 int ossl_statem_set_mutator(SSL *s,
40                             ossl_statem_mutate_handshake_cb mutate_handshake_cb,
41                             ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb,
42                             void *mutatearg)
43 {
44     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
45
46     if (sc == NULL)
47         return 0;
48
49     sc->statem.mutate_handshake_cb = mutate_handshake_cb;
50     sc->statem.mutatearg = mutatearg;
51     sc->statem.finish_mutate_handshake_cb = finish_mutate_handshake_cb;
52
53     return 1;
54 }
55
56 /*
57  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
58  * SSL3_RT_CHANGE_CIPHER_SPEC)
59  */
60 int ssl3_do_write(SSL_CONNECTION *s, int type)
61 {
62     int ret;
63     size_t written = 0;
64     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
65
66     /*
67      * If we're running the test suite then we may need to mutate the message
68      * we've been asked to write. Does not happen in normal operation.
69      */
70     if (s->statem.mutate_handshake_cb != NULL
71             && !s->statem.write_in_progress
72             && type == SSL3_RT_HANDSHAKE
73             && s->init_num >= SSL3_HM_HEADER_LENGTH) {
74         unsigned char *msg;
75         size_t msglen;
76
77         if (!s->statem.mutate_handshake_cb((unsigned char *)s->init_buf->data,
78                                            s->init_num,
79                                            &msg, &msglen,
80                                            s->statem.mutatearg))
81             return -1;
82         if (msglen < SSL3_HM_HEADER_LENGTH
83                 || !BUF_MEM_grow(s->init_buf, msglen))
84             return -1;
85         memcpy(s->init_buf->data, msg, msglen);
86         s->init_num = msglen;
87         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
88         s->statem.finish_mutate_handshake_cb(s->statem.mutatearg);
89         s->statem.write_in_progress = 1;
90     }
91
92     ret = ssl3_write_bytes(ssl, type, &s->init_buf->data[s->init_off],
93                            s->init_num, &written);
94     if (ret < 0)
95         return -1;
96     if (type == SSL3_RT_HANDSHAKE)
97         /*
98          * should not be done for 'Hello Request's, but in that case we'll
99          * ignore the result anyway
100          * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
101          */
102         if (!SSL_CONNECTION_IS_TLS13(s)
103             || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
104                                  && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
105                                  && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
106             if (!ssl3_finish_mac(s,
107                                  (unsigned char *)&s->init_buf->data[s->init_off],
108                                  written))
109                 return -1;
110     if (written == s->init_num) {
111         s->statem.write_in_progress = 0;
112         if (s->msg_callback)
113             s->msg_callback(1, s->version, type, s->init_buf->data,
114                             (size_t)(s->init_off + s->init_num), ssl,
115                             s->msg_callback_arg);
116         return 1;
117     }
118     s->init_off += written;
119     s->init_num -= written;
120     return 0;
121 }
122
123 int tls_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
124 {
125     size_t msglen;
126
127     if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
128             || !WPACKET_get_length(pkt, &msglen)
129             || msglen > INT_MAX)
130         return 0;
131     s->init_num = (int)msglen;
132     s->init_off = 0;
133
134     return 1;
135 }
136
137 int tls_setup_handshake(SSL_CONNECTION *s)
138 {
139     int ver_min, ver_max, ok;
140     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
141     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
142
143     if (!ssl3_init_finished_mac(s)) {
144         /* SSLfatal() already called */
145         return 0;
146     }
147
148     /* Reset any extension flags */
149     memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
150
151     if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
152         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
153         return 0;
154     }
155
156     /* Sanity check that we have MD5-SHA1 if we need it */
157     if (sctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
158         int md5sha1_needed = 0;
159
160         /* We don't have MD5-SHA1 - do we need it? */
161         if (SSL_CONNECTION_IS_DTLS(s)) {
162             if (DTLS_VERSION_LE(ver_max, DTLS1_VERSION))
163                 md5sha1_needed = 1;
164         } else {
165             if (ver_max <= TLS1_1_VERSION)
166                 md5sha1_needed = 1;
167         }
168         if (md5sha1_needed) {
169             SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
170                           SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
171                           "The max supported SSL/TLS version needs the"
172                           " MD5-SHA1 digest but it is not available"
173                           " in the loaded providers. Use (D)TLSv1.2 or"
174                           " above, or load different providers");
175             return 0;
176         }
177
178         ok = 1;
179         /* Don't allow TLSv1.1 or below to be negotiated */
180         if (SSL_CONNECTION_IS_DTLS(s)) {
181             if (DTLS_VERSION_LT(ver_min, DTLS1_2_VERSION))
182                 ok = SSL_set_min_proto_version(ssl, DTLS1_2_VERSION);
183         } else {
184             if (ver_min < TLS1_2_VERSION)
185                 ok = SSL_set_min_proto_version(ssl, TLS1_2_VERSION);
186         }
187         if (!ok) {
188             /* Shouldn't happen */
189             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
190             return 0;
191         }
192     }
193
194     ok = 0;
195     if (s->server) {
196         STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
197         int i;
198
199         /*
200          * Sanity check that the maximum version we accept has ciphers
201          * enabled. For clients we do this check during construction of the
202          * ClientHello.
203          */
204         for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
205             const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
206
207             if (SSL_CONNECTION_IS_DTLS(s)) {
208                 if (DTLS_VERSION_GE(ver_max, c->min_dtls) &&
209                         DTLS_VERSION_LE(ver_max, c->max_dtls))
210                     ok = 1;
211             } else if (ver_max >= c->min_tls && ver_max <= c->max_tls) {
212                 ok = 1;
213             }
214             if (ok)
215                 break;
216         }
217         if (!ok) {
218             SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
219                           SSL_R_NO_CIPHERS_AVAILABLE,
220                           "No ciphers enabled for max supported "
221                           "SSL/TLS version");
222             return 0;
223         }
224         if (SSL_IS_FIRST_HANDSHAKE(s)) {
225             /* N.B. s->session_ctx == s->ctx here */
226             ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
227         } else {
228             /* N.B. s->ctx may not equal s->session_ctx */
229             ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
230
231             s->s3.tmp.cert_request = 0;
232         }
233     } else {
234         if (SSL_IS_FIRST_HANDSHAKE(s))
235             ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
236         else
237             ssl_tsan_counter(s->session_ctx,
238                          &s->session_ctx->stats.sess_connect_renegotiate);
239
240         /* mark client_random uninitialized */
241         memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
242         s->hit = 0;
243
244         s->s3.tmp.cert_req = 0;
245
246         if (SSL_CONNECTION_IS_DTLS(s))
247             s->statem.use_timer = 1;
248     }
249
250     return 1;
251 }
252
253 /*
254  * Size of the to-be-signed TLS13 data, without the hash size itself:
255  * 64 bytes of value 32, 33 context bytes, 1 byte separator
256  */
257 #define TLS13_TBS_START_SIZE            64
258 #define TLS13_TBS_PREAMBLE_SIZE         (TLS13_TBS_START_SIZE + 33 + 1)
259
260 static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
261                                     void **hdata, size_t *hdatalen)
262 {
263     /* ASCII: "TLS 1.3, server CertificateVerify", in hex for EBCDIC compatibility */
264     static const char servercontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x73\x65\x72"
265         "\x76\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
266     /* ASCII: "TLS 1.3, client CertificateVerify", in hex for EBCDIC compatibility */
267     static const char clientcontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x63\x6c\x69"
268         "\x65\x6e\x74\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
269
270     if (SSL_CONNECTION_IS_TLS13(s)) {
271         size_t hashlen;
272
273         /* Set the first 64 bytes of to-be-signed data to octet 32 */
274         memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
275         /* This copies the 33 bytes of context plus the 0 separator byte */
276         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
277                  || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
278             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
279         else
280             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
281
282         /*
283          * If we're currently reading then we need to use the saved handshake
284          * hash value. We can't use the current handshake hash state because
285          * that includes the CertVerify itself.
286          */
287         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
288                 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
289             memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
290                    s->cert_verify_hash_len);
291             hashlen = s->cert_verify_hash_len;
292         } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
293                                        EVP_MAX_MD_SIZE, &hashlen)) {
294             /* SSLfatal() already called */
295             return 0;
296         }
297
298         *hdata = tls13tbs;
299         *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
300     } else {
301         size_t retlen;
302         long retlen_l;
303
304         retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
305         if (retlen_l <= 0) {
306             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
307             return 0;
308         }
309         *hdatalen = retlen;
310     }
311
312     return 1;
313 }
314
315 CON_FUNC_RETURN tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
316 {
317     EVP_PKEY *pkey = NULL;
318     const EVP_MD *md = NULL;
319     EVP_MD_CTX *mctx = NULL;
320     EVP_PKEY_CTX *pctx = NULL;
321     size_t hdatalen = 0, siglen = 0;
322     void *hdata;
323     unsigned char *sig = NULL;
324     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
325     const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
326     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
327
328     if (lu == NULL || s->s3.tmp.cert == NULL) {
329         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
330         goto err;
331     }
332     pkey = s->s3.tmp.cert->privatekey;
333
334     if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
335         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
336         goto err;
337     }
338
339     mctx = EVP_MD_CTX_new();
340     if (mctx == NULL) {
341         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
342         goto err;
343     }
344
345     /* Get the data to be signed */
346     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
347         /* SSLfatal() already called */
348         goto err;
349     }
350
351     if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
352         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
353         goto err;
354     }
355
356     if (EVP_DigestSignInit_ex(mctx, &pctx,
357                               md == NULL ? NULL : EVP_MD_get0_name(md),
358                               sctx->libctx, sctx->propq, pkey,
359                               NULL) <= 0) {
360         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
361         goto err;
362     }
363
364     if (lu->sig == EVP_PKEY_RSA_PSS) {
365         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
366             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
367                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
368             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
369             goto err;
370         }
371     }
372     if (s->version == SSL3_VERSION) {
373         /*
374          * Here we use EVP_DigestSignUpdate followed by EVP_DigestSignFinal
375          * in order to add the EVP_CTRL_SSL3_MASTER_SECRET call between them.
376          */
377         if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
378             || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
379                                (int)s->session->master_key_length,
380                                s->session->master_key) <= 0
381             || EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0) {
382
383             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
384             goto err;
385         }
386         sig = OPENSSL_malloc(siglen);
387         if (sig == NULL
388                 || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
389             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
390             goto err;
391         }
392     } else {
393         /*
394          * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
395          * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
396          */
397         if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
398             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
399             goto err;
400         }
401         sig = OPENSSL_malloc(siglen);
402         if (sig == NULL
403                 || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
404             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
405             goto err;
406         }
407     }
408
409 #ifndef OPENSSL_NO_GOST
410     {
411         int pktype = lu->sig;
412
413         if (pktype == NID_id_GostR3410_2001
414             || pktype == NID_id_GostR3410_2012_256
415             || pktype == NID_id_GostR3410_2012_512)
416             BUF_reverse(sig, NULL, siglen);
417     }
418 #endif
419
420     if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
421         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
422         goto err;
423     }
424
425     /* Digest cached records and discard handshake buffer */
426     if (!ssl3_digest_cached_records(s, 0)) {
427         /* SSLfatal() already called */
428         goto err;
429     }
430
431     OPENSSL_free(sig);
432     EVP_MD_CTX_free(mctx);
433     return CON_FUNC_SUCCESS;
434  err:
435     OPENSSL_free(sig);
436     EVP_MD_CTX_free(mctx);
437     return CON_FUNC_ERROR;
438 }
439
440 MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
441 {
442     EVP_PKEY *pkey = NULL;
443     const unsigned char *data;
444 #ifndef OPENSSL_NO_GOST
445     unsigned char *gost_data = NULL;
446 #endif
447     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
448     int j;
449     unsigned int len;
450     X509 *peer;
451     const EVP_MD *md = NULL;
452     size_t hdatalen = 0;
453     void *hdata;
454     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
455     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
456     EVP_PKEY_CTX *pctx = NULL;
457     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
458
459     if (mctx == NULL) {
460         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
461         goto err;
462     }
463
464     peer = s->session->peer;
465     pkey = X509_get0_pubkey(peer);
466     if (pkey == NULL) {
467         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
468         goto err;
469     }
470
471     if (ssl_cert_lookup_by_pkey(pkey, NULL, sctx) == NULL) {
472         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
473                  SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
474         goto err;
475     }
476
477     if (SSL_USE_SIGALGS(s)) {
478         unsigned int sigalg;
479
480         if (!PACKET_get_net_2(pkt, &sigalg)) {
481             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
482             goto err;
483         }
484         if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
485             /* SSLfatal() already called */
486             goto err;
487         }
488     } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
489             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
490                      SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
491             goto err;
492     }
493
494     if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
495         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
496         goto err;
497     }
498
499     if (SSL_USE_SIGALGS(s))
500         OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
501                     md == NULL ? "n/a" : EVP_MD_get0_name(md));
502
503     /* Check for broken implementations of GOST ciphersuites */
504     /*
505      * If key is GOST and len is exactly 64 or 128, it is signature without
506      * length field (CryptoPro implementations at least till TLS 1.2)
507      */
508 #ifndef OPENSSL_NO_GOST
509     if (!SSL_USE_SIGALGS(s)
510         && ((PACKET_remaining(pkt) == 64
511              && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
512                  || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
513             || (PACKET_remaining(pkt) == 128
514                 && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
515         len = PACKET_remaining(pkt);
516     } else
517 #endif
518     if (!PACKET_get_net_2(pkt, &len)) {
519         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
520         goto err;
521     }
522
523     if (!PACKET_get_bytes(pkt, &data, len)) {
524         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
525         goto err;
526     }
527
528     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
529         /* SSLfatal() already called */
530         goto err;
531     }
532
533     OSSL_TRACE1(TLS, "Using client verify alg %s\n",
534                 md == NULL ? "n/a" : EVP_MD_get0_name(md));
535
536     if (EVP_DigestVerifyInit_ex(mctx, &pctx,
537                                 md == NULL ? NULL : EVP_MD_get0_name(md),
538                                 sctx->libctx, sctx->propq, pkey,
539                                 NULL) <= 0) {
540         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
541         goto err;
542     }
543 #ifndef OPENSSL_NO_GOST
544     {
545         int pktype = EVP_PKEY_get_id(pkey);
546         if (pktype == NID_id_GostR3410_2001
547             || pktype == NID_id_GostR3410_2012_256
548             || pktype == NID_id_GostR3410_2012_512) {
549             if ((gost_data = OPENSSL_malloc(len)) == NULL)
550                 goto err;
551             BUF_reverse(gost_data, data, len);
552             data = gost_data;
553         }
554     }
555 #endif
556
557     if (SSL_USE_PSS(s)) {
558         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
559             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
560                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
561             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
562             goto err;
563         }
564     }
565     if (s->version == SSL3_VERSION) {
566         if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
567                 || EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
568                                    (int)s->session->master_key_length,
569                                     s->session->master_key) <= 0) {
570             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
571             goto err;
572         }
573         if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
574             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
575             goto err;
576         }
577     } else {
578         j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
579         if (j <= 0) {
580             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
581             goto err;
582         }
583     }
584
585     /*
586      * In TLSv1.3 on the client side we make sure we prepare the client
587      * certificate after the CertVerify instead of when we get the
588      * CertificateRequest. This is because in TLSv1.3 the CertificateRequest
589      * comes *before* the Certificate message. In TLSv1.2 it comes after. We
590      * want to make sure that SSL_get1_peer_certificate() will return the actual
591      * server certificate from the client_cert_cb callback.
592      */
593     if (!s->server && SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.cert_req == 1)
594         ret = MSG_PROCESS_CONTINUE_PROCESSING;
595     else
596         ret = MSG_PROCESS_CONTINUE_READING;
597  err:
598     BIO_free(s->s3.handshake_buffer);
599     s->s3.handshake_buffer = NULL;
600     EVP_MD_CTX_free(mctx);
601 #ifndef OPENSSL_NO_GOST
602     OPENSSL_free(gost_data);
603 #endif
604     return ret;
605 }
606
607 CON_FUNC_RETURN tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
608 {
609     size_t finish_md_len;
610     const char *sender;
611     size_t slen;
612     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
613
614     /* This is a real handshake so make sure we clean it up at the end */
615     if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
616         s->statem.cleanuphand = 1;
617
618     /*
619      * We only change the keys if we didn't already do this when we sent the
620      * client certificate
621      */
622     if (SSL_CONNECTION_IS_TLS13(s)
623             && !s->server
624             && s->s3.tmp.cert_req == 0
625             && (!ssl->method->ssl3_enc->change_cipher_state(s,
626                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
627         /* SSLfatal() already called */
628         return CON_FUNC_ERROR;
629     }
630
631     if (s->server) {
632         sender = ssl->method->ssl3_enc->server_finished_label;
633         slen = ssl->method->ssl3_enc->server_finished_label_len;
634     } else {
635         sender = ssl->method->ssl3_enc->client_finished_label;
636         slen = ssl->method->ssl3_enc->client_finished_label_len;
637     }
638
639     finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
640                                                             sender, slen,
641                                                             s->s3.tmp.finish_md);
642     if (finish_md_len == 0) {
643         /* SSLfatal() already called */
644         return CON_FUNC_ERROR;
645     }
646
647     s->s3.tmp.finish_md_len = finish_md_len;
648
649     if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
650         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
651         return CON_FUNC_ERROR;
652     }
653
654     /*
655      * Log the master secret, if logging is enabled. We don't log it for
656      * TLSv1.3: there's a different key schedule for that.
657      */
658     if (!SSL_CONNECTION_IS_TLS13(s)
659         && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
660                            s->session->master_key_length)) {
661         /* SSLfatal() already called */
662         return CON_FUNC_ERROR;
663     }
664
665     /*
666      * Copy the finished so we can use it for renegotiation checks
667      */
668     if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
669         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
670         return CON_FUNC_ERROR;
671     }
672     if (!s->server) {
673         memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
674                finish_md_len);
675         s->s3.previous_client_finished_len = finish_md_len;
676     } else {
677         memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
678                finish_md_len);
679         s->s3.previous_server_finished_len = finish_md_len;
680     }
681
682     return CON_FUNC_SUCCESS;
683 }
684
685 CON_FUNC_RETURN tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
686 {
687     if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
688         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
689         return CON_FUNC_ERROR;
690     }
691
692     s->key_update = SSL_KEY_UPDATE_NONE;
693     return CON_FUNC_SUCCESS;
694 }
695
696 MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
697 {
698     unsigned int updatetype;
699
700     /*
701      * A KeyUpdate message signals a key change so the end of the message must
702      * be on a record boundary.
703      */
704     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
705         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
706         return MSG_PROCESS_ERROR;
707     }
708
709     if (!PACKET_get_1(pkt, &updatetype)
710             || PACKET_remaining(pkt) != 0) {
711         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
712         return MSG_PROCESS_ERROR;
713     }
714
715     /*
716      * There are only two defined key update types. Fail if we get a value we
717      * didn't recognise.
718      */
719     if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
720             && updatetype != SSL_KEY_UPDATE_REQUESTED) {
721         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
722         return MSG_PROCESS_ERROR;
723     }
724
725     /*
726      * If we get a request for us to update our sending keys too then, we need
727      * to additionally send a KeyUpdate message. However that message should
728      * not also request an update (otherwise we get into an infinite loop).
729      */
730     if (updatetype == SSL_KEY_UPDATE_REQUESTED)
731         s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
732
733     if (!tls13_update_key(s, 0)) {
734         /* SSLfatal() already called */
735         return MSG_PROCESS_ERROR;
736     }
737
738     return MSG_PROCESS_FINISHED_READING;
739 }
740
741 /*
742  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
743  * to far.
744  */
745 int ssl3_take_mac(SSL_CONNECTION *s)
746 {
747     const char *sender;
748     size_t slen;
749     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
750
751     if (!s->server) {
752         sender = ssl->method->ssl3_enc->server_finished_label;
753         slen = ssl->method->ssl3_enc->server_finished_label_len;
754     } else {
755         sender = ssl->method->ssl3_enc->client_finished_label;
756         slen = ssl->method->ssl3_enc->client_finished_label_len;
757     }
758
759     s->s3.tmp.peer_finish_md_len =
760         ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
761                                                 s->s3.tmp.peer_finish_md);
762
763     if (s->s3.tmp.peer_finish_md_len == 0) {
764         /* SSLfatal() already called */
765         return 0;
766     }
767
768     return 1;
769 }
770
771 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
772                                                   PACKET *pkt)
773 {
774     size_t remain;
775
776     remain = PACKET_remaining(pkt);
777     /*
778      * 'Change Cipher Spec' is just a single byte, which should already have
779      * been consumed by ssl_get_message() so there should be no bytes left,
780      * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
781      */
782     if (SSL_CONNECTION_IS_DTLS(s)) {
783         if ((s->version == DTLS1_BAD_VER
784              && remain != DTLS1_CCS_HEADER_LENGTH + 1)
785             || (s->version != DTLS1_BAD_VER
786                 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
787             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
788             return MSG_PROCESS_ERROR;
789         }
790     } else {
791         if (remain != 0) {
792             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
793             return MSG_PROCESS_ERROR;
794         }
795     }
796
797     /* Check we have a cipher to change to */
798     if (s->s3.tmp.new_cipher == NULL) {
799         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
800         return MSG_PROCESS_ERROR;
801     }
802
803     s->s3.change_cipher_spec = 1;
804     if (!ssl3_do_change_cipher_spec(s)) {
805         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
806         return MSG_PROCESS_ERROR;
807     }
808
809     if (SSL_CONNECTION_IS_DTLS(s)) {
810         dtls1_increment_epoch(s, SSL3_CC_READ);
811
812         if (s->version == DTLS1_BAD_VER)
813             s->d1->handshake_read_seq++;
814
815 #ifndef OPENSSL_NO_SCTP
816         /*
817          * Remember that a CCS has been received, so that an old key of
818          * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
819          * SCTP is used
820          */
821         BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
822                  BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
823 #endif
824     }
825
826     return MSG_PROCESS_CONTINUE_READING;
827 }
828
829 MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
830 {
831     size_t md_len;
832     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
833     int was_first = SSL_IS_FIRST_HANDSHAKE(s);
834     int ok;
835
836
837     /* This is a real handshake so make sure we clean it up at the end */
838     if (s->server) {
839         /*
840         * To get this far we must have read encrypted data from the client. We
841         * no longer tolerate unencrypted alerts. This is ignored if less than
842         * TLSv1.3
843         */
844         if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
845             s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
846         if (s->post_handshake_auth != SSL_PHA_REQUESTED)
847             s->statem.cleanuphand = 1;
848         if (SSL_CONNECTION_IS_TLS13(s)
849             && !tls13_save_handshake_digest_for_pha(s)) {
850                 /* SSLfatal() already called */
851                 return MSG_PROCESS_ERROR;
852         }
853     }
854
855     /*
856      * In TLSv1.3 a Finished message signals a key change so the end of the
857      * message must be on a record boundary.
858      */
859     if (SSL_CONNECTION_IS_TLS13(s)
860         && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
861         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
862         return MSG_PROCESS_ERROR;
863     }
864
865     /* If this occurs, we have missed a message */
866     if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
867         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
868         return MSG_PROCESS_ERROR;
869     }
870     s->s3.change_cipher_spec = 0;
871
872     md_len = s->s3.tmp.peer_finish_md_len;
873
874     if (md_len != PACKET_remaining(pkt)) {
875         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
876         return MSG_PROCESS_ERROR;
877     }
878
879     ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
880                        md_len);
881 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
882     if (ok != 0) {
883         if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
884             ok = 0;
885         }
886     }
887 #endif
888     if (ok != 0) {
889         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
890         return MSG_PROCESS_ERROR;
891     }
892
893     /*
894      * Copy the finished so we can use it for renegotiation checks
895      */
896     if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
897         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
898         return MSG_PROCESS_ERROR;
899     }
900     if (s->server) {
901         memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
902                md_len);
903         s->s3.previous_client_finished_len = md_len;
904     } else {
905         memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
906                md_len);
907         s->s3.previous_server_finished_len = md_len;
908     }
909
910     /*
911      * In TLS1.3 we also have to change cipher state and do any final processing
912      * of the initial server flight (if we are a client)
913      */
914     if (SSL_CONNECTION_IS_TLS13(s)) {
915         if (s->server) {
916             if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
917                     !ssl->method->ssl3_enc->change_cipher_state(s,
918                         SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
919                 /* SSLfatal() already called */
920                 return MSG_PROCESS_ERROR;
921             }
922         } else {
923             /* TLS 1.3 gets the secret size from the handshake md */
924             size_t dummy;
925             if (!ssl->method->ssl3_enc->generate_master_secret(s,
926                     s->master_secret, s->handshake_secret, 0,
927                     &dummy)) {
928                 /* SSLfatal() already called */
929                 return MSG_PROCESS_ERROR;
930             }
931             if (!ssl->method->ssl3_enc->change_cipher_state(s,
932                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
933                 /* SSLfatal() already called */
934                 return MSG_PROCESS_ERROR;
935             }
936             if (!tls_process_initial_server_flight(s)) {
937                 /* SSLfatal() already called */
938                 return MSG_PROCESS_ERROR;
939             }
940         }
941     }
942
943     if (was_first
944             && !SSL_IS_FIRST_HANDSHAKE(s)
945             && s->rlayer.rrlmethod->set_first_handshake != NULL)
946         s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
947
948     return MSG_PROCESS_FINISHED_READING;
949 }
950
951 CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
952 {
953     if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
954         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
955         return CON_FUNC_ERROR;
956     }
957
958     return CON_FUNC_SUCCESS;
959 }
960
961 /* Add a certificate to the WPACKET */
962 static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
963                                    X509 *x, int chain, int for_comp)
964 {
965     int len;
966     unsigned char *outbytes;
967     int context = SSL_EXT_TLS1_3_CERTIFICATE;
968
969     if (for_comp)
970         context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
971
972     len = i2d_X509(x, NULL);
973     if (len < 0) {
974         if (!for_comp)
975             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
976         return 0;
977     }
978     if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
979             || i2d_X509(x, &outbytes) != len) {
980         if (!for_comp)
981             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
982         return 0;
983     }
984
985     if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
986             && !tls_construct_extensions(s, pkt, context, x, chain)) {
987         /* SSLfatal() already called */
988         return 0;
989     }
990
991     return 1;
992 }
993
994 /* Add certificate chain to provided WPACKET */
995 static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
996 {
997     int i, chain_count;
998     X509 *x;
999     STACK_OF(X509) *extra_certs;
1000     STACK_OF(X509) *chain = NULL;
1001     X509_STORE *chain_store;
1002     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1003
1004     if (cpk == NULL || cpk->x509 == NULL)
1005         return 1;
1006
1007     x = cpk->x509;
1008
1009     /*
1010      * If we have a certificate specific chain use it, else use parent ctx.
1011      */
1012     if (cpk->chain != NULL)
1013         extra_certs = cpk->chain;
1014     else
1015         extra_certs = sctx->extra_certs;
1016
1017     if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1018         chain_store = NULL;
1019     else if (s->cert->chain_store)
1020         chain_store = s->cert->chain_store;
1021     else
1022         chain_store = sctx->cert_store;
1023
1024     if (chain_store != NULL) {
1025         X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
1026                                                        sctx->propq);
1027
1028         if (xs_ctx == NULL) {
1029             if (!for_comp)
1030                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1031             return 0;
1032         }
1033         if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1034             X509_STORE_CTX_free(xs_ctx);
1035             if (!for_comp)
1036                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1037             return 0;
1038         }
1039         /*
1040          * It is valid for the chain not to be complete (because normally we
1041          * don't include the root cert in the chain). Therefore we deliberately
1042          * ignore the error return from this call. We're not actually verifying
1043          * the cert - we're just building as much of the chain as we can
1044          */
1045         (void)X509_verify_cert(xs_ctx);
1046         /* Don't leave errors in the queue */
1047         ERR_clear_error();
1048         chain = X509_STORE_CTX_get0_chain(xs_ctx);
1049         i = ssl_security_cert_chain(s, chain, NULL, 0);
1050         if (i != 1) {
1051 #if 0
1052             /* Dummy error calls so mkerr generates them */
1053             ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1054             ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1055             ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1056 #endif
1057             X509_STORE_CTX_free(xs_ctx);
1058             if (!for_comp)
1059                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1060             return 0;
1061         }
1062         chain_count = sk_X509_num(chain);
1063         for (i = 0; i < chain_count; i++) {
1064             x = sk_X509_value(chain, i);
1065
1066             if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1067                 /* SSLfatal() already called */
1068                 X509_STORE_CTX_free(xs_ctx);
1069                 return 0;
1070             }
1071         }
1072         X509_STORE_CTX_free(xs_ctx);
1073     } else {
1074         i = ssl_security_cert_chain(s, extra_certs, x, 0);
1075         if (i != 1) {
1076             if (!for_comp)
1077                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1078             return 0;
1079         }
1080         if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1081             /* SSLfatal() already called */
1082             return 0;
1083         }
1084         for (i = 0; i < sk_X509_num(extra_certs); i++) {
1085             x = sk_X509_value(extra_certs, i);
1086             if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1087                 /* SSLfatal() already called */
1088                 return 0;
1089             }
1090         }
1091     }
1092     return 1;
1093 }
1094
1095 unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1096                                      CERT_PKEY *cpk, int for_comp)
1097 {
1098     if (!WPACKET_start_sub_packet_u24(pkt)) {
1099         if (!for_comp)
1100             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1101         return 0;
1102     }
1103
1104     if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1105         return 0;
1106
1107     if (!WPACKET_close(pkt)) {
1108         if (!for_comp)
1109             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1110         return 0;
1111     }
1112
1113     return 1;
1114 }
1115
1116 /*
1117  * Tidy up after the end of a handshake. In the case of SCTP this may result
1118  * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1119  * freed up as well.
1120  */
1121 WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1122                                 int clearbufs, int stop)
1123 {
1124     void (*cb) (const SSL *ssl, int type, int val) = NULL;
1125     int cleanuphand = s->statem.cleanuphand;
1126     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1127     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1128
1129     if (clearbufs) {
1130         if (!SSL_CONNECTION_IS_DTLS(s)
1131 #ifndef OPENSSL_NO_SCTP
1132             /*
1133              * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1134              * messages that require it. Therefore, DTLS procedures for retransmissions
1135              * MUST NOT be used.
1136              * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1137              */
1138             || BIO_dgram_is_sctp(SSL_get_wbio(ssl))
1139 #endif
1140             ) {
1141             /*
1142              * We don't do this in DTLS over UDP because we may still need the init_buf
1143              * in case there are any unexpected retransmits
1144              */
1145             BUF_MEM_free(s->init_buf);
1146             s->init_buf = NULL;
1147         }
1148
1149         if (!ssl_free_wbio_buffer(s)) {
1150             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1151             return WORK_ERROR;
1152         }
1153         s->init_num = 0;
1154     }
1155
1156     if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1157             && s->post_handshake_auth == SSL_PHA_REQUESTED)
1158         s->post_handshake_auth = SSL_PHA_EXT_SENT;
1159
1160     /*
1161      * Only set if there was a Finished message and this isn't after a TLSv1.3
1162      * post handshake exchange
1163      */
1164     if (cleanuphand) {
1165         /* skipped if we just sent a HelloRequest */
1166         s->renegotiate = 0;
1167         s->new_session = 0;
1168         s->statem.cleanuphand = 0;
1169         s->ext.ticket_expected = 0;
1170
1171         ssl3_cleanup_key_block(s);
1172
1173         if (s->server) {
1174             /*
1175              * In TLSv1.3 we update the cache as part of constructing the
1176              * NewSessionTicket
1177              */
1178             if (!SSL_CONNECTION_IS_TLS13(s))
1179                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1180
1181             /* N.B. s->ctx may not equal s->session_ctx */
1182             ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1183             s->handshake_func = ossl_statem_accept;
1184         } else {
1185             if (SSL_CONNECTION_IS_TLS13(s)) {
1186                 /*
1187                  * We encourage applications to only use TLSv1.3 tickets once,
1188                  * so we remove this one from the cache.
1189                  */
1190                 if ((s->session_ctx->session_cache_mode
1191                      & SSL_SESS_CACHE_CLIENT) != 0)
1192                     SSL_CTX_remove_session(s->session_ctx, s->session);
1193             } else {
1194                 /*
1195                  * In TLSv1.3 we update the cache as part of processing the
1196                  * NewSessionTicket
1197                  */
1198                 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1199             }
1200             if (s->hit)
1201                 ssl_tsan_counter(s->session_ctx,
1202                                  &s->session_ctx->stats.sess_hit);
1203
1204             s->handshake_func = ossl_statem_connect;
1205             ssl_tsan_counter(s->session_ctx,
1206                              &s->session_ctx->stats.sess_connect_good);
1207         }
1208
1209         if (SSL_CONNECTION_IS_DTLS(s)) {
1210             /* done with handshaking */
1211             s->d1->handshake_read_seq = 0;
1212             s->d1->handshake_write_seq = 0;
1213             s->d1->next_handshake_write_seq = 0;
1214             dtls1_clear_received_buffer(s);
1215         }
1216     }
1217
1218     if (s->info_callback != NULL)
1219         cb = s->info_callback;
1220     else if (sctx->info_callback != NULL)
1221         cb = sctx->info_callback;
1222
1223     /* The callback may expect us to not be in init at handshake done */
1224     ossl_statem_set_in_init(s, 0);
1225
1226     if (cb != NULL) {
1227         if (cleanuphand
1228                 || !SSL_CONNECTION_IS_TLS13(s)
1229                 || SSL_IS_FIRST_HANDSHAKE(s))
1230             cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1231     }
1232
1233     if (!stop) {
1234         /* If we've got more work to do we go back into init */
1235         ossl_statem_set_in_init(s, 1);
1236         return WORK_FINISHED_CONTINUE;
1237     }
1238
1239     return WORK_FINISHED_STOP;
1240 }
1241
1242 int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1243 {
1244     /* s->init_num < SSL3_HM_HEADER_LENGTH */
1245     int skip_message, i, recvd_type;
1246     unsigned char *p;
1247     size_t l, readbytes;
1248     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1249
1250     p = (unsigned char *)s->init_buf->data;
1251
1252     do {
1253         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1254             i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1255                                             &p[s->init_num],
1256                                             SSL3_HM_HEADER_LENGTH - s->init_num,
1257                                             0, &readbytes);
1258             if (i <= 0) {
1259                 s->rwstate = SSL_READING;
1260                 return 0;
1261             }
1262             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1263                 /*
1264                  * A ChangeCipherSpec must be a single byte and may not occur
1265                  * in the middle of a handshake message.
1266                  */
1267                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1268                     SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1269                              SSL_R_BAD_CHANGE_CIPHER_SPEC);
1270                     return 0;
1271                 }
1272                 if (s->statem.hand_state == TLS_ST_BEFORE
1273                         && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1274                     /*
1275                      * We are stateless and we received a CCS. Probably this is
1276                      * from a client between the first and second ClientHellos.
1277                      * We should ignore this, but return an error because we do
1278                      * not return success until we see the second ClientHello
1279                      * with a valid cookie.
1280                      */
1281                     return 0;
1282                 }
1283                 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1284                 s->init_num = readbytes - 1;
1285                 s->init_msg = s->init_buf->data;
1286                 s->s3.tmp.message_size = readbytes;
1287                 return 1;
1288             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1289                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1290                          SSL_R_CCS_RECEIVED_EARLY);
1291                 return 0;
1292             }
1293             s->init_num += readbytes;
1294         }
1295
1296         skip_message = 0;
1297         if (!s->server)
1298             if (s->statem.hand_state != TLS_ST_OK
1299                     && p[0] == SSL3_MT_HELLO_REQUEST)
1300                 /*
1301                  * The server may always send 'Hello Request' messages --
1302                  * we are doing a handshake anyway now, so ignore them if
1303                  * their format is correct. Does not count for 'Finished'
1304                  * MAC.
1305                  */
1306                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1307                     s->init_num = 0;
1308                     skip_message = 1;
1309
1310                     if (s->msg_callback)
1311                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1312                                         p, SSL3_HM_HEADER_LENGTH, ssl,
1313                                         s->msg_callback_arg);
1314                 }
1315     } while (skip_message);
1316     /* s->init_num == SSL3_HM_HEADER_LENGTH */
1317
1318     *mt = *p;
1319     s->s3.tmp.message_type = *(p++);
1320
1321     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1322         /*
1323          * Only happens with SSLv3+ in an SSLv2 backward compatible
1324          * ClientHello
1325          *
1326          * Total message size is the remaining record bytes to read
1327          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1328          */
1329         l = s->rlayer.tlsrecs[0].length + SSL3_HM_HEADER_LENGTH;
1330         s->s3.tmp.message_size = l;
1331
1332         s->init_msg = s->init_buf->data;
1333         s->init_num = SSL3_HM_HEADER_LENGTH;
1334     } else {
1335         n2l3(p, l);
1336         /* BUF_MEM_grow takes an 'int' parameter */
1337         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1338             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1339                      SSL_R_EXCESSIVE_MESSAGE_SIZE);
1340             return 0;
1341         }
1342         s->s3.tmp.message_size = l;
1343
1344         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1345         s->init_num = 0;
1346     }
1347
1348     return 1;
1349 }
1350
1351 int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1352 {
1353     size_t n, readbytes;
1354     unsigned char *p;
1355     int i;
1356     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1357
1358     if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1359         /* We've already read everything in */
1360         *len = (unsigned long)s->init_num;
1361         return 1;
1362     }
1363
1364     p = s->init_msg;
1365     n = s->s3.tmp.message_size - s->init_num;
1366     while (n > 0) {
1367         i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1368                                         &p[s->init_num], n, 0, &readbytes);
1369         if (i <= 0) {
1370             s->rwstate = SSL_READING;
1371             *len = 0;
1372             return 0;
1373         }
1374         s->init_num += readbytes;
1375         n -= readbytes;
1376     }
1377
1378     /*
1379      * If receiving Finished, record MAC of prior handshake messages for
1380      * Finished verification.
1381      */
1382     if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1383         /* SSLfatal() already called */
1384         *len = 0;
1385         return 0;
1386     }
1387
1388     /* Feed this message into MAC computation. */
1389     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1390         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1391                              s->init_num)) {
1392             /* SSLfatal() already called */
1393             *len = 0;
1394             return 0;
1395         }
1396         if (s->msg_callback)
1397             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1398                             (size_t)s->init_num, ssl, s->msg_callback_arg);
1399     } else {
1400         /*
1401          * We defer feeding in the HRR until later. We'll do it as part of
1402          * processing the message
1403          * The TLsv1.3 handshake transcript stops at the ClientFinished
1404          * message.
1405          */
1406 #define SERVER_HELLO_RANDOM_OFFSET  (SSL3_HM_HEADER_LENGTH + 2)
1407         /* KeyUpdate and NewSessionTicket do not need to be added */
1408         if (!SSL_CONNECTION_IS_TLS13(s)
1409             || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1410                          && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1411             if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1412                     || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1413                     || memcmp(hrrrandom,
1414                               s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1415                               SSL3_RANDOM_SIZE) != 0) {
1416                 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1417                                      s->init_num + SSL3_HM_HEADER_LENGTH)) {
1418                     /* SSLfatal() already called */
1419                     *len = 0;
1420                     return 0;
1421                 }
1422             }
1423         }
1424         if (s->msg_callback)
1425             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1426                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ssl,
1427                             s->msg_callback_arg);
1428     }
1429
1430     *len = s->init_num;
1431     return 1;
1432 }
1433
1434 static const X509ERR2ALERT x509table[] = {
1435     {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1436     {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1437     {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1438     {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1439     {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1440     {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1441     {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1442     {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1443     {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1444     {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1445     {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1446     {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1447     {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1448     {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1449     {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1450     {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1451     {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1452     {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1453     {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1454     {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1455     {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1456     {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1457     {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1458     {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1459     {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1460     {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1461     {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1462     {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1463     {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1464     {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1465     {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1466     {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1467     {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1468     {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1469     {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1470     {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1471     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1472     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1473     {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1474     {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1475
1476     /* Last entry; return this if we don't find the value above. */
1477     {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1478 };
1479
1480 int ssl_x509err2alert(int x509err)
1481 {
1482     const X509ERR2ALERT *tp;
1483
1484     for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1485         if (tp->x509err == x509err)
1486             break;
1487     return tp->alert;
1488 }
1489
1490 int ssl_allow_compression(SSL_CONNECTION *s)
1491 {
1492     if (s->options & SSL_OP_NO_COMPRESSION)
1493         return 0;
1494     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1495 }
1496
1497 static int version_cmp(const SSL_CONNECTION *s, int a, int b)
1498 {
1499     int dtls = SSL_CONNECTION_IS_DTLS(s);
1500
1501     if (a == b)
1502         return 0;
1503     if (!dtls)
1504         return a < b ? -1 : 1;
1505     return DTLS_VERSION_LT(a, b) ? -1 : 1;
1506 }
1507
1508 typedef struct {
1509     int version;
1510     const SSL_METHOD *(*cmeth) (void);
1511     const SSL_METHOD *(*smeth) (void);
1512 } version_info;
1513
1514 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1515 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1516 #endif
1517
1518 /* Must be in order high to low */
1519 static const version_info tls_version_table[] = {
1520 #ifndef OPENSSL_NO_TLS1_3
1521     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1522 #else
1523     {TLS1_3_VERSION, NULL, NULL},
1524 #endif
1525 #ifndef OPENSSL_NO_TLS1_2
1526     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1527 #else
1528     {TLS1_2_VERSION, NULL, NULL},
1529 #endif
1530 #ifndef OPENSSL_NO_TLS1_1
1531     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1532 #else
1533     {TLS1_1_VERSION, NULL, NULL},
1534 #endif
1535 #ifndef OPENSSL_NO_TLS1
1536     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1537 #else
1538     {TLS1_VERSION, NULL, NULL},
1539 #endif
1540 #ifndef OPENSSL_NO_SSL3
1541     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1542 #else
1543     {SSL3_VERSION, NULL, NULL},
1544 #endif
1545     {0, NULL, NULL},
1546 };
1547
1548 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1549 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1550 #endif
1551
1552 /* Must be in order high to low */
1553 static const version_info dtls_version_table[] = {
1554 #ifndef OPENSSL_NO_DTLS1_2
1555     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1556 #else
1557     {DTLS1_2_VERSION, NULL, NULL},
1558 #endif
1559 #ifndef OPENSSL_NO_DTLS1
1560     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1561     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1562 #else
1563     {DTLS1_VERSION, NULL, NULL},
1564     {DTLS1_BAD_VER, NULL, NULL},
1565 #endif
1566     {0, NULL, NULL},
1567 };
1568
1569 /*
1570  * ssl_method_error - Check whether an SSL_METHOD is enabled.
1571  *
1572  * @s: The SSL handle for the candidate method
1573  * @method: the intended method.
1574  *
1575  * Returns 0 on success, or an SSL error reason on failure.
1576  */
1577 static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1578 {
1579     int version = method->version;
1580
1581     if ((s->min_proto_version != 0 &&
1582          version_cmp(s, version, s->min_proto_version) < 0) ||
1583         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1584         return SSL_R_VERSION_TOO_LOW;
1585
1586     if (s->max_proto_version != 0 &&
1587         version_cmp(s, version, s->max_proto_version) > 0)
1588         return SSL_R_VERSION_TOO_HIGH;
1589
1590     if ((s->options & method->mask) != 0)
1591         return SSL_R_UNSUPPORTED_PROTOCOL;
1592     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1593         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1594
1595     return 0;
1596 }
1597
1598 /*
1599  * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1600  * certificate type, or has PSK or a certificate callback configured, or has
1601  * a servername callback configure. Otherwise returns 0.
1602  */
1603 static int is_tls13_capable(const SSL_CONNECTION *s)
1604 {
1605     size_t i;
1606     int curve;
1607     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1608
1609     if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1610         return 0;
1611
1612     /*
1613      * A servername callback can change the available certs, so if a servername
1614      * cb is set then we just assume TLSv1.3 will be ok
1615      */
1616     if (sctx->ext.servername_cb != NULL
1617             || s->session_ctx->ext.servername_cb != NULL)
1618         return 1;
1619
1620 #ifndef OPENSSL_NO_PSK
1621     if (s->psk_server_callback != NULL)
1622         return 1;
1623 #endif
1624
1625     if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1626         return 1;
1627
1628     /* All provider-based sig algs are required to support at least TLS1.3 */
1629     for (i = 0; i < s->ssl_pkey_num; i++) {
1630         /* Skip over certs disallowed for TLSv1.3 */
1631         switch (i) {
1632         case SSL_PKEY_DSA_SIGN:
1633         case SSL_PKEY_GOST01:
1634         case SSL_PKEY_GOST12_256:
1635         case SSL_PKEY_GOST12_512:
1636             continue;
1637         default:
1638             break;
1639         }
1640         if (!ssl_has_cert(s, i))
1641             continue;
1642         if (i != SSL_PKEY_ECC)
1643             return 1;
1644         /*
1645          * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1646          * more restrictive so check that our sig algs are consistent with this
1647          * EC cert. See section 4.2.3 of RFC8446.
1648          */
1649         curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1650         if (tls_check_sigalg_curve(s, curve))
1651             return 1;
1652     }
1653
1654     return 0;
1655 }
1656
1657 /*
1658  * ssl_version_supported - Check that the specified `version` is supported by
1659  * `SSL *` instance
1660  *
1661  * @s: The SSL handle for the candidate method
1662  * @version: Protocol version to test against
1663  *
1664  * Returns 1 when supported, otherwise 0
1665  */
1666 int ssl_version_supported(const SSL_CONNECTION *s, int version,
1667                           const SSL_METHOD **meth)
1668 {
1669     const version_info *vent;
1670     const version_info *table;
1671
1672     switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1673     default:
1674         /* Version should match method version for non-ANY method */
1675         return version_cmp(s, version, s->version) == 0;
1676     case TLS_ANY_VERSION:
1677         table = tls_version_table;
1678         break;
1679     case DTLS_ANY_VERSION:
1680         table = dtls_version_table;
1681         break;
1682     }
1683
1684     for (vent = table;
1685          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1686          ++vent) {
1687         if (vent->cmeth != NULL
1688                 && version_cmp(s, version, vent->version) == 0
1689                 && ssl_method_error(s, vent->cmeth()) == 0
1690                 && (!s->server
1691                     || version != TLS1_3_VERSION
1692                     || is_tls13_capable(s))) {
1693             if (meth != NULL)
1694                 *meth = vent->cmeth();
1695             return 1;
1696         }
1697     }
1698     return 0;
1699 }
1700
1701 /*
1702  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1703  * fallback indication from a client check whether we're using the highest
1704  * supported protocol version.
1705  *
1706  * @s server SSL handle.
1707  *
1708  * Returns 1 when using the highest enabled version, 0 otherwise.
1709  */
1710 int ssl_check_version_downgrade(SSL_CONNECTION *s)
1711 {
1712     const version_info *vent;
1713     const version_info *table;
1714     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1715
1716     /*
1717      * Check that the current protocol is the highest enabled version
1718      * (according to ssl->defltmethod, as version negotiation may have changed
1719      * s->method).
1720      */
1721     if (s->version == ssl->defltmeth->version)
1722         return 1;
1723
1724     /*
1725      * Apparently we're using a version-flexible SSL_METHOD (not at its
1726      * highest protocol version).
1727      */
1728     if (ssl->defltmeth->version == TLS_method()->version)
1729         table = tls_version_table;
1730     else if (ssl->defltmeth->version == DTLS_method()->version)
1731         table = dtls_version_table;
1732     else {
1733         /* Unexpected state; fail closed. */
1734         return 0;
1735     }
1736
1737     for (vent = table; vent->version != 0; ++vent) {
1738         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1739             return s->version == vent->version;
1740     }
1741     return 0;
1742 }
1743
1744 /*
1745  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1746  * protocols, provided the initial (D)TLS method is version-flexible.  This
1747  * function sanity-checks the proposed value and makes sure the method is
1748  * version-flexible, then sets the limit if all is well.
1749  *
1750  * @method_version: The version of the current SSL_METHOD.
1751  * @version: the intended limit.
1752  * @bound: pointer to limit to be updated.
1753  *
1754  * Returns 1 on success, 0 on failure.
1755  */
1756 int ssl_set_version_bound(int method_version, int version, int *bound)
1757 {
1758     int valid_tls;
1759     int valid_dtls;
1760
1761     if (version == 0) {
1762         *bound = version;
1763         return 1;
1764     }
1765
1766     valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1767     valid_dtls =
1768         DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1769         DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1770
1771     if (!valid_tls && !valid_dtls)
1772         return 0;
1773
1774     /*-
1775      * Restrict TLS methods to TLS protocol versions.
1776      * Restrict DTLS methods to DTLS protocol versions.
1777      * Note, DTLS version numbers are decreasing, use comparison macros.
1778      *
1779      * Note that for both lower-bounds we use explicit versions, not
1780      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
1781      * configurations.  If the MIN (supported) version ever rises, the user's
1782      * "floor" remains valid even if no longer available.  We don't expect the
1783      * MAX ceiling to ever get lower, so making that variable makes sense.
1784      *
1785      * We ignore attempts to set bounds on version-inflexible methods,
1786      * returning success.
1787      */
1788     switch (method_version) {
1789     default:
1790         break;
1791
1792     case TLS_ANY_VERSION:
1793         if (valid_tls)
1794             *bound = version;
1795         break;
1796
1797     case DTLS_ANY_VERSION:
1798         if (valid_dtls)
1799             *bound = version;
1800         break;
1801     }
1802     return 1;
1803 }
1804
1805 static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
1806 {
1807     if (vers == TLS1_2_VERSION
1808             && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1809         *dgrd = DOWNGRADE_TO_1_2;
1810     } else if (!SSL_CONNECTION_IS_DTLS(s)
1811             && vers < TLS1_2_VERSION
1812                /*
1813                 * We need to ensure that a server that disables TLSv1.2
1814                 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1815                 * complete handshakes with clients that support TLSv1.2 and
1816                 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1817                 * enabled and TLSv1.2 is not.
1818                 */
1819             && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1820         *dgrd = DOWNGRADE_TO_1_1;
1821     } else {
1822         *dgrd = DOWNGRADE_NONE;
1823     }
1824 }
1825
1826 /*
1827  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
1828  * client HELLO is received to select the final server protocol version and
1829  * the version specific method.
1830  *
1831  * @s: server SSL handle.
1832  *
1833  * Returns 0 on success or an SSL error reason number on failure.
1834  */
1835 int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
1836                               DOWNGRADE *dgrd)
1837 {
1838     /*-
1839      * With version-flexible methods we have an initial state with:
1840      *
1841      *   s->method->version == (D)TLS_ANY_VERSION,
1842      *   s->version == (D)TLS_MAX_VERSION_INTERNAL.
1843      *
1844      * So we detect version-flexible methods via the method version, not the
1845      * handle version.
1846      */
1847     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1848     int server_version = ssl->method->version;
1849     int client_version = hello->legacy_version;
1850     const version_info *vent;
1851     const version_info *table;
1852     int disabled = 0;
1853     RAW_EXTENSION *suppversions;
1854
1855     s->client_version = client_version;
1856
1857     switch (server_version) {
1858     default:
1859         if (!SSL_CONNECTION_IS_TLS13(s)) {
1860             if (version_cmp(s, client_version, s->version) < 0)
1861                 return SSL_R_WRONG_SSL_VERSION;
1862             *dgrd = DOWNGRADE_NONE;
1863             /*
1864              * If this SSL handle is not from a version flexible method we don't
1865              * (and never did) check min/max FIPS or Suite B constraints.  Hope
1866              * that's OK.  It is up to the caller to not choose fixed protocol
1867              * versions they don't want.  If not, then easy to fix, just return
1868              * ssl_method_error(s, s->method)
1869              */
1870             return 0;
1871         }
1872         /*
1873          * Fall through if we are TLSv1.3 already (this means we must be after
1874          * a HelloRetryRequest
1875          */
1876         /* fall thru */
1877     case TLS_ANY_VERSION:
1878         table = tls_version_table;
1879         break;
1880     case DTLS_ANY_VERSION:
1881         table = dtls_version_table;
1882         break;
1883     }
1884
1885     suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1886
1887     /* If we did an HRR then supported versions is mandatory */
1888     if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1889         return SSL_R_UNSUPPORTED_PROTOCOL;
1890
1891     if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
1892         unsigned int candidate_vers = 0;
1893         unsigned int best_vers = 0;
1894         const SSL_METHOD *best_method = NULL;
1895         PACKET versionslist;
1896
1897         suppversions->parsed = 1;
1898
1899         if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1900             /* Trailing or invalid data? */
1901             return SSL_R_LENGTH_MISMATCH;
1902         }
1903
1904         /*
1905          * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1906          * The spec only requires servers to check that it isn't SSLv3:
1907          * "Any endpoint receiving a Hello message with
1908          * ClientHello.legacy_version or ServerHello.legacy_version set to
1909          * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1910          * We are slightly stricter and require that it isn't SSLv3 or lower.
1911          * We tolerate TLSv1 and TLSv1.1.
1912          */
1913         if (client_version <= SSL3_VERSION)
1914             return SSL_R_BAD_LEGACY_VERSION;
1915
1916         while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1917             if (version_cmp(s, candidate_vers, best_vers) <= 0)
1918                 continue;
1919             if (ssl_version_supported(s, candidate_vers, &best_method))
1920                 best_vers = candidate_vers;
1921         }
1922         if (PACKET_remaining(&versionslist) != 0) {
1923             /* Trailing data? */
1924             return SSL_R_LENGTH_MISMATCH;
1925         }
1926
1927         if (best_vers > 0) {
1928             if (s->hello_retry_request != SSL_HRR_NONE) {
1929                 /*
1930                  * This is after a HelloRetryRequest so we better check that we
1931                  * negotiated TLSv1.3
1932                  */
1933                 if (best_vers != TLS1_3_VERSION)
1934                     return SSL_R_UNSUPPORTED_PROTOCOL;
1935                 return 0;
1936             }
1937             check_for_downgrade(s, best_vers, dgrd);
1938             s->version = best_vers;
1939             ssl->method = best_method;
1940             if (!ssl_set_record_protocol_version(s, best_vers))
1941                 return ERR_R_INTERNAL_ERROR;
1942
1943             return 0;
1944         }
1945         return SSL_R_UNSUPPORTED_PROTOCOL;
1946     }
1947
1948     /*
1949      * If the supported versions extension isn't present, then the highest
1950      * version we can negotiate is TLSv1.2
1951      */
1952     if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1953         client_version = TLS1_2_VERSION;
1954
1955     /*
1956      * No supported versions extension, so we just use the version supplied in
1957      * the ClientHello.
1958      */
1959     for (vent = table; vent->version != 0; ++vent) {
1960         const SSL_METHOD *method;
1961
1962         if (vent->smeth == NULL ||
1963             version_cmp(s, client_version, vent->version) < 0)
1964             continue;
1965         method = vent->smeth();
1966         if (ssl_method_error(s, method) == 0) {
1967             check_for_downgrade(s, vent->version, dgrd);
1968             s->version = vent->version;
1969             ssl->method = method;
1970             if (!ssl_set_record_protocol_version(s, s->version))
1971                 return ERR_R_INTERNAL_ERROR;
1972
1973             return 0;
1974         }
1975         disabled = 1;
1976     }
1977     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1978 }
1979
1980 /*
1981  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
1982  * server HELLO is received to select the final client protocol version and
1983  * the version specific method.
1984  *
1985  * @s: client SSL handle.
1986  * @version: The proposed version from the server's HELLO.
1987  * @extensions: The extensions received
1988  *
1989  * Returns 1 on success or 0 on error.
1990  */
1991 int ssl_choose_client_version(SSL_CONNECTION *s, int version,
1992                               RAW_EXTENSION *extensions)
1993 {
1994     const version_info *vent;
1995     const version_info *table;
1996     int ret, ver_min, ver_max, real_max, origv;
1997     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1998
1999     origv = s->version;
2000     s->version = version;
2001
2002     /* This will overwrite s->version if the extension is present */
2003     if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
2004                              SSL_EXT_TLS1_2_SERVER_HELLO
2005                              | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
2006                              NULL, 0)) {
2007         s->version = origv;
2008         return 0;
2009     }
2010
2011     if (s->hello_retry_request != SSL_HRR_NONE
2012             && s->version != TLS1_3_VERSION) {
2013         s->version = origv;
2014         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2015         return 0;
2016     }
2017
2018     switch (ssl->method->version) {
2019     default:
2020         if (s->version != ssl->method->version) {
2021             s->version = origv;
2022             SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2023             return 0;
2024         }
2025         /*
2026          * If this SSL handle is not from a version flexible method we don't
2027          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
2028          * that's OK.  It is up to the caller to not choose fixed protocol
2029          * versions they don't want.  If not, then easy to fix, just return
2030          * ssl_method_error(s, s->method)
2031          */
2032         if (!ssl_set_record_protocol_version(s, s->version)) {
2033             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2034             return 0;
2035         }
2036         return 1;
2037     case TLS_ANY_VERSION:
2038         table = tls_version_table;
2039         break;
2040     case DTLS_ANY_VERSION:
2041         table = dtls_version_table;
2042         break;
2043     }
2044
2045     ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2046     if (ret != 0) {
2047         s->version = origv;
2048         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2049         return 0;
2050     }
2051     if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
2052                                   : s->version < ver_min) {
2053         s->version = origv;
2054         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2055         return 0;
2056     } else if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
2057                                          : s->version > ver_max) {
2058         s->version = origv;
2059         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2060         return 0;
2061     }
2062
2063     if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2064         real_max = ver_max;
2065
2066     /* Check for downgrades */
2067     if (s->version == TLS1_2_VERSION && real_max > s->version) {
2068         if (memcmp(tls12downgrade,
2069                    s->s3.server_random + SSL3_RANDOM_SIZE
2070                                         - sizeof(tls12downgrade),
2071                    sizeof(tls12downgrade)) == 0) {
2072             s->version = origv;
2073             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2074                      SSL_R_INAPPROPRIATE_FALLBACK);
2075             return 0;
2076         }
2077     } else if (!SSL_CONNECTION_IS_DTLS(s)
2078                && s->version < TLS1_2_VERSION
2079                && real_max > s->version) {
2080         if (memcmp(tls11downgrade,
2081                    s->s3.server_random + SSL3_RANDOM_SIZE
2082                                         - sizeof(tls11downgrade),
2083                    sizeof(tls11downgrade)) == 0) {
2084             s->version = origv;
2085             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2086                      SSL_R_INAPPROPRIATE_FALLBACK);
2087             return 0;
2088         }
2089     }
2090
2091     for (vent = table; vent->version != 0; ++vent) {
2092         if (vent->cmeth == NULL || s->version != vent->version)
2093             continue;
2094
2095         ssl->method = vent->cmeth();
2096         if (!ssl_set_record_protocol_version(s, s->version)) {
2097             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2098             return 0;
2099         }
2100         return 1;
2101     }
2102
2103     s->version = origv;
2104     SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2105     return 0;
2106 }
2107
2108 /*
2109  * ssl_get_min_max_version - get minimum and maximum protocol version
2110  * @s: The SSL connection
2111  * @min_version: The minimum supported version
2112  * @max_version: The maximum supported version
2113  * @real_max:    The highest version below the lowest compile time version hole
2114  *               where that hole lies above at least one run-time enabled
2115  *               protocol.
2116  *
2117  * Work out what version we should be using for the initial ClientHello if the
2118  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
2119  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2120  * constraints and any floor imposed by the security level here,
2121  * so we don't advertise the wrong protocol version to only reject the outcome later.
2122  *
2123  * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
2124  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
2125  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2126  *
2127  * Returns 0 on success or an SSL error reason number on failure.  On failure
2128  * min_version and max_version will also be set to 0.
2129  */
2130 int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2131                             int *max_version, int *real_max)
2132 {
2133     int version, tmp_real_max;
2134     int hole;
2135     const SSL_METHOD *single = NULL;
2136     const SSL_METHOD *method;
2137     const version_info *table;
2138     const version_info *vent;
2139     const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2140
2141     switch (ssl->method->version) {
2142     default:
2143         /*
2144          * If this SSL handle is not from a version flexible method we don't
2145          * (and never did) check min/max FIPS or Suite B constraints.  Hope
2146          * that's OK.  It is up to the caller to not choose fixed protocol
2147          * versions they don't want.  If not, then easy to fix, just return
2148          * ssl_method_error(s, s->method)
2149          */
2150         *min_version = *max_version = s->version;
2151         /*
2152          * Providing a real_max only makes sense where we're using a version
2153          * flexible method.
2154          */
2155         if (!ossl_assert(real_max == NULL))
2156             return ERR_R_INTERNAL_ERROR;
2157         return 0;
2158     case TLS_ANY_VERSION:
2159         table = tls_version_table;
2160         break;
2161     case DTLS_ANY_VERSION:
2162         table = dtls_version_table;
2163         break;
2164     }
2165
2166     /*
2167      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2168      * below X enabled. This is required in order to maintain the "version
2169      * capability" vector contiguous. Any versions with a NULL client method
2170      * (protocol version client is disabled at compile-time) is also a "hole".
2171      *
2172      * Our initial state is hole == 1, version == 0.  That is, versions above
2173      * the first version in the method table are disabled (a "hole" above
2174      * the valid protocol entries) and we don't have a selected version yet.
2175      *
2176      * Whenever "hole == 1", and we hit an enabled method, its version becomes
2177      * the selected version, and the method becomes a candidate "single"
2178      * method.  We're no longer in a hole, so "hole" becomes 0.
2179      *
2180      * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2181      * as we support a contiguous range of at least two methods.  If we hit
2182      * a disabled method, then hole becomes true again, but nothing else
2183      * changes yet, because all the remaining methods may be disabled too.
2184      * If we again hit an enabled method after the new hole, it becomes
2185      * selected, as we start from scratch.
2186      */
2187     *min_version = version = 0;
2188     hole = 1;
2189     if (real_max != NULL)
2190         *real_max = 0;
2191     tmp_real_max = 0;
2192     for (vent = table; vent->version != 0; ++vent) {
2193         /*
2194          * A table entry with a NULL client method is still a hole in the
2195          * "version capability" vector.
2196          */
2197         if (vent->cmeth == NULL) {
2198             hole = 1;
2199             tmp_real_max = 0;
2200             continue;
2201         }
2202         method = vent->cmeth();
2203
2204         if (hole == 1 && tmp_real_max == 0)
2205             tmp_real_max = vent->version;
2206
2207         if (ssl_method_error(s, method) != 0) {
2208             hole = 1;
2209         } else if (!hole) {
2210             single = NULL;
2211             *min_version = method->version;
2212         } else {
2213             if (real_max != NULL && tmp_real_max != 0)
2214                 *real_max = tmp_real_max;
2215             version = (single = method)->version;
2216             *min_version = version;
2217             hole = 0;
2218         }
2219     }
2220
2221     *max_version = version;
2222
2223     /* Fail if everything is disabled */
2224     if (version == 0)
2225         return SSL_R_NO_PROTOCOLS_AVAILABLE;
2226
2227     return 0;
2228 }
2229
2230 /*
2231  * ssl_set_client_hello_version - Work out what version we should be using for
2232  * the initial ClientHello.legacy_version field.
2233  *
2234  * @s: client SSL handle.
2235  *
2236  * Returns 0 on success or an SSL error reason number on failure.
2237  */
2238 int ssl_set_client_hello_version(SSL_CONNECTION *s)
2239 {
2240     int ver_min, ver_max, ret;
2241
2242     /*
2243      * In a renegotiation we always send the same client_version that we sent
2244      * last time, regardless of which version we eventually negotiated.
2245      */
2246     if (!SSL_IS_FIRST_HANDSHAKE(s))
2247         return 0;
2248
2249     ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2250
2251     if (ret != 0)
2252         return ret;
2253
2254     s->version = ver_max;
2255
2256     if (SSL_CONNECTION_IS_DTLS(s)) {
2257         if (ver_max == DTLS1_BAD_VER) {
2258             /*
2259              * Even though this is technically before version negotiation,
2260              * because we have asked for DTLS1_BAD_VER we will never negotiate
2261              * anything else, and this has impacts on the record layer for when
2262              * we read the ServerHello. So we need to tell the record layer
2263              * about this immediately.
2264              */
2265             if (!ssl_set_record_protocol_version(s, ver_max))
2266                 return 0;
2267         }
2268     } else if (ver_max > TLS1_2_VERSION) {
2269         /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2270         ver_max = TLS1_2_VERSION;
2271     }
2272
2273     s->client_version = ver_max;
2274     return 0;
2275 }
2276
2277 /*
2278  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2279  * and |checkallow| is 1 then additionally check if the group is allowed to be
2280  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2281  * 1) or 0 otherwise.
2282  */
2283 int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2284                   size_t num_groups, int checkallow)
2285 {
2286     size_t i;
2287
2288     if (groups == NULL || num_groups == 0)
2289         return 0;
2290
2291     for (i = 0; i < num_groups; i++) {
2292         uint16_t group = groups[i];
2293
2294         if (group_id == group
2295                 && (!checkallow
2296                     || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2297             return 1;
2298         }
2299     }
2300
2301     return 0;
2302 }
2303
2304 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2305 int create_synthetic_message_hash(SSL_CONNECTION *s,
2306                                   const unsigned char *hashval,
2307                                   size_t hashlen, const unsigned char *hrr,
2308                                   size_t hrrlen)
2309 {
2310     unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2311     unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2312
2313     memset(msghdr, 0, sizeof(msghdr));
2314
2315     if (hashval == NULL) {
2316         hashval = hashvaltmp;
2317         hashlen = 0;
2318         /* Get the hash of the initial ClientHello */
2319         if (!ssl3_digest_cached_records(s, 0)
2320                 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2321                                        &hashlen)) {
2322             /* SSLfatal() already called */
2323             return 0;
2324         }
2325     }
2326
2327     /* Reinitialise the transcript hash */
2328     if (!ssl3_init_finished_mac(s)) {
2329         /* SSLfatal() already called */
2330         return 0;
2331     }
2332
2333     /* Inject the synthetic message_hash message */
2334     msghdr[0] = SSL3_MT_MESSAGE_HASH;
2335     msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2336     if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2337             || !ssl3_finish_mac(s, hashval, hashlen)) {
2338         /* SSLfatal() already called */
2339         return 0;
2340     }
2341
2342     /*
2343      * Now re-inject the HRR and current message if appropriate (we just deleted
2344      * it when we reinitialised the transcript hash above). Only necessary after
2345      * receiving a ClientHello2 with a cookie.
2346      */
2347     if (hrr != NULL
2348             && (!ssl3_finish_mac(s, hrr, hrrlen)
2349                 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2350                                     s->s3.tmp.message_size
2351                                     + SSL3_HM_HEADER_LENGTH))) {
2352         /* SSLfatal() already called */
2353         return 0;
2354     }
2355
2356     return 1;
2357 }
2358
2359 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2360 {
2361     return X509_NAME_cmp(*a, *b);
2362 }
2363
2364 int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2365 {
2366     STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2367     X509_NAME *xn = NULL;
2368     PACKET cadns;
2369
2370     if (ca_sk == NULL) {
2371         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2372         goto err;
2373     }
2374     /* get the CA RDNs */
2375     if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2376         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2377         goto err;
2378     }
2379
2380     while (PACKET_remaining(&cadns)) {
2381         const unsigned char *namestart, *namebytes;
2382         unsigned int name_len;
2383
2384         if (!PACKET_get_net_2(&cadns, &name_len)
2385             || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2386             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2387             goto err;
2388         }
2389
2390         namestart = namebytes;
2391         if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2392             SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2393             goto err;
2394         }
2395         if (namebytes != (namestart + name_len)) {
2396             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2397             goto err;
2398         }
2399
2400         if (!sk_X509_NAME_push(ca_sk, xn)) {
2401             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2402             goto err;
2403         }
2404         xn = NULL;
2405     }
2406
2407     sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2408     s->s3.tmp.peer_ca_names = ca_sk;
2409
2410     return 1;
2411
2412  err:
2413     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2414     X509_NAME_free(xn);
2415     return 0;
2416 }
2417
2418 const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2419 {
2420     const STACK_OF(X509_NAME) *ca_sk = NULL;
2421     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2422
2423     if (s->server) {
2424         ca_sk = SSL_get_client_CA_list(ssl);
2425         if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2426             ca_sk = NULL;
2427     }
2428
2429     if (ca_sk == NULL)
2430         ca_sk = SSL_get0_CA_list(ssl);
2431
2432     return ca_sk;
2433 }
2434
2435 int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2436                        WPACKET *pkt)
2437 {
2438     /* Start sub-packet for client CA list */
2439     if (!WPACKET_start_sub_packet_u16(pkt)) {
2440         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2441         return 0;
2442     }
2443
2444     if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2445         int i;
2446
2447         for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2448             unsigned char *namebytes;
2449             X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2450             int namelen;
2451
2452             if (name == NULL
2453                     || (namelen = i2d_X509_NAME(name, NULL)) < 0
2454                     || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2455                                                        &namebytes)
2456                     || i2d_X509_NAME(name, &namebytes) != namelen) {
2457                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2458                 return 0;
2459             }
2460         }
2461     }
2462
2463     if (!WPACKET_close(pkt)) {
2464         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2465         return 0;
2466     }
2467
2468     return 1;
2469 }
2470
2471 /* Create a buffer containing data to be signed for server key exchange */
2472 size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2473                                   const void *param, size_t paramlen)
2474 {
2475     size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2476     unsigned char *tbs = OPENSSL_malloc(tbslen);
2477
2478     if (tbs == NULL) {
2479         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2480         return 0;
2481     }
2482     memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2483     memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2484
2485     memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2486
2487     *ptbs = tbs;
2488     return tbslen;
2489 }
2490
2491 /*
2492  * Saves the current handshake digest for Post-Handshake Auth,
2493  * Done after ClientFinished is processed, done exactly once
2494  */
2495 int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2496 {
2497     if (s->pha_dgst == NULL) {
2498         if (!ssl3_digest_cached_records(s, 1))
2499             /* SSLfatal() already called */
2500             return 0;
2501
2502         s->pha_dgst = EVP_MD_CTX_new();
2503         if (s->pha_dgst == NULL) {
2504             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2505             return 0;
2506         }
2507         if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2508                                 s->s3.handshake_dgst)) {
2509             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2510             EVP_MD_CTX_free(s->pha_dgst);
2511             s->pha_dgst = NULL;
2512             return 0;
2513         }
2514     }
2515     return 1;
2516 }
2517
2518 /*
2519  * Restores the Post-Handshake Auth handshake digest
2520  * Done just before sending/processing the Cert Request
2521  */
2522 int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2523 {
2524     if (s->pha_dgst == NULL) {
2525         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2526         return 0;
2527     }
2528     if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2529                             s->pha_dgst)) {
2530         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2531         return 0;
2532     }
2533     return 1;
2534 }
2535
2536 #ifndef OPENSSL_NO_COMP_ALG
2537 MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
2538                                                         PACKET *pkt,
2539                                                         PACKET *tmppkt,
2540                                                         BUF_MEM *buf)
2541 {
2542     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2543     int comp_alg;
2544     COMP_METHOD *method = NULL;
2545     COMP_CTX *comp = NULL;
2546     size_t expected_length;
2547     size_t comp_length;
2548     int i;
2549     int found = 0;
2550
2551     if (buf == NULL) {
2552         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2553         goto err;
2554     }
2555     if (!PACKET_get_net_2(pkt, (unsigned int*)&comp_alg)) {
2556         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2557         goto err;
2558     }
2559     /* If we have a prefs list, make sure the algorithm is in it */
2560     if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
2561         for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2562             if (sc->cert_comp_prefs[i] == comp_alg) {
2563                 found = 1;
2564                 break;
2565             }
2566         }
2567         if (!found) {
2568             SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2569             goto err;
2570         }
2571     }
2572     if (!ossl_comp_has_alg(comp_alg)) {
2573         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2574         goto err;
2575     }
2576     switch (comp_alg) {
2577     case TLSEXT_comp_cert_zlib:
2578         method = COMP_zlib_oneshot();
2579         break;
2580     case TLSEXT_comp_cert_brotli:
2581         method = COMP_brotli_oneshot();
2582         break;
2583     case TLSEXT_comp_cert_zstd:
2584         method = COMP_zstd_oneshot();
2585         break;
2586     default:
2587         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2588         goto err;
2589     }
2590
2591     if ((comp = COMP_CTX_new(method)) == NULL
2592         || !PACKET_get_net_3_len(pkt, &expected_length)
2593         || !PACKET_get_net_3_len(pkt, &comp_length)
2594         || PACKET_remaining(pkt) != comp_length
2595         || !BUF_MEM_grow(buf, expected_length)
2596         || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
2597         || COMP_expand_block(comp, (unsigned char *)buf->data, expected_length,
2598                              (unsigned char*)PACKET_data(pkt), comp_length) != (int)expected_length) {
2599         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2600         goto err;
2601     }
2602     ret = MSG_PROCESS_CONTINUE_PROCESSING;
2603  err:
2604     COMP_CTX_free(comp);
2605     return ret;
2606 }
2607 #endif