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