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