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