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