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