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