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