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