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