Useless header include of openssl/rand.h
[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
34     ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
35                            s->init_num);
36     if (ret < 0)
37         return (-1);
38     if (type == SSL3_RT_HANDSHAKE)
39         /*
40          * should not be done for 'Hello Request's, but in that case we'll
41          * ignore the result anyway
42          */
43         ssl3_finish_mac(s, (unsigned char *)&s->init_buf->data[s->init_off],
44                         ret);
45
46     if (ret == s->init_num) {
47         if (s->msg_callback)
48             s->msg_callback(1, s->version, type, s->init_buf->data,
49                             (size_t)(s->init_off + s->init_num), s,
50                             s->msg_callback_arg);
51         return (1);
52     }
53     s->init_off += ret;
54     s->init_num -= ret;
55     return (0);
56 }
57
58 int tls_construct_finished(SSL *s, const char *sender, int slen)
59 {
60     unsigned char *p;
61     int i;
62     unsigned long l;
63
64     p = ssl_handshake_start(s);
65
66     i = s->method->ssl3_enc->final_finish_mac(s,
67                                               sender, slen,
68                                               s->s3->tmp.finish_md);
69     if (i <= 0)
70         return 0;
71     s->s3->tmp.finish_md_len = i;
72     memcpy(p, s->s3->tmp.finish_md, i);
73     l = i;
74
75     /*
76      * Copy the finished so we can use it for renegotiation checks
77      */
78     if (!s->server) {
79         OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
80         memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md, i);
81         s->s3->previous_client_finished_len = i;
82     } else {
83         OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
84         memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md, i);
85         s->s3->previous_server_finished_len = i;
86     }
87
88     if (!ssl_set_handshake_header(s, SSL3_MT_FINISHED, l)) {
89         SSLerr(SSL_F_TLS_CONSTRUCT_FINISHED, ERR_R_INTERNAL_ERROR);
90         return 0;
91     }
92
93     return 1;
94 }
95
96 #ifndef OPENSSL_NO_NEXTPROTONEG
97 /*
98  * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
99  * to far.
100  */
101 static void ssl3_take_mac(SSL *s)
102 {
103     const char *sender;
104     int slen;
105     /*
106      * If no new cipher setup return immediately: other functions will set
107      * the appropriate error.
108      */
109     if (s->s3->tmp.new_cipher == NULL)
110         return;
111     if (!s->server) {
112         sender = s->method->ssl3_enc->server_finished_label;
113         slen = s->method->ssl3_enc->server_finished_label_len;
114     } else {
115         sender = s->method->ssl3_enc->client_finished_label;
116         slen = s->method->ssl3_enc->client_finished_label_len;
117     }
118
119     s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
120                                                                           sender,
121                                                                           slen,
122                                                                           s->s3->tmp.peer_finish_md);
123 }
124 #endif
125
126 MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL *s, PACKET *pkt)
127 {
128     int al;
129     long remain;
130
131     remain = PACKET_remaining(pkt);
132     /*
133      * 'Change Cipher Spec' is just a single byte, which should already have
134      * been consumed by ssl_get_message() so there should be no bytes left,
135      * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
136      */
137     if (SSL_IS_DTLS(s)) {
138         if ((s->version == DTLS1_BAD_VER
139                         && remain != DTLS1_CCS_HEADER_LENGTH + 1)
140                     || (s->version != DTLS1_BAD_VER
141                         && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
142                 al = SSL_AD_ILLEGAL_PARAMETER;
143                 SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
144                        SSL_R_BAD_CHANGE_CIPHER_SPEC);
145                 goto f_err;
146         }
147     } else {
148         if (remain != 0) {
149             al = SSL_AD_ILLEGAL_PARAMETER;
150             SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC,
151                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
152             goto f_err;
153         }
154     }
155
156     /* Check we have a cipher to change to */
157     if (s->s3->tmp.new_cipher == NULL) {
158         al = SSL_AD_UNEXPECTED_MESSAGE;
159         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, SSL_R_CCS_RECEIVED_EARLY);
160         goto f_err;
161     }
162
163     s->s3->change_cipher_spec = 1;
164     if (!ssl3_do_change_cipher_spec(s)) {
165         al = SSL_AD_INTERNAL_ERROR;
166         SSLerr(SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
167         goto f_err;
168     }
169
170     if (SSL_IS_DTLS(s)) {
171         dtls1_reset_seq_numbers(s, SSL3_CC_READ);
172
173         if (s->version == DTLS1_BAD_VER)
174             s->d1->handshake_read_seq++;
175
176 #ifndef OPENSSL_NO_SCTP
177         /*
178          * Remember that a CCS has been received, so that an old key of
179          * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
180          * SCTP is used
181          */
182         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
183 #endif
184     }
185
186     return MSG_PROCESS_CONTINUE_READING;
187  f_err:
188     ssl3_send_alert(s, SSL3_AL_FATAL, al);
189     ossl_statem_set_error(s);
190     return MSG_PROCESS_ERROR;
191 }
192
193 MSG_PROCESS_RETURN tls_process_finished(SSL *s, PACKET *pkt)
194 {
195     int al, i;
196
197     /* If this occurs, we have missed a message */
198     if (!s->s3->change_cipher_spec) {
199         al = SSL_AD_UNEXPECTED_MESSAGE;
200         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
201         goto f_err;
202     }
203     s->s3->change_cipher_spec = 0;
204
205     i = s->s3->tmp.peer_finish_md_len;
206
207     if ((unsigned long)i != PACKET_remaining(pkt)) {
208         al = SSL_AD_DECODE_ERROR;
209         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_BAD_DIGEST_LENGTH);
210         goto f_err;
211     }
212
213     if (CRYPTO_memcmp(PACKET_data(pkt), s->s3->tmp.peer_finish_md, i) != 0) {
214         al = SSL_AD_DECRYPT_ERROR;
215         SSLerr(SSL_F_TLS_PROCESS_FINISHED, SSL_R_DIGEST_CHECK_FAILED);
216         goto f_err;
217     }
218
219     /*
220      * Copy the finished so we can use it for renegotiation checks
221      */
222     if (s->server) {
223         OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
224         memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md, i);
225         s->s3->previous_client_finished_len = i;
226     } else {
227         OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
228         memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md, i);
229         s->s3->previous_server_finished_len = i;
230     }
231
232     return MSG_PROCESS_FINISHED_READING;
233  f_err:
234     ssl3_send_alert(s, SSL3_AL_FATAL, al);
235     ossl_statem_set_error(s);
236     return MSG_PROCESS_ERROR;
237 }
238
239 int tls_construct_change_cipher_spec(SSL *s)
240 {
241     unsigned char *p;
242
243     p = (unsigned char *)s->init_buf->data;
244     *p = SSL3_MT_CCS;
245     s->init_num = 1;
246     s->init_off = 0;
247
248     return 1;
249 }
250
251 unsigned long ssl3_output_cert_chain(SSL *s, CERT_PKEY *cpk)
252 {
253     unsigned char *p;
254     unsigned long l = 3 + SSL_HM_HEADER_LENGTH(s);
255
256     if (!ssl_add_cert_chain(s, cpk, &l))
257         return 0;
258
259     l -= 3 + SSL_HM_HEADER_LENGTH(s);
260     p = ssl_handshake_start(s);
261     l2n3(l, p);
262     l += 3;
263
264     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE, l)) {
265         SSLerr(SSL_F_SSL3_OUTPUT_CERT_CHAIN, ERR_R_INTERNAL_ERROR);
266         return 0;
267     }
268     return l + SSL_HM_HEADER_LENGTH(s);
269 }
270
271 WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst)
272 {
273     void (*cb) (const SSL *ssl, int type, int val) = NULL;
274
275 #ifndef OPENSSL_NO_SCTP
276     if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
277         WORK_STATE ret;
278         ret = dtls_wait_for_dry(s);
279         if (ret != WORK_FINISHED_CONTINUE)
280             return ret;
281     }
282 #endif
283
284     /* clean a few things up */
285     ssl3_cleanup_key_block(s);
286
287     if (!SSL_IS_DTLS(s)) {
288         /*
289          * We don't do this in DTLS because we may still need the init_buf
290          * in case there are any unexpected retransmits
291          */
292         BUF_MEM_free(s->init_buf);
293         s->init_buf = NULL;
294     }
295
296     ssl_free_wbio_buffer(s);
297
298     s->init_num = 0;
299
300     if (!s->server || s->renegotiate == 2) {
301         /* skipped if we just sent a HelloRequest */
302         s->renegotiate = 0;
303         s->new_session = 0;
304
305         if (s->server) {
306             ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
307
308             s->ctx->stats.sess_accept_good++;
309             s->handshake_func = ossl_statem_accept;
310         } else {
311             ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
312             if (s->hit)
313                 s->ctx->stats.sess_hit++;
314
315             s->handshake_func = ossl_statem_connect;
316             s->ctx->stats.sess_connect_good++;
317         }
318
319         if (s->info_callback != NULL)
320             cb = s->info_callback;
321         else if (s->ctx->info_callback != NULL)
322             cb = s->ctx->info_callback;
323
324         if (cb != NULL)
325             cb(s, SSL_CB_HANDSHAKE_DONE, 1);
326
327         if (SSL_IS_DTLS(s)) {
328             /* done with handshaking */
329             s->d1->handshake_read_seq = 0;
330             s->d1->handshake_write_seq = 0;
331             s->d1->next_handshake_write_seq = 0;
332         }
333     }
334
335     return WORK_FINISHED_STOP;
336 }
337
338 int tls_get_message_header(SSL *s, int *mt)
339 {
340     /* s->init_num < SSL3_HM_HEADER_LENGTH */
341     int skip_message, i, recvd_type, al;
342     unsigned char *p;
343     unsigned long l;
344
345     p = (unsigned char *)s->init_buf->data;
346
347     do {
348         while (s->init_num < SSL3_HM_HEADER_LENGTH) {
349             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type,
350                 &p[s->init_num], SSL3_HM_HEADER_LENGTH - s->init_num, 0);
351             if (i <= 0) {
352                 s->rwstate = SSL_READING;
353                 return 0;
354             }
355             if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
356                 /*
357                  * A ChangeCipherSpec must be a single byte and may not occur
358                  * in the middle of a handshake message.
359                  */
360                 if (s->init_num != 0 || i != 1 || p[0] != SSL3_MT_CCS) {
361                     al = SSL_AD_UNEXPECTED_MESSAGE;
362                     SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER,
363                            SSL_R_BAD_CHANGE_CIPHER_SPEC);
364                     goto f_err;
365                 }
366                 s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
367                 s->init_num = i - 1;
368                 s->s3->tmp.message_size = i;
369                 return 1;
370             } else if (recvd_type != SSL3_RT_HANDSHAKE) {
371                 al = SSL_AD_UNEXPECTED_MESSAGE;
372                 SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY);
373                 goto f_err;
374             }
375             s->init_num += i;
376         }
377
378         skip_message = 0;
379         if (!s->server)
380             if (p[0] == SSL3_MT_HELLO_REQUEST)
381                 /*
382                  * The server may always send 'Hello Request' messages --
383                  * we are doing a handshake anyway now, so ignore them if
384                  * their format is correct. Does not count for 'Finished'
385                  * MAC.
386                  */
387                 if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
388                     s->init_num = 0;
389                     skip_message = 1;
390
391                     if (s->msg_callback)
392                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
393                                         p, SSL3_HM_HEADER_LENGTH, s,
394                                         s->msg_callback_arg);
395                 }
396     } while (skip_message);
397     /* s->init_num == SSL3_HM_HEADER_LENGTH */
398
399     *mt = *p;
400     s->s3->tmp.message_type = *(p++);
401
402     if(RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
403         /*
404          * Only happens with SSLv3+ in an SSLv2 backward compatible
405          * ClientHello
406          */
407          /*
408           * Total message size is the remaining record bytes to read
409           * plus the SSL3_HM_HEADER_LENGTH bytes that we already read
410           */
411         l = RECORD_LAYER_get_rrec_length(&s->rlayer)
412             + SSL3_HM_HEADER_LENGTH;
413         if (l && !BUF_MEM_grow_clean(s->init_buf, (int)l)) {
414             SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB);
415             goto err;
416         }
417         s->s3->tmp.message_size = l;
418
419         s->init_msg = s->init_buf->data;
420         s->init_num = SSL3_HM_HEADER_LENGTH;
421     } else {
422         n2l3(p, l);
423         /* BUF_MEM_grow takes an 'int' parameter */
424         if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
425             al = SSL_AD_ILLEGAL_PARAMETER;
426             SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
427             goto f_err;
428         }
429         if (l && !BUF_MEM_grow_clean(s->init_buf,
430                                     (int)l + SSL3_HM_HEADER_LENGTH)) {
431             SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB);
432             goto err;
433         }
434         s->s3->tmp.message_size = l;
435
436         s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
437         s->init_num = 0;
438     }
439
440     return 1;
441  f_err:
442     ssl3_send_alert(s, SSL3_AL_FATAL, al);
443  err:
444     return 0;
445 }
446
447 int tls_get_message_body(SSL *s, unsigned long *len)
448 {
449     long n;
450     unsigned char *p;
451     int i;
452
453     if (s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
454         /* We've already read everything in */
455         *len = (unsigned long)s->init_num;
456         return 1;
457     }
458
459     p = s->init_msg;
460     n = s->s3->tmp.message_size - s->init_num;
461     while (n > 0) {
462         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
463                                       &p[s->init_num], n, 0);
464         if (i <= 0) {
465             s->rwstate = SSL_READING;
466             *len = 0;
467             return 0;
468         }
469         s->init_num += i;
470         n -= i;
471     }
472
473 #ifndef OPENSSL_NO_NEXTPROTONEG
474     /*
475      * If receiving Finished, record MAC of prior handshake messages for
476      * Finished verification.
477      */
478     if (*s->init_buf->data == SSL3_MT_FINISHED)
479         ssl3_take_mac(s);
480 #endif
481
482     /* Feed this message into MAC computation. */
483     if(RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
484         ssl3_finish_mac(s, (unsigned char *)s->init_buf->data, s->init_num);
485         if (s->msg_callback)
486             s->msg_callback(0, SSL2_VERSION, 0,  s->init_buf->data,
487                             (size_t)s->init_num, s, s->msg_callback_arg);
488     } else {
489         ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
490             s->init_num + SSL3_HM_HEADER_LENGTH);
491         if (s->msg_callback)
492             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
493                             (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s,
494                             s->msg_callback_arg);
495     }
496
497     /*
498      * init_num should never be negative...should probably be declared
499      * unsigned
500      */
501     if (s->init_num < 0) {
502         SSLerr(SSL_F_TLS_GET_MESSAGE_BODY, ERR_R_INTERNAL_ERROR);
503         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
504         *len = 0;
505         return 0;
506     }
507     *len = (unsigned long)s->init_num;
508     return 1;
509 }
510
511 int ssl_cert_type(X509 *x, EVP_PKEY *pk)
512 {
513     if (pk == NULL &&
514         (pk = X509_get0_pubkey(x)) == NULL)
515         return -1;
516
517     switch (EVP_PKEY_id(pk)) {
518     default:
519         return -1;
520     case EVP_PKEY_RSA:
521         return SSL_PKEY_RSA_ENC;
522     case EVP_PKEY_DSA:
523         return SSL_PKEY_DSA_SIGN;
524 #ifndef OPENSSL_NO_EC
525     case EVP_PKEY_EC:
526         return SSL_PKEY_ECC;
527 #endif
528 #ifndef OPENSSL_NO_GOST
529     case NID_id_GostR3410_2001:
530         return SSL_PKEY_GOST01;
531     case NID_id_GostR3410_2012_256:
532         return SSL_PKEY_GOST12_256;
533     case NID_id_GostR3410_2012_512:
534         return SSL_PKEY_GOST12_512;
535 #endif
536     }
537 }
538
539 int ssl_verify_alarm_type(long type)
540 {
541     int al;
542
543     switch (type) {
544     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
545     case X509_V_ERR_UNABLE_TO_GET_CRL:
546     case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
547         al = SSL_AD_UNKNOWN_CA;
548         break;
549     case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
550     case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
551     case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
552     case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
553     case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
554     case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
555     case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
556     case X509_V_ERR_CERT_NOT_YET_VALID:
557     case X509_V_ERR_CRL_NOT_YET_VALID:
558     case X509_V_ERR_CERT_UNTRUSTED:
559     case X509_V_ERR_CERT_REJECTED:
560     case X509_V_ERR_HOSTNAME_MISMATCH:
561     case X509_V_ERR_EMAIL_MISMATCH:
562     case X509_V_ERR_IP_ADDRESS_MISMATCH:
563     case X509_V_ERR_DANE_NO_MATCH:
564     case X509_V_ERR_EE_KEY_TOO_SMALL:
565     case X509_V_ERR_CA_KEY_TOO_SMALL:
566     case X509_V_ERR_CA_MD_TOO_WEAK:
567         al = SSL_AD_BAD_CERTIFICATE;
568         break;
569     case X509_V_ERR_CERT_SIGNATURE_FAILURE:
570     case X509_V_ERR_CRL_SIGNATURE_FAILURE:
571         al = SSL_AD_DECRYPT_ERROR;
572         break;
573     case X509_V_ERR_CERT_HAS_EXPIRED:
574     case X509_V_ERR_CRL_HAS_EXPIRED:
575         al = SSL_AD_CERTIFICATE_EXPIRED;
576         break;
577     case X509_V_ERR_CERT_REVOKED:
578         al = SSL_AD_CERTIFICATE_REVOKED;
579         break;
580     case X509_V_ERR_UNSPECIFIED:
581     case X509_V_ERR_OUT_OF_MEM:
582     case X509_V_ERR_INVALID_CALL:
583     case X509_V_ERR_STORE_LOOKUP:
584         al = SSL_AD_INTERNAL_ERROR;
585         break;
586     case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
587     case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
588     case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
589     case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
590     case X509_V_ERR_CERT_CHAIN_TOO_LONG:
591     case X509_V_ERR_PATH_LENGTH_EXCEEDED:
592     case X509_V_ERR_INVALID_CA:
593         al = SSL_AD_UNKNOWN_CA;
594         break;
595     case X509_V_ERR_APPLICATION_VERIFICATION:
596         al = SSL_AD_HANDSHAKE_FAILURE;
597         break;
598     case X509_V_ERR_INVALID_PURPOSE:
599         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
600         break;
601     default:
602         al = SSL_AD_CERTIFICATE_UNKNOWN;
603         break;
604     }
605     return (al);
606 }
607
608 int ssl_allow_compression(SSL *s)
609 {
610     if (s->options & SSL_OP_NO_COMPRESSION)
611         return 0;
612     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
613 }
614
615 static int version_cmp(const SSL *s, int a, int b)
616 {
617     int dtls = SSL_IS_DTLS(s);
618
619     if (a == b)
620         return 0;
621     if (!dtls)
622         return a < b ? -1 : 1;
623     return DTLS_VERSION_LT(a, b) ? -1 : 1;
624 }
625
626 typedef struct {
627     int version;
628     const SSL_METHOD *(*cmeth)(void);
629     const SSL_METHOD *(*smeth)(void);
630 } version_info;
631
632 #if TLS_MAX_VERSION != TLS1_2_VERSION
633 # error Code needs update for TLS_method() support beyond TLS1_2_VERSION.
634 #endif
635
636 static const version_info tls_version_table[] = {
637 #ifndef OPENSSL_NO_TLS1_2
638     { TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method },
639 #else
640     { TLS1_2_VERSION, NULL, NULL },
641 #endif
642 #ifndef OPENSSL_NO_TLS1_1
643     { TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method },
644 #else
645     { TLS1_1_VERSION, NULL, NULL },
646 #endif
647 #ifndef OPENSSL_NO_TLS1
648     { TLS1_VERSION, tlsv1_client_method, tlsv1_server_method },
649 #else
650     { TLS1_VERSION, NULL, NULL },
651 #endif
652 #ifndef OPENSSL_NO_SSL3
653     { SSL3_VERSION, sslv3_client_method, sslv3_server_method },
654 #else
655     { SSL3_VERSION, NULL, NULL },
656 #endif
657     { 0, NULL, NULL },
658 };
659
660 #if DTLS_MAX_VERSION != DTLS1_2_VERSION
661 # error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
662 #endif
663
664 static const version_info dtls_version_table[] = {
665 #ifndef OPENSSL_NO_DTLS1_2
666     { DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method },
667 #else
668     { DTLS1_2_VERSION, NULL, NULL },
669 #endif
670 #ifndef OPENSSL_NO_DTLS1
671     { DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method },
672 #else
673     { DTLS1_VERSION, NULL, NULL },
674 #endif
675     { 0, NULL, NULL },
676 };
677
678 /*
679  * ssl_method_error - Check whether an SSL_METHOD is enabled.
680  *
681  * @s: The SSL handle for the candidate method
682  * @method: the intended method.
683  *
684  * Returns 0 on success, or an SSL error reason on failure.
685  */
686 static int ssl_method_error(const SSL *s, const SSL_METHOD *method)
687 {
688     int version = method->version;
689
690     if ((s->min_proto_version != 0 &&
691          version_cmp(s, version, s->min_proto_version) < 0) ||
692         ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
693         return SSL_R_VERSION_TOO_LOW;
694
695     if (s->max_proto_version != 0 &&
696              version_cmp(s, version, s->max_proto_version) > 0)
697         return SSL_R_VERSION_TOO_HIGH;
698
699     if ((s->options & method->mask) != 0)
700         return SSL_R_UNSUPPORTED_PROTOCOL;
701     if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
702         return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
703     else if ((method->flags & SSL_METHOD_NO_FIPS) != 0 && FIPS_mode())
704         return SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE;
705
706     return 0;
707 }
708
709 /*
710  * ssl_version_supported - Check that the specified `version` is supported by
711  * `SSL *` instance
712  *
713  * @s: The SSL handle for the candidate method
714  * @version: Protocol version to test against
715  *
716  * Returns 1 when supported, otherwise 0
717  */
718 int ssl_version_supported(const SSL *s, int version)
719 {
720     const version_info *vent;
721     const version_info *table;
722
723     switch (s->method->version) {
724     default:
725         /* Version should match method version for non-ANY method */
726         return version_cmp(s, version, s->version) == 0;
727     case TLS_ANY_VERSION:
728         table = tls_version_table;
729         break;
730     case DTLS_ANY_VERSION:
731         table = dtls_version_table;
732         break;
733     }
734
735     for (vent = table;
736          vent->version != 0 && version_cmp(s, version, vent->version) <= 0;
737          ++vent) {
738         if (vent->cmeth != NULL &&
739             version_cmp(s, version, vent->version) == 0 &&
740             ssl_method_error(s, vent->cmeth()) == 0) {
741             return 1;
742         }
743     }
744     return 0;
745 }
746
747 /*
748  * ssl_check_version_downgrade - In response to RFC7507 SCSV version
749  * fallback indication from a client check whether we're using the highest
750  * supported protocol version.
751  *
752  * @s server SSL handle.
753  *
754  * Returns 1 when using the highest enabled version, 0 otherwise.
755  */
756 int ssl_check_version_downgrade(SSL *s)
757 {
758     const version_info *vent;
759     const version_info *table;
760
761     /*
762      * Check that the current protocol is the highest enabled version
763      * (according to s->ctx->method, as version negotiation may have changed
764      * s->method).
765      */
766     if (s->version == s->ctx->method->version)
767         return 1;
768
769     /*
770      * Apparently we're using a version-flexible SSL_METHOD (not at its
771      * highest protocol version).
772      */
773     if (s->ctx->method->version == TLS_method()->version)
774         table = tls_version_table;
775     else if (s->ctx->method->version == DTLS_method()->version)
776         table = dtls_version_table;
777     else {
778         /* Unexpected state; fail closed. */
779         return 0;
780     }
781
782     for (vent = table; vent->version != 0; ++vent) {
783         if (vent->smeth != NULL &&
784             ssl_method_error(s, vent->smeth()) == 0)
785             return s->version == vent->version;
786     }
787     return 0;
788 }
789
790 /*
791  * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
792  * protocols, provided the initial (D)TLS method is version-flexible.  This
793  * function sanity-checks the proposed value and makes sure the method is
794  * version-flexible, then sets the limit if all is well.
795  *
796  * @method_version: The version of the current SSL_METHOD.
797  * @version: the intended limit.
798  * @bound: pointer to limit to be updated.
799  *
800  * Returns 1 on success, 0 on failure.
801  */
802 int ssl_set_version_bound(int method_version, int version, int *bound)
803 {
804     if (version == 0) {
805         *bound = version;
806         return 1;
807     }
808
809     /*-
810      * Restrict TLS methods to TLS protocol versions.
811      * Restrict DTLS methods to DTLS protocol versions.
812      * Note, DTLS version numbers are decreasing, use comparison macros.
813      *
814      * Note that for both lower-bounds we use explicit versions, not
815      * (D)TLS_MIN_VERSION.  This is because we don't want to break user
816      * configurations.  If the MIN (supported) version ever rises, the user's
817      * "floor" remains valid even if no longer available.  We don't expect the
818      * MAX ceiling to ever get lower, so making that variable makes sense.
819      */
820     switch (method_version) {
821     default:
822         /*
823          * XXX For fixed version methods, should we always fail and not set any
824          * bounds, always succeed and not set any bounds, or set the bounds and
825          * arrange to fail later if they are not met?  At present fixed-version
826          * methods are not subject to controls that disable individual protocol
827          * versions.
828          */
829         return 0;
830
831     case TLS_ANY_VERSION:
832         if (version < SSL3_VERSION || version > TLS_MAX_VERSION)
833             return 0;
834         break;
835
836     case DTLS_ANY_VERSION:
837         if (DTLS_VERSION_GT(version, DTLS_MAX_VERSION) ||
838             DTLS_VERSION_LT(version, DTLS1_VERSION))
839             return 0;
840         break;
841     }
842
843     *bound = version;
844     return 1;
845 }
846
847 /*
848  * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
849  * client HELLO is received to select the final server protocol version and
850  * the version specific method.
851  *
852  * @s: server SSL handle.
853  *
854  * Returns 0 on success or an SSL error reason number on failure.
855  */
856 int ssl_choose_server_version(SSL *s)
857 {
858     /*-
859      * With version-flexible methods we have an initial state with:
860      *
861      *   s->method->version == (D)TLS_ANY_VERSION,
862      *   s->version == (D)TLS_MAX_VERSION.
863      *
864      * So we detect version-flexible methods via the method version, not the
865      * handle version.
866      */
867     int server_version = s->method->version;
868     int client_version = s->client_version;
869     const version_info *vent;
870     const version_info *table;
871     int disabled = 0;
872
873     switch (server_version) {
874     default:
875         if (version_cmp(s, client_version, s->version) < 0)
876             return SSL_R_WRONG_SSL_VERSION;
877         /*
878          * If this SSL handle is not from a version flexible method we don't
879          * (and never did) check min/max FIPS or Suite B constraints.  Hope
880          * that's OK.  It is up to the caller to not choose fixed protocol
881          * versions they don't want.  If not, then easy to fix, just return
882          * ssl_method_error(s, s->method)
883          */
884         return 0;
885     case TLS_ANY_VERSION:
886         table = tls_version_table;
887         break;
888     case DTLS_ANY_VERSION:
889         table = dtls_version_table;
890         break;
891     }
892
893     for (vent = table; vent->version != 0; ++vent) {
894         const SSL_METHOD *method;
895
896         if (vent->smeth == NULL ||
897             version_cmp(s, client_version, vent->version) < 0)
898             continue;
899         method = vent->smeth();
900         if (ssl_method_error(s, method) == 0) {
901             s->version = vent->version;
902             s->method = method;
903             return 0;
904         }
905         disabled = 1;
906     }
907     return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
908 }
909
910 /*
911  * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
912  * server HELLO is received to select the final client protocol version and
913  * the version specific method.
914  *
915  * @s: client SSL handle.
916  * @version: The proposed version from the server's HELLO.
917  *
918  * Returns 0 on success or an SSL error reason number on failure.
919  */
920 int ssl_choose_client_version(SSL *s, int version)
921 {
922     const version_info *vent;
923     const version_info *table;
924
925     switch (s->method->version) {
926     default:
927         if (version != s->version)
928             return SSL_R_WRONG_SSL_VERSION;
929         /*
930          * If this SSL handle is not from a version flexible method we don't
931          * (and never did) check min/max, FIPS or Suite B constraints.  Hope
932          * that's OK.  It is up to the caller to not choose fixed protocol
933          * versions they don't want.  If not, then easy to fix, just return
934          * ssl_method_error(s, s->method)
935          */
936         return 0;
937     case TLS_ANY_VERSION:
938         table = tls_version_table;
939         break;
940     case DTLS_ANY_VERSION:
941         table = dtls_version_table;
942         break;
943     }
944
945     for (vent = table; vent->version != 0; ++vent) {
946         const SSL_METHOD *method;
947         int err;
948
949         if (version != vent->version)
950             continue;
951         if (vent->cmeth == NULL)
952             break;
953         method = vent->cmeth();
954         err = ssl_method_error(s, method);
955         if (err != 0)
956             return err;
957         s->method = method;
958         s->version = version;
959         return 0;
960     }
961
962     return SSL_R_UNSUPPORTED_PROTOCOL;
963 }
964
965 /*
966  * ssl_get_client_min_max_version - get minimum and maximum client version
967  * @s: The SSL connection
968  * @min_version: The minimum supported version
969  * @max_version: The maximum supported version
970  *
971  * Work out what version we should be using for the initial ClientHello if the
972  * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
973  * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
974  * or FIPS_mode() constraints and any floor imposed by the security level here,
975  * so we don't advertise the wrong protocol version to only reject the outcome later.
976  *
977  * Computing the right floor matters.  If, e.g.,  TLS 1.0 and 1.2 are enabled,
978  * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
979  * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
980  *
981  * Returns 0 on success or an SSL error reason number on failure.  On failure
982  * min_version and max_version will also be set to 0.
983  */
984 int ssl_get_client_min_max_version(const SSL *s, int *min_version, int *max_version)
985 {
986     int version;
987     int hole;
988     const SSL_METHOD *single = NULL;
989     const SSL_METHOD *method;
990     const version_info *table;
991     const version_info *vent;
992
993     switch (s->method->version) {
994     default:
995         /*
996          * If this SSL handle is not from a version flexible method we don't
997          * (and never did) check min/max FIPS or Suite B constraints.  Hope
998          * that's OK.  It is up to the caller to not choose fixed protocol
999          * versions they don't want.  If not, then easy to fix, just return
1000          * ssl_method_error(s, s->method)
1001          */
1002         *min_version = *max_version = s->version;
1003         return 0;
1004     case TLS_ANY_VERSION:
1005         table = tls_version_table;
1006         break;
1007     case DTLS_ANY_VERSION:
1008         table = dtls_version_table;
1009         break;
1010     }
1011
1012     /*
1013      * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
1014      * below X enabled. This is required in order to maintain the "version
1015      * capability" vector contiguous. Any versions with a NULL client method
1016      * (protocol version client is disabled at compile-time) is also a "hole".
1017      *
1018      * Our initial state is hole == 1, version == 0.  That is, versions above
1019      * the first version in the method table are disabled (a "hole" above
1020      * the valid protocol entries) and we don't have a selected version yet.
1021      *
1022      * Whenever "hole == 1", and we hit an enabled method, its version becomes
1023      * the selected version, and the method becomes a candidate "single"
1024      * method.  We're no longer in a hole, so "hole" becomes 0.
1025      *
1026      * If "hole == 0" and we hit an enabled method, then "single" is cleared,
1027      * as we support a contiguous range of at least two methods.  If we hit
1028      * a disabled method, then hole becomes true again, but nothing else
1029      * changes yet, because all the remaining methods may be disabled too.
1030      * If we again hit an enabled method after the new hole, it becomes
1031      * selected, as we start from scratch.
1032      */
1033     *min_version = version = 0;
1034     hole = 1;
1035     for (vent = table; vent->version != 0; ++vent) {
1036         /*
1037          * A table entry with a NULL client method is still a hole in the
1038          * "version capability" vector.
1039          */
1040         if (vent->cmeth == NULL) {
1041             hole = 1;
1042             continue;
1043         }
1044         method = vent->cmeth();
1045         if (ssl_method_error(s, method) != 0) {
1046             hole = 1;
1047         } else if (!hole) {
1048             single = NULL;
1049             *min_version = method->version;
1050         } else {
1051             version = (single = method)->version;
1052             *min_version = version;
1053             hole = 0;
1054         }
1055     }
1056
1057     *max_version = version;
1058
1059     /* Fail if everything is disabled */
1060     if (version == 0)
1061         return SSL_R_NO_PROTOCOLS_AVAILABLE;
1062
1063     return 0;
1064 }
1065
1066 /*
1067  * ssl_set_client_hello_version - Work out what version we should be using for
1068  * the initial ClientHello.
1069  *
1070  * @s: client SSL handle.
1071  *
1072  * Returns 0 on success or an SSL error reason number on failure.
1073  */
1074 int ssl_set_client_hello_version(SSL *s)
1075 {
1076     int ver_min, ver_max, ret;
1077
1078     ret = ssl_get_client_min_max_version(s, &ver_min, &ver_max);
1079
1080     if (ret != 0)
1081         return ret;
1082
1083     s->client_version = s->version = ver_max;
1084     return 0;
1085 }