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