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