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