88f3b94f2e2b4d23e314b5779a329b19248a8e46
[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     int ok;
791
792
793     /* This is a real handshake so make sure we clean it up at the end */
794     if (s->server) {
795         /*
796         * To get this far we must have read encrypted data from the client. We
797         * no longer tolerate unencrypted alerts. This is ignored if less than
798         * TLSv1.3
799         */
800         if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
801             s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
802         if (s->post_handshake_auth != SSL_PHA_REQUESTED)
803             s->statem.cleanuphand = 1;
804         if (SSL_CONNECTION_IS_TLS13(s)
805             && !tls13_save_handshake_digest_for_pha(s)) {
806                 /* SSLfatal() already called */
807                 return MSG_PROCESS_ERROR;
808         }
809     }
810
811     /*
812      * In TLSv1.3 a Finished message signals a key change so the end of the
813      * message must be on a record boundary.
814      */
815     if (SSL_CONNECTION_IS_TLS13(s)
816         && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
817         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
818         return MSG_PROCESS_ERROR;
819     }
820
821     /* If this occurs, we have missed a message */
822     if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
823         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
824         return MSG_PROCESS_ERROR;
825     }
826     s->s3.change_cipher_spec = 0;
827
828     md_len = s->s3.tmp.peer_finish_md_len;
829
830     if (md_len != PACKET_remaining(pkt)) {
831         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
832         return MSG_PROCESS_ERROR;
833     }
834
835     ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
836                        md_len);
837 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
838     if (ok != 0) {
839         if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
840             ok = 0;
841         }
842     }
843 #endif
844     if (ok != 0) {
845         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
846         return MSG_PROCESS_ERROR;
847     }
848
849     /*
850      * Copy the finished so we can use it for renegotiation checks
851      */
852     if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
853         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
854         return MSG_PROCESS_ERROR;
855     }
856     if (s->server) {
857         memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
858                md_len);
859         s->s3.previous_client_finished_len = md_len;
860     } else {
861         memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
862                md_len);
863         s->s3.previous_server_finished_len = md_len;
864     }
865
866     /*
867      * In TLS1.3 we also have to change cipher state and do any final processing
868      * of the initial server flight (if we are a client)
869      */
870     if (SSL_CONNECTION_IS_TLS13(s)) {
871         if (s->server) {
872             if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
873                     !ssl->method->ssl3_enc->change_cipher_state(s,
874                         SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
875                 /* SSLfatal() already called */
876                 return MSG_PROCESS_ERROR;
877             }
878         } else {
879             /* TLS 1.3 gets the secret size from the handshake md */
880             size_t dummy;
881             if (!ssl->method->ssl3_enc->generate_master_secret(s,
882                     s->master_secret, s->handshake_secret, 0,
883                     &dummy)) {
884                 /* SSLfatal() already called */
885                 return MSG_PROCESS_ERROR;
886             }
887             if (!ssl->method->ssl3_enc->change_cipher_state(s,
888                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
889                 /* SSLfatal() already called */
890                 return MSG_PROCESS_ERROR;
891             }
892             if (!tls_process_initial_server_flight(s)) {
893                 /* SSLfatal() already called */
894                 return MSG_PROCESS_ERROR;
895             }
896         }
897     }
898
899     if (was_first
900             && !SSL_IS_FIRST_HANDSHAKE(s)
901             && s->rlayer.rrlmethod->set_first_handshake != NULL)
902         s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
903
904     return MSG_PROCESS_FINISHED_READING;
905 }
906
907 CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
908 {
909     if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
910         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
911         return CON_FUNC_ERROR;
912     }
913
914     return CON_FUNC_SUCCESS;
915 }
916
917 /* Add a certificate to the WPACKET */
918 static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
919                                    X509 *x, int chain, int for_comp)
920 {
921     int len;
922     unsigned char *outbytes;
923     int context = SSL_EXT_TLS1_3_CERTIFICATE;
924
925     if (for_comp)
926         context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
927
928     len = i2d_X509(x, NULL);
929     if (len < 0) {
930         if (!for_comp)
931             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
932         return 0;
933     }
934     if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
935             || i2d_X509(x, &outbytes) != len) {
936         if (!for_comp)
937             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
938         return 0;
939     }
940
941     if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
942             && !tls_construct_extensions(s, pkt, context, x, chain)) {
943         /* SSLfatal() already called */
944         return 0;
945     }
946
947     return 1;
948 }
949
950 /* Add certificate chain to provided WPACKET */
951 static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
952 {
953     int i, chain_count;
954     X509 *x;
955     STACK_OF(X509) *extra_certs;
956     STACK_OF(X509) *chain = NULL;
957     X509_STORE *chain_store;
958     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
959
960     if (cpk == NULL || cpk->x509 == NULL)
961         return 1;
962
963     x = cpk->x509;
964
965     /*
966      * If we have a certificate specific chain use it, else use parent ctx.
967      */
968     if (cpk->chain != NULL)
969         extra_certs = cpk->chain;
970     else
971         extra_certs = sctx->extra_certs;
972
973     if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
974         chain_store = NULL;
975     else if (s->cert->chain_store)
976         chain_store = s->cert->chain_store;
977     else
978         chain_store = sctx->cert_store;
979
980     if (chain_store != NULL) {
981         X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
982                                                        sctx->propq);
983
984         if (xs_ctx == NULL) {
985             if (!for_comp)
986                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
987             return 0;
988         }
989         if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
990             X509_STORE_CTX_free(xs_ctx);
991             if (!for_comp)
992                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
993             return 0;
994         }
995         /*
996          * It is valid for the chain not to be complete (because normally we
997          * don't include the root cert in the chain). Therefore we deliberately
998          * ignore the error return from this call. We're not actually verifying
999          * the cert - we're just building as much of the chain as we can
1000          */
1001         (void)X509_verify_cert(xs_ctx);
1002         /* Don't leave errors in the queue */
1003         ERR_clear_error();
1004         chain = X509_STORE_CTX_get0_chain(xs_ctx);
1005         i = ssl_security_cert_chain(s, chain, NULL, 0);
1006         if (i != 1) {
1007 #if 0
1008             /* Dummy error calls so mkerr generates them */
1009             ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1010             ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1011             ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1012 #endif
1013             X509_STORE_CTX_free(xs_ctx);
1014             if (!for_comp)
1015                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1016             return 0;
1017         }
1018         chain_count = sk_X509_num(chain);
1019         for (i = 0; i < chain_count; i++) {
1020             x = sk_X509_value(chain, i);
1021
1022             if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1023                 /* SSLfatal() already called */
1024                 X509_STORE_CTX_free(xs_ctx);
1025                 return 0;
1026             }
1027         }
1028         X509_STORE_CTX_free(xs_ctx);
1029     } else {
1030         i = ssl_security_cert_chain(s, extra_certs, x, 0);
1031         if (i != 1) {
1032             if (!for_comp)
1033                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1034             return 0;
1035         }
1036         if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1037             /* SSLfatal() already called */
1038             return 0;
1039         }
1040         for (i = 0; i < sk_X509_num(extra_certs); i++) {
1041             x = sk_X509_value(extra_certs, i);
1042             if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1043                 /* SSLfatal() already called */
1044                 return 0;
1045             }
1046         }
1047     }
1048     return 1;
1049 }
1050
1051 unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1052                                      CERT_PKEY *cpk, int for_comp)
1053 {
1054     if (!WPACKET_start_sub_packet_u24(pkt)) {
1055         if (!for_comp)
1056             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1057         return 0;
1058     }
1059
1060     if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1061         return 0;
1062
1063     if (!WPACKET_close(pkt)) {
1064         if (!for_comp)
1065             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1066         return 0;
1067     }
1068
1069     return 1;
1070 }
1071
1072 /*
1073  * Tidy up after the end of a handshake. In the case of SCTP this may result
1074  * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1075  * freed up as well.
1076  */
1077 WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1078                                 int clearbufs, int stop)
1079 {
1080     void (*cb) (const SSL *ssl, int type, int val) = NULL;
1081     int cleanuphand = s->statem.cleanuphand;
1082     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1083     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1084
1085     if (clearbufs) {
1086         if (!SSL_CONNECTION_IS_DTLS(s)
1087 #ifndef OPENSSL_NO_SCTP
1088             /*
1089              * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1090              * messages that require it. Therefore, DTLS procedures for retransmissions
1091              * MUST NOT be used.
1092              * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1093              */
1094             || BIO_dgram_is_sctp(SSL_get_wbio(ssl))
1095 #endif
1096             ) {
1097             /*
1098              * We don't do this in DTLS over UDP because we may still need the init_buf
1099              * in case there are any unexpected retransmits
1100              */
1101             BUF_MEM_free(s->init_buf);
1102             s->init_buf = NULL;
1103         }
1104
1105         if (!ssl_free_wbio_buffer(s)) {
1106             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1107             return WORK_ERROR;
1108         }
1109         s->init_num = 0;
1110     }
1111
1112     if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1113             && s->post_handshake_auth == SSL_PHA_REQUESTED)
1114         s->post_handshake_auth = SSL_PHA_EXT_SENT;
1115
1116     /*
1117      * Only set if there was a Finished message and this isn't after a TLSv1.3
1118      * post handshake exchange
1119      */
1120     if (cleanuphand) {
1121         /* skipped if we just sent a HelloRequest */
1122         s->renegotiate = 0;
1123         s->new_session = 0;
1124         s->statem.cleanuphand = 0;
1125         s->ext.ticket_expected = 0;
1126
1127         ssl3_cleanup_key_block(s);
1128
1129         if (s->server) {
1130             /*
1131              * In TLSv1.3 we update the cache as part of constructing the
1132              * NewSessionTicket
1133              */
1134             if (!SSL_CONNECTION_IS_TLS13(s))
1135                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1136
1137             /* N.B. s->ctx may not equal s->session_ctx */
1138             ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1139             s->handshake_func = ossl_statem_accept;
1140         } else {
1141             if (SSL_CONNECTION_IS_TLS13(s)) {
1142                 /*
1143                  * We encourage applications to only use TLSv1.3 tickets once,
1144                  * so we remove this one from the cache.
1145                  */
1146                 if ((s->session_ctx->session_cache_mode
1147                      & SSL_SESS_CACHE_CLIENT) != 0)
1148                     SSL_CTX_remove_session(s->session_ctx, s->session);
1149             } else {
1150                 /*
1151                  * In TLSv1.3 we update the cache as part of processing the
1152                  * NewSessionTicket
1153                  */
1154                 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1155             }
1156             if (s->hit)
1157                 ssl_tsan_counter(s->session_ctx,
1158                                  &s->session_ctx->stats.sess_hit);
1159
1160             s->handshake_func = ossl_statem_connect;
1161             ssl_tsan_counter(s->session_ctx,
1162                              &s->session_ctx->stats.sess_connect_good);
1163         }
1164
1165         if (SSL_CONNECTION_IS_DTLS(s)) {
1166             /* done with handshaking */
1167             s->d1->handshake_read_seq = 0;
1168             s->d1->handshake_write_seq = 0;
1169             s->d1->next_handshake_write_seq = 0;
1170             dtls1_clear_received_buffer(s);
1171         }
1172     }
1173
1174     if (s->info_callback != NULL)
1175         cb = s->info_callback;
1176     else if (sctx->info_callback != NULL)
1177         cb = sctx->info_callback;
1178
1179     /* The callback may expect us to not be in init at handshake done */
1180     ossl_statem_set_in_init(s, 0);
1181
1182     if (cb != NULL) {
1183         if (cleanuphand
1184                 || !SSL_CONNECTION_IS_TLS13(s)
1185                 || SSL_IS_FIRST_HANDSHAKE(s))
1186             cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1187     }
1188
1189     if (!stop) {
1190         /* If we've got more work to do we go back into init */
1191         ossl_statem_set_in_init(s, 1);
1192         return WORK_FINISHED_CONTINUE;
1193     }
1194
1195     return WORK_FINISHED_STOP;
1196 }
1197
1198 int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1199 {
1200     /* s->init_num < SSL3_HM_HEADER_LENGTH */
1201     int skip_message, i, recvd_type;
1202     unsigned char *p;
1203     size_t l, readbytes;
1204     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1205
1206     p = (unsigned char *)s->init_buf->data;
1207
1208     do {
1209         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1210             i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1211                                             &p[s->init_num],
1212                                             SSL3_HM_HEADER_LENGTH - s->init_num,
1213                                             0, &readbytes);
1214             if (i <= 0) {
1215                 s->rwstate = SSL_READING;
1216                 return 0;
1217             }
1218             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1219                 /*
1220                  * A ChangeCipherSpec must be a single byte and may not occur
1221                  * in the middle of a handshake message.
1222                  */
1223                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1224                     SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1225                              SSL_R_BAD_CHANGE_CIPHER_SPEC);
1226                     return 0;
1227                 }
1228                 if (s->statem.hand_state == TLS_ST_BEFORE
1229                         && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1230                     /*
1231                      * We are stateless and we received a CCS. Probably this is
1232                      * from a client between the first and second ClientHellos.
1233                      * We should ignore this, but return an error because we do
1234                      * not return success until we see the second ClientHello
1235                      * with a valid cookie.
1236                      */
1237                     return 0;
1238                 }
1239                 s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1240                 s->init_num = readbytes - 1;
1241                 s->init_msg = s->init_buf->data;
1242                 s->s3.tmp.message_size = readbytes;
1243                 return 1;
1244             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1245                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1246                          SSL_R_CCS_RECEIVED_EARLY);
1247                 return 0;
1248             }
1249             s->init_num += readbytes;
1250         }
1251
1252         skip_message = 0;
1253         if (!s->server)
1254             if (s->statem.hand_state != TLS_ST_OK
1255                     && p[0] == SSL3_MT_HELLO_REQUEST)
1256                 /*
1257                  * The server may always send 'Hello Request' messages --
1258                  * we are doing a handshake anyway now, so ignore them if
1259                  * their format is correct. Does not count for 'Finished'
1260                  * MAC.
1261                  */
1262                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1263                     s->init_num = 0;
1264                     skip_message = 1;
1265
1266                     if (s->msg_callback)
1267                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1268                                         p, SSL3_HM_HEADER_LENGTH, ssl,
1269                                         s->msg_callback_arg);
1270                 }
1271     } while (skip_message);
1272     /* s->init_num == SSL3_HM_HEADER_LENGTH */
1273
1274     *mt = *p;
1275     s->s3.tmp.message_type = *(p++);
1276
1277     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1278         /*
1279          * Only happens with SSLv3+ in an SSLv2 backward compatible
1280          * ClientHello
1281          *
1282          * Total message size is the remaining record bytes to read
1283          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1284          */
1285         l = s->rlayer.tlsrecs[0].length + SSL3_HM_HEADER_LENGTH;
1286         s->s3.tmp.message_size = l;
1287
1288         s->init_msg = s->init_buf->data;
1289         s->init_num = SSL3_HM_HEADER_LENGTH;
1290     } else {
1291         n2l3(p, l);
1292         /* BUF_MEM_grow takes an 'int' parameter */
1293         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1294             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1295                      SSL_R_EXCESSIVE_MESSAGE_SIZE);
1296             return 0;
1297         }
1298         s->s3.tmp.message_size = l;
1299
1300         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1301         s->init_num = 0;
1302     }
1303
1304     return 1;
1305 }
1306
1307 int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1308 {
1309     size_t n, readbytes;
1310     unsigned char *p;
1311     int i;
1312     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1313
1314     if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1315         /* We've already read everything in */
1316         *len = (unsigned long)s->init_num;
1317         return 1;
1318     }
1319
1320     p = s->init_msg;
1321     n = s->s3.tmp.message_size - s->init_num;
1322     while (n > 0) {
1323         i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1324                                         &p[s->init_num], n, 0, &readbytes);
1325         if (i <= 0) {
1326             s->rwstate = SSL_READING;
1327             *len = 0;
1328             return 0;
1329         }
1330         s->init_num += readbytes;
1331         n -= readbytes;
1332     }
1333
1334     /*
1335      * If receiving Finished, record MAC of prior handshake messages for
1336      * Finished verification.
1337      */
1338     if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1339         /* SSLfatal() already called */
1340         *len = 0;
1341         return 0;
1342     }
1343
1344     /* Feed this message into MAC computation. */
1345     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1346         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1347                              s->init_num)) {
1348             /* SSLfatal() already called */
1349             *len = 0;
1350             return 0;
1351         }
1352         if (s->msg_callback)
1353             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1354                             (size_t)s->init_num, ssl, s->msg_callback_arg);
1355     } else {
1356         /*
1357          * We defer feeding in the HRR until later. We'll do it as part of
1358          * processing the message
1359          * The TLsv1.3 handshake transcript stops at the ClientFinished
1360          * message.
1361          */
1362 #define SERVER_HELLO_RANDOM_OFFSET  (SSL3_HM_HEADER_LENGTH + 2)
1363         /* KeyUpdate and NewSessionTicket do not need to be added */
1364         if (!SSL_CONNECTION_IS_TLS13(s)
1365             || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1366                          && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1367             if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1368                     || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1369                     || memcmp(hrrrandom,
1370                               s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1371                               SSL3_RANDOM_SIZE) != 0) {
1372                 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1373                                      s->init_num + SSL3_HM_HEADER_LENGTH)) {
1374                     /* SSLfatal() already called */
1375                     *len = 0;
1376                     return 0;
1377                 }
1378             }
1379         }
1380         if (s->msg_callback)
1381             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1382                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ssl,
1383                             s->msg_callback_arg);
1384     }
1385
1386     *len = s->init_num;
1387     return 1;
1388 }
1389
1390 static const X509ERR2ALERT x509table[] = {
1391     {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1392     {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1393     {X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE},
1394     {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1395     {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1396     {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1397     {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1398     {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1399     {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1400     {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1401     {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1402     {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1403     {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1404     {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1405     {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1406     {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1407     {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1408     {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1409     {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1410     {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1411     {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1412     {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1413     {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1414     {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1415     {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1416     {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1417     {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1418     {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1419     {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1420     {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1421     {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1422     {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1423     {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1424     {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1425     {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1426     {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1427     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1428     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1429     {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1430     {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1431
1432     /* Last entry; return this if we don't find the value above. */
1433     {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1434 };
1435
1436 int ssl_x509err2alert(int x509err)
1437 {
1438     const X509ERR2ALERT *tp;
1439
1440     for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1441         if (tp->x509err == x509err)
1442             break;
1443     return tp->alert;
1444 }
1445
1446 int ssl_allow_compression(SSL_CONNECTION *s)
1447 {
1448     if (s->options & SSL_OP_NO_COMPRESSION)
1449         return 0;
1450     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1451 }
1452
1453 static int version_cmp(const SSL_CONNECTION *s, int a, int b)
1454 {
1455     int dtls = SSL_CONNECTION_IS_DTLS(s);
1456
1457     if (a == b)
1458         return 0;
1459     if (!dtls)
1460         return a < b ? -1 : 1;
1461     return DTLS_VERSION_LT(a, b) ? -1 : 1;
1462 }
1463
1464 typedef struct {
1465     int version;
1466     const SSL_METHOD *(*cmeth) (void);
1467     const SSL_METHOD *(*smeth) (void);
1468 } version_info;
1469
1470 #if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1471 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1472 #endif
1473
1474 /* Must be in order high to low */
1475 static const version_info tls_version_table[] = {
1476 #ifndef OPENSSL_NO_TLS1_3
1477     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1478 #else
1479     {TLS1_3_VERSION, NULL, NULL},
1480 #endif
1481 #ifndef OPENSSL_NO_TLS1_2
1482     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1483 #else
1484     {TLS1_2_VERSION, NULL, NULL},
1485 #endif
1486 #ifndef OPENSSL_NO_TLS1_1
1487     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1488 #else
1489     {TLS1_1_VERSION, NULL, NULL},
1490 #endif
1491 #ifndef OPENSSL_NO_TLS1
1492     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1493 #else
1494     {TLS1_VERSION, NULL, NULL},
1495 #endif
1496 #ifndef OPENSSL_NO_SSL3
1497     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1498 #else
1499     {SSL3_VERSION, NULL, NULL},
1500 #endif
1501     {0, NULL, NULL},
1502 };
1503
1504 #if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1505 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1506 #endif
1507
1508 /* Must be in order high to low */
1509 static const version_info dtls_version_table[] = {
1510 #ifndef OPENSSL_NO_DTLS1_2
1511     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1512 #else
1513     {DTLS1_2_VERSION, NULL, NULL},
1514 #endif
1515 #ifndef OPENSSL_NO_DTLS1
1516     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1517     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1518 #else
1519     {DTLS1_VERSION, NULL, NULL},
1520     {DTLS1_BAD_VER, NULL, NULL},
1521 #endif
1522     {0, NULL, NULL},
1523 };
1524
1525 /*
1526  * ssl_method_error - Check whether an SSL_METHOD is enabled.
1527  *
1528  * @s: The SSL handle for the candidate method
1529  * @method: the intended method.
1530  *
1531  * Returns 0 on success, or an SSL error reason on failure.
1532  */
1533 static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1534 {
1535     int version = method->version;
1536
1537     if ((s->min_proto_version != 0 &&
1538          version_cmp(s, version, s->min_proto_version) < 0) ||
1539         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1540         return SSL_R_VERSION_TOO_LOW;
1541
1542     if (s->max_proto_version != 0 &&
1543         version_cmp(s, version, s->max_proto_version) > 0)
1544         return SSL_R_VERSION_TOO_HIGH;
1545
1546     if ((s->options & method->mask) != 0)
1547         return SSL_R_UNSUPPORTED_PROTOCOL;
1548     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1549         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1550
1551     return 0;
1552 }
1553
1554 /*
1555  * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1556  * certificate type, or has PSK or a certificate callback configured, or has
1557  * a servername callback configure. Otherwise returns 0.
1558  */
1559 static int is_tls13_capable(const SSL_CONNECTION *s)
1560 {
1561     int i;
1562     int curve;
1563     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1564
1565     if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1566         return 0;
1567
1568     /*
1569      * A servername callback can change the available certs, so if a servername
1570      * cb is set then we just assume TLSv1.3 will be ok
1571      */
1572     if (sctx->ext.servername_cb != NULL
1573             || s->session_ctx->ext.servername_cb != NULL)
1574         return 1;
1575
1576 #ifndef OPENSSL_NO_PSK
1577     if (s->psk_server_callback != NULL)
1578         return 1;
1579 #endif
1580
1581     if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1582         return 1;
1583
1584     for (i = 0; i < SSL_PKEY_NUM; i++) {
1585         /* Skip over certs disallowed for TLSv1.3 */
1586         switch (i) {
1587         case SSL_PKEY_DSA_SIGN:
1588         case SSL_PKEY_GOST01:
1589         case SSL_PKEY_GOST12_256:
1590         case SSL_PKEY_GOST12_512:
1591             continue;
1592         default:
1593             break;
1594         }
1595         if (!ssl_has_cert(s, i))
1596             continue;
1597         if (i != SSL_PKEY_ECC)
1598             return 1;
1599         /*
1600          * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1601          * more restrictive so check that our sig algs are consistent with this
1602          * EC cert. See section 4.2.3 of RFC8446.
1603          */
1604         curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1605         if (tls_check_sigalg_curve(s, curve))
1606             return 1;
1607     }
1608
1609     return 0;
1610 }
1611
1612 /*
1613  * ssl_version_supported - Check that the specified `version` is supported by
1614  * `SSL *` instance
1615  *
1616  * @s: The SSL handle for the candidate method
1617  * @version: Protocol version to test against
1618  *
1619  * Returns 1 when supported, otherwise 0
1620  */
1621 int ssl_version_supported(const SSL_CONNECTION *s, int version,
1622                           const SSL_METHOD **meth)
1623 {
1624     const version_info *vent;
1625     const version_info *table;
1626
1627     switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1628     default:
1629         /* Version should match method version for non-ANY method */
1630         return version_cmp(s, version, s->version) == 0;
1631     case TLS_ANY_VERSION:
1632         table = tls_version_table;
1633         break;
1634     case DTLS_ANY_VERSION:
1635         table = dtls_version_table;
1636         break;
1637     }
1638
1639     for (vent = table;
1640          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1641          ++vent) {
1642         if (vent->cmeth != NULL
1643                 && version_cmp(s, version, vent->version) == 0
1644                 && ssl_method_error(s, vent->cmeth()) == 0
1645                 && (!s->server
1646                     || version != TLS1_3_VERSION
1647                     || is_tls13_capable(s))) {
1648             if (meth != NULL)
1649                 *meth = vent->cmeth();
1650             return 1;
1651         }
1652     }
1653     return 0;
1654 }
1655
1656 /*
1657  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1658  * fallback indication from a client check whether we're using the highest
1659  * supported protocol version.
1660  *
1661  * @s server SSL handle.
1662  *
1663  * Returns 1 when using the highest enabled version, 0 otherwise.
1664  */
1665 int ssl_check_version_downgrade(SSL_CONNECTION *s)
1666 {
1667     const version_info *vent;
1668     const version_info *table;
1669     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1670
1671     /*
1672      * Check that the current protocol is the highest enabled version
1673      * (according to ssl->defltmethod, as version negotiation may have changed
1674      * s->method).
1675      */
1676     if (s->version == ssl->defltmeth->version)
1677         return 1;
1678
1679     /*
1680      * Apparently we're using a version-flexible SSL_METHOD (not at its
1681      * highest protocol version).
1682      */
1683     if (ssl->defltmeth->version == TLS_method()->version)
1684         table = tls_version_table;
1685     else if (ssl->defltmeth->version == DTLS_method()->version)
1686         table = dtls_version_table;
1687     else {
1688         /* Unexpected state; fail closed. */
1689         return 0;
1690     }
1691
1692     for (vent = table; vent->version != 0; ++vent) {
1693         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1694             return s->version == vent->version;
1695     }
1696     return 0;
1697 }
1698
1699 /*
1700  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1701  * protocols, provided the initial (D)TLS method is version-flexible.  This
1702  * function sanity-checks the proposed value and makes sure the method is
1703  * version-flexible, then sets the limit if all is well.
1704  *
1705  * @method_version: The version of the current SSL_METHOD.
1706  * @version: the intended limit.
1707  * @bound: pointer to limit to be updated.
1708  *
1709  * Returns 1 on success, 0 on failure.
1710  */
1711 int ssl_set_version_bound(int method_version, int version, int *bound)
1712 {
1713     int valid_tls;
1714     int valid_dtls;
1715
1716     if (version == 0) {
1717         *bound = version;
1718         return 1;
1719     }
1720
1721     valid_tls = version >= SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
1722     valid_dtls =
1723         DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL) &&
1724         DTLS_VERSION_GE(version, DTLS1_BAD_VER);
1725
1726     if (!valid_tls && !valid_dtls)
1727         return 0;
1728
1729     /*-
1730      * Restrict TLS methods to TLS protocol versions.
1731      * Restrict DTLS methods to DTLS protocol versions.
1732      * Note, DTLS version numbers are decreasing, use comparison macros.
1733      *
1734      * Note that for both lower-bounds we use explicit versions, not
1735      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
1736      * configurations.  If the MIN (supported) version ever rises, the user's
1737      * "floor" remains valid even if no longer available.  We don't expect the
1738      * MAX ceiling to ever get lower, so making that variable makes sense.
1739      *
1740      * We ignore attempts to set bounds on version-inflexible methods,
1741      * returning success.
1742      */
1743     switch (method_version) {
1744     default:
1745         break;
1746
1747     case TLS_ANY_VERSION:
1748         if (valid_tls)
1749             *bound = version;
1750         break;
1751
1752     case DTLS_ANY_VERSION:
1753         if (valid_dtls)
1754             *bound = version;
1755         break;
1756     }
1757     return 1;
1758 }
1759
1760 static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
1761 {
1762     if (vers == TLS1_2_VERSION
1763             && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1764         *dgrd = DOWNGRADE_TO_1_2;
1765     } else if (!SSL_CONNECTION_IS_DTLS(s)
1766             && vers < TLS1_2_VERSION
1767                /*
1768                 * We need to ensure that a server that disables TLSv1.2
1769                 * (creating a hole between TLSv1.3 and TLSv1.1) can still
1770                 * complete handshakes with clients that support TLSv1.2 and
1771                 * below. Therefore we do not enable the sentinel if TLSv1.3 is
1772                 * enabled and TLSv1.2 is not.
1773                 */
1774             && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
1775         *dgrd = DOWNGRADE_TO_1_1;
1776     } else {
1777         *dgrd = DOWNGRADE_NONE;
1778     }
1779 }
1780
1781 /*
1782  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
1783  * client HELLO is received to select the final server protocol version and
1784  * the version specific method.
1785  *
1786  * @s: server SSL handle.
1787  *
1788  * Returns 0 on success or an SSL error reason number on failure.
1789  */
1790 int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
1791                               DOWNGRADE *dgrd)
1792 {
1793     /*-
1794      * With version-flexible methods we have an initial state with:
1795      *
1796      *   s->method->version == (D)TLS_ANY_VERSION,
1797      *   s->version == (D)TLS_MAX_VERSION_INTERNAL.
1798      *
1799      * So we detect version-flexible methods via the method version, not the
1800      * handle version.
1801      */
1802     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1803     int server_version = ssl->method->version;
1804     int client_version = hello->legacy_version;
1805     const version_info *vent;
1806     const version_info *table;
1807     int disabled = 0;
1808     RAW_EXTENSION *suppversions;
1809
1810     s->client_version = client_version;
1811
1812     switch (server_version) {
1813     default:
1814         if (!SSL_CONNECTION_IS_TLS13(s)) {
1815             if (version_cmp(s, client_version, s->version) < 0)
1816                 return SSL_R_WRONG_SSL_VERSION;
1817             *dgrd = DOWNGRADE_NONE;
1818             /*
1819              * If this SSL handle is not from a version flexible method we don't
1820              * (and never did) check min/max FIPS or Suite B constraints.  Hope
1821              * that's OK.  It is up to the caller to not choose fixed protocol
1822              * versions they don't want.  If not, then easy to fix, just return
1823              * ssl_method_error(s, s->method)
1824              */
1825             return 0;
1826         }
1827         /*
1828          * Fall through if we are TLSv1.3 already (this means we must be after
1829          * a HelloRetryRequest
1830          */
1831         /* fall thru */
1832     case TLS_ANY_VERSION:
1833         table = tls_version_table;
1834         break;
1835     case DTLS_ANY_VERSION:
1836         table = dtls_version_table;
1837         break;
1838     }
1839
1840     suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1841
1842     /* If we did an HRR then supported versions is mandatory */
1843     if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1844         return SSL_R_UNSUPPORTED_PROTOCOL;
1845
1846     if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
1847         unsigned int candidate_vers = 0;
1848         unsigned int best_vers = 0;
1849         const SSL_METHOD *best_method = NULL;
1850         PACKET versionslist;
1851
1852         suppversions->parsed = 1;
1853
1854         if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1855             /* Trailing or invalid data? */
1856             return SSL_R_LENGTH_MISMATCH;
1857         }
1858
1859         /*
1860          * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1861          * The spec only requires servers to check that it isn't SSLv3:
1862          * "Any endpoint receiving a Hello message with
1863          * ClientHello.legacy_version or ServerHello.legacy_version set to
1864          * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1865          * We are slightly stricter and require that it isn't SSLv3 or lower.
1866          * We tolerate TLSv1 and TLSv1.1.
1867          */
1868         if (client_version <= SSL3_VERSION)
1869             return SSL_R_BAD_LEGACY_VERSION;
1870
1871         while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1872             if (version_cmp(s, candidate_vers, best_vers) <= 0)
1873                 continue;
1874             if (ssl_version_supported(s, candidate_vers, &best_method))
1875                 best_vers = candidate_vers;
1876         }
1877         if (PACKET_remaining(&versionslist) != 0) {
1878             /* Trailing data? */
1879             return SSL_R_LENGTH_MISMATCH;
1880         }
1881
1882         if (best_vers > 0) {
1883             if (s->hello_retry_request != SSL_HRR_NONE) {
1884                 /*
1885                  * This is after a HelloRetryRequest so we better check that we
1886                  * negotiated TLSv1.3
1887                  */
1888                 if (best_vers != TLS1_3_VERSION)
1889                     return SSL_R_UNSUPPORTED_PROTOCOL;
1890                 return 0;
1891             }
1892             check_for_downgrade(s, best_vers, dgrd);
1893             s->version = best_vers;
1894             ssl->method = best_method;
1895             if (!ssl_set_record_protocol_version(s, best_vers))
1896                 return ERR_R_INTERNAL_ERROR;
1897
1898             return 0;
1899         }
1900         return SSL_R_UNSUPPORTED_PROTOCOL;
1901     }
1902
1903     /*
1904      * If the supported versions extension isn't present, then the highest
1905      * version we can negotiate is TLSv1.2
1906      */
1907     if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1908         client_version = TLS1_2_VERSION;
1909
1910     /*
1911      * No supported versions extension, so we just use the version supplied in
1912      * the ClientHello.
1913      */
1914     for (vent = table; vent->version != 0; ++vent) {
1915         const SSL_METHOD *method;
1916
1917         if (vent->smeth == NULL ||
1918             version_cmp(s, client_version, vent->version) < 0)
1919             continue;
1920         method = vent->smeth();
1921         if (ssl_method_error(s, method) == 0) {
1922             check_for_downgrade(s, vent->version, dgrd);
1923             s->version = vent->version;
1924             ssl->method = method;
1925             if (!ssl_set_record_protocol_version(s, s->version))
1926                 return ERR_R_INTERNAL_ERROR;
1927
1928             return 0;
1929         }
1930         disabled = 1;
1931     }
1932     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1933 }
1934
1935 /*
1936  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
1937  * server HELLO is received to select the final client protocol version and
1938  * the version specific method.
1939  *
1940  * @s: client SSL handle.
1941  * @version: The proposed version from the server's HELLO.
1942  * @extensions: The extensions received
1943  *
1944  * Returns 1 on success or 0 on error.
1945  */
1946 int ssl_choose_client_version(SSL_CONNECTION *s, int version,
1947                               RAW_EXTENSION *extensions)
1948 {
1949     const version_info *vent;
1950     const version_info *table;
1951     int ret, ver_min, ver_max, real_max, origv;
1952     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1953
1954     origv = s->version;
1955     s->version = version;
1956
1957     /* This will overwrite s->version if the extension is present */
1958     if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1959                              SSL_EXT_TLS1_2_SERVER_HELLO
1960                              | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1961                              NULL, 0)) {
1962         s->version = origv;
1963         return 0;
1964     }
1965
1966     if (s->hello_retry_request != SSL_HRR_NONE
1967             && s->version != TLS1_3_VERSION) {
1968         s->version = origv;
1969         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1970         return 0;
1971     }
1972
1973     switch (ssl->method->version) {
1974     default:
1975         if (s->version != ssl->method->version) {
1976             s->version = origv;
1977             SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
1978             return 0;
1979         }
1980         /*
1981          * If this SSL handle is not from a version flexible method we don't
1982          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
1983          * that's OK.  It is up to the caller to not choose fixed protocol
1984          * versions they don't want.  If not, then easy to fix, just return
1985          * ssl_method_error(s, s->method)
1986          */
1987         if (!ssl_set_record_protocol_version(s, s->version)) {
1988             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1989             return 0;
1990         }
1991         return 1;
1992     case TLS_ANY_VERSION:
1993         table = tls_version_table;
1994         break;
1995     case DTLS_ANY_VERSION:
1996         table = dtls_version_table;
1997         break;
1998     }
1999
2000     ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2001     if (ret != 0) {
2002         s->version = origv;
2003         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2004         return 0;
2005     }
2006     if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_LT(s->version, ver_min)
2007                                   : s->version < ver_min) {
2008         s->version = origv;
2009         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2010         return 0;
2011     } else if (SSL_CONNECTION_IS_DTLS(s) ? DTLS_VERSION_GT(s->version, ver_max)
2012                                          : s->version > ver_max) {
2013         s->version = origv;
2014         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2015         return 0;
2016     }
2017
2018     if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2019         real_max = ver_max;
2020
2021     /* Check for downgrades */
2022     if (s->version == TLS1_2_VERSION && real_max > s->version) {
2023         if (memcmp(tls12downgrade,
2024                    s->s3.server_random + SSL3_RANDOM_SIZE
2025                                         - sizeof(tls12downgrade),
2026                    sizeof(tls12downgrade)) == 0) {
2027             s->version = origv;
2028             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2029                      SSL_R_INAPPROPRIATE_FALLBACK);
2030             return 0;
2031         }
2032     } else if (!SSL_CONNECTION_IS_DTLS(s)
2033                && s->version < TLS1_2_VERSION
2034                && real_max > s->version) {
2035         if (memcmp(tls11downgrade,
2036                    s->s3.server_random + SSL3_RANDOM_SIZE
2037                                         - sizeof(tls11downgrade),
2038                    sizeof(tls11downgrade)) == 0) {
2039             s->version = origv;
2040             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2041                      SSL_R_INAPPROPRIATE_FALLBACK);
2042             return 0;
2043         }
2044     }
2045
2046     for (vent = table; vent->version != 0; ++vent) {
2047         if (vent->cmeth == NULL || s->version != vent->version)
2048             continue;
2049
2050         ssl->method = vent->cmeth();
2051         if (!ssl_set_record_protocol_version(s, s->version)) {
2052             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2053             return 0;
2054         }
2055         return 1;
2056     }
2057
2058     s->version = origv;
2059     SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2060     return 0;
2061 }
2062
2063 /*
2064  * ssl_get_min_max_version - get minimum and maximum protocol version
2065  * @s: The SSL connection
2066  * @min_version: The minimum supported version
2067  * @max_version: The maximum supported version
2068  * @real_max:    The highest version below the lowest compile time version hole
2069  *               where that hole lies above at least one run-time enabled
2070  *               protocol.
2071  *
2072  * Work out what version we should be using for the initial ClientHello if the
2073  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
2074  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2075  * constraints and any floor imposed by the security level here,
2076  * so we don't advertise the wrong protocol version to only reject the outcome later.
2077  *
2078  * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
2079  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
2080  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2081  *
2082  * Returns 0 on success or an SSL error reason number on failure.  On failure
2083  * min_version and max_version will also be set to 0.
2084  */
2085 int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2086                             int *max_version, int *real_max)
2087 {
2088     int version, tmp_real_max;
2089     int hole;
2090     const SSL_METHOD *single = NULL;
2091     const SSL_METHOD *method;
2092     const version_info *table;
2093     const version_info *vent;
2094     const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2095
2096     switch (ssl->method->version) {
2097     default:
2098         /*
2099          * If this SSL handle is not from a version flexible method we don't
2100          * (and never did) check min/max FIPS or Suite B constraints.  Hope
2101          * that's OK.  It is up to the caller to not choose fixed protocol
2102          * versions they don't want.  If not, then easy to fix, just return
2103          * ssl_method_error(s, s->method)
2104          */
2105         *min_version = *max_version = s->version;
2106         /*
2107          * Providing a real_max only makes sense where we're using a version
2108          * flexible method.
2109          */
2110         if (!ossl_assert(real_max == NULL))
2111             return ERR_R_INTERNAL_ERROR;
2112         return 0;
2113     case TLS_ANY_VERSION:
2114         table = tls_version_table;
2115         break;
2116     case DTLS_ANY_VERSION:
2117         table = dtls_version_table;
2118         break;
2119     }
2120
2121     /*
2122      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2123      * below X enabled. This is required in order to maintain the "version
2124      * capability" vector contiguous. Any versions with a NULL client method
2125      * (protocol version client is disabled at compile-time) is also a "hole".
2126      *
2127      * Our initial state is hole == 1, version == 0.  That is, versions above
2128      * the first version in the method table are disabled (a "hole" above
2129      * the valid protocol entries) and we don't have a selected version yet.
2130      *
2131      * Whenever "hole == 1", and we hit an enabled method, its version becomes
2132      * the selected version, and the method becomes a candidate "single"
2133      * method.  We're no longer in a hole, so "hole" becomes 0.
2134      *
2135      * If "hole == 0" and we hit an enabled method, then "single" is cleared,
2136      * as we support a contiguous range of at least two methods.  If we hit
2137      * a disabled method, then hole becomes true again, but nothing else
2138      * changes yet, because all the remaining methods may be disabled too.
2139      * If we again hit an enabled method after the new hole, it becomes
2140      * selected, as we start from scratch.
2141      */
2142     *min_version = version = 0;
2143     hole = 1;
2144     if (real_max != NULL)
2145         *real_max = 0;
2146     tmp_real_max = 0;
2147     for (vent = table; vent->version != 0; ++vent) {
2148         /*
2149          * A table entry with a NULL client method is still a hole in the
2150          * "version capability" vector.
2151          */
2152         if (vent->cmeth == NULL) {
2153             hole = 1;
2154             tmp_real_max = 0;
2155             continue;
2156         }
2157         method = vent->cmeth();
2158
2159         if (hole == 1 && tmp_real_max == 0)
2160             tmp_real_max = vent->version;
2161
2162         if (ssl_method_error(s, method) != 0) {
2163             hole = 1;
2164         } else if (!hole) {
2165             single = NULL;
2166             *min_version = method->version;
2167         } else {
2168             if (real_max != NULL && tmp_real_max != 0)
2169                 *real_max = tmp_real_max;
2170             version = (single = method)->version;
2171             *min_version = version;
2172             hole = 0;
2173         }
2174     }
2175
2176     *max_version = version;
2177
2178     /* Fail if everything is disabled */
2179     if (version == 0)
2180         return SSL_R_NO_PROTOCOLS_AVAILABLE;
2181
2182     return 0;
2183 }
2184
2185 /*
2186  * ssl_set_client_hello_version - Work out what version we should be using for
2187  * the initial ClientHello.legacy_version field.
2188  *
2189  * @s: client SSL handle.
2190  *
2191  * Returns 0 on success or an SSL error reason number on failure.
2192  */
2193 int ssl_set_client_hello_version(SSL_CONNECTION *s)
2194 {
2195     int ver_min, ver_max, ret;
2196
2197     /*
2198      * In a renegotiation we always send the same client_version that we sent
2199      * last time, regardless of which version we eventually negotiated.
2200      */
2201     if (!SSL_IS_FIRST_HANDSHAKE(s))
2202         return 0;
2203
2204     ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2205
2206     if (ret != 0)
2207         return ret;
2208
2209     s->version = ver_max;
2210
2211     if (SSL_CONNECTION_IS_DTLS(s)) {
2212         if (ver_max == DTLS1_BAD_VER) {
2213             /*
2214              * Even though this is technically before version negotiation,
2215              * because we have asked for DTLS1_BAD_VER we will never negotiate
2216              * anything else, and this has impacts on the record layer for when
2217              * we read the ServerHello. So we need to tell the record layer
2218              * about this immediately.
2219              */
2220             if (!ssl_set_record_protocol_version(s, ver_max))
2221                 return 0;
2222         }
2223     } else if (ver_max > TLS1_2_VERSION) {
2224         /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2225         ver_max = TLS1_2_VERSION;
2226     }
2227
2228     s->client_version = ver_max;
2229     return 0;
2230 }
2231
2232 /*
2233  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2234  * and |checkallow| is 1 then additionally check if the group is allowed to be
2235  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2236  * 1) or 0 otherwise.
2237  */
2238 int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2239                   size_t num_groups, int checkallow)
2240 {
2241     size_t i;
2242
2243     if (groups == NULL || num_groups == 0)
2244         return 0;
2245
2246     for (i = 0; i < num_groups; i++) {
2247         uint16_t group = groups[i];
2248
2249         if (group_id == group
2250                 && (!checkallow
2251                     || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2252             return 1;
2253         }
2254     }
2255
2256     return 0;
2257 }
2258
2259 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2260 int create_synthetic_message_hash(SSL_CONNECTION *s,
2261                                   const unsigned char *hashval,
2262                                   size_t hashlen, const unsigned char *hrr,
2263                                   size_t hrrlen)
2264 {
2265     unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2266     unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2267
2268     memset(msghdr, 0, sizeof(msghdr));
2269
2270     if (hashval == NULL) {
2271         hashval = hashvaltmp;
2272         hashlen = 0;
2273         /* Get the hash of the initial ClientHello */
2274         if (!ssl3_digest_cached_records(s, 0)
2275                 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2276                                        &hashlen)) {
2277             /* SSLfatal() already called */
2278             return 0;
2279         }
2280     }
2281
2282     /* Reinitialise the transcript hash */
2283     if (!ssl3_init_finished_mac(s)) {
2284         /* SSLfatal() already called */
2285         return 0;
2286     }
2287
2288     /* Inject the synthetic message_hash message */
2289     msghdr[0] = SSL3_MT_MESSAGE_HASH;
2290     msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2291     if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2292             || !ssl3_finish_mac(s, hashval, hashlen)) {
2293         /* SSLfatal() already called */
2294         return 0;
2295     }
2296
2297     /*
2298      * Now re-inject the HRR and current message if appropriate (we just deleted
2299      * it when we reinitialised the transcript hash above). Only necessary after
2300      * receiving a ClientHello2 with a cookie.
2301      */
2302     if (hrr != NULL
2303             && (!ssl3_finish_mac(s, hrr, hrrlen)
2304                 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2305                                     s->s3.tmp.message_size
2306                                     + SSL3_HM_HEADER_LENGTH))) {
2307         /* SSLfatal() already called */
2308         return 0;
2309     }
2310
2311     return 1;
2312 }
2313
2314 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2315 {
2316     return X509_NAME_cmp(*a, *b);
2317 }
2318
2319 int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2320 {
2321     STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2322     X509_NAME *xn = NULL;
2323     PACKET cadns;
2324
2325     if (ca_sk == NULL) {
2326         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2327         goto err;
2328     }
2329     /* get the CA RDNs */
2330     if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2331         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2332         goto err;
2333     }
2334
2335     while (PACKET_remaining(&cadns)) {
2336         const unsigned char *namestart, *namebytes;
2337         unsigned int name_len;
2338
2339         if (!PACKET_get_net_2(&cadns, &name_len)
2340             || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2341             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2342             goto err;
2343         }
2344
2345         namestart = namebytes;
2346         if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2347             SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2348             goto err;
2349         }
2350         if (namebytes != (namestart + name_len)) {
2351             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2352             goto err;
2353         }
2354
2355         if (!sk_X509_NAME_push(ca_sk, xn)) {
2356             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2357             goto err;
2358         }
2359         xn = NULL;
2360     }
2361
2362     sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2363     s->s3.tmp.peer_ca_names = ca_sk;
2364
2365     return 1;
2366
2367  err:
2368     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2369     X509_NAME_free(xn);
2370     return 0;
2371 }
2372
2373 const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2374 {
2375     const STACK_OF(X509_NAME) *ca_sk = NULL;
2376     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2377
2378     if (s->server) {
2379         ca_sk = SSL_get_client_CA_list(ssl);
2380         if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2381             ca_sk = NULL;
2382     }
2383
2384     if (ca_sk == NULL)
2385         ca_sk = SSL_get0_CA_list(ssl);
2386
2387     return ca_sk;
2388 }
2389
2390 int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2391                        WPACKET *pkt)
2392 {
2393     /* Start sub-packet for client CA list */
2394     if (!WPACKET_start_sub_packet_u16(pkt)) {
2395         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2396         return 0;
2397     }
2398
2399     if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2400         int i;
2401
2402         for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2403             unsigned char *namebytes;
2404             X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2405             int namelen;
2406
2407             if (name == NULL
2408                     || (namelen = i2d_X509_NAME(name, NULL)) < 0
2409                     || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2410                                                        &namebytes)
2411                     || i2d_X509_NAME(name, &namebytes) != namelen) {
2412                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2413                 return 0;
2414             }
2415         }
2416     }
2417
2418     if (!WPACKET_close(pkt)) {
2419         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2420         return 0;
2421     }
2422
2423     return 1;
2424 }
2425
2426 /* Create a buffer containing data to be signed for server key exchange */
2427 size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2428                                   const void *param, size_t paramlen)
2429 {
2430     size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2431     unsigned char *tbs = OPENSSL_malloc(tbslen);
2432
2433     if (tbs == NULL) {
2434         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2435         return 0;
2436     }
2437     memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2438     memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2439
2440     memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2441
2442     *ptbs = tbs;
2443     return tbslen;
2444 }
2445
2446 /*
2447  * Saves the current handshake digest for Post-Handshake Auth,
2448  * Done after ClientFinished is processed, done exactly once
2449  */
2450 int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2451 {
2452     if (s->pha_dgst == NULL) {
2453         if (!ssl3_digest_cached_records(s, 1))
2454             /* SSLfatal() already called */
2455             return 0;
2456
2457         s->pha_dgst = EVP_MD_CTX_new();
2458         if (s->pha_dgst == NULL) {
2459             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2460             return 0;
2461         }
2462         if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2463                                 s->s3.handshake_dgst)) {
2464             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2465             EVP_MD_CTX_free(s->pha_dgst);
2466             s->pha_dgst = NULL;
2467             return 0;
2468         }
2469     }
2470     return 1;
2471 }
2472
2473 /*
2474  * Restores the Post-Handshake Auth handshake digest
2475  * Done just before sending/processing the Cert Request
2476  */
2477 int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2478 {
2479     if (s->pha_dgst == NULL) {
2480         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2481         return 0;
2482     }
2483     if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2484                             s->pha_dgst)) {
2485         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2486         return 0;
2487     }
2488     return 1;
2489 }
2490
2491 #ifndef OPENSSL_NO_COMP_ALG
2492 MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
2493                                                         PACKET *pkt,
2494                                                         PACKET *tmppkt,
2495                                                         BUF_MEM *buf)
2496 {
2497     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2498     int comp_alg;
2499     COMP_METHOD *method = NULL;
2500     COMP_CTX *comp = NULL;
2501     size_t expected_length;
2502     size_t comp_length;
2503     int i;
2504     int found = 0;
2505
2506     if (buf == NULL) {
2507         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2508         goto err;
2509     }
2510     if (!PACKET_get_net_2(pkt, (unsigned int*)&comp_alg)) {
2511         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2512         goto err;
2513     }
2514     /* If we have a prefs list, make sure the algorithm is in it */
2515     if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
2516         for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2517             if (sc->cert_comp_prefs[i] == comp_alg) {
2518                 found = 1;
2519                 break;
2520             }
2521         }
2522         if (!found) {
2523             SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2524             goto err;
2525         }
2526     }
2527     if (!ossl_comp_has_alg(comp_alg)) {
2528         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2529         goto err;
2530     }
2531     switch (comp_alg) {
2532     case TLSEXT_comp_cert_zlib:
2533         method = COMP_zlib_oneshot();
2534         break;
2535     case TLSEXT_comp_cert_brotli:
2536         method = COMP_brotli_oneshot();
2537         break;
2538     case TLSEXT_comp_cert_zstd:
2539         method = COMP_zstd_oneshot();
2540         break;
2541     default:
2542         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2543         goto err;
2544     }
2545
2546     if ((comp = COMP_CTX_new(method)) == NULL
2547         || !PACKET_get_net_3_len(pkt, &expected_length)
2548         || !PACKET_get_net_3_len(pkt, &comp_length)
2549         || PACKET_remaining(pkt) != comp_length
2550         || !BUF_MEM_grow(buf, expected_length)
2551         || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
2552         || COMP_expand_block(comp, (unsigned char *)buf->data, expected_length,
2553                              (unsigned char*)PACKET_data(pkt), comp_length) != (int)expected_length) {
2554         SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2555         goto err;
2556     }
2557     ret = MSG_PROCESS_CONTINUE_PROCESSING;
2558  err:
2559     COMP_CTX_free(comp);
2560     return ret;
2561 }
2562 #endif