Validate legacy_version
[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             CRYPTO_atomic_add(&s->session_ctx->stats.sess_accept, 1, &i,
136                               s->session_ctx->lock);
137         } else {
138             /* N.B. s->ctx may not equal s->session_ctx */
139             CRYPTO_atomic_add(&s->ctx->stats.sess_accept_renegotiate, 1, &i,
140                               s->ctx->lock);
141
142             s->s3->tmp.cert_request = 0;
143         }
144     } else {
145         int discard;
146         if (SSL_IS_FIRST_HANDSHAKE(s))
147             CRYPTO_atomic_add(&s->session_ctx->stats.sess_connect, 1, &discard,
148                               s->session_ctx->lock);
149         else
150             CRYPTO_atomic_add(&s->session_ctx->stats.sess_connect_renegotiate,
151                               1, &discard, s->session_ctx->lock);
152
153         /* mark client_random uninitialized */
154         memset(s->s3->client_random, 0, sizeof(s->s3->client_random));
155         s->hit = 0;
156
157         s->s3->tmp.cert_req = 0;
158
159         if (SSL_IS_DTLS(s))
160             s->statem.use_timer = 1;
161     }
162
163     return 1;
164 }
165
166 /*
167  * Size of the to-be-signed TLS13 data, without the hash size itself:
168  * 64 bytes of value 32, 33 context bytes, 1 byte separator
169  */
170 #define TLS13_TBS_START_SIZE            64
171 #define TLS13_TBS_PREAMBLE_SIZE         (TLS13_TBS_START_SIZE + 33 + 1)
172
173 static int get_cert_verify_tbs_data(SSL *s, unsigned char *tls13tbs,
174                                     void **hdata, size_t *hdatalen)
175 {
176     static const char *servercontext = "TLS 1.3, server CertificateVerify";
177     static const char *clientcontext = "TLS 1.3, client CertificateVerify";
178
179     if (SSL_IS_TLS13(s)) {
180         size_t hashlen;
181
182         /* Set the first 64 bytes of to-be-signed data to octet 32 */
183         memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
184         /* This copies the 33 bytes of context plus the 0 separator byte */
185         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
186                  || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
187             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
188         else
189             strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
190
191         /*
192          * If we're currently reading then we need to use the saved handshake
193          * hash value. We can't use the current handshake hash state because
194          * that includes the CertVerify itself.
195          */
196         if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
197                 || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
198             memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
199                    s->cert_verify_hash_len);
200             hashlen = s->cert_verify_hash_len;
201         } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
202                                        EVP_MAX_MD_SIZE, &hashlen)) {
203             /* SSLfatal() already called */
204             return 0;
205         }
206
207         *hdata = tls13tbs;
208         *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
209     } else {
210         size_t retlen;
211
212         retlen = BIO_get_mem_data(s->s3->handshake_buffer, hdata);
213         if (retlen <= 0) {
214             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_GET_CERT_VERIFY_TBS_DATA,
215                      ERR_R_INTERNAL_ERROR);
216             return 0;
217         }
218         *hdatalen = retlen;
219     }
220
221     return 1;
222 }
223
224 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
225 {
226     EVP_PKEY *pkey = NULL;
227     const EVP_MD *md = NULL;
228     EVP_MD_CTX *mctx = NULL;
229     EVP_PKEY_CTX *pctx = NULL;
230     size_t hdatalen = 0, siglen = 0;
231     void *hdata;
232     unsigned char *sig = NULL;
233     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
234     const SIGALG_LOOKUP *lu = s->s3->tmp.sigalg;
235
236     if (lu == NULL || s->s3->tmp.cert == NULL) {
237         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
238                  ERR_R_INTERNAL_ERROR);
239         goto err;
240     }
241     pkey = s->s3->tmp.cert->privatekey;
242
243     if (pkey == NULL || !tls1_lookup_md(lu, &md)) {
244         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
245                  ERR_R_INTERNAL_ERROR);
246         goto err;
247     }
248
249     mctx = EVP_MD_CTX_new();
250     if (mctx == NULL) {
251         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
252                  ERR_R_MALLOC_FAILURE);
253         goto err;
254     }
255
256     /* Get the data to be signed */
257     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
258         /* SSLfatal() already called */
259         goto err;
260     }
261
262     if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
263         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
264                  ERR_R_INTERNAL_ERROR);
265         goto err;
266     }
267     siglen = EVP_PKEY_size(pkey);
268     sig = OPENSSL_malloc(siglen);
269     if (sig == NULL) {
270         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
271                  ERR_R_MALLOC_FAILURE);
272         goto err;
273     }
274
275     if (EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey) <= 0) {
276         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
277                  ERR_R_EVP_LIB);
278         goto err;
279     }
280
281     if (lu->sig == EVP_PKEY_RSA_PSS) {
282         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
283             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
284                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
285             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
286                      ERR_R_EVP_LIB);
287             goto err;
288         }
289     }
290     if (s->version == SSL3_VERSION) {
291         if (EVP_DigestSignUpdate(mctx, hdata, hdatalen) <= 0
292             || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
293                                 (int)s->session->master_key_length,
294                                 s->session->master_key)
295             || EVP_DigestSignFinal(mctx, sig, &siglen) <= 0) {
296
297             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
298                      ERR_R_EVP_LIB);
299             goto err;
300         }
301     } else if (EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
302         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
303                  ERR_R_EVP_LIB);
304         goto err;
305     }
306
307 #ifndef OPENSSL_NO_GOST
308     {
309         int pktype = lu->sig;
310
311         if (pktype == NID_id_GostR3410_2001
312             || pktype == NID_id_GostR3410_2012_256
313             || pktype == NID_id_GostR3410_2012_512)
314             BUF_reverse(sig, NULL, siglen);
315     }
316 #endif
317
318     if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
319         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_VERIFY,
320                  ERR_R_INTERNAL_ERROR);
321         goto err;
322     }
323
324     /* Digest cached records and discard handshake buffer */
325     if (!ssl3_digest_cached_records(s, 0)) {
326         /* SSLfatal() already called */
327         goto err;
328     }
329
330     OPENSSL_free(sig);
331     EVP_MD_CTX_free(mctx);
332     return 1;
333  err:
334     OPENSSL_free(sig);
335     EVP_MD_CTX_free(mctx);
336     return 0;
337 }
338
339 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
340 {
341     EVP_PKEY *pkey = NULL;
342     const unsigned char *data;
343 #ifndef OPENSSL_NO_GOST
344     unsigned char *gost_data = NULL;
345 #endif
346     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
347     int j;
348     unsigned int len;
349     X509 *peer;
350     const EVP_MD *md = NULL;
351     size_t hdatalen = 0;
352     void *hdata;
353     unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
354     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
355     EVP_PKEY_CTX *pctx = NULL;
356
357     if (mctx == NULL) {
358         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
359                  ERR_R_MALLOC_FAILURE);
360         goto err;
361     }
362
363     peer = s->session->peer;
364     pkey = X509_get0_pubkey(peer);
365     if (pkey == NULL) {
366         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
367                  ERR_R_INTERNAL_ERROR);
368         goto err;
369     }
370
371     if (ssl_cert_lookup_by_pkey(pkey, NULL) == NULL) {
372         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CERT_VERIFY,
373                  SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
374         goto err;
375     }
376
377     if (SSL_USE_SIGALGS(s)) {
378         unsigned int sigalg;
379
380         if (!PACKET_get_net_2(pkt, &sigalg)) {
381             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
382                      SSL_R_BAD_PACKET);
383             goto err;
384         }
385         if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
386             /* SSLfatal() already called */
387             goto err;
388         }
389 #ifdef SSL_DEBUG
390         fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
391 #endif
392     } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
393             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
394                      ERR_R_INTERNAL_ERROR);
395             goto err;
396     }
397
398     if (!tls1_lookup_md(s->s3->tmp.peer_sigalg, &md)) {
399         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
400                  ERR_R_INTERNAL_ERROR);
401         goto err;
402     }
403
404     /* Check for broken implementations of GOST ciphersuites */
405     /*
406      * If key is GOST and len is exactly 64 or 128, it is signature without
407      * length field (CryptoPro implementations at least till TLS 1.2)
408      */
409 #ifndef OPENSSL_NO_GOST
410     if (!SSL_USE_SIGALGS(s)
411         && ((PACKET_remaining(pkt) == 64
412              && (EVP_PKEY_id(pkey) == NID_id_GostR3410_2001
413                  || EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_256))
414             || (PACKET_remaining(pkt) == 128
415                 && EVP_PKEY_id(pkey) == NID_id_GostR3410_2012_512))) {
416         len = PACKET_remaining(pkt);
417     } else
418 #endif
419     if (!PACKET_get_net_2(pkt, &len)) {
420         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
421                  SSL_R_LENGTH_MISMATCH);
422         goto err;
423     }
424
425     j = EVP_PKEY_size(pkey);
426     if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
427         || (PACKET_remaining(pkt) == 0)) {
428         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
429                  SSL_R_WRONG_SIGNATURE_SIZE);
430         goto err;
431     }
432     if (!PACKET_get_bytes(pkt, &data, len)) {
433         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
434                  SSL_R_LENGTH_MISMATCH);
435         goto err;
436     }
437
438     if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
439         /* SSLfatal() already called */
440         goto err;
441     }
442
443 #ifdef SSL_DEBUG
444     fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
445 #endif
446     if (EVP_DigestVerifyInit(mctx, &pctx, md, NULL, pkey) <= 0) {
447         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
448                  ERR_R_EVP_LIB);
449         goto err;
450     }
451 #ifndef OPENSSL_NO_GOST
452     {
453         int pktype = EVP_PKEY_id(pkey);
454         if (pktype == NID_id_GostR3410_2001
455             || pktype == NID_id_GostR3410_2012_256
456             || pktype == NID_id_GostR3410_2012_512) {
457             if ((gost_data = OPENSSL_malloc(len)) == NULL) {
458                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
459                          SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
460                 goto err;
461             }
462             BUF_reverse(gost_data, data, len);
463             data = gost_data;
464         }
465     }
466 #endif
467
468     if (SSL_USE_PSS(s)) {
469         if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
470             || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
471                                                 RSA_PSS_SALTLEN_DIGEST) <= 0) {
472             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
473                      ERR_R_EVP_LIB);
474             goto err;
475         }
476     }
477     if (s->version == SSL3_VERSION) {
478         if (EVP_DigestVerifyUpdate(mctx, hdata, hdatalen) <= 0
479                 || !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
480                                     (int)s->session->master_key_length,
481                                     s->session->master_key)) {
482             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
483                      ERR_R_EVP_LIB);
484             goto err;
485         }
486         if (EVP_DigestVerifyFinal(mctx, data, len) <= 0) {
487             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
488                      SSL_R_BAD_SIGNATURE);
489             goto err;
490         }
491     } else {
492         j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
493         if (j <= 0) {
494             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CERT_VERIFY,
495                      SSL_R_BAD_SIGNATURE);
496             goto err;
497         }
498     }
499
500     ret = MSG_PROCESS_CONTINUE_READING;
501  err:
502     BIO_free(s->s3->handshake_buffer);
503     s->s3->handshake_buffer = NULL;
504     EVP_MD_CTX_free(mctx);
505 #ifndef OPENSSL_NO_GOST
506     OPENSSL_free(gost_data);
507 #endif
508     return ret;
509 }
510
511 int tls_construct_finished(SSL *s, WPACKET *pkt)
512 {
513     size_t finish_md_len;
514     const char *sender;
515     size_t slen;
516
517     /* This is a real handshake so make sure we clean it up at the end */
518     if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
519         s->statem.cleanuphand = 1;
520
521     /*
522      * We only change the keys if we didn't already do this when we sent the
523      * client certificate
524      */
525     if (SSL_IS_TLS13(s)
526             && !s->server
527             && s->s3->tmp.cert_req == 0
528             && (!s->method->ssl3_enc->change_cipher_state(s,
529                     SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {;
530         /* SSLfatal() already called */
531         return 0;
532     }
533
534     if (s->server) {
535         sender = s->method->ssl3_enc->server_finished_label;
536         slen = s->method->ssl3_enc->server_finished_label_len;
537     } else {
538         sender = s->method->ssl3_enc->client_finished_label;
539         slen = s->method->ssl3_enc->client_finished_label_len;
540     }
541
542     finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
543                                                           sender, slen,
544                                                           s->s3->tmp.finish_md);
545     if (finish_md_len == 0) {
546         /* SSLfatal() already called */
547         return 0;
548     }
549
550     s->s3->tmp.finish_md_len = finish_md_len;
551
552     if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
553         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
554                  ERR_R_INTERNAL_ERROR);
555         return 0;
556     }
557
558     /*
559      * Log the master secret, if logging is enabled. We don't log it for
560      * TLSv1.3: there's a different key schedule for that.
561      */
562     if (!SSL_IS_TLS13(s) && !ssl_log_secret(s, MASTER_SECRET_LABEL,
563                                             s->session->master_key,
564                                             s->session->master_key_length)) {
565         /* SSLfatal() already called */
566         return 0;
567     }
568
569     /*
570      * Copy the finished so we can use it for renegotiation checks
571      */
572     if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
573         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_FINISHED,
574                  ERR_R_INTERNAL_ERROR);
575         return 0;
576     }
577     if (!s->server) {
578         memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
579                finish_md_len);
580         s->s3->previous_client_finished_len = finish_md_len;
581     } else {
582         memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
583                finish_md_len);
584         s->s3->previous_server_finished_len = finish_md_len;
585     }
586
587     return 1;
588 }
589
590 int tls_construct_key_update(SSL *s, WPACKET *pkt)
591 {
592     if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
593         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_KEY_UPDATE,
594                  ERR_R_INTERNAL_ERROR);
595         return 0;
596     }
597
598     s->key_update = SSL_KEY_UPDATE_NONE;
599     return 1;
600 }
601
602 MSG_PROCESS_RETURN tls_process_key_update(SSL *s, PACKET *pkt)
603 {
604     unsigned int updatetype;
605
606     s->key_update_count++;
607     if (s->key_update_count > MAX_KEY_UPDATE_MESSAGES) {
608         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_KEY_UPDATE,
609                  SSL_R_TOO_MANY_KEY_UPDATES);
610         return MSG_PROCESS_ERROR;
611     }
612
613     /*
614      * A KeyUpdate message signals a key change so the end of the message must
615      * be on a record boundary.
616      */
617     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
618         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_KEY_UPDATE,
619                  SSL_R_NOT_ON_RECORD_BOUNDARY);
620         return MSG_PROCESS_ERROR;
621     }
622
623     if (!PACKET_get_1(pkt, &updatetype)
624             || PACKET_remaining(pkt) != 0) {
625         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_KEY_UPDATE,
626                  SSL_R_BAD_KEY_UPDATE);
627         return MSG_PROCESS_ERROR;
628     }
629
630     /*
631      * There are only two defined key update types. Fail if we get a value we
632      * didn't recognise.
633      */
634     if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
635             && updatetype != SSL_KEY_UPDATE_REQUESTED) {
636         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_KEY_UPDATE,
637                  SSL_R_BAD_KEY_UPDATE);
638         return MSG_PROCESS_ERROR;
639     }
640
641     /*
642      * If we get a request for us to update our sending keys too then, we need
643      * to additionally send a KeyUpdate message. However that message should
644      * not also request an update (otherwise we get into an infinite loop).
645      */
646     if (updatetype == SSL_KEY_UPDATE_REQUESTED)
647         s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
648
649     if (!tls13_update_key(s, 0)) {
650         /* SSLfatal() already called */
651         return MSG_PROCESS_ERROR;
652     }
653
654     return MSG_PROCESS_FINISHED_READING;
655 }
656
657 /*
658  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
659  * to far.
660  */
661 int ssl3_take_mac(SSL *s)
662 {
663     const char *sender;
664     size_t slen;
665
666     if (!s->server) {
667         sender = s->method->ssl3_enc->server_finished_label;
668         slen = s->method->ssl3_enc->server_finished_label_len;
669     } else {
670         sender = s->method->ssl3_enc->client_finished_label;
671         slen = s->method->ssl3_enc->client_finished_label_len;
672     }
673
674     s->s3->tmp.peer_finish_md_len =
675         s->method->ssl3_enc->final_finish_mac(s, sender, slen,
676                                               s->s3->tmp.peer_finish_md);
677
678     if (s->s3->tmp.peer_finish_md_len == 0) {
679         /* SSLfatal() already called */
680         return 0;
681     }
682
683     return 1;
684 }
685
686 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
687 {
688     size_t remain;
689
690     remain = PACKET_remaining(pkt);
691     /*
692      * 'Change Cipher Spec' is just a single byte, which should already have
693      * been consumed by ssl_get_message() so there should be no bytes left,
694      * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
695      */
696     if (SSL_IS_DTLS(s)) {
697         if ((s->version == DTLS1_BAD_VER
698              && remain != DTLS1_CCS_HEADER_LENGTH + 1)
699             || (s->version != DTLS1_BAD_VER
700                 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
701             SSLfatal(s, SSL_AD_DECODE_ERROR,
702                      SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
703                     SSL_R_BAD_CHANGE_CIPHER_SPEC);
704             return MSG_PROCESS_ERROR;
705         }
706     } else {
707         if (remain != 0) {
708             SSLfatal(s, SSL_AD_DECODE_ERROR,
709                      SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
710                      SSL_R_BAD_CHANGE_CIPHER_SPEC);
711             return MSG_PROCESS_ERROR;
712         }
713     }
714
715     /* Check we have a cipher to change to */
716     if (s->s3->tmp.new_cipher == NULL) {
717         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
718                  SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
719         return MSG_PROCESS_ERROR;
720     }
721
722     s->s3->change_cipher_spec = 1;
723     if (!ssl3_do_change_cipher_spec(s)) {
724         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
725                  ERR_R_INTERNAL_ERROR);
726         return MSG_PROCESS_ERROR;
727     }
728
729     if (SSL_IS_DTLS(s)) {
730         dtls1_reset_seq_numbers(s, SSL3_CC_READ);
731
732         if (s->version == DTLS1_BAD_VER)
733             s->d1->handshake_read_seq++;
734
735 #ifndef OPENSSL_NO_SCTP
736         /*
737          * Remember that a CCS has been received, so that an old key of
738          * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
739          * SCTP is used
740          */
741         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
742 #endif
743     }
744
745     return MSG_PROCESS_CONTINUE_READING;
746 }
747
748 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
749 {
750     size_t md_len;
751
752
753     /* This is a real handshake so make sure we clean it up at the end */
754     if (s->server) {
755         if (s->post_handshake_auth != SSL_PHA_REQUESTED)
756             s->statem.cleanuphand = 1;
757         if (SSL_IS_TLS13(s) && !tls13_save_handshake_digest_for_pha(s)) {
758                 /* SSLfatal() already called */
759                 return MSG_PROCESS_ERROR;
760         }
761     }
762
763     /*
764      * In TLSv1.3 a Finished message signals a key change so the end of the
765      * message must be on a record boundary.
766      */
767     if (SSL_IS_TLS13(s) && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
768         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
769                  SSL_R_NOT_ON_RECORD_BOUNDARY);
770         return MSG_PROCESS_ERROR;
771     }
772
773     /* If this occurs, we have missed a message */
774     if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
775         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_TLS_PROCESS_FINISHED,
776                  SSL_R_GOT_A_FIN_BEFORE_A_CCS);
777         return MSG_PROCESS_ERROR;
778     }
779     s->s3->change_cipher_spec = 0;
780
781     md_len = s->s3->tmp.peer_finish_md_len;
782
783     if (md_len != PACKET_remaining(pkt)) {
784         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_FINISHED,
785                  SSL_R_BAD_DIGEST_LENGTH);
786         return MSG_PROCESS_ERROR;
787     }
788
789     if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
790                       md_len) != 0) {
791         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_FINISHED,
792                  SSL_R_DIGEST_CHECK_FAILED);
793         return MSG_PROCESS_ERROR;
794     }
795
796     /*
797      * Copy the finished so we can use it for renegotiation checks
798      */
799     if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
800         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_FINISHED,
801                  ERR_R_INTERNAL_ERROR);
802         return MSG_PROCESS_ERROR;
803     }
804     if (s->server) {
805         memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
806                md_len);
807         s->s3->previous_client_finished_len = md_len;
808     } else {
809         memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
810                md_len);
811         s->s3->previous_server_finished_len = md_len;
812     }
813
814     /*
815      * In TLS1.3 we also have to change cipher state and do any final processing
816      * of the initial server flight (if we are a client)
817      */
818     if (SSL_IS_TLS13(s)) {
819         if (s->server) {
820             if (s->post_handshake_auth != SSL_PHA_REQUESTED &&
821                     !s->method->ssl3_enc->change_cipher_state(s,
822                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
823                 /* SSLfatal() already called */
824                 return MSG_PROCESS_ERROR;
825             }
826         } else {
827             if (!s->method->ssl3_enc->generate_master_secret(s,
828                     s->master_secret, s->handshake_secret, 0,
829                     &s->session->master_key_length)) {
830                 /* SSLfatal() already called */
831                 return MSG_PROCESS_ERROR;
832             }
833             if (!s->method->ssl3_enc->change_cipher_state(s,
834                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
835                 /* SSLfatal() already called */
836                 return MSG_PROCESS_ERROR;
837             }
838             if (!tls_process_initial_server_flight(s)) {
839                 /* SSLfatal() already called */
840                 return MSG_PROCESS_ERROR;
841             }
842         }
843     }
844
845     return MSG_PROCESS_FINISHED_READING;
846 }
847
848 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
849 {
850     if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
851         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
852                  SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
853         return 0;
854     }
855
856     return 1;
857 }
858
859 /* Add a certificate to the WPACKET */
860 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain)
861 {
862     int len;
863     unsigned char *outbytes;
864
865     len = i2d_X509(x, NULL);
866     if (len < 0) {
867         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
868                  ERR_R_BUF_LIB);
869         return 0;
870     }
871     if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
872             || i2d_X509(x, &outbytes) != len) {
873         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_TO_WPACKET,
874                  ERR_R_INTERNAL_ERROR);
875         return 0;
876     }
877
878     if (SSL_IS_TLS13(s)
879             && !tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_CERTIFICATE, x,
880                                          chain)) {
881         /* SSLfatal() already called */
882         return 0;
883     }
884
885     return 1;
886 }
887
888 /* Add certificate chain to provided WPACKET */
889 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
890 {
891     int i, chain_count;
892     X509 *x;
893     STACK_OF(X509) *extra_certs;
894     STACK_OF(X509) *chain = NULL;
895     X509_STORE *chain_store;
896
897     if (cpk == NULL || cpk->x509 == NULL)
898         return 1;
899
900     x = cpk->x509;
901
902     /*
903      * If we have a certificate specific chain use it, else use parent ctx.
904      */
905     if (cpk->chain != NULL)
906         extra_certs = cpk->chain;
907     else
908         extra_certs = s->ctx->extra_certs;
909
910     if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
911         chain_store = NULL;
912     else if (s->cert->chain_store)
913         chain_store = s->cert->chain_store;
914     else
915         chain_store = s->ctx->cert_store;
916
917     if (chain_store != NULL) {
918         X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
919
920         if (xs_ctx == NULL) {
921             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
922                      ERR_R_MALLOC_FAILURE);
923             return 0;
924         }
925         if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
926             X509_STORE_CTX_free(xs_ctx);
927             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN,
928                      ERR_R_X509_LIB);
929             return 0;
930         }
931         /*
932          * It is valid for the chain not to be complete (because normally we
933          * don't include the root cert in the chain). Therefore we deliberately
934          * ignore the error return from this call. We're not actually verifying
935          * the cert - we're just building as much of the chain as we can
936          */
937         (void)X509_verify_cert(xs_ctx);
938         /* Don't leave errors in the queue */
939         ERR_clear_error();
940         chain = X509_STORE_CTX_get0_chain(xs_ctx);
941         i = ssl_security_cert_chain(s, chain, NULL, 0);
942         if (i != 1) {
943 #if 0
944             /* Dummy error calls so mkerr generates them */
945             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
946             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
947             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
948 #endif
949             X509_STORE_CTX_free(xs_ctx);
950             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
951             return 0;
952         }
953         chain_count = sk_X509_num(chain);
954         for (i = 0; i < chain_count; i++) {
955             x = sk_X509_value(chain, i);
956
957             if (!ssl_add_cert_to_wpacket(s, pkt, x, i)) {
958                 /* SSLfatal() already called */
959                 X509_STORE_CTX_free(xs_ctx);
960                 return 0;
961             }
962         }
963         X509_STORE_CTX_free(xs_ctx);
964     } else {
965         i = ssl_security_cert_chain(s, extra_certs, x, 0);
966         if (i != 1) {
967             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_ADD_CERT_CHAIN, i);
968             return 0;
969         }
970         if (!ssl_add_cert_to_wpacket(s, pkt, x, 0)) {
971             /* SSLfatal() already called */
972             return 0;
973         }
974         for (i = 0; i < sk_X509_num(extra_certs); i++) {
975             x = sk_X509_value(extra_certs, i);
976             if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1)) {
977                 /* SSLfatal() already called */
978                 return 0;
979             }
980         }
981     }
982     return 1;
983 }
984
985 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk)
986 {
987     if (!WPACKET_start_sub_packet_u24(pkt)) {
988         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
989                  ERR_R_INTERNAL_ERROR);
990         return 0;
991     }
992
993     if (!ssl_add_cert_chain(s, pkt, cpk))
994         return 0;
995
996     if (!WPACKET_close(pkt)) {
997         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_OUTPUT_CERT_CHAIN,
998                  ERR_R_INTERNAL_ERROR);
999         return 0;
1000     }
1001
1002     return 1;
1003 }
1004
1005 /*
1006  * Tidy up after the end of a handshake. In the case of SCTP this may result
1007  * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1008  * freed up as well.
1009  */
1010 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst, int clearbufs, int stop)
1011 {
1012     int discard;
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             CRYPTO_atomic_add(&s->ctx->stats.sess_accept_good, 1, &discard,
1059                               s->ctx->lock);
1060             s->handshake_func = ossl_statem_accept;
1061
1062             if (SSL_IS_DTLS(s) && !s->hit) {
1063                 /*
1064                  * We are finishing after the client. We start the timer going
1065                  * in case there are any retransmits of our final flight
1066                  * required.
1067                  */
1068                 dtls1_start_timer(s);
1069             }
1070         } else {
1071             if (SSL_IS_TLS13(s)) {
1072                 /*
1073                  * We encourage applications to only use TLSv1.3 tickets once,
1074                  * so we remove this one from the cache.
1075                  */
1076                 if ((s->session_ctx->session_cache_mode
1077                      & SSL_SESS_CACHE_CLIENT) != 0)
1078                     SSL_CTX_remove_session(s->session_ctx, s->session);
1079             } else {
1080                 /*
1081                  * In TLSv1.3 we update the cache as part of processing the
1082                  * NewSessionTicket
1083                  */
1084                 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1085             }
1086             if (s->hit)
1087                 CRYPTO_atomic_add(&s->session_ctx->stats.sess_hit, 1, &discard,
1088                                   s->session_ctx->lock);
1089
1090             s->handshake_func = ossl_statem_connect;
1091             CRYPTO_atomic_add(&s->session_ctx->stats.sess_connect_good, 1,
1092                               &discard, s->session_ctx->lock);
1093
1094             if (SSL_IS_DTLS(s) && s->hit) {
1095                 /*
1096                  * We are finishing after the server. We start the timer going
1097                  * in case there are any retransmits of our final flight
1098                  * required.
1099                  */
1100                 dtls1_start_timer(s);
1101             }
1102         }
1103
1104         if (SSL_IS_DTLS(s)) {
1105             /* done with handshaking */
1106             s->d1->handshake_read_seq = 0;
1107             s->d1->handshake_write_seq = 0;
1108             s->d1->next_handshake_write_seq = 0;
1109             dtls1_clear_received_buffer(s);
1110         }
1111     }
1112
1113     if (s->info_callback != NULL)
1114         cb = s->info_callback;
1115     else if (s->ctx->info_callback != NULL)
1116         cb = s->ctx->info_callback;
1117
1118     /* The callback may expect us to not be in init at handshake done */
1119     ossl_statem_set_in_init(s, 0);
1120
1121     if (cb != NULL)
1122         cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1123
1124     if (!stop) {
1125         /* If we've got more work to do we go back into init */
1126         ossl_statem_set_in_init(s, 1);
1127         return WORK_FINISHED_CONTINUE;
1128     }
1129
1130     return WORK_FINISHED_STOP;
1131 }
1132
1133 int tls_get_message_header(SSL *s, int *mt)
1134 {
1135     /* s->init_num < SSL3_HM_HEADER_LENGTH */
1136     int skip_message, i, recvd_type;
1137     unsigned char *p;
1138     size_t l, readbytes;
1139
1140     p = (unsigned char *)s->init_buf->data;
1141
1142     do {
1143         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1144             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1145                                           &p[s->init_num],
1146                                           SSL3_HM_HEADER_LENGTH - s->init_num,
1147                                           0, &readbytes);
1148             if (i <= 0) {
1149                 s->rwstate = SSL_READING;
1150                 return 0;
1151             }
1152             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1153                 /*
1154                  * A ChangeCipherSpec must be a single byte and may not occur
1155                  * in the middle of a handshake message.
1156                  */
1157                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1158                     SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1159                              SSL_F_TLS_GET_MESSAGE_HEADER,
1160                              SSL_R_BAD_CHANGE_CIPHER_SPEC);
1161                     return 0;
1162                 }
1163                 if (s->statem.hand_state == TLS_ST_BEFORE
1164                         && (s->s3->flags & TLS1_FLAGS_STATELESS) != 0) {
1165                     /*
1166                      * We are stateless and we received a CCS. Probably this is
1167                      * from a client between the first and second ClientHellos.
1168                      * We should ignore this, but return an error because we do
1169                      * not return success until we see the second ClientHello
1170                      * with a valid cookie.
1171                      */
1172                     return 0;
1173                 }
1174                 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1175                 s->init_num = readbytes - 1;
1176                 s->init_msg = s->init_buf->data;
1177                 s->s3->tmp.message_size = readbytes;
1178                 return 1;
1179             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1180                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1181                          SSL_F_TLS_GET_MESSAGE_HEADER,
1182                          SSL_R_CCS_RECEIVED_EARLY);
1183                 return 0;
1184             }
1185             s->init_num += readbytes;
1186         }
1187
1188         skip_message = 0;
1189         if (!s->server)
1190             if (s->statem.hand_state != TLS_ST_OK
1191                     && p[0] == SSL3_MT_HELLO_REQUEST)
1192                 /*
1193                  * The server may always send 'Hello Request' messages --
1194                  * we are doing a handshake anyway now, so ignore them if
1195                  * their format is correct. Does not count for 'Finished'
1196                  * MAC.
1197                  */
1198                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1199                     s->init_num = 0;
1200                     skip_message = 1;
1201
1202                     if (s->msg_callback)
1203                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1204                                         p, SSL3_HM_HEADER_LENGTH, s,
1205                                         s->msg_callback_arg);
1206                 }
1207     } while (skip_message);
1208     /* s->init_num == SSL3_HM_HEADER_LENGTH */
1209
1210     *mt = *p;
1211     s->s3->tmp.message_type = *(p++);
1212
1213     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1214         /*
1215          * Only happens with SSLv3+ in an SSLv2 backward compatible
1216          * ClientHello
1217          *
1218          * Total message size is the remaining record bytes to read
1219          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1220          */
1221         l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1222             + SSL3_HM_HEADER_LENGTH;
1223         s->s3->tmp.message_size = l;
1224
1225         s->init_msg = s->init_buf->data;
1226         s->init_num = SSL3_HM_HEADER_LENGTH;
1227     } else {
1228         n2l3(p, l);
1229         /* BUF_MEM_grow takes an 'int' parameter */
1230         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1231             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_GET_MESSAGE_HEADER,
1232                      SSL_R_EXCESSIVE_MESSAGE_SIZE);
1233             return 0;
1234         }
1235         s->s3->tmp.message_size = l;
1236
1237         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1238         s->init_num = 0;
1239     }
1240
1241     return 1;
1242 }
1243
1244 int tls_get_message_body(SSL *s, size_t *len)
1245 {
1246     size_t n, readbytes;
1247     unsigned char *p;
1248     int i;
1249
1250     if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1251         /* We've already read everything in */
1252         *len = (unsigned long)s->init_num;
1253         return 1;
1254     }
1255
1256     p = s->init_msg;
1257     n = s->s3->tmp.message_size - s->init_num;
1258     while (n > 0) {
1259         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1260                                       &p[s->init_num], n, 0, &readbytes);
1261         if (i <= 0) {
1262             s->rwstate = SSL_READING;
1263             *len = 0;
1264             return 0;
1265         }
1266         s->init_num += readbytes;
1267         n -= readbytes;
1268     }
1269
1270     /*
1271      * If receiving Finished, record MAC of prior handshake messages for
1272      * Finished verification.
1273      */
1274     if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1275         /* SSLfatal() already called */
1276         *len = 0;
1277         return 0;
1278     }
1279
1280     /* Feed this message into MAC computation. */
1281     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1282         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1283                              s->init_num)) {
1284             /* SSLfatal() already called */
1285             *len = 0;
1286             return 0;
1287         }
1288         if (s->msg_callback)
1289             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1290                             (size_t)s->init_num, s, s->msg_callback_arg);
1291     } else {
1292         /*
1293          * We defer feeding in the HRR until later. We'll do it as part of
1294          * processing the message
1295          * The TLsv1.3 handshake transcript stops at the ClientFinished
1296          * message.
1297          */
1298 #define SERVER_HELLO_RANDOM_OFFSET  (SSL3_HM_HEADER_LENGTH + 2)
1299         /* KeyUpdate and NewSessionTicket do not need to be added */
1300         if (!SSL_IS_TLS13(s) || (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1301                                  && s->s3->tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1302             if (s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO
1303                     || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1304                     || memcmp(hrrrandom,
1305                               s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1306                               SSL3_RANDOM_SIZE) != 0) {
1307                 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1308                                      s->init_num + SSL3_HM_HEADER_LENGTH)) {
1309                     /* SSLfatal() already called */
1310                     *len = 0;
1311                     return 0;
1312                 }
1313             }
1314         }
1315         if (s->msg_callback)
1316             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1317                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1318                             s->msg_callback_arg);
1319     }
1320
1321     *len = s->init_num;
1322     return 1;
1323 }
1324
1325 static const X509ERR2ALERT x509table[] = {
1326     {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1327     {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1328     {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1329     {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1330     {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1331     {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1332     {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1333     {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1334     {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1335     {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1336     {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1337     {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1338     {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1339     {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1340     {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1341     {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1342     {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1343     {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1344     {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1345     {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1346     {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1347     {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1348     {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1349     {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1350     {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1351     {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1352     {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1353     {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1354     {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1355     {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1356     {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1357     {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1358     {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1359     {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1360     {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1361     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1362     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1363     {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1364     {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1365
1366     /* Last entry; return this if we don't find the value above. */
1367     {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1368 };
1369
1370 int ssl_x509err2alert(int x509err)
1371 {
1372     const X509ERR2ALERT *tp;
1373
1374     for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1375         if (tp->x509err == x509err)
1376             break;
1377     return tp->alert;
1378 }
1379
1380 int ssl_allow_compression(SSL *s)
1381 {
1382     if (s->options & SSL_OP_NO_COMPRESSION)
1383         return 0;
1384     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1385 }
1386
1387 static int version_cmp(const SSL *s, int a, int b)
1388 {
1389     int dtls = SSL_IS_DTLS(s);
1390
1391     if (a == b)
1392         return 0;
1393     if (!dtls)
1394         return a < b ? -1 : 1;
1395     return DTLS_VERSION_LT(a, b) ? -1 : 1;
1396 }
1397
1398 typedef struct {
1399     int version;
1400     const SSL_METHOD *(*cmeth) (void);
1401     const SSL_METHOD *(*smeth) (void);
1402 } version_info;
1403
1404 #if TLS_MAX_VERSION != TLS1_3_VERSION
1405 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1406 #endif
1407
1408 /* Must be in order high to low */
1409 static const version_info tls_version_table[] = {
1410 #ifndef OPENSSL_NO_TLS1_3
1411     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1412 #else
1413     {TLS1_3_VERSION, NULL, NULL},
1414 #endif
1415 #ifndef OPENSSL_NO_TLS1_2
1416     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1417 #else
1418     {TLS1_2_VERSION, NULL, NULL},
1419 #endif
1420 #ifndef OPENSSL_NO_TLS1_1
1421     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1422 #else
1423     {TLS1_1_VERSION, NULL, NULL},
1424 #endif
1425 #ifndef OPENSSL_NO_TLS1
1426     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1427 #else
1428     {TLS1_VERSION, NULL, NULL},
1429 #endif
1430 #ifndef OPENSSL_NO_SSL3
1431     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1432 #else
1433     {SSL3_VERSION, NULL, NULL},
1434 #endif
1435     {0, NULL, NULL},
1436 };
1437
1438 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1439 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1440 #endif
1441
1442 /* Must be in order high to low */
1443 static const version_info dtls_version_table[] = {
1444 #ifndef OPENSSL_NO_DTLS1_2
1445     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1446 #else
1447     {DTLS1_2_VERSION, NULL, NULL},
1448 #endif
1449 #ifndef OPENSSL_NO_DTLS1
1450     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1451     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1452 #else
1453     {DTLS1_VERSION, NULL, NULL},
1454     {DTLS1_BAD_VER, NULL, NULL},
1455 #endif
1456     {0, NULL, NULL},
1457 };
1458
1459 /*
1460  * ssl_method_error - Check whether an SSL_METHOD is enabled.
1461  *
1462  * @s: The SSL handle for the candidate method
1463  * @method: the intended method.
1464  *
1465  * Returns 0 on success, or an SSL error reason on failure.
1466  */
1467 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1468 {
1469     int version = method->version;
1470
1471     if ((s->min_proto_version != 0 &&
1472          version_cmp(s, version, s->min_proto_version) < 0) ||
1473         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1474         return SSL_R_VERSION_TOO_LOW;
1475
1476     if (s->max_proto_version != 0 &&
1477         version_cmp(s, version, s->max_proto_version) > 0)
1478         return SSL_R_VERSION_TOO_HIGH;
1479
1480     if ((s->options & method->mask) != 0)
1481         return SSL_R_UNSUPPORTED_PROTOCOL;
1482     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1483         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1484
1485     return 0;
1486 }
1487
1488 /*
1489  * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1490  * certificate type, or has PSK configured. Otherwise returns 0.
1491  */
1492 static int is_tls13_capable(const SSL *s)
1493 {
1494     int i;
1495
1496 #ifndef OPENSSL_NO_PSK
1497     if (s->psk_server_callback != NULL)
1498         return 1;
1499 #endif
1500
1501     if (s->psk_find_session_cb != NULL)
1502         return 1;
1503
1504     for (i = 0; i < SSL_PKEY_NUM; i++) {
1505         /* Skip over certs disallowed for TLSv1.3 */
1506         switch (i) {
1507         case SSL_PKEY_DSA_SIGN:
1508         case SSL_PKEY_GOST01:
1509         case SSL_PKEY_GOST12_256:
1510         case SSL_PKEY_GOST12_512:
1511             continue;
1512         default:
1513             break;
1514         }
1515         if (ssl_has_cert(s, i))
1516             return 1;
1517     }
1518
1519     return 0;
1520 }
1521
1522 /*
1523  * ssl_version_supported - Check that the specified `version` is supported by
1524  * `SSL *` instance
1525  *
1526  * @s: The SSL handle for the candidate method
1527  * @version: Protocol version to test against
1528  *
1529  * Returns 1 when supported, otherwise 0
1530  */
1531 int ssl_version_supported(const SSL *s, int version, const SSL_METHOD **meth)
1532 {
1533     const version_info *vent;
1534     const version_info *table;
1535
1536     switch (s->method->version) {
1537     default:
1538         /* Version should match method version for non-ANY method */
1539         return version_cmp(s, version, s->version) == 0;
1540     case TLS_ANY_VERSION:
1541         table = tls_version_table;
1542         break;
1543     case DTLS_ANY_VERSION:
1544         table = dtls_version_table;
1545         break;
1546     }
1547
1548     for (vent = table;
1549          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1550          ++vent) {
1551         if (vent->cmeth != NULL
1552                 && version_cmp(s, version, vent->version) == 0
1553                 && ssl_method_error(s, vent->cmeth()) == 0
1554                 && (!s->server
1555                     || version != TLS1_3_VERSION
1556                     || is_tls13_capable(s))) {
1557             if (meth != NULL)
1558                 *meth = vent->cmeth();
1559             return 1;
1560         }
1561     }
1562     return 0;
1563 }
1564
1565 /*
1566  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1567  * fallback indication from a client check whether we're using the highest
1568  * supported protocol version.
1569  *
1570  * @s server SSL handle.
1571  *
1572  * Returns 1 when using the highest enabled version, 0 otherwise.
1573  */
1574 int ssl_check_version_downgrade(SSL *s)
1575 {
1576     const version_info *vent;
1577     const version_info *table;
1578
1579     /*
1580      * Check that the current protocol is the highest enabled version
1581      * (according to s->ctx->method, as version negotiation may have changed
1582      * s->method).
1583      */
1584     if (s->version == s->ctx->method->version)
1585         return 1;
1586
1587     /*
1588      * Apparently we're using a version-flexible SSL_METHOD (not at its
1589      * highest protocol version).
1590      */
1591     if (s->ctx->method->version == TLS_method()->version)
1592         table = tls_version_table;
1593     else if (s->ctx->method->version == DTLS_method()->version)
1594         table = dtls_version_table;
1595     else {
1596         /* Unexpected state; fail closed. */
1597         return 0;
1598     }
1599
1600     for (vent = table; vent->version != 0; ++vent) {
1601         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1602             return s->version == vent->version;
1603     }
1604     return 0;
1605 }
1606
1607 /*
1608  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1609  * protocols, provided the initial (D)TLS method is version-flexible.  This
1610  * function sanity-checks the proposed value and makes sure the method is
1611  * version-flexible, then sets the limit if all is well.
1612  *
1613  * @method_version: The version of the current SSL_METHOD.
1614  * @version: the intended limit.
1615  * @bound: pointer to limit to be updated.
1616  *
1617  * Returns 1 on success, 0 on failure.
1618  */
1619 int ssl_set_version_bound(int method_version, int version, int *bound)
1620 {
1621     if (version == 0) {
1622         *bound = version;
1623         return 1;
1624     }
1625
1626     /*-
1627      * Restrict TLS methods to TLS protocol versions.
1628      * Restrict DTLS methods to DTLS protocol versions.
1629      * Note, DTLS version numbers are decreasing, use comparison macros.
1630      *
1631      * Note that for both lower-bounds we use explicit versions, not
1632      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
1633      * configurations.  If the MIN (supported) version ever rises, the user's
1634      * "floor" remains valid even if no longer available.  We don't expect the
1635      * MAX ceiling to ever get lower, so making that variable makes sense.
1636      */
1637     switch (method_version) {
1638     default:
1639         /*
1640          * XXX For fixed version methods, should we always fail and not set any
1641          * bounds, always succeed and not set any bounds, or set the bounds and
1642          * arrange to fail later if they are not met?  At present fixed-version
1643          * methods are not subject to controls that disable individual protocol
1644          * versions.
1645          */
1646         return 0;
1647
1648     case TLS_ANY_VERSION:
1649         if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1650             return 0;
1651         break;
1652
1653     case DTLS_ANY_VERSION:
1654         if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1655             DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1656             return 0;
1657         break;
1658     }
1659
1660     *bound = version;
1661     return 1;
1662 }
1663
1664 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1665 {
1666     if (vers == TLS1_2_VERSION
1667             && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
1668         *dgrd = DOWNGRADE_TO_1_2;
1669     } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1670             && (ssl_version_supported(s, TLS1_2_VERSION, NULL)
1671                 || ssl_version_supported(s, TLS1_3_VERSION, NULL))) {
1672         *dgrd = DOWNGRADE_TO_1_1;
1673     } else {
1674         *dgrd = DOWNGRADE_NONE;
1675     }
1676 }
1677
1678 /*
1679  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
1680  * client HELLO is received to select the final server protocol version and
1681  * the version specific method.
1682  *
1683  * @s: server SSL handle.
1684  *
1685  * Returns 0 on success or an SSL error reason number on failure.
1686  */
1687 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1688 {
1689     /*-
1690      * With version-flexible methods we have an initial state with:
1691      *
1692      *   s->method->version == (D)TLS_ANY_VERSION,
1693      *   s->version == (D)TLS_MAX_VERSION.
1694      *
1695      * So we detect version-flexible methods via the method version, not the
1696      * handle version.
1697      */
1698     int server_version = s->method->version;
1699     int client_version = hello->legacy_version;
1700     const version_info *vent;
1701     const version_info *table;
1702     int disabled = 0;
1703     RAW_EXTENSION *suppversions;
1704
1705     s->client_version = client_version;
1706
1707     switch (server_version) {
1708     default:
1709         if (!SSL_IS_TLS13(s)) {
1710             if (version_cmp(s, client_version, s->version) < 0)
1711                 return SSL_R_WRONG_SSL_VERSION;
1712             *dgrd = DOWNGRADE_NONE;
1713             /*
1714              * If this SSL handle is not from a version flexible method we don't
1715              * (and never did) check min/max FIPS or Suite B constraints.  Hope
1716              * that's OK.  It is up to the caller to not choose fixed protocol
1717              * versions they don't want.  If not, then easy to fix, just return
1718              * ssl_method_error(s, s->method)
1719              */
1720             return 0;
1721         }
1722         /*
1723          * Fall through if we are TLSv1.3 already (this means we must be after
1724          * a HelloRetryRequest
1725          */
1726         /* fall thru */
1727     case TLS_ANY_VERSION:
1728         table = tls_version_table;
1729         break;
1730     case DTLS_ANY_VERSION:
1731         table = dtls_version_table;
1732         break;
1733     }
1734
1735     suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1736
1737     /* If we did an HRR then supported versions is mandatory */
1738     if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1739         return SSL_R_UNSUPPORTED_PROTOCOL;
1740
1741     if (suppversions->present && !SSL_IS_DTLS(s)) {
1742         unsigned int candidate_vers = 0;
1743         unsigned int best_vers = 0;
1744         const SSL_METHOD *best_method = NULL;
1745         PACKET versionslist;
1746         /* TODO(TLS1.3): Remove this before release */
1747         unsigned int orig_candidate = 0;
1748
1749         suppversions->parsed = 1;
1750
1751         if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1752             /* Trailing or invalid data? */
1753             return SSL_R_LENGTH_MISMATCH;
1754         }
1755
1756         /*
1757          * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
1758          * The spec only requires servers to check that it isn't SSLv3:
1759          * "Any endpoint receiving a Hello message with
1760          * ClientHello.legacy_version or ServerHello.legacy_version set to
1761          * 0x0300 MUST abort the handshake with a "protocol_version" alert."
1762          * We are slightly stricter and require that it isn't SSLv3 or lower.
1763          * We tolerate TLSv1 and TLSv1.1.
1764          */
1765         if (client_version <= SSL3_VERSION)
1766             return SSL_R_BAD_LEGACY_VERSION;
1767
1768         while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1769             /* TODO(TLS1.3): Remove this before release */
1770             if (candidate_vers == TLS1_3_VERSION_DRAFT
1771                     || candidate_vers == TLS1_3_VERSION_DRAFT_27
1772                     || candidate_vers == TLS1_3_VERSION_DRAFT_26) {
1773                 if (best_vers == TLS1_3_VERSION
1774                         && orig_candidate > candidate_vers)
1775                     continue;
1776                 orig_candidate = candidate_vers;
1777                 candidate_vers = TLS1_3_VERSION;
1778             } else if (candidate_vers == TLS1_3_VERSION) {
1779                 /* Don't actually accept real TLSv1.3 */
1780                 continue;
1781             }
1782             /*
1783              * TODO(TLS1.3): There is some discussion on the TLS list about
1784              * whether to ignore versions <TLS1.2 in supported_versions. At the
1785              * moment we honour them if present. To be reviewed later
1786              */
1787             if (version_cmp(s, candidate_vers, best_vers) <= 0)
1788                 continue;
1789             if (ssl_version_supported(s, candidate_vers, &best_method))
1790                 best_vers = candidate_vers;
1791         }
1792         if (PACKET_remaining(&versionslist) != 0) {
1793             /* Trailing data? */
1794             return SSL_R_LENGTH_MISMATCH;
1795         }
1796
1797         if (best_vers > 0) {
1798             if (s->hello_retry_request != SSL_HRR_NONE) {
1799                 /*
1800                  * This is after a HelloRetryRequest so we better check that we
1801                  * negotiated TLSv1.3
1802                  */
1803                 if (best_vers != TLS1_3_VERSION)
1804                     return SSL_R_UNSUPPORTED_PROTOCOL;
1805                 return 0;
1806             }
1807             check_for_downgrade(s, best_vers, dgrd);
1808             s->version = best_vers;
1809             /* TODO(TLS1.3): Remove this before release */
1810             if (best_vers == TLS1_3_VERSION)
1811                 s->version_draft = orig_candidate;
1812             s->method = best_method;
1813             return 0;
1814         }
1815         return SSL_R_UNSUPPORTED_PROTOCOL;
1816     }
1817
1818     /*
1819      * If the supported versions extension isn't present, then the highest
1820      * version we can negotiate is TLSv1.2
1821      */
1822     if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1823         client_version = TLS1_2_VERSION;
1824
1825     /*
1826      * No supported versions extension, so we just use the version supplied in
1827      * the ClientHello.
1828      */
1829     for (vent = table; vent->version != 0; ++vent) {
1830         const SSL_METHOD *method;
1831
1832         if (vent->smeth == NULL ||
1833             version_cmp(s, client_version, vent->version) < 0)
1834             continue;
1835         method = vent->smeth();
1836         if (ssl_method_error(s, method) == 0) {
1837             check_for_downgrade(s, vent->version, dgrd);
1838             s->version = vent->version;
1839             s->method = method;
1840             return 0;
1841         }
1842         disabled = 1;
1843     }
1844     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1845 }
1846
1847 /*
1848  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
1849  * server HELLO is received to select the final client protocol version and
1850  * the version specific method.
1851  *
1852  * @s: client SSL handle.
1853  * @version: The proposed version from the server's HELLO.
1854  * @extensions: The extensions received
1855  *
1856  * Returns 1 on success or 0 on error.
1857  */
1858 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1859 {
1860     const version_info *vent;
1861     const version_info *table;
1862     int highver = 0;
1863     int origv;
1864
1865     origv = s->version;
1866     s->version = version;
1867
1868     /* This will overwrite s->version if the extension is present */
1869     if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1870                              SSL_EXT_TLS1_2_SERVER_HELLO
1871                              | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1872                              NULL, 0)) {
1873         s->version = origv;
1874         return 0;
1875     }
1876
1877     if (s->hello_retry_request != SSL_HRR_NONE
1878             && s->version != TLS1_3_VERSION) {
1879         s->version = origv;
1880         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1881                  SSL_R_WRONG_SSL_VERSION);
1882         return 0;
1883     }
1884
1885     switch (s->method->version) {
1886     default:
1887         if (s->version != s->method->version) {
1888             s->version = origv;
1889             SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1890                      SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1891                      SSL_R_WRONG_SSL_VERSION);
1892             return 0;
1893         }
1894         /*
1895          * If this SSL handle is not from a version flexible method we don't
1896          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
1897          * that's OK.  It is up to the caller to not choose fixed protocol
1898          * versions they don't want.  If not, then easy to fix, just return
1899          * ssl_method_error(s, s->method)
1900          */
1901         return 1;
1902     case TLS_ANY_VERSION:
1903         table = tls_version_table;
1904         break;
1905     case DTLS_ANY_VERSION:
1906         table = dtls_version_table;
1907         break;
1908     }
1909
1910     for (vent = table; vent->version != 0; ++vent) {
1911         const SSL_METHOD *method;
1912         int err;
1913
1914         if (vent->cmeth == NULL)
1915             continue;
1916
1917         if (highver != 0 && s->version != vent->version)
1918             continue;
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 }