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