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