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