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