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