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