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