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