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