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