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