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