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