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