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