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