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