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