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