sslapitest.c revision 1.1.1.14
1/*
2 * Copyright 2016-2023 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (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 * We need access to the deprecated low level HMAC APIs for legacy purposes
12 * when the deprecated calls are not hidden
13 */
14#ifndef OPENSSL_NO_DEPRECATED_3_0
15# define OPENSSL_SUPPRESS_DEPRECATED
16#endif
17
18#include <stdio.h>
19#include <string.h>
20
21#include <openssl/opensslconf.h>
22#include <openssl/bio.h>
23#include <openssl/crypto.h>
24#include <openssl/ssl.h>
25#include <openssl/ocsp.h>
26#include <openssl/srp.h>
27#include <openssl/txt_db.h>
28#include <openssl/aes.h>
29#include <openssl/rand.h>
30#include <openssl/core_names.h>
31#include <openssl/core_dispatch.h>
32#include <openssl/provider.h>
33#include <openssl/param_build.h>
34#include <openssl/x509v3.h>
35#include <openssl/dh.h>
36#include <openssl/engine.h>
37
38#include "helpers/ssltestlib.h"
39#include "testutil.h"
40#include "testutil/output.h"
41#include "internal/nelem.h"
42#include "internal/ktls.h"
43#include "../ssl/ssl_local.h"
44#include "filterprov.h"
45
46#undef OSSL_NO_USABLE_TLS1_3
47#if defined(OPENSSL_NO_TLS1_3) \
48    || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH))
49/*
50 * If we don't have ec or dh then there are no built-in groups that are usable
51 * with TLSv1.3
52 */
53# define OSSL_NO_USABLE_TLS1_3
54#endif
55
56/* Defined in tls-provider.c */
57int tls_provider_init(const OSSL_CORE_HANDLE *handle,
58                      const OSSL_DISPATCH *in,
59                      const OSSL_DISPATCH **out,
60                      void **provctx);
61
62static OSSL_LIB_CTX *libctx = NULL;
63static OSSL_PROVIDER *defctxnull = NULL;
64
65#ifndef OSSL_NO_USABLE_TLS1_3
66
67static SSL_SESSION *clientpsk = NULL;
68static SSL_SESSION *serverpsk = NULL;
69static const char *pskid = "Identity";
70static const char *srvid;
71
72static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
73                          size_t *idlen, SSL_SESSION **sess);
74static int find_session_cb(SSL *ssl, const unsigned char *identity,
75                           size_t identity_len, SSL_SESSION **sess);
76
77static int use_session_cb_cnt = 0;
78static int find_session_cb_cnt = 0;
79
80static SSL_SESSION *create_a_psk(SSL *ssl, size_t mdsize);
81#endif
82
83static char *certsdir = NULL;
84static char *cert = NULL;
85static char *privkey = NULL;
86static char *cert2 = NULL;
87static char *privkey2 = NULL;
88static char *cert1024 = NULL;
89static char *privkey1024 = NULL;
90static char *cert3072 = NULL;
91static char *privkey3072 = NULL;
92static char *cert4096 = NULL;
93static char *privkey4096 = NULL;
94static char *cert8192 = NULL;
95static char *privkey8192 = NULL;
96static char *srpvfile = NULL;
97static char *tmpfilename = NULL;
98static char *dhfile = NULL;
99
100static int is_fips = 0;
101
102#define LOG_BUFFER_SIZE 2048
103static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
104static size_t server_log_buffer_index = 0;
105static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
106static size_t client_log_buffer_index = 0;
107static int error_writing_log = 0;
108
109#ifndef OPENSSL_NO_OCSP
110static const unsigned char orespder[] = "Dummy OCSP Response";
111static int ocsp_server_called = 0;
112static int ocsp_client_called = 0;
113
114static int cdummyarg = 1;
115static X509 *ocspcert = NULL;
116#endif
117
118#define NUM_EXTRA_CERTS 40
119#define CLIENT_VERSION_LEN      2
120
121/*
122 * This structure is used to validate that the correct number of log messages
123 * of various types are emitted when emitting secret logs.
124 */
125struct sslapitest_log_counts {
126    unsigned int rsa_key_exchange_count;
127    unsigned int master_secret_count;
128    unsigned int client_early_secret_count;
129    unsigned int client_handshake_secret_count;
130    unsigned int server_handshake_secret_count;
131    unsigned int client_application_secret_count;
132    unsigned int server_application_secret_count;
133    unsigned int early_exporter_secret_count;
134    unsigned int exporter_secret_count;
135};
136
137
138static int hostname_cb(SSL *s, int *al, void *arg)
139{
140    const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
141
142    if (hostname != NULL && (strcmp(hostname, "goodhost") == 0
143                             || strcmp(hostname, "altgoodhost") == 0))
144        return  SSL_TLSEXT_ERR_OK;
145
146    return SSL_TLSEXT_ERR_NOACK;
147}
148
149static void client_keylog_callback(const SSL *ssl, const char *line)
150{
151    int line_length = strlen(line);
152
153    /* If the log doesn't fit, error out. */
154    if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
155        TEST_info("Client log too full");
156        error_writing_log = 1;
157        return;
158    }
159
160    strcat(client_log_buffer, line);
161    client_log_buffer_index += line_length;
162    client_log_buffer[client_log_buffer_index++] = '\n';
163}
164
165static void server_keylog_callback(const SSL *ssl, const char *line)
166{
167    int line_length = strlen(line);
168
169    /* If the log doesn't fit, error out. */
170    if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
171        TEST_info("Server log too full");
172        error_writing_log = 1;
173        return;
174    }
175
176    strcat(server_log_buffer, line);
177    server_log_buffer_index += line_length;
178    server_log_buffer[server_log_buffer_index++] = '\n';
179}
180
181static int compare_hex_encoded_buffer(const char *hex_encoded,
182                                      size_t hex_length,
183                                      const uint8_t *raw,
184                                      size_t raw_length)
185{
186    size_t i, j;
187    char hexed[3];
188
189    if (!TEST_size_t_eq(raw_length * 2, hex_length))
190        return 1;
191
192    for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
193        sprintf(hexed, "%02x", raw[i]);
194        if (!TEST_int_eq(hexed[0], hex_encoded[j])
195                || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
196            return 1;
197    }
198
199    return 0;
200}
201
202static int test_keylog_output(char *buffer, const SSL *ssl,
203                              const SSL_SESSION *session,
204                              struct sslapitest_log_counts *expected)
205{
206    char *token = NULL;
207    unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
208    size_t client_random_size = SSL3_RANDOM_SIZE;
209    unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
210    size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
211    unsigned int rsa_key_exchange_count = 0;
212    unsigned int master_secret_count = 0;
213    unsigned int client_early_secret_count = 0;
214    unsigned int client_handshake_secret_count = 0;
215    unsigned int server_handshake_secret_count = 0;
216    unsigned int client_application_secret_count = 0;
217    unsigned int server_application_secret_count = 0;
218    unsigned int early_exporter_secret_count = 0;
219    unsigned int exporter_secret_count = 0;
220
221    for (token = strtok(buffer, " \n"); token != NULL;
222         token = strtok(NULL, " \n")) {
223        if (strcmp(token, "RSA") == 0) {
224            /*
225             * Premaster secret. Tokens should be: 16 ASCII bytes of
226             * hex-encoded encrypted secret, then the hex-encoded pre-master
227             * secret.
228             */
229            if (!TEST_ptr(token = strtok(NULL, " \n")))
230                return 0;
231            if (!TEST_size_t_eq(strlen(token), 16))
232                return 0;
233            if (!TEST_ptr(token = strtok(NULL, " \n")))
234                return 0;
235            /*
236             * We can't sensibly check the log because the premaster secret is
237             * transient, and OpenSSL doesn't keep hold of it once the master
238             * secret is generated.
239             */
240            rsa_key_exchange_count++;
241        } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
242            /*
243             * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
244             * client random, then the hex-encoded master secret.
245             */
246            client_random_size = SSL_get_client_random(ssl,
247                                                       actual_client_random,
248                                                       SSL3_RANDOM_SIZE);
249            if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
250                return 0;
251
252            if (!TEST_ptr(token = strtok(NULL, " \n")))
253                return 0;
254            if (!TEST_size_t_eq(strlen(token), 64))
255                return 0;
256            if (!TEST_false(compare_hex_encoded_buffer(token, 64,
257                                                       actual_client_random,
258                                                       client_random_size)))
259                return 0;
260
261            if (!TEST_ptr(token = strtok(NULL, " \n")))
262                return 0;
263            master_key_size = SSL_SESSION_get_master_key(session,
264                                                         actual_master_key,
265                                                         master_key_size);
266            if (!TEST_size_t_ne(master_key_size, 0))
267                return 0;
268            if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
269                                                       actual_master_key,
270                                                       master_key_size)))
271                return 0;
272            master_secret_count++;
273        } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
274                    || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
275                    || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
276                    || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
277                    || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
278                    || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
279                    || strcmp(token, "EXPORTER_SECRET") == 0) {
280            /*
281             * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
282             * client random, and then the hex-encoded secret. In this case,
283             * we treat all of these secrets identically and then just
284             * distinguish between them when counting what we saw.
285             */
286            if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
287                client_early_secret_count++;
288            else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
289                client_handshake_secret_count++;
290            else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
291                server_handshake_secret_count++;
292            else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
293                client_application_secret_count++;
294            else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
295                server_application_secret_count++;
296            else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
297                early_exporter_secret_count++;
298            else if (strcmp(token, "EXPORTER_SECRET") == 0)
299                exporter_secret_count++;
300
301            client_random_size = SSL_get_client_random(ssl,
302                                                       actual_client_random,
303                                                       SSL3_RANDOM_SIZE);
304            if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
305                return 0;
306
307            if (!TEST_ptr(token = strtok(NULL, " \n")))
308                return 0;
309            if (!TEST_size_t_eq(strlen(token), 64))
310                return 0;
311            if (!TEST_false(compare_hex_encoded_buffer(token, 64,
312                                                       actual_client_random,
313                                                       client_random_size)))
314                return 0;
315
316            if (!TEST_ptr(token = strtok(NULL, " \n")))
317                return 0;
318        } else {
319            TEST_info("Unexpected token %s\n", token);
320            return 0;
321        }
322    }
323
324    /* Got what we expected? */
325    if (!TEST_size_t_eq(rsa_key_exchange_count,
326                        expected->rsa_key_exchange_count)
327            || !TEST_size_t_eq(master_secret_count,
328                               expected->master_secret_count)
329            || !TEST_size_t_eq(client_early_secret_count,
330                               expected->client_early_secret_count)
331            || !TEST_size_t_eq(client_handshake_secret_count,
332                               expected->client_handshake_secret_count)
333            || !TEST_size_t_eq(server_handshake_secret_count,
334                               expected->server_handshake_secret_count)
335            || !TEST_size_t_eq(client_application_secret_count,
336                               expected->client_application_secret_count)
337            || !TEST_size_t_eq(server_application_secret_count,
338                               expected->server_application_secret_count)
339            || !TEST_size_t_eq(early_exporter_secret_count,
340                               expected->early_exporter_secret_count)
341            || !TEST_size_t_eq(exporter_secret_count,
342                               expected->exporter_secret_count))
343        return 0;
344    return 1;
345}
346
347#if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
348static int test_keylog(void)
349{
350    SSL_CTX *cctx = NULL, *sctx = NULL;
351    SSL *clientssl = NULL, *serverssl = NULL;
352    int testresult = 0;
353    struct sslapitest_log_counts expected;
354
355    /* Clean up logging space */
356    memset(&expected, 0, sizeof(expected));
357    memset(client_log_buffer, 0, sizeof(client_log_buffer));
358    memset(server_log_buffer, 0, sizeof(server_log_buffer));
359    client_log_buffer_index = 0;
360    server_log_buffer_index = 0;
361    error_writing_log = 0;
362
363    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
364                                       TLS_client_method(),
365                                       TLS1_VERSION, 0,
366                                       &sctx, &cctx, cert, privkey)))
367        return 0;
368
369    /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
370    SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
371    SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
372
373    /* We also want to ensure that we use RSA-based key exchange. */
374    if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
375        goto end;
376
377    if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
378            || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
379        goto end;
380    SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
381    if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
382                   == client_keylog_callback))
383        goto end;
384    SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
385    if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
386                   == server_keylog_callback))
387        goto end;
388
389    /* Now do a handshake and check that the logs have been written to. */
390    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
391                                      &clientssl, NULL, NULL))
392            || !TEST_true(create_ssl_connection(serverssl, clientssl,
393                                                SSL_ERROR_NONE))
394            || !TEST_false(error_writing_log)
395            || !TEST_int_gt(client_log_buffer_index, 0)
396            || !TEST_int_gt(server_log_buffer_index, 0))
397        goto end;
398
399    /*
400     * Now we want to test that our output data was vaguely sensible. We
401     * do that by using strtok and confirming that we have more or less the
402     * data we expect. For both client and server, we expect to see one master
403     * secret. The client should also see an RSA key exchange.
404     */
405    expected.rsa_key_exchange_count = 1;
406    expected.master_secret_count = 1;
407    if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
408                                      SSL_get_session(clientssl), &expected)))
409        goto end;
410
411    expected.rsa_key_exchange_count = 0;
412    if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
413                                      SSL_get_session(serverssl), &expected)))
414        goto end;
415
416    testresult = 1;
417
418end:
419    SSL_free(serverssl);
420    SSL_free(clientssl);
421    SSL_CTX_free(sctx);
422    SSL_CTX_free(cctx);
423
424    return testresult;
425}
426#endif
427
428#ifndef OSSL_NO_USABLE_TLS1_3
429static int test_keylog_no_master_key(void)
430{
431    SSL_CTX *cctx = NULL, *sctx = NULL;
432    SSL *clientssl = NULL, *serverssl = NULL;
433    SSL_SESSION *sess = NULL;
434    int testresult = 0;
435    struct sslapitest_log_counts expected;
436    unsigned char buf[1];
437    size_t readbytes, written;
438
439    /* Clean up logging space */
440    memset(&expected, 0, sizeof(expected));
441    memset(client_log_buffer, 0, sizeof(client_log_buffer));
442    memset(server_log_buffer, 0, sizeof(server_log_buffer));
443    client_log_buffer_index = 0;
444    server_log_buffer_index = 0;
445    error_writing_log = 0;
446
447    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
448                                       TLS_client_method(), TLS1_VERSION, 0,
449                                       &sctx, &cctx, cert, privkey))
450        || !TEST_true(SSL_CTX_set_max_early_data(sctx,
451                                                 SSL3_RT_MAX_PLAIN_LENGTH)))
452        return 0;
453
454    if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
455            || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
456        goto end;
457
458    SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
459    if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
460                   == client_keylog_callback))
461        goto end;
462
463    SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
464    if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
465                   == server_keylog_callback))
466        goto end;
467
468    /* Now do a handshake and check that the logs have been written to. */
469    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
470                                      &clientssl, NULL, NULL))
471            || !TEST_true(create_ssl_connection(serverssl, clientssl,
472                                                SSL_ERROR_NONE))
473            || !TEST_false(error_writing_log))
474        goto end;
475
476    /*
477     * Now we want to test that our output data was vaguely sensible. For this
478     * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
479     * TLSv1.3, but we do expect both client and server to emit keys.
480     */
481    expected.client_handshake_secret_count = 1;
482    expected.server_handshake_secret_count = 1;
483    expected.client_application_secret_count = 1;
484    expected.server_application_secret_count = 1;
485    expected.exporter_secret_count = 1;
486    if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
487                                      SSL_get_session(clientssl), &expected))
488            || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
489                                             SSL_get_session(serverssl),
490                                             &expected)))
491        goto end;
492
493    /* Terminate old session and resume with early data. */
494    sess = SSL_get1_session(clientssl);
495    SSL_shutdown(clientssl);
496    SSL_shutdown(serverssl);
497    SSL_free(serverssl);
498    SSL_free(clientssl);
499    serverssl = clientssl = NULL;
500
501    /* Reset key log */
502    memset(client_log_buffer, 0, sizeof(client_log_buffer));
503    memset(server_log_buffer, 0, sizeof(server_log_buffer));
504    client_log_buffer_index = 0;
505    server_log_buffer_index = 0;
506
507    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
508                                      &clientssl, NULL, NULL))
509            || !TEST_true(SSL_set_session(clientssl, sess))
510            /* Here writing 0 length early data is enough. */
511            || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
512            || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
513                                                &readbytes),
514                            SSL_READ_EARLY_DATA_ERROR)
515            || !TEST_int_eq(SSL_get_early_data_status(serverssl),
516                            SSL_EARLY_DATA_ACCEPTED)
517            || !TEST_true(create_ssl_connection(serverssl, clientssl,
518                          SSL_ERROR_NONE))
519            || !TEST_true(SSL_session_reused(clientssl)))
520        goto end;
521
522    /* In addition to the previous entries, expect early secrets. */
523    expected.client_early_secret_count = 1;
524    expected.early_exporter_secret_count = 1;
525    if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
526                                      SSL_get_session(clientssl), &expected))
527            || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
528                                             SSL_get_session(serverssl),
529                                             &expected)))
530        goto end;
531
532    testresult = 1;
533
534end:
535    SSL_SESSION_free(sess);
536    SSL_free(serverssl);
537    SSL_free(clientssl);
538    SSL_CTX_free(sctx);
539    SSL_CTX_free(cctx);
540
541    return testresult;
542}
543#endif
544
545static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg)
546{
547    int res = X509_verify_cert(ctx);
548    int idx = SSL_get_ex_data_X509_STORE_CTX_idx();
549    SSL *ssl;
550
551    /* this should not happen but check anyway */
552    if (idx < 0
553        || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL)
554        return 0;
555
556    if (res == 0 && X509_STORE_CTX_get_error(ctx) ==
557        X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
558        /* indicate SSL_ERROR_WANT_RETRY_VERIFY */
559        return SSL_set_retry_verify(ssl);
560
561    return res;
562}
563
564static int test_client_cert_verify_cb(void)
565{
566    /* server key, cert, chain, and root */
567    char *skey = test_mk_file_path(certsdir, "leaf.key");
568    char *leaf = test_mk_file_path(certsdir, "leaf.pem");
569    char *int2 = test_mk_file_path(certsdir, "subinterCA.pem");
570    char *int1 = test_mk_file_path(certsdir, "interCA.pem");
571    char *root = test_mk_file_path(certsdir, "rootCA.pem");
572    X509 *crt1 = NULL, *crt2 = NULL;
573    STACK_OF(X509) *server_chain;
574    SSL_CTX *cctx = NULL, *sctx = NULL;
575    SSL *clientssl = NULL, *serverssl = NULL;
576    int testresult = 0;
577
578    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
579                                       TLS_client_method(), TLS1_VERSION, 0,
580                                       &sctx, &cctx, NULL, NULL)))
581        goto end;
582    if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(sctx, leaf), 1)
583            || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, skey,
584                                                        SSL_FILETYPE_PEM), 1)
585            || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
586        goto end;
587    if (!TEST_true(SSL_CTX_load_verify_locations(cctx, root, NULL)))
588        goto end;
589    SSL_CTX_set_verify(cctx, SSL_VERIFY_PEER, NULL);
590    SSL_CTX_set_cert_verify_callback(cctx, verify_retry_cb, NULL);
591    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
592                                      &clientssl, NULL, NULL)))
593        goto end;
594
595    /* attempt SSL_connect() with incomplete server chain */
596    if (!TEST_false(create_ssl_connection(serverssl, clientssl,
597                                          SSL_ERROR_WANT_RETRY_VERIFY)))
598        goto end;
599
600    /* application provides intermediate certs needed to verify server cert */
601    if (!TEST_ptr((crt1 = load_cert_pem(int1, libctx)))
602        || !TEST_ptr((crt2 = load_cert_pem(int2, libctx)))
603        || !TEST_ptr((server_chain = SSL_get_peer_cert_chain(clientssl))))
604        goto end;
605    /* add certs in reverse order to demonstrate real chain building */
606    if (!TEST_true(sk_X509_push(server_chain, crt1)))
607        goto end;
608    crt1 = NULL;
609    if (!TEST_true(sk_X509_push(server_chain, crt2)))
610        goto end;
611    crt2 = NULL;
612
613    /* continue SSL_connect(), must now succeed with completed server chain */
614    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
615                                         SSL_ERROR_NONE)))
616        goto end;
617
618    testresult = 1;
619
620end:
621    X509_free(crt1);
622    X509_free(crt2);
623    if (clientssl != NULL) {
624        SSL_shutdown(clientssl);
625        SSL_free(clientssl);
626    }
627    if (serverssl != NULL) {
628        SSL_shutdown(serverssl);
629        SSL_free(serverssl);
630    }
631    SSL_CTX_free(sctx);
632    SSL_CTX_free(cctx);
633
634    OPENSSL_free(skey);
635    OPENSSL_free(leaf);
636    OPENSSL_free(int2);
637    OPENSSL_free(int1);
638    OPENSSL_free(root);
639
640    return testresult;
641}
642
643static int test_ssl_build_cert_chain(void)
644{
645    int ret = 0;
646    SSL_CTX *ssl_ctx = NULL;
647    SSL *ssl = NULL;
648    char *skey = test_mk_file_path(certsdir, "leaf.key");
649    char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
650
651    if (!TEST_ptr(ssl_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
652        goto end;
653    if (!TEST_ptr(ssl = SSL_new(ssl_ctx)))
654        goto end;
655    /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
656    if (!TEST_int_eq(SSL_use_certificate_chain_file(ssl, leaf_chain), 1)
657        || !TEST_int_eq(SSL_use_PrivateKey_file(ssl, skey, SSL_FILETYPE_PEM), 1)
658        || !TEST_int_eq(SSL_check_private_key(ssl), 1))
659        goto end;
660    if (!TEST_true(SSL_build_cert_chain(ssl, SSL_BUILD_CHAIN_FLAG_NO_ROOT
661                                             | SSL_BUILD_CHAIN_FLAG_CHECK)))
662        goto end;
663    ret = 1;
664end:
665    SSL_free(ssl);
666    SSL_CTX_free(ssl_ctx);
667    OPENSSL_free(leaf_chain);
668    OPENSSL_free(skey);
669    return ret;
670}
671
672static int get_password_cb(char *buf, int size, int rw_flag, void *userdata)
673{
674    static const char pass[] = "testpass";
675
676    if (!TEST_int_eq(size, PEM_BUFSIZE))
677        return -1;
678
679    memcpy(buf, pass, sizeof(pass) - 1);
680    return sizeof(pass) - 1;
681}
682
683static int test_ssl_ctx_build_cert_chain(void)
684{
685    int ret = 0;
686    SSL_CTX *ctx = NULL;
687    char *skey = test_mk_file_path(certsdir, "leaf-encrypted.key");
688    char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
689
690    if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
691        goto end;
692    SSL_CTX_set_default_passwd_cb(ctx, get_password_cb);
693    /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
694    if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(ctx, leaf_chain), 1)
695        || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(ctx, skey,
696                                                    SSL_FILETYPE_PEM), 1)
697        || !TEST_int_eq(SSL_CTX_check_private_key(ctx), 1))
698        goto end;
699    if (!TEST_true(SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT
700                                                | SSL_BUILD_CHAIN_FLAG_CHECK)))
701        goto end;
702    ret = 1;
703end:
704    SSL_CTX_free(ctx);
705    OPENSSL_free(leaf_chain);
706    OPENSSL_free(skey);
707    return ret;
708}
709
710#ifndef OPENSSL_NO_TLS1_2
711static int full_client_hello_callback(SSL *s, int *al, void *arg)
712{
713    int *ctr = arg;
714    const unsigned char *p;
715    int *exts;
716    /* We only configure two ciphers, but the SCSV is added automatically. */
717#ifdef OPENSSL_NO_EC
718    const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
719#else
720    const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
721                                              0x2c, 0x00, 0xff};
722#endif
723    const int expected_extensions[] = {
724#ifndef OPENSSL_NO_EC
725                                       11, 10,
726#endif
727                                       35, 22, 23, 13};
728    size_t len;
729
730    /* Make sure we can defer processing and get called back. */
731    if ((*ctr)++ == 0)
732        return SSL_CLIENT_HELLO_RETRY;
733
734    len = SSL_client_hello_get0_ciphers(s, &p);
735    if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
736            || !TEST_size_t_eq(
737                       SSL_client_hello_get0_compression_methods(s, &p), 1)
738            || !TEST_int_eq(*p, 0))
739        return SSL_CLIENT_HELLO_ERROR;
740    if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
741        return SSL_CLIENT_HELLO_ERROR;
742    if (len != OSSL_NELEM(expected_extensions) ||
743        memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
744        printf("ClientHello callback expected extensions mismatch\n");
745        OPENSSL_free(exts);
746        return SSL_CLIENT_HELLO_ERROR;
747    }
748    OPENSSL_free(exts);
749    return SSL_CLIENT_HELLO_SUCCESS;
750}
751
752static int test_client_hello_cb(void)
753{
754    SSL_CTX *cctx = NULL, *sctx = NULL;
755    SSL *clientssl = NULL, *serverssl = NULL;
756    int testctr = 0, testresult = 0;
757
758    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
759                                       TLS_client_method(), TLS1_VERSION, 0,
760                                       &sctx, &cctx, cert, privkey)))
761        goto end;
762    SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
763
764    /* The gimpy cipher list we configure can't do TLS 1.3. */
765    SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
766
767    if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
768                        "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
769            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
770                                             &clientssl, NULL, NULL))
771            || !TEST_false(create_ssl_connection(serverssl, clientssl,
772                        SSL_ERROR_WANT_CLIENT_HELLO_CB))
773                /*
774                 * Passing a -1 literal is a hack since
775                 * the real value was lost.
776                 * */
777            || !TEST_int_eq(SSL_get_error(serverssl, -1),
778                            SSL_ERROR_WANT_CLIENT_HELLO_CB)
779            || !TEST_true(create_ssl_connection(serverssl, clientssl,
780                                                SSL_ERROR_NONE)))
781        goto end;
782
783    testresult = 1;
784
785end:
786    SSL_free(serverssl);
787    SSL_free(clientssl);
788    SSL_CTX_free(sctx);
789    SSL_CTX_free(cctx);
790
791    return testresult;
792}
793
794static int test_no_ems(void)
795{
796    SSL_CTX *cctx = NULL, *sctx = NULL;
797    SSL *clientssl = NULL, *serverssl = NULL;
798    int testresult = 0;
799
800    if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
801                             TLS1_VERSION, TLS1_2_VERSION,
802                             &sctx, &cctx, cert, privkey)) {
803        printf("Unable to create SSL_CTX pair\n");
804        goto end;
805    }
806
807    SSL_CTX_set_options(sctx, SSL_OP_NO_EXTENDED_MASTER_SECRET);
808
809    if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
810        printf("Unable to create SSL objects\n");
811        goto end;
812    }
813
814    if (!create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) {
815        printf("Creating SSL connection failed\n");
816        goto end;
817    }
818
819    if (SSL_get_extms_support(serverssl)) {
820        printf("Server reports Extended Master Secret support\n");
821        goto end;
822    }
823
824    if (SSL_get_extms_support(clientssl)) {
825        printf("Client reports Extended Master Secret support\n");
826        goto end;
827    }
828    testresult = 1;
829
830end:
831    SSL_free(serverssl);
832    SSL_free(clientssl);
833    SSL_CTX_free(sctx);
834    SSL_CTX_free(cctx);
835
836    return testresult;
837}
838
839/*
840 * Very focused test to exercise a single case in the server-side state
841 * machine, when the ChangeCipherState message needs to actually change
842 * from one cipher to a different cipher (i.e., not changing from null
843 * encryption to real encryption).
844 */
845static int test_ccs_change_cipher(void)
846{
847    SSL_CTX *cctx = NULL, *sctx = NULL;
848    SSL *clientssl = NULL, *serverssl = NULL;
849    SSL_SESSION *sess = NULL, *sesspre, *sesspost;
850    int testresult = 0;
851    int i;
852    unsigned char buf;
853    size_t readbytes;
854
855    /*
856     * Create a conection so we can resume and potentially (but not) use
857     * a different cipher in the second connection.
858     */
859    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
860                                       TLS_client_method(),
861                                       TLS1_VERSION, TLS1_2_VERSION,
862                                       &sctx, &cctx, cert, privkey))
863            || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
864            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
865                          NULL, NULL))
866            || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
867            || !TEST_true(create_ssl_connection(serverssl, clientssl,
868                                                SSL_ERROR_NONE))
869            || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
870            || !TEST_ptr(sess = SSL_get1_session(clientssl)))
871        goto end;
872
873    shutdown_ssl_connection(serverssl, clientssl);
874    serverssl = clientssl = NULL;
875
876    /* Resume, preferring a different cipher. Our server will force the
877     * same cipher to be used as the initial handshake. */
878    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
879                          NULL, NULL))
880            || !TEST_true(SSL_set_session(clientssl, sess))
881            || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
882            || !TEST_true(create_ssl_connection(serverssl, clientssl,
883                                                SSL_ERROR_NONE))
884            || !TEST_true(SSL_session_reused(clientssl))
885            || !TEST_true(SSL_session_reused(serverssl))
886            || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
887            || !TEST_ptr_eq(sesspre, sesspost)
888            || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
889                            SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
890        goto end;
891    shutdown_ssl_connection(serverssl, clientssl);
892    serverssl = clientssl = NULL;
893
894    /*
895     * Now create a fresh connection and try to renegotiate a different
896     * cipher on it.
897     */
898    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
899                                      NULL, NULL))
900            || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
901            || !TEST_true(create_ssl_connection(serverssl, clientssl,
902                                                SSL_ERROR_NONE))
903            || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
904            || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
905            || !TEST_true(SSL_renegotiate(clientssl))
906            || !TEST_true(SSL_renegotiate_pending(clientssl)))
907        goto end;
908    /* Actually drive the renegotiation. */
909    for (i = 0; i < 3; i++) {
910        if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
911            if (!TEST_ulong_eq(readbytes, 0))
912                goto end;
913        } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
914                                SSL_ERROR_WANT_READ)) {
915            goto end;
916        }
917        if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
918            if (!TEST_ulong_eq(readbytes, 0))
919                goto end;
920        } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
921                                SSL_ERROR_WANT_READ)) {
922            goto end;
923        }
924    }
925    /* sesspre and sesspost should be different since the cipher changed. */
926    if (!TEST_false(SSL_renegotiate_pending(clientssl))
927            || !TEST_false(SSL_session_reused(clientssl))
928            || !TEST_false(SSL_session_reused(serverssl))
929            || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
930            || !TEST_ptr_ne(sesspre, sesspost)
931            || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
932                            SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
933        goto end;
934
935    shutdown_ssl_connection(serverssl, clientssl);
936    serverssl = clientssl = NULL;
937
938    testresult = 1;
939
940end:
941    SSL_free(serverssl);
942    SSL_free(clientssl);
943    SSL_CTX_free(sctx);
944    SSL_CTX_free(cctx);
945    SSL_SESSION_free(sess);
946
947    return testresult;
948}
949#endif
950
951static int execute_test_large_message(const SSL_METHOD *smeth,
952                                      const SSL_METHOD *cmeth,
953                                      int min_version, int max_version,
954                                      int read_ahead)
955{
956    SSL_CTX *cctx = NULL, *sctx = NULL;
957    SSL *clientssl = NULL, *serverssl = NULL;
958    int testresult = 0;
959    int i;
960    BIO *certbio = NULL;
961    X509 *chaincert = NULL;
962    int certlen;
963
964    if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
965        goto end;
966
967    if (!TEST_ptr(chaincert = X509_new_ex(libctx, NULL)))
968        goto end;
969
970    if (PEM_read_bio_X509(certbio, &chaincert, NULL, NULL) == NULL)
971        goto end;
972    BIO_free(certbio);
973    certbio = NULL;
974
975    if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
976                                       max_version, &sctx, &cctx, cert,
977                                       privkey)))
978        goto end;
979
980#ifdef OPENSSL_NO_DTLS1_2
981    if (smeth == DTLS_server_method()) {
982        /*
983         * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
984         * level 0
985         */
986        if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
987                || !TEST_true(SSL_CTX_set_cipher_list(cctx,
988                                                    "DEFAULT:@SECLEVEL=0")))
989            goto end;
990    }
991#endif
992
993    if (read_ahead) {
994        /*
995         * Test that read_ahead works correctly when dealing with large
996         * records
997         */
998        SSL_CTX_set_read_ahead(cctx, 1);
999    }
1000
1001    /*
1002     * We assume the supplied certificate is big enough so that if we add
1003     * NUM_EXTRA_CERTS it will make the overall message large enough. The
1004     * default buffer size is requested to be 16k, but due to the way BUF_MEM
1005     * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
1006     * test we need to have a message larger than that.
1007     */
1008    certlen = i2d_X509(chaincert, NULL);
1009    OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
1010                   (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
1011    for (i = 0; i < NUM_EXTRA_CERTS; i++) {
1012        if (!X509_up_ref(chaincert))
1013            goto end;
1014        if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
1015            X509_free(chaincert);
1016            goto end;
1017        }
1018    }
1019
1020    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1021                                      NULL, NULL))
1022            || !TEST_true(create_ssl_connection(serverssl, clientssl,
1023                                                SSL_ERROR_NONE)))
1024        goto end;
1025
1026    /*
1027     * Calling SSL_clear() first is not required but this tests that SSL_clear()
1028     * doesn't leak.
1029     */
1030    if (!TEST_true(SSL_clear(serverssl)))
1031        goto end;
1032
1033    testresult = 1;
1034 end:
1035    BIO_free(certbio);
1036    X509_free(chaincert);
1037    SSL_free(serverssl);
1038    SSL_free(clientssl);
1039    SSL_CTX_free(sctx);
1040    SSL_CTX_free(cctx);
1041
1042    return testresult;
1043}
1044
1045#if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_KTLS) && \
1046    !(defined(OSSL_NO_USABLE_TLS1_3) && defined(OPENSSL_NO_TLS1_2))
1047/* sock must be connected */
1048static int ktls_chk_platform(int sock)
1049{
1050    if (!ktls_enable(sock))
1051        return 0;
1052    return 1;
1053}
1054
1055static int ping_pong_query(SSL *clientssl, SSL *serverssl)
1056{
1057    static char count = 1;
1058    unsigned char cbuf[16000] = {0};
1059    unsigned char sbuf[16000];
1060    size_t err = 0;
1061    char crec_wseq_before[SEQ_NUM_SIZE];
1062    char crec_wseq_after[SEQ_NUM_SIZE];
1063    char crec_rseq_before[SEQ_NUM_SIZE];
1064    char crec_rseq_after[SEQ_NUM_SIZE];
1065    char srec_wseq_before[SEQ_NUM_SIZE];
1066    char srec_wseq_after[SEQ_NUM_SIZE];
1067    char srec_rseq_before[SEQ_NUM_SIZE];
1068    char srec_rseq_after[SEQ_NUM_SIZE];
1069
1070    cbuf[0] = count++;
1071    memcpy(crec_wseq_before, &clientssl->rlayer.write_sequence, SEQ_NUM_SIZE);
1072    memcpy(crec_rseq_before, &clientssl->rlayer.read_sequence, SEQ_NUM_SIZE);
1073    memcpy(srec_wseq_before, &serverssl->rlayer.write_sequence, SEQ_NUM_SIZE);
1074    memcpy(srec_rseq_before, &serverssl->rlayer.read_sequence, SEQ_NUM_SIZE);
1075
1076    if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf)))
1077        goto end;
1078
1079    while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) {
1080        if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) {
1081            goto end;
1082        }
1083    }
1084
1085    if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf)))
1086        goto end;
1087
1088    while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) {
1089        if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) {
1090            goto end;
1091        }
1092    }
1093
1094    memcpy(crec_wseq_after, &clientssl->rlayer.write_sequence, SEQ_NUM_SIZE);
1095    memcpy(crec_rseq_after, &clientssl->rlayer.read_sequence, SEQ_NUM_SIZE);
1096    memcpy(srec_wseq_after, &serverssl->rlayer.write_sequence, SEQ_NUM_SIZE);
1097    memcpy(srec_rseq_after, &serverssl->rlayer.read_sequence, SEQ_NUM_SIZE);
1098
1099    /* verify the payload */
1100    if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1101        goto end;
1102
1103    /*
1104     * If ktls is used then kernel sequences are used instead of
1105     * OpenSSL sequences
1106     */
1107    if (!BIO_get_ktls_send(clientssl->wbio)) {
1108        if (!TEST_mem_ne(crec_wseq_before, SEQ_NUM_SIZE,
1109                         crec_wseq_after, SEQ_NUM_SIZE))
1110            goto end;
1111    } else {
1112        if (!TEST_mem_eq(crec_wseq_before, SEQ_NUM_SIZE,
1113                         crec_wseq_after, SEQ_NUM_SIZE))
1114            goto end;
1115    }
1116
1117    if (!BIO_get_ktls_send(serverssl->wbio)) {
1118        if (!TEST_mem_ne(srec_wseq_before, SEQ_NUM_SIZE,
1119                         srec_wseq_after, SEQ_NUM_SIZE))
1120            goto end;
1121    } else {
1122        if (!TEST_mem_eq(srec_wseq_before, SEQ_NUM_SIZE,
1123                         srec_wseq_after, SEQ_NUM_SIZE))
1124            goto end;
1125    }
1126
1127    if (!BIO_get_ktls_recv(clientssl->wbio)) {
1128        if (!TEST_mem_ne(crec_rseq_before, SEQ_NUM_SIZE,
1129                         crec_rseq_after, SEQ_NUM_SIZE))
1130            goto end;
1131    } else {
1132        if (!TEST_mem_eq(crec_rseq_before, SEQ_NUM_SIZE,
1133                         crec_rseq_after, SEQ_NUM_SIZE))
1134            goto end;
1135    }
1136
1137    if (!BIO_get_ktls_recv(serverssl->wbio)) {
1138        if (!TEST_mem_ne(srec_rseq_before, SEQ_NUM_SIZE,
1139                         srec_rseq_after, SEQ_NUM_SIZE))
1140            goto end;
1141    } else {
1142        if (!TEST_mem_eq(srec_rseq_before, SEQ_NUM_SIZE,
1143                         srec_rseq_after, SEQ_NUM_SIZE))
1144            goto end;
1145    }
1146
1147    return 1;
1148end:
1149    return 0;
1150}
1151
1152static int execute_test_ktls(int cis_ktls, int sis_ktls,
1153                             int tls_version, const char *cipher)
1154{
1155    SSL_CTX *cctx = NULL, *sctx = NULL;
1156    SSL *clientssl = NULL, *serverssl = NULL;
1157    int ktls_used = 0, testresult = 0;
1158    int cfd = -1, sfd = -1;
1159    int rx_supported;
1160
1161    if (!TEST_true(create_test_sockets(&cfd, &sfd)))
1162        goto end;
1163
1164    /* Skip this test if the platform does not support ktls */
1165    if (!ktls_chk_platform(cfd)) {
1166        testresult = TEST_skip("Kernel does not support KTLS");
1167        goto end;
1168    }
1169
1170    if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1171        testresult = TEST_skip("CHACHA is not supported in FIPS");
1172        goto end;
1173    }
1174
1175    /* Create a session based on SHA-256 */
1176    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1177                                       TLS_client_method(),
1178                                       tls_version, tls_version,
1179                                       &sctx, &cctx, cert, privkey)))
1180        goto end;
1181
1182    if (tls_version == TLS1_3_VERSION) {
1183        if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1184            || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1185            goto end;
1186    } else {
1187        if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1188            || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1189            goto end;
1190    }
1191
1192    if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1193                                       &clientssl, sfd, cfd)))
1194        goto end;
1195
1196    if (cis_ktls) {
1197        if (!TEST_true(SSL_set_options(clientssl, SSL_OP_ENABLE_KTLS)))
1198            goto end;
1199    }
1200
1201    if (sis_ktls) {
1202        if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1203            goto end;
1204    }
1205
1206    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1207        goto end;
1208
1209    /*
1210     * The running kernel may not support a given cipher suite
1211     * or direction, so just check that KTLS isn't used when it
1212     * isn't enabled.
1213     */
1214    if (!cis_ktls) {
1215        if (!TEST_false(BIO_get_ktls_send(clientssl->wbio)))
1216            goto end;
1217    } else {
1218        if (BIO_get_ktls_send(clientssl->wbio))
1219            ktls_used = 1;
1220    }
1221
1222    if (!sis_ktls) {
1223        if (!TEST_false(BIO_get_ktls_send(serverssl->wbio)))
1224            goto end;
1225    } else {
1226        if (BIO_get_ktls_send(serverssl->wbio))
1227            ktls_used = 1;
1228    }
1229
1230#if defined(OPENSSL_NO_KTLS_RX)
1231    rx_supported = 0;
1232#else
1233    rx_supported = (tls_version != TLS1_3_VERSION);
1234#endif
1235    if (!cis_ktls || !rx_supported) {
1236        if (!TEST_false(BIO_get_ktls_recv(clientssl->rbio)))
1237            goto end;
1238    } else {
1239        if (BIO_get_ktls_send(clientssl->rbio))
1240            ktls_used = 1;
1241    }
1242
1243    if (!sis_ktls || !rx_supported) {
1244        if (!TEST_false(BIO_get_ktls_recv(serverssl->rbio)))
1245            goto end;
1246    } else {
1247        if (BIO_get_ktls_send(serverssl->rbio))
1248            ktls_used = 1;
1249    }
1250
1251    if ((cis_ktls || sis_ktls) && !ktls_used) {
1252        testresult = TEST_skip("KTLS not supported for %s cipher %s",
1253                               tls_version == TLS1_3_VERSION ? "TLS 1.3" :
1254                               "TLS 1.2", cipher);
1255        goto end;
1256    }
1257
1258    if (!TEST_true(ping_pong_query(clientssl, serverssl)))
1259        goto end;
1260
1261    testresult = 1;
1262end:
1263    if (clientssl) {
1264        SSL_shutdown(clientssl);
1265        SSL_free(clientssl);
1266    }
1267    if (serverssl) {
1268        SSL_shutdown(serverssl);
1269        SSL_free(serverssl);
1270    }
1271    SSL_CTX_free(sctx);
1272    SSL_CTX_free(cctx);
1273    serverssl = clientssl = NULL;
1274    if (cfd != -1)
1275        close(cfd);
1276    if (sfd != -1)
1277        close(sfd);
1278    return testresult;
1279}
1280
1281#define SENDFILE_SZ                     (16 * 4096)
1282#define SENDFILE_CHUNK                  (4 * 4096)
1283#define min(a,b)                        ((a) > (b) ? (b) : (a))
1284
1285static int execute_test_ktls_sendfile(int tls_version, const char *cipher)
1286{
1287    SSL_CTX *cctx = NULL, *sctx = NULL;
1288    SSL *clientssl = NULL, *serverssl = NULL;
1289    unsigned char *buf, *buf_dst;
1290    BIO *out = NULL, *in = NULL;
1291    int cfd = -1, sfd = -1, ffd, err;
1292    ssize_t chunk_size = 0;
1293    off_t chunk_off = 0;
1294    int testresult = 0;
1295    FILE *ffdp;
1296
1297    buf = OPENSSL_zalloc(SENDFILE_SZ);
1298    buf_dst = OPENSSL_zalloc(SENDFILE_SZ);
1299    if (!TEST_ptr(buf) || !TEST_ptr(buf_dst)
1300        || !TEST_true(create_test_sockets(&cfd, &sfd)))
1301        goto end;
1302
1303    /* Skip this test if the platform does not support ktls */
1304    if (!ktls_chk_platform(sfd)) {
1305        testresult = TEST_skip("Kernel does not support KTLS");
1306        goto end;
1307    }
1308
1309    if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1310        testresult = TEST_skip("CHACHA is not supported in FIPS");
1311        goto end;
1312    }
1313
1314    /* Create a session based on SHA-256 */
1315    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1316                                       TLS_client_method(),
1317                                       tls_version, tls_version,
1318                                       &sctx, &cctx, cert, privkey)))
1319        goto end;
1320
1321    if (tls_version == TLS1_3_VERSION) {
1322        if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1323            || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1324            goto end;
1325    } else {
1326        if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1327            || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1328            goto end;
1329    }
1330
1331    if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1332                                       &clientssl, sfd, cfd)))
1333        goto end;
1334
1335    if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1336        goto end;
1337
1338    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1339                                         SSL_ERROR_NONE)))
1340        goto end;
1341
1342    if (!BIO_get_ktls_send(serverssl->wbio)) {
1343        testresult = TEST_skip("Failed to enable KTLS for %s cipher %s",
1344                               tls_version == TLS1_3_VERSION ? "TLS 1.3" :
1345                               "TLS 1.2", cipher);
1346        goto end;
1347    }
1348
1349    if (!TEST_int_gt(RAND_bytes_ex(libctx, buf, SENDFILE_SZ, 0), 0))
1350        goto end;
1351
1352    out = BIO_new_file(tmpfilename, "wb");
1353    if (!TEST_ptr(out))
1354        goto end;
1355
1356    if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ)
1357        goto end;
1358
1359    BIO_free(out);
1360    out = NULL;
1361    in = BIO_new_file(tmpfilename, "rb");
1362    BIO_get_fp(in, &ffdp);
1363    ffd = fileno(ffdp);
1364
1365    while (chunk_off < SENDFILE_SZ) {
1366        chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off);
1367        while ((err = SSL_sendfile(serverssl,
1368                                   ffd,
1369                                   chunk_off,
1370                                   chunk_size,
1371                                   0)) != chunk_size) {
1372            if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE)
1373                goto end;
1374        }
1375        while ((err = SSL_read(clientssl,
1376                               buf_dst + chunk_off,
1377                               chunk_size)) != chunk_size) {
1378            if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ)
1379                goto end;
1380        }
1381
1382        /* verify the payload */
1383        if (!TEST_mem_eq(buf_dst + chunk_off,
1384                         chunk_size,
1385                         buf + chunk_off,
1386                         chunk_size))
1387            goto end;
1388
1389        chunk_off += chunk_size;
1390    }
1391
1392    testresult = 1;
1393end:
1394    if (clientssl) {
1395        SSL_shutdown(clientssl);
1396        SSL_free(clientssl);
1397    }
1398    if (serverssl) {
1399        SSL_shutdown(serverssl);
1400        SSL_free(serverssl);
1401    }
1402    SSL_CTX_free(sctx);
1403    SSL_CTX_free(cctx);
1404    serverssl = clientssl = NULL;
1405    BIO_free(out);
1406    BIO_free(in);
1407    if (cfd != -1)
1408        close(cfd);
1409    if (sfd != -1)
1410        close(sfd);
1411    OPENSSL_free(buf);
1412    OPENSSL_free(buf_dst);
1413    return testresult;
1414}
1415
1416static struct ktls_test_cipher {
1417    int tls_version;
1418    const char *cipher;
1419} ktls_test_ciphers[] = {
1420# if !defined(OPENSSL_NO_TLS1_2)
1421#  ifdef OPENSSL_KTLS_AES_GCM_128
1422    { TLS1_2_VERSION, "AES128-GCM-SHA256" },
1423#  endif
1424#  ifdef OPENSSL_KTLS_AES_CCM_128
1425    { TLS1_2_VERSION, "AES128-CCM"},
1426#  endif
1427#  ifdef OPENSSL_KTLS_AES_GCM_256
1428    { TLS1_2_VERSION, "AES256-GCM-SHA384"},
1429#  endif
1430#  ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1431#    ifndef OPENSSL_NO_EC
1432    { TLS1_2_VERSION, "ECDHE-RSA-CHACHA20-POLY1305"},
1433#    endif
1434#  endif
1435# endif
1436# if !defined(OSSL_NO_USABLE_TLS1_3)
1437#  ifdef OPENSSL_KTLS_AES_GCM_128
1438    { TLS1_3_VERSION, "TLS_AES_128_GCM_SHA256" },
1439#  endif
1440#  ifdef OPENSSL_KTLS_AES_CCM_128
1441    { TLS1_3_VERSION, "TLS_AES_128_CCM_SHA256" },
1442#  endif
1443#  ifdef OPENSSL_KTLS_AES_GCM_256
1444    { TLS1_3_VERSION, "TLS_AES_256_GCM_SHA384" },
1445#  endif
1446#  ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1447    { TLS1_3_VERSION, "TLS_CHACHA20_POLY1305_SHA256" },
1448#  endif
1449# endif
1450};
1451
1452#define NUM_KTLS_TEST_CIPHERS \
1453    (sizeof(ktls_test_ciphers) / sizeof(ktls_test_ciphers[0]))
1454
1455static int test_ktls(int test)
1456{
1457    struct ktls_test_cipher *cipher;
1458    int cis_ktls, sis_ktls;
1459
1460    OPENSSL_assert(test / 4 < (int)NUM_KTLS_TEST_CIPHERS);
1461    cipher = &ktls_test_ciphers[test / 4];
1462
1463    cis_ktls = (test & 1) != 0;
1464    sis_ktls = (test & 2) != 0;
1465
1466    return execute_test_ktls(cis_ktls, sis_ktls, cipher->tls_version,
1467                             cipher->cipher);
1468}
1469
1470static int test_ktls_sendfile(int tst)
1471{
1472    struct ktls_test_cipher *cipher;
1473
1474    OPENSSL_assert(tst < (int)NUM_KTLS_TEST_CIPHERS);
1475    cipher = &ktls_test_ciphers[tst];
1476
1477    return execute_test_ktls_sendfile(cipher->tls_version, cipher->cipher);
1478}
1479#endif
1480
1481static int test_large_message_tls(void)
1482{
1483    return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1484                                      TLS1_VERSION, 0, 0);
1485}
1486
1487static int test_large_message_tls_read_ahead(void)
1488{
1489    return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1490                                      TLS1_VERSION, 0, 1);
1491}
1492
1493#ifndef OPENSSL_NO_DTLS
1494static int test_large_message_dtls(void)
1495{
1496# ifdef OPENSSL_NO_DTLS1_2
1497    /* Not supported in the FIPS provider */
1498    if (is_fips)
1499        return 1;
1500# endif
1501    /*
1502     * read_ahead is not relevant to DTLS because DTLS always acts as if
1503     * read_ahead is set.
1504     */
1505    return execute_test_large_message(DTLS_server_method(),
1506                                      DTLS_client_method(),
1507                                      DTLS1_VERSION, 0, 0);
1508}
1509#endif
1510
1511/*
1512 * Test we can successfully send the maximum amount of application data. We
1513 * test each protocol version individually, each with and without EtM enabled.
1514 * TLSv1.3 doesn't use EtM so technically it is redundant to test both but it is
1515 * simpler this way. We also test all combinations with and without the
1516 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS option which affects the size of the
1517 * underlying buffer.
1518 */
1519static int test_large_app_data(int tst)
1520{
1521    SSL_CTX *cctx = NULL, *sctx = NULL;
1522    SSL *clientssl = NULL, *serverssl = NULL;
1523    int testresult = 0, prot;
1524    unsigned char *msg, *buf = NULL;
1525    size_t written, readbytes;
1526    const SSL_METHOD *smeth = TLS_server_method();
1527    const SSL_METHOD *cmeth = TLS_client_method();
1528
1529    switch (tst >> 2) {
1530    case 0:
1531#ifndef OSSL_NO_USABLE_TLS1_3
1532        prot = TLS1_3_VERSION;
1533        break;
1534#else
1535        return 1;
1536#endif
1537
1538    case 1:
1539#ifndef OPENSSL_NO_TLS1_2
1540        prot = TLS1_2_VERSION;
1541        break;
1542#else
1543        return 1;
1544#endif
1545
1546    case 2:
1547#ifndef OPENSSL_NO_TLS1_1
1548        prot = TLS1_1_VERSION;
1549        break;
1550#else
1551        return 1;
1552#endif
1553
1554    case 3:
1555#ifndef OPENSSL_NO_TLS1
1556        prot = TLS1_VERSION;
1557        break;
1558#else
1559        return 1;
1560#endif
1561
1562    case 4:
1563#ifndef OPENSSL_NO_SSL3
1564        prot = SSL3_VERSION;
1565        break;
1566#else
1567        return 1;
1568#endif
1569
1570    case 5:
1571#ifndef OPENSSL_NO_DTLS1_2
1572        prot = DTLS1_2_VERSION;
1573        smeth = DTLS_server_method();
1574        cmeth = DTLS_client_method();
1575        break;
1576#else
1577        return 1;
1578#endif
1579
1580    case 6:
1581#ifndef OPENSSL_NO_DTLS1
1582        prot = DTLS1_VERSION;
1583        smeth = DTLS_server_method();
1584        cmeth = DTLS_client_method();
1585        break;
1586#else
1587        return 1;
1588#endif
1589
1590    default:
1591        /* Shouldn't happen */
1592        return 0;
1593    }
1594
1595    if ((prot < TLS1_2_VERSION || prot == DTLS1_VERSION) && is_fips)
1596        return 1;
1597
1598    /* Maximal sized message of zeros */
1599    msg = OPENSSL_zalloc(SSL3_RT_MAX_PLAIN_LENGTH);
1600    if (!TEST_ptr(msg))
1601        goto end;
1602
1603    buf = OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH + 1);
1604    if (!TEST_ptr(buf))
1605        goto end;
1606    /* Set whole buffer to all bits set */
1607    memset(buf, 0xff, SSL3_RT_MAX_PLAIN_LENGTH + 1);
1608
1609    if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, prot, prot,
1610                                       &sctx, &cctx, cert, privkey)))
1611        goto end;
1612
1613    if (prot < TLS1_2_VERSION || prot == DTLS1_VERSION) {
1614        /* Older protocol versions need SECLEVEL=0 due to SHA1 usage */
1615        if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0"))
1616                || !TEST_true(SSL_CTX_set_cipher_list(sctx,
1617                                                      "DEFAULT:@SECLEVEL=0")))
1618        goto end;
1619    }
1620
1621    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1622                                      &clientssl, NULL, NULL)))
1623        goto end;
1624
1625    if ((tst & 1) != 0) {
1626        /* Setting this option gives us a minimally sized underlying buffer */
1627        if (!TEST_true(SSL_set_options(serverssl,
1628                                       SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
1629                || !TEST_true(SSL_set_options(clientssl,
1630                                              SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)))
1631            goto end;
1632    }
1633
1634    if ((tst & 2) != 0) {
1635        /*
1636         * Setting this option means the MAC is added before encryption
1637         * giving us a larger record for the encryption process
1638         */
1639        if (!TEST_true(SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC))
1640                || !TEST_true(SSL_set_options(clientssl,
1641                                              SSL_OP_NO_ENCRYPT_THEN_MAC)))
1642            goto end;
1643    }
1644
1645    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1646        goto end;
1647
1648    if (!TEST_true(SSL_write_ex(clientssl, msg, SSL3_RT_MAX_PLAIN_LENGTH,
1649                                &written))
1650            || !TEST_size_t_eq(written, SSL3_RT_MAX_PLAIN_LENGTH))
1651        goto end;
1652
1653    /* We provide a buffer slightly larger than what we are actually expecting */
1654    if (!TEST_true(SSL_read_ex(serverssl, buf, SSL3_RT_MAX_PLAIN_LENGTH + 1,
1655                               &readbytes)))
1656        goto end;
1657
1658    if (!TEST_mem_eq(msg, written, buf, readbytes))
1659        goto end;
1660
1661    testresult = 1;
1662end:
1663    OPENSSL_free(msg);
1664    OPENSSL_free(buf);
1665    SSL_free(serverssl);
1666    SSL_free(clientssl);
1667    SSL_CTX_free(sctx);
1668    SSL_CTX_free(cctx);
1669    return testresult;
1670}
1671
1672static int execute_cleanse_plaintext(const SSL_METHOD *smeth,
1673                                     const SSL_METHOD *cmeth,
1674                                     int min_version, int max_version)
1675{
1676    size_t i;
1677    SSL_CTX *cctx = NULL, *sctx = NULL;
1678    SSL *clientssl = NULL, *serverssl = NULL;
1679    int testresult = 0;
1680    SSL3_RECORD *rr;
1681    void *zbuf;
1682
1683    static unsigned char cbuf[16000];
1684    static unsigned char sbuf[16000];
1685
1686    if (!TEST_true(create_ssl_ctx_pair(libctx,
1687                                       smeth, cmeth,
1688                                       min_version, max_version,
1689                                       &sctx, &cctx, cert,
1690                                       privkey)))
1691        goto end;
1692
1693#ifdef OPENSSL_NO_DTLS1_2
1694    if (smeth == DTLS_server_method()) {
1695# ifdef OPENSSL_NO_DTLS1_2
1696        /* Not supported in the FIPS provider */
1697        if (is_fips) {
1698            testresult = 1;
1699            goto end;
1700        };
1701# endif
1702        /*
1703         * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
1704         * level 0
1705         */
1706        if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
1707                || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1708                                                    "DEFAULT:@SECLEVEL=0")))
1709            goto end;
1710    }
1711#endif
1712
1713    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1714                                      NULL, NULL)))
1715        goto end;
1716
1717    if (!TEST_true(SSL_set_options(serverssl, SSL_OP_CLEANSE_PLAINTEXT)))
1718        goto end;
1719
1720    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1721                                         SSL_ERROR_NONE)))
1722        goto end;
1723
1724    for (i = 0; i < sizeof(cbuf); i++) {
1725        cbuf[i] = i & 0xff;
1726    }
1727
1728    if (!TEST_int_eq(SSL_write(clientssl, cbuf, sizeof(cbuf)), sizeof(cbuf)))
1729        goto end;
1730
1731    if (!TEST_int_eq(SSL_peek(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1732        goto end;
1733
1734    if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1735        goto end;
1736
1737    /*
1738     * Since we called SSL_peek(), we know the data in the record
1739     * layer is a plaintext record. We can gather the pointer to check
1740     * for zeroization after SSL_read().
1741     */
1742    rr = serverssl->rlayer.rrec;
1743    zbuf = &rr->data[rr->off];
1744    if (!TEST_int_eq(rr->length, sizeof(cbuf)))
1745        goto end;
1746
1747    /*
1748     * After SSL_peek() the plaintext must still be stored in the
1749     * record.
1750     */
1751    if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1752        goto end;
1753
1754    memset(sbuf, 0, sizeof(sbuf));
1755    if (!TEST_int_eq(SSL_read(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1756        goto end;
1757
1758    if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(cbuf)))
1759        goto end;
1760
1761    /* Check if rbuf is cleansed */
1762    memset(cbuf, 0, sizeof(cbuf));
1763    if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1764        goto end;
1765
1766    testresult = 1;
1767 end:
1768    SSL_free(serverssl);
1769    SSL_free(clientssl);
1770    SSL_CTX_free(sctx);
1771    SSL_CTX_free(cctx);
1772
1773    return testresult;
1774}
1775
1776static int test_cleanse_plaintext(void)
1777{
1778#if !defined(OPENSSL_NO_TLS1_2)
1779    if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1780                                             TLS_client_method(),
1781                                             TLS1_2_VERSION,
1782                                             TLS1_2_VERSION)))
1783        return 0;
1784
1785#endif
1786
1787#if !defined(OSSL_NO_USABLE_TLS1_3)
1788    if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1789                                             TLS_client_method(),
1790                                             TLS1_3_VERSION,
1791                                             TLS1_3_VERSION)))
1792        return 0;
1793#endif
1794
1795#if !defined(OPENSSL_NO_DTLS)
1796
1797    if (!TEST_true(execute_cleanse_plaintext(DTLS_server_method(),
1798                                             DTLS_client_method(),
1799                                             DTLS1_VERSION,
1800                                             0)))
1801        return 0;
1802#endif
1803    return 1;
1804}
1805
1806#ifndef OPENSSL_NO_OCSP
1807static int ocsp_server_cb(SSL *s, void *arg)
1808{
1809    int *argi = (int *)arg;
1810    unsigned char *copy = NULL;
1811    STACK_OF(OCSP_RESPID) *ids = NULL;
1812    OCSP_RESPID *id = NULL;
1813
1814    if (*argi == 2) {
1815        /* In this test we are expecting exactly 1 OCSP_RESPID */
1816        SSL_get_tlsext_status_ids(s, &ids);
1817        if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
1818            return SSL_TLSEXT_ERR_ALERT_FATAL;
1819
1820        id = sk_OCSP_RESPID_value(ids, 0);
1821        if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL))
1822            return SSL_TLSEXT_ERR_ALERT_FATAL;
1823    } else if (*argi != 1) {
1824        return SSL_TLSEXT_ERR_ALERT_FATAL;
1825    }
1826
1827    if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
1828        return SSL_TLSEXT_ERR_ALERT_FATAL;
1829
1830    if (!TEST_true(SSL_set_tlsext_status_ocsp_resp(s, copy,
1831                                                   sizeof(orespder)))) {
1832        OPENSSL_free(copy);
1833        return SSL_TLSEXT_ERR_ALERT_FATAL;
1834    }
1835    ocsp_server_called = 1;
1836    return SSL_TLSEXT_ERR_OK;
1837}
1838
1839static int ocsp_client_cb(SSL *s, void *arg)
1840{
1841    int *argi = (int *)arg;
1842    const unsigned char *respderin;
1843    size_t len;
1844
1845    if (*argi != 1 && *argi != 2)
1846        return 0;
1847
1848    len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
1849    if (!TEST_mem_eq(orespder, len, respderin, len))
1850        return 0;
1851
1852    ocsp_client_called = 1;
1853    return 1;
1854}
1855
1856static int test_tlsext_status_type(void)
1857{
1858    SSL_CTX *cctx = NULL, *sctx = NULL;
1859    SSL *clientssl = NULL, *serverssl = NULL;
1860    int testresult = 0;
1861    STACK_OF(OCSP_RESPID) *ids = NULL;
1862    OCSP_RESPID *id = NULL;
1863    BIO *certbio = NULL;
1864
1865    if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
1866                             TLS1_VERSION, 0,
1867                             &sctx, &cctx, cert, privkey))
1868        return 0;
1869
1870    if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
1871        goto end;
1872
1873    /* First just do various checks getting and setting tlsext_status_type */
1874
1875    clientssl = SSL_new(cctx);
1876    if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
1877            || !TEST_true(SSL_set_tlsext_status_type(clientssl,
1878                                                      TLSEXT_STATUSTYPE_ocsp))
1879            || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
1880                            TLSEXT_STATUSTYPE_ocsp))
1881        goto end;
1882
1883    SSL_free(clientssl);
1884    clientssl = NULL;
1885
1886    if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
1887     || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
1888        goto end;
1889
1890    clientssl = SSL_new(cctx);
1891    if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
1892        goto end;
1893    SSL_free(clientssl);
1894    clientssl = NULL;
1895
1896    /*
1897     * Now actually do a handshake and check OCSP information is exchanged and
1898     * the callbacks get called
1899     */
1900    SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
1901    SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
1902    SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
1903    SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
1904    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1905                                      &clientssl, NULL, NULL))
1906            || !TEST_true(create_ssl_connection(serverssl, clientssl,
1907                                                SSL_ERROR_NONE))
1908            || !TEST_true(ocsp_client_called)
1909            || !TEST_true(ocsp_server_called))
1910        goto end;
1911    SSL_free(serverssl);
1912    SSL_free(clientssl);
1913    serverssl = NULL;
1914    clientssl = NULL;
1915
1916    /* Try again but this time force the server side callback to fail */
1917    ocsp_client_called = 0;
1918    ocsp_server_called = 0;
1919    cdummyarg = 0;
1920    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1921                                      &clientssl, NULL, NULL))
1922                /* This should fail because the callback will fail */
1923            || !TEST_false(create_ssl_connection(serverssl, clientssl,
1924                                                 SSL_ERROR_NONE))
1925            || !TEST_false(ocsp_client_called)
1926            || !TEST_false(ocsp_server_called))
1927        goto end;
1928    SSL_free(serverssl);
1929    SSL_free(clientssl);
1930    serverssl = NULL;
1931    clientssl = NULL;
1932
1933    /*
1934     * This time we'll get the client to send an OCSP_RESPID that it will
1935     * accept.
1936     */
1937    ocsp_client_called = 0;
1938    ocsp_server_called = 0;
1939    cdummyarg = 2;
1940    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1941                                      &clientssl, NULL, NULL)))
1942        goto end;
1943
1944    /*
1945     * We'll just use any old cert for this test - it doesn't have to be an OCSP
1946     * specific one. We'll use the server cert.
1947     */
1948    if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
1949            || !TEST_ptr(id = OCSP_RESPID_new())
1950            || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
1951            || !TEST_ptr(ocspcert = X509_new_ex(libctx, NULL))
1952            || !TEST_ptr(PEM_read_bio_X509(certbio, &ocspcert, NULL, NULL))
1953            || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL))
1954            || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
1955        goto end;
1956    id = NULL;
1957    SSL_set_tlsext_status_ids(clientssl, ids);
1958    /* Control has been transferred */
1959    ids = NULL;
1960
1961    BIO_free(certbio);
1962    certbio = NULL;
1963
1964    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1965                                         SSL_ERROR_NONE))
1966            || !TEST_true(ocsp_client_called)
1967            || !TEST_true(ocsp_server_called))
1968        goto end;
1969
1970    testresult = 1;
1971
1972 end:
1973    SSL_free(serverssl);
1974    SSL_free(clientssl);
1975    SSL_CTX_free(sctx);
1976    SSL_CTX_free(cctx);
1977    sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
1978    OCSP_RESPID_free(id);
1979    BIO_free(certbio);
1980    X509_free(ocspcert);
1981    ocspcert = NULL;
1982
1983    return testresult;
1984}
1985#endif
1986
1987#if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
1988static int new_called, remove_called, get_called;
1989
1990static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
1991{
1992    new_called++;
1993    /*
1994     * sess has been up-refed for us, but we don't actually need it so free it
1995     * immediately.
1996     */
1997    SSL_SESSION_free(sess);
1998    return 1;
1999}
2000
2001static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
2002{
2003    remove_called++;
2004}
2005
2006static SSL_SESSION *get_sess_val = NULL;
2007
2008static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
2009                                   int *copy)
2010{
2011    get_called++;
2012    *copy = 1;
2013    return get_sess_val;
2014}
2015
2016static int execute_test_session(int maxprot, int use_int_cache,
2017                                int use_ext_cache, long s_options)
2018{
2019    SSL_CTX *sctx = NULL, *cctx = NULL;
2020    SSL *serverssl1 = NULL, *clientssl1 = NULL;
2021    SSL *serverssl2 = NULL, *clientssl2 = NULL;
2022# ifndef OPENSSL_NO_TLS1_1
2023    SSL *serverssl3 = NULL, *clientssl3 = NULL;
2024# endif
2025    SSL_SESSION *sess1 = NULL, *sess2 = NULL;
2026    int testresult = 0, numnewsesstick = 1;
2027
2028    new_called = remove_called = 0;
2029
2030    /* TLSv1.3 sends 2 NewSessionTickets */
2031    if (maxprot == TLS1_3_VERSION)
2032        numnewsesstick = 2;
2033
2034    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2035                                       TLS_client_method(), TLS1_VERSION, 0,
2036                                       &sctx, &cctx, cert, privkey)))
2037        return 0;
2038
2039    /*
2040     * Only allow the max protocol version so we can force a connection failure
2041     * later
2042     */
2043    SSL_CTX_set_min_proto_version(cctx, maxprot);
2044    SSL_CTX_set_max_proto_version(cctx, maxprot);
2045
2046    /* Set up session cache */
2047    if (use_ext_cache) {
2048        SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2049        SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
2050    }
2051    if (use_int_cache) {
2052        /* Also covers instance where both are set */
2053        SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
2054    } else {
2055        SSL_CTX_set_session_cache_mode(cctx,
2056                                       SSL_SESS_CACHE_CLIENT
2057                                       | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2058    }
2059
2060    if (s_options) {
2061        SSL_CTX_set_options(sctx, s_options);
2062    }
2063
2064    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2065                                      NULL, NULL))
2066            || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2067                                                SSL_ERROR_NONE))
2068            || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
2069        goto end;
2070
2071    /* Should fail because it should already be in the cache */
2072    if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
2073        goto end;
2074    if (use_ext_cache
2075            && (!TEST_int_eq(new_called, numnewsesstick)
2076
2077                || !TEST_int_eq(remove_called, 0)))
2078        goto end;
2079
2080    new_called = remove_called = 0;
2081    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2082                                      &clientssl2, NULL, NULL))
2083            || !TEST_true(SSL_set_session(clientssl2, sess1))
2084            || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2085                                                SSL_ERROR_NONE))
2086            || !TEST_true(SSL_session_reused(clientssl2)))
2087        goto end;
2088
2089    if (maxprot == TLS1_3_VERSION) {
2090        /*
2091         * In TLSv1.3 we should have created a new session even though we have
2092         * resumed. Since we attempted a resume we should also have removed the
2093         * old ticket from the cache so that we try to only use tickets once.
2094         */
2095        if (use_ext_cache
2096                && (!TEST_int_eq(new_called, 1)
2097                    || !TEST_int_eq(remove_called, 1)))
2098            goto end;
2099    } else {
2100        /*
2101         * In TLSv1.2 we expect to have resumed so no sessions added or
2102         * removed.
2103         */
2104        if (use_ext_cache
2105                && (!TEST_int_eq(new_called, 0)
2106                    || !TEST_int_eq(remove_called, 0)))
2107            goto end;
2108    }
2109
2110    SSL_SESSION_free(sess1);
2111    if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
2112        goto end;
2113    shutdown_ssl_connection(serverssl2, clientssl2);
2114    serverssl2 = clientssl2 = NULL;
2115
2116    new_called = remove_called = 0;
2117    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2118                                      &clientssl2, NULL, NULL))
2119            || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2120                                                SSL_ERROR_NONE)))
2121        goto end;
2122
2123    if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
2124        goto end;
2125
2126    if (use_ext_cache
2127            && (!TEST_int_eq(new_called, numnewsesstick)
2128                || !TEST_int_eq(remove_called, 0)))
2129        goto end;
2130
2131    new_called = remove_called = 0;
2132    /*
2133     * This should clear sess2 from the cache because it is a "bad" session.
2134     * See SSL_set_session() documentation.
2135     */
2136    if (!TEST_true(SSL_set_session(clientssl2, sess1)))
2137        goto end;
2138    if (use_ext_cache
2139            && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2140        goto end;
2141    if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
2142        goto end;
2143
2144    if (use_int_cache) {
2145        /* Should succeeded because it should not already be in the cache */
2146        if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
2147                || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
2148            goto end;
2149    }
2150
2151    new_called = remove_called = 0;
2152    /* This shouldn't be in the cache so should fail */
2153    if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
2154        goto end;
2155
2156    if (use_ext_cache
2157            && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2158        goto end;
2159
2160# if !defined(OPENSSL_NO_TLS1_1)
2161    new_called = remove_called = 0;
2162    /* Force a connection failure */
2163    SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
2164    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
2165                                      &clientssl3, NULL, NULL))
2166            || !TEST_true(SSL_set_session(clientssl3, sess1))
2167            /* This should fail because of the mismatched protocol versions */
2168            || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
2169                                                 SSL_ERROR_NONE)))
2170        goto end;
2171
2172    /* We should have automatically removed the session from the cache */
2173    if (use_ext_cache
2174            && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2175        goto end;
2176
2177    /* Should succeed because it should not already be in the cache */
2178    if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
2179        goto end;
2180# endif
2181
2182    /* Now do some tests for server side caching */
2183    if (use_ext_cache) {
2184        SSL_CTX_sess_set_new_cb(cctx, NULL);
2185        SSL_CTX_sess_set_remove_cb(cctx, NULL);
2186        SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2187        SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
2188        SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
2189        get_sess_val = NULL;
2190    }
2191
2192    SSL_CTX_set_session_cache_mode(cctx, 0);
2193    /* Internal caching is the default on the server side */
2194    if (!use_int_cache)
2195        SSL_CTX_set_session_cache_mode(sctx,
2196                                       SSL_SESS_CACHE_SERVER
2197                                       | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2198
2199    SSL_free(serverssl1);
2200    SSL_free(clientssl1);
2201    serverssl1 = clientssl1 = NULL;
2202    SSL_free(serverssl2);
2203    SSL_free(clientssl2);
2204    serverssl2 = clientssl2 = NULL;
2205    SSL_SESSION_free(sess1);
2206    sess1 = NULL;
2207    SSL_SESSION_free(sess2);
2208    sess2 = NULL;
2209
2210    SSL_CTX_set_max_proto_version(sctx, maxprot);
2211    if (maxprot == TLS1_2_VERSION)
2212        SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
2213    new_called = remove_called = get_called = 0;
2214    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2215                                      NULL, NULL))
2216            || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2217                                                SSL_ERROR_NONE))
2218            || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
2219            || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
2220        goto end;
2221
2222    if (use_int_cache) {
2223        if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
2224            /*
2225             * In TLSv1.3 it should not have been added to the internal cache,
2226             * except in the case where we also have an external cache (in that
2227             * case it gets added to the cache in order to generate remove
2228             * events after timeout).
2229             */
2230            if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
2231                goto end;
2232        } else {
2233            /* Should fail because it should already be in the cache */
2234            if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
2235                goto end;
2236        }
2237    }
2238
2239    if (use_ext_cache) {
2240        SSL_SESSION *tmp = sess2;
2241
2242        if (!TEST_int_eq(new_called, numnewsesstick)
2243                || !TEST_int_eq(remove_called, 0)
2244                || !TEST_int_eq(get_called, 0))
2245            goto end;
2246        /*
2247         * Delete the session from the internal cache to force a lookup from
2248         * the external cache. We take a copy first because
2249         * SSL_CTX_remove_session() also marks the session as non-resumable.
2250         */
2251        if (use_int_cache && maxprot != TLS1_3_VERSION) {
2252            if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
2253                || !TEST_true(sess2->owner != NULL)
2254                || !TEST_true(tmp->owner == NULL)
2255                || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
2256                goto end;
2257            SSL_SESSION_free(sess2);
2258        }
2259        sess2 = tmp;
2260    }
2261
2262    new_called = remove_called = get_called = 0;
2263    get_sess_val = sess2;
2264    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2265                                      &clientssl2, NULL, NULL))
2266            || !TEST_true(SSL_set_session(clientssl2, sess1))
2267            || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2268                                                SSL_ERROR_NONE))
2269            || !TEST_true(SSL_session_reused(clientssl2)))
2270        goto end;
2271
2272    if (use_ext_cache) {
2273        if (!TEST_int_eq(remove_called, 0))
2274            goto end;
2275
2276        if (maxprot == TLS1_3_VERSION) {
2277            if (!TEST_int_eq(new_called, 1)
2278                    || !TEST_int_eq(get_called, 0))
2279                goto end;
2280        } else {
2281            if (!TEST_int_eq(new_called, 0)
2282                    || !TEST_int_eq(get_called, 1))
2283                goto end;
2284        }
2285    }
2286    /*
2287     * Make a small cache, force out all other sessions but
2288     * sess2, try to add sess1, which should succeed. Then
2289     * make sure it's there by checking the owners. Despite
2290     * the timeouts, sess1 should have kicked out sess2
2291     */
2292
2293    /* Make sess1 expire before sess2 */
2294    if (!TEST_long_gt(SSL_SESSION_set_time(sess1, 1000), 0)
2295            || !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0)
2296            || !TEST_long_gt(SSL_SESSION_set_time(sess2, 2000), 0)
2297            || !TEST_long_gt(SSL_SESSION_set_timeout(sess2, 2000), 0))
2298        goto end;
2299
2300    if (!TEST_long_ne(SSL_CTX_sess_set_cache_size(sctx, 1), 0))
2301        goto end;
2302
2303    /* Don't care about results - cache should only be sess2 at end */
2304    SSL_CTX_add_session(sctx, sess1);
2305    SSL_CTX_add_session(sctx, sess2);
2306
2307    /* Now add sess1, and make sure it remains, despite timeout */
2308    if (!TEST_true(SSL_CTX_add_session(sctx, sess1))
2309            || !TEST_ptr(sess1->owner)
2310            || !TEST_ptr_null(sess2->owner))
2311        goto end;
2312
2313    testresult = 1;
2314
2315 end:
2316    SSL_free(serverssl1);
2317    SSL_free(clientssl1);
2318    SSL_free(serverssl2);
2319    SSL_free(clientssl2);
2320# ifndef OPENSSL_NO_TLS1_1
2321    SSL_free(serverssl3);
2322    SSL_free(clientssl3);
2323# endif
2324    SSL_SESSION_free(sess1);
2325    SSL_SESSION_free(sess2);
2326    SSL_CTX_free(sctx);
2327    SSL_CTX_free(cctx);
2328
2329    return testresult;
2330}
2331#endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
2332
2333static int test_session_with_only_int_cache(void)
2334{
2335#ifndef OSSL_NO_USABLE_TLS1_3
2336    if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0))
2337        return 0;
2338#endif
2339
2340#ifndef OPENSSL_NO_TLS1_2
2341    return execute_test_session(TLS1_2_VERSION, 1, 0, 0);
2342#else
2343    return 1;
2344#endif
2345}
2346
2347static int test_session_with_only_ext_cache(void)
2348{
2349#ifndef OSSL_NO_USABLE_TLS1_3
2350    if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0))
2351        return 0;
2352#endif
2353
2354#ifndef OPENSSL_NO_TLS1_2
2355    return execute_test_session(TLS1_2_VERSION, 0, 1, 0);
2356#else
2357    return 1;
2358#endif
2359}
2360
2361static int test_session_with_both_cache(void)
2362{
2363#ifndef OSSL_NO_USABLE_TLS1_3
2364    if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0))
2365        return 0;
2366#endif
2367
2368#ifndef OPENSSL_NO_TLS1_2
2369    return execute_test_session(TLS1_2_VERSION, 1, 1, 0);
2370#else
2371    return 1;
2372#endif
2373}
2374
2375static int test_session_wo_ca_names(void)
2376{
2377#ifndef OSSL_NO_USABLE_TLS1_3
2378    if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES))
2379        return 0;
2380#endif
2381
2382#ifndef OPENSSL_NO_TLS1_2
2383    return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
2384#else
2385    return 1;
2386#endif
2387}
2388
2389
2390#ifndef OSSL_NO_USABLE_TLS1_3
2391static SSL_SESSION *sesscache[6];
2392static int do_cache;
2393
2394static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
2395{
2396    if (do_cache) {
2397        sesscache[new_called] = sess;
2398    } else {
2399        /* We don't need the reference to the session, so free it */
2400        SSL_SESSION_free(sess);
2401    }
2402    new_called++;
2403
2404    return 1;
2405}
2406
2407static int post_handshake_verify(SSL *sssl, SSL *cssl)
2408{
2409    SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
2410    if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
2411        return 0;
2412
2413    /* Start handshake on the server and client */
2414    if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
2415            || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
2416            || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
2417            || !TEST_true(create_ssl_connection(sssl, cssl,
2418                                                SSL_ERROR_NONE)))
2419        return 0;
2420
2421    return 1;
2422}
2423
2424static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
2425                             SSL_CTX **cctx)
2426{
2427    int sess_id_ctx = 1;
2428
2429    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2430                                       TLS_client_method(), TLS1_VERSION, 0,
2431                                       sctx, cctx, cert, privkey))
2432            || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
2433            || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
2434                                                         (void *)&sess_id_ctx,
2435                                                         sizeof(sess_id_ctx))))
2436        return 0;
2437
2438    if (stateful)
2439        SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
2440
2441    SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT
2442                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2443    SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
2444
2445    return 1;
2446}
2447
2448static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
2449{
2450    SSL *serverssl = NULL, *clientssl = NULL;
2451    int i;
2452
2453    /* Test that we can resume with all the tickets we got given */
2454    for (i = 0; i < idx * 2; i++) {
2455        new_called = 0;
2456        if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2457                                              &clientssl, NULL, NULL))
2458                || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
2459            goto end;
2460
2461        SSL_set_post_handshake_auth(clientssl, 1);
2462
2463        if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2464                                                    SSL_ERROR_NONE)))
2465            goto end;
2466
2467        /*
2468         * Following a successful resumption we only get 1 ticket. After a
2469         * failed one we should get idx tickets.
2470         */
2471        if (succ) {
2472            if (!TEST_true(SSL_session_reused(clientssl))
2473                    || !TEST_int_eq(new_called, 1))
2474                goto end;
2475        } else {
2476            if (!TEST_false(SSL_session_reused(clientssl))
2477                    || !TEST_int_eq(new_called, idx))
2478                goto end;
2479        }
2480
2481        new_called = 0;
2482        /* After a post-handshake authentication we should get 1 new ticket */
2483        if (succ
2484                && (!post_handshake_verify(serverssl, clientssl)
2485                    || !TEST_int_eq(new_called, 1)))
2486            goto end;
2487
2488        SSL_shutdown(clientssl);
2489        SSL_shutdown(serverssl);
2490        SSL_free(serverssl);
2491        SSL_free(clientssl);
2492        serverssl = clientssl = NULL;
2493        SSL_SESSION_free(sesscache[i]);
2494        sesscache[i] = NULL;
2495    }
2496
2497    return 1;
2498
2499 end:
2500    SSL_free(clientssl);
2501    SSL_free(serverssl);
2502    return 0;
2503}
2504
2505static int test_tickets(int stateful, int idx)
2506{
2507    SSL_CTX *sctx = NULL, *cctx = NULL;
2508    SSL *serverssl = NULL, *clientssl = NULL;
2509    int testresult = 0;
2510    size_t j;
2511
2512    /* idx is the test number, but also the number of tickets we want */
2513
2514    new_called = 0;
2515    do_cache = 1;
2516
2517    if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2518        goto end;
2519
2520    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2521                                          &clientssl, NULL, NULL)))
2522        goto end;
2523
2524    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2525                                                SSL_ERROR_NONE))
2526               /* Check we got the number of tickets we were expecting */
2527            || !TEST_int_eq(idx, new_called))
2528        goto end;
2529
2530    SSL_shutdown(clientssl);
2531    SSL_shutdown(serverssl);
2532    SSL_free(serverssl);
2533    SSL_free(clientssl);
2534    SSL_CTX_free(sctx);
2535    SSL_CTX_free(cctx);
2536    clientssl = serverssl = NULL;
2537    sctx = cctx = NULL;
2538
2539    /*
2540     * Now we try to resume with the tickets we previously created. The
2541     * resumption attempt is expected to fail (because we're now using a new
2542     * SSL_CTX). We should see idx number of tickets issued again.
2543     */
2544
2545    /* Stop caching sessions - just count them */
2546    do_cache = 0;
2547
2548    if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2549        goto end;
2550
2551    if (!check_resumption(idx, sctx, cctx, 0))
2552        goto end;
2553
2554    /* Start again with caching sessions */
2555    new_called = 0;
2556    do_cache = 1;
2557    SSL_CTX_free(sctx);
2558    SSL_CTX_free(cctx);
2559    sctx = cctx = NULL;
2560
2561    if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2562        goto end;
2563
2564    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2565                                          &clientssl, NULL, NULL)))
2566        goto end;
2567
2568    SSL_set_post_handshake_auth(clientssl, 1);
2569
2570    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2571                                                SSL_ERROR_NONE))
2572               /* Check we got the number of tickets we were expecting */
2573            || !TEST_int_eq(idx, new_called))
2574        goto end;
2575
2576    /* After a post-handshake authentication we should get new tickets issued */
2577    if (!post_handshake_verify(serverssl, clientssl)
2578            || !TEST_int_eq(idx * 2, new_called))
2579        goto end;
2580
2581    SSL_shutdown(clientssl);
2582    SSL_shutdown(serverssl);
2583    SSL_free(serverssl);
2584    SSL_free(clientssl);
2585    serverssl = clientssl = NULL;
2586
2587    /* Stop caching sessions - just count them */
2588    do_cache = 0;
2589
2590    /*
2591     * Check we can resume with all the tickets we created. This time around the
2592     * resumptions should all be successful.
2593     */
2594    if (!check_resumption(idx, sctx, cctx, 1))
2595        goto end;
2596
2597    testresult = 1;
2598
2599 end:
2600    SSL_free(serverssl);
2601    SSL_free(clientssl);
2602    for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2603        SSL_SESSION_free(sesscache[j]);
2604        sesscache[j] = NULL;
2605    }
2606    SSL_CTX_free(sctx);
2607    SSL_CTX_free(cctx);
2608
2609    return testresult;
2610}
2611
2612static int test_stateless_tickets(int idx)
2613{
2614    return test_tickets(0, idx);
2615}
2616
2617static int test_stateful_tickets(int idx)
2618{
2619    return test_tickets(1, idx);
2620}
2621
2622static int test_psk_tickets(void)
2623{
2624    SSL_CTX *sctx = NULL, *cctx = NULL;
2625    SSL *serverssl = NULL, *clientssl = NULL;
2626    int testresult = 0;
2627    int sess_id_ctx = 1;
2628
2629    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2630                                       TLS_client_method(), TLS1_VERSION, 0,
2631                                       &sctx, &cctx, NULL, NULL))
2632            || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2633                                                         (void *)&sess_id_ctx,
2634                                                         sizeof(sess_id_ctx))))
2635        goto end;
2636
2637    SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
2638                                         | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2639    SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2640    SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2641    SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2642    use_session_cb_cnt = 0;
2643    find_session_cb_cnt = 0;
2644    srvid = pskid;
2645    new_called = 0;
2646
2647    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2648                                      NULL, NULL)))
2649        goto end;
2650    clientpsk = serverpsk = create_a_psk(clientssl, SHA384_DIGEST_LENGTH);
2651    if (!TEST_ptr(clientpsk))
2652        goto end;
2653    SSL_SESSION_up_ref(clientpsk);
2654
2655    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2656                                                SSL_ERROR_NONE))
2657            || !TEST_int_eq(1, find_session_cb_cnt)
2658            || !TEST_int_eq(1, use_session_cb_cnt)
2659               /* We should always get 1 ticket when using external PSK */
2660            || !TEST_int_eq(1, new_called))
2661        goto end;
2662
2663    testresult = 1;
2664
2665 end:
2666    SSL_free(serverssl);
2667    SSL_free(clientssl);
2668    SSL_CTX_free(sctx);
2669    SSL_CTX_free(cctx);
2670    SSL_SESSION_free(clientpsk);
2671    SSL_SESSION_free(serverpsk);
2672    clientpsk = serverpsk = NULL;
2673
2674    return testresult;
2675}
2676
2677static int test_extra_tickets(int idx)
2678{
2679    SSL_CTX *sctx = NULL, *cctx = NULL;
2680    SSL *serverssl = NULL, *clientssl = NULL;
2681    BIO *bretry = BIO_new(bio_s_always_retry());
2682    BIO *tmp = NULL;
2683    int testresult = 0;
2684    int stateful = 0;
2685    size_t nbytes;
2686    unsigned char c, buf[1];
2687
2688    new_called = 0;
2689    do_cache = 1;
2690
2691    if (idx >= 3) {
2692        idx -= 3;
2693        stateful = 1;
2694    }
2695
2696    if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2697        goto end;
2698    SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2699    /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2700    SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2701
2702    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2703                                          &clientssl, NULL, NULL)))
2704        goto end;
2705
2706    /*
2707     * Note that we have new_session_cb on both sctx and cctx, so new_called is
2708     * incremented by both client and server.
2709     */
2710    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2711                                                SSL_ERROR_NONE))
2712               /* Check we got the number of tickets we were expecting */
2713            || !TEST_int_eq(idx * 2, new_called)
2714            || !TEST_true(SSL_new_session_ticket(serverssl))
2715            || !TEST_true(SSL_new_session_ticket(serverssl))
2716            || !TEST_int_eq(idx * 2, new_called))
2717        goto end;
2718
2719    /* Now try a (real) write to actually send the tickets */
2720    c = '1';
2721    if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2722            || !TEST_size_t_eq(1, nbytes)
2723            || !TEST_int_eq(idx * 2 + 2, new_called)
2724            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2725            || !TEST_int_eq(idx * 2 + 4, new_called)
2726            || !TEST_int_eq(sizeof(buf), nbytes)
2727            || !TEST_int_eq(c, buf[0])
2728            || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2729        goto end;
2730
2731    /* Try with only requesting one new ticket, too */
2732    c = '2';
2733    new_called = 0;
2734    if (!TEST_true(SSL_new_session_ticket(serverssl))
2735            || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2736            || !TEST_size_t_eq(sizeof(c), nbytes)
2737            || !TEST_int_eq(1, new_called)
2738            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2739            || !TEST_int_eq(2, new_called)
2740            || !TEST_size_t_eq(sizeof(buf), nbytes)
2741            || !TEST_int_eq(c, buf[0]))
2742        goto end;
2743
2744    /* Do it again but use dummy writes to drive the ticket generation */
2745    c = '3';
2746    new_called = 0;
2747    if (!TEST_true(SSL_new_session_ticket(serverssl))
2748            || !TEST_true(SSL_new_session_ticket(serverssl))
2749            || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2750            || !TEST_size_t_eq(0, nbytes)
2751            || !TEST_int_eq(2, new_called)
2752            || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2753            || !TEST_int_eq(4, new_called))
2754        goto end;
2755
2756    /* Once more, but with SSL_do_handshake() to drive the ticket generation */
2757    c = '4';
2758    new_called = 0;
2759    if (!TEST_true(SSL_new_session_ticket(serverssl))
2760            || !TEST_true(SSL_new_session_ticket(serverssl))
2761            || !TEST_true(SSL_do_handshake(serverssl))
2762            || !TEST_int_eq(2, new_called)
2763            || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2764            || !TEST_int_eq(4, new_called))
2765        goto end;
2766
2767    /*
2768     * Use the always-retry BIO to exercise the logic that forces ticket
2769     * generation to wait until a record boundary.
2770     */
2771    c = '5';
2772    new_called = 0;
2773    tmp = SSL_get_wbio(serverssl);
2774    if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2775        tmp = NULL;
2776        goto end;
2777    }
2778    SSL_set0_wbio(serverssl, bretry);
2779    bretry = NULL;
2780    if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2781            || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2782            || !TEST_size_t_eq(nbytes, 0))
2783        goto end;
2784    /* Restore a BIO that will let the write succeed */
2785    SSL_set0_wbio(serverssl, tmp);
2786    tmp = NULL;
2787    /*
2788     * These calls should just queue the request and not send anything
2789     * even if we explicitly try to hit the state machine.
2790     */
2791    if (!TEST_true(SSL_new_session_ticket(serverssl))
2792            || !TEST_true(SSL_new_session_ticket(serverssl))
2793            || !TEST_int_eq(0, new_called)
2794            || !TEST_true(SSL_do_handshake(serverssl))
2795            || !TEST_int_eq(0, new_called))
2796        goto end;
2797    /* Re-do the write; still no tickets sent */
2798    if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2799            || !TEST_size_t_eq(1, nbytes)
2800            || !TEST_int_eq(0, new_called)
2801            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2802            || !TEST_int_eq(0, new_called)
2803            || !TEST_int_eq(sizeof(buf), nbytes)
2804            || !TEST_int_eq(c, buf[0])
2805            || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2806        goto end;
2807    /* Even trying to hit the state machine now will still not send tickets */
2808    if (!TEST_true(SSL_do_handshake(serverssl))
2809            || !TEST_int_eq(0, new_called))
2810        goto end;
2811    /* Now the *next* write should send the tickets */
2812    c = '6';
2813    if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2814            || !TEST_size_t_eq(1, nbytes)
2815            || !TEST_int_eq(2, new_called)
2816            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2817            || !TEST_int_eq(4, new_called)
2818            || !TEST_int_eq(sizeof(buf), nbytes)
2819            || !TEST_int_eq(c, buf[0])
2820            || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2821        goto end;
2822
2823    SSL_shutdown(clientssl);
2824    SSL_shutdown(serverssl);
2825    testresult = 1;
2826
2827 end:
2828    BIO_free(bretry);
2829    BIO_free(tmp);
2830    SSL_free(serverssl);
2831    SSL_free(clientssl);
2832    SSL_CTX_free(sctx);
2833    SSL_CTX_free(cctx);
2834    clientssl = serverssl = NULL;
2835    sctx = cctx = NULL;
2836    return testresult;
2837}
2838#endif
2839
2840#define USE_NULL            0
2841#define USE_BIO_1           1
2842#define USE_BIO_2           2
2843#define USE_DEFAULT         3
2844
2845#define CONNTYPE_CONNECTION_SUCCESS  0
2846#define CONNTYPE_CONNECTION_FAIL     1
2847#define CONNTYPE_NO_CONNECTION       2
2848
2849#define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
2850#define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
2851#if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2852# define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
2853#else
2854# define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
2855#endif
2856
2857#define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
2858                                + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2859                                + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2860
2861static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2862{
2863    switch (type) {
2864    case USE_NULL:
2865        *res = NULL;
2866        break;
2867    case USE_BIO_1:
2868        *res = bio1;
2869        break;
2870    case USE_BIO_2:
2871        *res = bio2;
2872        break;
2873    }
2874}
2875
2876
2877/*
2878 * Tests calls to SSL_set_bio() under various conditions.
2879 *
2880 * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2881 * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2882 * then do more tests where we create a successful connection first using our
2883 * standard connection setup functions, and then call SSL_set_bio() with
2884 * various combinations of valid BIOs or NULL. We then repeat these tests
2885 * following a failed connection. In this last case we are looking to check that
2886 * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2887 */
2888static int test_ssl_set_bio(int idx)
2889{
2890    SSL_CTX *sctx = NULL, *cctx = NULL;
2891    BIO *bio1 = NULL;
2892    BIO *bio2 = NULL;
2893    BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2894    SSL *serverssl = NULL, *clientssl = NULL;
2895    int initrbio, initwbio, newrbio, newwbio, conntype;
2896    int testresult = 0;
2897
2898    if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2899        initrbio = idx % 3;
2900        idx /= 3;
2901        initwbio = idx % 3;
2902        idx /= 3;
2903        newrbio = idx % 3;
2904        idx /= 3;
2905        newwbio = idx % 3;
2906        conntype = CONNTYPE_NO_CONNECTION;
2907    } else {
2908        idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2909        initrbio = initwbio = USE_DEFAULT;
2910        newrbio = idx % 2;
2911        idx /= 2;
2912        newwbio = idx % 2;
2913        idx /= 2;
2914        conntype = idx % 2;
2915    }
2916
2917    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2918                                       TLS_client_method(), TLS1_VERSION, 0,
2919                                       &sctx, &cctx, cert, privkey)))
2920        goto end;
2921
2922    if (conntype == CONNTYPE_CONNECTION_FAIL) {
2923        /*
2924         * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2925         * because we reduced the number of tests in the definition of
2926         * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2927         * mismatched protocol versions we will force a connection failure.
2928         */
2929        SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2930        SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2931    }
2932
2933    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2934                                      NULL, NULL)))
2935        goto end;
2936
2937    if (initrbio == USE_BIO_1
2938            || initwbio == USE_BIO_1
2939            || newrbio == USE_BIO_1
2940            || newwbio == USE_BIO_1) {
2941        if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2942            goto end;
2943    }
2944
2945    if (initrbio == USE_BIO_2
2946            || initwbio == USE_BIO_2
2947            || newrbio == USE_BIO_2
2948            || newwbio == USE_BIO_2) {
2949        if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
2950            goto end;
2951    }
2952
2953    if (initrbio != USE_DEFAULT) {
2954        setupbio(&irbio, bio1, bio2, initrbio);
2955        setupbio(&iwbio, bio1, bio2, initwbio);
2956        SSL_set_bio(clientssl, irbio, iwbio);
2957
2958        /*
2959         * We want to maintain our own refs to these BIO, so do an up ref for
2960         * each BIO that will have ownership transferred in the SSL_set_bio()
2961         * call
2962         */
2963        if (irbio != NULL)
2964            BIO_up_ref(irbio);
2965        if (iwbio != NULL && iwbio != irbio)
2966            BIO_up_ref(iwbio);
2967    }
2968
2969    if (conntype != CONNTYPE_NO_CONNECTION
2970            && !TEST_true(create_ssl_connection(serverssl, clientssl,
2971                                                SSL_ERROR_NONE)
2972                          == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
2973        goto end;
2974
2975    setupbio(&nrbio, bio1, bio2, newrbio);
2976    setupbio(&nwbio, bio1, bio2, newwbio);
2977
2978    /*
2979     * We will (maybe) transfer ownership again so do more up refs.
2980     * SSL_set_bio() has some really complicated ownership rules where BIOs have
2981     * already been set!
2982     */
2983    if (nrbio != NULL
2984            && nrbio != irbio
2985            && (nwbio != iwbio || nrbio != nwbio))
2986        BIO_up_ref(nrbio);
2987    if (nwbio != NULL
2988            && nwbio != nrbio
2989            && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
2990        BIO_up_ref(nwbio);
2991
2992    SSL_set_bio(clientssl, nrbio, nwbio);
2993
2994    testresult = 1;
2995
2996 end:
2997    BIO_free(bio1);
2998    BIO_free(bio2);
2999
3000    /*
3001     * This test is checking that the ref counting for SSL_set_bio is correct.
3002     * If we get here and we did too many frees then we will fail in the above
3003     * functions.
3004     */
3005    SSL_free(serverssl);
3006    SSL_free(clientssl);
3007    SSL_CTX_free(sctx);
3008    SSL_CTX_free(cctx);
3009    return testresult;
3010}
3011
3012typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
3013
3014static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
3015{
3016    BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
3017    SSL_CTX *ctx;
3018    SSL *ssl = NULL;
3019    int testresult = 0;
3020
3021    if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
3022            || !TEST_ptr(ssl = SSL_new(ctx))
3023            || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
3024            || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
3025        goto end;
3026
3027    BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
3028
3029    /*
3030     * If anything goes wrong here then we could leak memory.
3031     */
3032    BIO_push(sslbio, membio1);
3033
3034    /* Verify changing the rbio/wbio directly does not cause leaks */
3035    if (change_bio != NO_BIO_CHANGE) {
3036        if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
3037            ssl = NULL;
3038            goto end;
3039        }
3040        if (change_bio == CHANGE_RBIO)
3041            SSL_set0_rbio(ssl, membio2);
3042        else
3043            SSL_set0_wbio(ssl, membio2);
3044    }
3045    ssl = NULL;
3046
3047    if (pop_ssl)
3048        BIO_pop(sslbio);
3049    else
3050        BIO_pop(membio1);
3051
3052    testresult = 1;
3053 end:
3054    BIO_free(membio1);
3055    BIO_free(sslbio);
3056    SSL_free(ssl);
3057    SSL_CTX_free(ctx);
3058
3059    return testresult;
3060}
3061
3062static int test_ssl_bio_pop_next_bio(void)
3063{
3064    return execute_test_ssl_bio(0, NO_BIO_CHANGE);
3065}
3066
3067static int test_ssl_bio_pop_ssl_bio(void)
3068{
3069    return execute_test_ssl_bio(1, NO_BIO_CHANGE);
3070}
3071
3072static int test_ssl_bio_change_rbio(void)
3073{
3074    return execute_test_ssl_bio(0, CHANGE_RBIO);
3075}
3076
3077static int test_ssl_bio_change_wbio(void)
3078{
3079    return execute_test_ssl_bio(0, CHANGE_WBIO);
3080}
3081
3082#if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
3083typedef struct {
3084    /* The list of sig algs */
3085    const int *list;
3086    /* The length of the list */
3087    size_t listlen;
3088    /* A sigalgs list in string format */
3089    const char *liststr;
3090    /* Whether setting the list should succeed */
3091    int valid;
3092    /* Whether creating a connection with the list should succeed */
3093    int connsuccess;
3094} sigalgs_list;
3095
3096static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
3097# ifndef OPENSSL_NO_EC
3098static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
3099static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
3100# endif
3101static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
3102static const int invalidlist2[] = {NID_sha256, NID_undef};
3103static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
3104static const int invalidlist4[] = {NID_sha256};
3105static const sigalgs_list testsigalgs[] = {
3106    {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
3107# ifndef OPENSSL_NO_EC
3108    {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
3109    {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
3110# endif
3111    {NULL, 0, "RSA+SHA256", 1, 1},
3112# ifndef OPENSSL_NO_EC
3113    {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
3114    {NULL, 0, "ECDSA+SHA512", 1, 0},
3115# endif
3116    {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
3117    {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
3118    {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
3119    {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
3120    {NULL, 0, "RSA", 0, 0},
3121    {NULL, 0, "SHA256", 0, 0},
3122    {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
3123    {NULL, 0, "Invalid", 0, 0}
3124};
3125
3126static int test_set_sigalgs(int idx)
3127{
3128    SSL_CTX *cctx = NULL, *sctx = NULL;
3129    SSL *clientssl = NULL, *serverssl = NULL;
3130    int testresult = 0;
3131    const sigalgs_list *curr;
3132    int testctx;
3133
3134    /* Should never happen */
3135    if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
3136        return 0;
3137
3138    testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
3139    curr = testctx ? &testsigalgs[idx]
3140                   : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
3141
3142    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3143                                       TLS_client_method(), TLS1_VERSION, 0,
3144                                       &sctx, &cctx, cert, privkey)))
3145        return 0;
3146
3147    SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
3148
3149    if (testctx) {
3150        int ret;
3151
3152        if (curr->list != NULL)
3153            ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
3154        else
3155            ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
3156
3157        if (!ret) {
3158            if (curr->valid)
3159                TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
3160            else
3161                testresult = 1;
3162            goto end;
3163        }
3164        if (!curr->valid) {
3165            TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
3166            goto end;
3167        }
3168    }
3169
3170    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3171                                      &clientssl, NULL, NULL)))
3172        goto end;
3173
3174    if (!testctx) {
3175        int ret;
3176
3177        if (curr->list != NULL)
3178            ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
3179        else
3180            ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
3181        if (!ret) {
3182            if (curr->valid)
3183                TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
3184            else
3185                testresult = 1;
3186            goto end;
3187        }
3188        if (!curr->valid)
3189            goto end;
3190    }
3191
3192    if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
3193                                           SSL_ERROR_NONE),
3194                curr->connsuccess))
3195        goto end;
3196
3197    testresult = 1;
3198
3199 end:
3200    SSL_free(serverssl);
3201    SSL_free(clientssl);
3202    SSL_CTX_free(sctx);
3203    SSL_CTX_free(cctx);
3204
3205    return testresult;
3206}
3207#endif
3208
3209#ifndef OSSL_NO_USABLE_TLS1_3
3210static int psk_client_cb_cnt = 0;
3211static int psk_server_cb_cnt = 0;
3212
3213static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
3214                          size_t *idlen, SSL_SESSION **sess)
3215{
3216    switch (++use_session_cb_cnt) {
3217    case 1:
3218        /* The first call should always have a NULL md */
3219        if (md != NULL)
3220            return 0;
3221        break;
3222
3223    case 2:
3224        /* The second call should always have an md */
3225        if (md == NULL)
3226            return 0;
3227        break;
3228
3229    default:
3230        /* We should only be called a maximum of twice */
3231        return 0;
3232    }
3233
3234    if (clientpsk != NULL)
3235        SSL_SESSION_up_ref(clientpsk);
3236
3237    *sess = clientpsk;
3238    *id = (const unsigned char *)pskid;
3239    *idlen = strlen(pskid);
3240
3241    return 1;
3242}
3243
3244#ifndef OPENSSL_NO_PSK
3245static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
3246                                  unsigned int max_id_len,
3247                                  unsigned char *psk,
3248                                  unsigned int max_psk_len)
3249{
3250    unsigned int psklen = 0;
3251
3252    psk_client_cb_cnt++;
3253
3254    if (strlen(pskid) + 1 > max_id_len)
3255        return 0;
3256
3257    /* We should only ever be called a maximum of twice per connection */
3258    if (psk_client_cb_cnt > 2)
3259        return 0;
3260
3261    if (clientpsk == NULL)
3262        return 0;
3263
3264    /* We'll reuse the PSK we set up for TLSv1.3 */
3265    if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
3266        return 0;
3267    psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
3268    strncpy(id, pskid, max_id_len);
3269
3270    return psklen;
3271}
3272#endif /* OPENSSL_NO_PSK */
3273
3274static int find_session_cb(SSL *ssl, const unsigned char *identity,
3275                           size_t identity_len, SSL_SESSION **sess)
3276{
3277    find_session_cb_cnt++;
3278
3279    /* We should only ever be called a maximum of twice per connection */
3280    if (find_session_cb_cnt > 2)
3281        return 0;
3282
3283    if (serverpsk == NULL)
3284        return 0;
3285
3286    /* Identity should match that set by the client */
3287    if (strlen(srvid) != identity_len
3288            || strncmp(srvid, (const char *)identity, identity_len) != 0) {
3289        /* No PSK found, continue but without a PSK */
3290        *sess = NULL;
3291        return 1;
3292    }
3293
3294    SSL_SESSION_up_ref(serverpsk);
3295    *sess = serverpsk;
3296
3297    return 1;
3298}
3299
3300#ifndef OPENSSL_NO_PSK
3301static unsigned int psk_server_cb(SSL *ssl, const char *identity,
3302                                  unsigned char *psk, unsigned int max_psk_len)
3303{
3304    unsigned int psklen = 0;
3305
3306    psk_server_cb_cnt++;
3307
3308    /* We should only ever be called a maximum of twice per connection */
3309    if (find_session_cb_cnt > 2)
3310        return 0;
3311
3312    if (serverpsk == NULL)
3313        return 0;
3314
3315    /* Identity should match that set by the client */
3316    if (strcmp(srvid, identity) != 0) {
3317        return 0;
3318    }
3319
3320    /* We'll reuse the PSK we set up for TLSv1.3 */
3321    if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
3322        return 0;
3323    psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
3324
3325    return psklen;
3326}
3327#endif /* OPENSSL_NO_PSK */
3328
3329#define MSG1    "Hello"
3330#define MSG2    "World."
3331#define MSG3    "This"
3332#define MSG4    "is"
3333#define MSG5    "a"
3334#define MSG6    "test"
3335#define MSG7    "message."
3336
3337#define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
3338#define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
3339#define TLS13_CHACHA20_POLY1305_SHA256_BYTES ((const unsigned char *)"\x13\x03")
3340#define TLS13_AES_128_CCM_SHA256_BYTES ((const unsigned char *)"\x13\x04")
3341#define TLS13_AES_128_CCM_8_SHA256_BYTES ((const unsigned char *)"\x13\05")
3342
3343
3344static SSL_SESSION *create_a_psk(SSL *ssl, size_t mdsize)
3345{
3346    const SSL_CIPHER *cipher = NULL;
3347    const unsigned char key[] = {
3348        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
3349        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
3350        0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
3351        0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
3352        0x2c, 0x2d, 0x2e, 0x2f /* SHA384_DIGEST_LENGTH bytes */
3353    };
3354    SSL_SESSION *sess = NULL;
3355
3356    if (mdsize == SHA384_DIGEST_LENGTH) {
3357        cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES);
3358    } else if (mdsize == SHA256_DIGEST_LENGTH) {
3359        /*
3360         * Any ciphersuite using SHA256 will do - it will be compatible with
3361         * the actual ciphersuite selected as long as it too is based on SHA256
3362         */
3363        cipher = SSL_CIPHER_find(ssl, TLS13_AES_128_GCM_SHA256_BYTES);
3364    } else {
3365        /* Should not happen */
3366        return NULL;
3367    }
3368    sess = SSL_SESSION_new();
3369    if (!TEST_ptr(sess)
3370            || !TEST_ptr(cipher)
3371            || !TEST_true(SSL_SESSION_set1_master_key(sess, key, mdsize))
3372            || !TEST_true(SSL_SESSION_set_cipher(sess, cipher))
3373            || !TEST_true(
3374                    SSL_SESSION_set_protocol_version(sess,
3375                                                     TLS1_3_VERSION))) {
3376        SSL_SESSION_free(sess);
3377        return NULL;
3378    }
3379    return sess;
3380}
3381
3382/*
3383 * Helper method to setup objects for early data test. Caller frees objects on
3384 * error.
3385 */
3386static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
3387                                SSL **serverssl, SSL_SESSION **sess, int idx,
3388                                size_t mdsize)
3389{
3390    if (*sctx == NULL
3391            && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3392                                              TLS_client_method(),
3393                                              TLS1_VERSION, 0,
3394                                              sctx, cctx, cert, privkey)))
3395        return 0;
3396
3397    if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
3398        return 0;
3399
3400    if (idx == 1) {
3401        /* When idx == 1 we repeat the tests with read_ahead set */
3402        SSL_CTX_set_read_ahead(*cctx, 1);
3403        SSL_CTX_set_read_ahead(*sctx, 1);
3404    } else if (idx == 2) {
3405        /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
3406        SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
3407        SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
3408        use_session_cb_cnt = 0;
3409        find_session_cb_cnt = 0;
3410        srvid = pskid;
3411    }
3412
3413    if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
3414                                      NULL, NULL)))
3415        return 0;
3416
3417    /*
3418     * For one of the run throughs (doesn't matter which one), we'll try sending
3419     * some SNI data in the initial ClientHello. This will be ignored (because
3420     * there is no SNI cb set up by the server), so it should not impact
3421     * early_data.
3422     */
3423    if (idx == 1
3424            && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
3425        return 0;
3426
3427    if (idx == 2) {
3428        clientpsk = create_a_psk(*clientssl, mdsize);
3429        if (!TEST_ptr(clientpsk)
3430                   /*
3431                    * We just choose an arbitrary value for max_early_data which
3432                    * should be big enough for testing purposes.
3433                    */
3434                || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
3435                                                             0x100))
3436                || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3437            SSL_SESSION_free(clientpsk);
3438            clientpsk = NULL;
3439            return 0;
3440        }
3441        serverpsk = clientpsk;
3442
3443        if (sess != NULL) {
3444            if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3445                SSL_SESSION_free(clientpsk);
3446                SSL_SESSION_free(serverpsk);
3447                clientpsk = serverpsk = NULL;
3448                return 0;
3449            }
3450            *sess = clientpsk;
3451        }
3452        return 1;
3453    }
3454
3455    if (sess == NULL)
3456        return 1;
3457
3458    if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
3459                                         SSL_ERROR_NONE)))
3460        return 0;
3461
3462    *sess = SSL_get1_session(*clientssl);
3463    SSL_shutdown(*clientssl);
3464    SSL_shutdown(*serverssl);
3465    SSL_free(*serverssl);
3466    SSL_free(*clientssl);
3467    *serverssl = *clientssl = NULL;
3468
3469    if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
3470                                      clientssl, NULL, NULL))
3471            || !TEST_true(SSL_set_session(*clientssl, *sess)))
3472        return 0;
3473
3474    return 1;
3475}
3476
3477static int test_early_data_read_write(int idx)
3478{
3479    SSL_CTX *cctx = NULL, *sctx = NULL;
3480    SSL *clientssl = NULL, *serverssl = NULL;
3481    int testresult = 0;
3482    SSL_SESSION *sess = NULL;
3483    unsigned char buf[20], data[1024];
3484    size_t readbytes, written, eoedlen, rawread, rawwritten;
3485    BIO *rbio;
3486
3487    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3488                                        &serverssl, &sess, idx,
3489                                        SHA384_DIGEST_LENGTH)))
3490        goto end;
3491
3492    /* Write and read some early data */
3493    if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3494                                        &written))
3495            || !TEST_size_t_eq(written, strlen(MSG1))
3496            || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
3497                                                sizeof(buf), &readbytes),
3498                            SSL_READ_EARLY_DATA_SUCCESS)
3499            || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
3500            || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3501                            SSL_EARLY_DATA_ACCEPTED))
3502        goto end;
3503
3504    /*
3505     * Server should be able to write data, and client should be able to
3506     * read it.
3507     */
3508    if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
3509                                        &written))
3510            || !TEST_size_t_eq(written, strlen(MSG2))
3511            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3512            || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3513        goto end;
3514
3515    /* Even after reading normal data, client should be able write early data */
3516    if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
3517                                        &written))
3518            || !TEST_size_t_eq(written, strlen(MSG3)))
3519        goto end;
3520
3521    /* Server should still be able read early data after writing data */
3522    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3523                                         &readbytes),
3524                     SSL_READ_EARLY_DATA_SUCCESS)
3525            || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
3526        goto end;
3527
3528    /* Write more data from server and read it from client */
3529    if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
3530                                        &written))
3531            || !TEST_size_t_eq(written, strlen(MSG4))
3532            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3533            || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
3534        goto end;
3535
3536    /*
3537     * If client writes normal data it should mean writing early data is no
3538     * longer possible.
3539     */
3540    if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3541            || !TEST_size_t_eq(written, strlen(MSG5))
3542            || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3543                            SSL_EARLY_DATA_ACCEPTED))
3544        goto end;
3545
3546    /*
3547     * At this point the client has written EndOfEarlyData, ClientFinished and
3548     * normal (fully protected) data. We are going to cause a delay between the
3549     * arrival of EndOfEarlyData and ClientFinished. We read out all the data
3550     * in the read BIO, and then just put back the EndOfEarlyData message.
3551     */
3552    rbio = SSL_get_rbio(serverssl);
3553    if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
3554            || !TEST_size_t_lt(rawread, sizeof(data))
3555            || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
3556        goto end;
3557
3558    /* Record length is in the 4th and 5th bytes of the record header */
3559    eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
3560    if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
3561            || !TEST_size_t_eq(rawwritten, eoedlen))
3562        goto end;
3563
3564    /* Server should be told that there is no more early data */
3565    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3566                                         &readbytes),
3567                     SSL_READ_EARLY_DATA_FINISH)
3568            || !TEST_size_t_eq(readbytes, 0))
3569        goto end;
3570
3571    /*
3572     * Server has not finished init yet, so should still be able to write early
3573     * data.
3574     */
3575    if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
3576                                        &written))
3577            || !TEST_size_t_eq(written, strlen(MSG6)))
3578        goto end;
3579
3580    /* Push the ClientFinished and the normal data back into the server rbio */
3581    if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
3582                                &rawwritten))
3583            || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
3584        goto end;
3585
3586    /* Server should be able to read normal data */
3587    if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3588            || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3589        goto end;
3590
3591    /* Client and server should not be able to write/read early data now */
3592    if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3593                                         &written)))
3594        goto end;
3595    ERR_clear_error();
3596    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3597                                         &readbytes),
3598                     SSL_READ_EARLY_DATA_ERROR))
3599        goto end;
3600    ERR_clear_error();
3601
3602    /* Client should be able to read the data sent by the server */
3603    if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3604            || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
3605        goto end;
3606
3607    /*
3608     * Make sure we process the two NewSessionTickets. These arrive
3609     * post-handshake. We attempt reads which we do not expect to return any
3610     * data.
3611     */
3612    if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3613            || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3614                           &readbytes)))
3615        goto end;
3616
3617    /* Server should be able to write normal data */
3618    if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3619            || !TEST_size_t_eq(written, strlen(MSG7))
3620            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3621            || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3622        goto end;
3623
3624    SSL_SESSION_free(sess);
3625    sess = SSL_get1_session(clientssl);
3626    use_session_cb_cnt = 0;
3627    find_session_cb_cnt = 0;
3628
3629    SSL_shutdown(clientssl);
3630    SSL_shutdown(serverssl);
3631    SSL_free(serverssl);
3632    SSL_free(clientssl);
3633    serverssl = clientssl = NULL;
3634    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3635                                      &clientssl, NULL, NULL))
3636            || !TEST_true(SSL_set_session(clientssl, sess)))
3637        goto end;
3638
3639    /* Write and read some early data */
3640    if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3641                                        &written))
3642            || !TEST_size_t_eq(written, strlen(MSG1))
3643            || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3644                                                &readbytes),
3645                            SSL_READ_EARLY_DATA_SUCCESS)
3646            || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3647        goto end;
3648
3649    if (!TEST_int_gt(SSL_connect(clientssl), 0)
3650            || !TEST_int_gt(SSL_accept(serverssl), 0))
3651        goto end;
3652
3653    /* Client and server should not be able to write/read early data now */
3654    if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3655                                         &written)))
3656        goto end;
3657    ERR_clear_error();
3658    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3659                                         &readbytes),
3660                     SSL_READ_EARLY_DATA_ERROR))
3661        goto end;
3662    ERR_clear_error();
3663
3664    /* Client and server should be able to write/read normal data */
3665    if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3666            || !TEST_size_t_eq(written, strlen(MSG5))
3667            || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3668            || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3669        goto end;
3670
3671    testresult = 1;
3672
3673 end:
3674    SSL_SESSION_free(sess);
3675    SSL_SESSION_free(clientpsk);
3676    SSL_SESSION_free(serverpsk);
3677    clientpsk = serverpsk = NULL;
3678    SSL_free(serverssl);
3679    SSL_free(clientssl);
3680    SSL_CTX_free(sctx);
3681    SSL_CTX_free(cctx);
3682    return testresult;
3683}
3684
3685static int allow_ed_cb_called = 0;
3686
3687static int allow_early_data_cb(SSL *s, void *arg)
3688{
3689    int *usecb = (int *)arg;
3690
3691    allow_ed_cb_called++;
3692
3693    if (*usecb == 1)
3694        return 0;
3695
3696    return 1;
3697}
3698
3699/*
3700 * idx == 0: Standard early_data setup
3701 * idx == 1: early_data setup using read_ahead
3702 * usecb == 0: Don't use a custom early data callback
3703 * usecb == 1: Use a custom early data callback and reject the early data
3704 * usecb == 2: Use a custom early data callback and accept the early data
3705 * confopt == 0: Configure anti-replay directly
3706 * confopt == 1: Configure anti-replay using SSL_CONF
3707 */
3708static int test_early_data_replay_int(int idx, int usecb, int confopt)
3709{
3710    SSL_CTX *cctx = NULL, *sctx = NULL;
3711    SSL *clientssl = NULL, *serverssl = NULL;
3712    int testresult = 0;
3713    SSL_SESSION *sess = NULL;
3714    size_t readbytes, written;
3715    unsigned char buf[20];
3716
3717    allow_ed_cb_called = 0;
3718
3719    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3720                                       TLS_client_method(), TLS1_VERSION, 0,
3721                                       &sctx, &cctx, cert, privkey)))
3722        return 0;
3723
3724    if (usecb > 0) {
3725        if (confopt == 0) {
3726            SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3727        } else {
3728            SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3729
3730            if (!TEST_ptr(confctx))
3731                goto end;
3732            SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
3733                                            | SSL_CONF_FLAG_SERVER);
3734            SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3735            if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3736                             2)) {
3737                SSL_CONF_CTX_free(confctx);
3738                goto end;
3739            }
3740            SSL_CONF_CTX_free(confctx);
3741        }
3742        SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3743    }
3744
3745    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3746                                        &serverssl, &sess, idx,
3747                                        SHA384_DIGEST_LENGTH)))
3748        goto end;
3749
3750    /*
3751     * The server is configured to accept early data. Create a connection to
3752     * "use up" the ticket
3753     */
3754    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3755            || !TEST_true(SSL_session_reused(clientssl)))
3756        goto end;
3757
3758    SSL_shutdown(clientssl);
3759    SSL_shutdown(serverssl);
3760    SSL_free(serverssl);
3761    SSL_free(clientssl);
3762    serverssl = clientssl = NULL;
3763
3764    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3765                                      &clientssl, NULL, NULL))
3766            || !TEST_true(SSL_set_session(clientssl, sess)))
3767        goto end;
3768
3769    /* Write and read some early data */
3770    if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3771                                        &written))
3772            || !TEST_size_t_eq(written, strlen(MSG1)))
3773        goto end;
3774
3775    if (usecb <= 1) {
3776        if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3777                                             &readbytes),
3778                         SSL_READ_EARLY_DATA_FINISH)
3779                   /*
3780                    * The ticket was reused, so the we should have rejected the
3781                    * early data
3782                    */
3783                || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3784                                SSL_EARLY_DATA_REJECTED))
3785            goto end;
3786    } else {
3787        /* In this case the callback decides to accept the early data */
3788        if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3789                                             &readbytes),
3790                         SSL_READ_EARLY_DATA_SUCCESS)
3791                || !TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3792                   /*
3793                    * Server will have sent its flight so client can now send
3794                    * end of early data and complete its half of the handshake
3795                    */
3796                || !TEST_int_gt(SSL_connect(clientssl), 0)
3797                || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3798                                             &readbytes),
3799                                SSL_READ_EARLY_DATA_FINISH)
3800                || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3801                                SSL_EARLY_DATA_ACCEPTED))
3802            goto end;
3803    }
3804
3805    /* Complete the connection */
3806    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3807            || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3808            || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3809        goto end;
3810
3811    testresult = 1;
3812
3813 end:
3814    SSL_SESSION_free(sess);
3815    SSL_SESSION_free(clientpsk);
3816    SSL_SESSION_free(serverpsk);
3817    clientpsk = serverpsk = NULL;
3818    SSL_free(serverssl);
3819    SSL_free(clientssl);
3820    SSL_CTX_free(sctx);
3821    SSL_CTX_free(cctx);
3822    return testresult;
3823}
3824
3825static int test_early_data_replay(int idx)
3826{
3827    int ret = 1, usecb, confopt;
3828
3829    for (usecb = 0; usecb < 3; usecb++) {
3830        for (confopt = 0; confopt < 2; confopt++)
3831            ret &= test_early_data_replay_int(idx, usecb, confopt);
3832    }
3833
3834    return ret;
3835}
3836
3837static const char *ciphersuites[] = {
3838    "TLS_AES_128_CCM_8_SHA256",
3839    "TLS_AES_128_GCM_SHA256",
3840    "TLS_AES_256_GCM_SHA384",
3841    "TLS_AES_128_CCM_SHA256",
3842#if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3843    "TLS_CHACHA20_POLY1305_SHA256"
3844#endif
3845};
3846
3847/*
3848 * Helper function to test that a server attempting to read early data can
3849 * handle a connection from a client where the early data should be skipped.
3850 * testtype: 0 == No HRR
3851 * testtype: 1 == HRR
3852 * testtype: 2 == HRR, invalid early_data sent after HRR
3853 * testtype: 3 == recv_max_early_data set to 0
3854 */
3855static int early_data_skip_helper(int testtype, int cipher, int idx)
3856{
3857    SSL_CTX *cctx = NULL, *sctx = NULL;
3858    SSL *clientssl = NULL, *serverssl = NULL;
3859    int testresult = 0;
3860    SSL_SESSION *sess = NULL;
3861    unsigned char buf[20];
3862    size_t readbytes, written;
3863
3864    if (is_fips && cipher == 4)
3865        return 1;
3866
3867    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3868                                              TLS_client_method(),
3869                                              TLS1_VERSION, 0,
3870                                              &sctx, &cctx, cert, privkey)))
3871        goto end;
3872
3873    if (cipher == 0) {
3874        SSL_CTX_set_security_level(sctx, 0);
3875        SSL_CTX_set_security_level(cctx, 0);
3876    }
3877
3878    if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, ciphersuites[cipher]))
3879            || !TEST_true(SSL_CTX_set_ciphersuites(cctx, ciphersuites[cipher])))
3880        goto end;
3881
3882    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3883                                        &serverssl, &sess, idx,
3884                                        cipher == 2 ? SHA384_DIGEST_LENGTH
3885                                                    : SHA256_DIGEST_LENGTH)))
3886        goto end;
3887
3888    if (testtype == 1 || testtype == 2) {
3889        /* Force an HRR to occur */
3890#if defined(OPENSSL_NO_EC)
3891        if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
3892            goto end;
3893#else
3894        if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
3895            goto end;
3896#endif
3897    } else if (idx == 2) {
3898        /*
3899         * We force early_data rejection by ensuring the PSK identity is
3900         * unrecognised
3901         */
3902        srvid = "Dummy Identity";
3903    } else {
3904        /*
3905         * Deliberately corrupt the creation time. We take 20 seconds off the
3906         * time. It could be any value as long as it is not within tolerance.
3907         * This should mean the ticket is rejected.
3908         */
3909        if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
3910            goto end;
3911    }
3912
3913    if (testtype == 3
3914            && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
3915        goto end;
3916
3917    /* Write some early data */
3918    if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3919                                        &written))
3920            || !TEST_size_t_eq(written, strlen(MSG1)))
3921        goto end;
3922
3923    /* Server should reject the early data */
3924    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3925                                         &readbytes),
3926                     SSL_READ_EARLY_DATA_FINISH)
3927            || !TEST_size_t_eq(readbytes, 0)
3928            || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3929                            SSL_EARLY_DATA_REJECTED))
3930        goto end;
3931
3932    switch (testtype) {
3933    case 0:
3934        /* Nothing to do */
3935        break;
3936
3937    case 1:
3938        /*
3939         * Finish off the handshake. We perform the same writes and reads as
3940         * further down but we expect them to fail due to the incomplete
3941         * handshake.
3942         */
3943        if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3944                || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
3945                               &readbytes)))
3946            goto end;
3947        break;
3948
3949    case 2:
3950        {
3951            BIO *wbio = SSL_get_wbio(clientssl);
3952            /* A record that will appear as bad early_data */
3953            const unsigned char bad_early_data[] = {
3954                0x17, 0x03, 0x03, 0x00, 0x01, 0x00
3955            };
3956
3957            /*
3958             * We force the client to attempt a write. This will fail because
3959             * we're still in the handshake. It will cause the second
3960             * ClientHello to be sent.
3961             */
3962            if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
3963                                         &written)))
3964                goto end;
3965
3966            /*
3967             * Inject some early_data after the second ClientHello. This should
3968             * cause the server to fail
3969             */
3970            if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
3971                                        sizeof(bad_early_data), &written)))
3972                goto end;
3973        }
3974        /* fallthrough */
3975
3976    case 3:
3977        /*
3978         * This client has sent more early_data than we are willing to skip
3979         * (case 3) or sent invalid early_data (case 2) so the connection should
3980         * abort.
3981         */
3982        if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3983                || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
3984            goto end;
3985
3986        /* Connection has failed - nothing more to do */
3987        testresult = 1;
3988        goto end;
3989
3990    default:
3991        TEST_error("Invalid test type");
3992        goto end;
3993    }
3994
3995    ERR_clear_error();
3996    /*
3997     * Should be able to send normal data despite rejection of early data. The
3998     * early_data should be skipped.
3999     */
4000    if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4001            || !TEST_size_t_eq(written, strlen(MSG2))
4002            || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4003                            SSL_EARLY_DATA_REJECTED)
4004            || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4005            || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4006        goto end;
4007
4008    /*
4009     * Failure to decrypt early data records should not leave spurious errors
4010     * on the error stack
4011     */
4012    if (!TEST_long_eq(ERR_peek_error(), 0))
4013        goto end;
4014
4015    testresult = 1;
4016
4017 end:
4018    SSL_SESSION_free(clientpsk);
4019    SSL_SESSION_free(serverpsk);
4020    clientpsk = serverpsk = NULL;
4021    SSL_SESSION_free(sess);
4022    SSL_free(serverssl);
4023    SSL_free(clientssl);
4024    SSL_CTX_free(sctx);
4025    SSL_CTX_free(cctx);
4026    return testresult;
4027}
4028
4029/*
4030 * Test that a server attempting to read early data can handle a connection
4031 * from a client where the early data is not acceptable.
4032 */
4033static int test_early_data_skip(int idx)
4034{
4035    return early_data_skip_helper(0,
4036                                  idx % OSSL_NELEM(ciphersuites),
4037                                  idx / OSSL_NELEM(ciphersuites));
4038}
4039
4040/*
4041 * Test that a server attempting to read early data can handle a connection
4042 * from a client where an HRR occurs.
4043 */
4044static int test_early_data_skip_hrr(int idx)
4045{
4046    return early_data_skip_helper(1,
4047                                  idx % OSSL_NELEM(ciphersuites),
4048                                  idx / OSSL_NELEM(ciphersuites));
4049}
4050
4051/*
4052 * Test that a server attempting to read early data can handle a connection
4053 * from a client where an HRR occurs and correctly fails if early_data is sent
4054 * after the HRR
4055 */
4056static int test_early_data_skip_hrr_fail(int idx)
4057{
4058    return early_data_skip_helper(2,
4059                                  idx % OSSL_NELEM(ciphersuites),
4060                                  idx / OSSL_NELEM(ciphersuites));
4061}
4062
4063/*
4064 * Test that a server attempting to read early data will abort if it tries to
4065 * skip over too much.
4066 */
4067static int test_early_data_skip_abort(int idx)
4068{
4069    return early_data_skip_helper(3,
4070                                  idx % OSSL_NELEM(ciphersuites),
4071                                  idx / OSSL_NELEM(ciphersuites));
4072}
4073
4074/*
4075 * Test that a server attempting to read early data can handle a connection
4076 * from a client that doesn't send any.
4077 */
4078static int test_early_data_not_sent(int idx)
4079{
4080    SSL_CTX *cctx = NULL, *sctx = NULL;
4081    SSL *clientssl = NULL, *serverssl = NULL;
4082    int testresult = 0;
4083    SSL_SESSION *sess = NULL;
4084    unsigned char buf[20];
4085    size_t readbytes, written;
4086
4087    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4088                                        &serverssl, &sess, idx,
4089                                        SHA384_DIGEST_LENGTH)))
4090        goto end;
4091
4092    /* Write some data - should block due to handshake with server */
4093    SSL_set_connect_state(clientssl);
4094    if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4095        goto end;
4096
4097    /* Server should detect that early data has not been sent */
4098    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4099                                         &readbytes),
4100                     SSL_READ_EARLY_DATA_FINISH)
4101            || !TEST_size_t_eq(readbytes, 0)
4102            || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4103                            SSL_EARLY_DATA_NOT_SENT)
4104            || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4105                            SSL_EARLY_DATA_NOT_SENT))
4106        goto end;
4107
4108    /* Continue writing the message we started earlier */
4109    if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4110            || !TEST_size_t_eq(written, strlen(MSG1))
4111            || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4112            || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4113            || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
4114            || !TEST_size_t_eq(written, strlen(MSG2)))
4115        goto end;
4116
4117    if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4118            || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4119        goto end;
4120
4121    testresult = 1;
4122
4123 end:
4124    SSL_SESSION_free(sess);
4125    SSL_SESSION_free(clientpsk);
4126    SSL_SESSION_free(serverpsk);
4127    clientpsk = serverpsk = NULL;
4128    SSL_free(serverssl);
4129    SSL_free(clientssl);
4130    SSL_CTX_free(sctx);
4131    SSL_CTX_free(cctx);
4132    return testresult;
4133}
4134
4135static const char *servalpn;
4136
4137static int alpn_select_cb(SSL *ssl, const unsigned char **out,
4138                          unsigned char *outlen, const unsigned char *in,
4139                          unsigned int inlen, void *arg)
4140{
4141    unsigned int protlen = 0;
4142    const unsigned char *prot;
4143
4144    for (prot = in; prot < in + inlen; prot += protlen) {
4145        protlen = *prot++;
4146        if (in + inlen < prot + protlen)
4147            return SSL_TLSEXT_ERR_NOACK;
4148
4149        if (protlen == strlen(servalpn)
4150                && memcmp(prot, servalpn, protlen) == 0) {
4151            *out = prot;
4152            *outlen = protlen;
4153            return SSL_TLSEXT_ERR_OK;
4154        }
4155    }
4156
4157    return SSL_TLSEXT_ERR_NOACK;
4158}
4159
4160/* Test that a PSK can be used to send early_data */
4161static int test_early_data_psk(int idx)
4162{
4163    SSL_CTX *cctx = NULL, *sctx = NULL;
4164    SSL *clientssl = NULL, *serverssl = NULL;
4165    int testresult = 0;
4166    SSL_SESSION *sess = NULL;
4167    unsigned char alpnlist[] = {
4168        0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
4169        'l', 'p', 'n'
4170    };
4171#define GOODALPNLEN     9
4172#define BADALPNLEN      8
4173#define GOODALPN        (alpnlist)
4174#define BADALPN         (alpnlist + GOODALPNLEN)
4175    int err = 0;
4176    unsigned char buf[20];
4177    size_t readbytes, written;
4178    int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
4179    int edstatus = SSL_EARLY_DATA_ACCEPTED;
4180
4181    /* We always set this up with a final parameter of "2" for PSK */
4182    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4183                                        &serverssl, &sess, 2,
4184                                        SHA384_DIGEST_LENGTH)))
4185        goto end;
4186
4187    servalpn = "goodalpn";
4188
4189    /*
4190     * Note: There is no test for inconsistent SNI with late client detection.
4191     * This is because servers do not acknowledge SNI even if they are using
4192     * it in a resumption handshake - so it is not actually possible for a
4193     * client to detect a problem.
4194     */
4195    switch (idx) {
4196    case 0:
4197        /* Set inconsistent SNI (early client detection) */
4198        err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
4199        if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4200                || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
4201            goto end;
4202        break;
4203
4204    case 1:
4205        /* Set inconsistent ALPN (early client detection) */
4206        err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
4207        /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
4208        if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
4209                                                      GOODALPNLEN))
4210                || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
4211                                                   BADALPNLEN)))
4212            goto end;
4213        break;
4214
4215    case 2:
4216        /*
4217         * Set invalid protocol version. Technically this affects PSKs without
4218         * early_data too, but we test it here because it is similar to the
4219         * SNI/ALPN consistency tests.
4220         */
4221        err = SSL_R_BAD_PSK;
4222        if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
4223            goto end;
4224        break;
4225
4226    case 3:
4227        /*
4228         * Set inconsistent SNI (server side). In this case the connection
4229         * will succeed and accept early_data. In TLSv1.3 on the server side SNI
4230         * is associated with each handshake - not the session. Therefore it
4231         * should not matter that we used a different server name last time.
4232         */
4233        SSL_SESSION_free(serverpsk);
4234        serverpsk = SSL_SESSION_dup(clientpsk);
4235        if (!TEST_ptr(serverpsk)
4236                || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
4237            goto end;
4238        /* Fall through */
4239    case 4:
4240        /* Set consistent SNI */
4241        if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4242                || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
4243                || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
4244                                hostname_cb)))
4245            goto end;
4246        break;
4247
4248    case 5:
4249        /*
4250         * Set inconsistent ALPN (server detected). In this case the connection
4251         * will succeed but reject early_data.
4252         */
4253        servalpn = "badalpn";
4254        edstatus = SSL_EARLY_DATA_REJECTED;
4255        readearlyres = SSL_READ_EARLY_DATA_FINISH;
4256        /* Fall through */
4257    case 6:
4258        /*
4259         * Set consistent ALPN.
4260         * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
4261         * accepts a list of protos (each one length prefixed).
4262         * SSL_set1_alpn_selected accepts a single protocol (not length
4263         * prefixed)
4264         */
4265        if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
4266                                                      GOODALPNLEN - 1))
4267                || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
4268                                                   GOODALPNLEN)))
4269            goto end;
4270
4271        SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4272        break;
4273
4274    case 7:
4275        /* Set inconsistent ALPN (late client detection) */
4276        SSL_SESSION_free(serverpsk);
4277        serverpsk = SSL_SESSION_dup(clientpsk);
4278        if (!TEST_ptr(serverpsk)
4279                || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
4280                                                             BADALPN + 1,
4281                                                             BADALPNLEN - 1))
4282                || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
4283                                                             GOODALPN + 1,
4284                                                             GOODALPNLEN - 1))
4285                || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
4286                                                   sizeof(alpnlist))))
4287            goto end;
4288        SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4289        edstatus = SSL_EARLY_DATA_ACCEPTED;
4290        readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
4291        /* SSL_connect() call should fail */
4292        connectres = -1;
4293        break;
4294
4295    default:
4296        TEST_error("Bad test index");
4297        goto end;
4298    }
4299
4300    SSL_set_connect_state(clientssl);
4301    if (err != 0) {
4302        if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4303                                            &written))
4304                || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
4305                || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
4306            goto end;
4307    } else {
4308        if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4309                                            &written)))
4310            goto end;
4311
4312        if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4313                                             &readbytes), readearlyres)
4314                || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
4315                    && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
4316                || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
4317                || !TEST_int_eq(SSL_connect(clientssl), connectres))
4318            goto end;
4319    }
4320
4321    testresult = 1;
4322
4323 end:
4324    SSL_SESSION_free(sess);
4325    SSL_SESSION_free(clientpsk);
4326    SSL_SESSION_free(serverpsk);
4327    clientpsk = serverpsk = NULL;
4328    SSL_free(serverssl);
4329    SSL_free(clientssl);
4330    SSL_CTX_free(sctx);
4331    SSL_CTX_free(cctx);
4332    return testresult;
4333}
4334
4335/*
4336 * Test TLSv1.3 PSK can be used to send early_data with all 5 ciphersuites
4337 * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
4338 * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
4339 * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4340 * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
4341 * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
4342 */
4343static int test_early_data_psk_with_all_ciphers(int idx)
4344{
4345    SSL_CTX *cctx = NULL, *sctx = NULL;
4346    SSL *clientssl = NULL, *serverssl = NULL;
4347    int testresult = 0;
4348    SSL_SESSION *sess = NULL;
4349    unsigned char buf[20];
4350    size_t readbytes, written;
4351    const SSL_CIPHER *cipher;
4352    const char *cipher_str[] = {
4353        TLS1_3_RFC_AES_128_GCM_SHA256,
4354        TLS1_3_RFC_AES_256_GCM_SHA384,
4355# if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4356        TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4357# else
4358        NULL,
4359# endif
4360        TLS1_3_RFC_AES_128_CCM_SHA256,
4361        TLS1_3_RFC_AES_128_CCM_8_SHA256
4362    };
4363    const unsigned char *cipher_bytes[] = {
4364        TLS13_AES_128_GCM_SHA256_BYTES,
4365        TLS13_AES_256_GCM_SHA384_BYTES,
4366# if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4367        TLS13_CHACHA20_POLY1305_SHA256_BYTES,
4368# else
4369        NULL,
4370# endif
4371        TLS13_AES_128_CCM_SHA256_BYTES,
4372        TLS13_AES_128_CCM_8_SHA256_BYTES
4373    };
4374
4375    if (cipher_str[idx] == NULL)
4376        return 1;
4377    /* Skip ChaCha20Poly1305 as currently FIPS module does not support it */
4378    if (idx == 2 && is_fips == 1)
4379        return 1;
4380
4381    /* We always set this up with a final parameter of "2" for PSK */
4382    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4383                                        &serverssl, &sess, 2,
4384                                        SHA384_DIGEST_LENGTH)))
4385        goto end;
4386
4387    if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
4388            || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
4389        goto end;
4390
4391    /*
4392     * 'setupearly_data_test' creates only one instance of SSL_SESSION
4393     * and assigns to both client and server with incremented reference
4394     * and the same instance is updated in 'sess'.
4395     * So updating ciphersuite in 'sess' which will get reflected in
4396     * PSK handshake using psk use sess and find sess cb.
4397     */
4398    cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
4399    if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
4400        goto end;
4401
4402    SSL_set_connect_state(clientssl);
4403    if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4404                                        &written)))
4405        goto end;
4406
4407    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4408                                         &readbytes),
4409                                         SSL_READ_EARLY_DATA_SUCCESS)
4410            || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4411            || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4412                                                      SSL_EARLY_DATA_ACCEPTED)
4413            || !TEST_int_eq(SSL_connect(clientssl), 1)
4414            || !TEST_int_eq(SSL_accept(serverssl), 1))
4415        goto end;
4416
4417    /* Send some normal data from client to server */
4418    if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4419            || !TEST_size_t_eq(written, strlen(MSG2)))
4420        goto end;
4421
4422    if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4423            || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4424        goto end;
4425
4426    testresult = 1;
4427 end:
4428    SSL_SESSION_free(sess);
4429    SSL_SESSION_free(clientpsk);
4430    SSL_SESSION_free(serverpsk);
4431    clientpsk = serverpsk = NULL;
4432    if (clientssl != NULL)
4433        SSL_shutdown(clientssl);
4434    if (serverssl != NULL)
4435        SSL_shutdown(serverssl);
4436    SSL_free(serverssl);
4437    SSL_free(clientssl);
4438    SSL_CTX_free(sctx);
4439    SSL_CTX_free(cctx);
4440    return testresult;
4441}
4442
4443/*
4444 * Test that a server that doesn't try to read early data can handle a
4445 * client sending some.
4446 */
4447static int test_early_data_not_expected(int idx)
4448{
4449    SSL_CTX *cctx = NULL, *sctx = NULL;
4450    SSL *clientssl = NULL, *serverssl = NULL;
4451    int testresult = 0;
4452    SSL_SESSION *sess = NULL;
4453    unsigned char buf[20];
4454    size_t readbytes, written;
4455
4456    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4457                                        &serverssl, &sess, idx,
4458                                        SHA384_DIGEST_LENGTH)))
4459        goto end;
4460
4461    /* Write some early data */
4462    if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4463                                        &written)))
4464        goto end;
4465
4466    /*
4467     * Server should skip over early data and then block waiting for client to
4468     * continue handshake
4469     */
4470    if (!TEST_int_le(SSL_accept(serverssl), 0)
4471     || !TEST_int_gt(SSL_connect(clientssl), 0)
4472     || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4473                     SSL_EARLY_DATA_REJECTED)
4474     || !TEST_int_gt(SSL_accept(serverssl), 0)
4475     || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4476                     SSL_EARLY_DATA_REJECTED))
4477        goto end;
4478
4479    /* Send some normal data from client to server */
4480    if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4481            || !TEST_size_t_eq(written, strlen(MSG2)))
4482        goto end;
4483
4484    if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4485            || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4486        goto end;
4487
4488    testresult = 1;
4489
4490 end:
4491    SSL_SESSION_free(sess);
4492    SSL_SESSION_free(clientpsk);
4493    SSL_SESSION_free(serverpsk);
4494    clientpsk = serverpsk = NULL;
4495    SSL_free(serverssl);
4496    SSL_free(clientssl);
4497    SSL_CTX_free(sctx);
4498    SSL_CTX_free(cctx);
4499    return testresult;
4500}
4501
4502
4503# ifndef OPENSSL_NO_TLS1_2
4504/*
4505 * Test that a server attempting to read early data can handle a connection
4506 * from a TLSv1.2 client.
4507 */
4508static int test_early_data_tls1_2(int idx)
4509{
4510    SSL_CTX *cctx = NULL, *sctx = NULL;
4511    SSL *clientssl = NULL, *serverssl = NULL;
4512    int testresult = 0;
4513    unsigned char buf[20];
4514    size_t readbytes, written;
4515
4516    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4517                                        &serverssl, NULL, idx,
4518                                        SHA384_DIGEST_LENGTH)))
4519        goto end;
4520
4521    /* Write some data - should block due to handshake with server */
4522    SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
4523    SSL_set_connect_state(clientssl);
4524    if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4525        goto end;
4526
4527    /*
4528     * Server should do TLSv1.2 handshake. First it will block waiting for more
4529     * messages from client after ServerDone. Then SSL_read_early_data should
4530     * finish and detect that early data has not been sent
4531     */
4532    if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4533                                         &readbytes),
4534                     SSL_READ_EARLY_DATA_ERROR))
4535        goto end;
4536
4537    /*
4538     * Continue writing the message we started earlier. Will still block waiting
4539     * for the CCS/Finished from server
4540     */
4541    if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4542            || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4543                                                &readbytes),
4544                            SSL_READ_EARLY_DATA_FINISH)
4545            || !TEST_size_t_eq(readbytes, 0)
4546            || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4547                            SSL_EARLY_DATA_NOT_SENT))
4548        goto end;
4549
4550    /* Continue writing the message we started earlier */
4551    if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4552            || !TEST_size_t_eq(written, strlen(MSG1))
4553            || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4554                            SSL_EARLY_DATA_NOT_SENT)
4555            || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4556            || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4557            || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
4558            || !TEST_size_t_eq(written, strlen(MSG2))
4559            || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
4560            || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4561        goto end;
4562
4563    testresult = 1;
4564
4565 end:
4566    SSL_SESSION_free(clientpsk);
4567    SSL_SESSION_free(serverpsk);
4568    clientpsk = serverpsk = NULL;
4569    SSL_free(serverssl);
4570    SSL_free(clientssl);
4571    SSL_CTX_free(sctx);
4572    SSL_CTX_free(cctx);
4573
4574    return testresult;
4575}
4576# endif /* OPENSSL_NO_TLS1_2 */
4577
4578/*
4579 * Test configuring the TLSv1.3 ciphersuites
4580 *
4581 * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
4582 * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
4583 * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
4584 * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
4585 * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4586 * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4587 * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
4588 * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
4589 * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
4590 * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
4591 */
4592static int test_set_ciphersuite(int idx)
4593{
4594    SSL_CTX *cctx = NULL, *sctx = NULL;
4595    SSL *clientssl = NULL, *serverssl = NULL;
4596    int testresult = 0;
4597
4598    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4599                                       TLS_client_method(), TLS1_VERSION, 0,
4600                                       &sctx, &cctx, cert, privkey))
4601            || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4602                           "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
4603        goto end;
4604
4605    if (idx >=4 && idx <= 7) {
4606        /* SSL_CTX explicit cipher list */
4607        if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
4608            goto end;
4609    }
4610
4611    if (idx == 0 || idx == 4) {
4612        /* Default ciphersuite */
4613        if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4614                                                "TLS_AES_128_GCM_SHA256")))
4615            goto end;
4616    } else if (idx == 1 || idx == 5) {
4617        /* Non default ciphersuite */
4618        if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4619                                                "TLS_AES_128_CCM_SHA256")))
4620            goto end;
4621    }
4622
4623    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4624                                          &clientssl, NULL, NULL)))
4625        goto end;
4626
4627    if (idx == 8 || idx == 9) {
4628        /* SSL explicit cipher list */
4629        if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
4630            goto end;
4631    }
4632
4633    if (idx == 2 || idx == 6 || idx == 8) {
4634        /* Default ciphersuite */
4635        if (!TEST_true(SSL_set_ciphersuites(clientssl,
4636                                            "TLS_AES_128_GCM_SHA256")))
4637            goto end;
4638    } else if (idx == 3 || idx == 7 || idx == 9) {
4639        /* Non default ciphersuite */
4640        if (!TEST_true(SSL_set_ciphersuites(clientssl,
4641                                            "TLS_AES_128_CCM_SHA256")))
4642            goto end;
4643    }
4644
4645    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4646        goto end;
4647
4648    testresult = 1;
4649
4650 end:
4651    SSL_free(serverssl);
4652    SSL_free(clientssl);
4653    SSL_CTX_free(sctx);
4654    SSL_CTX_free(cctx);
4655
4656    return testresult;
4657}
4658
4659static int test_ciphersuite_change(void)
4660{
4661    SSL_CTX *cctx = NULL, *sctx = NULL;
4662    SSL *clientssl = NULL, *serverssl = NULL;
4663    SSL_SESSION *clntsess = NULL;
4664    int testresult = 0;
4665    const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
4666
4667    /* Create a session based on SHA-256 */
4668    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4669                                       TLS_client_method(), TLS1_VERSION, 0,
4670                                       &sctx, &cctx, cert, privkey))
4671            || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4672                                                   "TLS_AES_128_GCM_SHA256:"
4673                                                   "TLS_AES_256_GCM_SHA384:"
4674                                                   "TLS_AES_128_CCM_SHA256"))
4675            || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4676                                                   "TLS_AES_128_GCM_SHA256"))
4677            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4678                                          &clientssl, NULL, NULL))
4679            || !TEST_true(create_ssl_connection(serverssl, clientssl,
4680                                                SSL_ERROR_NONE)))
4681        goto end;
4682
4683    clntsess = SSL_get1_session(clientssl);
4684    /* Save for later */
4685    aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
4686    SSL_shutdown(clientssl);
4687    SSL_shutdown(serverssl);
4688    SSL_free(serverssl);
4689    SSL_free(clientssl);
4690    serverssl = clientssl = NULL;
4691
4692    /* Check we can resume a session with a different SHA-256 ciphersuite */
4693    if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4694                                            "TLS_AES_128_CCM_SHA256"))
4695            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4696                                             &clientssl, NULL, NULL))
4697            || !TEST_true(SSL_set_session(clientssl, clntsess))
4698            || !TEST_true(create_ssl_connection(serverssl, clientssl,
4699                                                SSL_ERROR_NONE))
4700            || !TEST_true(SSL_session_reused(clientssl)))
4701        goto end;
4702
4703    SSL_SESSION_free(clntsess);
4704    clntsess = SSL_get1_session(clientssl);
4705    SSL_shutdown(clientssl);
4706    SSL_shutdown(serverssl);
4707    SSL_free(serverssl);
4708    SSL_free(clientssl);
4709    serverssl = clientssl = NULL;
4710
4711    /*
4712     * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
4713     * succeeds but does not resume.
4714     */
4715    if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4716            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4717                                             NULL, NULL))
4718            || !TEST_true(SSL_set_session(clientssl, clntsess))
4719            || !TEST_true(create_ssl_connection(serverssl, clientssl,
4720                                                SSL_ERROR_SSL))
4721            || !TEST_false(SSL_session_reused(clientssl)))
4722        goto end;
4723
4724    SSL_SESSION_free(clntsess);
4725    clntsess = NULL;
4726    SSL_shutdown(clientssl);
4727    SSL_shutdown(serverssl);
4728    SSL_free(serverssl);
4729    SSL_free(clientssl);
4730    serverssl = clientssl = NULL;
4731
4732    /* Create a session based on SHA384 */
4733    if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4734            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4735                                          &clientssl, NULL, NULL))
4736            || !TEST_true(create_ssl_connection(serverssl, clientssl,
4737                                                SSL_ERROR_NONE)))
4738        goto end;
4739
4740    clntsess = SSL_get1_session(clientssl);
4741    SSL_shutdown(clientssl);
4742    SSL_shutdown(serverssl);
4743    SSL_free(serverssl);
4744    SSL_free(clientssl);
4745    serverssl = clientssl = NULL;
4746
4747    if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4748                   "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
4749            || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4750                                                   "TLS_AES_256_GCM_SHA384"))
4751            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4752                                             NULL, NULL))
4753            || !TEST_true(SSL_set_session(clientssl, clntsess))
4754               /*
4755                * We use SSL_ERROR_WANT_READ below so that we can pause the
4756                * connection after the initial ClientHello has been sent to
4757                * enable us to make some session changes.
4758                */
4759            || !TEST_false(create_ssl_connection(serverssl, clientssl,
4760                                                SSL_ERROR_WANT_READ)))
4761        goto end;
4762
4763    /* Trick the client into thinking this session is for a different digest */
4764    clntsess->cipher = aes_128_gcm_sha256;
4765    clntsess->cipher_id = clntsess->cipher->id;
4766
4767    /*
4768     * Continue the previously started connection. Server has selected a SHA-384
4769     * ciphersuite, but client thinks the session is for SHA-256, so it should
4770     * bail out.
4771     */
4772    if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4773                                                SSL_ERROR_SSL))
4774            || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4775                            SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4776        goto end;
4777
4778    testresult = 1;
4779
4780 end:
4781    SSL_SESSION_free(clntsess);
4782    SSL_free(serverssl);
4783    SSL_free(clientssl);
4784    SSL_CTX_free(sctx);
4785    SSL_CTX_free(cctx);
4786
4787    return testresult;
4788}
4789
4790/*
4791 * Test TLSv1.3 Key exchange
4792 * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4793 * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4794 * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4795 * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4796 * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4797 * Test 5 = Test NID_X448 with TLSv1.3 client and server
4798 * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4799 * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4800 * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4801 * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4802 * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4803 * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4804 * Test 12 = Test all ECDHE with TLSv1.2 client and server
4805 * Test 13 = Test all FFDHE with TLSv1.2 client and server
4806 */
4807# ifndef OPENSSL_NO_EC
4808static int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
4809                                   NID_secp521r1, NID_X25519, NID_X448};
4810# endif
4811# ifndef OPENSSL_NO_DH
4812static int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4813                                   NID_ffdhe6144, NID_ffdhe8192};
4814# endif
4815static int test_key_exchange(int idx)
4816{
4817    SSL_CTX *sctx = NULL, *cctx = NULL;
4818    SSL *serverssl = NULL, *clientssl = NULL;
4819    int testresult = 0;
4820    int kexch_alg;
4821    int *kexch_groups = &kexch_alg;
4822    int kexch_groups_size = 1;
4823    int max_version = TLS1_3_VERSION;
4824    char *kexch_name0 = NULL;
4825
4826    switch (idx) {
4827# ifndef OPENSSL_NO_EC
4828# ifndef OPENSSL_NO_TLS1_2
4829        case 12:
4830            max_version = TLS1_2_VERSION;
4831# endif
4832            /* Fall through */
4833        case 0:
4834            kexch_groups = ecdhe_kexch_groups;
4835            kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
4836            kexch_name0 = "secp256r1";
4837            break;
4838        case 1:
4839            kexch_alg = NID_X9_62_prime256v1;
4840            kexch_name0 = "secp256r1";
4841            break;
4842        case 2:
4843            kexch_alg = NID_secp384r1;
4844            kexch_name0 = "secp384r1";
4845            break;
4846        case 3:
4847            kexch_alg = NID_secp521r1;
4848            kexch_name0 = "secp521r1";
4849            break;
4850        case 4:
4851            kexch_alg = NID_X25519;
4852            kexch_name0 = "x25519";
4853            break;
4854        case 5:
4855            kexch_alg = NID_X448;
4856            kexch_name0 = "x448";
4857            break;
4858# endif
4859# ifndef OPENSSL_NO_DH
4860# ifndef OPENSSL_NO_TLS1_2
4861        case 13:
4862            max_version = TLS1_2_VERSION;
4863            kexch_name0 = "ffdhe2048";
4864# endif
4865            /* Fall through */
4866        case 6:
4867            kexch_groups = ffdhe_kexch_groups;
4868            kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
4869            kexch_name0 = "ffdhe2048";
4870            break;
4871        case 7:
4872            kexch_alg = NID_ffdhe2048;
4873            kexch_name0 = "ffdhe2048";
4874            break;
4875        case 8:
4876            kexch_alg = NID_ffdhe3072;
4877            kexch_name0 = "ffdhe3072";
4878            break;
4879        case 9:
4880            kexch_alg = NID_ffdhe4096;
4881            kexch_name0 = "ffdhe4096";
4882            break;
4883        case 10:
4884            kexch_alg = NID_ffdhe6144;
4885            kexch_name0 = "ffdhe6144";
4886            break;
4887        case 11:
4888            kexch_alg = NID_ffdhe8192;
4889            kexch_name0 = "ffdhe8192";
4890            break;
4891# endif
4892        default:
4893            /* We're skipping this test */
4894            return 1;
4895    }
4896
4897    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4898                                       TLS_client_method(), TLS1_VERSION,
4899                                       max_version, &sctx, &cctx, cert,
4900                                       privkey)))
4901        goto end;
4902
4903    if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
4904                   TLS1_3_RFC_AES_128_GCM_SHA256)))
4905        goto end;
4906
4907    if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4908                   TLS1_3_RFC_AES_128_GCM_SHA256)))
4909        goto end;
4910
4911    if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
4912                   TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
4913                   TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
4914            || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
4915        goto end;
4916
4917    /*
4918     * Must include an EC ciphersuite so that we send supported groups in
4919     * TLSv1.2
4920     */
4921# ifndef OPENSSL_NO_TLS1_2
4922    if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
4923                   TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
4924                   TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
4925        goto end;
4926# endif
4927
4928    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4929                                             NULL, NULL)))
4930        goto end;
4931
4932    if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
4933        || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
4934        goto end;
4935
4936    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4937        goto end;
4938
4939    /*
4940     * If Handshake succeeds the negotiated kexch alg should be the first one in
4941     * configured, except in the case of FFDHE groups (idx 13), which are
4942     * TLSv1.3 only so we expect no shared group to exist.
4943     */
4944    if (!TEST_int_eq(SSL_get_shared_group(serverssl, 0),
4945                     idx == 13 ? 0 : kexch_groups[0]))
4946        goto end;
4947
4948    if (!TEST_str_eq(SSL_group_to_name(serverssl, kexch_groups[0]),
4949                     kexch_name0))
4950        goto end;
4951
4952    /* We don't implement RFC 7919 named groups for TLS 1.2. */
4953    if (idx != 13) {
4954        if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), kexch_groups[0]))
4955            goto end;
4956        if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), kexch_groups[0]))
4957            goto end;
4958    }
4959
4960    testresult = 1;
4961 end:
4962    SSL_free(serverssl);
4963    SSL_free(clientssl);
4964    SSL_CTX_free(sctx);
4965    SSL_CTX_free(cctx);
4966    return testresult;
4967}
4968
4969# if !defined(OPENSSL_NO_TLS1_2) \
4970     && !defined(OPENSSL_NO_EC)  \
4971     && !defined(OPENSSL_NO_DH)
4972static int set_ssl_groups(SSL *serverssl, SSL *clientssl, int clientmulti,
4973                          int isecdhe, int idx)
4974{
4975    int kexch_alg;
4976    int *kexch_groups = &kexch_alg;
4977    int numec, numff;
4978
4979    numec = OSSL_NELEM(ecdhe_kexch_groups);
4980    numff = OSSL_NELEM(ffdhe_kexch_groups);
4981    if (isecdhe)
4982        kexch_alg = ecdhe_kexch_groups[idx];
4983    else
4984        kexch_alg = ffdhe_kexch_groups[idx];
4985
4986    if (clientmulti) {
4987        if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, 1)))
4988            return 0;
4989        if (isecdhe) {
4990            if (!TEST_true(SSL_set1_groups(clientssl, ecdhe_kexch_groups,
4991                                           numec)))
4992                return 0;
4993        } else {
4994            if (!TEST_true(SSL_set1_groups(clientssl, ffdhe_kexch_groups,
4995                                           numff)))
4996                return 0;
4997        }
4998    } else {
4999        if (!TEST_true(SSL_set1_groups(clientssl, kexch_groups, 1)))
5000            return 0;
5001        if (isecdhe) {
5002            if (!TEST_true(SSL_set1_groups(serverssl, ecdhe_kexch_groups,
5003                                           numec)))
5004                return 0;
5005        } else {
5006            if (!TEST_true(SSL_set1_groups(serverssl, ffdhe_kexch_groups,
5007                                           numff)))
5008                return 0;
5009        }
5010    }
5011    return 1;
5012}
5013
5014/*-
5015 * Test the SSL_get_negotiated_group() API across a battery of scenarios.
5016 * Run through both the ECDHE and FFDHE group lists used in the previous
5017 * test, for both TLS 1.2 and TLS 1.3, negotiating each group in turn,
5018 * confirming the expected result; then perform a resumption handshake
5019 * while offering the same group list, and another resumption handshake
5020 * offering a different group list.  The returned value should be the
5021 * negotiated group for the initial handshake; for TLS 1.3 resumption
5022 * handshakes the returned value will be negotiated on the resumption
5023 * handshake itself, but for TLS 1.2 resumption handshakes the value will
5024 * be cached in the session from the original handshake, regardless of what
5025 * was offered in the resumption ClientHello.
5026 *
5027 * Using E for the number of EC groups and F for the number of FF groups:
5028 * E tests of ECDHE with TLS 1.3, server only has one group
5029 * F tests of FFDHE with TLS 1.3, server only has one group
5030 * E tests of ECDHE with TLS 1.2, server only has one group
5031 * F tests of FFDHE with TLS 1.2, server only has one group
5032 * E tests of ECDHE with TLS 1.3, client sends only one group
5033 * F tests of FFDHE with TLS 1.3, client sends only one group
5034 * E tests of ECDHE with TLS 1.2, client sends only one group
5035 * F tests of FFDHE with TLS 1.2, client sends only one group
5036 */
5037static int test_negotiated_group(int idx)
5038{
5039    int clientmulti, istls13, isecdhe, numec, numff, numgroups;
5040    int expectednid;
5041    SSL_CTX *sctx = NULL, *cctx = NULL;
5042    SSL *serverssl = NULL, *clientssl = NULL;
5043    SSL_SESSION *origsess = NULL;
5044    int testresult = 0;
5045    int kexch_alg;
5046    int max_version = TLS1_3_VERSION;
5047
5048    numec = OSSL_NELEM(ecdhe_kexch_groups);
5049    numff = OSSL_NELEM(ffdhe_kexch_groups);
5050    numgroups = numec + numff;
5051    clientmulti = (idx < 2 * numgroups);
5052    idx = idx % (2 * numgroups);
5053    istls13 = (idx < numgroups);
5054    idx = idx % numgroups;
5055    isecdhe = (idx < numec);
5056    if (!isecdhe)
5057        idx -= numec;
5058    /* Now 'idx' is an index into ecdhe_kexch_groups or ffdhe_kexch_groups */
5059    if (isecdhe)
5060        kexch_alg = ecdhe_kexch_groups[idx];
5061    else
5062        kexch_alg = ffdhe_kexch_groups[idx];
5063    /* We expect nothing for the unimplemented TLS 1.2 FFDHE named groups */
5064    if (!istls13 && !isecdhe)
5065        expectednid = NID_undef;
5066    else
5067        expectednid = kexch_alg;
5068
5069    if (!istls13)
5070        max_version = TLS1_2_VERSION;
5071
5072    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5073                                       TLS_client_method(), TLS1_VERSION,
5074                                       max_version, &sctx, &cctx, cert,
5075                                       privkey)))
5076        goto end;
5077
5078    /*
5079     * Force (EC)DHE ciphers for TLS 1.2.
5080     * Be sure to enable auto tmp DH so that FFDHE can succeed.
5081     */
5082    if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5083                   TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5084                   TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5085            || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5086        goto end;
5087    if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5088                   TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5089                   TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5090        goto end;
5091
5092    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5093                                             NULL, NULL)))
5094        goto end;
5095
5096    if (!TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe,
5097                                  idx)))
5098        goto end;
5099
5100    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5101        goto end;
5102
5103    /* Initial handshake; always the configured one */
5104    if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5105            || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5106        goto end;
5107
5108    if (!TEST_ptr((origsess = SSL_get1_session(clientssl))))
5109        goto end;
5110
5111    SSL_shutdown(clientssl);
5112    SSL_shutdown(serverssl);
5113    SSL_free(serverssl);
5114    SSL_free(clientssl);
5115    serverssl = clientssl = NULL;
5116
5117    /* First resumption attempt; use the same config as initial handshake */
5118    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5119                                             NULL, NULL))
5120            || !TEST_true(SSL_set_session(clientssl, origsess))
5121            || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5122                                         isecdhe, idx)))
5123        goto end;
5124
5125    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5126            || !TEST_true(SSL_session_reused(clientssl)))
5127        goto end;
5128
5129    /* Still had better agree, since nothing changed... */
5130    if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5131            || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5132        goto end;
5133
5134    SSL_shutdown(clientssl);
5135    SSL_shutdown(serverssl);
5136    SSL_free(serverssl);
5137    SSL_free(clientssl);
5138    serverssl = clientssl = NULL;
5139
5140    /*-
5141     * Second resumption attempt
5142     * The party that picks one group changes it, which we effectuate by
5143     * changing 'idx' and updating what we expect.
5144     */
5145    if (idx == 0)
5146        idx = 1;
5147    else
5148        idx--;
5149    if (istls13) {
5150        if (isecdhe)
5151            expectednid = ecdhe_kexch_groups[idx];
5152        else
5153            expectednid = ffdhe_kexch_groups[idx];
5154        /* Verify that we are changing what we expect. */
5155        if (!TEST_int_ne(expectednid, kexch_alg))
5156            goto end;
5157    } else {
5158        /* TLS 1.2 only supports named groups for ECDHE. */
5159        if (isecdhe)
5160            expectednid = kexch_alg;
5161        else
5162            expectednid = 0;
5163    }
5164    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5165                                             NULL, NULL))
5166            || !TEST_true(SSL_set_session(clientssl, origsess))
5167            || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5168                                         isecdhe, idx)))
5169        goto end;
5170
5171    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5172            || !TEST_true(SSL_session_reused(clientssl)))
5173        goto end;
5174
5175    /* Check that we get what we expected */
5176    if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5177            || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5178        goto end;
5179
5180    testresult = 1;
5181 end:
5182    SSL_free(serverssl);
5183    SSL_free(clientssl);
5184    SSL_CTX_free(sctx);
5185    SSL_CTX_free(cctx);
5186    SSL_SESSION_free(origsess);
5187    return testresult;
5188}
5189# endif /* !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) */
5190
5191/*
5192 * Test TLSv1.3 Cipher Suite
5193 * Test 0 = Set TLS1.3 cipher on context
5194 * Test 1 = Set TLS1.3 cipher on SSL
5195 * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
5196 * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
5197 */
5198static int test_tls13_ciphersuite(int idx)
5199{
5200    SSL_CTX *sctx = NULL, *cctx = NULL;
5201    SSL *serverssl = NULL, *clientssl = NULL;
5202    static const struct {
5203        const char *ciphername;
5204        int fipscapable;
5205    } t13_ciphers[] = {
5206        { TLS1_3_RFC_AES_128_GCM_SHA256, 1 },
5207        { TLS1_3_RFC_AES_256_GCM_SHA384, 1 },
5208        { TLS1_3_RFC_AES_128_CCM_SHA256, 1 },
5209# if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5210        { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
5211        { TLS1_3_RFC_AES_256_GCM_SHA384
5212          ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
5213# endif
5214        { TLS1_3_RFC_AES_128_CCM_8_SHA256 ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1 }
5215    };
5216    const char *t13_cipher = NULL;
5217    const char *t12_cipher = NULL;
5218    const char *negotiated_scipher;
5219    const char *negotiated_ccipher;
5220    int set_at_ctx = 0;
5221    int set_at_ssl = 0;
5222    int testresult = 0;
5223    int max_ver;
5224    size_t i;
5225
5226    switch (idx) {
5227        case 0:
5228            set_at_ctx = 1;
5229            break;
5230        case 1:
5231            set_at_ssl = 1;
5232            break;
5233        case 2:
5234            set_at_ctx = 1;
5235            t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5236            break;
5237        case 3:
5238            set_at_ssl = 1;
5239            t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5240            break;
5241    }
5242
5243    for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
5244# ifdef OPENSSL_NO_TLS1_2
5245        if (max_ver == TLS1_2_VERSION)
5246            continue;
5247# endif
5248        for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
5249            if (is_fips && !t13_ciphers[i].fipscapable)
5250                continue;
5251            t13_cipher = t13_ciphers[i].ciphername;
5252            if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5253                                               TLS_client_method(),
5254                                               TLS1_VERSION, max_ver,
5255                                               &sctx, &cctx, cert, privkey)))
5256                goto end;
5257
5258            if (set_at_ctx) {
5259                if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
5260                    || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
5261                    goto end;
5262                if (t12_cipher != NULL) {
5263                    if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
5264                        || !TEST_true(SSL_CTX_set_cipher_list(cctx,
5265                                                              t12_cipher)))
5266                        goto end;
5267                }
5268            }
5269
5270            if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5271                                              &clientssl, NULL, NULL)))
5272                goto end;
5273
5274            if (set_at_ssl) {
5275                if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
5276                    || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
5277                    goto end;
5278                if (t12_cipher != NULL) {
5279                    if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
5280                        || !TEST_true(SSL_set_cipher_list(clientssl,
5281                                                          t12_cipher)))
5282                        goto end;
5283                }
5284            }
5285
5286            if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5287                                                 SSL_ERROR_NONE)))
5288                goto end;
5289
5290            negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5291                                                                 serverssl));
5292            negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5293                                                                 clientssl));
5294            if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
5295                goto end;
5296
5297            /*
5298             * TEST_strn_eq is used below because t13_cipher can contain
5299             * multiple ciphersuites
5300             */
5301            if (max_ver == TLS1_3_VERSION
5302                && !TEST_strn_eq(t13_cipher, negotiated_scipher,
5303                                 strlen(negotiated_scipher)))
5304                goto end;
5305
5306# ifndef OPENSSL_NO_TLS1_2
5307            /* Below validation is not done when t12_cipher is NULL */
5308            if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
5309                && !TEST_str_eq(t12_cipher, negotiated_scipher))
5310                goto end;
5311# endif
5312
5313            SSL_free(serverssl);
5314            serverssl = NULL;
5315            SSL_free(clientssl);
5316            clientssl = NULL;
5317            SSL_CTX_free(sctx);
5318            sctx = NULL;
5319            SSL_CTX_free(cctx);
5320            cctx = NULL;
5321        }
5322    }
5323
5324    testresult = 1;
5325 end:
5326    SSL_free(serverssl);
5327    SSL_free(clientssl);
5328    SSL_CTX_free(sctx);
5329    SSL_CTX_free(cctx);
5330    return testresult;
5331}
5332
5333/*
5334 * Test TLSv1.3 PSKs
5335 * Test 0 = Test new style callbacks
5336 * Test 1 = Test both new and old style callbacks
5337 * Test 2 = Test old style callbacks
5338 * Test 3 = Test old style callbacks with no certificate
5339 */
5340static int test_tls13_psk(int idx)
5341{
5342    SSL_CTX *sctx = NULL, *cctx = NULL;
5343    SSL *serverssl = NULL, *clientssl = NULL;
5344    const SSL_CIPHER *cipher = NULL;
5345    const unsigned char key[] = {
5346        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
5347        0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5348        0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
5349        0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
5350    };
5351    int testresult = 0;
5352
5353    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5354                                       TLS_client_method(), TLS1_VERSION, 0,
5355                                       &sctx, &cctx, idx == 3 ? NULL : cert,
5356                                       idx == 3 ? NULL : privkey)))
5357        goto end;
5358
5359    if (idx != 3) {
5360        /*
5361         * We use a ciphersuite with SHA256 to ease testing old style PSK
5362         * callbacks which will always default to SHA256. This should not be
5363         * necessary if we have no cert/priv key. In that case the server should
5364         * prefer SHA256 automatically.
5365         */
5366        if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5367                                                "TLS_AES_128_GCM_SHA256")))
5368            goto end;
5369    } else {
5370        /*
5371         * As noted above the server should prefer SHA256 automatically. However
5372         * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
5373         * code works even if we are testing with only the FIPS provider loaded.
5374         */
5375        if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5376                                                "TLS_AES_256_GCM_SHA384:"
5377                                                "TLS_AES_128_GCM_SHA256")))
5378            goto end;
5379    }
5380
5381    /*
5382     * Test 0: New style callbacks only
5383     * Test 1: New and old style callbacks (only the new ones should be used)
5384     * Test 2: Old style callbacks only
5385     */
5386    if (idx == 0 || idx == 1) {
5387        SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
5388        SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
5389    }
5390#ifndef OPENSSL_NO_PSK
5391    if (idx >= 1) {
5392        SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
5393        SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
5394    }
5395#endif
5396    srvid = pskid;
5397    use_session_cb_cnt = 0;
5398    find_session_cb_cnt = 0;
5399    psk_client_cb_cnt = 0;
5400    psk_server_cb_cnt = 0;
5401
5402    if (idx != 3) {
5403        /*
5404         * Check we can create a connection if callback decides not to send a
5405         * PSK
5406         */
5407        if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5408                                                 NULL, NULL))
5409                || !TEST_true(create_ssl_connection(serverssl, clientssl,
5410                                                    SSL_ERROR_NONE))
5411                || !TEST_false(SSL_session_reused(clientssl))
5412                || !TEST_false(SSL_session_reused(serverssl)))
5413            goto end;
5414
5415        if (idx == 0 || idx == 1) {
5416            if (!TEST_true(use_session_cb_cnt == 1)
5417                    || !TEST_true(find_session_cb_cnt == 0)
5418                       /*
5419                        * If no old style callback then below should be 0
5420                        * otherwise 1
5421                        */
5422                    || !TEST_true(psk_client_cb_cnt == idx)
5423                    || !TEST_true(psk_server_cb_cnt == 0))
5424                goto end;
5425        } else {
5426            if (!TEST_true(use_session_cb_cnt == 0)
5427                    || !TEST_true(find_session_cb_cnt == 0)
5428                    || !TEST_true(psk_client_cb_cnt == 1)
5429                    || !TEST_true(psk_server_cb_cnt == 0))
5430                goto end;
5431        }
5432
5433        shutdown_ssl_connection(serverssl, clientssl);
5434        serverssl = clientssl = NULL;
5435        use_session_cb_cnt = psk_client_cb_cnt = 0;
5436    }
5437
5438    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5439                                             NULL, NULL)))
5440        goto end;
5441
5442    /* Create the PSK */
5443    cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
5444    clientpsk = SSL_SESSION_new();
5445    if (!TEST_ptr(clientpsk)
5446            || !TEST_ptr(cipher)
5447            || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
5448                                                      sizeof(key)))
5449            || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
5450            || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
5451                                                           TLS1_3_VERSION))
5452            || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
5453        goto end;
5454    serverpsk = clientpsk;
5455
5456    /* Check we can create a connection and the PSK is used */
5457    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5458            || !TEST_true(SSL_session_reused(clientssl))
5459            || !TEST_true(SSL_session_reused(serverssl)))
5460        goto end;
5461
5462    if (idx == 0 || idx == 1) {
5463        if (!TEST_true(use_session_cb_cnt == 1)
5464                || !TEST_true(find_session_cb_cnt == 1)
5465                || !TEST_true(psk_client_cb_cnt == 0)
5466                || !TEST_true(psk_server_cb_cnt == 0))
5467            goto end;
5468    } else {
5469        if (!TEST_true(use_session_cb_cnt == 0)
5470                || !TEST_true(find_session_cb_cnt == 0)
5471                || !TEST_true(psk_client_cb_cnt == 1)
5472                || !TEST_true(psk_server_cb_cnt == 1))
5473            goto end;
5474    }
5475
5476    shutdown_ssl_connection(serverssl, clientssl);
5477    serverssl = clientssl = NULL;
5478    use_session_cb_cnt = find_session_cb_cnt = 0;
5479    psk_client_cb_cnt = psk_server_cb_cnt = 0;
5480
5481    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5482                                             NULL, NULL)))
5483        goto end;
5484
5485    /* Force an HRR */
5486#if defined(OPENSSL_NO_EC)
5487    if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
5488        goto end;
5489#else
5490    if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
5491        goto end;
5492#endif
5493
5494    /*
5495     * Check we can create a connection, the PSK is used and the callbacks are
5496     * called twice.
5497     */
5498    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5499            || !TEST_true(SSL_session_reused(clientssl))
5500            || !TEST_true(SSL_session_reused(serverssl)))
5501        goto end;
5502
5503    if (idx == 0 || idx == 1) {
5504        if (!TEST_true(use_session_cb_cnt == 2)
5505                || !TEST_true(find_session_cb_cnt == 2)
5506                || !TEST_true(psk_client_cb_cnt == 0)
5507                || !TEST_true(psk_server_cb_cnt == 0))
5508            goto end;
5509    } else {
5510        if (!TEST_true(use_session_cb_cnt == 0)
5511                || !TEST_true(find_session_cb_cnt == 0)
5512                || !TEST_true(psk_client_cb_cnt == 2)
5513                || !TEST_true(psk_server_cb_cnt == 2))
5514            goto end;
5515    }
5516
5517    shutdown_ssl_connection(serverssl, clientssl);
5518    serverssl = clientssl = NULL;
5519    use_session_cb_cnt = find_session_cb_cnt = 0;
5520    psk_client_cb_cnt = psk_server_cb_cnt = 0;
5521
5522    if (idx != 3) {
5523        /*
5524         * Check that if the server rejects the PSK we can still connect, but with
5525         * a full handshake
5526         */
5527        srvid = "Dummy Identity";
5528        if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5529                                                 NULL, NULL))
5530                || !TEST_true(create_ssl_connection(serverssl, clientssl,
5531                                                    SSL_ERROR_NONE))
5532                || !TEST_false(SSL_session_reused(clientssl))
5533                || !TEST_false(SSL_session_reused(serverssl)))
5534            goto end;
5535
5536        if (idx == 0 || idx == 1) {
5537            if (!TEST_true(use_session_cb_cnt == 1)
5538                    || !TEST_true(find_session_cb_cnt == 1)
5539                    || !TEST_true(psk_client_cb_cnt == 0)
5540                       /*
5541                        * If no old style callback then below should be 0
5542                        * otherwise 1
5543                        */
5544                    || !TEST_true(psk_server_cb_cnt == idx))
5545                goto end;
5546        } else {
5547            if (!TEST_true(use_session_cb_cnt == 0)
5548                    || !TEST_true(find_session_cb_cnt == 0)
5549                    || !TEST_true(psk_client_cb_cnt == 1)
5550                    || !TEST_true(psk_server_cb_cnt == 1))
5551                goto end;
5552        }
5553
5554        shutdown_ssl_connection(serverssl, clientssl);
5555        serverssl = clientssl = NULL;
5556    }
5557    testresult = 1;
5558
5559 end:
5560    SSL_SESSION_free(clientpsk);
5561    SSL_SESSION_free(serverpsk);
5562    clientpsk = serverpsk = NULL;
5563    SSL_free(serverssl);
5564    SSL_free(clientssl);
5565    SSL_CTX_free(sctx);
5566    SSL_CTX_free(cctx);
5567    return testresult;
5568}
5569
5570static unsigned char cookie_magic_value[] = "cookie magic";
5571
5572static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
5573                                    unsigned int *cookie_len)
5574{
5575    /*
5576     * Not suitable as a real cookie generation function but good enough for
5577     * testing!
5578     */
5579    memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
5580    *cookie_len = sizeof(cookie_magic_value) - 1;
5581
5582    return 1;
5583}
5584
5585static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
5586                                  unsigned int cookie_len)
5587{
5588    if (cookie_len == sizeof(cookie_magic_value) - 1
5589        && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
5590        return 1;
5591
5592    return 0;
5593}
5594
5595static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
5596                                        size_t *cookie_len)
5597{
5598    unsigned int temp;
5599    int res = generate_cookie_callback(ssl, cookie, &temp);
5600    *cookie_len = temp;
5601    return res;
5602}
5603
5604static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
5605                                      size_t cookie_len)
5606{
5607    return verify_cookie_callback(ssl, cookie, cookie_len);
5608}
5609
5610static int test_stateless(void)
5611{
5612    SSL_CTX *sctx = NULL, *cctx = NULL;
5613    SSL *serverssl = NULL, *clientssl = NULL;
5614    int testresult = 0;
5615
5616    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5617                                       TLS_client_method(), TLS1_VERSION, 0,
5618                                       &sctx, &cctx, cert, privkey)))
5619        goto end;
5620
5621    /* The arrival of CCS messages can confuse the test */
5622    SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5623
5624    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5625                                      NULL, NULL))
5626               /* Send the first ClientHello */
5627            || !TEST_false(create_ssl_connection(serverssl, clientssl,
5628                                                 SSL_ERROR_WANT_READ))
5629               /*
5630                * This should fail with a -1 return because we have no callbacks
5631                * set up
5632                */
5633            || !TEST_int_eq(SSL_stateless(serverssl), -1))
5634        goto end;
5635
5636    /* Fatal error so abandon the connection from this client */
5637    SSL_free(clientssl);
5638    clientssl = NULL;
5639
5640    /* Set up the cookie generation and verification callbacks */
5641    SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
5642    SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
5643
5644    /*
5645     * Create a new connection from the client (we can reuse the server SSL
5646     * object).
5647     */
5648    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5649                                             NULL, NULL))
5650               /* Send the first ClientHello */
5651            || !TEST_false(create_ssl_connection(serverssl, clientssl,
5652                                                SSL_ERROR_WANT_READ))
5653               /* This should fail because there is no cookie */
5654            || !TEST_int_eq(SSL_stateless(serverssl), 0))
5655        goto end;
5656
5657    /* Abandon the connection from this client */
5658    SSL_free(clientssl);
5659    clientssl = NULL;
5660
5661    /*
5662     * Now create a connection from a new client but with the same server SSL
5663     * object
5664     */
5665    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5666                                             NULL, NULL))
5667               /* Send the first ClientHello */
5668            || !TEST_false(create_ssl_connection(serverssl, clientssl,
5669                                                SSL_ERROR_WANT_READ))
5670               /* This should fail because there is no cookie */
5671            || !TEST_int_eq(SSL_stateless(serverssl), 0)
5672               /* Send the second ClientHello */
5673            || !TEST_false(create_ssl_connection(serverssl, clientssl,
5674                                                SSL_ERROR_WANT_READ))
5675               /* This should succeed because a cookie is now present */
5676            || !TEST_int_eq(SSL_stateless(serverssl), 1)
5677               /* Complete the connection */
5678            || !TEST_true(create_ssl_connection(serverssl, clientssl,
5679                                                SSL_ERROR_NONE)))
5680        goto end;
5681
5682    shutdown_ssl_connection(serverssl, clientssl);
5683    serverssl = clientssl = NULL;
5684    testresult = 1;
5685
5686 end:
5687    SSL_free(serverssl);
5688    SSL_free(clientssl);
5689    SSL_CTX_free(sctx);
5690    SSL_CTX_free(cctx);
5691    return testresult;
5692
5693}
5694#endif /* OSSL_NO_USABLE_TLS1_3 */
5695
5696static int clntaddoldcb = 0;
5697static int clntparseoldcb = 0;
5698static int srvaddoldcb = 0;
5699static int srvparseoldcb = 0;
5700static int clntaddnewcb = 0;
5701static int clntparsenewcb = 0;
5702static int srvaddnewcb = 0;
5703static int srvparsenewcb = 0;
5704static int snicb = 0;
5705
5706#define TEST_EXT_TYPE1  0xff00
5707
5708static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
5709                      size_t *outlen, int *al, void *add_arg)
5710{
5711    int *server = (int *)add_arg;
5712    unsigned char *data;
5713
5714    if (SSL_is_server(s))
5715        srvaddoldcb++;
5716    else
5717        clntaddoldcb++;
5718
5719    if (*server != SSL_is_server(s)
5720            || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
5721        return -1;
5722
5723    *data = 1;
5724    *out = data;
5725    *outlen = sizeof(char);
5726    return 1;
5727}
5728
5729static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
5730                        void *add_arg)
5731{
5732    OPENSSL_free((unsigned char *)out);
5733}
5734
5735static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
5736                        size_t inlen, int *al, void *parse_arg)
5737{
5738    int *server = (int *)parse_arg;
5739
5740    if (SSL_is_server(s))
5741        srvparseoldcb++;
5742    else
5743        clntparseoldcb++;
5744
5745    if (*server != SSL_is_server(s)
5746            || inlen != sizeof(char)
5747            || *in != 1)
5748        return -1;
5749
5750    return 1;
5751}
5752
5753static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
5754                      const unsigned char **out, size_t *outlen, X509 *x,
5755                      size_t chainidx, int *al, void *add_arg)
5756{
5757    int *server = (int *)add_arg;
5758    unsigned char *data;
5759
5760    if (SSL_is_server(s))
5761        srvaddnewcb++;
5762    else
5763        clntaddnewcb++;
5764
5765    if (*server != SSL_is_server(s)
5766            || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
5767        return -1;
5768
5769    *data = 1;
5770    *out = data;
5771    *outlen = sizeof(*data);
5772    return 1;
5773}
5774
5775static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
5776                        const unsigned char *out, void *add_arg)
5777{
5778    OPENSSL_free((unsigned char *)out);
5779}
5780
5781static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
5782                        const unsigned char *in, size_t inlen, X509 *x,
5783                        size_t chainidx, int *al, void *parse_arg)
5784{
5785    int *server = (int *)parse_arg;
5786
5787    if (SSL_is_server(s))
5788        srvparsenewcb++;
5789    else
5790        clntparsenewcb++;
5791
5792    if (*server != SSL_is_server(s)
5793            || inlen != sizeof(char) || *in != 1)
5794        return -1;
5795
5796    return 1;
5797}
5798
5799static int sni_cb(SSL *s, int *al, void *arg)
5800{
5801    SSL_CTX *ctx = (SSL_CTX *)arg;
5802
5803    if (SSL_set_SSL_CTX(s, ctx) == NULL) {
5804        *al = SSL_AD_INTERNAL_ERROR;
5805        return SSL_TLSEXT_ERR_ALERT_FATAL;
5806    }
5807    snicb++;
5808    return SSL_TLSEXT_ERR_OK;
5809}
5810
5811static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
5812{
5813    return 1;
5814}
5815
5816/*
5817 * Custom call back tests.
5818 * Test 0: Old style callbacks in TLSv1.2
5819 * Test 1: New style callbacks in TLSv1.2
5820 * Test 2: New style callbacks in TLSv1.2 with SNI
5821 * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
5822 * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
5823 * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
5824 */
5825static int test_custom_exts(int tst)
5826{
5827    SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
5828    SSL *clientssl = NULL, *serverssl = NULL;
5829    int testresult = 0;
5830    static int server = 1;
5831    static int client = 0;
5832    SSL_SESSION *sess = NULL;
5833    unsigned int context;
5834
5835#if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
5836    /* Skip tests for TLSv1.2 and below in this case */
5837    if (tst < 3)
5838        return 1;
5839#endif
5840
5841    /* Reset callback counters */
5842    clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
5843    clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
5844    snicb = 0;
5845
5846    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5847                                       TLS_client_method(), TLS1_VERSION, 0,
5848                                       &sctx, &cctx, cert, privkey)))
5849        goto end;
5850
5851    if (tst == 2
5852            && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
5853                                              TLS1_VERSION, 0,
5854                                              &sctx2, NULL, cert, privkey)))
5855        goto end;
5856
5857
5858    if (tst < 3) {
5859        SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
5860        SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
5861        if (sctx2 != NULL)
5862            SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
5863    }
5864
5865    if (tst == 5) {
5866        context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
5867                  | SSL_EXT_TLS1_3_CERTIFICATE;
5868        SSL_CTX_set_verify(sctx,
5869                           SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
5870                           verify_cb);
5871        if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
5872                                                      SSL_FILETYPE_PEM), 1)
5873                || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
5874                                                            SSL_FILETYPE_PEM), 1)
5875                || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
5876            goto end;
5877    } else if (tst == 4) {
5878        context = SSL_EXT_CLIENT_HELLO
5879                  | SSL_EXT_TLS1_2_SERVER_HELLO
5880                  | SSL_EXT_TLS1_3_SERVER_HELLO
5881                  | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
5882                  | SSL_EXT_TLS1_3_CERTIFICATE
5883                  | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
5884    } else {
5885        context = SSL_EXT_CLIENT_HELLO
5886                  | SSL_EXT_TLS1_2_SERVER_HELLO
5887                  | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
5888    }
5889
5890    /* Create a client side custom extension */
5891    if (tst == 0) {
5892        if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
5893                                                     old_add_cb, old_free_cb,
5894                                                     &client, old_parse_cb,
5895                                                     &client)))
5896            goto end;
5897    } else {
5898        if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
5899                                              new_add_cb, new_free_cb,
5900                                              &client, new_parse_cb, &client)))
5901            goto end;
5902    }
5903
5904    /* Should not be able to add duplicates */
5905    if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
5906                                                  old_add_cb, old_free_cb,
5907                                                  &client, old_parse_cb,
5908                                                  &client))
5909            || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
5910                                                  context, new_add_cb,
5911                                                  new_free_cb, &client,
5912                                                  new_parse_cb, &client)))
5913        goto end;
5914
5915    /* Create a server side custom extension */
5916    if (tst == 0) {
5917        if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
5918                                                     old_add_cb, old_free_cb,
5919                                                     &server, old_parse_cb,
5920                                                     &server)))
5921            goto end;
5922    } else {
5923        if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
5924                                              new_add_cb, new_free_cb,
5925                                              &server, new_parse_cb, &server)))
5926            goto end;
5927        if (sctx2 != NULL
5928                && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
5929                                                     context, new_add_cb,
5930                                                     new_free_cb, &server,
5931                                                     new_parse_cb, &server)))
5932            goto end;
5933    }
5934
5935    /* Should not be able to add duplicates */
5936    if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
5937                                                  old_add_cb, old_free_cb,
5938                                                  &server, old_parse_cb,
5939                                                  &server))
5940            || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
5941                                                  context, new_add_cb,
5942                                                  new_free_cb, &server,
5943                                                  new_parse_cb, &server)))
5944        goto end;
5945
5946    if (tst == 2) {
5947        /* Set up SNI */
5948        if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
5949                || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
5950            goto end;
5951    }
5952
5953    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5954                                      &clientssl, NULL, NULL))
5955            || !TEST_true(create_ssl_connection(serverssl, clientssl,
5956                                                SSL_ERROR_NONE)))
5957        goto end;
5958
5959    if (tst == 0) {
5960        if (clntaddoldcb != 1
5961                || clntparseoldcb != 1
5962                || srvaddoldcb != 1
5963                || srvparseoldcb != 1)
5964            goto end;
5965    } else if (tst == 1 || tst == 2 || tst == 3) {
5966        if (clntaddnewcb != 1
5967                || clntparsenewcb != 1
5968                || srvaddnewcb != 1
5969                || srvparsenewcb != 1
5970                || (tst != 2 && snicb != 0)
5971                || (tst == 2 && snicb != 1))
5972            goto end;
5973    } else if (tst == 5) {
5974        if (clntaddnewcb != 1
5975                || clntparsenewcb != 1
5976                || srvaddnewcb != 1
5977                || srvparsenewcb != 1)
5978            goto end;
5979    } else {
5980        /* In this case there 2 NewSessionTicket messages created */
5981        if (clntaddnewcb != 1
5982                || clntparsenewcb != 5
5983                || srvaddnewcb != 5
5984                || srvparsenewcb != 1)
5985            goto end;
5986    }
5987
5988    sess = SSL_get1_session(clientssl);
5989    SSL_shutdown(clientssl);
5990    SSL_shutdown(serverssl);
5991    SSL_free(serverssl);
5992    SSL_free(clientssl);
5993    serverssl = clientssl = NULL;
5994
5995    if (tst == 3 || tst == 5) {
5996        /* We don't bother with the resumption aspects for these tests */
5997        testresult = 1;
5998        goto end;
5999    }
6000
6001    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6002                                      NULL, NULL))
6003            || !TEST_true(SSL_set_session(clientssl, sess))
6004            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6005                                               SSL_ERROR_NONE)))
6006        goto end;
6007
6008    /*
6009     * For a resumed session we expect to add the ClientHello extension. For the
6010     * old style callbacks we ignore it on the server side because they set
6011     * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
6012     * them.
6013     */
6014    if (tst == 0) {
6015        if (clntaddoldcb != 2
6016                || clntparseoldcb != 1
6017                || srvaddoldcb != 1
6018                || srvparseoldcb != 1)
6019            goto end;
6020    } else if (tst == 1 || tst == 2 || tst == 3) {
6021        if (clntaddnewcb != 2
6022                || clntparsenewcb != 2
6023                || srvaddnewcb != 2
6024                || srvparsenewcb != 2)
6025            goto end;
6026    } else {
6027        /*
6028         * No Certificate message extensions in the resumption handshake,
6029         * 2 NewSessionTickets in the initial handshake, 1 in the resumption
6030         */
6031        if (clntaddnewcb != 2
6032                || clntparsenewcb != 8
6033                || srvaddnewcb != 8
6034                || srvparsenewcb != 2)
6035            goto end;
6036    }
6037
6038    testresult = 1;
6039
6040end:
6041    SSL_SESSION_free(sess);
6042    SSL_free(serverssl);
6043    SSL_free(clientssl);
6044    SSL_CTX_free(sctx2);
6045    SSL_CTX_free(sctx);
6046    SSL_CTX_free(cctx);
6047    return testresult;
6048}
6049
6050#if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6051
6052#define  SYNTHV1CONTEXT     (SSL_EXT_TLS1_2_AND_BELOW_ONLY \
6053                             | SSL_EXT_CLIENT_HELLO \
6054                             | SSL_EXT_TLS1_2_SERVER_HELLO \
6055                             | SSL_EXT_IGNORE_ON_RESUMPTION)
6056
6057#define TLS13CONTEXT (SSL_EXT_TLS1_3_CERTIFICATE \
6058                      | SSL_EXT_TLS1_2_SERVER_HELLO \
6059                      | SSL_EXT_CLIENT_HELLO)
6060
6061#define SERVERINFO_CUSTOM                                 \
6062    0x00, (char)TLSEXT_TYPE_signed_certificate_timestamp, \
6063    0x00, 0x03,                                           \
6064    0x04, 0x05, 0x06                                      \
6065
6066static const unsigned char serverinfo_custom_tls13[] = {
6067    0x00, 0x00, (TLS13CONTEXT >> 8) & 0xff, TLS13CONTEXT & 0xff,
6068    SERVERINFO_CUSTOM
6069};
6070static const unsigned char serverinfo_custom_v2[] = {
6071    0x00, 0x00, (SYNTHV1CONTEXT >> 8) & 0xff,  SYNTHV1CONTEXT & 0xff,
6072    SERVERINFO_CUSTOM
6073};
6074static const unsigned char serverinfo_custom_v1[] = {
6075    SERVERINFO_CUSTOM
6076};
6077static const size_t serverinfo_custom_tls13_len = sizeof(serverinfo_custom_tls13);
6078static const size_t serverinfo_custom_v2_len = sizeof(serverinfo_custom_v2);
6079static const size_t serverinfo_custom_v1_len = sizeof(serverinfo_custom_v1);
6080
6081static int serverinfo_custom_parse_cb(SSL *s, unsigned int ext_type,
6082                                      unsigned int context,
6083                                      const unsigned char *in,
6084                                      size_t inlen, X509 *x,
6085                                      size_t chainidx, int *al,
6086                                      void *parse_arg)
6087{
6088    const size_t len = serverinfo_custom_v1_len;
6089    const unsigned char *si = &serverinfo_custom_v1[len - 3];
6090    int *p_cb_result = (int*)parse_arg;
6091    *p_cb_result = TEST_mem_eq(in, inlen, si, 3);
6092    return 1;
6093}
6094
6095static int test_serverinfo_custom(const int idx)
6096{
6097    SSL_CTX *sctx = NULL, *cctx = NULL;
6098    SSL *clientssl = NULL, *serverssl = NULL;
6099    int testresult = 0;
6100    int cb_result = 0;
6101
6102    /*
6103     * Following variables are set in the switch statement
6104     *  according to the test iteration.
6105     * Default values do not make much sense: test would fail with them.
6106     */
6107    int serverinfo_version = 0;
6108    int protocol_version = 0;
6109    unsigned int extension_context = 0;
6110    const unsigned char *si = NULL;
6111    size_t si_len = 0;
6112
6113    const int call_use_serverinfo_ex = idx > 0;
6114    switch (idx) {
6115    case 0: /* FALLTHROUGH */
6116    case 1:
6117        serverinfo_version = SSL_SERVERINFOV1;
6118        protocol_version = TLS1_2_VERSION;
6119        extension_context = SYNTHV1CONTEXT;
6120        si = serverinfo_custom_v1;
6121        si_len = serverinfo_custom_v1_len;
6122        break;
6123    case 2:
6124        serverinfo_version = SSL_SERVERINFOV2;
6125        protocol_version = TLS1_2_VERSION;
6126        extension_context = SYNTHV1CONTEXT;
6127        si = serverinfo_custom_v2;
6128        si_len = serverinfo_custom_v2_len;
6129        break;
6130    case 3:
6131        serverinfo_version = SSL_SERVERINFOV2;
6132        protocol_version = TLS1_3_VERSION;
6133        extension_context = TLS13CONTEXT;
6134        si = serverinfo_custom_tls13;
6135        si_len = serverinfo_custom_tls13_len;
6136        break;
6137    }
6138
6139    if (!TEST_true(create_ssl_ctx_pair(libctx,
6140                                       TLS_method(),
6141                                       TLS_method(),
6142                                       protocol_version,
6143                                       protocol_version,
6144                                       &sctx, &cctx, cert, privkey)))
6145        goto end;
6146
6147    if (call_use_serverinfo_ex) {
6148        if (!TEST_true(SSL_CTX_use_serverinfo_ex(sctx, serverinfo_version,
6149                                                 si, si_len)))
6150            goto end;
6151    } else {
6152        if (!TEST_true(SSL_CTX_use_serverinfo(sctx, si, si_len)))
6153            goto end;
6154    }
6155
6156    if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TLSEXT_TYPE_signed_certificate_timestamp,
6157                                          extension_context,
6158                                          NULL, NULL, NULL,
6159                                          serverinfo_custom_parse_cb,
6160                                          &cb_result))
6161        || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6162                                         NULL, NULL))
6163        || !TEST_true(create_ssl_connection(serverssl, clientssl,
6164                                            SSL_ERROR_NONE))
6165        || !TEST_int_eq(SSL_do_handshake(clientssl), 1))
6166        goto end;
6167
6168    if (!TEST_true(cb_result))
6169        goto end;
6170
6171    testresult = 1;
6172
6173 end:
6174    SSL_free(serverssl);
6175    SSL_free(clientssl);
6176    SSL_CTX_free(sctx);
6177    SSL_CTX_free(cctx);
6178
6179    return testresult;
6180}
6181#endif
6182
6183/*
6184 * Test that SSL_export_keying_material() produces expected results. There are
6185 * no test vectors so all we do is test that both sides of the communication
6186 * produce the same results for different protocol versions.
6187 */
6188#define SMALL_LABEL_LEN 10
6189#define LONG_LABEL_LEN  249
6190static int test_export_key_mat(int tst)
6191{
6192    int testresult = 0;
6193    SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6194    SSL *clientssl = NULL, *serverssl = NULL;
6195    const char label[LONG_LABEL_LEN + 1] = "test label";
6196    const unsigned char context[] = "context";
6197    const unsigned char *emptycontext = NULL;
6198    unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
6199    unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
6200    size_t labellen;
6201    const int protocols[] = {
6202        TLS1_VERSION,
6203        TLS1_1_VERSION,
6204        TLS1_2_VERSION,
6205        TLS1_3_VERSION,
6206        TLS1_3_VERSION,
6207        TLS1_3_VERSION
6208    };
6209
6210#ifdef OPENSSL_NO_TLS1
6211    if (tst == 0)
6212        return 1;
6213#endif
6214#ifdef OPENSSL_NO_TLS1_1
6215    if (tst == 1)
6216        return 1;
6217#endif
6218    if (is_fips && (tst == 0 || tst == 1))
6219        return 1;
6220#ifdef OPENSSL_NO_TLS1_2
6221    if (tst == 2)
6222        return 1;
6223#endif
6224#ifdef OSSL_NO_USABLE_TLS1_3
6225    if (tst >= 3)
6226        return 1;
6227#endif
6228    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6229                                       TLS_client_method(), TLS1_VERSION, 0,
6230                                       &sctx, &cctx, cert, privkey)))
6231        goto end;
6232
6233    OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
6234    SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
6235    SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
6236    if ((protocols[tst] < TLS1_2_VERSION) &&
6237        (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0")
6238        || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
6239        goto end;
6240
6241    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6242                                      NULL)))
6243        goto end;
6244
6245    /*
6246     * Premature call of SSL_export_keying_material should just fail.
6247     */
6248    if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6249                                                sizeof(ckeymat1), label,
6250                                                SMALL_LABEL_LEN + 1, context,
6251                                                sizeof(context) - 1, 1), 0))
6252        goto end;
6253
6254    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6255                                         SSL_ERROR_NONE)))
6256        goto end;
6257
6258    if (tst == 5) {
6259        /*
6260         * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
6261         * go over that.
6262         */
6263        if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6264                                                    sizeof(ckeymat1), label,
6265                                                    LONG_LABEL_LEN + 1, context,
6266                                                    sizeof(context) - 1, 1), 0))
6267            goto end;
6268
6269        testresult = 1;
6270        goto end;
6271    } else if (tst == 4) {
6272        labellen = LONG_LABEL_LEN;
6273    } else {
6274        labellen = SMALL_LABEL_LEN;
6275    }
6276
6277    if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
6278                                                sizeof(ckeymat1), label,
6279                                                labellen, context,
6280                                                sizeof(context) - 1, 1), 1)
6281            || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
6282                                                       sizeof(ckeymat2), label,
6283                                                       labellen,
6284                                                       emptycontext,
6285                                                       0, 1), 1)
6286            || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
6287                                                       sizeof(ckeymat3), label,
6288                                                       labellen,
6289                                                       NULL, 0, 0), 1)
6290            || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
6291                                                       sizeof(skeymat1), label,
6292                                                       labellen,
6293                                                       context,
6294                                                       sizeof(context) -1, 1),
6295                            1)
6296            || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
6297                                                       sizeof(skeymat2), label,
6298                                                       labellen,
6299                                                       emptycontext,
6300                                                       0, 1), 1)
6301            || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
6302                                                       sizeof(skeymat3), label,
6303                                                       labellen,
6304                                                       NULL, 0, 0), 1)
6305               /*
6306                * Check that both sides created the same key material with the
6307                * same context.
6308                */
6309            || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6310                            sizeof(skeymat1))
6311               /*
6312                * Check that both sides created the same key material with an
6313                * empty context.
6314                */
6315            || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6316                            sizeof(skeymat2))
6317               /*
6318                * Check that both sides created the same key material without a
6319                * context.
6320                */
6321            || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
6322                            sizeof(skeymat3))
6323               /* Different contexts should produce different results */
6324            || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6325                            sizeof(ckeymat2)))
6326        goto end;
6327
6328    /*
6329     * Check that an empty context and no context produce different results in
6330     * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
6331     */
6332    if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
6333                                  sizeof(ckeymat3)))
6334            || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
6335                                         sizeof(ckeymat3))))
6336        goto end;
6337
6338    testresult = 1;
6339
6340 end:
6341    SSL_free(serverssl);
6342    SSL_free(clientssl);
6343    SSL_CTX_free(sctx2);
6344    SSL_CTX_free(sctx);
6345    SSL_CTX_free(cctx);
6346
6347    return testresult;
6348}
6349
6350#ifndef OSSL_NO_USABLE_TLS1_3
6351/*
6352 * Test that SSL_export_keying_material_early() produces expected
6353 * results. There are no test vectors so all we do is test that both
6354 * sides of the communication produce the same results for different
6355 * protocol versions.
6356 */
6357static int test_export_key_mat_early(int idx)
6358{
6359    static const char label[] = "test label";
6360    static const unsigned char context[] = "context";
6361    int testresult = 0;
6362    SSL_CTX *cctx = NULL, *sctx = NULL;
6363    SSL *clientssl = NULL, *serverssl = NULL;
6364    SSL_SESSION *sess = NULL;
6365    const unsigned char *emptycontext = NULL;
6366    unsigned char ckeymat1[80], ckeymat2[80];
6367    unsigned char skeymat1[80], skeymat2[80];
6368    unsigned char buf[1];
6369    size_t readbytes, written;
6370
6371    if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
6372                                        &sess, idx, SHA384_DIGEST_LENGTH)))
6373        goto end;
6374
6375    /* Here writing 0 length early data is enough. */
6376    if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
6377            || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
6378                                                &readbytes),
6379                            SSL_READ_EARLY_DATA_ERROR)
6380            || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6381                            SSL_EARLY_DATA_ACCEPTED))
6382        goto end;
6383
6384    if (!TEST_int_eq(SSL_export_keying_material_early(
6385                     clientssl, ckeymat1, sizeof(ckeymat1), label,
6386                     sizeof(label) - 1, context, sizeof(context) - 1), 1)
6387            || !TEST_int_eq(SSL_export_keying_material_early(
6388                            clientssl, ckeymat2, sizeof(ckeymat2), label,
6389                            sizeof(label) - 1, emptycontext, 0), 1)
6390            || !TEST_int_eq(SSL_export_keying_material_early(
6391                            serverssl, skeymat1, sizeof(skeymat1), label,
6392                            sizeof(label) - 1, context, sizeof(context) - 1), 1)
6393            || !TEST_int_eq(SSL_export_keying_material_early(
6394                            serverssl, skeymat2, sizeof(skeymat2), label,
6395                            sizeof(label) - 1, emptycontext, 0), 1)
6396               /*
6397                * Check that both sides created the same key material with the
6398                * same context.
6399                */
6400            || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6401                            sizeof(skeymat1))
6402               /*
6403                * Check that both sides created the same key material with an
6404                * empty context.
6405                */
6406            || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6407                            sizeof(skeymat2))
6408               /* Different contexts should produce different results */
6409            || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6410                            sizeof(ckeymat2)))
6411        goto end;
6412
6413    testresult = 1;
6414
6415 end:
6416    SSL_SESSION_free(sess);
6417    SSL_SESSION_free(clientpsk);
6418    SSL_SESSION_free(serverpsk);
6419    clientpsk = serverpsk = NULL;
6420    SSL_free(serverssl);
6421    SSL_free(clientssl);
6422    SSL_CTX_free(sctx);
6423    SSL_CTX_free(cctx);
6424
6425    return testresult;
6426}
6427
6428#define NUM_KEY_UPDATE_MESSAGES 40
6429/*
6430 * Test KeyUpdate.
6431 */
6432static int test_key_update(void)
6433{
6434    SSL_CTX *cctx = NULL, *sctx = NULL;
6435    SSL *clientssl = NULL, *serverssl = NULL;
6436    int testresult = 0, i, j;
6437    char buf[20];
6438    static char *mess = "A test message";
6439
6440    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6441                                       TLS_client_method(),
6442                                       TLS1_3_VERSION,
6443                                       0,
6444                                       &sctx, &cctx, cert, privkey))
6445            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6446                                             NULL, NULL))
6447            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6448                                                SSL_ERROR_NONE)))
6449        goto end;
6450
6451    for (j = 0; j < 2; j++) {
6452        /* Send lots of KeyUpdate messages */
6453        for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
6454            if (!TEST_true(SSL_key_update(clientssl,
6455                                          (j == 0)
6456                                          ? SSL_KEY_UPDATE_NOT_REQUESTED
6457                                          : SSL_KEY_UPDATE_REQUESTED))
6458                    || !TEST_true(SSL_do_handshake(clientssl)))
6459                goto end;
6460        }
6461
6462        /* Check that sending and receiving app data is ok */
6463        if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
6464                || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
6465                                         strlen(mess)))
6466            goto end;
6467
6468        if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
6469                || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
6470                                         strlen(mess)))
6471            goto end;
6472    }
6473
6474    testresult = 1;
6475
6476 end:
6477    SSL_free(serverssl);
6478    SSL_free(clientssl);
6479    SSL_CTX_free(sctx);
6480    SSL_CTX_free(cctx);
6481
6482    return testresult;
6483}
6484
6485/*
6486 * Test we can handle a KeyUpdate (update requested) message while
6487 * write data is pending in peer.
6488 * Test 0: Client sends KeyUpdate while Server is writing
6489 * Test 1: Server sends KeyUpdate while Client is writing
6490 */
6491static int test_key_update_peer_in_write(int tst)
6492{
6493    SSL_CTX *cctx = NULL, *sctx = NULL;
6494    SSL *clientssl = NULL, *serverssl = NULL;
6495    int testresult = 0;
6496    char buf[20];
6497    static char *mess = "A test message";
6498    BIO *bretry = BIO_new(bio_s_always_retry());
6499    BIO *tmp = NULL;
6500    SSL *peerupdate = NULL, *peerwrite = NULL;
6501
6502    if (!TEST_ptr(bretry)
6503            || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6504                                              TLS_client_method(),
6505                                              TLS1_3_VERSION,
6506                                              0,
6507                                              &sctx, &cctx, cert, privkey))
6508            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6509                                             NULL, NULL))
6510            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6511                                                SSL_ERROR_NONE)))
6512        goto end;
6513
6514    peerupdate = tst == 0 ? clientssl : serverssl;
6515    peerwrite = tst == 0 ? serverssl : clientssl;
6516
6517    if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
6518            || !TEST_int_eq(SSL_do_handshake(peerupdate), 1))
6519        goto end;
6520
6521    /* Swap the writing endpoint's write BIO to force a retry */
6522    tmp = SSL_get_wbio(peerwrite);
6523    if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6524        tmp = NULL;
6525        goto end;
6526    }
6527    SSL_set0_wbio(peerwrite, bretry);
6528    bretry = NULL;
6529
6530    /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
6531    if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
6532            || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE))
6533        goto end;
6534
6535    /* Reinstate the original writing endpoint's write BIO */
6536    SSL_set0_wbio(peerwrite, tmp);
6537    tmp = NULL;
6538
6539    /* Now read some data - we will read the key update */
6540    if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
6541            || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ))
6542        goto end;
6543
6544    /*
6545     * Complete the write we started previously and read it from the other
6546     * endpoint
6547     */
6548    if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6549            || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6550        goto end;
6551
6552    /* Write more data to ensure we send the KeyUpdate message back */
6553    if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6554            || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6555        goto end;
6556
6557    testresult = 1;
6558
6559 end:
6560    SSL_free(serverssl);
6561    SSL_free(clientssl);
6562    SSL_CTX_free(sctx);
6563    SSL_CTX_free(cctx);
6564    BIO_free(bretry);
6565    BIO_free(tmp);
6566
6567    return testresult;
6568}
6569
6570/*
6571 * Test we can handle a KeyUpdate (update requested) message while
6572 * peer read data is pending after peer accepted keyupdate(the msg header
6573 * had been read 5 bytes).
6574 * Test 0: Client sends KeyUpdate while Server is reading
6575 * Test 1: Server sends KeyUpdate while Client is reading
6576 */
6577static int test_key_update_peer_in_read(int tst)
6578{
6579    SSL_CTX *cctx = NULL, *sctx = NULL;
6580    SSL *clientssl = NULL, *serverssl = NULL;
6581    int testresult = 0;
6582    char prbuf[515], lwbuf[515] = {0};
6583    static char *mess = "A test message";
6584    BIO *lbio = NULL, *pbio = NULL;
6585    SSL *local = NULL, *peer = NULL;
6586
6587    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6588                                              TLS_client_method(),
6589                                              TLS1_3_VERSION,
6590                                              0,
6591                                              &sctx, &cctx, cert, privkey))
6592            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6593                                             NULL, NULL))
6594            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6595                                                SSL_ERROR_NONE)))
6596        goto end;
6597
6598    local = tst == 0 ? clientssl : serverssl;
6599    peer = tst == 0 ? serverssl : clientssl;
6600
6601    if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
6602        goto end;
6603
6604    SSL_set_bio(local, lbio, lbio);
6605    SSL_set_bio(peer, pbio, pbio);
6606
6607    /*
6608     * we first write keyupdate msg then appdata in local
6609     * write data in local will fail with SSL_ERROR_WANT_WRITE,because
6610     * lwbuf app data msg size + key updata msg size > 512(the size of
6611     * the bio pair buffer)
6612     */
6613    if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6614            || !TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), -1)
6615            || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
6616        goto end;
6617
6618    /*
6619     * first read keyupdate msg in peer in peer
6620     * then read appdata that we know will fail with SSL_ERROR_WANT_READ
6621     */
6622    if (!TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), -1)
6623            || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_READ))
6624        goto end;
6625
6626    /* Now write some data in peer - we will write the key update */
6627    if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)))
6628        goto end;
6629
6630    /*
6631     * write data in local previously that we will complete
6632     * read data in peer previously that we will complete
6633     */
6634    if (!TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), sizeof(lwbuf))
6635            || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), sizeof(prbuf)))
6636        goto end;
6637
6638    /* check that sending and receiving appdata ok */
6639    if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
6640            || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
6641        goto end;
6642
6643    testresult = 1;
6644
6645 end:
6646    SSL_free(serverssl);
6647    SSL_free(clientssl);
6648    SSL_CTX_free(sctx);
6649    SSL_CTX_free(cctx);
6650
6651    return testresult;
6652}
6653
6654/*
6655 * Test we can't send a KeyUpdate (update requested) message while
6656 * local write data is pending.
6657 * Test 0: Client sends KeyUpdate while Client is writing
6658 * Test 1: Server sends KeyUpdate while Server is writing
6659 */
6660static int test_key_update_local_in_write(int tst)
6661{
6662    SSL_CTX *cctx = NULL, *sctx = NULL;
6663    SSL *clientssl = NULL, *serverssl = NULL;
6664    int testresult = 0;
6665    char buf[20];
6666    static char *mess = "A test message";
6667    BIO *bretry = BIO_new(bio_s_always_retry());
6668    BIO *tmp = NULL;
6669    SSL *local = NULL, *peer = NULL;
6670
6671    if (!TEST_ptr(bretry)
6672            || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6673                                              TLS_client_method(),
6674                                              TLS1_3_VERSION,
6675                                              0,
6676                                              &sctx, &cctx, cert, privkey))
6677            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6678                                             NULL, NULL))
6679            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6680                                                SSL_ERROR_NONE)))
6681        goto end;
6682
6683    local = tst == 0 ? clientssl : serverssl;
6684    peer = tst == 0 ? serverssl : clientssl;
6685
6686    /* Swap the writing endpoint's write BIO to force a retry */
6687    tmp = SSL_get_wbio(local);
6688    if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6689        tmp = NULL;
6690        goto end;
6691    }
6692    SSL_set0_wbio(local, bretry);
6693    bretry = NULL;
6694
6695    /* write data in local will fail with SSL_ERROR_WANT_WRITE */
6696    if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), -1)
6697            || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
6698        goto end;
6699
6700    /* Reinstate the original writing endpoint's write BIO */
6701    SSL_set0_wbio(local, tmp);
6702    tmp = NULL;
6703
6704    /* SSL_key_update will fail, because writing in local*/
6705    if (!TEST_false(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6706        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_BAD_WRITE_RETRY))
6707    goto end;
6708
6709    ERR_clear_error();
6710    /* write data in local previously that we will complete */
6711    if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)))
6712        goto end;
6713
6714    /* SSL_key_update will succeed because there is no pending write data */
6715    if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6716        || !TEST_int_eq(SSL_do_handshake(local), 1))
6717        goto end;
6718
6719    /*
6720     * we write some appdata in local
6721     * read data in peer - we will read the keyupdate msg
6722     */
6723    if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
6724        || !TEST_int_eq(SSL_read(peer, buf, sizeof(buf)), strlen(mess)))
6725        goto end;
6726
6727    /* Write more peer more data to ensure we send the keyupdate message back */
6728    if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
6729            || !TEST_int_eq(SSL_read(local, buf, sizeof(buf)), strlen(mess)))
6730        goto end;
6731
6732    testresult = 1;
6733
6734 end:
6735    SSL_free(serverssl);
6736    SSL_free(clientssl);
6737    SSL_CTX_free(sctx);
6738    SSL_CTX_free(cctx);
6739    BIO_free(bretry);
6740    BIO_free(tmp);
6741
6742    return testresult;
6743}
6744
6745/*
6746 * Test we can handle a KeyUpdate (update requested) message while
6747 * local read data is pending(the msg header had been read 5 bytes).
6748 * Test 0: Client sends KeyUpdate while Client is reading
6749 * Test 1: Server sends KeyUpdate while Server is reading
6750 */
6751static int test_key_update_local_in_read(int tst)
6752{
6753    SSL_CTX *cctx = NULL, *sctx = NULL;
6754    SSL *clientssl = NULL, *serverssl = NULL;
6755    int testresult = 0;
6756    char lrbuf[515], pwbuf[515] = {0}, prbuf[20];
6757    static char *mess = "A test message";
6758    BIO *lbio = NULL, *pbio = NULL;
6759    SSL *local = NULL, *peer = NULL;
6760
6761    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6762                                              TLS_client_method(),
6763                                              TLS1_3_VERSION,
6764                                              0,
6765                                              &sctx, &cctx, cert, privkey))
6766            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6767                                             NULL, NULL))
6768            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6769                                                SSL_ERROR_NONE)))
6770        goto end;
6771
6772    local = tst == 0 ? clientssl : serverssl;
6773    peer = tst == 0 ? serverssl : clientssl;
6774
6775    if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
6776        goto end;
6777
6778    SSL_set_bio(local, lbio, lbio);
6779    SSL_set_bio(peer, pbio, pbio);
6780
6781    /* write app data in peer will fail with SSL_ERROR_WANT_WRITE */
6782    if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), -1)
6783        || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_WRITE))
6784        goto end;
6785
6786    /* read appdata in local will fail with SSL_ERROR_WANT_READ */
6787    if (!TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), -1)
6788            || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_READ))
6789        goto end;
6790
6791    /* SSL_do_handshake will send keyupdate msg */
6792    if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6793            || !TEST_int_eq(SSL_do_handshake(local), 1))
6794        goto end;
6795
6796    /*
6797     * write data in peer previously that we will complete
6798     * read data in local previously that we will complete
6799     */
6800    if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), sizeof(pwbuf))
6801        || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), sizeof(lrbuf)))
6802        goto end;
6803
6804    /*
6805     * write data in local
6806     * read data in peer - we will read the key update
6807     */
6808    if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
6809        || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
6810        goto end;
6811
6812  /* Write more peer data to ensure we send the keyupdate message back */
6813    if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
6814            || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), strlen(mess)))
6815        goto end;
6816
6817    testresult = 1;
6818
6819 end:
6820    SSL_free(serverssl);
6821    SSL_free(clientssl);
6822    SSL_CTX_free(sctx);
6823    SSL_CTX_free(cctx);
6824
6825    return testresult;
6826}
6827#endif /* OSSL_NO_USABLE_TLS1_3 */
6828
6829static int test_ssl_clear(int idx)
6830{
6831    SSL_CTX *cctx = NULL, *sctx = NULL;
6832    SSL *clientssl = NULL, *serverssl = NULL;
6833    int testresult = 0;
6834
6835#ifdef OPENSSL_NO_TLS1_2
6836    if (idx == 1)
6837        return 1;
6838#endif
6839
6840    /* Create an initial connection */
6841    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6842                                       TLS_client_method(), TLS1_VERSION, 0,
6843                                       &sctx, &cctx, cert, privkey))
6844            || (idx == 1
6845                && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
6846                                                            TLS1_2_VERSION)))
6847            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6848                                          &clientssl, NULL, NULL))
6849            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6850                                                SSL_ERROR_NONE)))
6851        goto end;
6852
6853    SSL_shutdown(clientssl);
6854    SSL_shutdown(serverssl);
6855    SSL_free(serverssl);
6856    serverssl = NULL;
6857
6858    /* Clear clientssl - we're going to reuse the object */
6859    if (!TEST_true(SSL_clear(clientssl)))
6860        goto end;
6861
6862    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6863                                             NULL, NULL))
6864            || !TEST_true(create_ssl_connection(serverssl, clientssl,
6865                                                SSL_ERROR_NONE))
6866            || !TEST_true(SSL_session_reused(clientssl)))
6867        goto end;
6868
6869    SSL_shutdown(clientssl);
6870    SSL_shutdown(serverssl);
6871
6872    testresult = 1;
6873
6874 end:
6875    SSL_free(serverssl);
6876    SSL_free(clientssl);
6877    SSL_CTX_free(sctx);
6878    SSL_CTX_free(cctx);
6879
6880    return testresult;
6881}
6882
6883/* Parse CH and retrieve any MFL extension value if present */
6884static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
6885{
6886    long len;
6887    unsigned char *data;
6888    PACKET pkt, pkt2, pkt3;
6889    unsigned int MFL_code = 0, type = 0;
6890
6891    if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
6892        goto end;
6893
6894    memset(&pkt, 0, sizeof(pkt));
6895    memset(&pkt2, 0, sizeof(pkt2));
6896    memset(&pkt3, 0, sizeof(pkt3));
6897
6898    if (!TEST_long_gt(len, 0)
6899            || !TEST_true( PACKET_buf_init( &pkt, data, len ) )
6900               /* Skip the record header */
6901            || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
6902               /* Skip the handshake message header */
6903            || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
6904               /* Skip client version and random */
6905            || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
6906                                               + SSL3_RANDOM_SIZE))
6907               /* Skip session id */
6908            || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
6909               /* Skip ciphers */
6910            || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
6911               /* Skip compression */
6912            || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
6913               /* Extensions len */
6914            || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
6915        goto end;
6916
6917    /* Loop through all extensions */
6918    while (PACKET_remaining(&pkt2)) {
6919        if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
6920                || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
6921            goto end;
6922
6923        if (type == TLSEXT_TYPE_max_fragment_length) {
6924            if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
6925                    || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
6926                goto end;
6927
6928            *mfl_codemfl_code = MFL_code;
6929            return 1;
6930        }
6931    }
6932
6933 end:
6934    return 0;
6935}
6936
6937/* Maximum-Fragment-Length TLS extension mode to test */
6938static const unsigned char max_fragment_len_test[] = {
6939    TLSEXT_max_fragment_length_512,
6940    TLSEXT_max_fragment_length_1024,
6941    TLSEXT_max_fragment_length_2048,
6942    TLSEXT_max_fragment_length_4096
6943};
6944
6945static int test_max_fragment_len_ext(int idx_tst)
6946{
6947    SSL_CTX *ctx = NULL;
6948    SSL *con = NULL;
6949    int testresult = 0, MFL_mode = 0;
6950    BIO *rbio, *wbio;
6951
6952    if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(),
6953                                       TLS1_VERSION, 0, NULL, &ctx, NULL,
6954                                       NULL)))
6955        return 0;
6956
6957    if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
6958                   ctx, max_fragment_len_test[idx_tst])))
6959        goto end;
6960
6961    con = SSL_new(ctx);
6962    if (!TEST_ptr(con))
6963        goto end;
6964
6965    rbio = BIO_new(BIO_s_mem());
6966    wbio = BIO_new(BIO_s_mem());
6967    if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
6968        BIO_free(rbio);
6969        BIO_free(wbio);
6970        goto end;
6971    }
6972
6973    SSL_set_bio(con, rbio, wbio);
6974
6975    if (!TEST_int_le(SSL_connect(con), 0)) {
6976        /* This shouldn't succeed because we don't have a server! */
6977        goto end;
6978    }
6979
6980    if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
6981        /* no MFL in client hello */
6982        goto end;
6983    if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
6984        goto end;
6985
6986    testresult = 1;
6987
6988end:
6989    SSL_free(con);
6990    SSL_CTX_free(ctx);
6991
6992    return testresult;
6993}
6994
6995#ifndef OSSL_NO_USABLE_TLS1_3
6996static int test_pha_key_update(void)
6997{
6998    SSL_CTX *cctx = NULL, *sctx = NULL;
6999    SSL *clientssl = NULL, *serverssl = NULL;
7000    int testresult = 0;
7001
7002    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7003                                       TLS_client_method(), TLS1_VERSION, 0,
7004                                       &sctx, &cctx, cert, privkey)))
7005        return 0;
7006
7007    if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
7008        || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
7009        || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
7010        || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
7011        goto end;
7012
7013    SSL_CTX_set_post_handshake_auth(cctx, 1);
7014
7015    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7016                                      NULL, NULL)))
7017        goto end;
7018
7019    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7020                                         SSL_ERROR_NONE)))
7021        goto end;
7022
7023    SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
7024    if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
7025        goto end;
7026
7027    if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
7028        goto end;
7029
7030    /* Start handshake on the server */
7031    if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
7032        goto end;
7033
7034    /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
7035    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7036                                         SSL_ERROR_NONE)))
7037        goto end;
7038
7039    SSL_shutdown(clientssl);
7040    SSL_shutdown(serverssl);
7041
7042    testresult = 1;
7043
7044 end:
7045    SSL_free(serverssl);
7046    SSL_free(clientssl);
7047    SSL_CTX_free(sctx);
7048    SSL_CTX_free(cctx);
7049    return testresult;
7050}
7051#endif
7052
7053#if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7054
7055static SRP_VBASE *vbase = NULL;
7056
7057static int ssl_srp_cb(SSL *s, int *ad, void *arg)
7058{
7059    int ret = SSL3_AL_FATAL;
7060    char *username;
7061    SRP_user_pwd *user = NULL;
7062
7063    username = SSL_get_srp_username(s);
7064    if (username == NULL) {
7065        *ad = SSL_AD_INTERNAL_ERROR;
7066        goto err;
7067    }
7068
7069    user = SRP_VBASE_get1_by_user(vbase, username);
7070    if (user == NULL) {
7071        *ad = SSL_AD_INTERNAL_ERROR;
7072        goto err;
7073    }
7074
7075    if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
7076                                 user->info) <= 0) {
7077        *ad = SSL_AD_INTERNAL_ERROR;
7078        goto err;
7079    }
7080
7081    ret = 0;
7082
7083 err:
7084    SRP_user_pwd_free(user);
7085    return ret;
7086}
7087
7088static int create_new_vfile(char *userid, char *password, const char *filename)
7089{
7090    char *gNid = NULL;
7091    OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
7092    TXT_DB *db = NULL;
7093    int ret = 0;
7094    BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
7095    size_t i;
7096
7097    if (!TEST_ptr(dummy) || !TEST_ptr(row))
7098        goto end;
7099
7100    gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
7101                                  &row[DB_srpverifier], NULL, NULL, libctx, NULL);
7102    if (!TEST_ptr(gNid))
7103        goto end;
7104
7105    /*
7106     * The only way to create an empty TXT_DB is to provide a BIO with no data
7107     * in it!
7108     */
7109    db = TXT_DB_read(dummy, DB_NUMBER);
7110    if (!TEST_ptr(db))
7111        goto end;
7112
7113    out = BIO_new_file(filename, "w");
7114    if (!TEST_ptr(out))
7115        goto end;
7116
7117    row[DB_srpid] = OPENSSL_strdup(userid);
7118    row[DB_srptype] = OPENSSL_strdup("V");
7119    row[DB_srpgN] = OPENSSL_strdup(gNid);
7120
7121    if (!TEST_ptr(row[DB_srpid])
7122            || !TEST_ptr(row[DB_srptype])
7123            || !TEST_ptr(row[DB_srpgN])
7124            || !TEST_true(TXT_DB_insert(db, row)))
7125        goto end;
7126
7127    row = NULL;
7128
7129    if (TXT_DB_write(out, db) <= 0)
7130        goto end;
7131
7132    ret = 1;
7133 end:
7134    if (row != NULL) {
7135        for (i = 0; i < DB_NUMBER; i++)
7136            OPENSSL_free(row[i]);
7137    }
7138    OPENSSL_free(row);
7139    BIO_free(dummy);
7140    BIO_free(out);
7141    TXT_DB_free(db);
7142
7143    return ret;
7144}
7145
7146static int create_new_vbase(char *userid, char *password)
7147{
7148    BIGNUM *verifier = NULL, *salt = NULL;
7149    const SRP_gN *lgN = NULL;
7150    SRP_user_pwd *user_pwd = NULL;
7151    int ret = 0;
7152
7153    lgN = SRP_get_default_gN(NULL);
7154    if (!TEST_ptr(lgN))
7155        goto end;
7156
7157    if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
7158                                             lgN->N, lgN->g, libctx, NULL)))
7159        goto end;
7160
7161    user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
7162    if (!TEST_ptr(user_pwd))
7163        goto end;
7164
7165    user_pwd->N = lgN->N;
7166    user_pwd->g = lgN->g;
7167    user_pwd->id = OPENSSL_strdup(userid);
7168    if (!TEST_ptr(user_pwd->id))
7169        goto end;
7170
7171    user_pwd->v = verifier;
7172    user_pwd->s = salt;
7173    verifier = salt = NULL;
7174
7175    if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
7176        goto end;
7177    user_pwd = NULL;
7178
7179    ret = 1;
7180end:
7181    SRP_user_pwd_free(user_pwd);
7182    BN_free(salt);
7183    BN_free(verifier);
7184
7185    return ret;
7186}
7187
7188/*
7189 * SRP tests
7190 *
7191 * Test 0: Simple successful SRP connection, new vbase
7192 * Test 1: Connection failure due to bad password, new vbase
7193 * Test 2: Simple successful SRP connection, vbase loaded from existing file
7194 * Test 3: Connection failure due to bad password, vbase loaded from existing
7195 *         file
7196 * Test 4: Simple successful SRP connection, vbase loaded from new file
7197 * Test 5: Connection failure due to bad password, vbase loaded from new file
7198 */
7199static int test_srp(int tst)
7200{
7201    char *userid = "test", *password = "password", *tstsrpfile;
7202    SSL_CTX *cctx = NULL, *sctx = NULL;
7203    SSL *clientssl = NULL, *serverssl = NULL;
7204    int ret, testresult = 0;
7205
7206    vbase = SRP_VBASE_new(NULL);
7207    if (!TEST_ptr(vbase))
7208        goto end;
7209
7210    if (tst == 0 || tst == 1) {
7211        if (!TEST_true(create_new_vbase(userid, password)))
7212            goto end;
7213    } else {
7214        if (tst == 4 || tst == 5) {
7215            if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
7216                goto end;
7217            tstsrpfile = tmpfilename;
7218        } else {
7219            tstsrpfile = srpvfile;
7220        }
7221        if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
7222            goto end;
7223    }
7224
7225    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7226                                       TLS_client_method(), TLS1_VERSION, 0,
7227                                       &sctx, &cctx, cert, privkey)))
7228        goto end;
7229
7230    if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
7231            || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
7232            || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
7233            || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
7234            || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
7235        goto end;
7236
7237    if (tst % 2 == 1) {
7238        if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
7239            goto end;
7240    } else {
7241        if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
7242            goto end;
7243    }
7244
7245    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7246                                      NULL, NULL)))
7247        goto end;
7248
7249    ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
7250    if (ret) {
7251        if (!TEST_true(tst % 2 == 0))
7252            goto end;
7253    } else {
7254        if (!TEST_true(tst % 2 == 1))
7255            goto end;
7256    }
7257
7258    testresult = 1;
7259
7260 end:
7261    SRP_VBASE_free(vbase);
7262    vbase = NULL;
7263    SSL_free(serverssl);
7264    SSL_free(clientssl);
7265    SSL_CTX_free(sctx);
7266    SSL_CTX_free(cctx);
7267
7268    return testresult;
7269}
7270#endif
7271
7272static int info_cb_failed = 0;
7273static int info_cb_offset = 0;
7274static int info_cb_this_state = -1;
7275
7276static struct info_cb_states_st {
7277    int where;
7278    const char *statestr;
7279} info_cb_states[][60] = {
7280    {
7281        /* TLSv1.2 server followed by resumption */
7282        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7283        {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7284        {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
7285        {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
7286        {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
7287        {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7288        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7289        {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7290        {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"},
7291        {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7292        {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
7293        {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7294        {SSL_CB_EXIT, NULL}, {0, NULL},
7295    }, {
7296        /* TLSv1.2 client followed by resumption */
7297        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7298        {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7299        {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
7300        {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
7301        {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
7302        {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7303        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7304        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7305        {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7306        {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7307        {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
7308        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
7309    }, {
7310        /* TLSv1.3 server followed by resumption */
7311        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7312        {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7313        {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
7314        {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
7315        {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
7316        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7317        {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7318        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7319        {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7320        {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7321        {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
7322        {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7323        {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7324    }, {
7325        /* TLSv1.3 client followed by resumption */
7326        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7327        {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7328        {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
7329        {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
7330        {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
7331        {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7332        {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"},
7333        {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
7334        {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7335        {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
7336        {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
7337        {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7338        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7339        {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"},
7340        {SSL_CB_EXIT, NULL}, {0, NULL},
7341    }, {
7342        /* TLSv1.3 server, early_data */
7343        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7344        {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7345        {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7346        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7347        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7348        {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
7349        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7350        {SSL_CB_EXIT, NULL}, {0, NULL},
7351    }, {
7352        /* TLSv1.3 client, early_data */
7353        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7354        {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
7355        {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7356        {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7357        {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
7358        {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
7359        {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7360        {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7361        {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7362    }, {
7363        {0, NULL},
7364    }
7365};
7366
7367static void sslapi_info_callback(const SSL *s, int where, int ret)
7368{
7369    struct info_cb_states_st *state = info_cb_states[info_cb_offset];
7370
7371    /* We do not ever expect a connection to fail in this test */
7372    if (!TEST_false(ret == 0)) {
7373        info_cb_failed = 1;
7374        return;
7375    }
7376
7377    /*
7378     * Do some sanity checks. We never expect these things to happen in this
7379     * test
7380     */
7381    if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
7382            || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
7383            || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
7384        info_cb_failed = 1;
7385        return;
7386    }
7387
7388    /* Now check we're in the right state */
7389    if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
7390        info_cb_failed = 1;
7391        return;
7392    }
7393    if ((where & SSL_CB_LOOP) != 0
7394            && !TEST_int_eq(strcmp(SSL_state_string(s),
7395                            state[info_cb_this_state].statestr), 0)) {
7396        info_cb_failed = 1;
7397        return;
7398    }
7399
7400    /*
7401     * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
7402     */
7403    if ((where & SSL_CB_HANDSHAKE_DONE)
7404            && SSL_in_init((SSL *)s) != 0) {
7405        info_cb_failed = 1;
7406        return;
7407    }
7408}
7409
7410/*
7411 * Test the info callback gets called when we expect it to.
7412 *
7413 * Test 0: TLSv1.2, server
7414 * Test 1: TLSv1.2, client
7415 * Test 2: TLSv1.3, server
7416 * Test 3: TLSv1.3, client
7417 * Test 4: TLSv1.3, server, early_data
7418 * Test 5: TLSv1.3, client, early_data
7419 */
7420static int test_info_callback(int tst)
7421{
7422    SSL_CTX *cctx = NULL, *sctx = NULL;
7423    SSL *clientssl = NULL, *serverssl = NULL;
7424    SSL_SESSION *clntsess = NULL;
7425    int testresult = 0;
7426    int tlsvers;
7427
7428    if (tst < 2) {
7429/* We need either ECDHE or DHE for the TLSv1.2 test to work */
7430#if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
7431                                    || !defined(OPENSSL_NO_DH))
7432        tlsvers = TLS1_2_VERSION;
7433#else
7434        return 1;
7435#endif
7436    } else {
7437#ifndef OSSL_NO_USABLE_TLS1_3
7438        tlsvers = TLS1_3_VERSION;
7439#else
7440        return 1;
7441#endif
7442    }
7443
7444    /* Reset globals */
7445    info_cb_failed = 0;
7446    info_cb_this_state = -1;
7447    info_cb_offset = tst;
7448
7449#ifndef OSSL_NO_USABLE_TLS1_3
7450    if (tst >= 4) {
7451        SSL_SESSION *sess = NULL;
7452        size_t written, readbytes;
7453        unsigned char buf[80];
7454
7455        /* early_data tests */
7456        if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
7457                                            &serverssl, &sess, 0,
7458                                            SHA384_DIGEST_LENGTH)))
7459            goto end;
7460
7461        /* We don't actually need this reference */
7462        SSL_SESSION_free(sess);
7463
7464        SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
7465                              sslapi_info_callback);
7466
7467        /* Write and read some early data and then complete the connection */
7468        if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
7469                                            &written))
7470                || !TEST_size_t_eq(written, strlen(MSG1))
7471                || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
7472                                                    sizeof(buf), &readbytes),
7473                                SSL_READ_EARLY_DATA_SUCCESS)
7474                || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
7475                || !TEST_int_eq(SSL_get_early_data_status(serverssl),
7476                                SSL_EARLY_DATA_ACCEPTED)
7477                || !TEST_true(create_ssl_connection(serverssl, clientssl,
7478                                                    SSL_ERROR_NONE))
7479                || !TEST_false(info_cb_failed))
7480            goto end;
7481
7482        testresult = 1;
7483        goto end;
7484    }
7485#endif
7486
7487    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7488                                       TLS_client_method(),
7489                                       tlsvers, tlsvers, &sctx, &cctx, cert,
7490                                       privkey)))
7491        goto end;
7492
7493    if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
7494        goto end;
7495
7496    /*
7497     * For even numbered tests we check the server callbacks. For odd numbers we
7498     * check the client.
7499     */
7500    SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
7501                              sslapi_info_callback);
7502
7503    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
7504                                          &clientssl, NULL, NULL))
7505        || !TEST_true(create_ssl_connection(serverssl, clientssl,
7506                                            SSL_ERROR_NONE))
7507        || !TEST_false(info_cb_failed))
7508    goto end;
7509
7510
7511
7512    clntsess = SSL_get1_session(clientssl);
7513    SSL_shutdown(clientssl);
7514    SSL_shutdown(serverssl);
7515    SSL_free(serverssl);
7516    SSL_free(clientssl);
7517    serverssl = clientssl = NULL;
7518
7519    /* Now do a resumption */
7520    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
7521                                      NULL))
7522            || !TEST_true(SSL_set_session(clientssl, clntsess))
7523            || !TEST_true(create_ssl_connection(serverssl, clientssl,
7524                                                SSL_ERROR_NONE))
7525            || !TEST_true(SSL_session_reused(clientssl))
7526            || !TEST_false(info_cb_failed))
7527        goto end;
7528
7529    testresult = 1;
7530
7531 end:
7532    SSL_free(serverssl);
7533    SSL_free(clientssl);
7534    SSL_SESSION_free(clntsess);
7535    SSL_CTX_free(sctx);
7536    SSL_CTX_free(cctx);
7537    return testresult;
7538}
7539
7540static int test_ssl_pending(int tst)
7541{
7542    SSL_CTX *cctx = NULL, *sctx = NULL;
7543    SSL *clientssl = NULL, *serverssl = NULL;
7544    int testresult = 0;
7545    char msg[] = "A test message";
7546    char buf[5];
7547    size_t written, readbytes;
7548
7549    if (tst == 0) {
7550        if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7551                                           TLS_client_method(),
7552                                           TLS1_VERSION, 0,
7553                                           &sctx, &cctx, cert, privkey)))
7554            goto end;
7555    } else {
7556#ifndef OPENSSL_NO_DTLS
7557        if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
7558                                           DTLS_client_method(),
7559                                           DTLS1_VERSION, 0,
7560                                           &sctx, &cctx, cert, privkey)))
7561            goto end;
7562
7563# ifdef OPENSSL_NO_DTLS1_2
7564        /* Not supported in the FIPS provider */
7565        if (is_fips) {
7566            testresult = 1;
7567            goto end;
7568        };
7569        /*
7570         * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
7571         * level 0
7572         */
7573        if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
7574                || !TEST_true(SSL_CTX_set_cipher_list(cctx,
7575                                                    "DEFAULT:@SECLEVEL=0")))
7576            goto end;
7577# endif
7578#else
7579        return 1;
7580#endif
7581    }
7582
7583    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7584                                             NULL, NULL))
7585            || !TEST_true(create_ssl_connection(serverssl, clientssl,
7586                                                SSL_ERROR_NONE)))
7587        goto end;
7588
7589    if (!TEST_int_eq(SSL_pending(clientssl), 0)
7590            || !TEST_false(SSL_has_pending(clientssl))
7591            || !TEST_int_eq(SSL_pending(serverssl), 0)
7592            || !TEST_false(SSL_has_pending(serverssl))
7593            || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
7594            || !TEST_size_t_eq(written, sizeof(msg))
7595            || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
7596            || !TEST_size_t_eq(readbytes, sizeof(buf))
7597            || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
7598            || !TEST_true(SSL_has_pending(clientssl)))
7599        goto end;
7600
7601    testresult = 1;
7602
7603 end:
7604    SSL_free(serverssl);
7605    SSL_free(clientssl);
7606    SSL_CTX_free(sctx);
7607    SSL_CTX_free(cctx);
7608
7609    return testresult;
7610}
7611
7612static struct {
7613    unsigned int maxprot;
7614    const char *clntciphers;
7615    const char *clnttls13ciphers;
7616    const char *srvrciphers;
7617    const char *srvrtls13ciphers;
7618    const char *shared;
7619    const char *fipsshared;
7620} shared_ciphers_data[] = {
7621/*
7622 * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
7623 * TLSv1.3 is enabled but TLSv1.2 is disabled.
7624 */
7625#if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
7626    {
7627        TLS1_2_VERSION,
7628        "AES128-SHA:AES256-SHA",
7629        NULL,
7630        "AES256-SHA:DHE-RSA-AES128-SHA",
7631        NULL,
7632        "AES256-SHA",
7633        "AES256-SHA"
7634    },
7635# if !defined(OPENSSL_NO_CHACHA) \
7636     && !defined(OPENSSL_NO_POLY1305) \
7637     && !defined(OPENSSL_NO_EC)
7638    {
7639        TLS1_2_VERSION,
7640        "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
7641        NULL,
7642        "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
7643        NULL,
7644        "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
7645        "AES128-SHA"
7646    },
7647# endif
7648    {
7649        TLS1_2_VERSION,
7650        "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
7651        NULL,
7652        "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
7653        NULL,
7654        "AES128-SHA:AES256-SHA",
7655        "AES128-SHA:AES256-SHA"
7656    },
7657    {
7658        TLS1_2_VERSION,
7659        "AES128-SHA:AES256-SHA",
7660        NULL,
7661        "AES128-SHA:DHE-RSA-AES128-SHA",
7662        NULL,
7663        "AES128-SHA",
7664        "AES128-SHA"
7665    },
7666#endif
7667/*
7668 * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
7669 * enabled.
7670 */
7671#if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
7672    && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
7673    {
7674        TLS1_3_VERSION,
7675        "AES128-SHA:AES256-SHA",
7676        NULL,
7677        "AES256-SHA:AES128-SHA256",
7678        NULL,
7679        "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
7680        "TLS_AES_128_GCM_SHA256:AES256-SHA",
7681        "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA"
7682    },
7683#endif
7684#ifndef OSSL_NO_USABLE_TLS1_3
7685    {
7686        TLS1_3_VERSION,
7687        "AES128-SHA",
7688        "TLS_AES_256_GCM_SHA384",
7689        "AES256-SHA",
7690        "TLS_AES_256_GCM_SHA384",
7691        "TLS_AES_256_GCM_SHA384",
7692        "TLS_AES_256_GCM_SHA384"
7693    },
7694#endif
7695};
7696
7697static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
7698{
7699    SSL_CTX *cctx = NULL, *sctx = NULL;
7700    SSL *clientssl = NULL, *serverssl = NULL;
7701    int testresult = 0;
7702    char buf[1024];
7703    OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
7704
7705    if (!TEST_ptr(tmplibctx))
7706        goto end;
7707
7708    /*
7709     * Regardless of whether we're testing with the FIPS provider loaded into
7710     * libctx, we want one peer to always use the full set of ciphersuites
7711     * available. Therefore we use a separate libctx with the default provider
7712     * loaded into it. We run the same tests twice - once with the client side
7713     * having the full set of ciphersuites and once with the server side.
7714     */
7715    if (clnt) {
7716        cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
7717        if (!TEST_ptr(cctx))
7718            goto end;
7719    } else {
7720        sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
7721        if (!TEST_ptr(sctx))
7722            goto end;
7723    }
7724
7725    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7726                                       TLS_client_method(),
7727                                       TLS1_VERSION,
7728                                       shared_ciphers_data[tst].maxprot,
7729                                       &sctx, &cctx, cert, privkey)))
7730        goto end;
7731
7732    if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
7733                                        shared_ciphers_data[tst].clntciphers))
7734            || (shared_ciphers_data[tst].clnttls13ciphers != NULL
7735                && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
7736                                    shared_ciphers_data[tst].clnttls13ciphers)))
7737            || !TEST_true(SSL_CTX_set_cipher_list(sctx,
7738                                        shared_ciphers_data[tst].srvrciphers))
7739            || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
7740                && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
7741                                    shared_ciphers_data[tst].srvrtls13ciphers))))
7742        goto end;
7743
7744
7745    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7746                                             NULL, NULL))
7747            || !TEST_true(create_ssl_connection(serverssl, clientssl,
7748                                                SSL_ERROR_NONE)))
7749        goto end;
7750
7751    if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
7752            || !TEST_int_eq(strcmp(buf,
7753                                   is_fips
7754                                   ? shared_ciphers_data[tst].fipsshared
7755                                   : shared_ciphers_data[tst].shared),
7756                                   0)) {
7757        TEST_info("Shared ciphers are: %s\n", buf);
7758        goto end;
7759    }
7760
7761    testresult = 1;
7762
7763 end:
7764    SSL_free(serverssl);
7765    SSL_free(clientssl);
7766    SSL_CTX_free(sctx);
7767    SSL_CTX_free(cctx);
7768    OSSL_LIB_CTX_free(tmplibctx);
7769
7770    return testresult;
7771}
7772
7773static int test_ssl_get_shared_ciphers(int tst)
7774{
7775    return int_test_ssl_get_shared_ciphers(tst, 0)
7776           && int_test_ssl_get_shared_ciphers(tst, 1);
7777}
7778
7779
7780static const char *appdata = "Hello World";
7781static int gen_tick_called, dec_tick_called, tick_key_cb_called;
7782static int tick_key_renew = 0;
7783static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
7784
7785static int gen_tick_cb(SSL *s, void *arg)
7786{
7787    gen_tick_called = 1;
7788
7789    return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
7790                                           strlen(appdata));
7791}
7792
7793static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
7794                                     const unsigned char *keyname,
7795                                     size_t keyname_length,
7796                                     SSL_TICKET_STATUS status,
7797                                     void *arg)
7798{
7799    void *tickdata;
7800    size_t tickdlen;
7801
7802    dec_tick_called = 1;
7803
7804    if (status == SSL_TICKET_EMPTY)
7805        return SSL_TICKET_RETURN_IGNORE_RENEW;
7806
7807    if (!TEST_true(status == SSL_TICKET_SUCCESS
7808                   || status == SSL_TICKET_SUCCESS_RENEW))
7809        return SSL_TICKET_RETURN_ABORT;
7810
7811    if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
7812                                                   &tickdlen))
7813            || !TEST_size_t_eq(tickdlen, strlen(appdata))
7814            || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
7815        return SSL_TICKET_RETURN_ABORT;
7816
7817    if (tick_key_cb_called)  {
7818        /* Don't change what the ticket key callback wanted to do */
7819        switch (status) {
7820        case SSL_TICKET_NO_DECRYPT:
7821            return SSL_TICKET_RETURN_IGNORE_RENEW;
7822
7823        case SSL_TICKET_SUCCESS:
7824            return SSL_TICKET_RETURN_USE;
7825
7826        case SSL_TICKET_SUCCESS_RENEW:
7827            return SSL_TICKET_RETURN_USE_RENEW;
7828
7829        default:
7830            return SSL_TICKET_RETURN_ABORT;
7831        }
7832    }
7833    return tick_dec_ret;
7834
7835}
7836
7837#ifndef OPENSSL_NO_DEPRECATED_3_0
7838static int tick_key_cb(SSL *s, unsigned char key_name[16],
7839                       unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
7840                       HMAC_CTX *hctx, int enc)
7841{
7842    const unsigned char tick_aes_key[16] = "0123456789abcdef";
7843    const unsigned char tick_hmac_key[16] = "0123456789abcdef";
7844    EVP_CIPHER *aes128cbc;
7845    EVP_MD *sha256;
7846    int ret;
7847
7848    tick_key_cb_called = 1;
7849
7850    if (tick_key_renew == -1)
7851        return 0;
7852
7853    aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
7854    if (!TEST_ptr(aes128cbc))
7855        return 0;
7856    sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
7857    if (!TEST_ptr(sha256)) {
7858        EVP_CIPHER_free(aes128cbc);
7859        return 0;
7860    }
7861
7862    memset(iv, 0, AES_BLOCK_SIZE);
7863    memset(key_name, 0, 16);
7864    if (aes128cbc == NULL
7865            || sha256 == NULL
7866            || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
7867            || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
7868                             NULL))
7869        ret = -1;
7870    else
7871        ret = tick_key_renew ? 2 : 1;
7872
7873    EVP_CIPHER_free(aes128cbc);
7874    EVP_MD_free(sha256);
7875
7876    return ret;
7877}
7878#endif
7879
7880static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
7881                           unsigned char iv[EVP_MAX_IV_LENGTH],
7882                           EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
7883{
7884    const unsigned char tick_aes_key[16] = "0123456789abcdef";
7885    unsigned char tick_hmac_key[16] = "0123456789abcdef";
7886    OSSL_PARAM params[2];
7887    EVP_CIPHER *aes128cbc;
7888    int ret;
7889
7890    tick_key_cb_called = 1;
7891
7892    if (tick_key_renew == -1)
7893        return 0;
7894
7895    aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
7896    if (!TEST_ptr(aes128cbc))
7897        return 0;
7898
7899    memset(iv, 0, AES_BLOCK_SIZE);
7900    memset(key_name, 0, 16);
7901    params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
7902                                                 "SHA256", 0);
7903    params[1] = OSSL_PARAM_construct_end();
7904    if (aes128cbc == NULL
7905            || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
7906            || !EVP_MAC_init(hctx, tick_hmac_key, sizeof(tick_hmac_key),
7907                             params))
7908        ret = -1;
7909    else
7910        ret = tick_key_renew ? 2 : 1;
7911
7912    EVP_CIPHER_free(aes128cbc);
7913
7914    return ret;
7915}
7916
7917/*
7918 * Test the various ticket callbacks
7919 * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
7920 * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
7921 * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
7922 * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
7923 * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
7924 * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
7925 * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
7926 * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
7927 * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
7928 * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
7929 * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
7930 * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
7931 * Test 12: TLSv1.2, old ticket key callback, no ticket
7932 * Test 13: TLSv1.3, old ticket key callback, no ticket
7933 * Test 14: TLSv1.2, ticket key callback, ticket, no renewal
7934 * Test 15: TLSv1.3, ticket key callback, ticket, no renewal
7935 * Test 16: TLSv1.2, ticket key callback, ticket, renewal
7936 * Test 17: TLSv1.3, ticket key callback, ticket, renewal
7937 * Test 18: TLSv1.2, ticket key callback, no ticket
7938 * Test 19: TLSv1.3, ticket key callback, no ticket
7939 */
7940static int test_ticket_callbacks(int tst)
7941{
7942    SSL_CTX *cctx = NULL, *sctx = NULL;
7943    SSL *clientssl = NULL, *serverssl = NULL;
7944    SSL_SESSION *clntsess = NULL;
7945    int testresult = 0;
7946
7947#ifdef OPENSSL_NO_TLS1_2
7948    if (tst % 2 == 0)
7949        return 1;
7950#endif
7951#ifdef OSSL_NO_USABLE_TLS1_3
7952    if (tst % 2 == 1)
7953        return 1;
7954#endif
7955#ifdef OPENSSL_NO_DEPRECATED_3_0
7956    if (tst >= 8 && tst <= 13)
7957        return 1;
7958#endif
7959
7960    gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
7961
7962    /* Which tests the ticket key callback should request renewal for */
7963
7964    if (tst == 10 || tst == 11 || tst == 16 || tst == 17)
7965        tick_key_renew = 1;
7966    else if (tst == 12 || tst == 13 || tst == 18 || tst == 19)
7967        tick_key_renew = -1; /* abort sending the ticket/0-length ticket */
7968    else
7969        tick_key_renew = 0;
7970
7971    /* Which tests the decrypt ticket callback should request renewal for */
7972    switch (tst) {
7973    case 0:
7974    case 1:
7975        tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
7976        break;
7977
7978    case 2:
7979    case 3:
7980        tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
7981        break;
7982
7983    case 4:
7984    case 5:
7985        tick_dec_ret = SSL_TICKET_RETURN_USE;
7986        break;
7987
7988    case 6:
7989    case 7:
7990        tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
7991        break;
7992
7993    default:
7994        tick_dec_ret = SSL_TICKET_RETURN_ABORT;
7995    }
7996
7997    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7998                                       TLS_client_method(),
7999                                       TLS1_VERSION,
8000                                       ((tst % 2) == 0) ? TLS1_2_VERSION
8001                                                        : TLS1_3_VERSION,
8002                                       &sctx, &cctx, cert, privkey)))
8003        goto end;
8004
8005    /*
8006     * We only want sessions to resume from tickets - not the session cache. So
8007     * switch the cache off.
8008     */
8009    if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
8010        goto end;
8011
8012    if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
8013                                                 NULL)))
8014        goto end;
8015
8016    if (tst >= 14) {
8017        if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
8018            goto end;
8019#ifndef OPENSSL_NO_DEPRECATED_3_0
8020    } else if (tst >= 8) {
8021        if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
8022            goto end;
8023#endif
8024    }
8025
8026    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8027                                             NULL, NULL))
8028            || !TEST_true(create_ssl_connection(serverssl, clientssl,
8029                                                SSL_ERROR_NONE)))
8030        goto end;
8031
8032    /*
8033     * The decrypt ticket key callback in TLSv1.2 should be called even though
8034     * we have no ticket yet, because it gets called with a status of
8035     * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
8036     * actually send any ticket data). This does not happen in TLSv1.3 because
8037     * it is not valid to send empty ticket data in TLSv1.3.
8038     */
8039    if (!TEST_int_eq(gen_tick_called, 1)
8040            || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
8041        goto end;
8042
8043    gen_tick_called = dec_tick_called = 0;
8044
8045    clntsess = SSL_get1_session(clientssl);
8046    SSL_shutdown(clientssl);
8047    SSL_shutdown(serverssl);
8048    SSL_free(serverssl);
8049    SSL_free(clientssl);
8050    serverssl = clientssl = NULL;
8051
8052    /* Now do a resumption */
8053    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8054                                      NULL))
8055            || !TEST_true(SSL_set_session(clientssl, clntsess))
8056            || !TEST_true(create_ssl_connection(serverssl, clientssl,
8057                                                SSL_ERROR_NONE)))
8058        goto end;
8059
8060    if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
8061            || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8062            || tick_key_renew == -1) {
8063        if (!TEST_false(SSL_session_reused(clientssl)))
8064            goto end;
8065    } else {
8066        if (!TEST_true(SSL_session_reused(clientssl)))
8067            goto end;
8068    }
8069
8070    if (!TEST_int_eq(gen_tick_called,
8071                     (tick_key_renew
8072                      || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8073                      || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
8074                     ? 1 : 0)
8075               /* There is no ticket to decrypt in tests 13 and 19 */
8076            || !TEST_int_eq(dec_tick_called, (tst == 13 || tst == 19) ? 0 : 1))
8077        goto end;
8078
8079    testresult = 1;
8080
8081 end:
8082    SSL_SESSION_free(clntsess);
8083    SSL_free(serverssl);
8084    SSL_free(clientssl);
8085    SSL_CTX_free(sctx);
8086    SSL_CTX_free(cctx);
8087
8088    return testresult;
8089}
8090
8091/*
8092 * Test incorrect shutdown.
8093 * Test 0: client does not shutdown properly,
8094 *         server does not set SSL_OP_IGNORE_UNEXPECTED_EOF,
8095 *         server should get SSL_ERROR_SSL
8096 * Test 1: client does not shutdown properly,
8097 *         server sets SSL_OP_IGNORE_UNEXPECTED_EOF,
8098 *         server should get SSL_ERROR_ZERO_RETURN
8099 */
8100static int test_incorrect_shutdown(int tst)
8101{
8102    SSL_CTX *cctx = NULL, *sctx = NULL;
8103    SSL *clientssl = NULL, *serverssl = NULL;
8104    int testresult = 0;
8105    char buf[80];
8106    BIO *c2s;
8107
8108    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8109                                       TLS_client_method(), 0, 0,
8110                                       &sctx, &cctx, cert, privkey)))
8111        goto end;
8112
8113    if (tst == 1)
8114        SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
8115
8116    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8117                                            NULL, NULL)))
8118        goto end;
8119
8120    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8121                                              SSL_ERROR_NONE)))
8122        goto end;
8123
8124    c2s = SSL_get_rbio(serverssl);
8125    BIO_set_mem_eof_return(c2s, 0);
8126
8127    if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf))))
8128        goto end;
8129
8130    if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL) )
8131        goto end;
8132    if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN) )
8133        goto end;
8134
8135    testresult = 1;
8136
8137 end:
8138    SSL_free(serverssl);
8139    SSL_free(clientssl);
8140    SSL_CTX_free(sctx);
8141    SSL_CTX_free(cctx);
8142
8143    return testresult;
8144}
8145
8146/*
8147 * Test bi-directional shutdown.
8148 * Test 0: TLSv1.2
8149 * Test 1: TLSv1.2, server continues to read/write after client shutdown
8150 * Test 2: TLSv1.3, no pending NewSessionTicket messages
8151 * Test 3: TLSv1.3, pending NewSessionTicket messages
8152 * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
8153 *                  sends key update, client reads it
8154 * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
8155 *                  sends CertificateRequest, client reads and ignores it
8156 * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
8157 *                  doesn't read it
8158 */
8159static int test_shutdown(int tst)
8160{
8161    SSL_CTX *cctx = NULL, *sctx = NULL;
8162    SSL *clientssl = NULL, *serverssl = NULL;
8163    int testresult = 0;
8164    char msg[] = "A test message";
8165    char buf[80];
8166    size_t written, readbytes;
8167    SSL_SESSION *sess;
8168
8169#ifdef OPENSSL_NO_TLS1_2
8170    if (tst <= 1)
8171        return 1;
8172#endif
8173#ifdef OSSL_NO_USABLE_TLS1_3
8174    if (tst >= 2)
8175        return 1;
8176#endif
8177
8178    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8179                                       TLS_client_method(),
8180                                       TLS1_VERSION,
8181                                       (tst <= 1) ? TLS1_2_VERSION
8182                                                  : TLS1_3_VERSION,
8183                                       &sctx, &cctx, cert, privkey)))
8184        goto end;
8185
8186    if (tst == 5)
8187        SSL_CTX_set_post_handshake_auth(cctx, 1);
8188
8189    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8190                                             NULL, NULL)))
8191        goto end;
8192
8193    if (tst == 3) {
8194        if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
8195                                                  SSL_ERROR_NONE, 1))
8196                || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8197                || !TEST_false(SSL_SESSION_is_resumable(sess)))
8198            goto end;
8199    } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8200                                              SSL_ERROR_NONE))
8201            || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8202            || !TEST_true(SSL_SESSION_is_resumable(sess))) {
8203        goto end;
8204    }
8205
8206    if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8207        goto end;
8208
8209    if (tst >= 4) {
8210        /*
8211         * Reading on the server after the client has sent close_notify should
8212         * fail and provide SSL_ERROR_ZERO_RETURN
8213         */
8214        if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
8215                || !TEST_int_eq(SSL_get_error(serverssl, 0),
8216                                SSL_ERROR_ZERO_RETURN)
8217                || !TEST_int_eq(SSL_get_shutdown(serverssl),
8218                                SSL_RECEIVED_SHUTDOWN)
8219                   /*
8220                    * Even though we're shutdown on receive we should still be
8221                    * able to write.
8222                    */
8223                || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8224            goto end;
8225        if (tst == 4
8226                && !TEST_true(SSL_key_update(serverssl,
8227                                             SSL_KEY_UPDATE_REQUESTED)))
8228            goto end;
8229        if (tst == 5) {
8230            SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
8231            if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
8232                goto end;
8233        }
8234        if ((tst == 4 || tst == 5)
8235                && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8236            goto end;
8237        if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8238            goto end;
8239        if (tst == 4 || tst == 5) {
8240            /* Should still be able to read data from server */
8241            if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8242                                       &readbytes))
8243                    || !TEST_size_t_eq(readbytes, sizeof(msg))
8244                    || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
8245                    || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8246                                              &readbytes))
8247                    || !TEST_size_t_eq(readbytes, sizeof(msg))
8248                    || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
8249                goto end;
8250        }
8251    }
8252
8253    /* Writing on the client after sending close_notify shouldn't be possible */
8254    if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
8255        goto end;
8256
8257    if (tst < 4) {
8258        /*
8259         * For these tests the client has sent close_notify but it has not yet
8260         * been received by the server. The server has not sent close_notify
8261         * yet.
8262         */
8263        if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
8264                   /*
8265                    * Writing on the server after sending close_notify shouldn't
8266                    * be possible.
8267                    */
8268                || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8269                || !TEST_int_eq(SSL_shutdown(clientssl), 1)
8270                || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8271                || !TEST_true(SSL_SESSION_is_resumable(sess))
8272                || !TEST_int_eq(SSL_shutdown(serverssl), 1))
8273            goto end;
8274    } else if (tst == 4 || tst == 5) {
8275        /*
8276         * In this test the client has sent close_notify and it has been
8277         * received by the server which has responded with a close_notify. The
8278         * client needs to read the close_notify sent by the server.
8279         */
8280        if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
8281                || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8282                || !TEST_true(SSL_SESSION_is_resumable(sess)))
8283            goto end;
8284    } else {
8285        /*
8286         * tst == 6
8287         *
8288         * The client has sent close_notify and is expecting a close_notify
8289         * back, but instead there is application data first. The shutdown
8290         * should fail with a fatal error.
8291         */
8292        if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
8293                || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
8294            goto end;
8295    }
8296
8297    testresult = 1;
8298
8299 end:
8300    SSL_free(serverssl);
8301    SSL_free(clientssl);
8302    SSL_CTX_free(sctx);
8303    SSL_CTX_free(cctx);
8304
8305    return testresult;
8306}
8307
8308#if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
8309static int cert_cb_cnt;
8310
8311static int cert_cb(SSL *s, void *arg)
8312{
8313    SSL_CTX *ctx = (SSL_CTX *)arg;
8314    BIO *in = NULL;
8315    EVP_PKEY *pkey = NULL;
8316    X509 *x509 = NULL, *rootx = NULL;
8317    STACK_OF(X509) *chain = NULL;
8318    char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
8319    int ret = 0;
8320
8321    if (cert_cb_cnt == 0) {
8322        /* Suspend the handshake */
8323        cert_cb_cnt++;
8324        return -1;
8325    } else if (cert_cb_cnt == 1) {
8326        /*
8327         * Update the SSL_CTX, set the certificate and private key and then
8328         * continue the handshake normally.
8329         */
8330        if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
8331            return 0;
8332
8333        if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
8334                || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
8335                                                      SSL_FILETYPE_PEM))
8336                || !TEST_true(SSL_check_private_key(s)))
8337            return 0;
8338        cert_cb_cnt++;
8339        return 1;
8340    } else if (cert_cb_cnt == 3) {
8341        int rv;
8342
8343        rootfile = test_mk_file_path(certsdir, "rootcert.pem");
8344        ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
8345        ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
8346        if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
8347            goto out;
8348        chain = sk_X509_new_null();
8349        if (!TEST_ptr(chain))
8350            goto out;
8351        if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8352                || !TEST_int_gt(BIO_read_filename(in, rootfile), 0)
8353                || !TEST_ptr(rootx = X509_new_ex(libctx, NULL))
8354                || !TEST_ptr(PEM_read_bio_X509(in, &rootx, NULL, NULL))
8355                || !TEST_true(sk_X509_push(chain, rootx)))
8356            goto out;
8357        rootx = NULL;
8358        BIO_free(in);
8359        if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8360                || !TEST_int_gt(BIO_read_filename(in, ecdsacert), 0)
8361                || !TEST_ptr(x509 = X509_new_ex(libctx, NULL))
8362                || !TEST_ptr(PEM_read_bio_X509(in, &x509, NULL, NULL)))
8363            goto out;
8364        BIO_free(in);
8365        if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8366                || !TEST_int_gt(BIO_read_filename(in, ecdsakey), 0)
8367                || !TEST_ptr(pkey = PEM_read_bio_PrivateKey_ex(in, NULL,
8368                                                               NULL, NULL,
8369                                                               libctx, NULL)))
8370            goto out;
8371        rv = SSL_check_chain(s, x509, pkey, chain);
8372        /*
8373         * If the cert doesn't show as valid here (e.g., because we don't
8374         * have any shared sigalgs), then we will not set it, and there will
8375         * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
8376         * will cause tls_choose_sigalgs() to fail the connection.
8377         */
8378        if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
8379                == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
8380            if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
8381                goto out;
8382        }
8383
8384        ret = 1;
8385    }
8386
8387    /* Abort the handshake */
8388 out:
8389    OPENSSL_free(ecdsacert);
8390    OPENSSL_free(ecdsakey);
8391    OPENSSL_free(rootfile);
8392    BIO_free(in);
8393    EVP_PKEY_free(pkey);
8394    X509_free(x509);
8395    X509_free(rootx);
8396    sk_X509_pop_free(chain, X509_free);
8397    return ret;
8398}
8399
8400/*
8401 * Test the certificate callback.
8402 * Test 0: Callback fails
8403 * Test 1: Success - no SSL_set_SSL_CTX() in the callback
8404 * Test 2: Success - SSL_set_SSL_CTX() in the callback
8405 * Test 3: Success - Call SSL_check_chain from the callback
8406 * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
8407 *                   chain
8408 * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
8409 */
8410static int test_cert_cb_int(int prot, int tst)
8411{
8412    SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
8413    SSL *clientssl = NULL, *serverssl = NULL;
8414    int testresult = 0, ret;
8415
8416#ifdef OPENSSL_NO_EC
8417    /* We use an EC cert in these tests, so we skip in a no-ec build */
8418    if (tst >= 3)
8419        return 1;
8420#endif
8421
8422    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8423                                       TLS_client_method(),
8424                                       TLS1_VERSION,
8425                                       prot,
8426                                       &sctx, &cctx, NULL, NULL)))
8427        goto end;
8428
8429    if (tst == 0)
8430        cert_cb_cnt = -1;
8431    else if (tst >= 3)
8432        cert_cb_cnt = 3;
8433    else
8434        cert_cb_cnt = 0;
8435
8436    if (tst == 2) {
8437        snictx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
8438        if (!TEST_ptr(snictx))
8439            goto end;
8440    }
8441
8442    SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
8443
8444    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8445                                      NULL, NULL)))
8446        goto end;
8447
8448    if (tst == 4) {
8449        /*
8450         * We cause SSL_check_chain() to fail by specifying sig_algs that
8451         * the chain doesn't meet (the root uses an RSA cert)
8452         */
8453        if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
8454                                             "ecdsa_secp256r1_sha256")))
8455            goto end;
8456    } else if (tst == 5) {
8457        /*
8458         * We cause SSL_check_chain() to fail by specifying sig_algs that
8459         * the ee cert doesn't meet (the ee uses an ECDSA cert)
8460         */
8461        if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
8462                           "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
8463            goto end;
8464    }
8465
8466    ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
8467    if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
8468            || (tst > 0
8469                && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
8470        goto end;
8471    }
8472
8473    testresult = 1;
8474
8475 end:
8476    SSL_free(serverssl);
8477    SSL_free(clientssl);
8478    SSL_CTX_free(sctx);
8479    SSL_CTX_free(cctx);
8480    SSL_CTX_free(snictx);
8481
8482    return testresult;
8483}
8484#endif
8485
8486static int test_cert_cb(int tst)
8487{
8488    int testresult = 1;
8489
8490#ifndef OPENSSL_NO_TLS1_2
8491    testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
8492#endif
8493#ifndef OSSL_NO_USABLE_TLS1_3
8494    testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
8495#endif
8496
8497    return testresult;
8498}
8499
8500static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
8501{
8502    X509 *xcert;
8503    EVP_PKEY *privpkey;
8504    BIO *in = NULL;
8505    BIO *priv_in = NULL;
8506
8507    /* Check that SSL_get0_peer_certificate() returns something sensible */
8508    if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
8509        return 0;
8510
8511    in = BIO_new_file(cert, "r");
8512    if (!TEST_ptr(in))
8513        return 0;
8514
8515    if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL))
8516            || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
8517            || !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
8518            || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
8519                                                               NULL, NULL,
8520                                                               libctx, NULL)))
8521        goto err;
8522
8523    *x509 = xcert;
8524    *pkey = privpkey;
8525
8526    BIO_free(in);
8527    BIO_free(priv_in);
8528    return 1;
8529err:
8530    X509_free(xcert);
8531    BIO_free(in);
8532    BIO_free(priv_in);
8533    return 0;
8534}
8535
8536static int test_client_cert_cb(int tst)
8537{
8538    SSL_CTX *cctx = NULL, *sctx = NULL;
8539    SSL *clientssl = NULL, *serverssl = NULL;
8540    int testresult = 0;
8541
8542#ifdef OPENSSL_NO_TLS1_2
8543    if (tst == 0)
8544        return 1;
8545#endif
8546#ifdef OSSL_NO_USABLE_TLS1_3
8547    if (tst == 1)
8548        return 1;
8549#endif
8550
8551    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8552                                       TLS_client_method(),
8553                                       TLS1_VERSION,
8554                                       tst == 0 ? TLS1_2_VERSION
8555                                                : TLS1_3_VERSION,
8556                                       &sctx, &cctx, cert, privkey)))
8557        goto end;
8558
8559    /*
8560     * Test that setting a client_cert_cb results in a client certificate being
8561     * sent.
8562     */
8563    SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
8564    SSL_CTX_set_verify(sctx,
8565                       SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
8566                       verify_cb);
8567
8568    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8569                                      NULL, NULL))
8570            || !TEST_true(create_ssl_connection(serverssl, clientssl,
8571                                                SSL_ERROR_NONE)))
8572        goto end;
8573
8574    testresult = 1;
8575
8576 end:
8577    SSL_free(serverssl);
8578    SSL_free(clientssl);
8579    SSL_CTX_free(sctx);
8580    SSL_CTX_free(cctx);
8581
8582    return testresult;
8583}
8584
8585#if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
8586/*
8587 * Test setting certificate authorities on both client and server.
8588 *
8589 * Test 0: SSL_CTX_set0_CA_list() only
8590 * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
8591 * Test 2: Only SSL_CTX_set_client_CA_list()
8592 */
8593static int test_ca_names_int(int prot, int tst)
8594{
8595    SSL_CTX *cctx = NULL, *sctx = NULL;
8596    SSL *clientssl = NULL, *serverssl = NULL;
8597    int testresult = 0;
8598    size_t i;
8599    X509_NAME *name[] = { NULL, NULL, NULL, NULL };
8600    char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
8601    STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
8602    const STACK_OF(X509_NAME) *sktmp = NULL;
8603
8604    for (i = 0; i < OSSL_NELEM(name); i++) {
8605        name[i] = X509_NAME_new();
8606        if (!TEST_ptr(name[i])
8607                || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
8608                                                         MBSTRING_ASC,
8609                                                         (unsigned char *)
8610                                                         strnames[i],
8611                                                         -1, -1, 0)))
8612            goto end;
8613    }
8614
8615    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8616                                       TLS_client_method(),
8617                                       TLS1_VERSION,
8618                                       prot,
8619                                       &sctx, &cctx, cert, privkey)))
8620        goto end;
8621
8622    SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
8623
8624    if (tst == 0 || tst == 1) {
8625        if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
8626                || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
8627                || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
8628                || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
8629                || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
8630                || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
8631            goto end;
8632
8633        SSL_CTX_set0_CA_list(sctx, sk1);
8634        SSL_CTX_set0_CA_list(cctx, sk2);
8635        sk1 = sk2 = NULL;
8636    }
8637    if (tst == 1 || tst == 2) {
8638        if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
8639                || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
8640                || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
8641                || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
8642                || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
8643                || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
8644            goto end;
8645
8646        SSL_CTX_set_client_CA_list(sctx, sk1);
8647        SSL_CTX_set_client_CA_list(cctx, sk2);
8648        sk1 = sk2 = NULL;
8649    }
8650
8651    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8652                                      NULL, NULL))
8653            || !TEST_true(create_ssl_connection(serverssl, clientssl,
8654                                                SSL_ERROR_NONE)))
8655        goto end;
8656
8657    /*
8658     * We only expect certificate authorities to have been sent to the server
8659     * if we are using TLSv1.3 and SSL_set0_CA_list() was used
8660     */
8661    sktmp = SSL_get0_peer_CA_list(serverssl);
8662    if (prot == TLS1_3_VERSION
8663            && (tst == 0 || tst == 1)) {
8664        if (!TEST_ptr(sktmp)
8665                || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
8666                || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
8667                                              name[0]), 0)
8668                || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
8669                                              name[1]), 0))
8670            goto end;
8671    } else if (!TEST_ptr_null(sktmp)) {
8672        goto end;
8673    }
8674
8675    /*
8676     * In all tests we expect certificate authorities to have been sent to the
8677     * client. However, SSL_set_client_CA_list() should override
8678     * SSL_set0_CA_list()
8679     */
8680    sktmp = SSL_get0_peer_CA_list(clientssl);
8681    if (!TEST_ptr(sktmp)
8682            || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
8683            || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
8684                                          name[tst == 0 ? 0 : 2]), 0)
8685            || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
8686                                          name[tst == 0 ? 1 : 3]), 0))
8687        goto end;
8688
8689    testresult = 1;
8690
8691 end:
8692    SSL_free(serverssl);
8693    SSL_free(clientssl);
8694    SSL_CTX_free(sctx);
8695    SSL_CTX_free(cctx);
8696    for (i = 0; i < OSSL_NELEM(name); i++)
8697        X509_NAME_free(name[i]);
8698    sk_X509_NAME_pop_free(sk1, X509_NAME_free);
8699    sk_X509_NAME_pop_free(sk2, X509_NAME_free);
8700
8701    return testresult;
8702}
8703#endif
8704
8705static int test_ca_names(int tst)
8706{
8707    int testresult = 1;
8708
8709#ifndef OPENSSL_NO_TLS1_2
8710    testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
8711#endif
8712#ifndef OSSL_NO_USABLE_TLS1_3
8713    testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
8714#endif
8715
8716    return testresult;
8717}
8718
8719#ifndef OPENSSL_NO_TLS1_2
8720static const char *multiblock_cipherlist_data[]=
8721{
8722    "AES128-SHA",
8723    "AES128-SHA256",
8724    "AES256-SHA",
8725    "AES256-SHA256",
8726};
8727
8728/* Reduce the fragment size - so the multiblock test buffer can be small */
8729# define MULTIBLOCK_FRAGSIZE 512
8730
8731static int test_multiblock_write(int test_index)
8732{
8733    static const char *fetchable_ciphers[]=
8734    {
8735        "AES-128-CBC-HMAC-SHA1",
8736        "AES-128-CBC-HMAC-SHA256",
8737        "AES-256-CBC-HMAC-SHA1",
8738        "AES-256-CBC-HMAC-SHA256"
8739    };
8740    const char *cipherlist = multiblock_cipherlist_data[test_index];
8741    const SSL_METHOD *smeth = TLS_server_method();
8742    const SSL_METHOD *cmeth = TLS_client_method();
8743    int min_version = TLS1_VERSION;
8744    int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
8745    SSL_CTX *cctx = NULL, *sctx = NULL;
8746    SSL *clientssl = NULL, *serverssl = NULL;
8747    int testresult = 0;
8748
8749    /*
8750     * Choose a buffer large enough to perform a multi-block operation
8751     * i.e: write_len >= 4 * frag_size
8752     * 9 * is chosen so that multiple multiblocks are used + some leftover.
8753     */
8754    unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
8755    unsigned char buf[sizeof(msg)], *p = buf;
8756    size_t readbytes, written, len;
8757    EVP_CIPHER *ciph = NULL;
8758
8759    /*
8760     * Check if the cipher exists before attempting to use it since it only has
8761     * a hardware specific implementation.
8762     */
8763    ciph = EVP_CIPHER_fetch(libctx, fetchable_ciphers[test_index], "");
8764    if (ciph == NULL) {
8765        TEST_skip("Multiblock cipher is not available for %s", cipherlist);
8766        return 1;
8767    }
8768    EVP_CIPHER_free(ciph);
8769
8770    /* Set up a buffer with some data that will be sent to the client */
8771    RAND_bytes(msg, sizeof(msg));
8772
8773    if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
8774                                       max_version, &sctx, &cctx, cert,
8775                                       privkey)))
8776        goto end;
8777
8778    if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
8779        goto end;
8780
8781    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8782                                      NULL, NULL)))
8783            goto end;
8784
8785    /* settings to force it to use AES-CBC-HMAC_SHA */
8786    SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
8787    if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
8788       goto end;
8789
8790    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8791        goto end;
8792
8793    if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8794        || !TEST_size_t_eq(written, sizeof(msg)))
8795        goto end;
8796
8797    len = written;
8798    while (len > 0) {
8799        if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
8800            goto end;
8801        p += readbytes;
8802        len -= readbytes;
8803    }
8804    if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
8805        goto end;
8806
8807    testresult = 1;
8808end:
8809    SSL_free(serverssl);
8810    SSL_free(clientssl);
8811    SSL_CTX_free(sctx);
8812    SSL_CTX_free(cctx);
8813
8814    return testresult;
8815}
8816#endif /* OPENSSL_NO_TLS1_2 */
8817
8818static int test_session_timeout(int test)
8819{
8820    /*
8821     * Test session ordering and timeout
8822     * Can't explicitly test performance of the new code,
8823     * but can test to see if the ordering of the sessions
8824     * are correct, and they they are removed as expected
8825     */
8826    SSL_SESSION *early = NULL;
8827    SSL_SESSION *middle = NULL;
8828    SSL_SESSION *late = NULL;
8829    SSL_CTX *ctx;
8830    int testresult = 0;
8831    long now = (long)time(NULL);
8832#define TIMEOUT 10
8833
8834    if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
8835        || !TEST_ptr(early = SSL_SESSION_new())
8836        || !TEST_ptr(middle = SSL_SESSION_new())
8837        || !TEST_ptr(late = SSL_SESSION_new()))
8838        goto end;
8839
8840    /* assign unique session ids */
8841    early->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
8842    memset(early->session_id, 1, SSL3_SSL_SESSION_ID_LENGTH);
8843    middle->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
8844    memset(middle->session_id, 2, SSL3_SSL_SESSION_ID_LENGTH);
8845    late->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
8846    memset(late->session_id, 3, SSL3_SSL_SESSION_ID_LENGTH);
8847
8848    if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
8849        || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
8850        || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
8851        goto end;
8852
8853    /* Make sure they are all added */
8854    if (!TEST_ptr(early->prev)
8855        || !TEST_ptr(middle->prev)
8856        || !TEST_ptr(late->prev))
8857        goto end;
8858
8859    if (!TEST_int_ne(SSL_SESSION_set_time(early, now - 10), 0)
8860        || !TEST_int_ne(SSL_SESSION_set_time(middle, now), 0)
8861        || !TEST_int_ne(SSL_SESSION_set_time(late, now + 10), 0))
8862        goto end;
8863
8864    if (!TEST_int_ne(SSL_SESSION_set_timeout(early, TIMEOUT), 0)
8865        || !TEST_int_ne(SSL_SESSION_set_timeout(middle, TIMEOUT), 0)
8866        || !TEST_int_ne(SSL_SESSION_set_timeout(late, TIMEOUT), 0))
8867        goto end;
8868
8869    /* Make sure they are all still there */
8870    if (!TEST_ptr(early->prev)
8871        || !TEST_ptr(middle->prev)
8872        || !TEST_ptr(late->prev))
8873        goto end;
8874
8875    /* Make sure they are in the expected order */
8876    if (!TEST_ptr_eq(late->next, middle)
8877        || !TEST_ptr_eq(middle->next, early)
8878        || !TEST_ptr_eq(early->prev, middle)
8879        || !TEST_ptr_eq(middle->prev, late))
8880        goto end;
8881
8882    /* This should remove "early" */
8883    SSL_CTX_flush_sessions(ctx, now + TIMEOUT - 1);
8884    if (!TEST_ptr_null(early->prev)
8885        || !TEST_ptr(middle->prev)
8886        || !TEST_ptr(late->prev))
8887        goto end;
8888
8889    /* This should remove "middle" */
8890    SSL_CTX_flush_sessions(ctx, now + TIMEOUT + 1);
8891    if (!TEST_ptr_null(early->prev)
8892        || !TEST_ptr_null(middle->prev)
8893        || !TEST_ptr(late->prev))
8894        goto end;
8895
8896    /* This should remove "late" */
8897    SSL_CTX_flush_sessions(ctx, now + TIMEOUT + 11);
8898    if (!TEST_ptr_null(early->prev)
8899        || !TEST_ptr_null(middle->prev)
8900        || !TEST_ptr_null(late->prev))
8901        goto end;
8902
8903    /* Add them back in again */
8904    if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
8905        || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
8906        || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
8907        goto end;
8908
8909    /* Make sure they are all added */
8910    if (!TEST_ptr(early->prev)
8911        || !TEST_ptr(middle->prev)
8912        || !TEST_ptr(late->prev))
8913        goto end;
8914
8915    /* This should remove all of them */
8916    SSL_CTX_flush_sessions(ctx, 0);
8917    if (!TEST_ptr_null(early->prev)
8918        || !TEST_ptr_null(middle->prev)
8919        || !TEST_ptr_null(late->prev))
8920        goto end;
8921
8922    (void)SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_UPDATE_TIME
8923                                         | SSL_CTX_get_session_cache_mode(ctx));
8924
8925    /* make sure |now| is NOT  equal to the current time */
8926    now -= 10;
8927    if (!TEST_int_ne(SSL_SESSION_set_time(early, now), 0)
8928        || !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
8929        || !TEST_long_ne(SSL_SESSION_get_time(early), now))
8930        goto end;
8931
8932    testresult = 1;
8933 end:
8934    SSL_CTX_free(ctx);
8935    SSL_SESSION_free(early);
8936    SSL_SESSION_free(middle);
8937    SSL_SESSION_free(late);
8938    return testresult;
8939}
8940
8941/*
8942 * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
8943 * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
8944 * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
8945 * Test 3: Client does not set servername on initial handshake (TLSv1.2)
8946 * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
8947 * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
8948 * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
8949 * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
8950 * Test 8: Client does not set servername on initial handshake(TLSv1.3)
8951 * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
8952 */
8953static int test_servername(int tst)
8954{
8955    SSL_CTX *cctx = NULL, *sctx = NULL;
8956    SSL *clientssl = NULL, *serverssl = NULL;
8957    int testresult = 0;
8958    SSL_SESSION *sess = NULL;
8959    const char *sexpectedhost = NULL, *cexpectedhost = NULL;
8960
8961#ifdef OPENSSL_NO_TLS1_2
8962    if (tst <= 4)
8963        return 1;
8964#endif
8965#ifdef OSSL_NO_USABLE_TLS1_3
8966    if (tst >= 5)
8967        return 1;
8968#endif
8969
8970    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8971                                       TLS_client_method(),
8972                                       TLS1_VERSION,
8973                                       (tst <= 4) ? TLS1_2_VERSION
8974                                                  : TLS1_3_VERSION,
8975                                       &sctx, &cctx, cert, privkey))
8976            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8977                                             NULL, NULL)))
8978        goto end;
8979
8980    if (tst != 1 && tst != 6) {
8981        if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
8982                                                              hostname_cb)))
8983            goto end;
8984    }
8985
8986    if (tst != 3 && tst != 8) {
8987        if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
8988            goto end;
8989        sexpectedhost = cexpectedhost = "goodhost";
8990    }
8991
8992    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8993        goto end;
8994
8995    if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
8996                     cexpectedhost)
8997            || !TEST_str_eq(SSL_get_servername(serverssl,
8998                                               TLSEXT_NAMETYPE_host_name),
8999                            sexpectedhost))
9000        goto end;
9001
9002    /* Now repeat with a resumption handshake */
9003
9004    if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
9005            || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
9006            || !TEST_true(SSL_SESSION_is_resumable(sess))
9007            || !TEST_int_eq(SSL_shutdown(serverssl), 0))
9008        goto end;
9009
9010    SSL_free(clientssl);
9011    SSL_free(serverssl);
9012    clientssl = serverssl = NULL;
9013
9014    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9015                                      NULL)))
9016        goto end;
9017
9018    if (!TEST_true(SSL_set_session(clientssl, sess)))
9019        goto end;
9020
9021    sexpectedhost = cexpectedhost = "goodhost";
9022    if (tst == 2 || tst == 7) {
9023        /* Set an inconsistent hostname */
9024        if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
9025            goto end;
9026        /*
9027         * In TLSv1.2 we expect the hostname from the original handshake, in
9028         * TLSv1.3 we expect the hostname from this handshake
9029         */
9030        if (tst == 7)
9031            sexpectedhost = cexpectedhost = "altgoodhost";
9032
9033        if (!TEST_str_eq(SSL_get_servername(clientssl,
9034                                            TLSEXT_NAMETYPE_host_name),
9035                         "altgoodhost"))
9036            goto end;
9037    } else if (tst == 4 || tst == 9) {
9038        /*
9039         * A TLSv1.3 session does not associate a session with a servername,
9040         * but a TLSv1.2 session does.
9041         */
9042        if (tst == 9)
9043            sexpectedhost = cexpectedhost = NULL;
9044
9045        if (!TEST_str_eq(SSL_get_servername(clientssl,
9046                                            TLSEXT_NAMETYPE_host_name),
9047                         cexpectedhost))
9048            goto end;
9049    } else {
9050        if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9051            goto end;
9052        /*
9053         * In a TLSv1.2 resumption where the hostname was not acknowledged
9054         * we expect the hostname on the server to be empty. On the client we
9055         * return what was requested in this case.
9056         *
9057         * Similarly if the client didn't set a hostname on an original TLSv1.2
9058         * session but is now, the server hostname will be empty, but the client
9059         * is as we set it.
9060         */
9061        if (tst == 1 || tst == 3)
9062            sexpectedhost = NULL;
9063
9064        if (!TEST_str_eq(SSL_get_servername(clientssl,
9065                                            TLSEXT_NAMETYPE_host_name),
9066                         "goodhost"))
9067            goto end;
9068    }
9069
9070    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9071        goto end;
9072
9073    if (!TEST_true(SSL_session_reused(clientssl))
9074            || !TEST_true(SSL_session_reused(serverssl))
9075            || !TEST_str_eq(SSL_get_servername(clientssl,
9076                                               TLSEXT_NAMETYPE_host_name),
9077                            cexpectedhost)
9078            || !TEST_str_eq(SSL_get_servername(serverssl,
9079                                               TLSEXT_NAMETYPE_host_name),
9080                            sexpectedhost))
9081        goto end;
9082
9083    testresult = 1;
9084
9085 end:
9086    SSL_SESSION_free(sess);
9087    SSL_free(serverssl);
9088    SSL_free(clientssl);
9089    SSL_CTX_free(sctx);
9090    SSL_CTX_free(cctx);
9091
9092    return testresult;
9093}
9094
9095#if !defined(OPENSSL_NO_EC) \
9096    && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
9097/*
9098 * Test that if signature algorithms are not available, then we do not offer or
9099 * accept them.
9100 * Test 0: Two RSA sig algs available: both RSA sig algs shared
9101 * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared
9102 * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared
9103 * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared
9104 * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared
9105 * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared
9106 */
9107static int test_sigalgs_available(int idx)
9108{
9109    SSL_CTX *cctx = NULL, *sctx = NULL;
9110    SSL *clientssl = NULL, *serverssl = NULL;
9111    int testresult = 0;
9112    OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
9113    OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx;
9114    OSSL_PROVIDER *filterprov = NULL;
9115    int sig, hash;
9116
9117    if (!TEST_ptr(tmpctx))
9118        goto end;
9119
9120    if (idx != 0 && idx != 3) {
9121        if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter",
9122                                                 filter_provider_init)))
9123            goto end;
9124
9125        filterprov = OSSL_PROVIDER_load(tmpctx, "filter");
9126        if (!TEST_ptr(filterprov))
9127            goto end;
9128
9129        if (idx < 3) {
9130            /*
9131             * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered
9132             * or accepted for the peer that uses this libctx. Note that libssl
9133             * *requires* SHA2-256 to be available so we cannot disable that. We
9134             * also need SHA1 for our certificate.
9135             */
9136            if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST,
9137                                                      "SHA2-256:SHA1")))
9138                goto end;
9139        } else {
9140            if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE,
9141                                                      "ECDSA"))
9142                    || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
9143                                                             "EC:X25519:X448")))
9144                goto end;
9145        }
9146
9147        if (idx == 1 || idx == 4)
9148            clientctx = tmpctx;
9149        else
9150            serverctx = tmpctx;
9151    }
9152
9153    cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method());
9154    sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method());
9155    if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
9156        goto end;
9157
9158    if (idx != 5) {
9159        if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9160                                           TLS_client_method(),
9161                                           TLS1_VERSION,
9162                                           0,
9163                                           &sctx, &cctx, cert, privkey)))
9164            goto end;
9165    } else {
9166        if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9167                                           TLS_client_method(),
9168                                           TLS1_VERSION,
9169                                           0,
9170                                           &sctx, &cctx, cert2, privkey2)))
9171            goto end;
9172    }
9173
9174    /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */
9175    if (idx < 4) {
9176        if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
9177                                               "ECDHE-RSA-AES128-GCM-SHA256")))
9178            goto end;
9179    } else {
9180        if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
9181                                               "ECDHE-ECDSA-AES128-GCM-SHA256")))
9182            goto end;
9183    }
9184
9185    if (idx < 3) {
9186        if (!SSL_CTX_set1_sigalgs_list(cctx,
9187                                       "rsa_pss_rsae_sha384"
9188                                       ":rsa_pss_rsae_sha256")
9189                || !SSL_CTX_set1_sigalgs_list(sctx,
9190                                              "rsa_pss_rsae_sha384"
9191                                              ":rsa_pss_rsae_sha256"))
9192            goto end;
9193    } else {
9194        if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")
9195                || !SSL_CTX_set1_sigalgs_list(sctx,
9196                                              "rsa_pss_rsae_sha256:ECDSA+SHA256"))
9197            goto end;
9198    }
9199
9200    if (idx != 5
9201        && (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2,
9202                                                      SSL_FILETYPE_PEM), 1)
9203            || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
9204                                                        privkey2,
9205                                                        SSL_FILETYPE_PEM), 1)
9206            || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)))
9207        goto end;
9208
9209    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9210                                      NULL, NULL)))
9211        goto end;
9212
9213    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9214        goto end;
9215
9216    /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */
9217    if (!TEST_int_eq(SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash, NULL,
9218                                            NULL, NULL),
9219                     (idx == 0 || idx == 3) ? 2 : 1))
9220        goto end;
9221
9222    if (!TEST_int_eq(hash, idx == 0 ? NID_sha384 : NID_sha256))
9223        goto end;
9224
9225    if (!TEST_int_eq(sig, (idx == 4 || idx == 5) ? EVP_PKEY_EC
9226                                                 : NID_rsassaPss))
9227        goto end;
9228
9229    testresult = filter_provider_check_clean_finish();
9230
9231 end:
9232    SSL_free(serverssl);
9233    SSL_free(clientssl);
9234    SSL_CTX_free(sctx);
9235    SSL_CTX_free(cctx);
9236    OSSL_PROVIDER_unload(filterprov);
9237    OSSL_LIB_CTX_free(tmpctx);
9238
9239    return testresult;
9240}
9241#endif /*
9242        * !defined(OPENSSL_NO_EC) \
9243        * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
9244        */
9245
9246#ifndef OPENSSL_NO_TLS1_3
9247/* This test can run in TLSv1.3 even if ec and dh are disabled */
9248static int test_pluggable_group(int idx)
9249{
9250    SSL_CTX *cctx = NULL, *sctx = NULL;
9251    SSL *clientssl = NULL, *serverssl = NULL;
9252    int testresult = 0;
9253    OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
9254    /* Check that we are not impacted by a provider without any groups */
9255    OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy");
9256    const char *group_name = idx == 0 ? "xorgroup" : "xorkemgroup";
9257
9258    if (!TEST_ptr(tlsprov))
9259        goto end;
9260
9261    if (legacyprov == NULL) {
9262        /*
9263         * In this case we assume we've been built with "no-legacy" and skip
9264         * this test (there is no OPENSSL_NO_LEGACY)
9265         */
9266        testresult = 1;
9267        goto end;
9268    }
9269
9270    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9271                                       TLS_client_method(),
9272                                       TLS1_3_VERSION,
9273                                       TLS1_3_VERSION,
9274                                       &sctx, &cctx, cert, privkey))
9275            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9276                                             NULL, NULL)))
9277        goto end;
9278
9279    if (!TEST_true(SSL_set1_groups_list(serverssl, group_name))
9280            || !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
9281        goto end;
9282
9283    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9284        goto end;
9285
9286    if (!TEST_str_eq(group_name,
9287                     SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
9288        goto end;
9289
9290    testresult = 1;
9291
9292 end:
9293    SSL_free(serverssl);
9294    SSL_free(clientssl);
9295    SSL_CTX_free(sctx);
9296    SSL_CTX_free(cctx);
9297    OSSL_PROVIDER_unload(tlsprov);
9298    OSSL_PROVIDER_unload(legacyprov);
9299
9300    return testresult;
9301}
9302#endif
9303
9304#ifndef OPENSSL_NO_TLS1_2
9305static int test_ssl_dup(void)
9306{
9307    SSL_CTX *cctx = NULL, *sctx = NULL;
9308    SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
9309    int testresult = 0;
9310    BIO *rbio = NULL, *wbio = NULL;
9311
9312    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9313                                       TLS_client_method(),
9314                                       0,
9315                                       0,
9316                                       &sctx, &cctx, cert, privkey)))
9317        goto end;
9318
9319    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9320                                             NULL, NULL)))
9321        goto end;
9322
9323    if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
9324            || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
9325        goto end;
9326
9327    client2ssl = SSL_dup(clientssl);
9328    rbio = SSL_get_rbio(clientssl);
9329    if (!TEST_ptr(rbio)
9330            || !TEST_true(BIO_up_ref(rbio)))
9331        goto end;
9332    SSL_set0_rbio(client2ssl, rbio);
9333    rbio = NULL;
9334
9335    wbio = SSL_get_wbio(clientssl);
9336    if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
9337        goto end;
9338    SSL_set0_wbio(client2ssl, wbio);
9339    rbio = NULL;
9340
9341    if (!TEST_ptr(client2ssl)
9342               /* Handshake not started so pointers should be different */
9343            || !TEST_ptr_ne(clientssl, client2ssl))
9344        goto end;
9345
9346    if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
9347            || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
9348        goto end;
9349
9350    if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
9351        goto end;
9352
9353    SSL_free(clientssl);
9354    clientssl = SSL_dup(client2ssl);
9355    if (!TEST_ptr(clientssl)
9356               /* Handshake has finished so pointers should be the same */
9357            || !TEST_ptr_eq(clientssl, client2ssl))
9358        goto end;
9359
9360    testresult = 1;
9361
9362 end:
9363    SSL_free(serverssl);
9364    SSL_free(clientssl);
9365    SSL_free(client2ssl);
9366    SSL_CTX_free(sctx);
9367    SSL_CTX_free(cctx);
9368
9369    return testresult;
9370}
9371
9372# ifndef OPENSSL_NO_DH
9373
9374static EVP_PKEY *tmp_dh_params = NULL;
9375
9376/* Helper function for the test_set_tmp_dh() tests */
9377static EVP_PKEY *get_tmp_dh_params(void)
9378{
9379    if (tmp_dh_params == NULL) {
9380        BIGNUM *p = NULL;
9381        OSSL_PARAM_BLD *tmpl = NULL;
9382        EVP_PKEY_CTX *pctx = NULL;
9383        OSSL_PARAM *params = NULL;
9384        EVP_PKEY *dhpkey = NULL;
9385
9386        p = BN_get_rfc3526_prime_2048(NULL);
9387        if (!TEST_ptr(p))
9388            goto end;
9389
9390        pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL);
9391        if (!TEST_ptr(pctx)
9392                || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx), 1))
9393            goto end;
9394
9395        tmpl = OSSL_PARAM_BLD_new();
9396        if (!TEST_ptr(tmpl)
9397                || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl,
9398                                                        OSSL_PKEY_PARAM_FFC_P,
9399                                                        p))
9400                || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl,
9401                                                        OSSL_PKEY_PARAM_FFC_G,
9402                                                        2)))
9403            goto end;
9404
9405        params = OSSL_PARAM_BLD_to_param(tmpl);
9406        if (!TEST_ptr(params)
9407                || !TEST_int_eq(EVP_PKEY_fromdata(pctx, &dhpkey,
9408                                                  EVP_PKEY_KEY_PARAMETERS,
9409                                                  params), 1))
9410            goto end;
9411
9412        tmp_dh_params = dhpkey;
9413    end:
9414        BN_free(p);
9415        EVP_PKEY_CTX_free(pctx);
9416        OSSL_PARAM_BLD_free(tmpl);
9417        OSSL_PARAM_free(params);
9418    }
9419
9420    if (tmp_dh_params != NULL && !EVP_PKEY_up_ref(tmp_dh_params))
9421        return NULL;
9422
9423    return tmp_dh_params;
9424}
9425
9426#  ifndef OPENSSL_NO_DEPRECATED_3_0
9427/* Callback used by test_set_tmp_dh() */
9428static DH *tmp_dh_callback(SSL *s, int is_export, int keylen)
9429{
9430    EVP_PKEY *dhpkey = get_tmp_dh_params();
9431    DH *ret = NULL;
9432
9433    if (!TEST_ptr(dhpkey))
9434        return NULL;
9435
9436    /*
9437     * libssl does not free the returned DH, so we free it now knowing that even
9438     * after we free dhpkey, there will still be a reference to the owning
9439     * EVP_PKEY in tmp_dh_params, and so the DH object will live for the length
9440     * of time we need it for.
9441     */
9442    ret = EVP_PKEY_get1_DH(dhpkey);
9443    DH_free(ret);
9444
9445    EVP_PKEY_free(dhpkey);
9446
9447    return ret;
9448}
9449#  endif
9450
9451/*
9452 * Test the various methods for setting temporary DH parameters
9453 *
9454 * Test  0: Default (no auto) setting
9455 * Test  1: Explicit SSL_CTX auto off
9456 * Test  2: Explicit SSL auto off
9457 * Test  3: Explicit SSL_CTX auto on
9458 * Test  4: Explicit SSL auto on
9459 * Test  5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY
9460 * Test  6: Explicit SSL auto off, custom DH params via EVP_PKEY
9461 *
9462 * The following are testing deprecated APIs, so we only run them if available
9463 * Test  7: Explicit SSL_CTX auto off, custom DH params via DH
9464 * Test  8: Explicit SSL auto off, custom DH params via DH
9465 * Test  9: Explicit SSL_CTX auto off, custom DH params via callback
9466 * Test 10: Explicit SSL auto off, custom DH params via callback
9467 */
9468static int test_set_tmp_dh(int idx)
9469{
9470    SSL_CTX *cctx = NULL, *sctx = NULL;
9471    SSL *clientssl = NULL, *serverssl = NULL;
9472    int testresult = 0;
9473    int dhauto = (idx == 3 || idx == 4) ? 1 : 0;
9474    int expected = (idx <= 2) ? 0 : 1;
9475    EVP_PKEY *dhpkey = NULL;
9476#  ifndef OPENSSL_NO_DEPRECATED_3_0
9477    DH *dh = NULL;
9478#  else
9479
9480    if (idx >= 7)
9481        return 1;
9482#  endif
9483
9484    if (idx >= 5 && idx <= 8) {
9485        dhpkey = get_tmp_dh_params();
9486        if (!TEST_ptr(dhpkey))
9487            goto end;
9488    }
9489#  ifndef OPENSSL_NO_DEPRECATED_3_0
9490    if (idx == 7 || idx == 8) {
9491        dh = EVP_PKEY_get1_DH(dhpkey);
9492        if (!TEST_ptr(dh))
9493            goto end;
9494    }
9495#  endif
9496
9497    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9498                                       TLS_client_method(),
9499                                       0,
9500                                       0,
9501                                       &sctx, &cctx, cert, privkey)))
9502        goto end;
9503
9504    if ((idx & 1) == 1) {
9505        if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto)))
9506            goto end;
9507    }
9508
9509    if (idx == 5) {
9510        if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey)))
9511            goto end;
9512        dhpkey = NULL;
9513    }
9514#  ifndef OPENSSL_NO_DEPRECATED_3_0
9515    else if (idx == 7) {
9516        if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh)))
9517            goto end;
9518    } else if (idx == 9) {
9519        SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback);
9520    }
9521#  endif
9522
9523    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9524                                      NULL, NULL)))
9525        goto end;
9526
9527    if ((idx & 1) == 0 && idx != 0) {
9528        if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto)))
9529            goto end;
9530    }
9531    if (idx == 6) {
9532        if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey)))
9533            goto end;
9534        dhpkey = NULL;
9535    }
9536#  ifndef OPENSSL_NO_DEPRECATED_3_0
9537    else if (idx == 8) {
9538        if (!TEST_true(SSL_set_tmp_dh(serverssl, dh)))
9539            goto end;
9540    } else if (idx == 10) {
9541        SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback);
9542    }
9543#  endif
9544
9545    if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
9546            || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
9547            || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA")))
9548        goto end;
9549
9550    /*
9551     * If autoon then we should succeed. Otherwise we expect failure because
9552     * there are no parameters
9553     */
9554    if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
9555                                           SSL_ERROR_NONE), expected))
9556        goto end;
9557
9558    testresult = 1;
9559
9560 end:
9561#  ifndef OPENSSL_NO_DEPRECATED_3_0
9562    DH_free(dh);
9563#  endif
9564    SSL_free(serverssl);
9565    SSL_free(clientssl);
9566    SSL_CTX_free(sctx);
9567    SSL_CTX_free(cctx);
9568    EVP_PKEY_free(dhpkey);
9569
9570    return testresult;
9571}
9572
9573/*
9574 * Test the auto DH keys are appropriately sized
9575 */
9576static int test_dh_auto(int idx)
9577{
9578    SSL_CTX *cctx = NULL, *sctx = NULL;
9579    SSL *clientssl = NULL, *serverssl = NULL;
9580    int testresult = 0;
9581    EVP_PKEY *tmpkey = NULL;
9582    char *thiscert = NULL, *thiskey = NULL;
9583    size_t expdhsize = 0;
9584    const char *ciphersuite = "DHE-RSA-AES128-SHA";
9585
9586    switch (idx) {
9587    case 0:
9588        /* The FIPS provider doesn't support this DH size - so we ignore it */
9589        if (is_fips)
9590            return 1;
9591        thiscert = cert1024;
9592        thiskey = privkey1024;
9593        expdhsize = 1024;
9594        break;
9595    case 1:
9596        /* 2048 bit prime */
9597        thiscert = cert;
9598        thiskey = privkey;
9599        expdhsize = 2048;
9600        break;
9601    case 2:
9602        thiscert = cert3072;
9603        thiskey = privkey3072;
9604        expdhsize = 3072;
9605        break;
9606    case 3:
9607        thiscert = cert4096;
9608        thiskey = privkey4096;
9609        expdhsize = 4096;
9610        break;
9611    case 4:
9612        thiscert = cert8192;
9613        thiskey = privkey8192;
9614        expdhsize = 8192;
9615        break;
9616    /* No certificate cases */
9617    case 5:
9618        /* The FIPS provider doesn't support this DH size - so we ignore it */
9619        if (is_fips)
9620            return 1;
9621        ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0";
9622        expdhsize = 1024;
9623        break;
9624    case 6:
9625        ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0";
9626        expdhsize = 3072;
9627        break;
9628    default:
9629        TEST_error("Invalid text index");
9630        goto end;
9631    }
9632
9633    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9634                                       TLS_client_method(),
9635                                       0,
9636                                       0,
9637                                       &sctx, &cctx, thiscert, thiskey)))
9638        goto end;
9639
9640    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9641                                      NULL, NULL)))
9642        goto end;
9643
9644    if (!TEST_true(SSL_set_dh_auto(serverssl, 1))
9645            || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
9646            || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
9647            || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite))
9648            || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite)))
9649        goto end;
9650
9651    /*
9652     * Send the server's first flight. At this point the server has created the
9653     * temporary DH key but hasn't finished using it yet. Once used it is
9654     * removed, so we cannot test it.
9655     */
9656    if (!TEST_int_le(SSL_connect(clientssl), 0)
9657            || !TEST_int_le(SSL_accept(serverssl), 0))
9658        goto end;
9659
9660    if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0))
9661        goto end;
9662    if (!TEST_size_t_eq(EVP_PKEY_get_bits(tmpkey), expdhsize))
9663        goto end;
9664
9665    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9666        goto end;
9667
9668    testresult = 1;
9669
9670 end:
9671    SSL_free(serverssl);
9672    SSL_free(clientssl);
9673    SSL_CTX_free(sctx);
9674    SSL_CTX_free(cctx);
9675    EVP_PKEY_free(tmpkey);
9676
9677    return testresult;
9678
9679}
9680# endif /* OPENSSL_NO_DH */
9681#endif /* OPENSSL_NO_TLS1_2 */
9682
9683#ifndef OSSL_NO_USABLE_TLS1_3
9684/*
9685 * Test that setting an SNI callback works with TLSv1.3. Specifically we check
9686 * that it works even without a certificate configured for the original
9687 * SSL_CTX
9688 */
9689static int test_sni_tls13(void)
9690{
9691    SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
9692    SSL *clientssl = NULL, *serverssl = NULL;
9693    int testresult = 0;
9694
9695    /* Reset callback counter */
9696    snicb = 0;
9697
9698    /* Create an initial SSL_CTX with no certificate configured */
9699    sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9700    if (!TEST_ptr(sctx))
9701        goto end;
9702    /* Require TLSv1.3 as a minimum */
9703    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9704                                       TLS_client_method(), TLS1_3_VERSION, 0,
9705                                       &sctx2, &cctx, cert, privkey)))
9706        goto end;
9707
9708    /* Set up SNI */
9709    if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
9710            || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
9711        goto end;
9712
9713    /*
9714     * Connection should still succeed because the final SSL_CTX has the right
9715     * certificates configured.
9716     */
9717    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
9718                                      &clientssl, NULL, NULL))
9719            || !TEST_true(create_ssl_connection(serverssl, clientssl,
9720                                                SSL_ERROR_NONE)))
9721        goto end;
9722
9723    /* We should have had the SNI callback called exactly once */
9724    if (!TEST_int_eq(snicb, 1))
9725        goto end;
9726
9727    testresult = 1;
9728
9729end:
9730    SSL_free(serverssl);
9731    SSL_free(clientssl);
9732    SSL_CTX_free(sctx2);
9733    SSL_CTX_free(sctx);
9734    SSL_CTX_free(cctx);
9735    return testresult;
9736}
9737
9738/*
9739 * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week
9740 * 0 = TLSv1.2
9741 * 1 = TLSv1.3
9742 */
9743static int test_ticket_lifetime(int idx)
9744{
9745    SSL_CTX *cctx = NULL, *sctx = NULL;
9746    SSL *clientssl = NULL, *serverssl = NULL;
9747    int testresult = 0;
9748    int version = TLS1_3_VERSION;
9749
9750#define ONE_WEEK_SEC (7 * 24 * 60 * 60)
9751#define TWO_WEEK_SEC (2 * ONE_WEEK_SEC)
9752
9753    if (idx == 0) {
9754#ifdef OPENSSL_NO_TLS1_2
9755        return TEST_skip("TLS 1.2 is disabled.");
9756#else
9757        version = TLS1_2_VERSION;
9758#endif
9759    }
9760
9761    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9762                                       TLS_client_method(), version, version,
9763                                       &sctx, &cctx, cert, privkey)))
9764        goto end;
9765
9766    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
9767                                      &clientssl, NULL, NULL)))
9768        goto end;
9769
9770    /*
9771     * Set the timeout to be more than 1 week
9772     * make sure the returned value is the default
9773     */
9774    if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC),
9775                      SSL_get_default_timeout(serverssl)))
9776        goto end;
9777
9778    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9779        goto end;
9780
9781    if (idx == 0) {
9782        /* TLSv1.2 uses the set value */
9783        if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC))
9784            goto end;
9785    } else {
9786        /* TLSv1.3 uses the limited value */
9787        if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC))
9788            goto end;
9789    }
9790    testresult = 1;
9791
9792end:
9793    SSL_free(serverssl);
9794    SSL_free(clientssl);
9795    SSL_CTX_free(sctx);
9796    SSL_CTX_free(cctx);
9797    return testresult;
9798}
9799#endif
9800/*
9801 * Test that setting an ALPN does not violate RFC
9802 */
9803static int test_set_alpn(void)
9804{
9805    SSL_CTX *ctx = NULL;
9806    SSL *ssl = NULL;
9807    int testresult = 0;
9808
9809    unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
9810    unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
9811    unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
9812    unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00};
9813    unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'};
9814    unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'};
9815
9816    /* Create an initial SSL_CTX with no certificate configured */
9817    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9818    if (!TEST_ptr(ctx))
9819        goto end;
9820
9821    /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
9822    if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
9823        goto end;
9824    if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
9825        goto end;
9826    if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
9827        goto end;
9828    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
9829        goto end;
9830    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
9831        goto end;
9832    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
9833        goto end;
9834    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
9835        goto end;
9836    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
9837        goto end;
9838    if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
9839        goto end;
9840
9841    ssl = SSL_new(ctx);
9842    if (!TEST_ptr(ssl))
9843        goto end;
9844
9845    if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
9846        goto end;
9847    if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
9848        goto end;
9849    if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
9850        goto end;
9851    if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
9852        goto end;
9853    if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
9854        goto end;
9855    if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
9856        goto end;
9857    if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
9858        goto end;
9859    if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
9860        goto end;
9861    if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
9862        goto end;
9863
9864    testresult = 1;
9865
9866end:
9867    SSL_free(ssl);
9868    SSL_CTX_free(ctx);
9869    return testresult;
9870}
9871
9872/*
9873 * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store.
9874 */
9875static int test_set_verify_cert_store_ssl_ctx(void)
9876{
9877   SSL_CTX *ctx = NULL;
9878   int testresult = 0;
9879   X509_STORE *store = NULL, *new_store = NULL,
9880              *cstore = NULL, *new_cstore = NULL;
9881
9882   /* Create an initial SSL_CTX. */
9883   ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9884   if (!TEST_ptr(ctx))
9885       goto end;
9886
9887   /* Retrieve verify store pointer. */
9888   if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
9889       goto end;
9890
9891   /* Retrieve chain store pointer. */
9892   if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
9893       goto end;
9894
9895   /* We haven't set any yet, so this should be NULL. */
9896   if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
9897       goto end;
9898
9899   /* Create stores. We use separate stores so pointers are different. */
9900   new_store = X509_STORE_new();
9901   if (!TEST_ptr(new_store))
9902       goto end;
9903
9904   new_cstore = X509_STORE_new();
9905   if (!TEST_ptr(new_cstore))
9906       goto end;
9907
9908   /* Set stores. */
9909   if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store)))
9910       goto end;
9911
9912   if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore)))
9913       goto end;
9914
9915   /* Should be able to retrieve the same pointer. */
9916   if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
9917       goto end;
9918
9919   if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
9920       goto end;
9921
9922   if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
9923       goto end;
9924
9925   /* Should be able to unset again. */
9926   if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL)))
9927       goto end;
9928
9929   if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL)))
9930       goto end;
9931
9932   /* Should now be NULL. */
9933   if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
9934       goto end;
9935
9936   if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
9937       goto end;
9938
9939   if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
9940       goto end;
9941
9942   testresult = 1;
9943
9944end:
9945   X509_STORE_free(new_store);
9946   X509_STORE_free(new_cstore);
9947   SSL_CTX_free(ctx);
9948   return testresult;
9949}
9950
9951/*
9952 * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store.
9953 */
9954static int test_set_verify_cert_store_ssl(void)
9955{
9956   SSL_CTX *ctx = NULL;
9957   SSL *ssl = NULL;
9958   int testresult = 0;
9959   X509_STORE *store = NULL, *new_store = NULL,
9960              *cstore = NULL, *new_cstore = NULL;
9961
9962   /* Create an initial SSL_CTX. */
9963   ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9964   if (!TEST_ptr(ctx))
9965       goto end;
9966
9967   /* Create an SSL object. */
9968   ssl = SSL_new(ctx);
9969   if (!TEST_ptr(ssl))
9970       goto end;
9971
9972   /* Retrieve verify store pointer. */
9973   if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
9974       goto end;
9975
9976   /* Retrieve chain store pointer. */
9977   if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
9978       goto end;
9979
9980   /* We haven't set any yet, so this should be NULL. */
9981   if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
9982       goto end;
9983
9984   /* Create stores. We use separate stores so pointers are different. */
9985   new_store = X509_STORE_new();
9986   if (!TEST_ptr(new_store))
9987       goto end;
9988
9989   new_cstore = X509_STORE_new();
9990   if (!TEST_ptr(new_cstore))
9991       goto end;
9992
9993   /* Set stores. */
9994   if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store)))
9995       goto end;
9996
9997   if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore)))
9998       goto end;
9999
10000   /* Should be able to retrieve the same pointer. */
10001   if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10002       goto end;
10003
10004   if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10005       goto end;
10006
10007   if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
10008       goto end;
10009
10010   /* Should be able to unset again. */
10011   if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL)))
10012       goto end;
10013
10014   if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL)))
10015       goto end;
10016
10017   /* Should now be NULL. */
10018   if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10019       goto end;
10020
10021   if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10022       goto end;
10023
10024   if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10025       goto end;
10026
10027   testresult = 1;
10028
10029end:
10030   X509_STORE_free(new_store);
10031   X509_STORE_free(new_cstore);
10032   SSL_free(ssl);
10033   SSL_CTX_free(ctx);
10034   return testresult;
10035}
10036
10037
10038static int test_inherit_verify_param(void)
10039{
10040    int testresult = 0;
10041
10042    SSL_CTX *ctx = NULL;
10043    X509_VERIFY_PARAM *cp = NULL;
10044    SSL *ssl = NULL;
10045    X509_VERIFY_PARAM *sp = NULL;
10046    int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
10047
10048    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10049    if (!TEST_ptr(ctx))
10050        goto end;
10051
10052    cp = SSL_CTX_get0_param(ctx);
10053    if (!TEST_ptr(cp))
10054        goto end;
10055    if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
10056        goto end;
10057
10058    X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
10059
10060    ssl = SSL_new(ctx);
10061    if (!TEST_ptr(ssl))
10062        goto end;
10063
10064    sp = SSL_get0_param(ssl);
10065    if (!TEST_ptr(sp))
10066        goto end;
10067    if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
10068        goto end;
10069
10070    testresult = 1;
10071
10072 end:
10073    SSL_free(ssl);
10074    SSL_CTX_free(ctx);
10075
10076    return testresult;
10077}
10078
10079static int test_load_dhfile(void)
10080{
10081#ifndef OPENSSL_NO_DH
10082    int testresult = 0;
10083
10084    SSL_CTX *ctx = NULL;
10085    SSL_CONF_CTX *cctx = NULL;
10086
10087    if (dhfile == NULL)
10088        return 1;
10089
10090    if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()))
10091        || !TEST_ptr(cctx = SSL_CONF_CTX_new()))
10092        goto end;
10093
10094    SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
10095    SSL_CONF_CTX_set_flags(cctx,
10096                           SSL_CONF_FLAG_CERTIFICATE
10097                           | SSL_CONF_FLAG_SERVER
10098                           | SSL_CONF_FLAG_FILE);
10099
10100    if (!TEST_int_eq(SSL_CONF_cmd(cctx, "DHParameters", dhfile), 2))
10101        goto end;
10102
10103    testresult = 1;
10104end:
10105    SSL_CONF_CTX_free(cctx);
10106    SSL_CTX_free(ctx);
10107
10108    return testresult;
10109#else
10110    return TEST_skip("DH not supported by this build");
10111#endif
10112}
10113
10114#if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
10115/*
10116 * Test TLSv1.2 with a pipeline capable cipher. TLSv1.3 and DTLS do not
10117 * support this yet. The only pipeline capable cipher that we have is in the
10118 * dasync engine (providers don't support this yet), so we have to use
10119 * deprecated APIs for this test.
10120 *
10121 * Test 0: Client has pipelining enabled, server does not
10122 * Test 1: Server has pipelining enabled, client does not
10123 * Test 2: Client has pipelining enabled, server does not: not enough data to
10124 *         fill all the pipelines
10125 * Test 3: Client has pipelining enabled, server does not: not enough data to
10126 *         fill all the pipelines by more than a full pipeline's worth
10127 * Test 4: Client has pipelining enabled, server does not: more data than all
10128 *         the available pipelines can take
10129 * Test 5: Client has pipelining enabled, server does not: Maximum size pipeline
10130 */
10131static int test_pipelining(int idx)
10132{
10133    SSL_CTX *cctx = NULL, *sctx = NULL;
10134    SSL *clientssl = NULL, *serverssl = NULL, *peera, *peerb;
10135    int testresult = 0, numreads;
10136    /* A 55 byte message */
10137    unsigned char *msg = (unsigned char *)
10138        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123";
10139    size_t written, readbytes, offset, msglen, fragsize = 10, numpipes = 5;
10140    size_t expectedreads;
10141    unsigned char *buf = NULL;
10142    ENGINE *e;
10143
10144    if (!TEST_ptr(e = ENGINE_by_id("dasync")))
10145        return 0;
10146
10147    if (!TEST_true(ENGINE_init(e))) {
10148        ENGINE_free(e);
10149        return 0;
10150    }
10151
10152    if (!TEST_true(ENGINE_register_ciphers(e)))
10153        goto end;
10154
10155    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10156                                       TLS_client_method(), 0,
10157                                       TLS1_2_VERSION, &sctx, &cctx, cert,
10158                                       privkey)))
10159        goto end;
10160
10161    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10162                                      &clientssl, NULL, NULL)))
10163        goto end;
10164
10165    if (!TEST_true(SSL_set_cipher_list(clientssl, "AES128-SHA")))
10166        goto end;
10167
10168    /* peera is always configured for pipelining, while peerb is not. */
10169    if (idx == 1) {
10170        peera = serverssl;
10171        peerb = clientssl;
10172
10173    } else {
10174        peera = clientssl;
10175        peerb = serverssl;
10176    }
10177
10178    if (idx == 5) {
10179        numpipes = 2;
10180        /* Maximum allowed fragment size */
10181        fragsize = SSL3_RT_MAX_PLAIN_LENGTH;
10182        msglen = fragsize * numpipes;
10183        msg = OPENSSL_malloc(msglen);
10184        if (!TEST_ptr(msg))
10185            goto end;
10186        if (!TEST_int_gt(RAND_bytes_ex(libctx, msg, msglen, 0), 0))
10187            goto end;
10188    } else if (idx == 4) {
10189        msglen = 55;
10190    } else {
10191        msglen = 50;
10192    }
10193    if (idx == 2)
10194        msglen -= 2; /* Send 2 less bytes */
10195    else if (idx == 3)
10196        msglen -= 12; /* Send 12 less bytes */
10197
10198    buf = OPENSSL_malloc(msglen);
10199    if (!TEST_ptr(buf))
10200        goto end;
10201
10202    if (idx == 5) {
10203        /*
10204         * Test that setting a split send fragment longer than the maximum
10205         * allowed fails
10206         */
10207        if (!TEST_false(SSL_set_split_send_fragment(peera, fragsize + 1)))
10208            goto end;
10209    }
10210
10211    /*
10212     * In the normal case. We have 5 pipelines with 10 bytes per pipeline
10213     * (50 bytes in total). This is a ridiculously small number of bytes -
10214     * but sufficient for our purposes
10215     */
10216    if (!TEST_true(SSL_set_max_pipelines(peera, numpipes))
10217            || !TEST_true(SSL_set_split_send_fragment(peera, fragsize)))
10218        goto end;
10219
10220    if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10221        goto end;
10222
10223    /* Write some data from peera to peerb */
10224    if (!TEST_true(SSL_write_ex(peera, msg, msglen, &written))
10225        || !TEST_size_t_eq(written, msglen))
10226        goto end;
10227
10228    /*
10229     * If the pipelining code worked, then we expect all |numpipes| pipelines to
10230     * have been used - except in test 3 where only |numpipes - 1| pipelines
10231     * will be used. This will result in |numpipes| records (|numpipes - 1| for
10232     * test 3) having been sent to peerb. Since peerb is not using read_ahead we
10233     * expect this to be read in |numpipes| or |numpipes - 1| separate
10234     * SSL_read_ex calls. In the case of test 4, there is then one additional
10235     * read for left over data that couldn't fit in the previous pipelines
10236     */
10237    for (offset = 0, numreads = 0;
10238         offset < msglen;
10239         offset += readbytes, numreads++) {
10240        if (!TEST_true(SSL_read_ex(peerb, buf + offset,
10241                                   msglen - offset, &readbytes)))
10242            goto end;
10243    }
10244
10245    expectedreads = idx == 4 ? numpipes + 1
10246                             : (idx == 3 ? numpipes - 1 : numpipes);
10247    if (!TEST_mem_eq(msg, msglen, buf, offset)
10248            || !TEST_int_eq(numreads, expectedreads))
10249        goto end;
10250
10251    /*
10252     * Write some data from peerb to peera. We do this in up to |numpipes + 1|
10253     * chunks to exercise the read pipelining code on peera.
10254     */
10255    for (offset = 0; offset < msglen; offset += fragsize) {
10256        size_t sendlen = msglen - offset;
10257
10258        if (sendlen > fragsize)
10259            sendlen = fragsize;
10260        if (!TEST_true(SSL_write_ex(peerb, msg + offset, sendlen, &written))
10261                || !TEST_size_t_eq(written, sendlen))
10262            goto end;
10263    }
10264
10265    /*
10266     * The data was written in |numpipes|, |numpipes - 1| or |numpipes + 1|
10267     * separate chunks (depending on which test we are running). If the
10268     * pipelining is working then we expect peera to read up to numpipes chunks
10269     * and process them in parallel, giving back the complete result in a single
10270     * call to SSL_read_ex
10271     */
10272    if (!TEST_true(SSL_read_ex(peera, buf, msglen, &readbytes))
10273            || !TEST_size_t_le(readbytes, msglen))
10274        goto end;
10275
10276    if (idx == 4) {
10277        size_t readbytes2;
10278
10279        if (!TEST_true(SSL_read_ex(peera, buf + readbytes,
10280                                   msglen - readbytes, &readbytes2)))
10281            goto end;
10282        readbytes += readbytes2;
10283        if (!TEST_size_t_le(readbytes, msglen))
10284            goto end;
10285    }
10286
10287    if (!TEST_mem_eq(msg, msglen, buf, readbytes))
10288        goto end;
10289
10290    testresult = 1;
10291end:
10292    SSL_free(serverssl);
10293    SSL_free(clientssl);
10294    SSL_CTX_free(sctx);
10295    SSL_CTX_free(cctx);
10296    ENGINE_unregister_ciphers(e);
10297    ENGINE_finish(e);
10298    ENGINE_free(e);
10299    OPENSSL_free(buf);
10300    if (idx == 5)
10301        OPENSSL_free(msg);
10302    return testresult;
10303}
10304#endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */
10305
10306OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config dhfile\n")
10307
10308int setup_tests(void)
10309{
10310    char *modulename;
10311    char *configfile;
10312
10313    libctx = OSSL_LIB_CTX_new();
10314    if (!TEST_ptr(libctx))
10315        return 0;
10316
10317    defctxnull = OSSL_PROVIDER_load(NULL, "null");
10318
10319    /*
10320     * Verify that the default and fips providers in the default libctx are not
10321     * available
10322     */
10323    if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
10324            || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
10325        return 0;
10326
10327    if (!test_skip_common_options()) {
10328        TEST_error("Error parsing test options\n");
10329        return 0;
10330    }
10331
10332    if (!TEST_ptr(certsdir = test_get_argument(0))
10333            || !TEST_ptr(srpvfile = test_get_argument(1))
10334            || !TEST_ptr(tmpfilename = test_get_argument(2))
10335            || !TEST_ptr(modulename = test_get_argument(3))
10336            || !TEST_ptr(configfile = test_get_argument(4))
10337            || !TEST_ptr(dhfile = test_get_argument(5)))
10338        return 0;
10339
10340    if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
10341        return 0;
10342
10343    /* Check we have the expected provider available */
10344    if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
10345        return 0;
10346
10347    /* Check the default provider is not available */
10348    if (strcmp(modulename, "default") != 0
10349            && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
10350        return 0;
10351
10352    if (strcmp(modulename, "fips") == 0)
10353        is_fips = 1;
10354
10355    /*
10356     * We add, but don't load the test "tls-provider". We'll load it when we
10357     * need it.
10358     */
10359    if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider",
10360                                             tls_provider_init)))
10361        return 0;
10362
10363
10364    if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
10365#ifdef OPENSSL_NO_CRYPTO_MDEBUG
10366        TEST_error("not supported in this build");
10367        return 0;
10368#else
10369        int i, mcount, rcount, fcount;
10370
10371        for (i = 0; i < 4; i++)
10372            test_export_key_mat(i);
10373        CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
10374        test_printf_stdout("malloc %d realloc %d free %d\n",
10375                mcount, rcount, fcount);
10376        return 1;
10377#endif
10378    }
10379
10380    cert = test_mk_file_path(certsdir, "servercert.pem");
10381    if (cert == NULL)
10382        goto err;
10383
10384    privkey = test_mk_file_path(certsdir, "serverkey.pem");
10385    if (privkey == NULL)
10386        goto err;
10387
10388    cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
10389    if (cert2 == NULL)
10390        goto err;
10391
10392    privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
10393    if (privkey2 == NULL)
10394        goto err;
10395
10396    cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem");
10397    if (cert1024 == NULL)
10398        goto err;
10399
10400    privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem");
10401    if (privkey1024 == NULL)
10402        goto err;
10403
10404    cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem");
10405    if (cert3072 == NULL)
10406        goto err;
10407
10408    privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem");
10409    if (privkey3072 == NULL)
10410        goto err;
10411
10412    cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem");
10413    if (cert4096 == NULL)
10414        goto err;
10415
10416    privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem");
10417    if (privkey4096 == NULL)
10418        goto err;
10419
10420    cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem");
10421    if (cert8192 == NULL)
10422        goto err;
10423
10424    privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem");
10425    if (privkey8192 == NULL)
10426        goto err;
10427
10428#if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
10429# if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
10430    ADD_ALL_TESTS(test_ktls, NUM_KTLS_TEST_CIPHERS * 4);
10431    ADD_ALL_TESTS(test_ktls_sendfile, NUM_KTLS_TEST_CIPHERS);
10432# endif
10433#endif
10434    ADD_TEST(test_large_message_tls);
10435    ADD_TEST(test_large_message_tls_read_ahead);
10436#ifndef OPENSSL_NO_DTLS
10437    ADD_TEST(test_large_message_dtls);
10438#endif
10439    ADD_ALL_TESTS(test_large_app_data, 28);
10440    ADD_TEST(test_cleanse_plaintext);
10441#ifndef OPENSSL_NO_OCSP
10442    ADD_TEST(test_tlsext_status_type);
10443#endif
10444    ADD_TEST(test_session_with_only_int_cache);
10445    ADD_TEST(test_session_with_only_ext_cache);
10446    ADD_TEST(test_session_with_both_cache);
10447    ADD_TEST(test_session_wo_ca_names);
10448#ifndef OSSL_NO_USABLE_TLS1_3
10449    ADD_ALL_TESTS(test_stateful_tickets, 3);
10450    ADD_ALL_TESTS(test_stateless_tickets, 3);
10451    ADD_TEST(test_psk_tickets);
10452    ADD_ALL_TESTS(test_extra_tickets, 6);
10453#endif
10454    ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
10455    ADD_TEST(test_ssl_bio_pop_next_bio);
10456    ADD_TEST(test_ssl_bio_pop_ssl_bio);
10457    ADD_TEST(test_ssl_bio_change_rbio);
10458    ADD_TEST(test_ssl_bio_change_wbio);
10459#if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
10460    ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
10461    ADD_TEST(test_keylog);
10462#endif
10463#ifndef OSSL_NO_USABLE_TLS1_3
10464    ADD_TEST(test_keylog_no_master_key);
10465#endif
10466    ADD_TEST(test_client_cert_verify_cb);
10467    ADD_TEST(test_ssl_build_cert_chain);
10468    ADD_TEST(test_ssl_ctx_build_cert_chain);
10469#ifndef OPENSSL_NO_TLS1_2
10470    ADD_TEST(test_client_hello_cb);
10471    ADD_TEST(test_no_ems);
10472    ADD_TEST(test_ccs_change_cipher);
10473#endif
10474#ifndef OSSL_NO_USABLE_TLS1_3
10475    ADD_ALL_TESTS(test_early_data_read_write, 6);
10476    /*
10477     * We don't do replay tests for external PSK. Replay protection isn't used
10478     * in that scenario.
10479     */
10480    ADD_ALL_TESTS(test_early_data_replay, 2);
10481    ADD_ALL_TESTS(test_early_data_skip, OSSL_NELEM(ciphersuites) * 3);
10482    ADD_ALL_TESTS(test_early_data_skip_hrr, OSSL_NELEM(ciphersuites) * 3);
10483    ADD_ALL_TESTS(test_early_data_skip_hrr_fail, OSSL_NELEM(ciphersuites) * 3);
10484    ADD_ALL_TESTS(test_early_data_skip_abort, OSSL_NELEM(ciphersuites) * 3);
10485    ADD_ALL_TESTS(test_early_data_not_sent, 3);
10486    ADD_ALL_TESTS(test_early_data_psk, 8);
10487    ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 5);
10488    ADD_ALL_TESTS(test_early_data_not_expected, 3);
10489# ifndef OPENSSL_NO_TLS1_2
10490    ADD_ALL_TESTS(test_early_data_tls1_2, 3);
10491# endif
10492#endif
10493#ifndef OSSL_NO_USABLE_TLS1_3
10494    ADD_ALL_TESTS(test_set_ciphersuite, 10);
10495    ADD_TEST(test_ciphersuite_change);
10496    ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
10497# ifdef OPENSSL_NO_PSK
10498    ADD_ALL_TESTS(test_tls13_psk, 1);
10499# else
10500    ADD_ALL_TESTS(test_tls13_psk, 4);
10501# endif  /* OPENSSL_NO_PSK */
10502# ifndef OPENSSL_NO_TLS1_2
10503    /* Test with both TLSv1.3 and 1.2 versions */
10504    ADD_ALL_TESTS(test_key_exchange, 14);
10505#  if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH)
10506    ADD_ALL_TESTS(test_negotiated_group,
10507                  4 * (OSSL_NELEM(ecdhe_kexch_groups)
10508                       + OSSL_NELEM(ffdhe_kexch_groups)));
10509#  endif
10510# else
10511    /* Test with only TLSv1.3 versions */
10512    ADD_ALL_TESTS(test_key_exchange, 12);
10513# endif
10514    ADD_ALL_TESTS(test_custom_exts, 6);
10515    ADD_TEST(test_stateless);
10516    ADD_TEST(test_pha_key_update);
10517#else
10518    ADD_ALL_TESTS(test_custom_exts, 3);
10519#endif
10520    ADD_ALL_TESTS(test_export_key_mat, 6);
10521#ifndef OSSL_NO_USABLE_TLS1_3
10522    ADD_ALL_TESTS(test_export_key_mat_early, 3);
10523    ADD_TEST(test_key_update);
10524    ADD_ALL_TESTS(test_key_update_peer_in_write, 2);
10525    ADD_ALL_TESTS(test_key_update_peer_in_read, 2);
10526    ADD_ALL_TESTS(test_key_update_local_in_write, 2);
10527    ADD_ALL_TESTS(test_key_update_local_in_read, 2);
10528#endif
10529    ADD_ALL_TESTS(test_ssl_clear, 2);
10530    ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
10531#if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
10532    ADD_ALL_TESTS(test_srp, 6);
10533#endif
10534    ADD_ALL_TESTS(test_info_callback, 6);
10535    ADD_ALL_TESTS(test_ssl_pending, 2);
10536    ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
10537    ADD_ALL_TESTS(test_ticket_callbacks, 20);
10538    ADD_ALL_TESTS(test_shutdown, 7);
10539    ADD_ALL_TESTS(test_incorrect_shutdown, 2);
10540    ADD_ALL_TESTS(test_cert_cb, 6);
10541    ADD_ALL_TESTS(test_client_cert_cb, 2);
10542    ADD_ALL_TESTS(test_ca_names, 3);
10543#ifndef OPENSSL_NO_TLS1_2
10544    ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
10545#endif
10546    ADD_ALL_TESTS(test_servername, 10);
10547#if !defined(OPENSSL_NO_EC) \
10548    && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
10549    ADD_ALL_TESTS(test_sigalgs_available, 6);
10550#endif
10551#ifndef OPENSSL_NO_TLS1_3
10552    ADD_ALL_TESTS(test_pluggable_group, 2);
10553#endif
10554#ifndef OPENSSL_NO_TLS1_2
10555    ADD_TEST(test_ssl_dup);
10556# ifndef OPENSSL_NO_DH
10557    ADD_ALL_TESTS(test_set_tmp_dh, 11);
10558    ADD_ALL_TESTS(test_dh_auto, 7);
10559# endif
10560#endif
10561#ifndef OSSL_NO_USABLE_TLS1_3
10562    ADD_TEST(test_sni_tls13);
10563    ADD_ALL_TESTS(test_ticket_lifetime, 2);
10564#endif
10565    ADD_TEST(test_inherit_verify_param);
10566    ADD_TEST(test_set_alpn);
10567    ADD_TEST(test_set_verify_cert_store_ssl_ctx);
10568    ADD_TEST(test_set_verify_cert_store_ssl);
10569    ADD_ALL_TESTS(test_session_timeout, 1);
10570    ADD_TEST(test_load_dhfile);
10571#if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
10572    ADD_ALL_TESTS(test_serverinfo_custom, 4);
10573#endif
10574#if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
10575    ADD_ALL_TESTS(test_pipelining, 6);
10576#endif
10577    return 1;
10578
10579 err:
10580    OPENSSL_free(cert);
10581    OPENSSL_free(privkey);
10582    OPENSSL_free(cert2);
10583    OPENSSL_free(privkey2);
10584    return 0;
10585}
10586
10587void cleanup_tests(void)
10588{
10589# if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH)
10590    EVP_PKEY_free(tmp_dh_params);
10591#endif
10592    OPENSSL_free(cert);
10593    OPENSSL_free(privkey);
10594    OPENSSL_free(cert2);
10595    OPENSSL_free(privkey2);
10596    OPENSSL_free(cert1024);
10597    OPENSSL_free(privkey1024);
10598    OPENSSL_free(cert3072);
10599    OPENSSL_free(privkey3072);
10600    OPENSSL_free(cert4096);
10601    OPENSSL_free(privkey4096);
10602    OPENSSL_free(cert8192);
10603    OPENSSL_free(privkey8192);
10604    bio_s_mempacket_test_free();
10605    bio_s_always_retry_free();
10606    OSSL_PROVIDER_unload(defctxnull);
10607    OSSL_LIB_CTX_free(libctx);
10608}
10609