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