Keep the DTLS timer running after the end of the handshake if appropriate
[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
1046         ssl3_cleanup_key_block(s);
1047
1048         if (s->server) {
1049             /*
1050              * In TLSv1.3 we update the cache as part of constructing the
1051              * NewSessionTicket
1052              */
1053             if (!SSL_IS_TLS13(s))
1054                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1055
1056             /* N.B. s->ctx may not equal s->session_ctx */
1057             CRYPTO_atomic_add(&s->ctx->stats.sess_accept_good, 1, &discard,
1058                               s->ctx->lock);
1059             s->handshake_func = ossl_statem_accept;
1060
1061             if (SSL_IS_DTLS(s) && !s->hit) {
1062                 /*
1063                  * We are finishing after the client. We start the timer going
1064                  * in case there are any retransmits of our final flight
1065                  * required.
1066                  */
1067                 dtls1_start_timer(s);
1068             }
1069         } else {
1070             /*
1071              * In TLSv1.3 we update the cache as part of processing the
1072              * NewSessionTicket
1073              */
1074             if (!SSL_IS_TLS13(s))
1075                 ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1076             if (s->hit)
1077                 CRYPTO_atomic_add(&s->session_ctx->stats.sess_hit, 1, &discard,
1078                                   s->session_ctx->lock);
1079
1080             s->handshake_func = ossl_statem_connect;
1081             CRYPTO_atomic_add(&s->session_ctx->stats.sess_connect_good, 1,
1082                               &discard, s->session_ctx->lock);
1083
1084             if (SSL_IS_DTLS(s) && s->hit) {
1085                 /*
1086                  * We are finishing after the server. We start the timer going
1087                  * in case there are any retransmits of our final flight
1088                  * required.
1089                  */
1090                 dtls1_start_timer(s);
1091             }
1092         }
1093
1094         if (SSL_IS_DTLS(s)) {
1095             /* done with handshaking */
1096             s->d1->handshake_read_seq = 0;
1097             s->d1->handshake_write_seq = 0;
1098             s->d1->next_handshake_write_seq = 0;
1099             dtls1_clear_received_buffer(s);
1100         }
1101     }
1102
1103     if (s->info_callback != NULL)
1104         cb = s->info_callback;
1105     else if (s->ctx->info_callback != NULL)
1106         cb = s->ctx->info_callback;
1107
1108     /* The callback may expect us to not be in init at handshake done */
1109     ossl_statem_set_in_init(s, 0);
1110
1111     if (cb != NULL)
1112         cb(s, SSL_CB_HANDSHAKE_DONE, 1);
1113
1114     if (!stop) {
1115         /* If we've got more work to do we go back into init */
1116         ossl_statem_set_in_init(s, 1);
1117         return WORK_FINISHED_CONTINUE;
1118     }
1119
1120     return WORK_FINISHED_STOP;
1121 }
1122
1123 int tls_get_message_header(SSL *s, int *mt)
1124 {
1125     /* s->init_num < SSL3_HM_HEADER_LENGTH */
1126     int skip_message, i, recvd_type;
1127     unsigned char *p;
1128     size_t l, readbytes;
1129
1130     p = (unsigned char *)s->init_buf->data;
1131
1132     do {
1133         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1134             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
1135                                           &p[s->init_num],
1136                                           SSL3_HM_HEADER_LENGTH - s->init_num,
1137                                           0, &readbytes);
1138             if (i <= 0) {
1139                 s->rwstate = SSL_READING;
1140                 return 0;
1141             }
1142             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1143                 /*
1144                  * A ChangeCipherSpec must be a single byte and may not occur
1145                  * in the middle of a handshake message.
1146                  */
1147                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1148                     SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1149                              SSL_F_TLS_GET_MESSAGE_HEADER,
1150                              SSL_R_BAD_CHANGE_CIPHER_SPEC);
1151                     return 0;
1152                 }
1153                 if (s->statem.hand_state == TLS_ST_BEFORE
1154                         && (s->s3->flags & TLS1_FLAGS_STATELESS) != 0) {
1155                     /*
1156                      * We are stateless and we received a CCS. Probably this is
1157                      * from a client between the first and second ClientHellos.
1158                      * We should ignore this, but return an error because we do
1159                      * not return success until we see the second ClientHello
1160                      * with a valid cookie.
1161                      */
1162                     return 0;
1163                 }
1164                 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1165                 s->init_num = readbytes - 1;
1166                 s->init_msg = s->init_buf->data;
1167                 s->s3->tmp.message_size = readbytes;
1168                 return 1;
1169             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1170                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1171                          SSL_F_TLS_GET_MESSAGE_HEADER,
1172                          SSL_R_CCS_RECEIVED_EARLY);
1173                 return 0;
1174             }
1175             s->init_num += readbytes;
1176         }
1177
1178         skip_message = 0;
1179         if (!s->server)
1180             if (s->statem.hand_state != TLS_ST_OK
1181                     && p[0] == SSL3_MT_HELLO_REQUEST)
1182                 /*
1183                  * The server may always send 'Hello Request' messages --
1184                  * we are doing a handshake anyway now, so ignore them if
1185                  * their format is correct. Does not count for 'Finished'
1186                  * MAC.
1187                  */
1188                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1189                     s->init_num = 0;
1190                     skip_message = 1;
1191
1192                     if (s->msg_callback)
1193                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1194                                         p, SSL3_HM_HEADER_LENGTH, s,
1195                                         s->msg_callback_arg);
1196                 }
1197     } while (skip_message);
1198     /* s->init_num == SSL3_HM_HEADER_LENGTH */
1199
1200     *mt = *p;
1201     s->s3->tmp.message_type = *(p++);
1202
1203     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1204         /*
1205          * Only happens with SSLv3+ in an SSLv2 backward compatible
1206          * ClientHello
1207          *
1208          * Total message size is the remaining record bytes to read
1209          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
1210          */
1211         l = RECORD_LAYER_get_rrec_length(&s->rlayer)
1212             + SSL3_HM_HEADER_LENGTH;
1213         s->s3->tmp.message_size = l;
1214
1215         s->init_msg = s->init_buf->data;
1216         s->init_num = SSL3_HM_HEADER_LENGTH;
1217     } else {
1218         n2l3(p, l);
1219         /* BUF_MEM_grow takes an 'int' parameter */
1220         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1221             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_GET_MESSAGE_HEADER,
1222                      SSL_R_EXCESSIVE_MESSAGE_SIZE);
1223             return 0;
1224         }
1225         s->s3->tmp.message_size = l;
1226
1227         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1228         s->init_num = 0;
1229     }
1230
1231     return 1;
1232 }
1233
1234 int tls_get_message_body(SSL *s, size_t *len)
1235 {
1236     size_t n, readbytes;
1237     unsigned char *p;
1238     int i;
1239
1240     if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1241         /* We've already read everything in */
1242         *len = (unsigned long)s->init_num;
1243         return 1;
1244     }
1245
1246     p = s->init_msg;
1247     n = s->s3->tmp.message_size - s->init_num;
1248     while (n > 0) {
1249         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1250                                       &p[s->init_num], n, 0, &readbytes);
1251         if (i <= 0) {
1252             s->rwstate = SSL_READING;
1253             *len = 0;
1254             return 0;
1255         }
1256         s->init_num += readbytes;
1257         n -= readbytes;
1258     }
1259
1260     /*
1261      * If receiving Finished, record MAC of prior handshake messages for
1262      * Finished verification.
1263      */
1264     if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1265         /* SSLfatal() already called */
1266         *len = 0;
1267         return 0;
1268     }
1269
1270     /* Feed this message into MAC computation. */
1271     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1272         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1273                              s->init_num)) {
1274             /* SSLfatal() already called */
1275             *len = 0;
1276             return 0;
1277         }
1278         if (s->msg_callback)
1279             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
1280                             (size_t)s->init_num, s, s->msg_callback_arg);
1281     } else {
1282         /*
1283          * We defer feeding in the HRR until later. We'll do it as part of
1284          * processing the message
1285          * The TLsv1.3 handshake transcript stops at the ClientFinished
1286          * message.
1287          */
1288 #define SERVER_HELLO_RANDOM_OFFSET  (SSL3_HM_HEADER_LENGTH + 2)
1289         /* KeyUpdate and NewSessionTicket do not need to be added */
1290         if (!SSL_IS_TLS13(s) || (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1291                                  && s->s3->tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1292             if (s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO
1293                     || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1294                     || memcmp(hrrrandom,
1295                               s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1296                               SSL3_RANDOM_SIZE) != 0) {
1297                 if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1298                                      s->init_num + SSL3_HM_HEADER_LENGTH)) {
1299                     /* SSLfatal() already called */
1300                     *len = 0;
1301                     return 0;
1302                 }
1303             }
1304         }
1305         if (s->msg_callback)
1306             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1307                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
1308                             s->msg_callback_arg);
1309     }
1310
1311     *len = s->init_num;
1312     return 1;
1313 }
1314
1315 static const X509ERR2ALERT x509table[] = {
1316     {X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE},
1317     {X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1318     {X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE},
1319     {X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA},
1320     {X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1321     {X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1322     {X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE},
1323     {X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED},
1324     {X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1325     {X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE},
1326     {X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED},
1327     {X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE},
1328     {X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR},
1329     {X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE},
1330     {X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA},
1331     {X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE},
1332     {X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1333     {X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE},
1334     {X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE},
1335     {X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1336     {X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE},
1337     {X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1338     {X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA},
1339     {X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR},
1340     {X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE},
1341     {X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE},
1342     {X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR},
1343     {X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA},
1344     {X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA},
1345     {X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR},
1346     {X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE},
1347     {X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1348     {X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE},
1349     {X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA},
1350     {X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA},
1351     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA},
1352     {X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA},
1353     {X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA},
1354     {X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR},
1355
1356     /* Last entry; return this if we don't find the value above. */
1357     {X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN}
1358 };
1359
1360 int ssl_x509err2alert(int x509err)
1361 {
1362     const X509ERR2ALERT *tp;
1363
1364     for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1365         if (tp->x509err == x509err)
1366             break;
1367     return tp->alert;
1368 }
1369
1370 int ssl_allow_compression(SSL *s)
1371 {
1372     if (s->options & SSL_OP_NO_COMPRESSION)
1373         return 0;
1374     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1375 }
1376
1377 static int version_cmp(const SSL *s, int a, int b)
1378 {
1379     int dtls = SSL_IS_DTLS(s);
1380
1381     if (a == b)
1382         return 0;
1383     if (!dtls)
1384         return a < b ? -1 : 1;
1385     return DTLS_VERSION_LT(a, b) ? -1 : 1;
1386 }
1387
1388 typedef struct {
1389     int version;
1390     const SSL_METHOD *(*cmeth) (void);
1391     const SSL_METHOD *(*smeth) (void);
1392 } version_info;
1393
1394 #if TLS_MAX_VERSION != TLS1_3_VERSION
1395 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1396 #endif
1397
1398 /* Must be in order high to low */
1399 static const version_info tls_version_table[] = {
1400 #ifndef OPENSSL_NO_TLS1_3
1401     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1402 #else
1403     {TLS1_3_VERSION, NULL, NULL},
1404 #endif
1405 #ifndef OPENSSL_NO_TLS1_2
1406     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1407 #else
1408     {TLS1_2_VERSION, NULL, NULL},
1409 #endif
1410 #ifndef OPENSSL_NO_TLS1_1
1411     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1412 #else
1413     {TLS1_1_VERSION, NULL, NULL},
1414 #endif
1415 #ifndef OPENSSL_NO_TLS1
1416     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1417 #else
1418     {TLS1_VERSION, NULL, NULL},
1419 #endif
1420 #ifndef OPENSSL_NO_SSL3
1421     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1422 #else
1423     {SSL3_VERSION, NULL, NULL},
1424 #endif
1425     {0, NULL, NULL},
1426 };
1427
1428 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1429 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1430 #endif
1431
1432 /* Must be in order high to low */
1433 static const version_info dtls_version_table[] = {
1434 #ifndef OPENSSL_NO_DTLS1_2
1435     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1436 #else
1437     {DTLS1_2_VERSION, NULL, NULL},
1438 #endif
1439 #ifndef OPENSSL_NO_DTLS1
1440     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1441     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1442 #else
1443     {DTLS1_VERSION, NULL, NULL},
1444     {DTLS1_BAD_VER, NULL, NULL},
1445 #endif
1446     {0, NULL, NULL},
1447 };
1448
1449 /*
1450  * ssl_method_error - Check whether an SSL_METHOD is enabled.
1451  *
1452  * @s: The SSL handle for the candidate method
1453  * @method: the intended method.
1454  *
1455  * Returns 0 on success, or an SSL error reason on failure.
1456  */
1457 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1458 {
1459     int version = method->version;
1460
1461     if ((s->min_proto_version != 0 &&
1462          version_cmp(s, version, s->min_proto_version) < 0) ||
1463         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1464         return SSL_R_VERSION_TOO_LOW;
1465
1466     if (s->max_proto_version != 0 &&
1467         version_cmp(s, version, s->max_proto_version) > 0)
1468         return SSL_R_VERSION_TOO_HIGH;
1469
1470     if ((s->options & method->mask) != 0)
1471         return SSL_R_UNSUPPORTED_PROTOCOL;
1472     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1473         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1474
1475     return 0;
1476 }
1477
1478 /*
1479  * ssl_version_supported - Check that the specified `version` is supported by
1480  * `SSL *` instance
1481  *
1482  * @s: The SSL handle for the candidate method
1483  * @version: Protocol version to test against
1484  *
1485  * Returns 1 when supported, otherwise 0
1486  */
1487 int ssl_version_supported(const SSL *s, int version)
1488 {
1489     const version_info *vent;
1490     const version_info *table;
1491
1492     switch (s->method->version) {
1493     default:
1494         /* Version should match method version for non-ANY method */
1495         return version_cmp(s, version, s->version) == 0;
1496     case TLS_ANY_VERSION:
1497         table = tls_version_table;
1498         break;
1499     case DTLS_ANY_VERSION:
1500         table = dtls_version_table;
1501         break;
1502     }
1503
1504     for (vent = table;
1505          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1506          ++vent) {
1507         if (vent->cmeth != NULL &&
1508             version_cmp(s, version, vent->version) == 0 &&
1509             ssl_method_error(s, vent->cmeth()) == 0) {
1510             return 1;
1511         }
1512     }
1513     return 0;
1514 }
1515
1516 /*
1517  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1518  * fallback indication from a client check whether we're using the highest
1519  * supported protocol version.
1520  *
1521  * @s server SSL handle.
1522  *
1523  * Returns 1 when using the highest enabled version, 0 otherwise.
1524  */
1525 int ssl_check_version_downgrade(SSL *s)
1526 {
1527     const version_info *vent;
1528     const version_info *table;
1529
1530     /*
1531      * Check that the current protocol is the highest enabled version
1532      * (according to s->ctx->method, as version negotiation may have changed
1533      * s->method).
1534      */
1535     if (s->version == s->ctx->method->version)
1536         return 1;
1537
1538     /*
1539      * Apparently we're using a version-flexible SSL_METHOD (not at its
1540      * highest protocol version).
1541      */
1542     if (s->ctx->method->version == TLS_method()->version)
1543         table = tls_version_table;
1544     else if (s->ctx->method->version == DTLS_method()->version)
1545         table = dtls_version_table;
1546     else {
1547         /* Unexpected state; fail closed. */
1548         return 0;
1549     }
1550
1551     for (vent = table; vent->version != 0; ++vent) {
1552         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1553             return s->version == vent->version;
1554     }
1555     return 0;
1556 }
1557
1558 /*
1559  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1560  * protocols, provided the initial (D)TLS method is version-flexible.  This
1561  * function sanity-checks the proposed value and makes sure the method is
1562  * version-flexible, then sets the limit if all is well.
1563  *
1564  * @method_version: The version of the current SSL_METHOD.
1565  * @version: the intended limit.
1566  * @bound: pointer to limit to be updated.
1567  *
1568  * Returns 1 on success, 0 on failure.
1569  */
1570 int ssl_set_version_bound(int method_version, int version, int *bound)
1571 {
1572     if (version == 0) {
1573         *bound = version;
1574         return 1;
1575     }
1576
1577     /*-
1578      * Restrict TLS methods to TLS protocol versions.
1579      * Restrict DTLS methods to DTLS protocol versions.
1580      * Note, DTLS version numbers are decreasing, use comparison macros.
1581      *
1582      * Note that for both lower-bounds we use explicit versions, not
1583      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
1584      * configurations.  If the MIN (supported) version ever rises, the user's
1585      * "floor" remains valid even if no longer available.  We don't expect the
1586      * MAX ceiling to ever get lower, so making that variable makes sense.
1587      */
1588     switch (method_version) {
1589     default:
1590         /*
1591          * XXX For fixed version methods, should we always fail and not set any
1592          * bounds, always succeed and not set any bounds, or set the bounds and
1593          * arrange to fail later if they are not met?  At present fixed-version
1594          * methods are not subject to controls that disable individual protocol
1595          * versions.
1596          */
1597         return 0;
1598
1599     case TLS_ANY_VERSION:
1600         if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1601             return 0;
1602         break;
1603
1604     case DTLS_ANY_VERSION:
1605         if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1606             DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1607             return 0;
1608         break;
1609     }
1610
1611     *bound = version;
1612     return 1;
1613 }
1614
1615 static void check_for_downgrade(SSL *s, int vers, DOWNGRADE *dgrd)
1616 {
1617     if (vers == TLS1_2_VERSION
1618             && ssl_version_supported(s, TLS1_3_VERSION)) {
1619         *dgrd = DOWNGRADE_TO_1_2;
1620     } else if (!SSL_IS_DTLS(s) && vers < TLS1_2_VERSION
1621             && (ssl_version_supported(s, TLS1_2_VERSION)
1622                 || ssl_version_supported(s, TLS1_3_VERSION))) {
1623         *dgrd = DOWNGRADE_TO_1_1;
1624     } else {
1625         *dgrd = DOWNGRADE_NONE;
1626     }
1627 }
1628
1629 /*
1630  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
1631  * client HELLO is received to select the final server protocol version and
1632  * the version specific method.
1633  *
1634  * @s: server SSL handle.
1635  *
1636  * Returns 0 on success or an SSL error reason number on failure.
1637  */
1638 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello, DOWNGRADE *dgrd)
1639 {
1640     /*-
1641      * With version-flexible methods we have an initial state with:
1642      *
1643      *   s->method->version == (D)TLS_ANY_VERSION,
1644      *   s->version == (D)TLS_MAX_VERSION.
1645      *
1646      * So we detect version-flexible methods via the method version, not the
1647      * handle version.
1648      */
1649     int server_version = s->method->version;
1650     int client_version = hello->legacy_version;
1651     const version_info *vent;
1652     const version_info *table;
1653     int disabled = 0;
1654     RAW_EXTENSION *suppversions;
1655
1656     s->client_version = client_version;
1657
1658     switch (server_version) {
1659     default:
1660         if (!SSL_IS_TLS13(s)) {
1661             if (version_cmp(s, client_version, s->version) < 0)
1662                 return SSL_R_WRONG_SSL_VERSION;
1663             *dgrd = DOWNGRADE_NONE;
1664             /*
1665              * If this SSL handle is not from a version flexible method we don't
1666              * (and never did) check min/max FIPS or Suite B constraints.  Hope
1667              * that's OK.  It is up to the caller to not choose fixed protocol
1668              * versions they don't want.  If not, then easy to fix, just return
1669              * ssl_method_error(s, s->method)
1670              */
1671             return 0;
1672         }
1673         /*
1674          * Fall through if we are TLSv1.3 already (this means we must be after
1675          * a HelloRetryRequest
1676          */
1677         /* fall thru */
1678     case TLS_ANY_VERSION:
1679         table = tls_version_table;
1680         break;
1681     case DTLS_ANY_VERSION:
1682         table = dtls_version_table;
1683         break;
1684     }
1685
1686     suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1687
1688     /* If we did an HRR then supported versions is mandatory */
1689     if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
1690         return SSL_R_UNSUPPORTED_PROTOCOL;
1691
1692     if (suppversions->present && !SSL_IS_DTLS(s)) {
1693         unsigned int candidate_vers = 0;
1694         unsigned int best_vers = 0;
1695         const SSL_METHOD *best_method = NULL;
1696         PACKET versionslist;
1697
1698         suppversions->parsed = 1;
1699
1700         if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1701             /* Trailing or invalid data? */
1702             return SSL_R_LENGTH_MISMATCH;
1703         }
1704
1705         while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1706             /* TODO(TLS1.3): Remove this before release */
1707             if (candidate_vers == TLS1_3_VERSION_DRAFT)
1708                 candidate_vers = TLS1_3_VERSION;
1709             /*
1710              * TODO(TLS1.3): There is some discussion on the TLS list about
1711              * whether to ignore versions <TLS1.2 in supported_versions. At the
1712              * moment we honour them if present. To be reviewed later
1713              */
1714             if (version_cmp(s, candidate_vers, best_vers) <= 0)
1715                 continue;
1716             for (vent = table;
1717                  vent->version != 0 && vent->version != (int)candidate_vers;
1718                  ++vent)
1719                 continue;
1720             if (vent->version != 0 && vent->smeth != NULL) {
1721                 const SSL_METHOD *method;
1722
1723                 method = vent->smeth();
1724                 if (ssl_method_error(s, method) == 0) {
1725                     best_vers = candidate_vers;
1726                     best_method = method;
1727                 }
1728             }
1729         }
1730         if (PACKET_remaining(&versionslist) != 0) {
1731             /* Trailing data? */
1732             return SSL_R_LENGTH_MISMATCH;
1733         }
1734
1735         if (best_vers > 0) {
1736             if (s->hello_retry_request != SSL_HRR_NONE) {
1737                 /*
1738                  * This is after a HelloRetryRequest so we better check that we
1739                  * negotiated TLSv1.3
1740                  */
1741                 if (best_vers != TLS1_3_VERSION)
1742                     return SSL_R_UNSUPPORTED_PROTOCOL;
1743                 return 0;
1744             }
1745             check_for_downgrade(s, best_vers, dgrd);
1746             s->version = best_vers;
1747             s->method = best_method;
1748             return 0;
1749         }
1750         return SSL_R_UNSUPPORTED_PROTOCOL;
1751     }
1752
1753     /*
1754      * If the supported versions extension isn't present, then the highest
1755      * version we can negotiate is TLSv1.2
1756      */
1757     if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1758         client_version = TLS1_2_VERSION;
1759
1760     /*
1761      * No supported versions extension, so we just use the version supplied in
1762      * the ClientHello.
1763      */
1764     for (vent = table; vent->version != 0; ++vent) {
1765         const SSL_METHOD *method;
1766
1767         if (vent->smeth == NULL ||
1768             version_cmp(s, client_version, vent->version) < 0)
1769             continue;
1770         method = vent->smeth();
1771         if (ssl_method_error(s, method) == 0) {
1772             check_for_downgrade(s, vent->version, dgrd);
1773             s->version = vent->version;
1774             s->method = method;
1775             return 0;
1776         }
1777         disabled = 1;
1778     }
1779     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1780 }
1781
1782 /*
1783  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
1784  * server HELLO is received to select the final client protocol version and
1785  * the version specific method.
1786  *
1787  * @s: client SSL handle.
1788  * @version: The proposed version from the server's HELLO.
1789  * @extensions: The extensions received
1790  *
1791  * Returns 1 on success or 0 on error.
1792  */
1793 int ssl_choose_client_version(SSL *s, int version, RAW_EXTENSION *extensions)
1794 {
1795     const version_info *vent;
1796     const version_info *table;
1797     int highver = 0;
1798     int origv;
1799
1800     origv = s->version;
1801     s->version = version;
1802
1803     /* This will overwrite s->version if the extension is present */
1804     if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
1805                              SSL_EXT_TLS1_2_SERVER_HELLO
1806                              | SSL_EXT_TLS1_3_SERVER_HELLO, extensions,
1807                              NULL, 0)) {
1808         s->version = origv;
1809         return 0;
1810     }
1811
1812     if (s->hello_retry_request != SSL_HRR_NONE
1813             && s->version != TLS1_3_VERSION) {
1814         s->version = origv;
1815         SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1816                  SSL_R_WRONG_SSL_VERSION);
1817         return 0;
1818     }
1819
1820     switch (s->method->version) {
1821     default:
1822         if (s->version != s->method->version) {
1823             s->version = origv;
1824             SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1825                      SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1826                      SSL_R_WRONG_SSL_VERSION);
1827             return 0;
1828         }
1829         /*
1830          * If this SSL handle is not from a version flexible method we don't
1831          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
1832          * that's OK.  It is up to the caller to not choose fixed protocol
1833          * versions they don't want.  If not, then easy to fix, just return
1834          * ssl_method_error(s, s->method)
1835          */
1836         return 1;
1837     case TLS_ANY_VERSION:
1838         table = tls_version_table;
1839         break;
1840     case DTLS_ANY_VERSION:
1841         table = dtls_version_table;
1842         break;
1843     }
1844
1845     for (vent = table; vent->version != 0; ++vent) {
1846         const SSL_METHOD *method;
1847         int err;
1848
1849         if (vent->cmeth == NULL)
1850             continue;
1851
1852         if (highver != 0 && s->version != vent->version)
1853             continue;
1854
1855         method = vent->cmeth();
1856         err = ssl_method_error(s, method);
1857         if (err != 0) {
1858             if (s->version == vent->version) {
1859                 s->version = origv;
1860                 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1861                          SSL_F_SSL_CHOOSE_CLIENT_VERSION, err);
1862                 return 0;
1863             }
1864
1865             continue;
1866         }
1867         if (highver == 0)
1868             highver = vent->version;
1869
1870         if (s->version != vent->version)
1871             continue;
1872
1873 #ifndef OPENSSL_NO_TLS13DOWNGRADE
1874         /* Check for downgrades */
1875         if (s->version == TLS1_2_VERSION && highver > s->version) {
1876             if (memcmp(tls12downgrade,
1877                        s->s3->server_random + SSL3_RANDOM_SIZE
1878                                             - sizeof(tls12downgrade),
1879                        sizeof(tls12downgrade)) == 0) {
1880                 s->version = origv;
1881                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1882                          SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1883                          SSL_R_INAPPROPRIATE_FALLBACK);
1884                 return 0;
1885             }
1886         } else if (!SSL_IS_DTLS(s)
1887                    && s->version < TLS1_2_VERSION
1888                    && highver > s->version) {
1889             if (memcmp(tls11downgrade,
1890                        s->s3->server_random + SSL3_RANDOM_SIZE
1891                                             - sizeof(tls11downgrade),
1892                        sizeof(tls11downgrade)) == 0) {
1893                 s->version = origv;
1894                 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1895                          SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1896                          SSL_R_INAPPROPRIATE_FALLBACK);
1897                 return 0;
1898             }
1899         }
1900 #endif
1901
1902         s->method = method;
1903         return 1;
1904     }
1905
1906     s->version = origv;
1907     SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL_CHOOSE_CLIENT_VERSION,
1908              SSL_R_UNSUPPORTED_PROTOCOL);
1909     return 0;
1910 }
1911
1912 /*
1913  * ssl_get_min_max_version - get minimum and maximum protocol version
1914  * @s: The SSL connection
1915  * @min_version: The minimum supported version
1916  * @max_version: The maximum supported version
1917  *
1918  * Work out what version we should be using for the initial ClientHello if the
1919  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
1920  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1921  * constraints and any floor imposed by the security level here,
1922  * so we don't advertise the wrong protocol version to only reject the outcome later.
1923  *
1924  * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
1925  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
1926  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1927  *
1928  * Returns 0 on success or an SSL error reason number on failure.  On failure
1929  * min_version and max_version will also be set to 0.
1930  */
1931 int ssl_get_min_max_version(const SSL *s, int *min_version, int *max_version)
1932 {
1933     int version;
1934     int hole;
1935     const SSL_METHOD *single = NULL;
1936     const SSL_METHOD *method;
1937     const version_info *table;
1938     const version_info *vent;
1939
1940     switch (s->method->version) {
1941     default:
1942         /*
1943          * If this SSL handle is not from a version flexible method we don't
1944          * (and never did) check min/max FIPS or Suite B constraints.  Hope
1945          * that's OK.  It is up to the caller to not choose fixed protocol
1946          * versions they don't want.  If not, then easy to fix, just return
1947          * ssl_method_error(s, s->method)
1948          */
1949         *min_version = *max_version = s->version;
1950         return 0;
1951     case TLS_ANY_VERSION:
1952         table = tls_version_table;
1953         break;
1954     case DTLS_ANY_VERSION:
1955         table = dtls_version_table;
1956         break;
1957     }
1958
1959     /*
1960      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1961      * below X enabled. This is required in order to maintain the "version
1962      * capability" vector contiguous. Any versions with a NULL client method
1963      * (protocol version client is disabled at compile-time) is also a "hole".
1964      *
1965      * Our initial state is hole == 1, version == 0.  That is, versions above
1966      * the first version in the method table are disabled (a "hole" above
1967      * the valid protocol entries) and we don't have a selected version yet.
1968      *
1969      * Whenever "hole == 1", and we hit an enabled method, its version becomes
1970      * the selected version, and the method becomes a candidate "single"
1971      * method.  We're no longer in a hole, so "hole" becomes 0.
1972      *
1973      * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1974      * as we support a contiguous range of at least two methods.  If we hit
1975      * a disabled method, then hole becomes true again, but nothing else
1976      * changes yet, because all the remaining methods may be disabled too.
1977      * If we again hit an enabled method after the new hole, it becomes
1978      * selected, as we start from scratch.
1979      */
1980     *min_version = version = 0;
1981     hole = 1;
1982     for (vent = table; vent->version != 0; ++vent) {
1983         /*
1984          * A table entry with a NULL client method is still a hole in the
1985          * "version capability" vector.
1986          */
1987         if (vent->cmeth == NULL) {
1988             hole = 1;
1989             continue;
1990         }
1991         method = vent->cmeth();
1992         if (ssl_method_error(s, method) != 0) {
1993             hole = 1;
1994         } else if (!hole) {
1995             single = NULL;
1996             *min_version = method->version;
1997         } else {
1998             version = (single = method)->version;
1999             *min_version = version;
2000             hole = 0;
2001         }
2002     }
2003
2004     *max_version = version;
2005
2006     /* Fail if everything is disabled */
2007     if (version == 0)
2008         return SSL_R_NO_PROTOCOLS_AVAILABLE;
2009
2010     return 0;
2011 }
2012
2013 /*
2014  * ssl_set_client_hello_version - Work out what version we should be using for
2015  * the initial ClientHello.legacy_version field.
2016  *
2017  * @s: client SSL handle.
2018  *
2019  * Returns 0 on success or an SSL error reason number on failure.
2020  */
2021 int ssl_set_client_hello_version(SSL *s)
2022 {
2023     int ver_min, ver_max, ret;
2024
2025     /*
2026      * In a renegotiation we always send the same client_version that we sent
2027      * last time, regardless of which version we eventually negotiated.
2028      */
2029     if (!SSL_IS_FIRST_HANDSHAKE(s))
2030         return 0;
2031
2032     ret = ssl_get_min_max_version(s, &ver_min, &ver_max);
2033
2034     if (ret != 0)
2035         return ret;
2036
2037     s->version = ver_max;
2038
2039     /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2040     if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
2041         ver_max = TLS1_2_VERSION;
2042
2043     s->client_version = ver_max;
2044     return 0;
2045 }
2046
2047 /*
2048  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2049  * and |checkallow| is 1 then additionally check if the group is allowed to be
2050  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2051  * 1) or 0 otherwise.
2052  */
2053 #ifndef OPENSSL_NO_EC
2054 int check_in_list(SSL *s, uint16_t group_id, const uint16_t *groups,
2055                   size_t num_groups, int checkallow)
2056 {
2057     size_t i;
2058
2059     if (groups == NULL || num_groups == 0)
2060         return 0;
2061
2062     for (i = 0; i < num_groups; i++) {
2063         uint16_t group = groups[i];
2064
2065         if (group_id == group
2066                 && (!checkallow
2067                     || tls_curve_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2068             return 1;
2069         }
2070     }
2071
2072     return 0;
2073 }
2074 #endif
2075
2076 /* Replace ClientHello1 in the transcript hash with a synthetic message */
2077 int create_synthetic_message_hash(SSL *s, const unsigned char *hashval,
2078                                   size_t hashlen, const unsigned char *hrr,
2079                                   size_t hrrlen)
2080 {
2081     unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2082     unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2083
2084     memset(msghdr, 0, sizeof(msghdr));
2085
2086     if (hashval == NULL) {
2087         hashval = hashvaltmp;
2088         hashlen = 0;
2089         /* Get the hash of the initial ClientHello */
2090         if (!ssl3_digest_cached_records(s, 0)
2091                 || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2092                                        &hashlen)) {
2093             /* SSLfatal() already called */
2094             return 0;
2095         }
2096     }
2097
2098     /* Reinitialise the transcript hash */
2099     if (!ssl3_init_finished_mac(s)) {
2100         /* SSLfatal() already called */
2101         return 0;
2102     }
2103
2104     /* Inject the synthetic message_hash message */
2105     msghdr[0] = SSL3_MT_MESSAGE_HASH;
2106     msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2107     if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2108             || !ssl3_finish_mac(s, hashval, hashlen)) {
2109         /* SSLfatal() already called */
2110         return 0;
2111     }
2112
2113     /*
2114      * Now re-inject the HRR and current message if appropriate (we just deleted
2115      * it when we reinitialised the transcript hash above). Only necessary after
2116      * receiving a ClientHello2 with a cookie.
2117      */
2118     if (hrr != NULL
2119             && (!ssl3_finish_mac(s, hrr, hrrlen)
2120                 || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2121                                     s->s3->tmp.message_size
2122                                     + SSL3_HM_HEADER_LENGTH))) {
2123         /* SSLfatal() already called */
2124         return 0;
2125     }
2126
2127     return 1;
2128 }
2129
2130 static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2131 {
2132     return X509_NAME_cmp(*a, *b);
2133 }
2134
2135 int parse_ca_names(SSL *s, PACKET *pkt)
2136 {
2137     STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2138     X509_NAME *xn = NULL;
2139     PACKET cadns;
2140
2141     if (ca_sk == NULL) {
2142         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2143                  ERR_R_MALLOC_FAILURE);
2144         goto err;
2145     }
2146     /* get the CA RDNs */
2147     if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2148         SSLfatal(s, SSL_AD_DECODE_ERROR,SSL_F_PARSE_CA_NAMES,
2149                  SSL_R_LENGTH_MISMATCH);
2150         goto err;
2151     }
2152
2153     while (PACKET_remaining(&cadns)) {
2154         const unsigned char *namestart, *namebytes;
2155         unsigned int name_len;
2156
2157         if (!PACKET_get_net_2(&cadns, &name_len)
2158             || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2159             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2160                      SSL_R_LENGTH_MISMATCH);
2161             goto err;
2162         }
2163
2164         namestart = namebytes;
2165         if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2166             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2167                      ERR_R_ASN1_LIB);
2168             goto err;
2169         }
2170         if (namebytes != (namestart + name_len)) {
2171             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_PARSE_CA_NAMES,
2172                      SSL_R_CA_DN_LENGTH_MISMATCH);
2173             goto err;
2174         }
2175
2176         if (!sk_X509_NAME_push(ca_sk, xn)) {
2177             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_PARSE_CA_NAMES,
2178                      ERR_R_MALLOC_FAILURE);
2179             goto err;
2180         }
2181         xn = NULL;
2182     }
2183
2184     sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
2185     s->s3->tmp.peer_ca_names = ca_sk;
2186
2187     return 1;
2188
2189  err:
2190     sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2191     X509_NAME_free(xn);
2192     return 0;
2193 }
2194
2195 int construct_ca_names(SSL *s, WPACKET *pkt)
2196 {
2197     const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
2198
2199     /* Start sub-packet for client CA list */
2200     if (!WPACKET_start_sub_packet_u16(pkt)) {
2201         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2202                  ERR_R_INTERNAL_ERROR);
2203         return 0;
2204     }
2205
2206     if (ca_sk != NULL) {
2207         int i;
2208
2209         for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2210             unsigned char *namebytes;
2211             X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2212             int namelen;
2213
2214             if (name == NULL
2215                     || (namelen = i2d_X509_NAME(name, NULL)) < 0
2216                     || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2217                                                        &namebytes)
2218                     || i2d_X509_NAME(name, &namebytes) != namelen) {
2219                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2220                          ERR_R_INTERNAL_ERROR);
2221                 return 0;
2222             }
2223         }
2224     }
2225
2226     if (!WPACKET_close(pkt)) {
2227         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_CA_NAMES,
2228                  ERR_R_INTERNAL_ERROR);
2229         return 0;
2230     }
2231
2232     return 1;
2233 }
2234
2235 /* Create a buffer containing data to be signed for server key exchange */
2236 size_t construct_key_exchange_tbs(SSL *s, unsigned char **ptbs,
2237                                   const void *param, size_t paramlen)
2238 {
2239     size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2240     unsigned char *tbs = OPENSSL_malloc(tbslen);
2241
2242     if (tbs == NULL) {
2243         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS,
2244                  ERR_R_MALLOC_FAILURE);
2245         return 0;
2246     }
2247     memcpy(tbs, s->s3->client_random, SSL3_RANDOM_SIZE);
2248     memcpy(tbs + SSL3_RANDOM_SIZE, s->s3->server_random, SSL3_RANDOM_SIZE);
2249
2250     memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2251
2252     *ptbs = tbs;
2253     return tbslen;
2254 }
2255
2256 /*
2257  * Saves the current handshake digest for Post-Handshake Auth,
2258  * Done after ClientFinished is processed, done exactly once
2259  */
2260 int tls13_save_handshake_digest_for_pha(SSL *s)
2261 {
2262     if (s->pha_dgst == NULL) {
2263         if (!ssl3_digest_cached_records(s, 1))
2264             /* SSLfatal() already called */
2265             return 0;
2266
2267         s->pha_dgst = EVP_MD_CTX_new();
2268         if (s->pha_dgst == NULL) {
2269             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2270                      SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2271                      ERR_R_INTERNAL_ERROR);
2272             return 0;
2273         }
2274         if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2275                                 s->s3->handshake_dgst)) {
2276             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2277                      SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA,
2278                      ERR_R_INTERNAL_ERROR);
2279             return 0;
2280         }
2281     }
2282     return 1;
2283 }
2284
2285 /*
2286  * Restores the Post-Handshake Auth handshake digest
2287  * Done just before sending/processing the Cert Request
2288  */
2289 int tls13_restore_handshake_digest_for_pha(SSL *s)
2290 {
2291     if (s->pha_dgst == NULL) {
2292         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2293                  SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2294                  ERR_R_INTERNAL_ERROR);
2295         return 0;
2296     }
2297     if (!EVP_MD_CTX_copy_ex(s->s3->handshake_dgst,
2298                             s->pha_dgst)) {
2299         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2300                  SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA,
2301                  ERR_R_INTERNAL_ERROR);
2302         return 0;
2303     }
2304     return 1;
2305 }