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