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