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