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