0395e9f002e813eb6e68b1da9f21fb83b14a89f8
[openssl.git] / ssl / statem / statem_lib.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  * ECC cipher suite support in OpenSSL originally developed by
13  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
14  */
15
16 #include <limits.h>
17 #include <string.h>
18 #include <stdio.h>
19 #include "../ssl_locl.h"
20 #include "statem_locl.h"
21 #include <openssl/buffer.h>
22 #include <openssl/objects.h>
23 #include <openssl/evp.h>
24 #include <openssl/x509.h>
25
26 /*
27  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
28  * SSL3_RT_CHANGE_CIPHER_SPEC)
29  */
30 int ssl3_do_write(SSL *s, int type)
31 {
32     int ret;
33     size_t written = 0;
34
35     ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
36                            s->init_num, &written);
37     if (ret < 0)
38         return (-1);
39     if (type == SSL3_RT_HANDSHAKE)
40         /*
41          * should not be done for 'Hello Request's, but in that case we'll
42          * ignore the result anyway
43          */
44         if (!ssl3_finish_mac(s,
45                              (unsigned char *)&s->init_buf->data[s->init_off],
46                              written))
47             return -1;
48
49     if (written == s->init_num) {
50         if (s->msg_callback)
51             s->msg_callback(1, s->version, type, s->init_buf->data,
52                             (size_t)(s->init_off + s->init_num), s,
53                             s->msg_callback_arg);
54         return (1);
55     }
56     s->init_off += written;
57     s->init_num -= written;
58     return (0);
59 }
60
61 int tls_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
62 {
63     size_t msglen;
64
65     if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
66             || !WPACKET_get_length(pkt, &msglen)
67             || msglen > INT_MAX)
68         return 0;
69     s->init_num = (int)msglen;
70     s->init_off = 0;
71
72     return 1;
73 }
74
75 int tls_construct_cert_verify(SSL *s, WPACKET *pkt)
76 {
77     EVP_PKEY *pkey;
78     const EVP_MD *md = s->s3->tmp.md[s->cert->key - s->cert->pkeys];
79     EVP_MD_CTX *mctx = NULL;
80     unsigned u = 0;
81     long hdatalen = 0;
82     void *hdata;
83     unsigned char *sig = NULL;
84
85     mctx = EVP_MD_CTX_new();
86     if (mctx == NULL) {
87         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
88         goto err;
89     }
90     pkey = s->cert->key->privatekey;
91
92     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
93     if (hdatalen <= 0) {
94         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
95         goto err;
96     }
97
98     if (SSL_USE_SIGALGS(s)&& !tls12_get_sigandhash(pkt, pkey, md)) {
99         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
100         goto err;
101     }
102 #ifdef SSL_DEBUG
103     fprintf(stderr, "Using client alg %s\n", EVP_MD_name(md));
104 #endif
105     sig = OPENSSL_malloc(EVP_PKEY_size(pkey));
106     if (sig == NULL) {
107         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
108         goto err;
109     }
110     if (!EVP_SignInit_ex(mctx, md, NULL)
111         || !EVP_SignUpdate(mctx, hdata, hdatalen)
112         || (s->version == SSL3_VERSION
113             && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
114                                 (int)s->session->master_key_length,
115                                 s->session->master_key))
116         || !EVP_SignFinal(mctx, sig, &u, pkey)) {
117         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_EVP_LIB);
118         goto err;
119     }
120 #ifndef OPENSSL_NO_GOST
121     {
122         int pktype = EVP_PKEY_id(pkey);
123         if (pktype == NID_id_GostR3410_2001
124             || pktype == NID_id_GostR3410_2012_256
125             || pktype == NID_id_GostR3410_2012_512)
126             BUF_reverse(sig, NULL, u);
127     }
128 #endif
129
130     if (!WPACKET_sub_memcpy_u16(pkt, sig, u)) {
131         SSLerr(SSL_F_TLS_CONSTRUCT_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
132         goto err;
133     }
134
135     /* Digest cached records and discard handshake buffer */
136     if (!ssl3_digest_cached_records(s, 0))
137         goto err;
138
139     OPENSSL_free(sig);
140     EVP_MD_CTX_free(mctx);
141     return 1;
142  err:
143     OPENSSL_free(sig);
144     EVP_MD_CTX_free(mctx);
145     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
146     return 0;
147 }
148
149 MSG_PROCESS_RETURN tls_process_cert_verify(SSL *s, PACKET *pkt)
150 {
151     EVP_PKEY *pkey = NULL;
152     const unsigned char *sig, *data;
153 #ifndef OPENSSL_NO_GOST
154     unsigned char *gost_data = NULL;
155 #endif
156     int al, ret = MSG_PROCESS_ERROR;
157     int type = 0, j;
158     unsigned int len;
159     X509 *peer;
160     const EVP_MD *md = NULL;
161     long hdatalen = 0;
162     void *hdata;
163
164     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
165
166     if (mctx == NULL) {
167         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
168         al = SSL_AD_INTERNAL_ERROR;
169         goto f_err;
170     }
171
172     peer = s->session->peer;
173     pkey = X509_get0_pubkey(peer);
174     type = X509_certificate_type(peer, pkey);
175
176     if (!(type & EVP_PKT_SIGN)) {
177         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY,
178                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
179         al = SSL_AD_ILLEGAL_PARAMETER;
180         goto f_err;
181     }
182
183     /* Check for broken implementations of GOST ciphersuites */
184     /*
185      * If key is GOST and n is exactly 64, it is bare signature without
186      * length field (CryptoPro implementations at least till CSP 4.0)
187      */
188 #ifndef OPENSSL_NO_GOST
189     if (PACKET_remaining(pkt) == 64
190         && EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
191         len = 64;
192     } else
193 #endif
194     {
195         if (SSL_USE_SIGALGS(s)) {
196             int rv;
197
198             if (!PACKET_get_bytes(pkt, &sig, 2)) {
199                 al = SSL_AD_DECODE_ERROR;
200                 goto f_err;
201             }
202             rv = tls12_check_peer_sigalg(&md, s, sig, pkey);
203             if (rv == -1) {
204                 al = SSL_AD_INTERNAL_ERROR;
205                 goto f_err;
206             } else if (rv == 0) {
207                 al = SSL_AD_DECODE_ERROR;
208                 goto f_err;
209             }
210 #ifdef SSL_DEBUG
211             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
212 #endif
213         } else {
214             /* Use default digest for this key type */
215             int idx = ssl_cert_type(NULL, pkey);
216             if (idx >= 0)
217                 md = s->s3->tmp.md[idx];
218             if (md == NULL) {
219                 al = SSL_AD_INTERNAL_ERROR;
220                 goto f_err;
221             }
222         }
223
224         if (!PACKET_get_net_2(pkt, &len)) {
225             SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
226             al = SSL_AD_DECODE_ERROR;
227             goto f_err;
228         }
229     }
230     j = EVP_PKEY_size(pkey);
231     if (((int)len > j) || ((int)PACKET_remaining(pkt) > j)
232         || (PACKET_remaining(pkt) == 0)) {
233         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
234         al = SSL_AD_DECODE_ERROR;
235         goto f_err;
236     }
237     if (!PACKET_get_bytes(pkt, &data, len)) {
238         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
239         al = SSL_AD_DECODE_ERROR;
240         goto f_err;
241     }
242
243     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
244     if (hdatalen <= 0) {
245         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
246         al = SSL_AD_INTERNAL_ERROR;
247         goto f_err;
248     }
249
250 #ifdef SSL_DEBUG
251     fprintf(stderr, "Using client verify alg %s\n", EVP_MD_name(md));
252 #endif
253     if (!EVP_VerifyInit_ex(mctx, md, NULL)
254         || !EVP_VerifyUpdate(mctx, hdata, hdatalen)) {
255         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
256         al = SSL_AD_INTERNAL_ERROR;
257         goto f_err;
258     }
259 #ifndef OPENSSL_NO_GOST
260     {
261         int pktype = EVP_PKEY_id(pkey);
262         if (pktype == NID_id_GostR3410_2001
263             || pktype == NID_id_GostR3410_2012_256
264             || pktype == NID_id_GostR3410_2012_512) {
265             if ((gost_data = OPENSSL_malloc(len)) == NULL) {
266                 SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_MALLOC_FAILURE);
267                 al = SSL_AD_INTERNAL_ERROR;
268                 goto f_err;
269             }
270             BUF_reverse(gost_data, data, len);
271             data = gost_data;
272         }
273     }
274 #endif
275
276     if (s->version == SSL3_VERSION
277         && !EVP_MD_CTX_ctrl(mctx, EVP_CTRL_SSL3_MASTER_SECRET,
278                             (int)s->session->master_key_length,
279                             s->session->master_key)) {
280         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, ERR_R_EVP_LIB);
281         al = SSL_AD_INTERNAL_ERROR;
282         goto f_err;
283     }
284
285     if (EVP_VerifyFinal(mctx, data, len, pkey) <= 0) {
286         al = SSL_AD_DECRYPT_ERROR;
287         SSLerr(SSL_F_TLS_PROCESS_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
288         goto f_err;
289     }
290
291     ret = MSG_PROCESS_CONTINUE_PROCESSING;
292     if (0) {
293  f_err:
294         ssl3_send_alert(s, SSL3_AL_FATAL, al);
295         ossl_statem_set_error(s);
296     }
297     BIO_free(s->s3->handshake_buffer);
298     s->s3->handshake_buffer = NULL;
299     EVP_MD_CTX_free(mctx);
300 #ifndef OPENSSL_NO_GOST
301     OPENSSL_free(gost_data);
302 #endif
303     return ret;
304 }
305
306 int tls_construct_finished(SSL *s, WPACKET *pkt)
307 {
308     size_t finish_md_len;
309     const char *sender;
310     size_t slen;
311
312     if (s->server) {
313         sender = s->method->ssl3_enc->server_finished_label;
314         slen = s->method->ssl3_enc->server_finished_label_len;
315     } else {
316         sender = s->method->ssl3_enc->client_finished_label;
317         slen = s->method->ssl3_enc->client_finished_label_len;
318     }
319
320     finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
321                                                           sender, slen,
322                                                           s->s3->tmp.finish_md);
323     if (finish_md_len == 0) {
324         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
325         goto err;
326     }
327
328     s->s3->tmp.finish_md_len = finish_md_len;
329
330     if (!WPACKET_memcpy(pkt, s->s3->tmp.finish_md, finish_md_len)) {
331         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
332         goto err;
333     }
334
335     /*
336      * Copy the finished so we can use it for renegotiation checks
337      */
338     if (!s->server) {
339         OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
340         memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md,
341                finish_md_len);
342         s->s3->previous_client_finished_len = finish_md_len;
343     } else {
344         OPENSSL_assert(finish_md_len <= EVP_MAX_MD_SIZE);
345         memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md,
346                finish_md_len);
347         s->s3->previous_server_finished_len = finish_md_len;
348     }
349
350     return 1;
351  err:
352     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
353     return 0;
354 }
355
356 #ifndef OPENSSL_NO_NEXTPROTONEG
357 /*
358  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
359  * to far.
360  */
361 static void ssl3_take_mac(SSL *s)
362 {
363     const char *sender;
364     size_t slen;
365     /*
366      * If no new cipher setup return immediately: other functions will set
367      * the appropriate error.
368      */
369     if (s->s3->tmp.new_cipher == NULL)
370         return;
371     if (!s->server) {
372         sender = s->method->ssl3_enc->server_finished_label;
373         slen = s->method->ssl3_enc->server_finished_label_len;
374     } else {
375         sender = s->method->ssl3_enc->client_finished_label;
376         slen = s->method->ssl3_enc->client_finished_label_len;
377     }
378
379     s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
380                                                                           sender,
381                                                                           slen,
382                                                                           s->s3->tmp.peer_finish_md);
383 }
384 #endif
385
386 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
387 {
388     int al;
389     size_t remain;
390
391     remain = PACKET_remaining(pkt);
392     /*
393      * 'Change Cipher Spec' is just a single byte, which should already have
394      * been consumed by ssl_get_message() so there should be no bytes left,
395      * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
396      */
397     if (SSL_IS_DTLS(s)) {
398         if ((s->version == DTLS1_BAD_VER
399              && remain != DTLS1_CCS_HEADER_LENGTH + 1)
400             || (s->version != DTLS1_BAD_VER
401                 && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
402             al = SSL_AD_ILLEGAL_PARAMETER;
403             SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
404                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
405             goto f_err;
406         }
407     } else {
408         if (remain != 0) {
409             al = SSL_AD_ILLEGAL_PARAMETER;
410             SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
411                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
412             goto f_err;
413         }
414     }
415
416     /* Check we have a cipher to change to */
417     if (s->s3->tmp.new_cipher == NULL) {
418         al = SSL_AD_UNEXPECTED_MESSAGE;
419         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
420         goto f_err;
421     }
422
423     s->s3->change_cipher_spec = 1;
424     if (!ssl3_do_change_cipher_spec(s)) {
425         al = SSL_AD_INTERNAL_ERROR;
426         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
427         goto f_err;
428     }
429
430     if (SSL_IS_DTLS(s)) {
431         dtls1_reset_seq_numbers(s, SSL3_CC_READ);
432
433         if (s->version == DTLS1_BAD_VER)
434             s->d1->handshake_read_seq++;
435
436 #ifndef OPENSSL_NO_SCTP
437         /*
438          * Remember that a CCS has been received, so that an old key of
439          * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
440          * SCTP is used
441          */
442         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
443 #endif
444     }
445
446     return MSG_PROCESS_CONTINUE_READING;
447  f_err:
448     ssl3_send_alert(s, SSL3_AL_FATAL, al);
449     ossl_statem_set_error(s);
450     return MSG_PROCESS_ERROR;
451 }
452
453 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
454 {
455     int al = SSL_AD_INTERNAL_ERROR;
456     size_t md_len;
457
458     /* If this occurs, we have missed a message */
459     if (!SSL_IS_TLS13(s) && !s->s3->change_cipher_spec) {
460         al = SSL_AD_UNEXPECTED_MESSAGE;
461         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
462         goto f_err;
463     }
464     s->s3->change_cipher_spec = 0;
465
466     md_len = s->s3->tmp.peer_finish_md_len;
467
468     if (md_len != PACKET_remaining(pkt)) {
469         al = SSL_AD_DECODE_ERROR;
470         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
471         goto f_err;
472     }
473
474     if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md,
475                       md_len) != 0) {
476         al = SSL_AD_DECRYPT_ERROR;
477         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
478         goto f_err;
479     }
480
481     /*
482      * Copy the finished so we can use it for renegotiation checks
483      */
484     if (s->server) {
485         OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
486         memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md,
487                md_len);
488         s->s3->previous_client_finished_len = md_len;
489     } else {
490         OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
491         memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md,
492                md_len);
493         s->s3->previous_server_finished_len = md_len;
494     }
495
496     /*
497      * In TLS1.3 we also have to change cipher state and do any final processing
498      * of the initial server flight (if we are a client)
499      */
500     if (SSL_IS_TLS13(s)) {
501         if (s->server) {
502             if (!s->method->ssl3_enc->change_cipher_state(s,
503                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
504                 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
505                 goto f_err;
506             }
507         } else {
508             if (!s->method->ssl3_enc->generate_master_secret(s,
509                     s->session->master_key, s->handshake_secret, 0,
510                     &s->session->master_key_length)) {
511                 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
512                 goto f_err;
513             }
514             if (!s->method->ssl3_enc->change_cipher_state(s,
515                     SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
516                 SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_CANNOT_CHANGE_CIPHER);
517                 goto f_err;
518             }
519             if (!tls_process_initial_server_flight(s, &al))
520                 goto f_err;
521         }
522     }
523
524     return MSG_PROCESS_FINISHED_READING;
525  f_err:
526     ssl3_send_alert(s, SSL3_AL_FATAL, al);
527     ossl_statem_set_error(s);
528     return MSG_PROCESS_ERROR;
529 }
530
531 int tls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
532 {
533     if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
534         SSLerr(SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
535         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
536         return 0;
537     }
538
539     return 1;
540 }
541
542 /* Add a certificate to the WPACKET */
543 static int ssl_add_cert_to_wpacket(SSL *s, WPACKET *pkt, X509 *x, int chain,
544                                    int *al)
545 {
546     int len;
547     unsigned char *outbytes;
548
549     len = i2d_X509(x, NULL);
550     if (len < 0) {
551         SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_BUF_LIB);
552         *al = SSL_AD_INTERNAL_ERROR;
553         return 0;
554     }
555     if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
556             || i2d_X509(x, &outbytes) != len) {
557         SSLerr(SSL_F_SSL_ADD_CERT_TO_WPACKET, ERR_R_INTERNAL_ERROR);
558         *al = SSL_AD_INTERNAL_ERROR;
559         return 0;
560     }
561
562     if (SSL_IS_TLS13(s)
563             && !tls_construct_extensions(s, pkt, EXT_TLS1_3_CERTIFICATE, x,
564                                          chain, al))
565         return 0;
566
567     return 1;
568 }
569
570 /* Add certificate chain to provided WPACKET */
571 static int ssl_add_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk, int *al)
572 {
573     int i, chain_count;
574     X509 *x;
575     STACK_OF(X509) *extra_certs;
576     STACK_OF(X509) *chain = NULL;
577     X509_STORE *chain_store;
578     int tmpal = SSL_AD_INTERNAL_ERROR;
579
580     if (cpk == NULL || cpk->x509 == NULL)
581         return 1;
582
583     x = cpk->x509;
584
585     /*
586      * If we have a certificate specific chain use it, else use parent ctx.
587      */
588     if (cpk->chain != NULL)
589         extra_certs = cpk->chain;
590     else
591         extra_certs = s->ctx->extra_certs;
592
593     if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
594         chain_store = NULL;
595     else if (s->cert->chain_store)
596         chain_store = s->cert->chain_store;
597     else
598         chain_store = s->ctx->cert_store;
599
600     if (chain_store != NULL) {
601         X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new();
602
603         if (xs_ctx == NULL) {
604             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
605             goto err;
606         }
607         if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
608             X509_STORE_CTX_free(xs_ctx);
609             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
610             goto err;
611         }
612         /*
613          * It is valid for the chain not to be complete (because normally we
614          * don't include the root cert in the chain). Therefore we deliberately
615          * ignore the error return from this call. We're not actually verifying
616          * the cert - we're just building as much of the chain as we can
617          */
618         (void)X509_verify_cert(xs_ctx);
619         /* Don't leave errors in the queue */
620         ERR_clear_error();
621         chain = X509_STORE_CTX_get0_chain(xs_ctx);
622         i = ssl_security_cert_chain(s, chain, NULL, 0);
623         if (i != 1) {
624 #if 0
625             /* Dummy error calls so mkerr generates them */
626             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
627             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
628             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
629 #endif
630             X509_STORE_CTX_free(xs_ctx);
631             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
632             goto err;
633         }
634         chain_count = sk_X509_num(chain);
635         for (i = 0; i < chain_count; i++) {
636             x = sk_X509_value(chain, i);
637
638             if (!ssl_add_cert_to_wpacket(s, pkt, x, i, &tmpal)) {
639                 X509_STORE_CTX_free(xs_ctx);
640                 goto err;
641             }
642         }
643         X509_STORE_CTX_free(xs_ctx);
644     } else {
645         i = ssl_security_cert_chain(s, extra_certs, x, 0);
646         if (i != 1) {
647             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
648             goto err;
649         }
650         if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, &tmpal))
651             goto err;
652         for (i = 0; i < sk_X509_num(extra_certs); i++) {
653             x = sk_X509_value(extra_certs, i);
654             if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, &tmpal))
655                 goto err;
656         }
657     }
658     return 1;
659
660  err:
661     *al = tmpal;
662     return 0;
663 }
664
665 unsigned long ssl3_output_cert_chain(SSL *s, WPACKET *pkt, CERT_PKEY *cpk,
666                                      int *al)
667 {
668     int tmpal = SSL_AD_INTERNAL_ERROR;
669
670     if (!WPACKET_start_sub_packet_u24(pkt)
671             || !ssl_add_cert_chain(s, pkt, cpk, &tmpal)
672             || !WPACKET_close(pkt)) {
673         SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
674         *al = tmpal;
675         return 0;
676     }
677     return 1;
678 }
679
680 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst)
681 {
682     void (*cb) (const SSL *ssl, int type, int val) = NULL;
683
684 #ifndef OPENSSL_NO_SCTP
685     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
686         WORK_STATE ret;
687         ret = dtls_wait_for_dry(s);
688         if (ret != WORK_FINISHED_CONTINUE)
689             return ret;
690     }
691 #endif
692
693     /* clean a few things up */
694     ssl3_cleanup_key_block(s);
695
696     if (!SSL_IS_DTLS(s)) {
697         /*
698          * We don't do this in DTLS because we may still need the init_buf
699          * in case there are any unexpected retransmits
700          */
701         BUF_MEM_free(s->init_buf);
702         s->init_buf = NULL;
703     }
704
705     ssl_free_wbio_buffer(s);
706
707     s->init_num = 0;
708
709     if (!s->server || s->renegotiate == 2) {
710         /* skipped if we just sent a HelloRequest */
711         s->renegotiate = 0;
712         s->new_session = 0;
713
714         if (s->server) {
715             ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
716
717             s->ctx->stats.sess_accept_good++;
718             s->handshake_func = ossl_statem_accept;
719         } else {
720             ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
721             if (s->hit)
722                 s->ctx->stats.sess_hit++;
723
724             s->handshake_func = ossl_statem_connect;
725             s->ctx->stats.sess_connect_good++;
726         }
727
728         if (s->info_callback != NULL)
729             cb = s->info_callback;
730         else if (s->ctx->info_callback != NULL)
731             cb = s->ctx->info_callback;
732
733         if (cb != NULL)
734             cb(s, SSL_CB_HANDSHAKE_DONE, 1);
735
736         if (SSL_IS_DTLS(s)) {
737             /* done with handshaking */
738             s->d1->handshake_read_seq = 0;
739             s->d1->handshake_write_seq = 0;
740             s->d1->next_handshake_write_seq = 0;
741             dtls1_clear_received_buffer(s);
742         }
743     }
744
745     return WORK_FINISHED_STOP;
746 }
747
748 int tls_get_message_header(SSL *s, int *mt)
749 {
750     /* s->init_num < SSL3_HM_HEADER_LENGTH */
751     int skip_message, i, recvd_type, al;
752     unsigned char *p;
753     size_t l, readbytes;
754
755     p = (unsigned char *)s->init_buf->data;
756
757     do {
758         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
759             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
760                                           &p[s->init_num],
761                                           SSL3_HM_HEADER_LENGTH - s->init_num,
762                                           0, &readbytes);
763             if (i <= 0) {
764                 s->rwstate = SSL_READING;
765                 return 0;
766             }
767             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
768                 /*
769                  * A ChangeCipherSpec must be a single byte and may not occur
770                  * in the middle of a handshake message.
771                  */
772                 if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
773                     al = SSL_AD_UNEXPECTED_MESSAGE;
774                     SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
775                            SSL_R_BAD_CHANGE_CIPHER_SPEC);
776                     goto f_err;
777                 }
778                 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
779                 s->init_num = readbytes - 1;
780                 s->init_msg = s->init_buf->data;
781                 s->s3->tmp.message_size = readbytes;
782                 return 1;
783             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
784                 al = SSL_AD_UNEXPECTED_MESSAGE;
785                 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
786                 goto f_err;
787             }
788             s->init_num += readbytes;
789         }
790
791         skip_message = 0;
792         if (!s->server)
793             if (p[0] == SSL3_MT_HELLO_REQUEST)
794                 /*
795                  * The server may always send 'Hello Request' messages --
796                  * we are doing a handshake anyway now, so ignore them if
797                  * their format is correct. Does not count for 'Finished'
798                  * MAC.
799                  */
800                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
801                     s->init_num = 0;
802                     skip_message = 1;
803
804                     if (s->msg_callback)
805                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
806                                         p, SSL3_HM_HEADER_LENGTH, s,
807                                         s->msg_callback_arg);
808                 }
809     } while (skip_message);
810     /* s->init_num == SSL3_HM_HEADER_LENGTH */
811
812     *mt = *p;
813     s->s3->tmp.message_type = *(p++);
814
815     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
816         /*
817          * Only happens with SSLv3+ in an SSLv2 backward compatible
818          * ClientHello
819          *
820          * Total message size is the remaining record bytes to read
821          * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
822          */
823         l = RECORD_LAYER_get_rrec_length(&s->rlayer)
824             + SSL3_HM_HEADER_LENGTH;
825         s->s3->tmp.message_size = l;
826
827         s->init_msg = s->init_buf->data;
828         s->init_num = SSL3_HM_HEADER_LENGTH;
829     } else {
830         n2l3(p, l);
831         /* BUF_MEM_grow takes an 'int' parameter */
832         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
833             al = SSL_AD_ILLEGAL_PARAMETER;
834             SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
835             goto f_err;
836         }
837         s->s3->tmp.message_size = l;
838
839         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
840         s->init_num = 0;
841     }
842
843     return 1;
844  f_err:
845     ssl3_send_alert(s, SSL3_AL_FATAL, al);
846     return 0;
847 }
848
849 int tls_get_message_body(SSL *s, size_t *len)
850 {
851     size_t n, readbytes;
852     unsigned char *p;
853     int i;
854
855     if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
856         /* We've already read everything in */
857         *len = (unsigned long)s->init_num;
858         return 1;
859     }
860
861     p = s->init_msg;
862     n = s->s3->tmp.message_size - s->init_num;
863     while (n > 0) {
864         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
865                                       &p[s->init_num], n, 0, &readbytes);
866         if (i <= 0) {
867             s->rwstate = SSL_READING;
868             *len = 0;
869             return 0;
870         }
871         s->init_num += readbytes;
872         n -= readbytes;
873     }
874
875 #ifndef OPENSSL_NO_NEXTPROTONEG
876     /*
877      * If receiving Finished, record MAC of prior handshake messages for
878      * Finished verification.
879      */
880     if (*s->init_buf->data == SSL3_MT_FINISHED)
881         ssl3_take_mac(s);
882 #endif
883
884     /* Feed this message into MAC computation. */
885     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
886         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
887                              s->init_num)) {
888             SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
889             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
890             *len = 0;
891             return 0;
892         }
893         if (s->msg_callback)
894             s->msg_callback(0, SSL2_VERSION, 0, s->init_buf->data,
895                             (size_t)s->init_num, s, s->msg_callback_arg);
896     } else {
897         if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
898                              s->init_num + SSL3_HM_HEADER_LENGTH)) {
899             SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_EVP_LIB);
900             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
901             *len = 0;
902             return 0;
903         }
904         if (s->msg_callback)
905             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
906                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
907                             s->msg_callback_arg);
908     }
909
910     *len = s->init_num;
911     return 1;
912 }
913
914 int ssl_cert_type(const X509 *x, const EVP_PKEY *pk)
915 {
916     if (pk == NULL && (pk = X509_get0_pubkey(x)) == NULL)
917         return -1;
918
919     switch (EVP_PKEY_id(pk)) {
920     default:
921         return -1;
922     case EVP_PKEY_RSA:
923         return SSL_PKEY_RSA_ENC;
924     case EVP_PKEY_DSA:
925         return SSL_PKEY_DSA_SIGN;
926 #ifndef OPENSSL_NO_EC
927     case EVP_PKEY_EC:
928         return SSL_PKEY_ECC;
929 #endif
930 #ifndef OPENSSL_NO_GOST
931     case NID_id_GostR3410_2001:
932         return SSL_PKEY_GOST01;
933     case NID_id_GostR3410_2012_256:
934         return SSL_PKEY_GOST12_256;
935     case NID_id_GostR3410_2012_512:
936         return SSL_PKEY_GOST12_512;
937 #endif
938     }
939 }
940
941 int ssl_verify_alarm_type(long type)
942 {
943     int al;
944
945     switch (type) {
946     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
947     case X509_V_ERR_UNABLE_TO_GET_CRL:
948     case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
949         al = SSL_AD_UNKNOWN_CA;
950         break;
951     case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
952     case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
953     case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
954     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
955     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
956     case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
957     case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
958     case X509_V_ERR_CERT_NOT_YET_VALID:
959     case X509_V_ERR_CRL_NOT_YET_VALID:
960     case X509_V_ERR_CERT_UNTRUSTED:
961     case X509_V_ERR_CERT_REJECTED:
962     case X509_V_ERR_HOSTNAME_MISMATCH:
963     case X509_V_ERR_EMAIL_MISMATCH:
964     case X509_V_ERR_IP_ADDRESS_MISMATCH:
965     case X509_V_ERR_DANE_NO_MATCH:
966     case X509_V_ERR_EE_KEY_TOO_SMALL:
967     case X509_V_ERR_CA_KEY_TOO_SMALL:
968     case X509_V_ERR_CA_MD_TOO_WEAK:
969         al = SSL_AD_BAD_CERTIFICATE;
970         break;
971     case X509_V_ERR_CERT_SIGNATURE_FAILURE:
972     case X509_V_ERR_CRL_SIGNATURE_FAILURE:
973         al = SSL_AD_DECRYPT_ERROR;
974         break;
975     case X509_V_ERR_CERT_HAS_EXPIRED:
976     case X509_V_ERR_CRL_HAS_EXPIRED:
977         al = SSL_AD_CERTIFICATE_EXPIRED;
978         break;
979     case X509_V_ERR_CERT_REVOKED:
980         al = SSL_AD_CERTIFICATE_REVOKED;
981         break;
982     case X509_V_ERR_UNSPECIFIED:
983     case X509_V_ERR_OUT_OF_MEM:
984     case X509_V_ERR_INVALID_CALL:
985     case X509_V_ERR_STORE_LOOKUP:
986         al = SSL_AD_INTERNAL_ERROR;
987         break;
988     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
989     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
990     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
991     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
992     case X509_V_ERR_CERT_CHAIN_TOO_LONG:
993     case X509_V_ERR_PATH_LENGTH_EXCEEDED:
994     case X509_V_ERR_INVALID_CA:
995         al = SSL_AD_UNKNOWN_CA;
996         break;
997     case X509_V_ERR_APPLICATION_VERIFICATION:
998         al = SSL_AD_HANDSHAKE_FAILURE;
999         break;
1000     case X509_V_ERR_INVALID_PURPOSE:
1001         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
1002         break;
1003     default:
1004         al = SSL_AD_CERTIFICATE_UNKNOWN;
1005         break;
1006     }
1007     return (al);
1008 }
1009
1010 int ssl_allow_compression(SSL *s)
1011 {
1012     if (s->options & SSL_OP_NO_COMPRESSION)
1013         return 0;
1014     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1015 }
1016
1017 static int version_cmp(const SSL *s, int a, int b)
1018 {
1019     int dtls = SSL_IS_DTLS(s);
1020
1021     if (a == b)
1022         return 0;
1023     if (!dtls)
1024         return a < b ? -1 : 1;
1025     return DTLS_VERSION_LT(a, b) ? -1 : 1;
1026 }
1027
1028 typedef struct {
1029     int version;
1030     const SSL_METHOD *(*cmeth) (void);
1031     const SSL_METHOD *(*smeth) (void);
1032 } version_info;
1033
1034 #if TLS_MAX_VERSION != TLS1_3_VERSION
1035 # error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1036 #endif
1037
1038 static const version_info tls_version_table[] = {
1039 #ifndef OPENSSL_NO_TLS1_3
1040     {TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method},
1041 #else
1042     {TLS1_3_VERSION, NULL, NULL},
1043 #endif
1044 #ifndef OPENSSL_NO_TLS1_2
1045     {TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method},
1046 #else
1047     {TLS1_2_VERSION, NULL, NULL},
1048 #endif
1049 #ifndef OPENSSL_NO_TLS1_1
1050     {TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method},
1051 #else
1052     {TLS1_1_VERSION, NULL, NULL},
1053 #endif
1054 #ifndef OPENSSL_NO_TLS1
1055     {TLS1_VERSION, tlsv1_client_method, tlsv1_server_method},
1056 #else
1057     {TLS1_VERSION, NULL, NULL},
1058 #endif
1059 #ifndef OPENSSL_NO_SSL3
1060     {SSL3_VERSION, sslv3_client_method, sslv3_server_method},
1061 #else
1062     {SSL3_VERSION, NULL, NULL},
1063 #endif
1064     {0, NULL, NULL},
1065 };
1066
1067 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
1068 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1069 #endif
1070
1071 static const version_info dtls_version_table[] = {
1072 #ifndef OPENSSL_NO_DTLS1_2
1073     {DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method},
1074 #else
1075     {DTLS1_2_VERSION, NULL, NULL},
1076 #endif
1077 #ifndef OPENSSL_NO_DTLS1
1078     {DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method},
1079     {DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL},
1080 #else
1081     {DTLS1_VERSION, NULL, NULL},
1082     {DTLS1_BAD_VER, NULL, NULL},
1083 #endif
1084     {0, NULL, NULL},
1085 };
1086
1087 /*
1088  * ssl_method_error - Check whether an SSL_METHOD is enabled.
1089  *
1090  * @s: The SSL handle for the candidate method
1091  * @method: the intended method.
1092  *
1093  * Returns 0 on success, or an SSL error reason on failure.
1094  */
1095 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
1096 {
1097     int version = method->version;
1098
1099     if ((s->min_proto_version != 0 &&
1100          version_cmp(s, version, s->min_proto_version) < 0) ||
1101         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1102         return SSL_R_VERSION_TOO_LOW;
1103
1104     if (s->max_proto_version != 0 &&
1105         version_cmp(s, version, s->max_proto_version) > 0)
1106         return SSL_R_VERSION_TOO_HIGH;
1107
1108     if ((s->options & method->mask) != 0)
1109         return SSL_R_UNSUPPORTED_PROTOCOL;
1110     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1111         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1112     else if ((method->flags & SSL_METHOD_NO_FIPS) != 0 && FIPS_mode())
1113         return SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE;
1114
1115     return 0;
1116 }
1117
1118 /*
1119  * ssl_version_supported - Check that the specified `version` is supported by
1120  * `SSL *` instance
1121  *
1122  * @s: The SSL handle for the candidate method
1123  * @version: Protocol version to test against
1124  *
1125  * Returns 1 when supported, otherwise 0
1126  */
1127 int ssl_version_supported(const SSL *s, int version)
1128 {
1129     const version_info *vent;
1130     const version_info *table;
1131
1132     switch (s->method->version) {
1133     default:
1134         /* Version should match method version for non-ANY method */
1135         return version_cmp(s, version, s->version) == 0;
1136     case TLS_ANY_VERSION:
1137         table = tls_version_table;
1138         break;
1139     case DTLS_ANY_VERSION:
1140         table = dtls_version_table;
1141         break;
1142     }
1143
1144     for (vent = table;
1145          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
1146          ++vent) {
1147         if (vent->cmeth != NULL &&
1148             version_cmp(s, version, vent->version) == 0 &&
1149             ssl_method_error(s, vent->cmeth()) == 0) {
1150             return 1;
1151         }
1152     }
1153     return 0;
1154 }
1155
1156 /*
1157  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
1158  * fallback indication from a client check whether we're using the highest
1159  * supported protocol version.
1160  *
1161  * @s server SSL handle.
1162  *
1163  * Returns 1 when using the highest enabled version, 0 otherwise.
1164  */
1165 int ssl_check_version_downgrade(SSL *s)
1166 {
1167     const version_info *vent;
1168     const version_info *table;
1169
1170     /*
1171      * Check that the current protocol is the highest enabled version
1172      * (according to s->ctx->method, as version negotiation may have changed
1173      * s->method).
1174      */
1175     if (s->version == s->ctx->method->version)
1176         return 1;
1177
1178     /*
1179      * Apparently we're using a version-flexible SSL_METHOD (not at its
1180      * highest protocol version).
1181      */
1182     if (s->ctx->method->version == TLS_method()->version)
1183         table = tls_version_table;
1184     else if (s->ctx->method->version == DTLS_method()->version)
1185         table = dtls_version_table;
1186     else {
1187         /* Unexpected state; fail closed. */
1188         return 0;
1189     }
1190
1191     for (vent = table; vent->version != 0; ++vent) {
1192         if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
1193             return s->version == vent->version;
1194     }
1195     return 0;
1196 }
1197
1198 /*
1199  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
1200  * protocols, provided the initial (D)TLS method is version-flexible.  This
1201  * function sanity-checks the proposed value and makes sure the method is
1202  * version-flexible, then sets the limit if all is well.
1203  *
1204  * @method_version: The version of the current SSL_METHOD.
1205  * @version: the intended limit.
1206  * @bound: pointer to limit to be updated.
1207  *
1208  * Returns 1 on success, 0 on failure.
1209  */
1210 int ssl_set_version_bound(int method_version, int version, int *bound)
1211 {
1212     if (version == 0) {
1213         *bound = version;
1214         return 1;
1215     }
1216
1217     /*-
1218      * Restrict TLS methods to TLS protocol versions.
1219      * Restrict DTLS methods to DTLS protocol versions.
1220      * Note, DTLS version numbers are decreasing, use comparison macros.
1221      *
1222      * Note that for both lower-bounds we use explicit versions, not
1223      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
1224      * configurations.  If the MIN (supported) version ever rises, the user's
1225      * "floor" remains valid even if no longer available.  We don't expect the
1226      * MAX ceiling to ever get lower, so making that variable makes sense.
1227      */
1228     switch (method_version) {
1229     default:
1230         /*
1231          * XXX For fixed version methods, should we always fail and not set any
1232          * bounds, always succeed and not set any bounds, or set the bounds and
1233          * arrange to fail later if they are not met?  At present fixed-version
1234          * methods are not subject to controls that disable individual protocol
1235          * versions.
1236          */
1237         return 0;
1238
1239     case TLS_ANY_VERSION:
1240         if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
1241             return 0;
1242         break;
1243
1244     case DTLS_ANY_VERSION:
1245         if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
1246             DTLS_VERSION_LT(version, DTLS1_BAD_VER))
1247             return 0;
1248         break;
1249     }
1250
1251     *bound = version;
1252     return 1;
1253 }
1254
1255 /*
1256  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
1257  * client HELLO is received to select the final server protocol version and
1258  * the version specific method.
1259  *
1260  * @s: server SSL handle.
1261  *
1262  * Returns 0 on success or an SSL error reason number on failure.
1263  */
1264 int ssl_choose_server_version(SSL *s, CLIENTHELLO_MSG *hello)
1265 {
1266     /*-
1267      * With version-flexible methods we have an initial state with:
1268      *
1269      *   s->method->version == (D)TLS_ANY_VERSION,
1270      *   s->version == (D)TLS_MAX_VERSION.
1271      *
1272      * So we detect version-flexible methods via the method version, not the
1273      * handle version.
1274      */
1275     int server_version = s->method->version;
1276     int client_version = hello->legacy_version;
1277     const version_info *vent;
1278     const version_info *table;
1279     int disabled = 0;
1280     RAW_EXTENSION *suppversions;
1281
1282     s->client_version = client_version;
1283
1284     switch (server_version) {
1285     default:
1286         /*
1287          * TODO(TLS1.3): This check will fail if someone attempts to do
1288          * renegotiation in TLS1.3 at the moment. We need to ensure we disable
1289          * renegotiation for TLS1.3
1290          */
1291         if (version_cmp(s, client_version, s->version) < 0)
1292             return SSL_R_WRONG_SSL_VERSION;
1293         /*
1294          * If this SSL handle is not from a version flexible method we don't
1295          * (and never did) check min/max FIPS or Suite B constraints.  Hope
1296          * that's OK.  It is up to the caller to not choose fixed protocol
1297          * versions they don't want.  If not, then easy to fix, just return
1298          * ssl_method_error(s, s->method)
1299          */
1300         return 0;
1301     case TLS_ANY_VERSION:
1302         table = tls_version_table;
1303         break;
1304     case DTLS_ANY_VERSION:
1305         table = dtls_version_table;
1306         break;
1307     }
1308
1309     suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
1310
1311     if (suppversions->present && !SSL_IS_DTLS(s)) {
1312         unsigned int candidate_vers = 0;
1313         unsigned int best_vers = 0;
1314         const SSL_METHOD *best_method = NULL;
1315         PACKET versionslist;
1316
1317         suppversions->parsed = 1;
1318
1319         if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
1320             /* Trailing or invalid data? */
1321             return SSL_R_LENGTH_MISMATCH;
1322         }
1323
1324         while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
1325             /* TODO(TLS1.3): Remove this before release */
1326             if (candidate_vers == TLS1_3_VERSION_DRAFT)
1327                 candidate_vers = TLS1_3_VERSION;
1328             /*
1329              * TODO(TLS1.3): There is some discussion on the TLS list about
1330              * wheter to ignore versions <TLS1.2 in supported_versions. At the
1331              * moment we honour them if present. To be reviewed later
1332              */
1333             if (version_cmp(s, candidate_vers, best_vers) <= 0)
1334                 continue;
1335             for (vent = table;
1336                  vent->version != 0 && vent->version != (int)candidate_vers;
1337                  ++vent)
1338                 continue;
1339             if (vent->version != 0 && vent->smeth != NULL) {
1340                 const SSL_METHOD *method;
1341
1342                 method = vent->smeth();
1343                 if (ssl_method_error(s, method) == 0) {
1344                     best_vers = candidate_vers;
1345                     best_method = method;
1346                 }
1347             }
1348         }
1349         if (PACKET_remaining(&versionslist) != 0) {
1350             /* Trailing data? */
1351             return SSL_R_LENGTH_MISMATCH;
1352         }
1353
1354         if (best_vers > 0) {
1355             s->version = best_vers;
1356             s->method = best_method;
1357             return 0;
1358         }
1359         return SSL_R_UNSUPPORTED_PROTOCOL;
1360     }
1361
1362     /*
1363      * If the supported versions extension isn't present, then the highest
1364      * version we can negotiate is TLSv1.2
1365      */
1366     if (version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
1367         client_version = TLS1_2_VERSION;
1368
1369     /*
1370      * No supported versions extension, so we just use the version supplied in
1371      * the ClientHello.
1372      */
1373     for (vent = table; vent->version != 0; ++vent) {
1374         const SSL_METHOD *method;
1375
1376         if (vent->smeth == NULL ||
1377             version_cmp(s, client_version, vent->version) < 0)
1378             continue;
1379         method = vent->smeth();
1380         if (ssl_method_error(s, method) == 0) {
1381             s->version = vent->version;
1382             s->method = method;
1383             return 0;
1384         }
1385         disabled = 1;
1386     }
1387     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
1388 }
1389
1390 /*
1391  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
1392  * server HELLO is received to select the final client protocol version and
1393  * the version specific method.
1394  *
1395  * @s: client SSL handle.
1396  * @version: The proposed version from the server's HELLO.
1397  *
1398  * Returns 0 on success or an SSL error reason number on failure.
1399  */
1400 int ssl_choose_client_version(SSL *s, int version)
1401 {
1402     const version_info *vent;
1403     const version_info *table;
1404
1405     /* TODO(TLS1.3): Remove this before release */
1406     if (version == TLS1_3_VERSION_DRAFT)
1407         version = TLS1_3_VERSION;
1408
1409     switch (s->method->version) {
1410     default:
1411         if (version != s->version)
1412             return SSL_R_WRONG_SSL_VERSION;
1413         /*
1414          * If this SSL handle is not from a version flexible method we don't
1415          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
1416          * that's OK.  It is up to the caller to not choose fixed protocol
1417          * versions they don't want.  If not, then easy to fix, just return
1418          * ssl_method_error(s, s->method)
1419          */
1420         return 0;
1421     case TLS_ANY_VERSION:
1422         table = tls_version_table;
1423         break;
1424     case DTLS_ANY_VERSION:
1425         table = dtls_version_table;
1426         break;
1427     }
1428
1429     for (vent = table; vent->version != 0; ++vent) {
1430         const SSL_METHOD *method;
1431         int err;
1432
1433         if (version != vent->version)
1434             continue;
1435         if (vent->cmeth == NULL)
1436             break;
1437         method = vent->cmeth();
1438         err = ssl_method_error(s, method);
1439         if (err != 0)
1440             return err;
1441         s->method = method;
1442         s->version = version;
1443         return 0;
1444     }
1445
1446     return SSL_R_UNSUPPORTED_PROTOCOL;
1447 }
1448
1449 /*
1450  * ssl_get_client_min_max_version - get minimum and maximum client version
1451  * @s: The SSL connection
1452  * @min_version: The minimum supported version
1453  * @max_version: The maximum supported version
1454  *
1455  * Work out what version we should be using for the initial ClientHello if the
1456  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
1457  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
1458  * or FIPS_mode() constraints and any floor imposed by the security level here,
1459  * so we don't advertise the wrong protocol version to only reject the outcome later.
1460  *
1461  * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
1462  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
1463  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
1464  *
1465  * Returns 0 on success or an SSL error reason number on failure.  On failure
1466  * min_version and max_version will also be set to 0.
1467  */
1468 int ssl_get_client_min_max_version(const SSL *s, int *min_version,
1469                                    int *max_version)
1470 {
1471     int version;
1472     int hole;
1473     const SSL_METHOD *single = NULL;
1474     const SSL_METHOD *method;
1475     const version_info *table;
1476     const version_info *vent;
1477
1478     switch (s->method->version) {
1479     default:
1480         /*
1481          * If this SSL handle is not from a version flexible method we don't
1482          * (and never did) check min/max FIPS or Suite B constraints.  Hope
1483          * that's OK.  It is up to the caller to not choose fixed protocol
1484          * versions they don't want.  If not, then easy to fix, just return
1485          * ssl_method_error(s, s->method)
1486          */
1487         *min_version = *max_version = s->version;
1488         return 0;
1489     case TLS_ANY_VERSION:
1490         table = tls_version_table;
1491         break;
1492     case DTLS_ANY_VERSION:
1493         table = dtls_version_table;
1494         break;
1495     }
1496
1497     /*
1498      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1499      * below X enabled. This is required in order to maintain the "version
1500      * capability" vector contiguous. Any versions with a NULL client method
1501      * (protocol version client is disabled at compile-time) is also a "hole".
1502      *
1503      * Our initial state is hole == 1, version == 0.  That is, versions above
1504      * the first version in the method table are disabled (a "hole" above
1505      * the valid protocol entries) and we don't have a selected version yet.
1506      *
1507      * Whenever "hole == 1", and we hit an enabled method, its version becomes
1508      * the selected version, and the method becomes a candidate "single"
1509      * method.  We're no longer in a hole, so "hole" becomes 0.
1510      *
1511      * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1512      * as we support a contiguous range of at least two methods.  If we hit
1513      * a disabled method, then hole becomes true again, but nothing else
1514      * changes yet, because all the remaining methods may be disabled too.
1515      * If we again hit an enabled method after the new hole, it becomes
1516      * selected, as we start from scratch.
1517      */
1518     *min_version = version = 0;
1519     hole = 1;
1520     for (vent = table; vent->version != 0; ++vent) {
1521         /*
1522          * A table entry with a NULL client method is still a hole in the
1523          * "version capability" vector.
1524          */
1525         if (vent->cmeth == NULL) {
1526             hole = 1;
1527             continue;
1528         }
1529         method = vent->cmeth();
1530         if (ssl_method_error(s, method) != 0) {
1531             hole = 1;
1532         } else if (!hole) {
1533             single = NULL;
1534             *min_version = method->version;
1535         } else {
1536             version = (single = method)->version;
1537             *min_version = version;
1538             hole = 0;
1539         }
1540     }
1541
1542     *max_version = version;
1543
1544     /* Fail if everything is disabled */
1545     if (version == 0)
1546         return SSL_R_NO_PROTOCOLS_AVAILABLE;
1547
1548     return 0;
1549 }
1550
1551 /*
1552  * ssl_set_client_hello_version - Work out what version we should be using for
1553  * the initial ClientHello.legacy_version field.
1554  *
1555  * @s: client SSL handle.
1556  *
1557  * Returns 0 on success or an SSL error reason number on failure.
1558  */
1559 int ssl_set_client_hello_version(SSL *s)
1560 {
1561     int ver_min, ver_max, ret;
1562
1563     ret = ssl_get_client_min_max_version(s, &ver_min, &ver_max);
1564
1565     if (ret != 0)
1566         return ret;
1567
1568     s->version = ver_max;
1569
1570     /* TLS1.3 always uses TLS1.2 in the legacy_version field */
1571     if (!SSL_IS_DTLS(s) && ver_max > TLS1_2_VERSION)
1572         ver_max = TLS1_2_VERSION;
1573
1574     s->client_version = ver_max;
1575     return 0;
1576 }