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