xref: /freebsd/crypto/openssl/test/sslapitest.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
1 /*
2  * Copyright 2016-2025 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/tlsgroups.h"
43 #include "internal/ktls.h"
44 #include "internal/ssl_unwrap.h"
45 #include "../ssl/ssl_local.h"
46 #include "../ssl/record/methods/recmethod_local.h"
47 #include "filterprov.h"
48 
49 #undef OSSL_NO_USABLE_TLS1_3
50 #if defined(OPENSSL_NO_TLS1_3) \
51     || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH))
52 /*
53  * If we don't have ec or dh then there are no built-in groups that are usable
54  * with TLSv1.3
55  */
56 #define OSSL_NO_USABLE_TLS1_3
57 #endif
58 
59 /* Defined in tls-provider.c */
60 int tls_provider_init(const OSSL_CORE_HANDLE *handle,
61     const OSSL_DISPATCH *in,
62     const OSSL_DISPATCH **out,
63     void **provctx);
64 
65 static OSSL_LIB_CTX *libctx = NULL;
66 static OSSL_PROVIDER *defctxnull = NULL;
67 
68 #ifndef OSSL_NO_USABLE_TLS1_3
69 
70 static SSL_SESSION *clientpsk = NULL;
71 static SSL_SESSION *serverpsk = NULL;
72 static const char *pskid = "Identity";
73 static const char *srvid;
74 
75 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
76     size_t *idlen, SSL_SESSION **sess);
77 static int find_session_cb(SSL *ssl, const unsigned char *identity,
78     size_t identity_len, SSL_SESSION **sess);
79 
80 static int use_session_cb_cnt = 0;
81 static int find_session_cb_cnt = 0;
82 static int end_of_early_data = 0;
83 #endif
84 
85 static char *certsdir = NULL;
86 static char *cert = NULL;
87 static char *privkey = NULL;
88 static char *cert2 = NULL;
89 static char *privkey2 = NULL;
90 static char *cert1024 = NULL;
91 static char *privkey1024 = NULL;
92 static char *cert3072 = NULL;
93 static char *privkey3072 = NULL;
94 static char *cert4096 = NULL;
95 static char *privkey4096 = NULL;
96 static char *cert8192 = NULL;
97 static char *privkey8192 = NULL;
98 static char *srpvfile = NULL;
99 static char *tmpfilename = NULL;
100 static char *dhfile = NULL;
101 static char *datadir = NULL;
102 
103 static int is_fips = 0;
104 static int fips_ems_check = 0;
105 
106 #define LOG_BUFFER_SIZE 2048
107 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = { 0 };
108 static size_t server_log_buffer_index = 0;
109 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = { 0 };
110 static size_t client_log_buffer_index = 0;
111 static int error_writing_log = 0;
112 
113 #ifndef OPENSSL_NO_OCSP
114 static const unsigned char orespder[] = "Dummy OCSP Response";
115 static int ocsp_server_called = 0;
116 static int ocsp_client_called = 0;
117 
118 static int cdummyarg = 1;
119 static X509 *ocspcert = NULL;
120 #endif
121 
122 #define CLIENT_VERSION_LEN 2
123 
124 /* The ssltrace test assumes some options are switched on/off */
125 #if !defined(OPENSSL_NO_SSL_TRACE)                                \
126     && defined(OPENSSL_NO_BROTLI) && defined(OPENSSL_NO_ZSTD)     \
127     && !defined(OPENSSL_NO_ECX) && !defined(OPENSSL_NO_DH)        \
128     && !defined(OPENSSL_NO_ML_DSA) && !defined(OPENSSL_NO_ML_KEM) \
129     && !defined(OPENSSL_NO_TLS1_3)
130 #define DO_SSL_TRACE_TEST
131 #endif
132 
133 /*
134  * This structure is used to validate that the correct number of log messages
135  * of various types are emitted when emitting secret logs.
136  */
137 struct sslapitest_log_counts {
138     unsigned int rsa_key_exchange_count;
139     unsigned int master_secret_count;
140     unsigned int client_early_secret_count;
141     unsigned int client_handshake_secret_count;
142     unsigned int server_handshake_secret_count;
143     unsigned int client_application_secret_count;
144     unsigned int server_application_secret_count;
145     unsigned int early_exporter_secret_count;
146     unsigned int exporter_secret_count;
147 };
148 
149 static int hostname_cb(SSL *s, int *al, void *arg)
150 {
151     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
152 
153     if (hostname != NULL && (strcmp(hostname, "goodhost") == 0 || strcmp(hostname, "altgoodhost") == 0))
154         return SSL_TLSEXT_ERR_OK;
155 
156     return SSL_TLSEXT_ERR_NOACK;
157 }
158 
159 static void client_keylog_callback(const SSL *ssl, const char *line)
160 {
161     int line_length = strlen(line);
162 
163     /* If the log doesn't fit, error out. */
164     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
165         TEST_info("Client log too full");
166         error_writing_log = 1;
167         return;
168     }
169 
170     strcat(client_log_buffer, line);
171     client_log_buffer_index += line_length;
172     client_log_buffer[client_log_buffer_index++] = '\n';
173 }
174 
175 static void server_keylog_callback(const SSL *ssl, const char *line)
176 {
177     int line_length = strlen(line);
178 
179     /* If the log doesn't fit, error out. */
180     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
181         TEST_info("Server log too full");
182         error_writing_log = 1;
183         return;
184     }
185 
186     strcat(server_log_buffer, line);
187     server_log_buffer_index += line_length;
188     server_log_buffer[server_log_buffer_index++] = '\n';
189 }
190 
191 static int compare_hex_encoded_buffer(const char *hex_encoded,
192     size_t hex_length,
193     const uint8_t *raw,
194     size_t raw_length)
195 {
196     size_t i, j;
197     char hexed[3];
198 
199     if (!TEST_size_t_eq(raw_length * 2, hex_length))
200         return 1;
201 
202     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
203         BIO_snprintf(hexed, sizeof(hexed), "%02x", raw[i]);
204         if (!TEST_int_eq(hexed[0], hex_encoded[j])
205             || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
206             return 1;
207     }
208 
209     return 0;
210 }
211 
212 static int test_keylog_output(char *buffer, const SSL *ssl,
213     const SSL_SESSION *session,
214     struct sslapitest_log_counts *expected)
215 {
216     char *token = NULL;
217     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = { 0 };
218     size_t client_random_size = SSL3_RANDOM_SIZE;
219     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = { 0 };
220     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
221     unsigned int rsa_key_exchange_count = 0;
222     unsigned int master_secret_count = 0;
223     unsigned int client_early_secret_count = 0;
224     unsigned int client_handshake_secret_count = 0;
225     unsigned int server_handshake_secret_count = 0;
226     unsigned int client_application_secret_count = 0;
227     unsigned int server_application_secret_count = 0;
228     unsigned int early_exporter_secret_count = 0;
229     unsigned int exporter_secret_count = 0;
230 
231     for (token = strtok(buffer, " \n"); token != NULL;
232         token = strtok(NULL, " \n")) {
233         if (strcmp(token, "RSA") == 0) {
234             /*
235              * Premaster secret. Tokens should be: 16 ASCII bytes of
236              * hex-encoded encrypted secret, then the hex-encoded pre-master
237              * secret.
238              */
239             if (!TEST_ptr(token = strtok(NULL, " \n")))
240                 return 0;
241             if (!TEST_size_t_eq(strlen(token), 16))
242                 return 0;
243             if (!TEST_ptr(token = strtok(NULL, " \n")))
244                 return 0;
245             /*
246              * We can't sensibly check the log because the premaster secret is
247              * transient, and OpenSSL doesn't keep hold of it once the master
248              * secret is generated.
249              */
250             rsa_key_exchange_count++;
251         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
252             /*
253              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
254              * client random, then the hex-encoded master secret.
255              */
256             client_random_size = SSL_get_client_random(ssl,
257                 actual_client_random,
258                 SSL3_RANDOM_SIZE);
259             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
260                 return 0;
261 
262             if (!TEST_ptr(token = strtok(NULL, " \n")))
263                 return 0;
264             if (!TEST_size_t_eq(strlen(token), 64))
265                 return 0;
266             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
267                     actual_client_random,
268                     client_random_size)))
269                 return 0;
270 
271             if (!TEST_ptr(token = strtok(NULL, " \n")))
272                 return 0;
273             master_key_size = SSL_SESSION_get_master_key(session,
274                 actual_master_key,
275                 master_key_size);
276             if (!TEST_size_t_ne(master_key_size, 0))
277                 return 0;
278             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
279                     actual_master_key,
280                     master_key_size)))
281                 return 0;
282             master_secret_count++;
283         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
284             || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
285             || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
286             || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
287             || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
288             || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
289             || strcmp(token, "EXPORTER_SECRET") == 0) {
290             /*
291              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
292              * client random, and then the hex-encoded secret. In this case,
293              * we treat all of these secrets identically and then just
294              * distinguish between them when counting what we saw.
295              */
296             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
297                 client_early_secret_count++;
298             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
299                 client_handshake_secret_count++;
300             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
301                 server_handshake_secret_count++;
302             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
303                 client_application_secret_count++;
304             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
305                 server_application_secret_count++;
306             else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
307                 early_exporter_secret_count++;
308             else if (strcmp(token, "EXPORTER_SECRET") == 0)
309                 exporter_secret_count++;
310 
311             client_random_size = SSL_get_client_random(ssl,
312                 actual_client_random,
313                 SSL3_RANDOM_SIZE);
314             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
315                 return 0;
316 
317             if (!TEST_ptr(token = strtok(NULL, " \n")))
318                 return 0;
319             if (!TEST_size_t_eq(strlen(token), 64))
320                 return 0;
321             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
322                     actual_client_random,
323                     client_random_size)))
324                 return 0;
325 
326             if (!TEST_ptr(token = strtok(NULL, " \n")))
327                 return 0;
328         } else {
329             TEST_info("Unexpected token %s\n", token);
330             return 0;
331         }
332     }
333 
334     /* Got what we expected? */
335     if (!TEST_size_t_eq(rsa_key_exchange_count,
336             expected->rsa_key_exchange_count)
337         || !TEST_size_t_eq(master_secret_count,
338             expected->master_secret_count)
339         || !TEST_size_t_eq(client_early_secret_count,
340             expected->client_early_secret_count)
341         || !TEST_size_t_eq(client_handshake_secret_count,
342             expected->client_handshake_secret_count)
343         || !TEST_size_t_eq(server_handshake_secret_count,
344             expected->server_handshake_secret_count)
345         || !TEST_size_t_eq(client_application_secret_count,
346             expected->client_application_secret_count)
347         || !TEST_size_t_eq(server_application_secret_count,
348             expected->server_application_secret_count)
349         || !TEST_size_t_eq(early_exporter_secret_count,
350             expected->early_exporter_secret_count)
351         || !TEST_size_t_eq(exporter_secret_count,
352             expected->exporter_secret_count))
353         return 0;
354     return 1;
355 }
356 
357 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
358 static int test_keylog(void)
359 {
360     SSL_CTX *cctx = NULL, *sctx = NULL;
361     SSL *clientssl = NULL, *serverssl = NULL;
362     int testresult = 0;
363     struct sslapitest_log_counts expected;
364 
365     /* Clean up logging space */
366     memset(&expected, 0, sizeof(expected));
367     memset(client_log_buffer, 0, sizeof(client_log_buffer));
368     memset(server_log_buffer, 0, sizeof(server_log_buffer));
369     client_log_buffer_index = 0;
370     server_log_buffer_index = 0;
371     error_writing_log = 0;
372 
373     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
374             TLS_client_method(),
375             TLS1_VERSION, 0,
376             &sctx, &cctx, cert, privkey)))
377         return 0;
378 
379     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
380     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
381     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
382 
383     /* We also want to ensure that we use RSA-based key exchange. */
384     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
385         goto end;
386 
387     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
388         || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
389         goto end;
390     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
391     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
392             == client_keylog_callback))
393         goto end;
394     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
395     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
396             == server_keylog_callback))
397         goto end;
398 
399     /* Now do a handshake and check that the logs have been written to. */
400     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
401             &clientssl, NULL, NULL))
402         || !TEST_true(create_ssl_connection(serverssl, clientssl,
403             SSL_ERROR_NONE))
404         || !TEST_false(error_writing_log)
405         || !TEST_int_gt(client_log_buffer_index, 0)
406         || !TEST_int_gt(server_log_buffer_index, 0))
407         goto end;
408 
409     /*
410      * Now we want to test that our output data was vaguely sensible. We
411      * do that by using strtok and confirming that we have more or less the
412      * data we expect. For both client and server, we expect to see one master
413      * secret. The client should also see an RSA key exchange.
414      */
415     expected.rsa_key_exchange_count = 1;
416     expected.master_secret_count = 1;
417     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
418             SSL_get_session(clientssl), &expected)))
419         goto end;
420 
421     expected.rsa_key_exchange_count = 0;
422     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
423             SSL_get_session(serverssl), &expected)))
424         goto end;
425 
426     testresult = 1;
427 
428 end:
429     SSL_free(serverssl);
430     SSL_free(clientssl);
431     SSL_CTX_free(sctx);
432     SSL_CTX_free(cctx);
433 
434     return testresult;
435 }
436 #endif
437 
438 #ifndef OSSL_NO_USABLE_TLS1_3
439 static int test_keylog_no_master_key(void)
440 {
441     SSL_CTX *cctx = NULL, *sctx = NULL;
442     SSL *clientssl = NULL, *serverssl = NULL;
443     SSL_SESSION *sess = NULL;
444     int testresult = 0;
445     struct sslapitest_log_counts expected;
446     unsigned char buf[1];
447     size_t readbytes, written;
448 
449     /* Clean up logging space */
450     memset(&expected, 0, sizeof(expected));
451     memset(client_log_buffer, 0, sizeof(client_log_buffer));
452     memset(server_log_buffer, 0, sizeof(server_log_buffer));
453     client_log_buffer_index = 0;
454     server_log_buffer_index = 0;
455     error_writing_log = 0;
456 
457     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
458             TLS_client_method(), TLS1_VERSION, 0,
459             &sctx, &cctx, cert, privkey))
460         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
461             SSL3_RT_MAX_PLAIN_LENGTH)))
462         return 0;
463 
464     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
465         || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
466         goto end;
467 
468     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
469     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
470             == client_keylog_callback))
471         goto end;
472 
473     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
474     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
475             == server_keylog_callback))
476         goto end;
477 
478     /* Now do a handshake and check that the logs have been written to. */
479     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
480             &clientssl, NULL, NULL))
481         || !TEST_true(create_ssl_connection(serverssl, clientssl,
482             SSL_ERROR_NONE))
483         || !TEST_false(error_writing_log))
484         goto end;
485 
486     /*
487      * Now we want to test that our output data was vaguely sensible. For this
488      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
489      * TLSv1.3, but we do expect both client and server to emit keys.
490      */
491     expected.client_handshake_secret_count = 1;
492     expected.server_handshake_secret_count = 1;
493     expected.client_application_secret_count = 1;
494     expected.server_application_secret_count = 1;
495     expected.exporter_secret_count = 1;
496     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
497             SSL_get_session(clientssl), &expected))
498         || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
499             SSL_get_session(serverssl),
500             &expected)))
501         goto end;
502 
503     /* Terminate old session and resume with early data. */
504     sess = SSL_get1_session(clientssl);
505     SSL_shutdown(clientssl);
506     SSL_shutdown(serverssl);
507     SSL_free(serverssl);
508     SSL_free(clientssl);
509     serverssl = clientssl = NULL;
510 
511     /* Reset key log */
512     memset(client_log_buffer, 0, sizeof(client_log_buffer));
513     memset(server_log_buffer, 0, sizeof(server_log_buffer));
514     client_log_buffer_index = 0;
515     server_log_buffer_index = 0;
516 
517     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
518             &clientssl, NULL, NULL))
519         || !TEST_true(SSL_set_session(clientssl, sess))
520         /* Here writing 0 length early data is enough. */
521         || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
522         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
523                             &readbytes),
524             SSL_READ_EARLY_DATA_ERROR)
525         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
526             SSL_EARLY_DATA_ACCEPTED)
527         || !TEST_true(create_ssl_connection(serverssl, clientssl,
528             SSL_ERROR_NONE))
529         || !TEST_true(SSL_session_reused(clientssl)))
530         goto end;
531 
532     /* In addition to the previous entries, expect early secrets. */
533     expected.client_early_secret_count = 1;
534     expected.early_exporter_secret_count = 1;
535     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
536             SSL_get_session(clientssl), &expected))
537         || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
538             SSL_get_session(serverssl),
539             &expected)))
540         goto end;
541 
542     testresult = 1;
543 
544 end:
545     SSL_SESSION_free(sess);
546     SSL_free(serverssl);
547     SSL_free(clientssl);
548     SSL_CTX_free(sctx);
549     SSL_CTX_free(cctx);
550 
551     return testresult;
552 }
553 #endif
554 
555 static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg)
556 {
557     int res = X509_verify_cert(ctx);
558     int idx = SSL_get_ex_data_X509_STORE_CTX_idx();
559     SSL *ssl;
560 
561     /* this should not happen but check anyway */
562     if (idx < 0
563         || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL)
564         return 0;
565 
566     if (res == 0 && X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
567         /* indicate SSL_ERROR_WANT_RETRY_VERIFY */
568         return SSL_set_retry_verify(ssl);
569 
570     return res;
571 }
572 
573 static int test_client_cert_verify_cb(void)
574 {
575     /* server key, cert, chain, and root */
576     char *skey = test_mk_file_path(certsdir, "leaf.key");
577     char *leaf = test_mk_file_path(certsdir, "leaf.pem");
578     char *int2 = test_mk_file_path(certsdir, "subinterCA.pem");
579     char *int1 = test_mk_file_path(certsdir, "interCA.pem");
580     char *root = test_mk_file_path(certsdir, "rootCA.pem");
581     X509 *crt1 = NULL, *crt2 = NULL;
582     STACK_OF(X509) *server_chain;
583     SSL_CTX *cctx = NULL, *sctx = NULL;
584     SSL *clientssl = NULL, *serverssl = NULL;
585     int testresult = 0;
586 
587     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
588             TLS_client_method(), TLS1_VERSION, 0,
589             &sctx, &cctx, NULL, NULL)))
590         goto end;
591     if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(sctx, leaf), 1)
592         || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, skey,
593                             SSL_FILETYPE_PEM),
594             1)
595         || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
596         goto end;
597     if (!TEST_true(SSL_CTX_load_verify_locations(cctx, root, NULL)))
598         goto end;
599     SSL_CTX_set_verify(cctx, SSL_VERIFY_PEER, NULL);
600     SSL_CTX_set_cert_verify_callback(cctx, verify_retry_cb, NULL);
601     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
602             &clientssl, NULL, NULL)))
603         goto end;
604 
605     /* attempt SSL_connect() with incomplete server chain */
606     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
607             SSL_ERROR_WANT_RETRY_VERIFY)))
608         goto end;
609 
610     /* application provides intermediate certs needed to verify server cert */
611     if (!TEST_ptr((crt1 = load_cert_pem(int1, libctx)))
612         || !TEST_ptr((crt2 = load_cert_pem(int2, libctx)))
613         || !TEST_ptr((server_chain = SSL_get_peer_cert_chain(clientssl))))
614         goto end;
615     /* add certs in reverse order to demonstrate real chain building */
616     if (!TEST_true(sk_X509_push(server_chain, crt1)))
617         goto end;
618     crt1 = NULL;
619     if (!TEST_true(sk_X509_push(server_chain, crt2)))
620         goto end;
621     crt2 = NULL;
622 
623     /* continue SSL_connect(), must now succeed with completed server chain */
624     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
625             SSL_ERROR_NONE)))
626         goto end;
627 
628     testresult = 1;
629 
630 end:
631     X509_free(crt1);
632     X509_free(crt2);
633     if (clientssl != NULL) {
634         SSL_shutdown(clientssl);
635         SSL_free(clientssl);
636     }
637     if (serverssl != NULL) {
638         SSL_shutdown(serverssl);
639         SSL_free(serverssl);
640     }
641     SSL_CTX_free(sctx);
642     SSL_CTX_free(cctx);
643 
644     OPENSSL_free(skey);
645     OPENSSL_free(leaf);
646     OPENSSL_free(int2);
647     OPENSSL_free(int1);
648     OPENSSL_free(root);
649 
650     return testresult;
651 }
652 
653 static int test_ssl_build_cert_chain(void)
654 {
655     int ret = 0;
656     SSL_CTX *ssl_ctx = NULL;
657     SSL *ssl = NULL;
658     char *skey = test_mk_file_path(certsdir, "leaf.key");
659     char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
660 
661     if (!TEST_ptr(ssl_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
662         goto end;
663     if (!TEST_ptr(ssl = SSL_new(ssl_ctx)))
664         goto end;
665     /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
666     if (!TEST_int_eq(SSL_use_certificate_chain_file(ssl, leaf_chain), 1)
667         || !TEST_int_eq(SSL_use_PrivateKey_file(ssl, skey, SSL_FILETYPE_PEM), 1)
668         || !TEST_int_eq(SSL_check_private_key(ssl), 1))
669         goto end;
670     if (!TEST_true(SSL_build_cert_chain(ssl, SSL_BUILD_CHAIN_FLAG_NO_ROOT | SSL_BUILD_CHAIN_FLAG_CHECK)))
671         goto end;
672     ret = 1;
673 end:
674     SSL_free(ssl);
675     SSL_CTX_free(ssl_ctx);
676     OPENSSL_free(leaf_chain);
677     OPENSSL_free(skey);
678     return ret;
679 }
680 
681 static int get_password_cb(char *buf, int size, int rw_flag, void *userdata)
682 {
683     static const char pass[] = "testpass";
684 
685     if (!TEST_int_eq(size, PEM_BUFSIZE))
686         return -1;
687 
688     memcpy(buf, pass, sizeof(pass) - 1);
689     return sizeof(pass) - 1;
690 }
691 
692 static int test_ssl_ctx_build_cert_chain(void)
693 {
694     int ret = 0;
695     SSL_CTX *ctx = NULL;
696     char *skey = test_mk_file_path(certsdir, "leaf-encrypted.key");
697     char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
698 
699     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
700         goto end;
701     SSL_CTX_set_default_passwd_cb(ctx, get_password_cb);
702     /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
703     if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(ctx, leaf_chain), 1)
704         || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(ctx, skey,
705                             SSL_FILETYPE_PEM),
706             1)
707         || !TEST_int_eq(SSL_CTX_check_private_key(ctx), 1))
708         goto end;
709     if (!TEST_true(SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT | SSL_BUILD_CHAIN_FLAG_CHECK)))
710         goto end;
711     ret = 1;
712 end:
713     SSL_CTX_free(ctx);
714     OPENSSL_free(leaf_chain);
715     OPENSSL_free(skey);
716     return ret;
717 }
718 
719 #ifndef OPENSSL_NO_TLS1_2
720 static int full_client_hello_callback(SSL *s, int *al, void *arg)
721 {
722     int *ctr = arg;
723     const unsigned char *p;
724     int *exts;
725 #ifdef OPENSSL_NO_EC
726     const unsigned char expected_ciphers[] = { 0x00, 0x9d };
727 #else
728     const unsigned char expected_ciphers[] = { 0x00, 0x9d, 0xc0,
729         0x2c };
730 #endif
731     const int expected_extensions[] = {
732         65281,
733 #ifndef OPENSSL_NO_EC
734         11, 10,
735 #endif
736         35, 22, 23, 13
737     };
738     size_t len;
739 
740     /* Make sure we can defer processing and get called back. */
741     if ((*ctr)++ == 0)
742         return SSL_CLIENT_HELLO_RETRY;
743 
744     len = SSL_client_hello_get0_ciphers(s, &p);
745     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
746         || !TEST_size_t_eq(
747             SSL_client_hello_get0_compression_methods(s, &p), 1)
748         || !TEST_int_eq(*p, 0))
749         return SSL_CLIENT_HELLO_ERROR;
750     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
751         return SSL_CLIENT_HELLO_ERROR;
752     if (len != OSSL_NELEM(expected_extensions) || memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
753         printf("ClientHello callback expected extensions mismatch\n");
754         OPENSSL_free(exts);
755         return SSL_CLIENT_HELLO_ERROR;
756     }
757     OPENSSL_free(exts);
758     return SSL_CLIENT_HELLO_SUCCESS;
759 }
760 
761 static int test_client_hello_cb(void)
762 {
763     SSL_CTX *cctx = NULL, *sctx = NULL;
764     SSL *clientssl = NULL, *serverssl = NULL;
765     int testctr = 0, testresult = 0;
766 
767     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
768             TLS_client_method(), TLS1_VERSION, 0,
769             &sctx, &cctx, cert, privkey)))
770         goto end;
771     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
772 
773     /* The gimpy cipher list we configure can't do TLS 1.3. */
774     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
775     /* Avoid problems where the default seclevel has been changed */
776     SSL_CTX_set_security_level(cctx, 2);
777     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
778             "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
779         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
780             &clientssl, NULL, NULL))
781         || !TEST_false(create_ssl_connection(serverssl, clientssl,
782             SSL_ERROR_WANT_CLIENT_HELLO_CB))
783         /*
784          * Passing a -1 literal is a hack since
785          * the real value was lost.
786          * */
787         || !TEST_int_eq(SSL_get_error(serverssl, -1),
788             SSL_ERROR_WANT_CLIENT_HELLO_CB)
789         || !TEST_true(create_ssl_connection(serverssl, clientssl,
790             SSL_ERROR_NONE)))
791         goto end;
792 
793     testresult = 1;
794 
795 end:
796     SSL_free(serverssl);
797     SSL_free(clientssl);
798     SSL_CTX_free(sctx);
799     SSL_CTX_free(cctx);
800 
801     return testresult;
802 }
803 
804 static int test_no_ems(void)
805 {
806     SSL_CTX *cctx = NULL, *sctx = NULL;
807     SSL *clientssl = NULL, *serverssl = NULL;
808     int testresult = 0, status;
809 
810     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
811             TLS1_VERSION, TLS1_2_VERSION,
812             &sctx, &cctx, cert, privkey)) {
813         printf("Unable to create SSL_CTX pair\n");
814         goto end;
815     }
816 
817     SSL_CTX_set_options(sctx, SSL_OP_NO_EXTENDED_MASTER_SECRET);
818 
819     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
820         printf("Unable to create SSL objects\n");
821         goto end;
822     }
823 
824     status = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
825     if (fips_ems_check) {
826         if (status == 1) {
827             printf("When FIPS uses the EMS check a connection that doesn't use EMS should fail\n");
828             goto end;
829         }
830     } else {
831         if (!status) {
832             printf("Creating SSL connection failed\n");
833             goto end;
834         }
835         if (SSL_get_extms_support(serverssl)) {
836             printf("Server reports Extended Master Secret support\n");
837             goto end;
838         }
839         if (SSL_get_extms_support(clientssl)) {
840             printf("Client reports Extended Master Secret support\n");
841             goto end;
842         }
843     }
844     testresult = 1;
845 
846 end:
847     SSL_free(serverssl);
848     SSL_free(clientssl);
849     SSL_CTX_free(sctx);
850     SSL_CTX_free(cctx);
851 
852     return testresult;
853 }
854 
855 /*
856  * Very focused test to exercise a single case in the server-side state
857  * machine, when the ChangeCipherState message needs to actually change
858  * from one cipher to a different cipher (i.e., not changing from null
859  * encryption to real encryption).
860  */
861 static int test_ccs_change_cipher(void)
862 {
863     SSL_CTX *cctx = NULL, *sctx = NULL;
864     SSL *clientssl = NULL, *serverssl = NULL;
865     SSL_SESSION *sess = NULL, *sesspre, *sesspost;
866     int testresult = 0;
867     int i;
868     unsigned char buf;
869     size_t readbytes;
870 
871     /*
872      * Create a connection so we can resume and potentially (but not) use
873      * a different cipher in the second connection.
874      */
875     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
876             TLS_client_method(),
877             TLS1_VERSION, TLS1_2_VERSION,
878             &sctx, &cctx, cert, privkey))
879         || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
880         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
881             NULL, NULL))
882         || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
883         || !TEST_true(create_ssl_connection(serverssl, clientssl,
884             SSL_ERROR_NONE))
885         || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
886         || !TEST_ptr(sess = SSL_get1_session(clientssl)))
887         goto end;
888 
889     shutdown_ssl_connection(serverssl, clientssl);
890     serverssl = clientssl = NULL;
891 
892     /* Resume, preferring a different cipher. Our server will force the
893      * same cipher to be used as the initial handshake. */
894     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
895             NULL, NULL))
896         || !TEST_true(SSL_set_session(clientssl, sess))
897         || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
898         || !TEST_true(create_ssl_connection(serverssl, clientssl,
899             SSL_ERROR_NONE))
900         || !TEST_true(SSL_session_reused(clientssl))
901         || !TEST_true(SSL_session_reused(serverssl))
902         || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
903         || !TEST_ptr_eq(sesspre, sesspost)
904         || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
905             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
906         goto end;
907     shutdown_ssl_connection(serverssl, clientssl);
908     serverssl = clientssl = NULL;
909 
910     /*
911      * Now create a fresh connection and try to renegotiate a different
912      * cipher on it.
913      */
914     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
915             NULL, NULL))
916         || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
917         || !TEST_true(create_ssl_connection(serverssl, clientssl,
918             SSL_ERROR_NONE))
919         || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
920         || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
921         || !TEST_true(SSL_renegotiate(clientssl))
922         || !TEST_true(SSL_renegotiate_pending(clientssl)))
923         goto end;
924     /* Actually drive the renegotiation. */
925     for (i = 0; i < 3; i++) {
926         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
927             if (!TEST_ulong_eq(readbytes, 0))
928                 goto end;
929         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
930                        SSL_ERROR_WANT_READ)) {
931             goto end;
932         }
933         if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
934             if (!TEST_ulong_eq(readbytes, 0))
935                 goto end;
936         } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
937                        SSL_ERROR_WANT_READ)) {
938             goto end;
939         }
940     }
941     /* sesspre and sesspost should be different since the cipher changed. */
942     if (!TEST_false(SSL_renegotiate_pending(clientssl))
943         || !TEST_false(SSL_session_reused(clientssl))
944         || !TEST_false(SSL_session_reused(serverssl))
945         || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
946         || !TEST_ptr_ne(sesspre, sesspost)
947         || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
948             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
949         goto end;
950 
951     shutdown_ssl_connection(serverssl, clientssl);
952     serverssl = clientssl = NULL;
953 
954     testresult = 1;
955 
956 end:
957     SSL_free(serverssl);
958     SSL_free(clientssl);
959     SSL_CTX_free(sctx);
960     SSL_CTX_free(cctx);
961     SSL_SESSION_free(sess);
962 
963     return testresult;
964 }
965 #endif
966 
967 static int execute_test_large_message(const SSL_METHOD *smeth,
968     const SSL_METHOD *cmeth,
969     int min_version, int max_version,
970     int read_ahead)
971 {
972     SSL_CTX *cctx = NULL, *sctx = NULL;
973     SSL *clientssl = NULL, *serverssl = NULL;
974     int testresult = 0;
975 
976     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
977             max_version, &sctx, &cctx, cert,
978             privkey)))
979         goto end;
980 
981 #ifdef OPENSSL_NO_DTLS1_2
982     if (smeth == DTLS_server_method()) {
983         /*
984          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
985          * level 0
986          */
987         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
988             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
989                 "DEFAULT:@SECLEVEL=0")))
990             goto end;
991     }
992 #endif
993 
994     if (read_ahead) {
995         /*
996          * Test that read_ahead works correctly when dealing with large
997          * records
998          */
999         SSL_CTX_set_read_ahead(cctx, 1);
1000     }
1001 
1002     if (!ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
1003         goto end;
1004 
1005     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1006             NULL, NULL))
1007         || !TEST_true(create_ssl_connection(serverssl, clientssl,
1008             SSL_ERROR_NONE)))
1009         goto end;
1010 
1011     /*
1012      * Calling SSL_clear() first is not required but this tests that SSL_clear()
1013      * doesn't leak.
1014      */
1015     if (!TEST_true(SSL_clear(serverssl)))
1016         goto end;
1017 
1018     testresult = 1;
1019 end:
1020     SSL_free(serverssl);
1021     SSL_free(clientssl);
1022     SSL_CTX_free(sctx);
1023     SSL_CTX_free(cctx);
1024 
1025     return testresult;
1026 }
1027 
1028 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_KTLS) && !(defined(OSSL_NO_USABLE_TLS1_3) && defined(OPENSSL_NO_TLS1_2))
1029 /* sock must be connected */
1030 static int ktls_chk_platform(int sock)
1031 {
1032     if (!ktls_enable(sock))
1033         return 0;
1034     return 1;
1035 }
1036 
1037 static int ping_pong_query(SSL *clientssl, SSL *serverssl)
1038 {
1039     static char count = 1;
1040     unsigned char cbuf[16000] = { 0 };
1041     unsigned char sbuf[16000];
1042     size_t err = 0;
1043     char crec_wseq_before[SEQ_NUM_SIZE];
1044     char crec_wseq_after[SEQ_NUM_SIZE];
1045     char crec_rseq_before[SEQ_NUM_SIZE];
1046     char crec_rseq_after[SEQ_NUM_SIZE];
1047     char srec_wseq_before[SEQ_NUM_SIZE];
1048     char srec_wseq_after[SEQ_NUM_SIZE];
1049     char srec_rseq_before[SEQ_NUM_SIZE];
1050     char srec_rseq_after[SEQ_NUM_SIZE];
1051     SSL_CONNECTION *clientsc, *serversc;
1052 
1053     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1054         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1055         goto end;
1056 
1057     cbuf[0] = count++;
1058     memcpy(crec_wseq_before, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1059     memcpy(srec_wseq_before, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1060     memcpy(crec_rseq_before, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1061     memcpy(srec_rseq_before, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1062 
1063     if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf)))
1064         goto end;
1065 
1066     while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) {
1067         if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) {
1068             goto end;
1069         }
1070     }
1071 
1072     if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf)))
1073         goto end;
1074 
1075     while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) {
1076         if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) {
1077             goto end;
1078         }
1079     }
1080 
1081     memcpy(crec_wseq_after, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1082     memcpy(srec_wseq_after, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1083     memcpy(crec_rseq_after, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1084     memcpy(srec_rseq_after, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1085 
1086     /* verify the payload */
1087     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1088         goto end;
1089 
1090     /*
1091      * If ktls is used then kernel sequences are used instead of
1092      * OpenSSL sequences
1093      */
1094     if (!BIO_get_ktls_send(clientsc->wbio)) {
1095         if (!TEST_mem_ne(crec_wseq_before, SEQ_NUM_SIZE,
1096                 crec_wseq_after, SEQ_NUM_SIZE))
1097             goto end;
1098     } else {
1099         if (!TEST_mem_eq(crec_wseq_before, SEQ_NUM_SIZE,
1100                 crec_wseq_after, SEQ_NUM_SIZE))
1101             goto end;
1102     }
1103 
1104     if (!BIO_get_ktls_send(serversc->wbio)) {
1105         if (!TEST_mem_ne(srec_wseq_before, SEQ_NUM_SIZE,
1106                 srec_wseq_after, SEQ_NUM_SIZE))
1107             goto end;
1108     } else {
1109         if (!TEST_mem_eq(srec_wseq_before, SEQ_NUM_SIZE,
1110                 srec_wseq_after, SEQ_NUM_SIZE))
1111             goto end;
1112     }
1113 
1114     if (!BIO_get_ktls_recv(clientsc->wbio)) {
1115         if (!TEST_mem_ne(crec_rseq_before, SEQ_NUM_SIZE,
1116                 crec_rseq_after, SEQ_NUM_SIZE))
1117             goto end;
1118     } else {
1119         if (!TEST_mem_eq(crec_rseq_before, SEQ_NUM_SIZE,
1120                 crec_rseq_after, SEQ_NUM_SIZE))
1121             goto end;
1122     }
1123 
1124     if (!BIO_get_ktls_recv(serversc->wbio)) {
1125         if (!TEST_mem_ne(srec_rseq_before, SEQ_NUM_SIZE,
1126                 srec_rseq_after, SEQ_NUM_SIZE))
1127             goto end;
1128     } else {
1129         if (!TEST_mem_eq(srec_rseq_before, SEQ_NUM_SIZE,
1130                 srec_rseq_after, SEQ_NUM_SIZE))
1131             goto end;
1132     }
1133 
1134     return 1;
1135 end:
1136     return 0;
1137 }
1138 
1139 static int execute_test_ktls(int cis_ktls, int sis_ktls,
1140     int tls_version, const char *cipher)
1141 {
1142     SSL_CTX *cctx = NULL, *sctx = NULL;
1143     SSL *clientssl = NULL, *serverssl = NULL;
1144     int ktls_used = 0, testresult = 0;
1145     int cfd = -1, sfd = -1;
1146     int rx_supported;
1147     SSL_CONNECTION *clientsc, *serversc;
1148     unsigned char *buf = NULL;
1149     const size_t bufsz = SSL3_RT_MAX_PLAIN_LENGTH + 16;
1150     int ret;
1151     size_t offset = 0, i;
1152 
1153     if (!TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1154         goto end;
1155 
1156     /* Skip this test if the platform does not support ktls */
1157     if (!ktls_chk_platform(cfd)) {
1158         testresult = TEST_skip("Kernel does not support KTLS");
1159         goto end;
1160     }
1161 
1162     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1163         testresult = TEST_skip("CHACHA is not supported in FIPS");
1164         goto end;
1165     }
1166 
1167     /* Create a session based on SHA-256 */
1168     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1169             TLS_client_method(),
1170             tls_version, tls_version,
1171             &sctx, &cctx, cert, privkey)))
1172         goto end;
1173 
1174     if (tls_version == TLS1_3_VERSION) {
1175         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1176             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1177             goto end;
1178     } else {
1179         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1180             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1181             goto end;
1182     }
1183 
1184     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1185             &clientssl, sfd, cfd)))
1186         goto end;
1187 
1188     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1189         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1190         goto end;
1191 
1192     if (cis_ktls) {
1193         if (!TEST_true(SSL_set_options(clientssl, SSL_OP_ENABLE_KTLS)))
1194             goto end;
1195     }
1196 
1197     if (sis_ktls) {
1198         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1199             goto end;
1200     }
1201 
1202     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1203         goto end;
1204 
1205     /*
1206      * The running kernel may not support a given cipher suite
1207      * or direction, so just check that KTLS isn't used when it
1208      * isn't enabled.
1209      */
1210     if (!cis_ktls) {
1211         if (!TEST_false(BIO_get_ktls_send(clientsc->wbio)))
1212             goto end;
1213     } else {
1214         if (BIO_get_ktls_send(clientsc->wbio))
1215             ktls_used = 1;
1216     }
1217 
1218     if (!sis_ktls) {
1219         if (!TEST_false(BIO_get_ktls_send(serversc->wbio)))
1220             goto end;
1221     } else {
1222         if (BIO_get_ktls_send(serversc->wbio))
1223             ktls_used = 1;
1224     }
1225 
1226 #if defined(OPENSSL_NO_KTLS_RX)
1227     rx_supported = 0;
1228 #else
1229     rx_supported = 1;
1230 #endif
1231     if (!cis_ktls || !rx_supported) {
1232         if (!TEST_false(BIO_get_ktls_recv(clientsc->rbio)))
1233             goto end;
1234     } else {
1235         if (BIO_get_ktls_send(clientsc->rbio))
1236             ktls_used = 1;
1237     }
1238 
1239     if (!sis_ktls || !rx_supported) {
1240         if (!TEST_false(BIO_get_ktls_recv(serversc->rbio)))
1241             goto end;
1242     } else {
1243         if (BIO_get_ktls_send(serversc->rbio))
1244             ktls_used = 1;
1245     }
1246 
1247     if ((cis_ktls || sis_ktls) && !ktls_used) {
1248         testresult = TEST_skip("KTLS not supported for %s cipher %s",
1249             tls_version == TLS1_3_VERSION ? "TLS 1.3" : "TLS 1.2", cipher);
1250         goto end;
1251     }
1252 
1253     if (!TEST_true(ping_pong_query(clientssl, serverssl)))
1254         goto end;
1255 
1256     buf = OPENSSL_zalloc(bufsz);
1257     if (!TEST_ptr(buf))
1258         goto end;
1259 
1260     /*
1261      * Write some data that exceeds the maximum record length. KTLS may choose
1262      * to coalesce this data into a single buffer when we read it again.
1263      */
1264     while ((ret = SSL_write(clientssl, buf, bufsz)) != (int)bufsz) {
1265         if (!TEST_true(SSL_get_error(clientssl, ret) == SSL_ERROR_WANT_WRITE))
1266             goto end;
1267     }
1268 
1269     /* Now check that we can read all the data we wrote */
1270     do {
1271         ret = SSL_read(serverssl, buf + offset, bufsz - offset);
1272         if (ret <= 0) {
1273             if (!TEST_true(SSL_get_error(serverssl, ret) == SSL_ERROR_WANT_READ))
1274                 goto end;
1275         } else {
1276             offset += ret;
1277         }
1278     } while (offset < bufsz);
1279 
1280     if (!TEST_true(offset == bufsz))
1281         goto end;
1282     for (i = 0; i < bufsz; i++)
1283         if (!TEST_true(buf[i] == 0))
1284             goto end;
1285 
1286     testresult = 1;
1287 end:
1288     OPENSSL_free(buf);
1289     if (clientssl) {
1290         SSL_shutdown(clientssl);
1291         SSL_free(clientssl);
1292     }
1293     if (serverssl) {
1294         SSL_shutdown(serverssl);
1295         SSL_free(serverssl);
1296     }
1297     SSL_CTX_free(sctx);
1298     SSL_CTX_free(cctx);
1299     serverssl = clientssl = NULL;
1300     if (cfd != -1)
1301         close(cfd);
1302     if (sfd != -1)
1303         close(sfd);
1304     return testresult;
1305 }
1306 
1307 #define SENDFILE_SZ (16 * 4096)
1308 #define SENDFILE_CHUNK (4 * 4096)
1309 #define min(a, b) ((a) > (b) ? (b) : (a))
1310 
1311 static int execute_test_ktls_sendfile(int tls_version, const char *cipher,
1312     int zerocopy)
1313 {
1314     SSL_CTX *cctx = NULL, *sctx = NULL;
1315     SSL *clientssl = NULL, *serverssl = NULL;
1316     unsigned char *buf, *buf_dst;
1317     BIO *out = NULL, *in = NULL;
1318     int cfd = -1, sfd = -1, ffd, err;
1319     ssize_t chunk_size = 0;
1320     off_t chunk_off = 0;
1321     int testresult = 0;
1322     FILE *ffdp;
1323     SSL_CONNECTION *serversc;
1324 
1325     buf = OPENSSL_zalloc(SENDFILE_SZ);
1326     buf_dst = OPENSSL_zalloc(SENDFILE_SZ);
1327     if (!TEST_ptr(buf) || !TEST_ptr(buf_dst)
1328         || !TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1329         goto end;
1330 
1331     /* Skip this test if the platform does not support ktls */
1332     if (!ktls_chk_platform(sfd)) {
1333         testresult = TEST_skip("Kernel does not support KTLS");
1334         goto end;
1335     }
1336 
1337     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1338         testresult = TEST_skip("CHACHA is not supported in FIPS");
1339         goto end;
1340     }
1341 
1342     /* Create a session based on SHA-256 */
1343     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1344             TLS_client_method(),
1345             tls_version, tls_version,
1346             &sctx, &cctx, cert, privkey)))
1347         goto end;
1348 
1349     if (tls_version == TLS1_3_VERSION) {
1350         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1351             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1352             goto end;
1353     } else {
1354         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1355             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1356             goto end;
1357     }
1358 
1359     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1360             &clientssl, sfd, cfd)))
1361         goto end;
1362 
1363     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1364         goto end;
1365 
1366     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1367         goto end;
1368 
1369     if (zerocopy) {
1370         if (!TEST_true(SSL_set_options(serverssl,
1371                 SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE)))
1372             goto end;
1373     }
1374 
1375     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1376             SSL_ERROR_NONE)))
1377         goto end;
1378 
1379     if (!BIO_get_ktls_send(serversc->wbio)) {
1380         testresult = TEST_skip("Failed to enable KTLS for %s cipher %s",
1381             tls_version == TLS1_3_VERSION ? "TLS 1.3" : "TLS 1.2", cipher);
1382         goto end;
1383     }
1384 
1385     if (!TEST_int_gt(RAND_bytes_ex(libctx, buf, SENDFILE_SZ, 0), 0))
1386         goto end;
1387 
1388     out = BIO_new_file(tmpfilename, "wb");
1389     if (!TEST_ptr(out))
1390         goto end;
1391 
1392     if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ)
1393         goto end;
1394 
1395     BIO_free(out);
1396     out = NULL;
1397     in = BIO_new_file(tmpfilename, "rb");
1398     BIO_get_fp(in, &ffdp);
1399     ffd = fileno(ffdp);
1400 
1401     while (chunk_off < SENDFILE_SZ) {
1402         chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off);
1403         while ((err = SSL_sendfile(serverssl,
1404                     ffd,
1405                     chunk_off,
1406                     chunk_size,
1407                     0))
1408             != chunk_size) {
1409             if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE)
1410                 goto end;
1411         }
1412         while ((err = SSL_read(clientssl,
1413                     buf_dst + chunk_off,
1414                     chunk_size))
1415             != chunk_size) {
1416             if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ)
1417                 goto end;
1418         }
1419 
1420         /* verify the payload */
1421         if (!TEST_mem_eq(buf_dst + chunk_off,
1422                 chunk_size,
1423                 buf + chunk_off,
1424                 chunk_size))
1425             goto end;
1426 
1427         chunk_off += chunk_size;
1428     }
1429 
1430     testresult = 1;
1431 end:
1432     if (clientssl) {
1433         SSL_shutdown(clientssl);
1434         SSL_free(clientssl);
1435     }
1436     if (serverssl) {
1437         SSL_shutdown(serverssl);
1438         SSL_free(serverssl);
1439     }
1440     SSL_CTX_free(sctx);
1441     SSL_CTX_free(cctx);
1442     serverssl = clientssl = NULL;
1443     BIO_free(out);
1444     BIO_free(in);
1445     if (cfd != -1)
1446         close(cfd);
1447     if (sfd != -1)
1448         close(sfd);
1449     OPENSSL_free(buf);
1450     OPENSSL_free(buf_dst);
1451     return testresult;
1452 }
1453 
1454 static struct ktls_test_cipher {
1455     int tls_version;
1456     const char *cipher;
1457 } ktls_test_ciphers[] = {
1458 #if !defined(OPENSSL_NO_TLS1_2)
1459 #ifdef OPENSSL_KTLS_AES_GCM_128
1460     { TLS1_2_VERSION, "AES128-GCM-SHA256" },
1461 #endif
1462 #ifdef OPENSSL_KTLS_AES_CCM_128
1463     { TLS1_2_VERSION, "AES128-CCM" },
1464 #endif
1465 #ifdef OPENSSL_KTLS_AES_GCM_256
1466     { TLS1_2_VERSION, "AES256-GCM-SHA384" },
1467 #endif
1468 #ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1469 #ifndef OPENSSL_NO_EC
1470     { TLS1_2_VERSION, "ECDHE-RSA-CHACHA20-POLY1305" },
1471 #endif
1472 #endif
1473 #endif
1474 #if !defined(OSSL_NO_USABLE_TLS1_3)
1475 #ifdef OPENSSL_KTLS_AES_GCM_128
1476     { TLS1_3_VERSION, "TLS_AES_128_GCM_SHA256" },
1477 #endif
1478 #ifdef OPENSSL_KTLS_AES_CCM_128
1479     { TLS1_3_VERSION, "TLS_AES_128_CCM_SHA256" },
1480 #endif
1481 #ifdef OPENSSL_KTLS_AES_GCM_256
1482     { TLS1_3_VERSION, "TLS_AES_256_GCM_SHA384" },
1483 #endif
1484 #ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1485     { TLS1_3_VERSION, "TLS_CHACHA20_POLY1305_SHA256" },
1486 #endif
1487 #endif
1488 };
1489 
1490 #define NUM_KTLS_TEST_CIPHERS OSSL_NELEM(ktls_test_ciphers)
1491 
1492 static int test_ktls(int test)
1493 {
1494     struct ktls_test_cipher *cipher;
1495     int cis_ktls, sis_ktls;
1496 
1497     OPENSSL_assert(test / 4 < (int)NUM_KTLS_TEST_CIPHERS);
1498     cipher = &ktls_test_ciphers[test / 4];
1499 
1500     cis_ktls = (test & 1) != 0;
1501     sis_ktls = (test & 2) != 0;
1502 
1503     return execute_test_ktls(cis_ktls, sis_ktls, cipher->tls_version,
1504         cipher->cipher);
1505 }
1506 
1507 static int test_ktls_sendfile(int test)
1508 {
1509     struct ktls_test_cipher *cipher;
1510     int tst = test >> 1;
1511 
1512     OPENSSL_assert(tst < (int)NUM_KTLS_TEST_CIPHERS);
1513     cipher = &ktls_test_ciphers[tst];
1514 
1515     return execute_test_ktls_sendfile(cipher->tls_version, cipher->cipher,
1516         test & 1);
1517 }
1518 #endif
1519 
1520 static int test_large_message_tls(void)
1521 {
1522     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1523         TLS1_VERSION, 0, 0);
1524 }
1525 
1526 static int test_large_message_tls_read_ahead(void)
1527 {
1528     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1529         TLS1_VERSION, 0, 1);
1530 }
1531 
1532 #ifndef OPENSSL_NO_DTLS
1533 static int test_large_message_dtls(void)
1534 {
1535 #ifdef OPENSSL_NO_DTLS1_2
1536     /* Not supported in the FIPS provider */
1537     if (is_fips)
1538         return 1;
1539 #endif
1540     /*
1541      * read_ahead is not relevant to DTLS because DTLS always acts as if
1542      * read_ahead is set.
1543      */
1544     return execute_test_large_message(DTLS_server_method(),
1545         DTLS_client_method(),
1546         DTLS1_VERSION, 0, 0);
1547 }
1548 #endif
1549 
1550 /*
1551  * Test we can successfully send the maximum amount of application data. We
1552  * test each protocol version individually, each with and without EtM enabled.
1553  * TLSv1.3 doesn't use EtM so technically it is redundant to test both but it is
1554  * simpler this way. We also test all combinations with and without the
1555  * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS option which affects the size of the
1556  * underlying buffer.
1557  */
1558 static int test_large_app_data(int tst)
1559 {
1560     SSL_CTX *cctx = NULL, *sctx = NULL;
1561     SSL *clientssl = NULL, *serverssl = NULL;
1562     int testresult = 0, prot;
1563     unsigned char *msg, *buf = NULL;
1564     size_t written, readbytes;
1565     const SSL_METHOD *smeth = TLS_server_method();
1566     const SSL_METHOD *cmeth = TLS_client_method();
1567 
1568     switch (tst >> 2) {
1569     case 0:
1570 #ifndef OSSL_NO_USABLE_TLS1_3
1571         prot = TLS1_3_VERSION;
1572         break;
1573 #else
1574         return TEST_skip("TLS 1.3 not supported");
1575 #endif
1576 
1577     case 1:
1578 #ifndef OPENSSL_NO_TLS1_2
1579         prot = TLS1_2_VERSION;
1580         break;
1581 #else
1582         return TEST_skip("TLS 1.2 not supported");
1583 #endif
1584 
1585     case 2:
1586 #ifndef OPENSSL_NO_TLS1_1
1587         prot = TLS1_1_VERSION;
1588         break;
1589 #else
1590         return TEST_skip("TLS 1.1 not supported");
1591 #endif
1592 
1593     case 3:
1594 #ifndef OPENSSL_NO_TLS1
1595         prot = TLS1_VERSION;
1596         break;
1597 #else
1598         return TEST_skip("TLS 1 not supported");
1599 #endif
1600 
1601     case 4:
1602 #ifndef OPENSSL_NO_SSL3
1603         prot = SSL3_VERSION;
1604         break;
1605 #else
1606         return TEST_skip("SSL 3 not supported");
1607 #endif
1608 
1609     case 5:
1610 #ifndef OPENSSL_NO_DTLS1_2
1611         prot = DTLS1_2_VERSION;
1612         smeth = DTLS_server_method();
1613         cmeth = DTLS_client_method();
1614         break;
1615 #else
1616         return TEST_skip("DTLS 1.2 not supported");
1617 #endif
1618 
1619     case 6:
1620 #ifndef OPENSSL_NO_DTLS1
1621         if (is_fips)
1622             return TEST_skip("DTLS 1 not supported by FIPS provider");
1623         prot = DTLS1_VERSION;
1624         smeth = DTLS_server_method();
1625         cmeth = DTLS_client_method();
1626         break;
1627 #else
1628         return TEST_skip("DTLS 1 not supported");
1629 #endif
1630 
1631     default:
1632         /* Shouldn't happen */
1633         return 0;
1634     }
1635 
1636     if (is_fips && prot < TLS1_2_VERSION)
1637         return TEST_skip("TLS versions < 1.2 not supported by FIPS provider");
1638 
1639     /* Maximal sized message of zeros */
1640     msg = OPENSSL_zalloc(SSL3_RT_MAX_PLAIN_LENGTH);
1641     if (!TEST_ptr(msg))
1642         goto end;
1643 
1644     buf = OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH + 1);
1645     if (!TEST_ptr(buf))
1646         goto end;
1647     /* Set whole buffer to all bits set */
1648     memset(buf, 0xff, SSL3_RT_MAX_PLAIN_LENGTH + 1);
1649 
1650     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, prot, prot,
1651             &sctx, &cctx, cert, privkey)))
1652         goto end;
1653 
1654     if (prot < TLS1_2_VERSION || prot == DTLS1_VERSION) {
1655         /* Older protocol versions need SECLEVEL=0 due to SHA1 usage */
1656         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0"))
1657             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
1658                 "DEFAULT:@SECLEVEL=0")))
1659             goto end;
1660     }
1661 
1662     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1663             &clientssl, NULL, NULL)))
1664         goto end;
1665 
1666     if ((tst & 1) != 0) {
1667         /* Setting this option gives us a minimally sized underlying buffer */
1668         if (!TEST_true(SSL_set_options(serverssl,
1669                 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
1670             || !TEST_true(SSL_set_options(clientssl,
1671                 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)))
1672             goto end;
1673     }
1674 
1675     if ((tst & 2) != 0) {
1676         /*
1677          * Setting this option means the MAC is added before encryption
1678          * giving us a larger record for the encryption process
1679          */
1680         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC))
1681             || !TEST_true(SSL_set_options(clientssl,
1682                 SSL_OP_NO_ENCRYPT_THEN_MAC)))
1683             goto end;
1684     }
1685 
1686     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1687         goto end;
1688 
1689     if (!TEST_true(SSL_write_ex(clientssl, msg, SSL3_RT_MAX_PLAIN_LENGTH,
1690             &written))
1691         || !TEST_size_t_eq(written, SSL3_RT_MAX_PLAIN_LENGTH))
1692         goto end;
1693 
1694     /* We provide a buffer slightly larger than what we are actually expecting */
1695     if (!TEST_true(SSL_read_ex(serverssl, buf, SSL3_RT_MAX_PLAIN_LENGTH + 1,
1696             &readbytes)))
1697         goto end;
1698 
1699     if (!TEST_mem_eq(msg, written, buf, readbytes))
1700         goto end;
1701 
1702     testresult = 1;
1703 end:
1704     OPENSSL_free(msg);
1705     OPENSSL_free(buf);
1706     SSL_free(serverssl);
1707     SSL_free(clientssl);
1708     SSL_CTX_free(sctx);
1709     SSL_CTX_free(cctx);
1710     return testresult;
1711 }
1712 
1713 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) \
1714     || !defined(OPENSSL_NO_DTLS)
1715 static int execute_cleanse_plaintext(const SSL_METHOD *smeth,
1716     const SSL_METHOD *cmeth,
1717     int min_version, int max_version)
1718 {
1719     size_t i;
1720     SSL_CTX *cctx = NULL, *sctx = NULL;
1721     SSL *clientssl = NULL, *serverssl = NULL;
1722     int testresult = 0;
1723     const unsigned char *zbuf;
1724     SSL_CONNECTION *serversc;
1725     TLS_RECORD *rr;
1726 
1727     static unsigned char cbuf[16000];
1728     static unsigned char sbuf[16000];
1729 
1730     if (!TEST_true(create_ssl_ctx_pair(libctx,
1731             smeth, cmeth,
1732             min_version, max_version,
1733             &sctx, &cctx, cert,
1734             privkey)))
1735         goto end;
1736 
1737 #ifdef OPENSSL_NO_DTLS1_2
1738     if (smeth == DTLS_server_method()) {
1739         /* Not supported in the FIPS provider */
1740         if (is_fips) {
1741             testresult = 1;
1742             goto end;
1743         };
1744         /*
1745          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
1746          * level 0
1747          */
1748         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
1749             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1750                 "DEFAULT:@SECLEVEL=0")))
1751             goto end;
1752     }
1753 #endif
1754 
1755     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1756             NULL, NULL)))
1757         goto end;
1758 
1759     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_CLEANSE_PLAINTEXT)))
1760         goto end;
1761 
1762     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1763             SSL_ERROR_NONE)))
1764         goto end;
1765 
1766     for (i = 0; i < sizeof(cbuf); i++) {
1767         cbuf[i] = i & 0xff;
1768     }
1769 
1770     if (!TEST_int_eq(SSL_write(clientssl, cbuf, sizeof(cbuf)), sizeof(cbuf)))
1771         goto end;
1772 
1773     if (!TEST_int_eq(SSL_peek(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1774         goto end;
1775 
1776     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1777         goto end;
1778 
1779     /*
1780      * Since we called SSL_peek(), we know the data in the record
1781      * layer is a plaintext record. We can gather the pointer to check
1782      * for zeroization after SSL_read().
1783      */
1784     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1785         goto end;
1786     rr = serversc->rlayer.tlsrecs;
1787 
1788     zbuf = &rr->data[rr->off];
1789     if (!TEST_int_eq(rr->length, sizeof(cbuf)))
1790         goto end;
1791 
1792     /*
1793      * After SSL_peek() the plaintext must still be stored in the
1794      * record.
1795      */
1796     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1797         goto end;
1798 
1799     memset(sbuf, 0, sizeof(sbuf));
1800     if (!TEST_int_eq(SSL_read(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1801         goto end;
1802 
1803     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(cbuf)))
1804         goto end;
1805 
1806     /* Check if rbuf is cleansed */
1807     memset(cbuf, 0, sizeof(cbuf));
1808     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1809         goto end;
1810 
1811     testresult = 1;
1812 end:
1813     SSL_free(serverssl);
1814     SSL_free(clientssl);
1815     SSL_CTX_free(sctx);
1816     SSL_CTX_free(cctx);
1817 
1818     return testresult;
1819 }
1820 #endif /*                                                                \
1821         * !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) \
1822         * || !defined(OPENSSL_NO_DTLS)                                   \
1823         */
1824 
1825 static int test_cleanse_plaintext(void)
1826 {
1827 #if !defined(OPENSSL_NO_TLS1_2)
1828     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1829             TLS_client_method(),
1830             TLS1_2_VERSION,
1831             TLS1_2_VERSION)))
1832         return 0;
1833 
1834 #endif
1835 
1836 #if !defined(OSSL_NO_USABLE_TLS1_3)
1837     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1838             TLS_client_method(),
1839             TLS1_3_VERSION,
1840             TLS1_3_VERSION)))
1841         return 0;
1842 #endif
1843 
1844 #if !defined(OPENSSL_NO_DTLS)
1845 
1846     if (!TEST_true(execute_cleanse_plaintext(DTLS_server_method(),
1847             DTLS_client_method(),
1848             DTLS1_VERSION,
1849             0)))
1850         return 0;
1851 #endif
1852     return 1;
1853 }
1854 
1855 #ifndef OPENSSL_NO_OCSP
1856 static int ocsp_server_cb(SSL *s, void *arg)
1857 {
1858     int *argi = (int *)arg;
1859     unsigned char *copy = NULL;
1860     STACK_OF(OCSP_RESPID) *ids = NULL;
1861     OCSP_RESPID *id = NULL;
1862 
1863     if (*argi == 2) {
1864         /* In this test we are expecting exactly 1 OCSP_RESPID */
1865         SSL_get_tlsext_status_ids(s, &ids);
1866         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
1867             return SSL_TLSEXT_ERR_ALERT_FATAL;
1868 
1869         id = sk_OCSP_RESPID_value(ids, 0);
1870         if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL))
1871             return SSL_TLSEXT_ERR_ALERT_FATAL;
1872     } else if (*argi != 1) {
1873         return SSL_TLSEXT_ERR_ALERT_FATAL;
1874     }
1875 
1876     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
1877         return SSL_TLSEXT_ERR_ALERT_FATAL;
1878 
1879     if (!TEST_true(SSL_set_tlsext_status_ocsp_resp(s, copy,
1880             sizeof(orespder)))) {
1881         OPENSSL_free(copy);
1882         return SSL_TLSEXT_ERR_ALERT_FATAL;
1883     }
1884     ocsp_server_called = 1;
1885     return SSL_TLSEXT_ERR_OK;
1886 }
1887 
1888 static int ocsp_client_cb(SSL *s, void *arg)
1889 {
1890     int *argi = (int *)arg;
1891     const unsigned char *respderin;
1892     size_t len;
1893 
1894     if (*argi != 1 && *argi != 2)
1895         return 0;
1896 
1897     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
1898     if (!TEST_mem_eq(orespder, len, respderin, len))
1899         return 0;
1900 
1901     ocsp_client_called = 1;
1902     return 1;
1903 }
1904 
1905 static int test_tlsext_status_type(void)
1906 {
1907     SSL_CTX *cctx = NULL, *sctx = NULL;
1908     SSL *clientssl = NULL, *serverssl = NULL;
1909     int testresult = 0;
1910     STACK_OF(OCSP_RESPID) *ids = NULL;
1911     OCSP_RESPID *id = NULL;
1912     BIO *certbio = NULL;
1913 
1914     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
1915             TLS1_VERSION, 0,
1916             &sctx, &cctx, cert, privkey))
1917         return 0;
1918 
1919     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
1920         goto end;
1921 
1922     /* First just do various checks getting and setting tlsext_status_type */
1923 
1924     clientssl = SSL_new(cctx);
1925     if (!TEST_ptr(clientssl))
1926         goto end;
1927     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
1928         || !TEST_true(SSL_set_tlsext_status_type(clientssl,
1929             TLSEXT_STATUSTYPE_ocsp))
1930         || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
1931             TLSEXT_STATUSTYPE_ocsp))
1932         goto end;
1933 
1934     SSL_free(clientssl);
1935     clientssl = NULL;
1936 
1937     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
1938         || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
1939         goto end;
1940 
1941     clientssl = SSL_new(cctx);
1942     if (!TEST_ptr(clientssl))
1943         goto end;
1944     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
1945         goto end;
1946     SSL_free(clientssl);
1947     clientssl = NULL;
1948 
1949     /*
1950      * Now actually do a handshake and check OCSP information is exchanged and
1951      * the callbacks get called
1952      */
1953     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
1954     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
1955     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
1956     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
1957     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1958             &clientssl, NULL, NULL))
1959         || !TEST_true(create_ssl_connection(serverssl, clientssl,
1960             SSL_ERROR_NONE))
1961         || !TEST_true(ocsp_client_called)
1962         || !TEST_true(ocsp_server_called))
1963         goto end;
1964     SSL_free(serverssl);
1965     SSL_free(clientssl);
1966     serverssl = NULL;
1967     clientssl = NULL;
1968 
1969     /* Try again but this time force the server side callback to fail */
1970     ocsp_client_called = 0;
1971     ocsp_server_called = 0;
1972     cdummyarg = 0;
1973     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1974             &clientssl, NULL, NULL))
1975         /* This should fail because the callback will fail */
1976         || !TEST_false(create_ssl_connection(serverssl, clientssl,
1977             SSL_ERROR_NONE))
1978         || !TEST_false(ocsp_client_called)
1979         || !TEST_false(ocsp_server_called))
1980         goto end;
1981     SSL_free(serverssl);
1982     SSL_free(clientssl);
1983     serverssl = NULL;
1984     clientssl = NULL;
1985 
1986     /*
1987      * This time we'll get the client to send an OCSP_RESPID that it will
1988      * accept.
1989      */
1990     ocsp_client_called = 0;
1991     ocsp_server_called = 0;
1992     cdummyarg = 2;
1993     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1994             &clientssl, NULL, NULL)))
1995         goto end;
1996 
1997     /*
1998      * We'll just use any old cert for this test - it doesn't have to be an OCSP
1999      * specific one. We'll use the server cert.
2000      */
2001     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
2002         || !TEST_ptr(id = OCSP_RESPID_new())
2003         || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
2004         || !TEST_ptr(ocspcert = X509_new_ex(libctx, NULL))
2005         || !TEST_ptr(PEM_read_bio_X509(certbio, &ocspcert, NULL, NULL))
2006         || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL))
2007         || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
2008         goto end;
2009     id = NULL;
2010     SSL_set_tlsext_status_ids(clientssl, ids);
2011     /* Control has been transferred */
2012     ids = NULL;
2013 
2014     BIO_free(certbio);
2015     certbio = NULL;
2016 
2017     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2018             SSL_ERROR_NONE))
2019         || !TEST_true(ocsp_client_called)
2020         || !TEST_true(ocsp_server_called))
2021         goto end;
2022 
2023     testresult = 1;
2024 
2025 end:
2026     SSL_free(serverssl);
2027     SSL_free(clientssl);
2028     SSL_CTX_free(sctx);
2029     SSL_CTX_free(cctx);
2030     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
2031     OCSP_RESPID_free(id);
2032     BIO_free(certbio);
2033     X509_free(ocspcert);
2034     ocspcert = NULL;
2035 
2036     return testresult;
2037 }
2038 #endif
2039 
2040 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
2041 static int new_called, remove_called, get_called;
2042 
2043 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
2044 {
2045     new_called++;
2046     /*
2047      * sess has been up-refed for us, but we don't actually need it so free it
2048      * immediately.
2049      */
2050     SSL_SESSION_free(sess);
2051     return 1;
2052 }
2053 
2054 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
2055 {
2056     remove_called++;
2057 }
2058 
2059 static SSL_SESSION *get_sess_val = NULL;
2060 
2061 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
2062     int *copy)
2063 {
2064     get_called++;
2065     *copy = 1;
2066     return get_sess_val;
2067 }
2068 
2069 static int execute_test_session(int maxprot, int use_int_cache,
2070     int use_ext_cache, long s_options)
2071 {
2072     SSL_CTX *sctx = NULL, *cctx = NULL;
2073     SSL *serverssl1 = NULL, *clientssl1 = NULL;
2074     SSL *serverssl2 = NULL, *clientssl2 = NULL;
2075 #ifndef OPENSSL_NO_TLS1_1
2076     SSL *serverssl3 = NULL, *clientssl3 = NULL;
2077 #endif
2078     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
2079     int testresult = 0, numnewsesstick = 1;
2080 
2081     new_called = remove_called = 0;
2082 
2083     /* TLSv1.3 sends 2 NewSessionTickets */
2084     if (maxprot == TLS1_3_VERSION)
2085         numnewsesstick = 2;
2086 
2087     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2088             TLS_client_method(), TLS1_VERSION, 0,
2089             &sctx, &cctx, cert, privkey)))
2090         return 0;
2091 
2092     /*
2093      * Only allow the max protocol version so we can force a connection failure
2094      * later
2095      */
2096     SSL_CTX_set_min_proto_version(cctx, maxprot);
2097     SSL_CTX_set_max_proto_version(cctx, maxprot);
2098 
2099     /* Set up session cache */
2100     if (use_ext_cache) {
2101         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2102         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
2103     }
2104     if (use_int_cache) {
2105         /* Also covers instance where both are set */
2106         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
2107     } else {
2108         SSL_CTX_set_session_cache_mode(cctx,
2109             SSL_SESS_CACHE_CLIENT
2110                 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2111     }
2112 
2113     if (s_options) {
2114         SSL_CTX_set_options(sctx, s_options);
2115     }
2116 
2117     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2118             NULL, NULL))
2119         || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2120             SSL_ERROR_NONE))
2121         || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
2122         goto end;
2123 
2124     /* Should fail because it should already be in the cache */
2125     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
2126         goto end;
2127     if (use_ext_cache
2128         && (!TEST_int_eq(new_called, numnewsesstick)
2129 
2130             || !TEST_int_eq(remove_called, 0)))
2131         goto end;
2132 
2133     new_called = remove_called = 0;
2134     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2135             &clientssl2, NULL, NULL))
2136         || !TEST_true(SSL_set_session(clientssl2, sess1))
2137         || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2138             SSL_ERROR_NONE))
2139         || !TEST_true(SSL_session_reused(clientssl2)))
2140         goto end;
2141 
2142     if (maxprot == TLS1_3_VERSION) {
2143         /*
2144          * In TLSv1.3 we should have created a new session even though we have
2145          * resumed. Since we attempted a resume we should also have removed the
2146          * old ticket from the cache so that we try to only use tickets once.
2147          */
2148         if (use_ext_cache
2149             && (!TEST_int_eq(new_called, 1)
2150                 || !TEST_int_eq(remove_called, 1)))
2151             goto end;
2152     } else {
2153         /*
2154          * In TLSv1.2 we expect to have resumed so no sessions added or
2155          * removed.
2156          */
2157         if (use_ext_cache
2158             && (!TEST_int_eq(new_called, 0)
2159                 || !TEST_int_eq(remove_called, 0)))
2160             goto end;
2161     }
2162 
2163     SSL_SESSION_free(sess1);
2164     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
2165         goto end;
2166     shutdown_ssl_connection(serverssl2, clientssl2);
2167     serverssl2 = clientssl2 = NULL;
2168 
2169     new_called = remove_called = 0;
2170     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2171             &clientssl2, NULL, NULL))
2172         || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2173             SSL_ERROR_NONE)))
2174         goto end;
2175 
2176     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
2177         goto end;
2178 
2179     if (use_ext_cache
2180         && (!TEST_int_eq(new_called, numnewsesstick)
2181             || !TEST_int_eq(remove_called, 0)))
2182         goto end;
2183 
2184     new_called = remove_called = 0;
2185     /*
2186      * This should clear sess2 from the cache because it is a "bad" session.
2187      * See SSL_set_session() documentation.
2188      */
2189     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
2190         goto end;
2191     if (use_ext_cache
2192         && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2193         goto end;
2194     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
2195         goto end;
2196 
2197     if (use_int_cache) {
2198         /* Should succeeded because it should not already be in the cache */
2199         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
2200             || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
2201             goto end;
2202     }
2203 
2204     new_called = remove_called = 0;
2205     /* This shouldn't be in the cache so should fail */
2206     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
2207         goto end;
2208 
2209     if (use_ext_cache
2210         && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2211         goto end;
2212 
2213 #if !defined(OPENSSL_NO_TLS1_1)
2214     new_called = remove_called = 0;
2215     /* Force a connection failure */
2216     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
2217     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
2218             &clientssl3, NULL, NULL))
2219         || !TEST_true(SSL_set_session(clientssl3, sess1))
2220         /* This should fail because of the mismatched protocol versions */
2221         || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
2222             SSL_ERROR_NONE)))
2223         goto end;
2224 
2225     /* We should have automatically removed the session from the cache */
2226     if (use_ext_cache
2227         && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2228         goto end;
2229 
2230     /* Should succeed because it should not already be in the cache */
2231     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
2232         goto end;
2233 #endif
2234 
2235     /* Now do some tests for server side caching */
2236     if (use_ext_cache) {
2237         SSL_CTX_sess_set_new_cb(cctx, NULL);
2238         SSL_CTX_sess_set_remove_cb(cctx, NULL);
2239         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2240         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
2241         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
2242         get_sess_val = NULL;
2243     }
2244 
2245     SSL_CTX_set_session_cache_mode(cctx, 0);
2246     /* Internal caching is the default on the server side */
2247     if (!use_int_cache)
2248         SSL_CTX_set_session_cache_mode(sctx,
2249             SSL_SESS_CACHE_SERVER
2250                 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2251 
2252     SSL_free(serverssl1);
2253     SSL_free(clientssl1);
2254     serverssl1 = clientssl1 = NULL;
2255     SSL_free(serverssl2);
2256     SSL_free(clientssl2);
2257     serverssl2 = clientssl2 = NULL;
2258     SSL_SESSION_free(sess1);
2259     sess1 = NULL;
2260     SSL_SESSION_free(sess2);
2261     sess2 = NULL;
2262 
2263     SSL_CTX_set_max_proto_version(sctx, maxprot);
2264     if (maxprot == TLS1_2_VERSION)
2265         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
2266     new_called = remove_called = get_called = 0;
2267     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2268             NULL, NULL))
2269         || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2270             SSL_ERROR_NONE))
2271         || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
2272         || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
2273         goto end;
2274 
2275     if (use_int_cache) {
2276         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
2277             /*
2278              * In TLSv1.3 it should not have been added to the internal cache,
2279              * except in the case where we also have an external cache (in that
2280              * case it gets added to the cache in order to generate remove
2281              * events after timeout).
2282              */
2283             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
2284                 goto end;
2285         } else {
2286             /* Should fail because it should already be in the cache */
2287             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
2288                 goto end;
2289         }
2290     }
2291 
2292     if (use_ext_cache) {
2293         SSL_SESSION *tmp = sess2;
2294 
2295         if (!TEST_int_eq(new_called, numnewsesstick)
2296             || !TEST_int_eq(remove_called, 0)
2297             || !TEST_int_eq(get_called, 0))
2298             goto end;
2299         /*
2300          * Delete the session from the internal cache to force a lookup from
2301          * the external cache. We take a copy first because
2302          * SSL_CTX_remove_session() also marks the session as non-resumable.
2303          */
2304         if (use_int_cache && maxprot != TLS1_3_VERSION) {
2305             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
2306                 || !TEST_true(sess2->owner != NULL)
2307                 || !TEST_true(tmp->owner == NULL)
2308                 || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
2309                 goto end;
2310             SSL_SESSION_free(sess2);
2311         }
2312         sess2 = tmp;
2313     }
2314 
2315     new_called = remove_called = get_called = 0;
2316     get_sess_val = sess2;
2317     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2318             &clientssl2, NULL, NULL))
2319         || !TEST_true(SSL_set_session(clientssl2, sess1))
2320         || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2321             SSL_ERROR_NONE))
2322         || !TEST_true(SSL_session_reused(clientssl2)))
2323         goto end;
2324 
2325     if (use_ext_cache) {
2326         if (!TEST_int_eq(remove_called, 0))
2327             goto end;
2328 
2329         if (maxprot == TLS1_3_VERSION) {
2330             if (!TEST_int_eq(new_called, 1)
2331                 || !TEST_int_eq(get_called, 0))
2332                 goto end;
2333         } else {
2334             if (!TEST_int_eq(new_called, 0)
2335                 || !TEST_int_eq(get_called, 1))
2336                 goto end;
2337         }
2338     }
2339     /*
2340      * Make a small cache, force out all other sessions but
2341      * sess2, try to add sess1, which should succeed. Then
2342      * make sure it's there by checking the owners. Despite
2343      * the timeouts, sess1 should have kicked out sess2
2344      */
2345 
2346     /* Make sess1 expire before sess2 */
2347     if (!TEST_time_t_gt(SSL_SESSION_set_time_ex(sess1, 1000), 0)
2348         || !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0)
2349         || !TEST_time_t_gt(SSL_SESSION_set_time_ex(sess2, 2000), 0)
2350         || !TEST_long_gt(SSL_SESSION_set_timeout(sess2, 2000), 0))
2351         goto end;
2352 
2353     if (!TEST_long_ne(SSL_CTX_sess_set_cache_size(sctx, 1), 0))
2354         goto end;
2355 
2356     /* Don't care about results - cache should only be sess2 at end */
2357     SSL_CTX_add_session(sctx, sess1);
2358     SSL_CTX_add_session(sctx, sess2);
2359 
2360     /* Now add sess1, and make sure it remains, despite timeout */
2361     if (!TEST_true(SSL_CTX_add_session(sctx, sess1))
2362         || !TEST_ptr(sess1->owner)
2363         || !TEST_ptr_null(sess2->owner))
2364         goto end;
2365 
2366     testresult = 1;
2367 
2368 end:
2369     SSL_free(serverssl1);
2370     SSL_free(clientssl1);
2371     SSL_free(serverssl2);
2372     SSL_free(clientssl2);
2373 #ifndef OPENSSL_NO_TLS1_1
2374     SSL_free(serverssl3);
2375     SSL_free(clientssl3);
2376 #endif
2377     SSL_SESSION_free(sess1);
2378     SSL_SESSION_free(sess2);
2379     SSL_CTX_free(sctx);
2380     SSL_CTX_free(cctx);
2381 
2382     return testresult;
2383 }
2384 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
2385 
2386 static int test_session_with_only_int_cache(void)
2387 {
2388 #ifndef OSSL_NO_USABLE_TLS1_3
2389     if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0))
2390         return 0;
2391 #endif
2392 
2393 #ifndef OPENSSL_NO_TLS1_2
2394     return execute_test_session(TLS1_2_VERSION, 1, 0, 0);
2395 #else
2396     return 1;
2397 #endif
2398 }
2399 
2400 static int test_session_with_only_ext_cache(void)
2401 {
2402 #ifndef OSSL_NO_USABLE_TLS1_3
2403     if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0))
2404         return 0;
2405 #endif
2406 
2407 #ifndef OPENSSL_NO_TLS1_2
2408     return execute_test_session(TLS1_2_VERSION, 0, 1, 0);
2409 #else
2410     return 1;
2411 #endif
2412 }
2413 
2414 static int test_session_with_both_cache(void)
2415 {
2416 #ifndef OSSL_NO_USABLE_TLS1_3
2417     if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0))
2418         return 0;
2419 #endif
2420 
2421 #ifndef OPENSSL_NO_TLS1_2
2422     return execute_test_session(TLS1_2_VERSION, 1, 1, 0);
2423 #else
2424     return 1;
2425 #endif
2426 }
2427 
2428 static int test_session_wo_ca_names(void)
2429 {
2430 #ifndef OSSL_NO_USABLE_TLS1_3
2431     if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES))
2432         return 0;
2433 #endif
2434 
2435 #ifndef OPENSSL_NO_TLS1_2
2436     return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
2437 #else
2438     return 1;
2439 #endif
2440 }
2441 
2442 #ifndef OSSL_NO_USABLE_TLS1_3
2443 static SSL_SESSION *sesscache[6];
2444 static int do_cache;
2445 
2446 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
2447 {
2448     if (do_cache) {
2449         sesscache[new_called] = sess;
2450     } else {
2451         /* We don't need the reference to the session, so free it */
2452         SSL_SESSION_free(sess);
2453     }
2454     new_called++;
2455 
2456     return 1;
2457 }
2458 
2459 static int post_handshake_verify(SSL *sssl, SSL *cssl)
2460 {
2461     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
2462     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
2463         return 0;
2464 
2465     /* Start handshake on the server and client */
2466     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
2467         || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
2468         || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
2469         || !TEST_true(create_ssl_connection(sssl, cssl,
2470             SSL_ERROR_NONE)))
2471         return 0;
2472 
2473     return 1;
2474 }
2475 
2476 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
2477     SSL_CTX **cctx)
2478 {
2479     int sess_id_ctx = 1;
2480 
2481     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2482             TLS_client_method(), TLS1_VERSION, 0,
2483             sctx, cctx, cert, privkey))
2484         || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
2485         || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
2486             (void *)&sess_id_ctx,
2487             sizeof(sess_id_ctx))))
2488         return 0;
2489 
2490     if (stateful)
2491         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
2492 
2493     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2494     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
2495 
2496     return 1;
2497 }
2498 
2499 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
2500 {
2501     SSL *serverssl = NULL, *clientssl = NULL;
2502     int i;
2503 
2504     /* Test that we can resume with all the tickets we got given */
2505     for (i = 0; i < idx * 2; i++) {
2506         new_called = 0;
2507         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2508                 &clientssl, NULL, NULL))
2509             || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
2510             goto end;
2511 
2512         SSL_set_post_handshake_auth(clientssl, 1);
2513 
2514         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2515                 SSL_ERROR_NONE)))
2516             goto end;
2517 
2518         /*
2519          * Following a successful resumption we only get 1 ticket. After a
2520          * failed one we should get idx tickets.
2521          */
2522         if (succ) {
2523             if (!TEST_true(SSL_session_reused(clientssl))
2524                 || !TEST_int_eq(new_called, 1))
2525                 goto end;
2526         } else {
2527             if (!TEST_false(SSL_session_reused(clientssl))
2528                 || !TEST_int_eq(new_called, idx))
2529                 goto end;
2530         }
2531 
2532         new_called = 0;
2533         /* After a post-handshake authentication we should get 1 new ticket */
2534         if (succ
2535             && (!post_handshake_verify(serverssl, clientssl)
2536                 || !TEST_int_eq(new_called, 1)))
2537             goto end;
2538 
2539         SSL_shutdown(clientssl);
2540         SSL_shutdown(serverssl);
2541         SSL_free(serverssl);
2542         SSL_free(clientssl);
2543         serverssl = clientssl = NULL;
2544         SSL_SESSION_free(sesscache[i]);
2545         sesscache[i] = NULL;
2546     }
2547 
2548     return 1;
2549 
2550 end:
2551     SSL_free(clientssl);
2552     SSL_free(serverssl);
2553     return 0;
2554 }
2555 
2556 static int test_tickets(int stateful, int idx)
2557 {
2558     SSL_CTX *sctx = NULL, *cctx = NULL;
2559     SSL *serverssl = NULL, *clientssl = NULL;
2560     int testresult = 0;
2561     size_t j;
2562 
2563     /* idx is the test number, but also the number of tickets we want */
2564 
2565     new_called = 0;
2566     do_cache = 1;
2567 
2568     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2569         goto end;
2570 
2571     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2572             &clientssl, NULL, NULL)))
2573         goto end;
2574 
2575     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2576             SSL_ERROR_NONE))
2577         /* Check we got the number of tickets we were expecting */
2578         || !TEST_int_eq(idx, new_called))
2579         goto end;
2580 
2581     SSL_shutdown(clientssl);
2582     SSL_shutdown(serverssl);
2583     SSL_free(serverssl);
2584     SSL_free(clientssl);
2585     SSL_CTX_free(sctx);
2586     SSL_CTX_free(cctx);
2587     clientssl = serverssl = NULL;
2588     sctx = cctx = NULL;
2589 
2590     /*
2591      * Now we try to resume with the tickets we previously created. The
2592      * resumption attempt is expected to fail (because we're now using a new
2593      * SSL_CTX). We should see idx number of tickets issued again.
2594      */
2595 
2596     /* Stop caching sessions - just count them */
2597     do_cache = 0;
2598 
2599     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2600         goto end;
2601 
2602     if (!check_resumption(idx, sctx, cctx, 0))
2603         goto end;
2604 
2605     /* Start again with caching sessions */
2606     new_called = 0;
2607     do_cache = 1;
2608     SSL_CTX_free(sctx);
2609     SSL_CTX_free(cctx);
2610     sctx = cctx = NULL;
2611 
2612     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2613         goto end;
2614 
2615     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2616             &clientssl, NULL, NULL)))
2617         goto end;
2618 
2619     SSL_set_post_handshake_auth(clientssl, 1);
2620 
2621     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2622             SSL_ERROR_NONE))
2623         /* Check we got the number of tickets we were expecting */
2624         || !TEST_int_eq(idx, new_called))
2625         goto end;
2626 
2627     /* After a post-handshake authentication we should get new tickets issued */
2628     if (!post_handshake_verify(serverssl, clientssl)
2629         || !TEST_int_eq(idx * 2, new_called))
2630         goto end;
2631 
2632     SSL_shutdown(clientssl);
2633     SSL_shutdown(serverssl);
2634     SSL_free(serverssl);
2635     SSL_free(clientssl);
2636     serverssl = clientssl = NULL;
2637 
2638     /* Stop caching sessions - just count them */
2639     do_cache = 0;
2640 
2641     /*
2642      * Check we can resume with all the tickets we created. This time around the
2643      * resumptions should all be successful.
2644      */
2645     if (!check_resumption(idx, sctx, cctx, 1))
2646         goto end;
2647 
2648     testresult = 1;
2649 
2650 end:
2651     SSL_free(serverssl);
2652     SSL_free(clientssl);
2653     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2654         SSL_SESSION_free(sesscache[j]);
2655         sesscache[j] = NULL;
2656     }
2657     SSL_CTX_free(sctx);
2658     SSL_CTX_free(cctx);
2659 
2660     return testresult;
2661 }
2662 
2663 static int test_stateless_tickets(int idx)
2664 {
2665     return test_tickets(0, idx);
2666 }
2667 
2668 static int test_stateful_tickets(int idx)
2669 {
2670     return test_tickets(1, idx);
2671 }
2672 
2673 static int test_psk_tickets(void)
2674 {
2675     SSL_CTX *sctx = NULL, *cctx = NULL;
2676     SSL *serverssl = NULL, *clientssl = NULL;
2677     int testresult = 0;
2678     int sess_id_ctx = 1;
2679 
2680     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2681             TLS_client_method(), TLS1_VERSION, 0,
2682             &sctx, &cctx, NULL, NULL))
2683         || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2684             (void *)&sess_id_ctx,
2685             sizeof(sess_id_ctx))))
2686         goto end;
2687 
2688     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2689     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2690     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2691     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2692     use_session_cb_cnt = 0;
2693     find_session_cb_cnt = 0;
2694     srvid = pskid;
2695     new_called = 0;
2696 
2697     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2698             NULL, NULL)))
2699         goto end;
2700     clientpsk = serverpsk = create_a_psk(clientssl, SHA384_DIGEST_LENGTH);
2701     if (!TEST_ptr(clientpsk) || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
2702         goto end;
2703 
2704     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2705             SSL_ERROR_NONE))
2706         || !TEST_int_eq(1, find_session_cb_cnt)
2707         || !TEST_int_eq(1, use_session_cb_cnt)
2708         /* We should always get 1 ticket when using external PSK */
2709         || !TEST_int_eq(1, new_called))
2710         goto end;
2711 
2712     testresult = 1;
2713 
2714 end:
2715     SSL_free(serverssl);
2716     SSL_free(clientssl);
2717     SSL_CTX_free(sctx);
2718     SSL_CTX_free(cctx);
2719     SSL_SESSION_free(clientpsk);
2720     SSL_SESSION_free(serverpsk);
2721     clientpsk = serverpsk = NULL;
2722 
2723     return testresult;
2724 }
2725 
2726 static int test_extra_tickets(int idx)
2727 {
2728     SSL_CTX *sctx = NULL, *cctx = NULL;
2729     SSL *serverssl = NULL, *clientssl = NULL;
2730     BIO *bretry = BIO_new(bio_s_always_retry());
2731     BIO *tmp = NULL;
2732     int testresult = 0;
2733     int stateful = 0;
2734     size_t nbytes;
2735     unsigned char c, buf[1];
2736 
2737     new_called = 0;
2738     do_cache = 1;
2739 
2740     if (idx >= 3) {
2741         idx -= 3;
2742         stateful = 1;
2743     }
2744 
2745     if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2746         goto end;
2747     SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2748     /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2749     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2750 
2751     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2752             &clientssl, NULL, NULL)))
2753         goto end;
2754 
2755     /*
2756      * Note that we have new_session_cb on both sctx and cctx, so new_called is
2757      * incremented by both client and server.
2758      */
2759     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2760             SSL_ERROR_NONE))
2761         /* Check we got the number of tickets we were expecting */
2762         || !TEST_int_eq(idx * 2, new_called)
2763         || !TEST_true(SSL_new_session_ticket(serverssl))
2764         || !TEST_true(SSL_new_session_ticket(serverssl))
2765         || !TEST_int_eq(idx * 2, new_called))
2766         goto end;
2767 
2768     /* Now try a (real) write to actually send the tickets */
2769     c = '1';
2770     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2771         || !TEST_size_t_eq(1, nbytes)
2772         || !TEST_int_eq(idx * 2 + 2, new_called)
2773         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2774         || !TEST_int_eq(idx * 2 + 4, new_called)
2775         || !TEST_int_eq(sizeof(buf), nbytes)
2776         || !TEST_int_eq(c, buf[0])
2777         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2778         goto end;
2779 
2780     /* Try with only requesting one new ticket, too */
2781     c = '2';
2782     new_called = 0;
2783     if (!TEST_true(SSL_new_session_ticket(serverssl))
2784         || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2785         || !TEST_size_t_eq(sizeof(c), nbytes)
2786         || !TEST_int_eq(1, new_called)
2787         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2788         || !TEST_int_eq(2, new_called)
2789         || !TEST_size_t_eq(sizeof(buf), nbytes)
2790         || !TEST_int_eq(c, buf[0]))
2791         goto end;
2792 
2793     /* Do it again but use dummy writes to drive the ticket generation */
2794     c = '3';
2795     new_called = 0;
2796     if (!TEST_true(SSL_new_session_ticket(serverssl))
2797         || !TEST_true(SSL_new_session_ticket(serverssl))
2798         || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2799         || !TEST_size_t_eq(0, nbytes)
2800         || !TEST_int_eq(2, new_called)
2801         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2802         || !TEST_int_eq(4, new_called))
2803         goto end;
2804 
2805     /* Once more, but with SSL_do_handshake() to drive the ticket generation */
2806     c = '4';
2807     new_called = 0;
2808     if (!TEST_true(SSL_new_session_ticket(serverssl))
2809         || !TEST_true(SSL_new_session_ticket(serverssl))
2810         || !TEST_true(SSL_do_handshake(serverssl))
2811         || !TEST_int_eq(2, new_called)
2812         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2813         || !TEST_int_eq(4, new_called))
2814         goto end;
2815 
2816     /*
2817      * Use the always-retry BIO to exercise the logic that forces ticket
2818      * generation to wait until a record boundary.
2819      */
2820     c = '5';
2821     new_called = 0;
2822     tmp = SSL_get_wbio(serverssl);
2823     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2824         tmp = NULL;
2825         goto end;
2826     }
2827     SSL_set0_wbio(serverssl, bretry);
2828     bretry = NULL;
2829     if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2830         || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2831         || !TEST_size_t_eq(nbytes, 0))
2832         goto end;
2833     /* Restore a BIO that will let the write succeed */
2834     SSL_set0_wbio(serverssl, tmp);
2835     tmp = NULL;
2836     /*
2837      * These calls should just queue the request and not send anything
2838      * even if we explicitly try to hit the state machine.
2839      */
2840     if (!TEST_true(SSL_new_session_ticket(serverssl))
2841         || !TEST_true(SSL_new_session_ticket(serverssl))
2842         || !TEST_int_eq(0, new_called)
2843         || !TEST_true(SSL_do_handshake(serverssl))
2844         || !TEST_int_eq(0, new_called))
2845         goto end;
2846     /* Re-do the write; still no tickets sent */
2847     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2848         || !TEST_size_t_eq(1, nbytes)
2849         || !TEST_int_eq(0, new_called)
2850         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2851         || !TEST_int_eq(0, new_called)
2852         || !TEST_int_eq(sizeof(buf), nbytes)
2853         || !TEST_int_eq(c, buf[0])
2854         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2855         goto end;
2856     /* Even trying to hit the state machine now will still not send tickets */
2857     if (!TEST_true(SSL_do_handshake(serverssl))
2858         || !TEST_int_eq(0, new_called))
2859         goto end;
2860     /* Now the *next* write should send the tickets */
2861     c = '6';
2862     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2863         || !TEST_size_t_eq(1, nbytes)
2864         || !TEST_int_eq(2, new_called)
2865         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2866         || !TEST_int_eq(4, new_called)
2867         || !TEST_int_eq(sizeof(buf), nbytes)
2868         || !TEST_int_eq(c, buf[0])
2869         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2870         goto end;
2871 
2872     SSL_shutdown(clientssl);
2873     SSL_shutdown(serverssl);
2874     testresult = 1;
2875 
2876 end:
2877     BIO_free(bretry);
2878     BIO_free(tmp);
2879     SSL_free(serverssl);
2880     SSL_free(clientssl);
2881     SSL_CTX_free(sctx);
2882     SSL_CTX_free(cctx);
2883     clientssl = serverssl = NULL;
2884     sctx = cctx = NULL;
2885     return testresult;
2886 }
2887 #endif
2888 
2889 #define USE_NULL 0
2890 #define USE_BIO_1 1
2891 #define USE_BIO_2 2
2892 #define USE_DEFAULT 3
2893 
2894 #define CONNTYPE_CONNECTION_SUCCESS 0
2895 #define CONNTYPE_CONNECTION_FAIL 1
2896 #define CONNTYPE_NO_CONNECTION 2
2897 
2898 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS (3 * 3 * 3 * 3)
2899 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS (2 * 2)
2900 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2901 #define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS (2 * 2)
2902 #else
2903 #define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS 0
2904 #endif
2905 
2906 #define TOTAL_SSL_SET_BIO_TESTS           \
2907     TOTAL_NO_CONN_SSL_SET_BIO_TESTS       \
2908     +TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2909         + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2910 
2911 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2912 {
2913     switch (type) {
2914     case USE_NULL:
2915         *res = NULL;
2916         break;
2917     case USE_BIO_1:
2918         *res = bio1;
2919         break;
2920     case USE_BIO_2:
2921         *res = bio2;
2922         break;
2923     }
2924 }
2925 
2926 /*
2927  * Tests calls to SSL_set_bio() under various conditions.
2928  *
2929  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2930  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2931  * then do more tests where we create a successful connection first using our
2932  * standard connection setup functions, and then call SSL_set_bio() with
2933  * various combinations of valid BIOs or NULL. We then repeat these tests
2934  * following a failed connection. In this last case we are looking to check that
2935  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2936  */
2937 static int test_ssl_set_bio(int idx)
2938 {
2939     SSL_CTX *sctx = NULL, *cctx = NULL;
2940     BIO *bio1 = NULL;
2941     BIO *bio2 = NULL;
2942     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2943     SSL *serverssl = NULL, *clientssl = NULL;
2944     int initrbio, initwbio, newrbio, newwbio, conntype;
2945     int testresult = 0;
2946 
2947     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2948         initrbio = idx % 3;
2949         idx /= 3;
2950         initwbio = idx % 3;
2951         idx /= 3;
2952         newrbio = idx % 3;
2953         idx /= 3;
2954         newwbio = idx % 3;
2955         conntype = CONNTYPE_NO_CONNECTION;
2956     } else {
2957         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2958         initrbio = initwbio = USE_DEFAULT;
2959         newrbio = idx % 2;
2960         idx /= 2;
2961         newwbio = idx % 2;
2962         idx /= 2;
2963         conntype = idx % 2;
2964     }
2965 
2966     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2967             TLS_client_method(), TLS1_VERSION, 0,
2968             &sctx, &cctx, cert, privkey)))
2969         goto end;
2970 
2971     if (conntype == CONNTYPE_CONNECTION_FAIL) {
2972         /*
2973          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2974          * because we reduced the number of tests in the definition of
2975          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2976          * mismatched protocol versions we will force a connection failure.
2977          */
2978         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2979         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2980     }
2981 
2982     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2983             NULL, NULL)))
2984         goto end;
2985 
2986     if (initrbio == USE_BIO_1
2987         || initwbio == USE_BIO_1
2988         || newrbio == USE_BIO_1
2989         || newwbio == USE_BIO_1) {
2990         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2991             goto end;
2992     }
2993 
2994     if (initrbio == USE_BIO_2
2995         || initwbio == USE_BIO_2
2996         || newrbio == USE_BIO_2
2997         || newwbio == USE_BIO_2) {
2998         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
2999             goto end;
3000     }
3001 
3002     if (initrbio != USE_DEFAULT) {
3003         setupbio(&irbio, bio1, bio2, initrbio);
3004         setupbio(&iwbio, bio1, bio2, initwbio);
3005         SSL_set_bio(clientssl, irbio, iwbio);
3006 
3007         /*
3008          * We want to maintain our own refs to these BIO, so do an up ref for
3009          * each BIO that will have ownership transferred in the SSL_set_bio()
3010          * call
3011          */
3012         if (irbio != NULL && !BIO_up_ref(irbio))
3013             goto end;
3014         if (iwbio != NULL && iwbio != irbio && !BIO_up_ref(iwbio)) {
3015             BIO_free(irbio);
3016             goto end;
3017         }
3018     }
3019 
3020     if (conntype != CONNTYPE_NO_CONNECTION
3021         && !TEST_true(create_ssl_connection(serverssl, clientssl,
3022                           SSL_ERROR_NONE)
3023             == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
3024         goto end;
3025 
3026     setupbio(&nrbio, bio1, bio2, newrbio);
3027     setupbio(&nwbio, bio1, bio2, newwbio);
3028 
3029     /*
3030      * We will (maybe) transfer ownership again so do more up refs.
3031      * SSL_set_bio() has some really complicated ownership rules where BIOs have
3032      * already been set!
3033      */
3034     if (nrbio != NULL
3035         && nrbio != irbio
3036         && (nwbio != iwbio || nrbio != nwbio))
3037         if (!TEST_true(BIO_up_ref(nrbio)))
3038             goto end;
3039     if (nwbio != NULL
3040         && nwbio != nrbio
3041         && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
3042         if (!TEST_true(BIO_up_ref(nwbio))) {
3043             if (nrbio != irbio
3044                 && (nwbio != iwbio || nrbio != nwbio))
3045                 BIO_free(nrbio);
3046             goto end;
3047         }
3048 
3049     SSL_set_bio(clientssl, nrbio, nwbio);
3050 
3051     testresult = 1;
3052 
3053 end:
3054     BIO_free(bio1);
3055     BIO_free(bio2);
3056 
3057     /*
3058      * This test is checking that the ref counting for SSL_set_bio is correct.
3059      * If we get here and we did too many frees then we will fail in the above
3060      * functions.
3061      */
3062     SSL_free(serverssl);
3063     SSL_free(clientssl);
3064     SSL_CTX_free(sctx);
3065     SSL_CTX_free(cctx);
3066     return testresult;
3067 }
3068 
3069 typedef enum { NO_BIO_CHANGE,
3070     CHANGE_RBIO,
3071     CHANGE_WBIO } bio_change_t;
3072 
3073 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
3074 {
3075     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
3076     SSL_CTX *ctx;
3077     SSL *ssl = NULL;
3078     int testresult = 0;
3079 
3080     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
3081         || !TEST_ptr(ssl = SSL_new(ctx))
3082         || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
3083         || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
3084         goto end;
3085 
3086     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
3087 
3088     /*
3089      * If anything goes wrong here then we could leak memory.
3090      */
3091     BIO_push(sslbio, membio1);
3092 
3093     /* Verify changing the rbio/wbio directly does not cause leaks */
3094     if (change_bio != NO_BIO_CHANGE) {
3095         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
3096             ssl = NULL;
3097             goto end;
3098         }
3099         if (change_bio == CHANGE_RBIO)
3100             SSL_set0_rbio(ssl, membio2);
3101         else
3102             SSL_set0_wbio(ssl, membio2);
3103     }
3104     ssl = NULL;
3105 
3106     if (pop_ssl)
3107         BIO_pop(sslbio);
3108     else
3109         BIO_pop(membio1);
3110 
3111     testresult = 1;
3112 end:
3113     BIO_free(membio1);
3114     BIO_free(sslbio);
3115     SSL_free(ssl);
3116     SSL_CTX_free(ctx);
3117 
3118     return testresult;
3119 }
3120 
3121 static int test_ssl_bio_pop_next_bio(void)
3122 {
3123     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
3124 }
3125 
3126 static int test_ssl_bio_pop_ssl_bio(void)
3127 {
3128     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
3129 }
3130 
3131 static int test_ssl_bio_change_rbio(void)
3132 {
3133     return execute_test_ssl_bio(0, CHANGE_RBIO);
3134 }
3135 
3136 static int test_ssl_bio_change_wbio(void)
3137 {
3138     return execute_test_ssl_bio(0, CHANGE_WBIO);
3139 }
3140 
3141 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
3142 typedef struct {
3143     /* The list of sig algs */
3144     const int *list;
3145     /* The length of the list */
3146     size_t listlen;
3147     /* A sigalgs list in string format */
3148     const char *liststr;
3149     /* Whether setting the list should succeed */
3150     int valid;
3151     /* Whether creating a connection with the list should succeed */
3152     int connsuccess;
3153 } sigalgs_list;
3154 
3155 static const int validlist1[] = { NID_sha256, EVP_PKEY_RSA };
3156 #ifndef OPENSSL_NO_EC
3157 static const int validlist2[] = { NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC };
3158 static const int validlist3[] = { NID_sha512, EVP_PKEY_EC };
3159 #endif
3160 static const int invalidlist1[] = { NID_undef, EVP_PKEY_RSA };
3161 static const int invalidlist2[] = { NID_sha256, NID_undef };
3162 static const int invalidlist3[] = { NID_sha256, EVP_PKEY_RSA, NID_sha256 };
3163 static const int invalidlist4[] = { NID_sha256 };
3164 static const sigalgs_list testsigalgs[] = {
3165     { validlist1, OSSL_NELEM(validlist1), NULL, 1, 1 },
3166 #ifndef OPENSSL_NO_EC
3167     { validlist2, OSSL_NELEM(validlist2), NULL, 1, 1 },
3168     { validlist3, OSSL_NELEM(validlist3), NULL, 1, 0 },
3169 #endif
3170     { NULL, 0, "RSA+SHA256", 1, 1 },
3171     { NULL, 0, "RSA+SHA256:?Invalid", 1, 1 },
3172 #ifndef OPENSSL_NO_EC
3173     { NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1 },
3174     { NULL, 0, "ECDSA+SHA512", 1, 0 },
3175 #endif
3176     { invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0 },
3177     { invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0 },
3178     { invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0 },
3179     { invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0 },
3180     { NULL, 0, "RSA", 0, 0 },
3181     { NULL, 0, "SHA256", 0, 0 },
3182     { NULL, 0, "RSA+SHA256:SHA256", 0, 0 },
3183     { NULL, 0, "Invalid", 0, 0 }
3184 };
3185 
3186 static int test_set_sigalgs(int idx)
3187 {
3188     SSL_CTX *cctx = NULL, *sctx = NULL;
3189     SSL *clientssl = NULL, *serverssl = NULL;
3190     int testresult = 0;
3191     const sigalgs_list *curr;
3192     int testctx;
3193 
3194     /* Should never happen */
3195     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
3196         return 0;
3197 
3198     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
3199     curr = testctx ? &testsigalgs[idx]
3200                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
3201 
3202     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3203             TLS_client_method(), TLS1_VERSION, 0,
3204             &sctx, &cctx, cert, privkey)))
3205         return 0;
3206 
3207     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
3208 
3209     if (testctx) {
3210         int ret;
3211 
3212         if (curr->list != NULL)
3213             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
3214         else
3215             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
3216 
3217         if (!ret) {
3218             if (curr->valid)
3219                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
3220             else
3221                 testresult = 1;
3222             goto end;
3223         }
3224         if (!curr->valid) {
3225             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
3226             goto end;
3227         }
3228     }
3229 
3230     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3231             &clientssl, NULL, NULL)))
3232         goto end;
3233 
3234     if (!testctx) {
3235         int ret;
3236 
3237         if (curr->list != NULL)
3238             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
3239         else
3240             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
3241         if (!ret) {
3242             if (curr->valid)
3243                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
3244             else
3245                 testresult = 1;
3246             goto end;
3247         }
3248         if (!curr->valid)
3249             goto end;
3250     }
3251 
3252     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
3253                          SSL_ERROR_NONE),
3254             curr->connsuccess))
3255         goto end;
3256 
3257     testresult = 1;
3258 
3259 end:
3260     SSL_free(serverssl);
3261     SSL_free(clientssl);
3262     SSL_CTX_free(sctx);
3263     SSL_CTX_free(cctx);
3264 
3265     return testresult;
3266 }
3267 #endif
3268 
3269 #ifndef OSSL_NO_USABLE_TLS1_3
3270 static int psk_client_cb_cnt = 0;
3271 static int psk_server_cb_cnt = 0;
3272 
3273 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
3274     size_t *idlen, SSL_SESSION **sess)
3275 {
3276     switch (++use_session_cb_cnt) {
3277     case 1:
3278         /* The first call should always have a NULL md */
3279         if (md != NULL)
3280             return 0;
3281         break;
3282 
3283     case 2:
3284         /* The second call should always have an md */
3285         if (md == NULL)
3286             return 0;
3287         break;
3288 
3289     default:
3290         /* We should only be called a maximum of twice */
3291         return 0;
3292     }
3293 
3294     if (clientpsk != NULL && !SSL_SESSION_up_ref(clientpsk))
3295         return 0;
3296 
3297     *sess = clientpsk;
3298     *id = (const unsigned char *)pskid;
3299     *idlen = strlen(pskid);
3300 
3301     return 1;
3302 }
3303 
3304 #ifndef OPENSSL_NO_PSK
3305 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
3306     unsigned int max_id_len,
3307     unsigned char *psk,
3308     unsigned int max_psk_len)
3309 {
3310     unsigned int psklen = 0;
3311 
3312     psk_client_cb_cnt++;
3313 
3314     if (strlen(pskid) + 1 > max_id_len)
3315         return 0;
3316 
3317     /* We should only ever be called a maximum of twice per connection */
3318     if (psk_client_cb_cnt > 2)
3319         return 0;
3320 
3321     if (clientpsk == NULL)
3322         return 0;
3323 
3324     /* We'll reuse the PSK we set up for TLSv1.3 */
3325     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
3326         return 0;
3327     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
3328     strncpy(id, pskid, max_id_len);
3329 
3330     return psklen;
3331 }
3332 #endif /* OPENSSL_NO_PSK */
3333 
3334 static int find_session_cb(SSL *ssl, const unsigned char *identity,
3335     size_t identity_len, SSL_SESSION **sess)
3336 {
3337     find_session_cb_cnt++;
3338 
3339     /* We should only ever be called a maximum of twice per connection */
3340     if (find_session_cb_cnt > 2)
3341         return 0;
3342 
3343     if (serverpsk == NULL)
3344         return 0;
3345 
3346     /* Identity should match that set by the client */
3347     if (strlen(srvid) != identity_len
3348         || strncmp(srvid, (const char *)identity, identity_len) != 0) {
3349         /* No PSK found, continue but without a PSK */
3350         *sess = NULL;
3351         return 1;
3352     }
3353 
3354     if (!SSL_SESSION_up_ref(serverpsk))
3355         return 0;
3356 
3357     *sess = serverpsk;
3358 
3359     return 1;
3360 }
3361 
3362 #ifndef OPENSSL_NO_PSK
3363 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
3364     unsigned char *psk, unsigned int max_psk_len)
3365 {
3366     unsigned int psklen = 0;
3367 
3368     psk_server_cb_cnt++;
3369 
3370     /* We should only ever be called a maximum of twice per connection */
3371     if (find_session_cb_cnt > 2)
3372         return 0;
3373 
3374     if (serverpsk == NULL)
3375         return 0;
3376 
3377     /* Identity should match that set by the client */
3378     if (strcmp(srvid, identity) != 0) {
3379         return 0;
3380     }
3381 
3382     /* We'll reuse the PSK we set up for TLSv1.3 */
3383     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
3384         return 0;
3385     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
3386 
3387     return psklen;
3388 }
3389 #endif /* OPENSSL_NO_PSK */
3390 
3391 #define MSG1 "Hello"
3392 #define MSG2 "World."
3393 #define MSG3 "This"
3394 #define MSG4 "is"
3395 #define MSG5 "a"
3396 #define MSG6 "test"
3397 #define MSG7 "message."
3398 
3399 static int artificial_ticket_time = 0;
3400 
3401 static int sub_session_time(SSL_SESSION *sess)
3402 {
3403     OSSL_TIME tick_time;
3404 
3405     tick_time = ossl_time_from_time_t(SSL_SESSION_get_time_ex(sess));
3406     tick_time = ossl_time_subtract(tick_time, ossl_seconds2time(10));
3407 
3408     return SSL_SESSION_set_time_ex(sess, ossl_time_to_time_t(tick_time)) != 0;
3409 }
3410 
3411 static int ed_gen_cb(SSL *s, void *arg)
3412 {
3413     SSL_SESSION *sess = SSL_get0_session(s);
3414 
3415     if (sess == NULL)
3416         return 0;
3417 
3418     /*
3419      * Artificially give the ticket some age. Just do it for the number of
3420      * tickets we've been told to do.
3421      */
3422     if (artificial_ticket_time == 0)
3423         return 1;
3424     artificial_ticket_time--;
3425 
3426     return sub_session_time(sess);
3427 }
3428 
3429 /*
3430  * Helper method to setup objects for early data test. Caller frees objects on
3431  * error.
3432  */
3433 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
3434     SSL **serverssl, SSL_SESSION **sess, int idx,
3435     size_t mdsize)
3436 {
3437     int artificial = (artificial_ticket_time > 0);
3438 
3439     if (*sctx == NULL
3440         && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3441             TLS_client_method(),
3442             TLS1_VERSION, 0,
3443             sctx, cctx, cert, privkey)))
3444         return 0;
3445 
3446     if (artificial)
3447         SSL_CTX_set_session_ticket_cb(*sctx, ed_gen_cb, NULL, NULL);
3448 
3449     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
3450         return 0;
3451 
3452     if (idx == 1) {
3453         /* When idx == 1 we repeat the tests with read_ahead set */
3454         SSL_CTX_set_read_ahead(*cctx, 1);
3455         SSL_CTX_set_read_ahead(*sctx, 1);
3456     } else if (idx == 2) {
3457         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
3458         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
3459         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
3460         use_session_cb_cnt = 0;
3461         find_session_cb_cnt = 0;
3462         srvid = pskid;
3463     }
3464 
3465     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
3466             NULL, NULL)))
3467         return 0;
3468 
3469     /*
3470      * For one of the run throughs (doesn't matter which one), we'll try sending
3471      * some SNI data in the initial ClientHello. This will be ignored (because
3472      * there is no SNI cb set up by the server), so it should not impact
3473      * early_data.
3474      */
3475     if (idx == 1
3476         && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
3477         return 0;
3478 
3479     if (idx == 2) {
3480         clientpsk = create_a_psk(*clientssl, mdsize);
3481         if (!TEST_ptr(clientpsk)
3482             /*
3483              * We just choose an arbitrary value for max_early_data which
3484              * should be big enough for testing purposes.
3485              */
3486             || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
3487                 0x100))
3488             || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3489             SSL_SESSION_free(clientpsk);
3490             clientpsk = NULL;
3491             return 0;
3492         }
3493         serverpsk = clientpsk;
3494 
3495         if (sess != NULL) {
3496             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3497                 SSL_SESSION_free(clientpsk);
3498                 SSL_SESSION_free(serverpsk);
3499                 clientpsk = serverpsk = NULL;
3500                 return 0;
3501             }
3502             *sess = clientpsk;
3503         }
3504         return 1;
3505     }
3506 
3507     if (sess == NULL)
3508         return 1;
3509 
3510     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
3511             SSL_ERROR_NONE)))
3512         return 0;
3513 
3514     *sess = SSL_get1_session(*clientssl);
3515     SSL_shutdown(*clientssl);
3516     SSL_shutdown(*serverssl);
3517     SSL_free(*serverssl);
3518     SSL_free(*clientssl);
3519     *serverssl = *clientssl = NULL;
3520 
3521     /*
3522      * Artificially give the ticket some age to match the artificial age we
3523      * gave it on the server side
3524      */
3525     if (artificial
3526         && !TEST_true(sub_session_time(*sess)))
3527         return 0;
3528 
3529     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
3530             clientssl, NULL, NULL))
3531         || !TEST_true(SSL_set_session(*clientssl, *sess)))
3532         return 0;
3533 
3534     return 1;
3535 }
3536 
3537 static int check_early_data_timeout(OSSL_TIME timer)
3538 {
3539     int res = 0;
3540 
3541     /*
3542      * Early data is time sensitive. We have an approx 8 second allowance
3543      * between writing the early data and reading it. If we exceed that time
3544      * then this test will fail. This can sometimes (rarely) occur in normal CI
3545      * operation. We can try and detect this and just ignore the result of this
3546      * test if it has taken too long. We assume anything over 7 seconds is too
3547      * long
3548      */
3549     timer = ossl_time_subtract(ossl_time_now(), timer);
3550     if (ossl_time_compare(timer, ossl_seconds2time(7)) >= 0)
3551         res = TEST_skip("Test took too long, ignoring result");
3552 
3553     return res;
3554 }
3555 
3556 static int test_early_data_read_write(int idx)
3557 {
3558     SSL_CTX *cctx = NULL, *sctx = NULL;
3559     SSL *clientssl = NULL, *serverssl = NULL;
3560     int testresult = 0;
3561     SSL_SESSION *sess = NULL;
3562     unsigned char buf[20], data[1024];
3563     size_t readbytes, written, eoedlen, rawread, rawwritten;
3564     BIO *rbio;
3565     OSSL_TIME timer;
3566 
3567     /* Artificially give the next 2 tickets some age for non PSK sessions */
3568     if (idx != 2)
3569         artificial_ticket_time = 2;
3570     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3571             &serverssl, &sess, idx,
3572             SHA384_DIGEST_LENGTH))) {
3573         artificial_ticket_time = 0;
3574         goto end;
3575     }
3576     artificial_ticket_time = 0;
3577 
3578     /* Write and read some early data */
3579     timer = ossl_time_now();
3580     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3581             &written))
3582         || !TEST_size_t_eq(written, strlen(MSG1)))
3583         goto end;
3584 
3585     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3586                          &readbytes),
3587             SSL_READ_EARLY_DATA_SUCCESS)) {
3588         testresult = check_early_data_timeout(timer);
3589         goto end;
3590     }
3591 
3592     if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
3593         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3594             SSL_EARLY_DATA_ACCEPTED))
3595         goto end;
3596 
3597     /*
3598      * Server should be able to write data, and client should be able to
3599      * read it.
3600      */
3601     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
3602             &written))
3603         || !TEST_size_t_eq(written, strlen(MSG2))
3604         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3605         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3606         goto end;
3607 
3608     /* Even after reading normal data, client should be able write early data */
3609     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
3610             &written))
3611         || !TEST_size_t_eq(written, strlen(MSG3)))
3612         goto end;
3613 
3614     /* Server should still be able read early data after writing data */
3615     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3616                          &readbytes),
3617             SSL_READ_EARLY_DATA_SUCCESS)
3618         || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
3619         goto end;
3620 
3621     /* Write more data from server and read it from client */
3622     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
3623             &written))
3624         || !TEST_size_t_eq(written, strlen(MSG4))
3625         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3626         || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
3627         goto end;
3628 
3629     /*
3630      * If client writes normal data it should mean writing early data is no
3631      * longer possible.
3632      */
3633     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3634         || !TEST_size_t_eq(written, strlen(MSG5))
3635         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3636             SSL_EARLY_DATA_ACCEPTED))
3637         goto end;
3638 
3639     /*
3640      * At this point the client has written EndOfEarlyData, ClientFinished and
3641      * normal (fully protected) data. We are going to cause a delay between the
3642      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
3643      * in the read BIO, and then just put back the EndOfEarlyData message.
3644      */
3645     rbio = SSL_get_rbio(serverssl);
3646     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
3647         || !TEST_size_t_lt(rawread, sizeof(data))
3648         || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
3649         goto end;
3650 
3651     /* Record length is in the 4th and 5th bytes of the record header */
3652     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
3653     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
3654         || !TEST_size_t_eq(rawwritten, eoedlen))
3655         goto end;
3656 
3657     /* Server should be told that there is no more early data */
3658     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3659                          &readbytes),
3660             SSL_READ_EARLY_DATA_FINISH)
3661         || !TEST_size_t_eq(readbytes, 0))
3662         goto end;
3663 
3664     /*
3665      * Server has not finished init yet, so should still be able to write early
3666      * data.
3667      */
3668     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
3669             &written))
3670         || !TEST_size_t_eq(written, strlen(MSG6)))
3671         goto end;
3672 
3673     /* Push the ClientFinished and the normal data back into the server rbio */
3674     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
3675             &rawwritten))
3676         || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
3677         goto end;
3678 
3679     /* Server should be able to read normal data */
3680     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3681         || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3682         goto end;
3683 
3684     /* Client and server should not be able to write/read early data now */
3685     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3686             &written)))
3687         goto end;
3688     ERR_clear_error();
3689     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3690                          &readbytes),
3691             SSL_READ_EARLY_DATA_ERROR))
3692         goto end;
3693     ERR_clear_error();
3694 
3695     /* Client should be able to read the data sent by the server */
3696     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3697         || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
3698         goto end;
3699 
3700     /*
3701      * Make sure we process the two NewSessionTickets. These arrive
3702      * post-handshake. We attempt reads which we do not expect to return any
3703      * data.
3704      */
3705     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3706         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3707             &readbytes)))
3708         goto end;
3709 
3710     /* Server should be able to write normal data */
3711     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3712         || !TEST_size_t_eq(written, strlen(MSG7))
3713         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3714         || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3715         goto end;
3716 
3717     SSL_SESSION_free(sess);
3718     sess = SSL_get1_session(clientssl);
3719     use_session_cb_cnt = 0;
3720     find_session_cb_cnt = 0;
3721 
3722     SSL_shutdown(clientssl);
3723     SSL_shutdown(serverssl);
3724     SSL_free(serverssl);
3725     SSL_free(clientssl);
3726     serverssl = clientssl = NULL;
3727     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3728             &clientssl, NULL, NULL))
3729         || !TEST_true(SSL_set_session(clientssl, sess)))
3730         goto end;
3731 
3732     /* Write and read some early data */
3733     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3734             &written))
3735         || !TEST_size_t_eq(written, strlen(MSG1))
3736         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3737                             &readbytes),
3738             SSL_READ_EARLY_DATA_SUCCESS)
3739         || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3740         goto end;
3741 
3742     if (!TEST_int_gt(SSL_connect(clientssl), 0)
3743         || !TEST_int_gt(SSL_accept(serverssl), 0))
3744         goto end;
3745 
3746     /* Client and server should not be able to write/read early data now */
3747     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3748             &written)))
3749         goto end;
3750     ERR_clear_error();
3751     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3752                          &readbytes),
3753             SSL_READ_EARLY_DATA_ERROR))
3754         goto end;
3755     ERR_clear_error();
3756 
3757     /* Client and server should be able to write/read normal data */
3758     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3759         || !TEST_size_t_eq(written, strlen(MSG5))
3760         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3761         || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3762         goto end;
3763 
3764     testresult = 1;
3765 
3766 end:
3767     SSL_SESSION_free(sess);
3768     SSL_SESSION_free(clientpsk);
3769     SSL_SESSION_free(serverpsk);
3770     clientpsk = serverpsk = NULL;
3771     SSL_free(serverssl);
3772     SSL_free(clientssl);
3773     SSL_CTX_free(sctx);
3774     SSL_CTX_free(cctx);
3775     return testresult;
3776 }
3777 
3778 static int allow_ed_cb_called = 0;
3779 
3780 static int allow_early_data_cb(SSL *s, void *arg)
3781 {
3782     int *usecb = (int *)arg;
3783 
3784     allow_ed_cb_called++;
3785 
3786     if (*usecb == 1)
3787         return 0;
3788 
3789     return 1;
3790 }
3791 
3792 /*
3793  * idx == 0: Standard early_data setup
3794  * idx == 1: early_data setup using read_ahead
3795  * usecb == 0: Don't use a custom early data callback
3796  * usecb == 1: Use a custom early data callback and reject the early data
3797  * usecb == 2: Use a custom early data callback and accept the early data
3798  * confopt == 0: Configure anti-replay directly
3799  * confopt == 1: Configure anti-replay using SSL_CONF
3800  */
3801 static int test_early_data_replay_int(int idx, int usecb, int confopt)
3802 {
3803     SSL_CTX *cctx = NULL, *sctx = NULL;
3804     SSL *clientssl = NULL, *serverssl = NULL;
3805     int testresult = 0;
3806     SSL_SESSION *sess = NULL;
3807     size_t readbytes, written;
3808     unsigned char buf[20];
3809     OSSL_TIME timer;
3810 
3811     allow_ed_cb_called = 0;
3812 
3813     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3814             TLS_client_method(), TLS1_VERSION, 0,
3815             &sctx, &cctx, cert, privkey)))
3816         return 0;
3817 
3818     if (usecb > 0) {
3819         if (confopt == 0) {
3820             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3821         } else {
3822             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3823 
3824             if (!TEST_ptr(confctx))
3825                 goto end;
3826             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_SERVER);
3827             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3828             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3829                     2)) {
3830                 SSL_CONF_CTX_free(confctx);
3831                 goto end;
3832             }
3833             SSL_CONF_CTX_free(confctx);
3834         }
3835         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3836     }
3837 
3838     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3839             &serverssl, &sess, idx,
3840             SHA384_DIGEST_LENGTH)))
3841         goto end;
3842 
3843     /*
3844      * The server is configured to accept early data. Create a connection to
3845      * "use up" the ticket
3846      */
3847     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3848         || !TEST_true(SSL_session_reused(clientssl)))
3849         goto end;
3850 
3851     SSL_shutdown(clientssl);
3852     SSL_shutdown(serverssl);
3853     SSL_free(serverssl);
3854     SSL_free(clientssl);
3855     serverssl = clientssl = NULL;
3856 
3857     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3858             &clientssl, NULL, NULL))
3859         || !TEST_true(SSL_set_session(clientssl, sess)))
3860         goto end;
3861 
3862     /* Write and read some early data */
3863     timer = ossl_time_now();
3864     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3865             &written))
3866         || !TEST_size_t_eq(written, strlen(MSG1)))
3867         goto end;
3868 
3869     if (usecb <= 1) {
3870         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3871                              &readbytes),
3872                 SSL_READ_EARLY_DATA_FINISH)
3873             /*
3874              * The ticket was reused, so the we should have rejected the
3875              * early data
3876              */
3877             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3878                 SSL_EARLY_DATA_REJECTED))
3879             goto end;
3880     } else {
3881         /* In this case the callback decides to accept the early data */
3882         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3883                              &readbytes),
3884                 SSL_READ_EARLY_DATA_SUCCESS)) {
3885             testresult = check_early_data_timeout(timer);
3886             goto end;
3887         }
3888         if (!TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3889             /*
3890              * Server will have sent its flight so client can now send
3891              * end of early data and complete its half of the handshake
3892              */
3893             || !TEST_int_gt(SSL_connect(clientssl), 0)
3894             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3895                                 &readbytes),
3896                 SSL_READ_EARLY_DATA_FINISH)
3897             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3898                 SSL_EARLY_DATA_ACCEPTED))
3899             goto end;
3900     }
3901 
3902     /* Complete the connection */
3903     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3904         || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3905         || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3906         goto end;
3907 
3908     testresult = 1;
3909 
3910 end:
3911     SSL_SESSION_free(sess);
3912     SSL_SESSION_free(clientpsk);
3913     SSL_SESSION_free(serverpsk);
3914     clientpsk = serverpsk = NULL;
3915     SSL_free(serverssl);
3916     SSL_free(clientssl);
3917     SSL_CTX_free(sctx);
3918     SSL_CTX_free(cctx);
3919     return testresult;
3920 }
3921 
3922 static int test_early_data_replay(int idx)
3923 {
3924     int ret = 1, usecb, confopt;
3925 
3926     for (usecb = 0; usecb < 3; usecb++) {
3927         for (confopt = 0; confopt < 2; confopt++)
3928             ret &= test_early_data_replay_int(idx, usecb, confopt);
3929     }
3930 
3931     return ret;
3932 }
3933 
3934 static const char *ciphersuites[] = {
3935     "TLS_AES_128_CCM_8_SHA256",
3936     "TLS_AES_128_GCM_SHA256",
3937     "TLS_AES_256_GCM_SHA384",
3938     "TLS_AES_128_CCM_SHA256",
3939 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3940     "TLS_CHACHA20_POLY1305_SHA256",
3941 #else
3942     NULL,
3943 #endif
3944 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
3945     "TLS_SHA256_SHA256",
3946     "TLS_SHA384_SHA384"
3947 #endif
3948 };
3949 
3950 /*
3951  * Helper function to test that a server attempting to read early data can
3952  * handle a connection from a client where the early data should be skipped.
3953  * testtype: 0 == No HRR
3954  * testtype: 1 == HRR
3955  * testtype: 2 == HRR, invalid early_data sent after HRR
3956  * testtype: 3 == recv_max_early_data set to 0
3957  */
3958 static int early_data_skip_helper(int testtype, int cipher, int idx)
3959 {
3960     SSL_CTX *cctx = NULL, *sctx = NULL;
3961     SSL *clientssl = NULL, *serverssl = NULL;
3962     int testresult = 0;
3963     SSL_SESSION *sess = NULL;
3964     unsigned char buf[20];
3965     size_t readbytes, written;
3966 
3967     if (is_fips && cipher >= 4)
3968         return 1;
3969 
3970     if (ciphersuites[cipher] == NULL)
3971         return TEST_skip("Cipher not supported");
3972 
3973     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3974             TLS_client_method(),
3975             TLS1_VERSION, 0,
3976             &sctx, &cctx, cert, privkey)))
3977         goto end;
3978 
3979     if (cipher == 0 || cipher == 5 || cipher == 6) {
3980         SSL_CTX_set_security_level(sctx, 0);
3981         SSL_CTX_set_security_level(cctx, 0);
3982     }
3983 
3984     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, ciphersuites[cipher]))
3985         || !TEST_true(SSL_CTX_set_ciphersuites(cctx, ciphersuites[cipher])))
3986         goto end;
3987 
3988     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3989             &serverssl, &sess, idx,
3990             (cipher == 2 || cipher == 6)
3991                 ? SHA384_DIGEST_LENGTH
3992                 : SHA256_DIGEST_LENGTH)))
3993         goto end;
3994 
3995     if (testtype == 1 || testtype == 2) {
3996         /* Force an HRR to occur */
3997 #if defined(OPENSSL_NO_EC)
3998         if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
3999             goto end;
4000 #else
4001         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
4002             goto end;
4003 #endif
4004     } else if (idx == 2) {
4005         /*
4006          * We force early_data rejection by ensuring the PSK identity is
4007          * unrecognised
4008          */
4009         srvid = "Dummy Identity";
4010     } else {
4011         /*
4012          * Deliberately corrupt the creation time. We take 20 seconds off the
4013          * time. It could be any value as long as it is not within tolerance.
4014          * This should mean the ticket is rejected.
4015          */
4016         if (!TEST_true(SSL_SESSION_set_time_ex(sess, time(NULL) - 20)))
4017             goto end;
4018     }
4019 
4020     if (testtype == 3
4021         && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
4022         goto end;
4023 
4024     /* Write some early data */
4025     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4026             &written))
4027         || !TEST_size_t_eq(written, strlen(MSG1)))
4028         goto end;
4029 
4030     /* Server should reject the early data */
4031     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4032                          &readbytes),
4033             SSL_READ_EARLY_DATA_FINISH)
4034         || !TEST_size_t_eq(readbytes, 0)
4035         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4036             SSL_EARLY_DATA_REJECTED))
4037         goto end;
4038 
4039     switch (testtype) {
4040     case 0:
4041         /* Nothing to do */
4042         break;
4043 
4044     case 1:
4045         /*
4046          * Finish off the handshake. We perform the same writes and reads as
4047          * further down but we expect them to fail due to the incomplete
4048          * handshake.
4049          */
4050         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4051             || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
4052                 &readbytes)))
4053             goto end;
4054         break;
4055 
4056     case 2: {
4057         BIO *wbio = SSL_get_wbio(clientssl);
4058         /* A record that will appear as bad early_data */
4059         const unsigned char bad_early_data[] = {
4060             0x17, 0x03, 0x03, 0x00, 0x01, 0x00
4061         };
4062 
4063         /*
4064          * We force the client to attempt a write. This will fail because
4065          * we're still in the handshake. It will cause the second
4066          * ClientHello to be sent.
4067          */
4068         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
4069                 &written)))
4070             goto end;
4071 
4072         /*
4073          * Inject some early_data after the second ClientHello. This should
4074          * cause the server to fail
4075          */
4076         if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
4077                 sizeof(bad_early_data), &written)))
4078             goto end;
4079     }
4080         /* FALLTHROUGH */
4081 
4082     case 3:
4083         /*
4084          * This client has sent more early_data than we are willing to skip
4085          * (case 3) or sent invalid early_data (case 2) so the connection should
4086          * abort.
4087          */
4088         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4089             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
4090             goto end;
4091 
4092         /* Connection has failed - nothing more to do */
4093         testresult = 1;
4094         goto end;
4095 
4096     default:
4097         TEST_error("Invalid test type");
4098         goto end;
4099     }
4100 
4101     ERR_clear_error();
4102     /*
4103      * Should be able to send normal data despite rejection of early data. The
4104      * early_data should be skipped.
4105      */
4106     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4107         || !TEST_size_t_eq(written, strlen(MSG2))
4108         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4109             SSL_EARLY_DATA_REJECTED)
4110         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4111         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4112         goto end;
4113 
4114     /*
4115      * Failure to decrypt early data records should not leave spurious errors
4116      * on the error stack
4117      */
4118     if (!TEST_long_eq(ERR_peek_error(), 0))
4119         goto end;
4120 
4121     testresult = 1;
4122 
4123 end:
4124     SSL_SESSION_free(clientpsk);
4125     SSL_SESSION_free(serverpsk);
4126     clientpsk = serverpsk = NULL;
4127     SSL_SESSION_free(sess);
4128     SSL_free(serverssl);
4129     SSL_free(clientssl);
4130     SSL_CTX_free(sctx);
4131     SSL_CTX_free(cctx);
4132     return testresult;
4133 }
4134 
4135 /*
4136  * Test that a server attempting to read early data can handle a connection
4137  * from a client where the early data is not acceptable.
4138  */
4139 static int test_early_data_skip(int idx)
4140 {
4141     return early_data_skip_helper(0,
4142         idx % OSSL_NELEM(ciphersuites),
4143         idx / OSSL_NELEM(ciphersuites));
4144 }
4145 
4146 /*
4147  * Test that a server attempting to read early data can handle a connection
4148  * from a client where an HRR occurs.
4149  */
4150 static int test_early_data_skip_hrr(int idx)
4151 {
4152     return early_data_skip_helper(1,
4153         idx % OSSL_NELEM(ciphersuites),
4154         idx / OSSL_NELEM(ciphersuites));
4155 }
4156 
4157 /*
4158  * Test that a server attempting to read early data can handle a connection
4159  * from a client where an HRR occurs and correctly fails if early_data is sent
4160  * after the HRR
4161  */
4162 static int test_early_data_skip_hrr_fail(int idx)
4163 {
4164     return early_data_skip_helper(2,
4165         idx % OSSL_NELEM(ciphersuites),
4166         idx / OSSL_NELEM(ciphersuites));
4167 }
4168 
4169 /*
4170  * Test that a server attempting to read early data will abort if it tries to
4171  * skip over too much.
4172  */
4173 static int test_early_data_skip_abort(int idx)
4174 {
4175     return early_data_skip_helper(3,
4176         idx % OSSL_NELEM(ciphersuites),
4177         idx / OSSL_NELEM(ciphersuites));
4178 }
4179 
4180 /*
4181  * Test that a server attempting to read early data can handle a connection
4182  * from a client that doesn't send any.
4183  */
4184 static int test_early_data_not_sent(int idx)
4185 {
4186     SSL_CTX *cctx = NULL, *sctx = NULL;
4187     SSL *clientssl = NULL, *serverssl = NULL;
4188     int testresult = 0;
4189     SSL_SESSION *sess = NULL;
4190     unsigned char buf[20];
4191     size_t readbytes, written;
4192 
4193     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4194             &serverssl, &sess, idx,
4195             SHA384_DIGEST_LENGTH)))
4196         goto end;
4197 
4198     /* Write some data - should block due to handshake with server */
4199     SSL_set_connect_state(clientssl);
4200     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4201         goto end;
4202 
4203     /* Server should detect that early data has not been sent */
4204     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4205                          &readbytes),
4206             SSL_READ_EARLY_DATA_FINISH)
4207         || !TEST_size_t_eq(readbytes, 0)
4208         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4209             SSL_EARLY_DATA_NOT_SENT)
4210         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4211             SSL_EARLY_DATA_NOT_SENT))
4212         goto end;
4213 
4214     /* Continue writing the message we started earlier */
4215     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4216         || !TEST_size_t_eq(written, strlen(MSG1))
4217         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4218         || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4219         || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
4220         || !TEST_size_t_eq(written, strlen(MSG2)))
4221         goto end;
4222 
4223     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4224         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4225         goto end;
4226 
4227     testresult = 1;
4228 
4229 end:
4230     SSL_SESSION_free(sess);
4231     SSL_SESSION_free(clientpsk);
4232     SSL_SESSION_free(serverpsk);
4233     clientpsk = serverpsk = NULL;
4234     SSL_free(serverssl);
4235     SSL_free(clientssl);
4236     SSL_CTX_free(sctx);
4237     SSL_CTX_free(cctx);
4238     return testresult;
4239 }
4240 
4241 static const char *servalpn;
4242 
4243 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
4244     unsigned char *outlen, const unsigned char *in,
4245     unsigned int inlen, void *arg)
4246 {
4247     unsigned int protlen = 0;
4248     const unsigned char *prot;
4249 
4250     for (prot = in; prot < in + inlen; prot += protlen) {
4251         protlen = *prot++;
4252         if (in + inlen < prot + protlen)
4253             return SSL_TLSEXT_ERR_NOACK;
4254 
4255         if (protlen == strlen(servalpn)
4256             && memcmp(prot, servalpn, protlen) == 0) {
4257             *out = prot;
4258             *outlen = protlen;
4259             return SSL_TLSEXT_ERR_OK;
4260         }
4261     }
4262 
4263     return SSL_TLSEXT_ERR_NOACK;
4264 }
4265 
4266 /* Test that a PSK can be used to send early_data */
4267 static int test_early_data_psk(int idx)
4268 {
4269     SSL_CTX *cctx = NULL, *sctx = NULL;
4270     SSL *clientssl = NULL, *serverssl = NULL;
4271     int testresult = 0;
4272     SSL_SESSION *sess = NULL;
4273     unsigned char alpnlist[] = {
4274         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
4275         'l', 'p', 'n'
4276     };
4277 #define GOODALPNLEN 9
4278 #define BADALPNLEN 8
4279 #define GOODALPN (alpnlist)
4280 #define BADALPN (alpnlist + GOODALPNLEN)
4281     int err = 0;
4282     unsigned char buf[20];
4283     size_t readbytes, written;
4284     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
4285     int edstatus = SSL_EARLY_DATA_ACCEPTED;
4286 
4287     /* We always set this up with a final parameter of "2" for PSK */
4288     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4289             &serverssl, &sess, 2,
4290             SHA384_DIGEST_LENGTH)))
4291         goto end;
4292 
4293     servalpn = "goodalpn";
4294 
4295     /*
4296      * Note: There is no test for inconsistent SNI with late client detection.
4297      * This is because servers do not acknowledge SNI even if they are using
4298      * it in a resumption handshake - so it is not actually possible for a
4299      * client to detect a problem.
4300      */
4301     switch (idx) {
4302     case 0:
4303         /* Set inconsistent SNI (early client detection) */
4304         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
4305         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4306             || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
4307             goto end;
4308         break;
4309 
4310     case 1:
4311         /* Set inconsistent ALPN (early client detection) */
4312         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
4313         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
4314         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
4315                 GOODALPNLEN))
4316             || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
4317                 BADALPNLEN)))
4318             goto end;
4319         break;
4320 
4321     case 2:
4322         /*
4323          * Set invalid protocol version. Technically this affects PSKs without
4324          * early_data too, but we test it here because it is similar to the
4325          * SNI/ALPN consistency tests.
4326          */
4327         err = SSL_R_BAD_PSK;
4328         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
4329             goto end;
4330         break;
4331 
4332     case 3:
4333         /*
4334          * Set inconsistent SNI (server side). In this case the connection
4335          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
4336          * is associated with each handshake - not the session. Therefore it
4337          * should not matter that we used a different server name last time.
4338          */
4339         SSL_SESSION_free(serverpsk);
4340         serverpsk = SSL_SESSION_dup(clientpsk);
4341         if (!TEST_ptr(serverpsk)
4342             || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
4343             goto end;
4344         /* Fall through */
4345     case 4:
4346         /* Set consistent SNI */
4347         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4348             || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
4349             || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
4350                 hostname_cb)))
4351             goto end;
4352         break;
4353 
4354     case 5:
4355         /*
4356          * Set inconsistent ALPN (server detected). In this case the connection
4357          * will succeed but reject early_data.
4358          */
4359         servalpn = "badalpn";
4360         edstatus = SSL_EARLY_DATA_REJECTED;
4361         readearlyres = SSL_READ_EARLY_DATA_FINISH;
4362         /* Fall through */
4363     case 6:
4364         /*
4365          * Set consistent ALPN.
4366          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
4367          * accepts a list of protos (each one length prefixed).
4368          * SSL_set1_alpn_selected accepts a single protocol (not length
4369          * prefixed)
4370          */
4371         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
4372                 GOODALPNLEN - 1))
4373             || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
4374                 GOODALPNLEN)))
4375             goto end;
4376 
4377         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4378         break;
4379 
4380     case 7:
4381         /* Set inconsistent ALPN (late client detection) */
4382         SSL_SESSION_free(serverpsk);
4383         serverpsk = SSL_SESSION_dup(clientpsk);
4384         if (!TEST_ptr(serverpsk)
4385             || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
4386                 BADALPN + 1,
4387                 BADALPNLEN - 1))
4388             || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
4389                 GOODALPN + 1,
4390                 GOODALPNLEN - 1))
4391             || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
4392                 sizeof(alpnlist))))
4393             goto end;
4394         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4395         edstatus = SSL_EARLY_DATA_ACCEPTED;
4396         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
4397         /* SSL_connect() call should fail */
4398         connectres = -1;
4399         break;
4400 
4401     default:
4402         TEST_error("Bad test index");
4403         goto end;
4404     }
4405 
4406     SSL_set_connect_state(clientssl);
4407     if (err != 0) {
4408         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4409                 &written))
4410             || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
4411             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
4412             goto end;
4413     } else {
4414         OSSL_TIME timer = ossl_time_now();
4415 
4416         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4417                 &written)))
4418             goto end;
4419 
4420         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4421                              &readbytes),
4422                 readearlyres)) {
4423             testresult = check_early_data_timeout(timer);
4424             goto end;
4425         }
4426 
4427         if ((readearlyres == SSL_READ_EARLY_DATA_SUCCESS
4428                 && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
4429             || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
4430             || !TEST_int_eq(SSL_connect(clientssl), connectres))
4431             goto end;
4432     }
4433 
4434     testresult = 1;
4435 
4436 end:
4437     SSL_SESSION_free(sess);
4438     SSL_SESSION_free(clientpsk);
4439     SSL_SESSION_free(serverpsk);
4440     clientpsk = serverpsk = NULL;
4441     SSL_free(serverssl);
4442     SSL_free(clientssl);
4443     SSL_CTX_free(sctx);
4444     SSL_CTX_free(cctx);
4445     return testresult;
4446 }
4447 
4448 /*
4449  * Test TLSv1.3 PSK can be used to send early_data with all 7 ciphersuites
4450  * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
4451  * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
4452  * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4453  * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
4454  * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
4455  * idx == 5: Test with TLS1_3_RFC_SHA256_SHA256
4456  * idx == 6: Test with TLS1_3_RFC_SHA384_SHA384
4457  */
4458 static int test_early_data_psk_with_all_ciphers(int idx)
4459 {
4460     SSL_CTX *cctx = NULL, *sctx = NULL;
4461     SSL *clientssl = NULL, *serverssl = NULL;
4462     int testresult = 0;
4463     SSL_SESSION *sess = NULL;
4464     unsigned char buf[20];
4465     size_t readbytes, written;
4466     const SSL_CIPHER *cipher;
4467     OSSL_TIME timer;
4468     const char *cipher_str[] = {
4469         TLS1_3_RFC_AES_128_GCM_SHA256,
4470         TLS1_3_RFC_AES_256_GCM_SHA384,
4471 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4472         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4473 #else
4474         NULL,
4475 #endif
4476         TLS1_3_RFC_AES_128_CCM_SHA256,
4477         TLS1_3_RFC_AES_128_CCM_8_SHA256,
4478 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4479         TLS1_3_RFC_SHA256_SHA256,
4480         TLS1_3_RFC_SHA384_SHA384
4481 #else
4482         NULL,
4483         NULL
4484 #endif
4485     };
4486     const unsigned char *cipher_bytes[] = {
4487         TLS13_AES_128_GCM_SHA256_BYTES,
4488         TLS13_AES_256_GCM_SHA384_BYTES,
4489 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4490         TLS13_CHACHA20_POLY1305_SHA256_BYTES,
4491 #else
4492         NULL,
4493 #endif
4494         TLS13_AES_128_CCM_SHA256_BYTES,
4495         TLS13_AES_128_CCM_8_SHA256_BYTES,
4496 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4497         TLS13_SHA256_SHA256_BYTES,
4498         TLS13_SHA384_SHA384_BYTES
4499 #else
4500         NULL,
4501         NULL
4502 #endif
4503     };
4504 
4505     if (cipher_str[idx] == NULL)
4506         return 1;
4507     /*
4508      * Skip ChaCha20Poly1305 and TLS_SHA{256,384}_SHA{256,384} ciphers
4509      * as currently FIPS module does not support them.
4510      */
4511     if ((idx == 2 || idx == 5 || idx == 6) && is_fips == 1)
4512         return 1;
4513 
4514     /* We always set this up with a final parameter of "2" for PSK */
4515     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4516             &serverssl, &sess, 2,
4517             SHA384_DIGEST_LENGTH)))
4518         goto end;
4519 
4520     if (idx == 4 || idx == 5 || idx == 6) {
4521         /*
4522          * CCM8 ciphers are considered low security due to their short tag.
4523          * Integrity-only cipher do not provide any confidentiality.
4524          */
4525         SSL_set_security_level(clientssl, 0);
4526         SSL_set_security_level(serverssl, 0);
4527     }
4528 
4529     if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
4530         || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
4531         goto end;
4532 
4533     /*
4534      * 'setupearly_data_test' creates only one instance of SSL_SESSION
4535      * and assigns to both client and server with incremented reference
4536      * and the same instance is updated in 'sess'.
4537      * So updating ciphersuite in 'sess' which will get reflected in
4538      * PSK handshake using psk use sess and find sess cb.
4539      */
4540     cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
4541     if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
4542         goto end;
4543 
4544     SSL_set_connect_state(clientssl);
4545     timer = ossl_time_now();
4546     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4547             &written)))
4548         goto end;
4549 
4550     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4551                          &readbytes),
4552             SSL_READ_EARLY_DATA_SUCCESS)) {
4553         testresult = check_early_data_timeout(timer);
4554         goto end;
4555     }
4556 
4557     if (!TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4558         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4559             SSL_EARLY_DATA_ACCEPTED)
4560         || !TEST_int_eq(SSL_connect(clientssl), 1)
4561         || !TEST_int_eq(SSL_accept(serverssl), 1))
4562         goto end;
4563 
4564     /* Send some normal data from client to server */
4565     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4566         || !TEST_size_t_eq(written, strlen(MSG2)))
4567         goto end;
4568 
4569     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4570         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4571         goto end;
4572 
4573     testresult = 1;
4574 end:
4575     SSL_SESSION_free(sess);
4576     SSL_SESSION_free(clientpsk);
4577     SSL_SESSION_free(serverpsk);
4578     clientpsk = serverpsk = NULL;
4579     if (clientssl != NULL)
4580         SSL_shutdown(clientssl);
4581     if (serverssl != NULL)
4582         SSL_shutdown(serverssl);
4583     SSL_free(serverssl);
4584     SSL_free(clientssl);
4585     SSL_CTX_free(sctx);
4586     SSL_CTX_free(cctx);
4587     return testresult;
4588 }
4589 
4590 /*
4591  * Test that a server that doesn't try to read early data can handle a
4592  * client sending some.
4593  */
4594 static int test_early_data_not_expected(int idx)
4595 {
4596     SSL_CTX *cctx = NULL, *sctx = NULL;
4597     SSL *clientssl = NULL, *serverssl = NULL;
4598     int testresult = 0;
4599     SSL_SESSION *sess = NULL;
4600     unsigned char buf[20];
4601     size_t readbytes, written;
4602 
4603     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4604             &serverssl, &sess, idx,
4605             SHA384_DIGEST_LENGTH)))
4606         goto end;
4607 
4608     /* Write some early data */
4609     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4610             &written)))
4611         goto end;
4612 
4613     /*
4614      * Server should skip over early data and then block waiting for client to
4615      * continue handshake
4616      */
4617     if (!TEST_int_le(SSL_accept(serverssl), 0)
4618         || !TEST_int_gt(SSL_connect(clientssl), 0)
4619         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4620             SSL_EARLY_DATA_REJECTED)
4621         || !TEST_int_gt(SSL_accept(serverssl), 0)
4622         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4623             SSL_EARLY_DATA_REJECTED))
4624         goto end;
4625 
4626     /* Send some normal data from client to server */
4627     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4628         || !TEST_size_t_eq(written, strlen(MSG2)))
4629         goto end;
4630 
4631     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4632         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4633         goto end;
4634 
4635     testresult = 1;
4636 
4637 end:
4638     SSL_SESSION_free(sess);
4639     SSL_SESSION_free(clientpsk);
4640     SSL_SESSION_free(serverpsk);
4641     clientpsk = serverpsk = NULL;
4642     SSL_free(serverssl);
4643     SSL_free(clientssl);
4644     SSL_CTX_free(sctx);
4645     SSL_CTX_free(cctx);
4646     return testresult;
4647 }
4648 
4649 #ifndef OPENSSL_NO_TLS1_2
4650 /*
4651  * Test that a server attempting to read early data can handle a connection
4652  * from a TLSv1.2 client.
4653  */
4654 static int test_early_data_tls1_2(int idx)
4655 {
4656     SSL_CTX *cctx = NULL, *sctx = NULL;
4657     SSL *clientssl = NULL, *serverssl = NULL;
4658     int testresult = 0;
4659     unsigned char buf[20];
4660     size_t readbytes, written;
4661 
4662     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4663             &serverssl, NULL, idx,
4664             SHA384_DIGEST_LENGTH)))
4665         goto end;
4666 
4667     /* Write some data - should block due to handshake with server */
4668     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
4669     SSL_set_connect_state(clientssl);
4670     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4671         goto end;
4672 
4673     /*
4674      * Server should do TLSv1.2 handshake. First it will block waiting for more
4675      * messages from client after ServerDone. Then SSL_read_early_data should
4676      * finish and detect that early data has not been sent
4677      */
4678     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4679                          &readbytes),
4680             SSL_READ_EARLY_DATA_ERROR))
4681         goto end;
4682 
4683     /*
4684      * Continue writing the message we started earlier. Will still block waiting
4685      * for the CCS/Finished from server
4686      */
4687     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4688         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4689                             &readbytes),
4690             SSL_READ_EARLY_DATA_FINISH)
4691         || !TEST_size_t_eq(readbytes, 0)
4692         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4693             SSL_EARLY_DATA_NOT_SENT))
4694         goto end;
4695 
4696     /* Continue writing the message we started earlier */
4697     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4698         || !TEST_size_t_eq(written, strlen(MSG1))
4699         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4700             SSL_EARLY_DATA_NOT_SENT)
4701         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4702         || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4703         || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
4704         || !TEST_size_t_eq(written, strlen(MSG2))
4705         || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
4706         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4707         goto end;
4708 
4709     testresult = 1;
4710 
4711 end:
4712     SSL_SESSION_free(clientpsk);
4713     SSL_SESSION_free(serverpsk);
4714     clientpsk = serverpsk = NULL;
4715     SSL_free(serverssl);
4716     SSL_free(clientssl);
4717     SSL_CTX_free(sctx);
4718     SSL_CTX_free(cctx);
4719 
4720     return testresult;
4721 }
4722 #endif /* OPENSSL_NO_TLS1_2 */
4723 
4724 /*
4725  * Test configuring the TLSv1.3 ciphersuites
4726  *
4727  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
4728  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
4729  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
4730  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
4731  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4732  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4733  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
4734  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
4735  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
4736  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
4737  */
4738 static int test_set_ciphersuite(int idx)
4739 {
4740     SSL_CTX *cctx = NULL, *sctx = NULL;
4741     SSL *clientssl = NULL, *serverssl = NULL;
4742     int testresult = 0;
4743 
4744     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4745             TLS_client_method(), TLS1_VERSION, 0,
4746             &sctx, &cctx, cert, privkey))
4747         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4748             "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
4749         goto end;
4750 
4751     if (idx >= 4 && idx <= 7) {
4752         /* SSL_CTX explicit cipher list */
4753         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
4754             goto end;
4755     }
4756 
4757     if (idx == 0 || idx == 4) {
4758         /* Default ciphersuite */
4759         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4760                 "TLS_AES_128_GCM_SHA256")))
4761             goto end;
4762     } else if (idx == 1 || idx == 5) {
4763         /* Non default ciphersuite */
4764         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4765                 "TLS_AES_128_CCM_SHA256")))
4766             goto end;
4767     }
4768 
4769     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4770             &clientssl, NULL, NULL)))
4771         goto end;
4772 
4773     if (idx == 8 || idx == 9) {
4774         /* SSL explicit cipher list */
4775         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
4776             goto end;
4777     }
4778 
4779     if (idx == 2 || idx == 6 || idx == 8) {
4780         /* Default ciphersuite */
4781         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4782                 "TLS_AES_128_GCM_SHA256")))
4783             goto end;
4784     } else if (idx == 3 || idx == 7 || idx == 9) {
4785         /* Non default ciphersuite */
4786         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4787                 "TLS_AES_128_CCM_SHA256")))
4788             goto end;
4789     }
4790 
4791     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4792         goto end;
4793 
4794     testresult = 1;
4795 
4796 end:
4797     SSL_free(serverssl);
4798     SSL_free(clientssl);
4799     SSL_CTX_free(sctx);
4800     SSL_CTX_free(cctx);
4801 
4802     return testresult;
4803 }
4804 
4805 static int test_ciphersuite_change(void)
4806 {
4807     SSL_CTX *cctx = NULL, *sctx = NULL;
4808     SSL *clientssl = NULL, *serverssl = NULL;
4809     SSL_SESSION *clntsess = NULL;
4810     int testresult = 0;
4811     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
4812 
4813     /* Create a session based on SHA-256 */
4814     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4815             TLS_client_method(), TLS1_VERSION, 0,
4816             &sctx, &cctx, cert, privkey))
4817         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4818             "TLS_AES_128_GCM_SHA256:"
4819             "TLS_AES_256_GCM_SHA384:"
4820             "TLS_AES_128_CCM_SHA256"))
4821         || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4822             "TLS_AES_128_GCM_SHA256")))
4823         goto end;
4824 
4825     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4826             NULL, NULL))
4827         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4828             SSL_ERROR_NONE)))
4829         goto end;
4830 
4831     clntsess = SSL_get1_session(clientssl);
4832     /* Save for later */
4833     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
4834     SSL_shutdown(clientssl);
4835     SSL_shutdown(serverssl);
4836     SSL_free(serverssl);
4837     SSL_free(clientssl);
4838     serverssl = clientssl = NULL;
4839 
4840     /* Check we can resume a session with a different SHA-256 ciphersuite */
4841     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4842             "TLS_AES_128_CCM_SHA256"))
4843         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4844             &clientssl, NULL, NULL))
4845         || !TEST_true(SSL_set_session(clientssl, clntsess))
4846         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4847             SSL_ERROR_NONE))
4848         || !TEST_true(SSL_session_reused(clientssl)))
4849         goto end;
4850 
4851     SSL_SESSION_free(clntsess);
4852     clntsess = SSL_get1_session(clientssl);
4853     SSL_shutdown(clientssl);
4854     SSL_shutdown(serverssl);
4855     SSL_free(serverssl);
4856     SSL_free(clientssl);
4857     serverssl = clientssl = NULL;
4858 
4859     /*
4860      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
4861      * succeeds but does not resume.
4862      */
4863     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4864         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4865             NULL, NULL))
4866         || !TEST_true(SSL_set_session(clientssl, clntsess))
4867         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4868             SSL_ERROR_SSL))
4869         || !TEST_false(SSL_session_reused(clientssl)))
4870         goto end;
4871 
4872     SSL_SESSION_free(clntsess);
4873     clntsess = NULL;
4874     SSL_shutdown(clientssl);
4875     SSL_shutdown(serverssl);
4876     SSL_free(serverssl);
4877     SSL_free(clientssl);
4878     serverssl = clientssl = NULL;
4879 
4880     /* Create a session based on SHA384 */
4881     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4882         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4883             &clientssl, NULL, NULL))
4884         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4885             SSL_ERROR_NONE)))
4886         goto end;
4887 
4888     clntsess = SSL_get1_session(clientssl);
4889     SSL_shutdown(clientssl);
4890     SSL_shutdown(serverssl);
4891     SSL_free(serverssl);
4892     SSL_free(clientssl);
4893     serverssl = clientssl = NULL;
4894 
4895     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4896             "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
4897         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4898             "TLS_AES_256_GCM_SHA384"))
4899         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4900             NULL, NULL))
4901         || !TEST_true(SSL_set_session(clientssl, clntsess))
4902         /*
4903          * We use SSL_ERROR_WANT_READ below so that we can pause the
4904          * connection after the initial ClientHello has been sent to
4905          * enable us to make some session changes.
4906          */
4907         || !TEST_false(create_ssl_connection(serverssl, clientssl,
4908             SSL_ERROR_WANT_READ)))
4909         goto end;
4910 
4911     /* Trick the client into thinking this session is for a different digest */
4912     clntsess->cipher = aes_128_gcm_sha256;
4913     clntsess->cipher_id = clntsess->cipher->id;
4914 
4915     /*
4916      * Continue the previously started connection. Server has selected a SHA-384
4917      * ciphersuite, but client thinks the session is for SHA-256, so it should
4918      * bail out.
4919      */
4920     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4921             SSL_ERROR_SSL))
4922         || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4923             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4924         goto end;
4925 
4926     testresult = 1;
4927 
4928 end:
4929     SSL_SESSION_free(clntsess);
4930     SSL_free(serverssl);
4931     SSL_free(clientssl);
4932     SSL_CTX_free(sctx);
4933     SSL_CTX_free(cctx);
4934 
4935     return testresult;
4936 }
4937 
4938 /*
4939  * Test TLSv1.3 Key exchange
4940  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4941  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4942  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4943  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4944  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4945  * Test 5 = Test NID_X448 with TLSv1.3 client and server
4946  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4947  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4948  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4949  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4950  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4951  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4952  * Test 12 = Test all ML-KEM with TLSv1.3 client and server
4953  * Test 13 = Test MLKEM512
4954  * Test 14 = Test MLKEM768
4955  * Test 15 = Test MLKEM1024
4956  * Test 16 = Test X25519MLKEM768
4957  * Test 17 = Test SecP256r1MLKEM768
4958  * Test 18 = Test SecP384r1MLKEM1024
4959  * Test 19 = Test all ML-KEM with TLSv1.2 client and server
4960  * Test 20 = Test all FFDHE with TLSv1.2 client and server
4961  * Test 21 = Test all ECDHE with TLSv1.2 client and server
4962  */
4963 #ifndef OPENSSL_NO_EC
4964 static int ecdhe_kexch_groups[] = { NID_X9_62_prime256v1, NID_secp384r1,
4965     NID_secp521r1,
4966 #ifndef OPENSSL_NO_ECX
4967     NID_X25519, NID_X448
4968 #endif
4969 };
4970 #endif
4971 #ifndef OPENSSL_NO_DH
4972 static int ffdhe_kexch_groups[] = { NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4973     NID_ffdhe6144, NID_ffdhe8192 };
4974 #endif
4975 static int test_key_exchange(int idx)
4976 {
4977     SSL_CTX *sctx = NULL, *cctx = NULL;
4978     SSL *serverssl = NULL, *clientssl = NULL;
4979     int testresult = 0;
4980     int kexch_alg = NID_undef;
4981     int *kexch_groups = &kexch_alg;
4982     int kexch_groups_size = 1;
4983     int max_version = TLS1_3_VERSION;
4984     char *kexch_name0 = NULL;
4985     const char *kexch_names = NULL;
4986     int shared_group0;
4987 
4988     switch (idx) {
4989 #ifndef OPENSSL_NO_EC
4990 #ifndef OPENSSL_NO_TLS1_2
4991     case 21:
4992         max_version = TLS1_2_VERSION;
4993 #endif
4994         /* Fall through */
4995     case 0:
4996         kexch_groups = ecdhe_kexch_groups;
4997         kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
4998         kexch_name0 = "secp256r1";
4999         break;
5000     case 1:
5001         kexch_alg = NID_X9_62_prime256v1;
5002         kexch_name0 = "secp256r1";
5003         break;
5004     case 2:
5005         kexch_alg = NID_secp384r1;
5006         kexch_name0 = "secp384r1";
5007         break;
5008     case 3:
5009         kexch_alg = NID_secp521r1;
5010         kexch_name0 = "secp521r1";
5011         break;
5012 #ifndef OPENSSL_NO_ECX
5013     case 4:
5014         if (is_fips)
5015             return TEST_skip("X25519 might not be supported by fips provider.");
5016         kexch_alg = NID_X25519;
5017         kexch_name0 = "x25519";
5018         break;
5019     case 5:
5020         if (is_fips)
5021             return TEST_skip("X448 might not be supported by fips provider.");
5022         kexch_alg = NID_X448;
5023         kexch_name0 = "x448";
5024         break;
5025 #endif
5026 #endif
5027 #ifndef OPENSSL_NO_DH
5028 #ifndef OPENSSL_NO_TLS1_2
5029     case 20:
5030         max_version = TLS1_2_VERSION;
5031         kexch_name0 = "ffdhe2048";
5032 #endif
5033         /* Fall through */
5034     case 6:
5035         kexch_groups = ffdhe_kexch_groups;
5036         kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
5037         kexch_name0 = "ffdhe2048";
5038         break;
5039     case 7:
5040         kexch_alg = NID_ffdhe2048;
5041         kexch_name0 = "ffdhe2048";
5042         break;
5043     case 8:
5044         kexch_alg = NID_ffdhe3072;
5045         kexch_name0 = "ffdhe3072";
5046         break;
5047     case 9:
5048         kexch_alg = NID_ffdhe4096;
5049         kexch_name0 = "ffdhe4096";
5050         break;
5051     case 10:
5052         kexch_alg = NID_ffdhe6144;
5053         kexch_name0 = "ffdhe6144";
5054         break;
5055     case 11:
5056         kexch_alg = NID_ffdhe8192;
5057         kexch_name0 = "ffdhe8192";
5058         break;
5059 #endif
5060 #ifndef OPENSSL_NO_ML_KEM
5061 #if !defined(OPENSSL_NO_TLS1_2)
5062     case 19:
5063         max_version = TLS1_2_VERSION;
5064 #if !defined(OPENSSL_NO_EC)
5065         /* Set at least one EC group so the handshake completes */
5066         kexch_names = "MLKEM512:MLKEM768:MLKEM1024:secp256r1";
5067 #elif !defined(OPENSSL_NO_DH)
5068         kexch_names = "MLKEM512:MLKEM768:MLKEM1024";
5069 #else
5070         /* With neither EC nor DH TLS 1.2 can't happen */
5071         return 1;
5072 #endif
5073 #endif
5074         /* Fall through */
5075     case 12:
5076         kexch_groups = NULL;
5077         if (kexch_names == NULL)
5078             kexch_names = "MLKEM512:MLKEM768:MLKEM1024";
5079         kexch_name0 = "MLKEM512";
5080         break;
5081     case 13:
5082         kexch_groups = NULL;
5083         kexch_name0 = "MLKEM512";
5084         kexch_names = kexch_name0;
5085         break;
5086     case 14:
5087         kexch_groups = NULL;
5088         kexch_name0 = "MLKEM768";
5089         kexch_names = kexch_name0;
5090         break;
5091     case 15:
5092         kexch_groups = NULL;
5093         kexch_name0 = "MLKEM1024";
5094         kexch_names = kexch_name0;
5095         break;
5096 #ifndef OPENSSL_NO_EC
5097 #ifndef OPENSSL_NO_ECX
5098     case 16:
5099         kexch_groups = NULL;
5100         kexch_name0 = "X25519MLKEM768";
5101         kexch_names = kexch_name0;
5102         break;
5103 #endif
5104     case 17:
5105         kexch_groups = NULL;
5106         kexch_name0 = "SecP256r1MLKEM768";
5107         kexch_names = kexch_name0;
5108         break;
5109     case 18:
5110         kexch_groups = NULL;
5111         kexch_name0 = "SecP384r1MLKEM1024";
5112         kexch_names = kexch_name0;
5113         break;
5114 #endif
5115 #endif
5116     default:
5117         /* We're skipping this test */
5118         return 1;
5119     }
5120 
5121     if (is_fips && fips_provider_version_lt(libctx, 3, 5, 0)
5122         && idx >= 12 && idx <= 19)
5123         return TEST_skip("ML-KEM not supported in this version of fips provider");
5124 
5125     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5126             TLS_client_method(), TLS1_VERSION,
5127             max_version, &sctx, &cctx, cert,
5128             privkey)))
5129         goto end;
5130 
5131     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
5132             TLS1_3_RFC_AES_128_GCM_SHA256)))
5133         goto end;
5134 
5135     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5136             TLS1_3_RFC_AES_128_GCM_SHA256)))
5137         goto end;
5138 
5139     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5140             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5141         || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5142         goto end;
5143 
5144     /*
5145      * Must include an EC ciphersuite so that we send supported groups in
5146      * TLSv1.2
5147      */
5148 #ifndef OPENSSL_NO_TLS1_2
5149     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5150             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5151         goto end;
5152 #endif
5153 
5154     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5155             NULL, NULL)))
5156         goto end;
5157 
5158     if (kexch_groups != NULL) {
5159         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
5160             || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
5161             goto end;
5162     } else {
5163         if (!TEST_true(SSL_set1_groups_list(serverssl, kexch_names))
5164             || !TEST_true(SSL_set1_groups_list(clientssl, kexch_names)))
5165             goto end;
5166     }
5167 
5168     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5169         goto end;
5170 
5171     /*
5172      * If the handshake succeeds the negotiated kexch alg should be the first
5173      * one in configured, except in the case of "all" FFDHE and "all" ML-KEM
5174      * groups (idx == 19, 20), which are TLSv1.3 only so we expect no shared
5175      * group to exist.
5176      */
5177     shared_group0 = SSL_get_shared_group(serverssl, 0);
5178     switch (idx) {
5179     case 19:
5180 #if !defined(OPENSSL_NO_EC)
5181         /* MLKEM + TLS 1.2 and no DH => "secp526r1" */
5182         if (!TEST_int_eq(shared_group0, NID_X9_62_prime256v1))
5183             goto end;
5184         break;
5185 #endif
5186         /* Fall through */
5187     case 20:
5188         if (!TEST_int_eq(shared_group0, 0))
5189             goto end;
5190         break;
5191     default:
5192         if (kexch_groups != NULL
5193             && !TEST_int_eq(shared_group0, kexch_groups[0]))
5194             goto end;
5195         if (!TEST_str_eq(SSL_group_to_name(serverssl, shared_group0),
5196                 kexch_name0))
5197             goto end;
5198         if (!TEST_str_eq(SSL_get0_group_name(serverssl), kexch_name0)
5199             || !TEST_str_eq(SSL_get0_group_name(clientssl), kexch_name0))
5200             goto end;
5201         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), shared_group0))
5202             goto end;
5203         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), shared_group0))
5204             goto end;
5205         break;
5206     }
5207 
5208     testresult = 1;
5209 end:
5210     SSL_free(serverssl);
5211     SSL_free(clientssl);
5212     SSL_CTX_free(sctx);
5213     SSL_CTX_free(cctx);
5214     return testresult;
5215 }
5216 
5217 #if !defined(OPENSSL_NO_TLS1_2) \
5218     && !defined(OPENSSL_NO_EC)  \
5219     && !defined(OPENSSL_NO_DH)
5220 static int set_ssl_groups(SSL *serverssl, SSL *clientssl, int clientmulti,
5221     int isecdhe, int idx)
5222 {
5223     int kexch_alg;
5224     int *kexch_groups = &kexch_alg;
5225     int numec, numff;
5226 
5227     numec = OSSL_NELEM(ecdhe_kexch_groups);
5228     numff = OSSL_NELEM(ffdhe_kexch_groups);
5229     if (isecdhe)
5230         kexch_alg = ecdhe_kexch_groups[idx];
5231     else
5232         kexch_alg = ffdhe_kexch_groups[idx];
5233 
5234     if (clientmulti) {
5235         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, 1)))
5236             return 0;
5237         if (isecdhe) {
5238             if (!TEST_true(SSL_set1_groups(clientssl, ecdhe_kexch_groups,
5239                     numec)))
5240                 return 0;
5241         } else {
5242             if (!TEST_true(SSL_set1_groups(clientssl, ffdhe_kexch_groups,
5243                     numff)))
5244                 return 0;
5245         }
5246     } else {
5247         if (!TEST_true(SSL_set1_groups(clientssl, kexch_groups, 1)))
5248             return 0;
5249         if (isecdhe) {
5250             if (!TEST_true(SSL_set1_groups(serverssl, ecdhe_kexch_groups,
5251                     numec)))
5252                 return 0;
5253         } else {
5254             if (!TEST_true(SSL_set1_groups(serverssl, ffdhe_kexch_groups,
5255                     numff)))
5256                 return 0;
5257         }
5258     }
5259     return 1;
5260 }
5261 
5262 /*-
5263  * Test the SSL_get_negotiated_group() API across a battery of scenarios.
5264  * Run through both the ECDHE and FFDHE group lists used in the previous
5265  * test, for both TLS 1.2 and TLS 1.3, negotiating each group in turn,
5266  * confirming the expected result; then perform a resumption handshake
5267  * while offering the same group list, and another resumption handshake
5268  * offering a different group list.  The returned value should be the
5269  * negotiated group for the initial handshake; for TLS 1.3 resumption
5270  * handshakes the returned value will be negotiated on the resumption
5271  * handshake itself, but for TLS 1.2 resumption handshakes the value will
5272  * be cached in the session from the original handshake, regardless of what
5273  * was offered in the resumption ClientHello.
5274  *
5275  * Using E for the number of EC groups and F for the number of FF groups:
5276  * E tests of ECDHE with TLS 1.3, server only has one group
5277  * F tests of FFDHE with TLS 1.3, server only has one group
5278  * E tests of ECDHE with TLS 1.2, server only has one group
5279  * F tests of FFDHE with TLS 1.2, server only has one group
5280  * E tests of ECDHE with TLS 1.3, client sends only one group
5281  * F tests of FFDHE with TLS 1.3, client sends only one group
5282  * E tests of ECDHE with TLS 1.2, client sends only one group
5283  * F tests of FFDHE with TLS 1.2, client sends only one group
5284  */
5285 static int test_negotiated_group(int idx)
5286 {
5287     int clientmulti, istls13, isecdhe, numec, numff, numgroups;
5288     int expectednid;
5289     SSL_CTX *sctx = NULL, *cctx = NULL;
5290     SSL *serverssl = NULL, *clientssl = NULL;
5291     SSL_SESSION *origsess = NULL;
5292     int testresult = 0;
5293     int kexch_alg;
5294     int max_version = TLS1_3_VERSION;
5295 
5296     numec = OSSL_NELEM(ecdhe_kexch_groups);
5297     numff = OSSL_NELEM(ffdhe_kexch_groups);
5298     numgroups = numec + numff;
5299     clientmulti = (idx < 2 * numgroups);
5300     idx = idx % (2 * numgroups);
5301     istls13 = (idx < numgroups);
5302     idx = idx % numgroups;
5303     isecdhe = (idx < numec);
5304     if (!isecdhe)
5305         idx -= numec;
5306     /* Now 'idx' is an index into ecdhe_kexch_groups or ffdhe_kexch_groups */
5307     if (isecdhe)
5308         kexch_alg = ecdhe_kexch_groups[idx];
5309     else
5310         kexch_alg = ffdhe_kexch_groups[idx];
5311     /* We expect nothing for the unimplemented TLS 1.2 FFDHE named groups */
5312     if (!istls13 && !isecdhe)
5313         expectednid = NID_undef;
5314     else
5315         expectednid = kexch_alg;
5316 
5317     if (is_fips && (kexch_alg == NID_X25519 || kexch_alg == NID_X448))
5318         return TEST_skip("X25519 and X448 might not be available in fips provider.");
5319 
5320     if (!istls13)
5321         max_version = TLS1_2_VERSION;
5322 
5323     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5324             TLS_client_method(), TLS1_VERSION,
5325             max_version, &sctx, &cctx, cert,
5326             privkey)))
5327         goto end;
5328 
5329     /*
5330      * Force (EC)DHE ciphers for TLS 1.2.
5331      * Be sure to enable auto tmp DH so that FFDHE can succeed.
5332      */
5333     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5334             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5335         || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5336         goto end;
5337     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5338             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5339         goto end;
5340 
5341     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5342             NULL, NULL)))
5343         goto end;
5344 
5345     if (!TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe,
5346             idx)))
5347         goto end;
5348 
5349     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5350         goto end;
5351 
5352     /* Initial handshake; always the configured one */
5353     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5354         || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5355         goto end;
5356 
5357     if (!TEST_ptr((origsess = SSL_get1_session(clientssl))))
5358         goto end;
5359 
5360     SSL_shutdown(clientssl);
5361     SSL_shutdown(serverssl);
5362     SSL_free(serverssl);
5363     SSL_free(clientssl);
5364     serverssl = clientssl = NULL;
5365 
5366     /* First resumption attempt; use the same config as initial handshake */
5367     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5368             NULL, NULL))
5369         || !TEST_true(SSL_set_session(clientssl, origsess))
5370         || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5371             isecdhe, idx)))
5372         goto end;
5373 
5374     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5375         || !TEST_true(SSL_session_reused(clientssl)))
5376         goto end;
5377 
5378     /* Still had better agree, since nothing changed... */
5379     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5380         || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5381         goto end;
5382 
5383     SSL_shutdown(clientssl);
5384     SSL_shutdown(serverssl);
5385     SSL_free(serverssl);
5386     SSL_free(clientssl);
5387     serverssl = clientssl = NULL;
5388 
5389     /*-
5390      * Second resumption attempt
5391      * The party that picks one group changes it, which we effectuate by
5392      * changing 'idx' and updating what we expect.
5393      */
5394     if (idx == 0)
5395         idx = 1;
5396     else
5397         idx--;
5398     if (istls13) {
5399         if (isecdhe)
5400             expectednid = ecdhe_kexch_groups[idx];
5401         else
5402             expectednid = ffdhe_kexch_groups[idx];
5403         /* Verify that we are changing what we expect. */
5404         if (!TEST_int_ne(expectednid, kexch_alg))
5405             goto end;
5406     } else {
5407         /* TLS 1.2 only supports named groups for ECDHE. */
5408         if (isecdhe)
5409             expectednid = kexch_alg;
5410         else
5411             expectednid = 0;
5412     }
5413     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5414             NULL, NULL))
5415         || !TEST_true(SSL_set_session(clientssl, origsess))
5416         || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5417             isecdhe, idx)))
5418         goto end;
5419 
5420     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5421         || !TEST_true(SSL_session_reused(clientssl)))
5422         goto end;
5423 
5424     /* Check that we get what we expected */
5425     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5426         || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5427         goto end;
5428 
5429     testresult = 1;
5430 end:
5431     SSL_free(serverssl);
5432     SSL_free(clientssl);
5433     SSL_CTX_free(sctx);
5434     SSL_CTX_free(cctx);
5435     SSL_SESSION_free(origsess);
5436     return testresult;
5437 }
5438 #endif /* !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) */
5439 
5440 /*
5441  * Test TLSv1.3 Cipher Suite
5442  * Test 0 = Set TLS1.3 cipher on context
5443  * Test 1 = Set TLS1.3 cipher on SSL
5444  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
5445  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
5446  */
5447 static int test_tls13_ciphersuite(int idx)
5448 {
5449     SSL_CTX *sctx = NULL, *cctx = NULL;
5450     SSL *serverssl = NULL, *clientssl = NULL;
5451     static const struct {
5452         const char *ciphername;
5453         int fipscapable;
5454         int low_security;
5455     } t13_ciphers[] = {
5456         { TLS1_3_RFC_AES_128_GCM_SHA256, 1, 0 },
5457         { TLS1_3_RFC_AES_256_GCM_SHA384, 1, 0 },
5458         { TLS1_3_RFC_AES_128_CCM_SHA256, 1, 0 },
5459 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5460         { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5461         { TLS1_3_RFC_AES_256_GCM_SHA384
5462             ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
5463             0, 0 },
5464 #endif
5465         /* CCM8 ciphers are considered low security due to their short tag */
5466         { TLS1_3_RFC_AES_128_CCM_8_SHA256
5467             ":" TLS1_3_RFC_AES_128_CCM_SHA256,
5468             1, 1 },
5469 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
5470         /* Integrity-only cipher do not provide any confidentiality */
5471         { TLS1_3_RFC_SHA256_SHA256, 0, 1 },
5472         { TLS1_3_RFC_SHA384_SHA384, 0, 1 }
5473 #endif
5474     };
5475     const char *t13_cipher = NULL;
5476     const char *t12_cipher = NULL;
5477     const char *negotiated_scipher;
5478     const char *negotiated_ccipher;
5479     int set_at_ctx = 0;
5480     int set_at_ssl = 0;
5481     int testresult = 0;
5482     int max_ver;
5483     size_t i;
5484 
5485     switch (idx) {
5486     case 0:
5487         set_at_ctx = 1;
5488         break;
5489     case 1:
5490         set_at_ssl = 1;
5491         break;
5492     case 2:
5493         set_at_ctx = 1;
5494         t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5495         break;
5496     case 3:
5497         set_at_ssl = 1;
5498         t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5499         break;
5500     }
5501 
5502     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
5503 #ifdef OPENSSL_NO_TLS1_2
5504         if (max_ver == TLS1_2_VERSION)
5505             continue;
5506 #endif
5507         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
5508             if (is_fips && !t13_ciphers[i].fipscapable)
5509                 continue;
5510             t13_cipher = t13_ciphers[i].ciphername;
5511             if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5512                     TLS_client_method(),
5513                     TLS1_VERSION, max_ver,
5514                     &sctx, &cctx, cert, privkey)))
5515                 goto end;
5516 
5517             if (t13_ciphers[i].low_security) {
5518                 SSL_CTX_set_security_level(sctx, 0);
5519                 SSL_CTX_set_security_level(cctx, 0);
5520             }
5521 
5522             if (set_at_ctx) {
5523                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
5524                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
5525                     goto end;
5526                 if (t12_cipher != NULL) {
5527                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
5528                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
5529                             t12_cipher)))
5530                         goto end;
5531                 }
5532             }
5533 
5534             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5535                     &clientssl, NULL, NULL)))
5536                 goto end;
5537 
5538             if (set_at_ssl) {
5539                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
5540                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
5541                     goto end;
5542                 if (t12_cipher != NULL) {
5543                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
5544                         || !TEST_true(SSL_set_cipher_list(clientssl,
5545                             t12_cipher)))
5546                         goto end;
5547                 }
5548             }
5549 
5550             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5551                     SSL_ERROR_NONE)))
5552                 goto end;
5553 
5554             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5555                 serverssl));
5556             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5557                 clientssl));
5558             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
5559                 goto end;
5560 
5561             /*
5562              * TEST_strn_eq is used below because t13_cipher can contain
5563              * multiple ciphersuites
5564              */
5565             if (max_ver == TLS1_3_VERSION
5566                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
5567                     strlen(negotiated_scipher)))
5568                 goto end;
5569 
5570 #ifndef OPENSSL_NO_TLS1_2
5571             /* Below validation is not done when t12_cipher is NULL */
5572             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
5573                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
5574                 goto end;
5575 #endif
5576 
5577             SSL_free(serverssl);
5578             serverssl = NULL;
5579             SSL_free(clientssl);
5580             clientssl = NULL;
5581             SSL_CTX_free(sctx);
5582             sctx = NULL;
5583             SSL_CTX_free(cctx);
5584             cctx = NULL;
5585         }
5586     }
5587 
5588     testresult = 1;
5589 end:
5590     SSL_free(serverssl);
5591     SSL_free(clientssl);
5592     SSL_CTX_free(sctx);
5593     SSL_CTX_free(cctx);
5594     return testresult;
5595 }
5596 
5597 /*
5598  * Test TLSv1.3 PSKs
5599  * Test 0 = Test new style callbacks
5600  * Test 1 = Test both new and old style callbacks
5601  * Test 2 = Test old style callbacks
5602  * Test 3 = Test old style callbacks with no certificate
5603  */
5604 static int test_tls13_psk(int idx)
5605 {
5606     SSL_CTX *sctx = NULL, *cctx = NULL;
5607     SSL *serverssl = NULL, *clientssl = NULL;
5608     const SSL_CIPHER *cipher = NULL;
5609     const unsigned char key[] = {
5610         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
5611         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5612         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
5613         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
5614     };
5615     int testresult = 0;
5616 
5617     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5618             TLS_client_method(), TLS1_VERSION, 0,
5619             &sctx, &cctx, idx == 3 ? NULL : cert,
5620             idx == 3 ? NULL : privkey)))
5621         goto end;
5622 
5623     if (idx != 3) {
5624         /*
5625          * We use a ciphersuite with SHA256 to ease testing old style PSK
5626          * callbacks which will always default to SHA256. This should not be
5627          * necessary if we have no cert/priv key. In that case the server should
5628          * prefer SHA256 automatically.
5629          */
5630         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5631                 "TLS_AES_128_GCM_SHA256")))
5632             goto end;
5633     } else {
5634         /*
5635          * As noted above the server should prefer SHA256 automatically. However
5636          * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
5637          * code works even if we are testing with only the FIPS provider loaded.
5638          */
5639         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5640                 "TLS_AES_256_GCM_SHA384:"
5641                 "TLS_AES_128_GCM_SHA256")))
5642             goto end;
5643     }
5644 
5645     /*
5646      * Test 0: New style callbacks only
5647      * Test 1: New and old style callbacks (only the new ones should be used)
5648      * Test 2: Old style callbacks only
5649      */
5650     if (idx == 0 || idx == 1) {
5651         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
5652         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
5653     }
5654 #ifndef OPENSSL_NO_PSK
5655     if (idx >= 1) {
5656         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
5657         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
5658     }
5659 #endif
5660     srvid = pskid;
5661     use_session_cb_cnt = 0;
5662     find_session_cb_cnt = 0;
5663     psk_client_cb_cnt = 0;
5664     psk_server_cb_cnt = 0;
5665 
5666     if (idx != 3) {
5667         /*
5668          * Check we can create a connection if callback decides not to send a
5669          * PSK
5670          */
5671         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5672                 NULL, NULL))
5673             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5674                 SSL_ERROR_NONE))
5675             || !TEST_false(SSL_session_reused(clientssl))
5676             || !TEST_false(SSL_session_reused(serverssl)))
5677             goto end;
5678 
5679         if (idx == 0 || idx == 1) {
5680             if (!TEST_true(use_session_cb_cnt == 1)
5681                 || !TEST_true(find_session_cb_cnt == 0)
5682                 /*
5683                  * If no old style callback then below should be 0
5684                  * otherwise 1
5685                  */
5686                 || !TEST_true(psk_client_cb_cnt == idx)
5687                 || !TEST_true(psk_server_cb_cnt == 0))
5688                 goto end;
5689         } else {
5690             if (!TEST_true(use_session_cb_cnt == 0)
5691                 || !TEST_true(find_session_cb_cnt == 0)
5692                 || !TEST_true(psk_client_cb_cnt == 1)
5693                 || !TEST_true(psk_server_cb_cnt == 0))
5694                 goto end;
5695         }
5696 
5697         shutdown_ssl_connection(serverssl, clientssl);
5698         serverssl = clientssl = NULL;
5699         use_session_cb_cnt = psk_client_cb_cnt = 0;
5700     }
5701 
5702     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5703             NULL, NULL)))
5704         goto end;
5705 
5706     /* Create the PSK */
5707     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
5708     clientpsk = SSL_SESSION_new();
5709     if (!TEST_ptr(clientpsk)
5710         || !TEST_ptr(cipher)
5711         || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
5712             sizeof(key)))
5713         || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
5714         || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
5715             TLS1_3_VERSION))
5716         || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
5717         goto end;
5718     serverpsk = clientpsk;
5719 
5720     /* Check we can create a connection and the PSK is used */
5721     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5722         || !TEST_true(SSL_session_reused(clientssl))
5723         || !TEST_true(SSL_session_reused(serverssl)))
5724         goto end;
5725 
5726     if (idx == 0 || idx == 1) {
5727         if (!TEST_true(use_session_cb_cnt == 1)
5728             || !TEST_true(find_session_cb_cnt == 1)
5729             || !TEST_true(psk_client_cb_cnt == 0)
5730             || !TEST_true(psk_server_cb_cnt == 0))
5731             goto end;
5732     } else {
5733         if (!TEST_true(use_session_cb_cnt == 0)
5734             || !TEST_true(find_session_cb_cnt == 0)
5735             || !TEST_true(psk_client_cb_cnt == 1)
5736             || !TEST_true(psk_server_cb_cnt == 1))
5737             goto end;
5738     }
5739 
5740     shutdown_ssl_connection(serverssl, clientssl);
5741     serverssl = clientssl = NULL;
5742     use_session_cb_cnt = find_session_cb_cnt = 0;
5743     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5744 
5745     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5746             NULL, NULL)))
5747         goto end;
5748 
5749     /* Force an HRR */
5750 #if defined(OPENSSL_NO_EC)
5751     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
5752         goto end;
5753 #else
5754     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
5755         goto end;
5756 #endif
5757 
5758     /*
5759      * Check we can create a connection, the PSK is used and the callbacks are
5760      * called twice.
5761      */
5762     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5763         || !TEST_true(SSL_session_reused(clientssl))
5764         || !TEST_true(SSL_session_reused(serverssl)))
5765         goto end;
5766 
5767     if (idx == 0 || idx == 1) {
5768         if (!TEST_true(use_session_cb_cnt == 2)
5769             || !TEST_true(find_session_cb_cnt == 2)
5770             || !TEST_true(psk_client_cb_cnt == 0)
5771             || !TEST_true(psk_server_cb_cnt == 0))
5772             goto end;
5773     } else {
5774         if (!TEST_true(use_session_cb_cnt == 0)
5775             || !TEST_true(find_session_cb_cnt == 0)
5776             || !TEST_true(psk_client_cb_cnt == 2)
5777             || !TEST_true(psk_server_cb_cnt == 2))
5778             goto end;
5779     }
5780 
5781     shutdown_ssl_connection(serverssl, clientssl);
5782     serverssl = clientssl = NULL;
5783     use_session_cb_cnt = find_session_cb_cnt = 0;
5784     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5785 
5786     if (idx != 3) {
5787         /*
5788          * Check that if the server rejects the PSK we can still connect, but with
5789          * a full handshake
5790          */
5791         srvid = "Dummy Identity";
5792         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5793                 NULL, NULL))
5794             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5795                 SSL_ERROR_NONE))
5796             || !TEST_false(SSL_session_reused(clientssl))
5797             || !TEST_false(SSL_session_reused(serverssl)))
5798             goto end;
5799 
5800         if (idx == 0 || idx == 1) {
5801             if (!TEST_true(use_session_cb_cnt == 1)
5802                 || !TEST_true(find_session_cb_cnt == 1)
5803                 || !TEST_true(psk_client_cb_cnt == 0)
5804                 /*
5805                  * If no old style callback then below should be 0
5806                  * otherwise 1
5807                  */
5808                 || !TEST_true(psk_server_cb_cnt == idx))
5809                 goto end;
5810         } else {
5811             if (!TEST_true(use_session_cb_cnt == 0)
5812                 || !TEST_true(find_session_cb_cnt == 0)
5813                 || !TEST_true(psk_client_cb_cnt == 1)
5814                 || !TEST_true(psk_server_cb_cnt == 1))
5815                 goto end;
5816         }
5817 
5818         shutdown_ssl_connection(serverssl, clientssl);
5819         serverssl = clientssl = NULL;
5820     }
5821     testresult = 1;
5822 
5823 end:
5824     SSL_SESSION_free(clientpsk);
5825     SSL_SESSION_free(serverpsk);
5826     clientpsk = serverpsk = NULL;
5827     SSL_free(serverssl);
5828     SSL_free(clientssl);
5829     SSL_CTX_free(sctx);
5830     SSL_CTX_free(cctx);
5831     return testresult;
5832 }
5833 
5834 #ifndef OSSL_NO_USABLE_TLS1_3
5835 /*
5836  * Test TLS1.3 connection establishment succeeds with various configurations of
5837  * the options `SSL_OP_ALLOW_NO_DHE_KEX` and `SSL_OP_PREFER_NO_DHE_KEX`.
5838  * The verification of whether the right KEX mode is chosen is not covered by
5839  * this test but by `test_tls13kexmodes`.
5840  *
5841  * Tests (idx & 1): Server has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5842  * Tests (idx & 2): Server has `SSL_OP_PREFER_NO_DHE_KEX` set.
5843  * Tests (idx & 4): Client has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5844  */
5845 static int test_tls13_no_dhe_kex(const int idx)
5846 {
5847     SSL_CTX *sctx = NULL, *cctx = NULL;
5848     SSL *serverssl = NULL, *clientssl = NULL;
5849     int testresult = 0;
5850     size_t j;
5851     SSL_SESSION *saved_session;
5852 
5853     int server_allow_no_dhe = (idx & 1) != 0;
5854     int server_prefer_no_dhe = (idx & 2) != 0;
5855     int client_allow_no_dhe = (idx & 4) != 0;
5856 
5857     uint64_t server_options = 0
5858         | (server_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0)
5859         | (server_prefer_no_dhe ? SSL_OP_PREFER_NO_DHE_KEX : 0);
5860 
5861     uint64_t client_options = 0
5862         | (client_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0);
5863 
5864     new_called = 0;
5865     do_cache = 1;
5866 
5867     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5868             TLS_client_method(), TLS1_3_VERSION, 0,
5869             &sctx, &cctx, cert, privkey)))
5870         goto end;
5871 
5872     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5873 
5874     SSL_CTX_set_options(sctx, server_options);
5875     SSL_CTX_set_options(cctx, client_options);
5876 
5877     SSL_CTX_sess_set_new_cb(cctx, new_cachesession_cb);
5878 
5879     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5880             &clientssl, NULL, NULL)))
5881         goto end;
5882 
5883     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5884             SSL_ERROR_NONE))
5885         /* Check we got the number of tickets we were expecting */
5886         || !TEST_int_eq(2, new_called))
5887         goto end;
5888 
5889     /* We'll reuse the last ticket. */
5890     saved_session = sesscache[new_called - 1];
5891 
5892     SSL_shutdown(clientssl);
5893     SSL_shutdown(serverssl);
5894     SSL_free(serverssl);
5895     SSL_free(clientssl);
5896     SSL_CTX_free(cctx);
5897     clientssl = serverssl = NULL;
5898     cctx = NULL;
5899 
5900     /*
5901      * Now we resume with the last ticket we created.
5902      */
5903 
5904     /* The server context already exists, so we only create the client. */
5905     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5906             TLS_client_method(), TLS1_3_VERSION, 0,
5907             NULL, &cctx, cert, privkey)))
5908         goto end;
5909 
5910     SSL_CTX_set_options(cctx, client_options);
5911 
5912     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5913             &clientssl, NULL, NULL))
5914         || !TEST_true(SSL_set_session(clientssl, saved_session)))
5915         goto end;
5916 
5917     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5918             SSL_ERROR_NONE)))
5919         goto end;
5920 
5921     /*
5922      * Make sure, the session was resumed.
5923      */
5924     if (!TEST_true(SSL_session_reused(clientssl)))
5925         goto end;
5926 
5927     SSL_shutdown(clientssl);
5928     SSL_shutdown(serverssl);
5929 
5930     testresult = 1;
5931 
5932 end:
5933     SSL_free(serverssl);
5934     SSL_free(clientssl);
5935     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
5936         SSL_SESSION_free(sesscache[j]);
5937         sesscache[j] = NULL;
5938     }
5939     SSL_CTX_free(sctx);
5940     SSL_CTX_free(cctx);
5941 
5942     return testresult;
5943 }
5944 #endif /* OSSL_NO_USABLE_TLS1_3 */
5945 
5946 static unsigned char cookie_magic_value[] = "cookie magic";
5947 
5948 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
5949     unsigned int *cookie_len)
5950 {
5951     /*
5952      * Not suitable as a real cookie generation function but good enough for
5953      * testing!
5954      */
5955     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
5956     *cookie_len = sizeof(cookie_magic_value) - 1;
5957 
5958     return 1;
5959 }
5960 
5961 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
5962     unsigned int cookie_len)
5963 {
5964     if (cookie_len == sizeof(cookie_magic_value) - 1
5965         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
5966         return 1;
5967 
5968     return 0;
5969 }
5970 
5971 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
5972     size_t *cookie_len)
5973 {
5974     unsigned int temp;
5975     int res = generate_cookie_callback(ssl, cookie, &temp);
5976     *cookie_len = temp;
5977     return res;
5978 }
5979 
5980 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
5981     size_t cookie_len)
5982 {
5983     return verify_cookie_callback(ssl, cookie, cookie_len);
5984 }
5985 
5986 static int test_stateless(void)
5987 {
5988     SSL_CTX *sctx = NULL, *cctx = NULL;
5989     SSL *serverssl = NULL, *clientssl = NULL;
5990     int testresult = 0;
5991 
5992     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5993             TLS_client_method(), TLS1_VERSION, 0,
5994             &sctx, &cctx, cert, privkey)))
5995         goto end;
5996 
5997     /* The arrival of CCS messages can confuse the test */
5998     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5999 
6000     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6001             NULL, NULL))
6002         /* Send the first ClientHello */
6003         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6004             SSL_ERROR_WANT_READ))
6005         /*
6006          * This should fail with a -1 return because we have no callbacks
6007          * set up
6008          */
6009         || !TEST_int_eq(SSL_stateless(serverssl), -1))
6010         goto end;
6011 
6012     /* Fatal error so abandon the connection from this client */
6013     SSL_free(clientssl);
6014     clientssl = NULL;
6015 
6016     /* Set up the cookie generation and verification callbacks */
6017     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
6018     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
6019 
6020     /*
6021      * Create a new connection from the client (we can reuse the server SSL
6022      * object).
6023      */
6024     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6025             NULL, NULL))
6026         /* Send the first ClientHello */
6027         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6028             SSL_ERROR_WANT_READ))
6029         /* This should fail because there is no cookie */
6030         || !TEST_int_eq(SSL_stateless(serverssl), 0))
6031         goto end;
6032 
6033     /* Abandon the connection from this client */
6034     SSL_free(clientssl);
6035     clientssl = NULL;
6036 
6037     /*
6038      * Now create a connection from a new client but with the same server SSL
6039      * object
6040      */
6041     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6042             NULL, NULL))
6043         /* Send the first ClientHello */
6044         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6045             SSL_ERROR_WANT_READ))
6046         /* This should fail because there is no cookie */
6047         || !TEST_int_eq(SSL_stateless(serverssl), 0)
6048         /* Send the second ClientHello */
6049         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6050             SSL_ERROR_WANT_READ))
6051         /* This should succeed because a cookie is now present */
6052         || !TEST_int_eq(SSL_stateless(serverssl), 1)
6053         /* Complete the connection */
6054         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6055             SSL_ERROR_NONE)))
6056         goto end;
6057 
6058     shutdown_ssl_connection(serverssl, clientssl);
6059     serverssl = clientssl = NULL;
6060     testresult = 1;
6061 
6062 end:
6063     SSL_free(serverssl);
6064     SSL_free(clientssl);
6065     SSL_CTX_free(sctx);
6066     SSL_CTX_free(cctx);
6067     return testresult;
6068 }
6069 #endif /* OSSL_NO_USABLE_TLS1_3 */
6070 
6071 static int clntaddoldcb = 0;
6072 static int clntparseoldcb = 0;
6073 static int srvaddoldcb = 0;
6074 static int srvparseoldcb = 0;
6075 static int clntaddnewcb = 0;
6076 static int clntparsenewcb = 0;
6077 static int srvaddnewcb = 0;
6078 static int srvparsenewcb = 0;
6079 static int snicb = 0;
6080 
6081 #define TEST_EXT_TYPE1 0xff00
6082 
6083 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
6084     size_t *outlen, int *al, void *add_arg)
6085 {
6086     int *server = (int *)add_arg;
6087     unsigned char *data;
6088 
6089     if (SSL_is_server(s))
6090         srvaddoldcb++;
6091     else
6092         clntaddoldcb++;
6093 
6094     if (*server != SSL_is_server(s)
6095         || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
6096         return -1;
6097 
6098     *data = 1;
6099     *out = data;
6100     *outlen = sizeof(char);
6101     return 1;
6102 }
6103 
6104 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
6105     void *add_arg)
6106 {
6107     OPENSSL_free((unsigned char *)out);
6108 }
6109 
6110 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
6111     size_t inlen, int *al, void *parse_arg)
6112 {
6113     int *server = (int *)parse_arg;
6114 
6115     if (SSL_is_server(s))
6116         srvparseoldcb++;
6117     else
6118         clntparseoldcb++;
6119 
6120     if (*server != SSL_is_server(s)
6121         || inlen != sizeof(char)
6122         || *in != 1)
6123         return -1;
6124 
6125     return 1;
6126 }
6127 
6128 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
6129     const unsigned char **out, size_t *outlen, X509 *x,
6130     size_t chainidx, int *al, void *add_arg)
6131 {
6132     int *server = (int *)add_arg;
6133     unsigned char *data;
6134 
6135     if (SSL_is_server(s))
6136         srvaddnewcb++;
6137     else
6138         clntaddnewcb++;
6139 
6140     if (*server != SSL_is_server(s)
6141         || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
6142         return -1;
6143 
6144     *data = 1;
6145     *out = data;
6146     *outlen = sizeof(*data);
6147     return 1;
6148 }
6149 
6150 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
6151     const unsigned char *out, void *add_arg)
6152 {
6153     OPENSSL_free((unsigned char *)out);
6154 }
6155 
6156 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
6157     const unsigned char *in, size_t inlen, X509 *x,
6158     size_t chainidx, int *al, void *parse_arg)
6159 {
6160     int *server = (int *)parse_arg;
6161 
6162     if (SSL_is_server(s))
6163         srvparsenewcb++;
6164     else
6165         clntparsenewcb++;
6166 
6167     if (*server != SSL_is_server(s)
6168         || inlen != sizeof(char) || *in != 1)
6169         return -1;
6170 
6171     return 1;
6172 }
6173 
6174 static int sni_cb(SSL *s, int *al, void *arg)
6175 {
6176     SSL_CTX *ctx = (SSL_CTX *)arg;
6177 
6178     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
6179         *al = SSL_AD_INTERNAL_ERROR;
6180         return SSL_TLSEXT_ERR_ALERT_FATAL;
6181     }
6182     snicb++;
6183     return SSL_TLSEXT_ERR_OK;
6184 }
6185 
6186 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
6187 {
6188     return 1;
6189 }
6190 
6191 /*
6192  * Custom call back tests.
6193  * Test 0: Old style callbacks in TLSv1.2
6194  * Test 1: New style callbacks in TLSv1.2
6195  * Test 2: New style callbacks in TLSv1.2 with SNI
6196  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
6197  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
6198  * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
6199  */
6200 static int test_custom_exts(int tst)
6201 {
6202     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6203     SSL *clientssl = NULL, *serverssl = NULL;
6204     int testresult = 0;
6205     static int server = 1;
6206     static int client = 0;
6207     SSL_SESSION *sess = NULL;
6208     unsigned int context;
6209 
6210 #if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6211     /* Skip tests for TLSv1.2 and below in this case */
6212     if (tst < 3)
6213         return 1;
6214 #endif
6215 
6216     /* Reset callback counters */
6217     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
6218     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
6219     snicb = 0;
6220 
6221     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6222             TLS_client_method(), TLS1_VERSION, 0,
6223             &sctx, &cctx, cert, privkey)))
6224         goto end;
6225 
6226     if (tst == 2
6227         && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
6228             TLS1_VERSION, 0,
6229             &sctx2, NULL, cert, privkey)))
6230         goto end;
6231 
6232     if (tst < 3) {
6233         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
6234         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
6235         if (sctx2 != NULL)
6236             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
6237     }
6238 
6239     if (tst == 5) {
6240         context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
6241             | SSL_EXT_TLS1_3_CERTIFICATE;
6242         SSL_CTX_set_verify(sctx,
6243             SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
6244             verify_cb);
6245         if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
6246                              SSL_FILETYPE_PEM),
6247                 1)
6248             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
6249                                 SSL_FILETYPE_PEM),
6250                 1)
6251             || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
6252             goto end;
6253     } else if (tst == 4) {
6254         context = SSL_EXT_CLIENT_HELLO
6255             | SSL_EXT_TLS1_2_SERVER_HELLO
6256             | SSL_EXT_TLS1_3_SERVER_HELLO
6257             | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
6258             | SSL_EXT_TLS1_3_CERTIFICATE
6259             | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
6260     } else {
6261         context = SSL_EXT_CLIENT_HELLO
6262             | SSL_EXT_TLS1_2_SERVER_HELLO
6263             | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
6264     }
6265 
6266     /* Create a client side custom extension */
6267     if (tst == 0) {
6268         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6269                 old_add_cb, old_free_cb,
6270                 &client, old_parse_cb,
6271                 &client)))
6272             goto end;
6273     } else {
6274         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
6275                 new_add_cb, new_free_cb,
6276                 &client, new_parse_cb, &client)))
6277             goto end;
6278     }
6279 
6280     /* Should not be able to add duplicates */
6281     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6282             old_add_cb, old_free_cb,
6283             &client, old_parse_cb,
6284             &client))
6285         || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
6286             context, new_add_cb,
6287             new_free_cb, &client,
6288             new_parse_cb, &client)))
6289         goto end;
6290 
6291     /* Create a server side custom extension */
6292     if (tst == 0) {
6293         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6294                 old_add_cb, old_free_cb,
6295                 &server, old_parse_cb,
6296                 &server)))
6297             goto end;
6298     } else {
6299         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
6300                 new_add_cb, new_free_cb,
6301                 &server, new_parse_cb, &server)))
6302             goto end;
6303         if (sctx2 != NULL
6304             && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
6305                 context, new_add_cb,
6306                 new_free_cb, &server,
6307                 new_parse_cb, &server)))
6308             goto end;
6309     }
6310 
6311     /* Should not be able to add duplicates */
6312     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6313             old_add_cb, old_free_cb,
6314             &server, old_parse_cb,
6315             &server))
6316         || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
6317             context, new_add_cb,
6318             new_free_cb, &server,
6319             new_parse_cb, &server)))
6320         goto end;
6321 
6322     if (tst == 2) {
6323         /* Set up SNI */
6324         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
6325             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
6326             goto end;
6327     }
6328 
6329     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6330             &clientssl, NULL, NULL))
6331         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6332             SSL_ERROR_NONE)))
6333         goto end;
6334 
6335     if (tst == 0) {
6336         if (clntaddoldcb != 1
6337             || clntparseoldcb != 1
6338             || srvaddoldcb != 1
6339             || srvparseoldcb != 1)
6340             goto end;
6341     } else if (tst == 1 || tst == 2 || tst == 3) {
6342         if (clntaddnewcb != 1
6343             || clntparsenewcb != 1
6344             || srvaddnewcb != 1
6345             || srvparsenewcb != 1
6346             || (tst != 2 && snicb != 0)
6347             || (tst == 2 && snicb != 1))
6348             goto end;
6349     } else if (tst == 5) {
6350         if (clntaddnewcb != 1
6351             || clntparsenewcb != 1
6352             || srvaddnewcb != 1
6353             || srvparsenewcb != 1)
6354             goto end;
6355     } else {
6356         /* In this case there 2 NewSessionTicket messages created */
6357         if (clntaddnewcb != 1
6358             || clntparsenewcb != 5
6359             || srvaddnewcb != 5
6360             || srvparsenewcb != 1)
6361             goto end;
6362     }
6363 
6364     sess = SSL_get1_session(clientssl);
6365     SSL_shutdown(clientssl);
6366     SSL_shutdown(serverssl);
6367     SSL_free(serverssl);
6368     SSL_free(clientssl);
6369     serverssl = clientssl = NULL;
6370 
6371     if (tst == 3 || tst == 5) {
6372         /* We don't bother with the resumption aspects for these tests */
6373         testresult = 1;
6374         goto end;
6375     }
6376 
6377     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6378             NULL, NULL))
6379         || !TEST_true(SSL_set_session(clientssl, sess))
6380         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6381             SSL_ERROR_NONE)))
6382         goto end;
6383 
6384     /*
6385      * For a resumed session we expect to add the ClientHello extension. For the
6386      * old style callbacks we ignore it on the server side because they set
6387      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
6388      * them.
6389      */
6390     if (tst == 0) {
6391         if (clntaddoldcb != 2
6392             || clntparseoldcb != 1
6393             || srvaddoldcb != 1
6394             || srvparseoldcb != 1)
6395             goto end;
6396     } else if (tst == 1 || tst == 2 || tst == 3) {
6397         if (clntaddnewcb != 2
6398             || clntparsenewcb != 2
6399             || srvaddnewcb != 2
6400             || srvparsenewcb != 2)
6401             goto end;
6402     } else {
6403         /*
6404          * No Certificate message extensions in the resumption handshake,
6405          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
6406          */
6407         if (clntaddnewcb != 2
6408             || clntparsenewcb != 8
6409             || srvaddnewcb != 8
6410             || srvparsenewcb != 2)
6411             goto end;
6412     }
6413 
6414     testresult = 1;
6415 
6416 end:
6417     SSL_SESSION_free(sess);
6418     SSL_free(serverssl);
6419     SSL_free(clientssl);
6420     SSL_CTX_free(sctx2);
6421     SSL_CTX_free(sctx);
6422     SSL_CTX_free(cctx);
6423     return testresult;
6424 }
6425 
6426 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6427 
6428 #define SYNTHV1CONTEXT (SSL_EXT_TLS1_2_AND_BELOW_ONLY \
6429     | SSL_EXT_CLIENT_HELLO                            \
6430     | SSL_EXT_TLS1_2_SERVER_HELLO                     \
6431     | SSL_EXT_IGNORE_ON_RESUMPTION)
6432 
6433 #define TLS13CONTEXT (SSL_EXT_TLS1_3_CERTIFICATE \
6434     | SSL_EXT_TLS1_2_SERVER_HELLO                \
6435     | SSL_EXT_CLIENT_HELLO)
6436 
6437 #define SERVERINFO_CUSTOM                                 \
6438     0x00, (char)TLSEXT_TYPE_signed_certificate_timestamp, \
6439         0x00, 0x03,                                       \
6440         0x04, 0x05, 0x06
6441 
6442 static const unsigned char serverinfo_custom_tls13[] = {
6443     0x00, 0x00, (TLS13CONTEXT >> 8) & 0xff, TLS13CONTEXT & 0xff,
6444     SERVERINFO_CUSTOM
6445 };
6446 static const unsigned char serverinfo_custom_v2[] = {
6447     0x00, 0x00, (SYNTHV1CONTEXT >> 8) & 0xff, SYNTHV1CONTEXT & 0xff,
6448     SERVERINFO_CUSTOM
6449 };
6450 static const unsigned char serverinfo_custom_v1[] = {
6451     SERVERINFO_CUSTOM
6452 };
6453 static const size_t serverinfo_custom_tls13_len = sizeof(serverinfo_custom_tls13);
6454 static const size_t serverinfo_custom_v2_len = sizeof(serverinfo_custom_v2);
6455 static const size_t serverinfo_custom_v1_len = sizeof(serverinfo_custom_v1);
6456 
6457 static int serverinfo_custom_parse_cb(SSL *s, unsigned int ext_type,
6458     unsigned int context,
6459     const unsigned char *in,
6460     size_t inlen, X509 *x,
6461     size_t chainidx, int *al,
6462     void *parse_arg)
6463 {
6464     const size_t len = serverinfo_custom_v1_len;
6465     const unsigned char *si = &serverinfo_custom_v1[len - 3];
6466     int *p_cb_result = (int *)parse_arg;
6467     *p_cb_result = TEST_mem_eq(in, inlen, si, 3);
6468     return 1;
6469 }
6470 
6471 static int test_serverinfo_custom(const int idx)
6472 {
6473     SSL_CTX *sctx = NULL, *cctx = NULL;
6474     SSL *clientssl = NULL, *serverssl = NULL;
6475     int testresult = 0;
6476     int cb_result = 0;
6477 
6478     /*
6479      * Following variables are set in the switch statement
6480      *  according to the test iteration.
6481      * Default values do not make much sense: test would fail with them.
6482      */
6483     int serverinfo_version = 0;
6484     int protocol_version = 0;
6485     unsigned int extension_context = 0;
6486     const unsigned char *si = NULL;
6487     size_t si_len = 0;
6488 
6489     const int call_use_serverinfo_ex = idx > 0;
6490     switch (idx) {
6491     case 0: /* FALLTHROUGH */
6492     case 1:
6493         serverinfo_version = SSL_SERVERINFOV1;
6494         protocol_version = TLS1_2_VERSION;
6495         extension_context = SYNTHV1CONTEXT;
6496         si = serverinfo_custom_v1;
6497         si_len = serverinfo_custom_v1_len;
6498         break;
6499     case 2:
6500         serverinfo_version = SSL_SERVERINFOV2;
6501         protocol_version = TLS1_2_VERSION;
6502         extension_context = SYNTHV1CONTEXT;
6503         si = serverinfo_custom_v2;
6504         si_len = serverinfo_custom_v2_len;
6505         break;
6506     case 3:
6507         serverinfo_version = SSL_SERVERINFOV2;
6508         protocol_version = TLS1_3_VERSION;
6509         extension_context = TLS13CONTEXT;
6510         si = serverinfo_custom_tls13;
6511         si_len = serverinfo_custom_tls13_len;
6512         break;
6513     }
6514 
6515     if (!TEST_true(create_ssl_ctx_pair(libctx,
6516             TLS_method(),
6517             TLS_method(),
6518             protocol_version,
6519             protocol_version,
6520             &sctx, &cctx, cert, privkey)))
6521         goto end;
6522 
6523     if (call_use_serverinfo_ex) {
6524         if (!TEST_true(SSL_CTX_use_serverinfo_ex(sctx, serverinfo_version,
6525                 si, si_len)))
6526             goto end;
6527     } else {
6528         if (!TEST_true(SSL_CTX_use_serverinfo(sctx, si, si_len)))
6529             goto end;
6530     }
6531 
6532     if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TLSEXT_TYPE_signed_certificate_timestamp,
6533             extension_context,
6534             NULL, NULL, NULL,
6535             serverinfo_custom_parse_cb,
6536             &cb_result))
6537         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6538             NULL, NULL))
6539         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6540             SSL_ERROR_NONE))
6541         || !TEST_int_eq(SSL_do_handshake(clientssl), 1))
6542         goto end;
6543 
6544     if (!TEST_true(cb_result))
6545         goto end;
6546 
6547     testresult = 1;
6548 
6549 end:
6550     SSL_free(serverssl);
6551     SSL_free(clientssl);
6552     SSL_CTX_free(sctx);
6553     SSL_CTX_free(cctx);
6554 
6555     return testresult;
6556 }
6557 #endif
6558 
6559 /*
6560  * Test that SSL_export_keying_material() produces expected results. There are
6561  * no test vectors so all we do is test that both sides of the communication
6562  * produce the same results for different protocol versions.
6563  */
6564 #define SMALL_LABEL_LEN 10
6565 #define LONG_LABEL_LEN 249
6566 static int test_export_key_mat(int tst)
6567 {
6568     int testresult = 0;
6569     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6570     SSL *clientssl = NULL, *serverssl = NULL;
6571     const char label[LONG_LABEL_LEN + 1] = "test label";
6572     const unsigned char context[] = "context";
6573     const unsigned char *emptycontext = NULL;
6574     unsigned char longcontext[1280];
6575     int test_longcontext = fips_provider_version_ge(libctx, 3, 3, 0);
6576     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80], ckeymat4[80];
6577     unsigned char skeymat1[80], skeymat2[80], skeymat3[80], skeymat4[80];
6578     size_t labellen;
6579     const int protocols[] = {
6580         TLS1_VERSION,
6581         TLS1_1_VERSION,
6582         TLS1_2_VERSION,
6583         TLS1_3_VERSION,
6584         TLS1_3_VERSION,
6585         TLS1_3_VERSION
6586     };
6587 
6588 #ifdef OPENSSL_NO_TLS1
6589     if (tst == 0)
6590         return 1;
6591 #endif
6592 #ifdef OPENSSL_NO_TLS1_1
6593     if (tst == 1)
6594         return 1;
6595 #endif
6596     if (is_fips && (tst == 0 || tst == 1))
6597         return 1;
6598 #ifdef OPENSSL_NO_TLS1_2
6599     if (tst == 2)
6600         return 1;
6601 #endif
6602 #ifdef OSSL_NO_USABLE_TLS1_3
6603     if (tst >= 3)
6604         return 1;
6605 #endif
6606     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6607             TLS_client_method(), TLS1_VERSION, 0,
6608             &sctx, &cctx, cert, privkey)))
6609         goto end;
6610 
6611     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
6612     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
6613     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
6614     if ((protocols[tst] < TLS1_2_VERSION) && (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0") || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
6615         goto end;
6616 
6617     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6618             NULL)))
6619         goto end;
6620 
6621     /*
6622      * Premature call of SSL_export_keying_material should just fail.
6623      */
6624     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6625                          sizeof(ckeymat1), label,
6626                          SMALL_LABEL_LEN + 1, context,
6627                          sizeof(context) - 1, 1),
6628             0))
6629         goto end;
6630 
6631     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6632             SSL_ERROR_NONE)))
6633         goto end;
6634 
6635     if (tst == 5) {
6636         /*
6637          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
6638          * go over that.
6639          */
6640         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6641                              sizeof(ckeymat1), label,
6642                              LONG_LABEL_LEN + 1, context,
6643                              sizeof(context) - 1, 1),
6644                 0))
6645             goto end;
6646 
6647         testresult = 1;
6648         goto end;
6649     } else if (tst == 4) {
6650         labellen = LONG_LABEL_LEN;
6651     } else {
6652         labellen = SMALL_LABEL_LEN;
6653     }
6654 
6655     memset(longcontext, 1, sizeof(longcontext));
6656 
6657     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
6658                          sizeof(ckeymat1), label,
6659                          labellen, context,
6660                          sizeof(context) - 1, 1),
6661             1)
6662         || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
6663                             sizeof(ckeymat2), label,
6664                             labellen,
6665                             emptycontext,
6666                             0, 1),
6667             1)
6668         || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
6669                             sizeof(ckeymat3), label,
6670                             labellen,
6671                             NULL, 0, 0),
6672             1)
6673         || (test_longcontext
6674             && !TEST_int_eq(SSL_export_keying_material(clientssl,
6675                                 ckeymat4,
6676                                 sizeof(ckeymat4), label,
6677                                 labellen,
6678                                 longcontext,
6679                                 sizeof(longcontext), 1),
6680                 1))
6681         || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
6682                             sizeof(skeymat1), label,
6683                             labellen,
6684                             context,
6685                             sizeof(context) - 1, 1),
6686             1)
6687         || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
6688                             sizeof(skeymat2), label,
6689                             labellen,
6690                             emptycontext,
6691                             0, 1),
6692             1)
6693         || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
6694                             sizeof(skeymat3), label,
6695                             labellen,
6696                             NULL, 0, 0),
6697             1)
6698         || (test_longcontext
6699             && !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat4,
6700                                 sizeof(skeymat4), label,
6701                                 labellen,
6702                                 longcontext,
6703                                 sizeof(longcontext), 1),
6704                 1))
6705         /*
6706          * Check that both sides created the same key material with the
6707          * same context.
6708          */
6709         || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6710             sizeof(skeymat1))
6711         /*
6712          * Check that both sides created the same key material with an
6713          * empty context.
6714          */
6715         || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6716             sizeof(skeymat2))
6717         /*
6718          * Check that both sides created the same key material without a
6719          * context.
6720          */
6721         || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
6722             sizeof(skeymat3))
6723         /*
6724          * Check that both sides created the same key material with a
6725          * long context.
6726          */
6727         || (test_longcontext
6728             && !TEST_mem_eq(ckeymat4, sizeof(ckeymat4), skeymat4,
6729                 sizeof(skeymat4)))
6730         /* Different contexts should produce different results */
6731         || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6732             sizeof(ckeymat2)))
6733         goto end;
6734 
6735     /*
6736      * Check that an empty context and no context produce different results in
6737      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
6738      */
6739     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3, sizeof(ckeymat3)))
6740         || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3, sizeof(ckeymat3))))
6741         goto end;
6742 
6743     testresult = 1;
6744 
6745 end:
6746     SSL_free(serverssl);
6747     SSL_free(clientssl);
6748     SSL_CTX_free(sctx2);
6749     SSL_CTX_free(sctx);
6750     SSL_CTX_free(cctx);
6751 
6752     return testresult;
6753 }
6754 
6755 #ifndef OSSL_NO_USABLE_TLS1_3
6756 /*
6757  * Test that SSL_export_keying_material_early() produces expected
6758  * results. There are no test vectors so all we do is test that both
6759  * sides of the communication produce the same results for different
6760  * protocol versions.
6761  */
6762 static int test_export_key_mat_early(int idx)
6763 {
6764     static const char label[] = "test label";
6765     static const unsigned char context[] = "context";
6766     int testresult = 0;
6767     SSL_CTX *cctx = NULL, *sctx = NULL;
6768     SSL *clientssl = NULL, *serverssl = NULL;
6769     SSL_SESSION *sess = NULL;
6770     const unsigned char *emptycontext = NULL;
6771     unsigned char ckeymat1[80], ckeymat2[80];
6772     unsigned char skeymat1[80], skeymat2[80];
6773     unsigned char buf[1];
6774     size_t readbytes, written;
6775 
6776     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
6777             &sess, idx, SHA384_DIGEST_LENGTH)))
6778         goto end;
6779 
6780     /* Here writing 0 length early data is enough. */
6781     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
6782         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
6783                             &readbytes),
6784             SSL_READ_EARLY_DATA_ERROR)
6785         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6786             SSL_EARLY_DATA_ACCEPTED))
6787         goto end;
6788 
6789     if (!TEST_int_eq(SSL_export_keying_material_early(
6790                          clientssl, ckeymat1, sizeof(ckeymat1), label,
6791                          sizeof(label) - 1, context, sizeof(context) - 1),
6792             1)
6793         || !TEST_int_eq(SSL_export_keying_material_early(
6794                             clientssl, ckeymat2, sizeof(ckeymat2), label,
6795                             sizeof(label) - 1, emptycontext, 0),
6796             1)
6797         || !TEST_int_eq(SSL_export_keying_material_early(
6798                             serverssl, skeymat1, sizeof(skeymat1), label,
6799                             sizeof(label) - 1, context, sizeof(context) - 1),
6800             1)
6801         || !TEST_int_eq(SSL_export_keying_material_early(
6802                             serverssl, skeymat2, sizeof(skeymat2), label,
6803                             sizeof(label) - 1, emptycontext, 0),
6804             1)
6805         /*
6806          * Check that both sides created the same key material with the
6807          * same context.
6808          */
6809         || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6810             sizeof(skeymat1))
6811         /*
6812          * Check that both sides created the same key material with an
6813          * empty context.
6814          */
6815         || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6816             sizeof(skeymat2))
6817         /* Different contexts should produce different results */
6818         || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6819             sizeof(ckeymat2)))
6820         goto end;
6821 
6822     testresult = 1;
6823 
6824 end:
6825     SSL_SESSION_free(sess);
6826     SSL_SESSION_free(clientpsk);
6827     SSL_SESSION_free(serverpsk);
6828     clientpsk = serverpsk = NULL;
6829     SSL_free(serverssl);
6830     SSL_free(clientssl);
6831     SSL_CTX_free(sctx);
6832     SSL_CTX_free(cctx);
6833 
6834     return testresult;
6835 }
6836 
6837 #define NUM_KEY_UPDATE_MESSAGES 40
6838 /*
6839  * Test KeyUpdate.
6840  */
6841 static int test_key_update(void)
6842 {
6843     SSL_CTX *cctx = NULL, *sctx = NULL;
6844     SSL *clientssl = NULL, *serverssl = NULL;
6845     int testresult = 0, i, j;
6846     char buf[20];
6847     static char *mess = "A test message";
6848 
6849     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6850             TLS_client_method(),
6851             TLS1_3_VERSION,
6852             0,
6853             &sctx, &cctx, cert, privkey))
6854         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6855             NULL, NULL))
6856         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6857             SSL_ERROR_NONE)))
6858         goto end;
6859 
6860     for (j = 0; j < 2; j++) {
6861         /* Send lots of KeyUpdate messages */
6862         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
6863             if (!TEST_true(SSL_key_update(clientssl,
6864                     (j == 0)
6865                         ? SSL_KEY_UPDATE_NOT_REQUESTED
6866                         : SSL_KEY_UPDATE_REQUESTED))
6867                 || !TEST_true(SSL_do_handshake(clientssl)))
6868                 goto end;
6869         }
6870 
6871         /* Check that sending and receiving app data is ok */
6872         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
6873             || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
6874                 strlen(mess)))
6875             goto end;
6876 
6877         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
6878             || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
6879                 strlen(mess)))
6880             goto end;
6881     }
6882 
6883     testresult = 1;
6884 
6885 end:
6886     SSL_free(serverssl);
6887     SSL_free(clientssl);
6888     SSL_CTX_free(sctx);
6889     SSL_CTX_free(cctx);
6890 
6891     return testresult;
6892 }
6893 
6894 /*
6895  * Test we can handle a KeyUpdate (update requested) message while
6896  * write data is pending in peer.
6897  * Test 0: Client sends KeyUpdate while Server is writing
6898  * Test 1: Server sends KeyUpdate while Client is writing
6899  */
6900 static int test_key_update_peer_in_write(int tst)
6901 {
6902     SSL_CTX *cctx = NULL, *sctx = NULL;
6903     SSL *clientssl = NULL, *serverssl = NULL;
6904     int testresult = 0;
6905     char buf[20];
6906     static char *mess = "A test message";
6907     BIO *bretry = BIO_new(bio_s_always_retry());
6908     BIO *tmp = NULL;
6909     SSL *peerupdate = NULL, *peerwrite = NULL;
6910 
6911     if (!TEST_ptr(bretry)
6912         || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6913             TLS_client_method(),
6914             TLS1_3_VERSION,
6915             0,
6916             &sctx, &cctx, cert, privkey))
6917         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6918             NULL, NULL))
6919         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6920             SSL_ERROR_NONE)))
6921         goto end;
6922 
6923     peerupdate = tst == 0 ? clientssl : serverssl;
6924     peerwrite = tst == 0 ? serverssl : clientssl;
6925 
6926     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
6927         || !TEST_int_eq(SSL_do_handshake(peerupdate), 1))
6928         goto end;
6929 
6930     /* Swap the writing endpoint's write BIO to force a retry */
6931     tmp = SSL_get_wbio(peerwrite);
6932     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6933         tmp = NULL;
6934         goto end;
6935     }
6936     SSL_set0_wbio(peerwrite, bretry);
6937     bretry = NULL;
6938 
6939     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
6940     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
6941         || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE)
6942         || !TEST_true(SSL_want_write(peerwrite))
6943         || !TEST_true(SSL_net_write_desired(peerwrite)))
6944         goto end;
6945 
6946     /* Reinstate the original writing endpoint's write BIO */
6947     SSL_set0_wbio(peerwrite, tmp);
6948     tmp = NULL;
6949 
6950     /* Now read some data - we will read the key update */
6951     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
6952         || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ)
6953         || !TEST_true(SSL_want_read(peerwrite))
6954         || !TEST_true(SSL_net_read_desired(peerwrite)))
6955         goto end;
6956 
6957     /*
6958      * Complete the write we started previously and read it from the other
6959      * endpoint
6960      */
6961     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6962         || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6963         goto end;
6964 
6965     /* Write more data to ensure we send the KeyUpdate message back */
6966     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6967         || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6968         goto end;
6969 
6970     if (!TEST_false(SSL_net_read_desired(peerwrite))
6971         || !TEST_false(SSL_net_write_desired(peerwrite))
6972         || !TEST_int_eq(SSL_want(peerwrite), SSL_NOTHING))
6973         goto end;
6974 
6975     testresult = 1;
6976 
6977 end:
6978     SSL_free(serverssl);
6979     SSL_free(clientssl);
6980     SSL_CTX_free(sctx);
6981     SSL_CTX_free(cctx);
6982     BIO_free(bretry);
6983     BIO_free(tmp);
6984 
6985     return testresult;
6986 }
6987 
6988 /*
6989  * Test we can handle a KeyUpdate (update requested) message while
6990  * peer read data is pending after peer accepted keyupdate(the msg header
6991  * had been read 5 bytes).
6992  * Test 0: Client sends KeyUpdate while Server is reading
6993  * Test 1: Server sends KeyUpdate while Client is reading
6994  */
6995 static int test_key_update_peer_in_read(int tst)
6996 {
6997     SSL_CTX *cctx = NULL, *sctx = NULL;
6998     SSL *clientssl = NULL, *serverssl = NULL;
6999     int testresult = 0;
7000     char prbuf[515], lwbuf[515] = { 0 };
7001     static char *mess = "A test message";
7002     BIO *lbio = NULL, *pbio = NULL;
7003     SSL *local = NULL, *peer = NULL;
7004 
7005     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7006             TLS_client_method(),
7007             TLS1_3_VERSION,
7008             0,
7009             &sctx, &cctx, cert, privkey))
7010         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7011             NULL, NULL))
7012         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7013             SSL_ERROR_NONE)))
7014         goto end;
7015 
7016     local = tst == 0 ? clientssl : serverssl;
7017     peer = tst == 0 ? serverssl : clientssl;
7018 
7019     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
7020         goto end;
7021 
7022     SSL_set_bio(local, lbio, lbio);
7023     SSL_set_bio(peer, pbio, pbio);
7024 
7025     /*
7026      * we first write keyupdate msg then appdata in local
7027      * write data in local will fail with SSL_ERROR_WANT_WRITE,because
7028      * lwbuf app data msg size + key updata msg size > 512(the size of
7029      * the bio pair buffer)
7030      */
7031     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7032         || !TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), -1)
7033         || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
7034         goto end;
7035 
7036     /*
7037      * first read keyupdate msg in peer in peer
7038      * then read appdata that we know will fail with SSL_ERROR_WANT_READ
7039      */
7040     if (!TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), -1)
7041         || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_READ))
7042         goto end;
7043 
7044     /* Now write some data in peer - we will write the key update */
7045     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)))
7046         goto end;
7047 
7048     /*
7049      * write data in local previously that we will complete
7050      * read data in peer previously that we will complete
7051      */
7052     if (!TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), sizeof(lwbuf))
7053         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), sizeof(prbuf)))
7054         goto end;
7055 
7056     /* check that sending and receiving appdata ok */
7057     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7058         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
7059         goto end;
7060 
7061     testresult = 1;
7062 
7063 end:
7064     SSL_free(serverssl);
7065     SSL_free(clientssl);
7066     SSL_CTX_free(sctx);
7067     SSL_CTX_free(cctx);
7068 
7069     return testresult;
7070 }
7071 
7072 /*
7073  * Test we can't send a KeyUpdate (update requested) message while
7074  * local write data is pending.
7075  * Test 0: Client sends KeyUpdate while Client is writing
7076  * Test 1: Server sends KeyUpdate while Server is writing
7077  */
7078 static int test_key_update_local_in_write(int tst)
7079 {
7080     SSL_CTX *cctx = NULL, *sctx = NULL;
7081     SSL *clientssl = NULL, *serverssl = NULL;
7082     int testresult = 0;
7083     char buf[20];
7084     static char *mess = "A test message";
7085     BIO *bretry = BIO_new(bio_s_always_retry());
7086     BIO *tmp = NULL;
7087     SSL *local = NULL, *peer = NULL;
7088 
7089     if (!TEST_ptr(bretry)
7090         || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7091             TLS_client_method(),
7092             TLS1_3_VERSION,
7093             0,
7094             &sctx, &cctx, cert, privkey))
7095         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7096             NULL, NULL))
7097         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7098             SSL_ERROR_NONE)))
7099         goto end;
7100 
7101     local = tst == 0 ? clientssl : serverssl;
7102     peer = tst == 0 ? serverssl : clientssl;
7103 
7104     /* Swap the writing endpoint's write BIO to force a retry */
7105     tmp = SSL_get_wbio(local);
7106     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
7107         tmp = NULL;
7108         goto end;
7109     }
7110     SSL_set0_wbio(local, bretry);
7111     bretry = NULL;
7112 
7113     /* write data in local will fail with SSL_ERROR_WANT_WRITE */
7114     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), -1)
7115         || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
7116         goto end;
7117 
7118     /* Reinstate the original writing endpoint's write BIO */
7119     SSL_set0_wbio(local, tmp);
7120     tmp = NULL;
7121 
7122     /* SSL_key_update will fail, because writing in local*/
7123     if (!TEST_false(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7124         || !TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_BAD_WRITE_RETRY))
7125         goto end;
7126 
7127     ERR_clear_error();
7128     /* write data in local previously that we will complete */
7129     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)))
7130         goto end;
7131 
7132     /* SSL_key_update will succeed because there is no pending write data */
7133     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7134         || !TEST_int_eq(SSL_do_handshake(local), 1))
7135         goto end;
7136 
7137     /*
7138      * we write some appdata in local
7139      * read data in peer - we will read the keyupdate msg
7140      */
7141     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7142         || !TEST_int_eq(SSL_read(peer, buf, sizeof(buf)), strlen(mess)))
7143         goto end;
7144 
7145     /* Write more peer more data to ensure we send the keyupdate message back */
7146     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7147         || !TEST_int_eq(SSL_read(local, buf, sizeof(buf)), strlen(mess)))
7148         goto end;
7149 
7150     testresult = 1;
7151 
7152 end:
7153     SSL_free(serverssl);
7154     SSL_free(clientssl);
7155     SSL_CTX_free(sctx);
7156     SSL_CTX_free(cctx);
7157     BIO_free(bretry);
7158     BIO_free(tmp);
7159 
7160     return testresult;
7161 }
7162 
7163 /*
7164  * Test we can handle a KeyUpdate (update requested) message while
7165  * local read data is pending(the msg header had been read 5 bytes).
7166  * Test 0: Client sends KeyUpdate while Client is reading
7167  * Test 1: Server sends KeyUpdate while Server is reading
7168  */
7169 static int test_key_update_local_in_read(int tst)
7170 {
7171     SSL_CTX *cctx = NULL, *sctx = NULL;
7172     SSL *clientssl = NULL, *serverssl = NULL;
7173     int testresult = 0;
7174     char lrbuf[515], pwbuf[515] = { 0 }, prbuf[20];
7175     static char *mess = "A test message";
7176     BIO *lbio = NULL, *pbio = NULL;
7177     SSL *local = NULL, *peer = NULL;
7178 
7179     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7180             TLS_client_method(),
7181             TLS1_3_VERSION,
7182             0,
7183             &sctx, &cctx, cert, privkey))
7184         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7185             NULL, NULL))
7186         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7187             SSL_ERROR_NONE)))
7188         goto end;
7189 
7190     local = tst == 0 ? clientssl : serverssl;
7191     peer = tst == 0 ? serverssl : clientssl;
7192 
7193     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
7194         goto end;
7195 
7196     SSL_set_bio(local, lbio, lbio);
7197     SSL_set_bio(peer, pbio, pbio);
7198 
7199     /* write app data in peer will fail with SSL_ERROR_WANT_WRITE */
7200     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), -1)
7201         || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_WRITE))
7202         goto end;
7203 
7204     /* read appdata in local will fail with SSL_ERROR_WANT_READ */
7205     if (!TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), -1)
7206         || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_READ))
7207         goto end;
7208 
7209     /* SSL_do_handshake will send keyupdate msg */
7210     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7211         || !TEST_int_eq(SSL_do_handshake(local), 1))
7212         goto end;
7213 
7214     /*
7215      * write data in peer previously that we will complete
7216      * read data in local previously that we will complete
7217      */
7218     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), sizeof(pwbuf))
7219         || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), sizeof(lrbuf)))
7220         goto end;
7221 
7222     /*
7223      * write data in local
7224      * read data in peer - we will read the key update
7225      */
7226     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7227         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
7228         goto end;
7229 
7230     /* Write more peer data to ensure we send the keyupdate message back */
7231     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7232         || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), strlen(mess)))
7233         goto end;
7234 
7235     testresult = 1;
7236 
7237 end:
7238     SSL_free(serverssl);
7239     SSL_free(clientssl);
7240     SSL_CTX_free(sctx);
7241     SSL_CTX_free(cctx);
7242 
7243     return testresult;
7244 }
7245 #endif /* OSSL_NO_USABLE_TLS1_3 */
7246 
7247 /*
7248  * Test clearing a connection via SSL_clear(), or resetting it via
7249  * SSL_set_connect_state()/SSL_set_accept_state()
7250  * Test 0: SSL_set_connect_state, TLSv1.3
7251  * Test 1: SSL_set_connect_state, TLSv1.2
7252  * Test 2: SSL_set_accept_state, TLSv1.3
7253  * Test 3: SSL_set_accept_state, TLSv1.2
7254  * Test 4: SSL_clear (client), TLSv1.3
7255  * Test 5: SSL_clear (client), TLSv1.2
7256  * Test 6: SSL_clear (server), TLSv1.3
7257  * Test 7: SSL_clear (server), TLSv1.2
7258  */
7259 static int test_ssl_clear(int idx)
7260 {
7261     SSL_CTX *cctx = NULL, *sctx = NULL;
7262     SSL *clientssl = NULL, *serverssl = NULL;
7263     SSL *writer, *reader;
7264     int testresult = 0;
7265     int tls12test, servertest, cleartest;
7266     size_t written, readbytes;
7267     const char *msg = "Hello World";
7268     unsigned char buf[5];
7269 
7270     tls12test = idx & 1;
7271     idx >>= 1;
7272     servertest = idx & 1;
7273     idx >>= 1;
7274     cleartest = idx & 1;
7275 
7276 #ifdef OPENSSL_NO_TLS1_2
7277     if (tls12test == 1)
7278         return TEST_skip("No TLSv1.2 in this build");
7279 #endif
7280 
7281     /* Create an initial connection */
7282     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7283             TLS_client_method(), TLS1_VERSION, 0,
7284             &sctx, &cctx, cert, privkey))
7285         || (tls12test
7286             && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
7287                 TLS1_2_VERSION)))
7288         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
7289             &clientssl, NULL, NULL))
7290         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7291             SSL_ERROR_NONE)))
7292         goto end;
7293 
7294     if (servertest) {
7295         writer = clientssl;
7296         reader = serverssl;
7297     } else {
7298         writer = serverssl;
7299         reader = clientssl;
7300     }
7301 
7302     /* Write some data */
7303     if (!TEST_true(SSL_write_ex(writer, msg, strlen(msg), &written))
7304         || written != strlen(msg))
7305         goto end;
7306 
7307     /*
7308      * Read a partial record. The remaining buffered data should be cleared by
7309      * the subsequent clear/reset
7310      */
7311     if (!TEST_true(SSL_read_ex(reader, buf, sizeof(buf), &readbytes))
7312         || readbytes != sizeof(buf))
7313         goto end;
7314 
7315     SSL_shutdown(clientssl);
7316     SSL_shutdown(serverssl);
7317 
7318     /* Reset/clear one SSL object in order to reuse it. We free the other one */
7319     if (servertest) {
7320         if (cleartest) {
7321             if (!TEST_true(SSL_clear(serverssl)))
7322                 goto end;
7323         } else {
7324             SSL_set_accept_state(serverssl);
7325         }
7326         SSL_free(clientssl);
7327         clientssl = NULL;
7328     } else {
7329         if (cleartest) {
7330             if (!TEST_true(SSL_clear(clientssl)))
7331                 goto end;
7332         } else {
7333             SSL_set_connect_state(clientssl);
7334         }
7335         SSL_free(serverssl);
7336         serverssl = NULL;
7337     }
7338 
7339     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7340             NULL, NULL))
7341         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7342             SSL_ERROR_NONE))
7343         || !TEST_true(servertest || SSL_session_reused(clientssl)))
7344         goto end;
7345 
7346     SSL_shutdown(clientssl);
7347     SSL_shutdown(serverssl);
7348 
7349     testresult = 1;
7350 
7351 end:
7352     SSL_free(serverssl);
7353     SSL_free(clientssl);
7354     SSL_CTX_free(sctx);
7355     SSL_CTX_free(cctx);
7356 
7357     return testresult;
7358 }
7359 
7360 /* Parse CH and retrieve any MFL extension value if present */
7361 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
7362 {
7363     long len;
7364     unsigned char *data;
7365     PACKET pkt, pkt2, pkt3;
7366     unsigned int MFL_code = 0, type = 0;
7367 
7368     if (!TEST_uint_gt(len = BIO_get_mem_data(bio, (char **)&data), 0))
7369         goto end;
7370 
7371     memset(&pkt, 0, sizeof(pkt));
7372     memset(&pkt2, 0, sizeof(pkt2));
7373     memset(&pkt3, 0, sizeof(pkt3));
7374 
7375     if (!TEST_long_gt(len, 0)
7376         || !TEST_true(PACKET_buf_init(&pkt, data, len))
7377         /* Skip the record header */
7378         || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
7379         /* Skip the handshake message header */
7380         || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
7381         /* Skip client version and random */
7382         || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN + SSL3_RANDOM_SIZE))
7383         /* Skip session id */
7384         || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7385         /* Skip ciphers */
7386         || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
7387         /* Skip compression */
7388         || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7389         /* Extensions len */
7390         || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
7391         goto end;
7392 
7393     /* Loop through all extensions */
7394     while (PACKET_remaining(&pkt2)) {
7395         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
7396             || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
7397             goto end;
7398 
7399         if (type == TLSEXT_TYPE_max_fragment_length) {
7400             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
7401                 || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
7402                 goto end;
7403 
7404             *mfl_codemfl_code = MFL_code;
7405             return 1;
7406         }
7407     }
7408 
7409 end:
7410     return 0;
7411 }
7412 
7413 /* Maximum-Fragment-Length TLS extension mode to test */
7414 static const unsigned char max_fragment_len_test[] = {
7415     TLSEXT_max_fragment_length_512,
7416     TLSEXT_max_fragment_length_1024,
7417     TLSEXT_max_fragment_length_2048,
7418     TLSEXT_max_fragment_length_4096
7419 };
7420 
7421 static int test_max_fragment_len_ext(int idx_tst)
7422 {
7423     SSL_CTX *ctx = NULL;
7424     SSL *con = NULL;
7425     int testresult = 0, MFL_mode = 0;
7426     BIO *rbio, *wbio;
7427 
7428     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(),
7429             TLS1_VERSION, 0, NULL, &ctx, NULL,
7430             NULL)))
7431         return 0;
7432 
7433     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
7434             ctx, max_fragment_len_test[idx_tst])))
7435         goto end;
7436 
7437     con = SSL_new(ctx);
7438     if (!TEST_ptr(con))
7439         goto end;
7440 
7441     rbio = BIO_new(BIO_s_mem());
7442     wbio = BIO_new(BIO_s_mem());
7443     if (!TEST_ptr(rbio) || !TEST_ptr(wbio)) {
7444         BIO_free(rbio);
7445         BIO_free(wbio);
7446         goto end;
7447     }
7448 
7449     SSL_set_bio(con, rbio, wbio);
7450 
7451     if (!TEST_int_le(SSL_connect(con), 0)) {
7452         /* This shouldn't succeed because we don't have a server! */
7453         goto end;
7454     }
7455 
7456     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
7457         /* no MFL in client hello */
7458         goto end;
7459     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
7460         goto end;
7461 
7462     testresult = 1;
7463 
7464 end:
7465     SSL_free(con);
7466     SSL_CTX_free(ctx);
7467 
7468     return testresult;
7469 }
7470 
7471 #ifndef OSSL_NO_USABLE_TLS1_3
7472 static int test_pha_key_update(void)
7473 {
7474     SSL_CTX *cctx = NULL, *sctx = NULL;
7475     SSL *clientssl = NULL, *serverssl = NULL;
7476     int testresult = 0;
7477 
7478     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7479             TLS_client_method(), TLS1_VERSION, 0,
7480             &sctx, &cctx, cert, privkey)))
7481         return 0;
7482 
7483     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
7484         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
7485         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
7486         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
7487         goto end;
7488 
7489     SSL_CTX_set_post_handshake_auth(cctx, 1);
7490 
7491     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7492             NULL, NULL)))
7493         goto end;
7494 
7495     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7496             SSL_ERROR_NONE)))
7497         goto end;
7498 
7499     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
7500     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
7501         goto end;
7502 
7503     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
7504         goto end;
7505 
7506     /* Start handshake on the server */
7507     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
7508         goto end;
7509 
7510     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
7511     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7512             SSL_ERROR_NONE)))
7513         goto end;
7514 
7515     SSL_shutdown(clientssl);
7516     SSL_shutdown(serverssl);
7517 
7518     testresult = 1;
7519 
7520 end:
7521     SSL_free(serverssl);
7522     SSL_free(clientssl);
7523     SSL_CTX_free(sctx);
7524     SSL_CTX_free(cctx);
7525     return testresult;
7526 }
7527 #endif
7528 
7529 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7530 
7531 static SRP_VBASE *vbase = NULL;
7532 
7533 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
7534 {
7535     int ret = SSL3_AL_FATAL;
7536     char *username;
7537     SRP_user_pwd *user = NULL;
7538 
7539     username = SSL_get_srp_username(s);
7540     if (username == NULL) {
7541         *ad = SSL_AD_INTERNAL_ERROR;
7542         goto err;
7543     }
7544 
7545     user = SRP_VBASE_get1_by_user(vbase, username);
7546     if (user == NULL) {
7547         *ad = SSL_AD_INTERNAL_ERROR;
7548         goto err;
7549     }
7550 
7551     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
7552             user->info)
7553         <= 0) {
7554         *ad = SSL_AD_INTERNAL_ERROR;
7555         goto err;
7556     }
7557 
7558     ret = 0;
7559 
7560 err:
7561     SRP_user_pwd_free(user);
7562     return ret;
7563 }
7564 
7565 static int create_new_vfile(char *userid, char *password, const char *filename)
7566 {
7567     char *gNid = NULL;
7568     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
7569     TXT_DB *db = NULL;
7570     int ret = 0;
7571     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
7572     size_t i;
7573 
7574     if (!TEST_ptr(dummy) || !TEST_ptr(row))
7575         goto end;
7576 
7577     gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
7578         &row[DB_srpverifier], NULL, NULL, libctx, NULL);
7579     if (!TEST_ptr(gNid))
7580         goto end;
7581 
7582     /*
7583      * The only way to create an empty TXT_DB is to provide a BIO with no data
7584      * in it!
7585      */
7586     db = TXT_DB_read(dummy, DB_NUMBER);
7587     if (!TEST_ptr(db))
7588         goto end;
7589 
7590     out = BIO_new_file(filename, "w");
7591     if (!TEST_ptr(out))
7592         goto end;
7593 
7594     row[DB_srpid] = OPENSSL_strdup(userid);
7595     row[DB_srptype] = OPENSSL_strdup("V");
7596     row[DB_srpgN] = OPENSSL_strdup(gNid);
7597 
7598     if (!TEST_ptr(row[DB_srpid])
7599         || !TEST_ptr(row[DB_srptype])
7600         || !TEST_ptr(row[DB_srpgN])
7601         || !TEST_true(TXT_DB_insert(db, row)))
7602         goto end;
7603 
7604     row = NULL;
7605 
7606     if (TXT_DB_write(out, db) <= 0)
7607         goto end;
7608 
7609     ret = 1;
7610 end:
7611     if (row != NULL) {
7612         for (i = 0; i < DB_NUMBER; i++)
7613             OPENSSL_free(row[i]);
7614     }
7615     OPENSSL_free(row);
7616     BIO_free(dummy);
7617     BIO_free(out);
7618     TXT_DB_free(db);
7619 
7620     return ret;
7621 }
7622 
7623 static int create_new_vbase(char *userid, char *password)
7624 {
7625     BIGNUM *verifier = NULL, *salt = NULL;
7626     const SRP_gN *lgN = NULL;
7627     SRP_user_pwd *user_pwd = NULL;
7628     int ret = 0;
7629 
7630     lgN = SRP_get_default_gN(NULL);
7631     if (!TEST_ptr(lgN))
7632         goto end;
7633 
7634     if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
7635             lgN->N, lgN->g, libctx, NULL)))
7636         goto end;
7637 
7638     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
7639     if (!TEST_ptr(user_pwd))
7640         goto end;
7641 
7642     user_pwd->N = lgN->N;
7643     user_pwd->g = lgN->g;
7644     user_pwd->id = OPENSSL_strdup(userid);
7645     if (!TEST_ptr(user_pwd->id))
7646         goto end;
7647 
7648     user_pwd->v = verifier;
7649     user_pwd->s = salt;
7650     verifier = salt = NULL;
7651 
7652     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
7653         goto end;
7654     user_pwd = NULL;
7655 
7656     ret = 1;
7657 end:
7658     SRP_user_pwd_free(user_pwd);
7659     BN_free(salt);
7660     BN_free(verifier);
7661 
7662     return ret;
7663 }
7664 
7665 /*
7666  * SRP tests
7667  *
7668  * Test 0: Simple successful SRP connection, new vbase
7669  * Test 1: Connection failure due to bad password, new vbase
7670  * Test 2: Simple successful SRP connection, vbase loaded from existing file
7671  * Test 3: Connection failure due to bad password, vbase loaded from existing
7672  *         file
7673  * Test 4: Simple successful SRP connection, vbase loaded from new file
7674  * Test 5: Connection failure due to bad password, vbase loaded from new file
7675  */
7676 static int test_srp(int tst)
7677 {
7678     char *userid = "test", *password = "password", *tstsrpfile;
7679     SSL_CTX *cctx = NULL, *sctx = NULL;
7680     SSL *clientssl = NULL, *serverssl = NULL;
7681     int ret, testresult = 0;
7682 
7683     vbase = SRP_VBASE_new(NULL);
7684     if (!TEST_ptr(vbase))
7685         goto end;
7686 
7687     if (tst == 0 || tst == 1) {
7688         if (!TEST_true(create_new_vbase(userid, password)))
7689             goto end;
7690     } else {
7691         if (tst == 4 || tst == 5) {
7692             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
7693                 goto end;
7694             tstsrpfile = tmpfilename;
7695         } else {
7696             tstsrpfile = srpvfile;
7697         }
7698         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
7699             goto end;
7700     }
7701 
7702     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7703             TLS_client_method(), TLS1_VERSION, 0,
7704             &sctx, &cctx, cert, privkey)))
7705         goto end;
7706 
7707     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
7708         || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
7709         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
7710         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
7711         || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
7712         goto end;
7713 
7714     if (tst % 2 == 1) {
7715         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
7716             goto end;
7717     } else {
7718         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
7719             goto end;
7720     }
7721 
7722     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7723             NULL, NULL)))
7724         goto end;
7725 
7726     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
7727     if (ret) {
7728         if (!TEST_true(tst % 2 == 0))
7729             goto end;
7730     } else {
7731         if (!TEST_true(tst % 2 == 1))
7732             goto end;
7733     }
7734 
7735     testresult = 1;
7736 
7737 end:
7738     SRP_VBASE_free(vbase);
7739     vbase = NULL;
7740     SSL_free(serverssl);
7741     SSL_free(clientssl);
7742     SSL_CTX_free(sctx);
7743     SSL_CTX_free(cctx);
7744 
7745     return testresult;
7746 }
7747 #endif
7748 
7749 static int info_cb_failed = 0;
7750 static int info_cb_offset = 0;
7751 static int info_cb_this_state = -1;
7752 
7753 static struct info_cb_states_st {
7754     int where;
7755     const char *statestr;
7756 } info_cb_states[][60] = {
7757     {
7758         /* TLSv1.2 server followed by resumption */
7759         { SSL_CB_HANDSHAKE_START, NULL },
7760         { SSL_CB_LOOP, "PINIT" },
7761         { SSL_CB_LOOP, "PINIT" },
7762         { SSL_CB_LOOP, "TRCH" },
7763         { SSL_CB_LOOP, "TWSH" },
7764         { SSL_CB_LOOP, "TWSC" },
7765         { SSL_CB_LOOP, "TWSKE" },
7766         { SSL_CB_LOOP, "TWSD" },
7767         { SSL_CB_EXIT, NULL },
7768         { SSL_CB_LOOP, "TWSD" },
7769         { SSL_CB_LOOP, "TRCKE" },
7770         { SSL_CB_LOOP, "TRCCS" },
7771         { SSL_CB_LOOP, "TRFIN" },
7772         { SSL_CB_LOOP, "TWST" },
7773         { SSL_CB_LOOP, "TWCCS" },
7774         { SSL_CB_LOOP, "TWFIN" },
7775         { SSL_CB_HANDSHAKE_DONE, NULL },
7776         { SSL_CB_EXIT, NULL },
7777         { SSL_CB_ALERT, NULL },
7778         { SSL_CB_HANDSHAKE_START, NULL },
7779         { SSL_CB_LOOP, "PINIT" },
7780         { SSL_CB_LOOP, "PINIT" },
7781         { SSL_CB_LOOP, "TRCH" },
7782         { SSL_CB_LOOP, "TWSH" },
7783         { SSL_CB_LOOP, "TWCCS" },
7784         { SSL_CB_LOOP, "TWFIN" },
7785         { SSL_CB_EXIT, NULL },
7786         { SSL_CB_LOOP, "TWFIN" },
7787         { SSL_CB_LOOP, "TRCCS" },
7788         { SSL_CB_LOOP, "TRFIN" },
7789         { SSL_CB_HANDSHAKE_DONE, NULL },
7790         { SSL_CB_EXIT, NULL },
7791         { 0, NULL },
7792     },
7793     {
7794         /* TLSv1.2 client followed by resumption */
7795         { SSL_CB_HANDSHAKE_START, NULL },
7796         { SSL_CB_LOOP, "PINIT" },
7797         { SSL_CB_LOOP, "TWCH" },
7798         { SSL_CB_EXIT, NULL },
7799         { SSL_CB_LOOP, "TWCH" },
7800         { SSL_CB_LOOP, "TRSH" },
7801         { SSL_CB_LOOP, "TRSC" },
7802         { SSL_CB_LOOP, "TRSKE" },
7803         { SSL_CB_LOOP, "TRSD" },
7804         { SSL_CB_LOOP, "TWCKE" },
7805         { SSL_CB_LOOP, "TWCCS" },
7806         { SSL_CB_LOOP, "TWFIN" },
7807         { SSL_CB_EXIT, NULL },
7808         { SSL_CB_LOOP, "TWFIN" },
7809         { SSL_CB_LOOP, "TRST" },
7810         { SSL_CB_LOOP, "TRCCS" },
7811         { SSL_CB_LOOP, "TRFIN" },
7812         { SSL_CB_HANDSHAKE_DONE, NULL },
7813         { SSL_CB_EXIT, NULL },
7814         { SSL_CB_ALERT, NULL },
7815         { SSL_CB_HANDSHAKE_START, NULL },
7816         { SSL_CB_LOOP, "PINIT" },
7817         { SSL_CB_LOOP, "TWCH" },
7818         { SSL_CB_EXIT, NULL },
7819         { SSL_CB_LOOP, "TWCH" },
7820         { SSL_CB_LOOP, "TRSH" },
7821         { SSL_CB_LOOP, "TRCCS" },
7822         { SSL_CB_LOOP, "TRFIN" },
7823         { SSL_CB_LOOP, "TWCCS" },
7824         { SSL_CB_LOOP, "TWFIN" },
7825         { SSL_CB_HANDSHAKE_DONE, NULL },
7826         { SSL_CB_EXIT, NULL },
7827         { 0, NULL },
7828     },
7829     {
7830         /* TLSv1.3 server followed by resumption */
7831         { SSL_CB_HANDSHAKE_START, NULL },
7832         { SSL_CB_LOOP, "PINIT" },
7833         { SSL_CB_LOOP, "PINIT" },
7834         { SSL_CB_LOOP, "TRCH" },
7835         { SSL_CB_LOOP, "TWSH" },
7836         { SSL_CB_LOOP, "TWCCS" },
7837         { SSL_CB_LOOP, "TWEE" },
7838         { SSL_CB_LOOP, "TWSC" },
7839         { SSL_CB_LOOP, "TWSCV" },
7840         { SSL_CB_LOOP, "TWFIN" },
7841         { SSL_CB_LOOP, "TED" },
7842         { SSL_CB_EXIT, NULL },
7843         { SSL_CB_LOOP, "TED" },
7844         { SSL_CB_LOOP, "TRFIN" },
7845         { SSL_CB_HANDSHAKE_DONE, NULL },
7846         { SSL_CB_LOOP, "TWST" },
7847         { SSL_CB_LOOP, "TWST" },
7848         { SSL_CB_EXIT, NULL },
7849         { SSL_CB_ALERT, NULL },
7850         { SSL_CB_HANDSHAKE_START, NULL },
7851         { SSL_CB_LOOP, "PINIT" },
7852         { SSL_CB_LOOP, "PINIT" },
7853         { SSL_CB_LOOP, "TRCH" },
7854         { SSL_CB_LOOP, "TWSH" },
7855         { SSL_CB_LOOP, "TWCCS" },
7856         { SSL_CB_LOOP, "TWEE" },
7857         { SSL_CB_LOOP, "TWFIN" },
7858         { SSL_CB_LOOP, "TED" },
7859         { SSL_CB_EXIT, NULL },
7860         { SSL_CB_LOOP, "TED" },
7861         { SSL_CB_LOOP, "TRFIN" },
7862         { SSL_CB_HANDSHAKE_DONE, NULL },
7863         { SSL_CB_LOOP, "TWST" },
7864         { SSL_CB_EXIT, NULL },
7865         { 0, NULL },
7866     },
7867     {
7868         /* TLSv1.3 client followed by resumption */
7869         { SSL_CB_HANDSHAKE_START, NULL },
7870         { SSL_CB_LOOP, "PINIT" },
7871         { SSL_CB_LOOP, "TWCH" },
7872         { SSL_CB_EXIT, NULL },
7873         { SSL_CB_LOOP, "TWCH" },
7874         { SSL_CB_LOOP, "TRSH" },
7875         { SSL_CB_LOOP, "TREE" },
7876         { SSL_CB_LOOP, "TRSC" },
7877         { SSL_CB_LOOP, "TRSCV" },
7878         { SSL_CB_LOOP, "TRFIN" },
7879         { SSL_CB_LOOP, "TWCCS" },
7880         { SSL_CB_LOOP, "TWFIN" },
7881         { SSL_CB_HANDSHAKE_DONE, NULL },
7882         { SSL_CB_EXIT, NULL },
7883         { SSL_CB_LOOP, "SSLOK" },
7884         { SSL_CB_LOOP, "SSLOK" },
7885         { SSL_CB_LOOP, "TRST" },
7886         { SSL_CB_EXIT, NULL },
7887         { SSL_CB_LOOP, "SSLOK" },
7888         { SSL_CB_LOOP, "SSLOK" },
7889         { SSL_CB_LOOP, "TRST" },
7890         { SSL_CB_EXIT, NULL },
7891         { SSL_CB_ALERT, NULL },
7892         { SSL_CB_HANDSHAKE_START, NULL },
7893         { SSL_CB_LOOP, "PINIT" },
7894         { SSL_CB_LOOP, "TWCH" },
7895         { SSL_CB_EXIT, NULL },
7896         { SSL_CB_LOOP, "TWCH" },
7897         { SSL_CB_LOOP, "TRSH" },
7898         { SSL_CB_LOOP, "TREE" },
7899         { SSL_CB_LOOP, "TRFIN" },
7900         { SSL_CB_LOOP, "TWCCS" },
7901         { SSL_CB_LOOP, "TWFIN" },
7902         { SSL_CB_HANDSHAKE_DONE, NULL },
7903         { SSL_CB_EXIT, NULL },
7904         { SSL_CB_LOOP, "SSLOK" },
7905         { SSL_CB_LOOP, "SSLOK" },
7906         { SSL_CB_LOOP, "TRST" },
7907         { SSL_CB_EXIT, NULL },
7908         { 0, NULL },
7909     },
7910     {
7911         /* TLSv1.3 server, early_data */
7912         { SSL_CB_HANDSHAKE_START, NULL },
7913         { SSL_CB_LOOP, "PINIT" },
7914         { SSL_CB_LOOP, "PINIT" },
7915         { SSL_CB_LOOP, "TRCH" },
7916         { SSL_CB_LOOP, "TWSH" },
7917         { SSL_CB_LOOP, "TWCCS" },
7918         { SSL_CB_LOOP, "TWEE" },
7919         { SSL_CB_LOOP, "TWFIN" },
7920         { SSL_CB_HANDSHAKE_DONE, NULL },
7921         { SSL_CB_EXIT, NULL },
7922         { SSL_CB_HANDSHAKE_START, NULL },
7923         { SSL_CB_LOOP, "TED" },
7924         { SSL_CB_LOOP, "TED" },
7925         { SSL_CB_LOOP, "TWEOED" },
7926         { SSL_CB_LOOP, "TRFIN" },
7927         { SSL_CB_HANDSHAKE_DONE, NULL },
7928         { SSL_CB_LOOP, "TWST" },
7929         { SSL_CB_EXIT, NULL },
7930         { 0, NULL },
7931     },
7932     {
7933         /* TLSv1.3 client, early_data */
7934         { SSL_CB_HANDSHAKE_START, NULL },
7935         { SSL_CB_LOOP, "PINIT" },
7936         { SSL_CB_LOOP, "TWCH" },
7937         { SSL_CB_LOOP, "TWCCS" },
7938         { SSL_CB_HANDSHAKE_DONE, NULL },
7939         { SSL_CB_EXIT, NULL },
7940         { SSL_CB_HANDSHAKE_START, NULL },
7941         { SSL_CB_LOOP, "TED" },
7942         { SSL_CB_LOOP, "TED" },
7943         { SSL_CB_LOOP, "TRSH" },
7944         { SSL_CB_LOOP, "TREE" },
7945         { SSL_CB_LOOP, "TRFIN" },
7946         { SSL_CB_LOOP, "TPEDE" },
7947         { SSL_CB_LOOP, "TWEOED" },
7948         { SSL_CB_LOOP, "TWFIN" },
7949         { SSL_CB_HANDSHAKE_DONE, NULL },
7950         { SSL_CB_EXIT, NULL },
7951         { SSL_CB_LOOP, "SSLOK" },
7952         { SSL_CB_LOOP, "SSLOK" },
7953         { SSL_CB_LOOP, "TRST" },
7954         { SSL_CB_EXIT, NULL },
7955         { 0, NULL },
7956     },
7957     {
7958         /* TLSv1.3 server, certificate compression, followed by resumption */
7959         { SSL_CB_HANDSHAKE_START, NULL },
7960         { SSL_CB_LOOP, "PINIT" },
7961         { SSL_CB_LOOP, "PINIT" },
7962         { SSL_CB_LOOP, "TRCH" },
7963         { SSL_CB_LOOP, "TWSH" },
7964         { SSL_CB_LOOP, "TWCCS" },
7965         { SSL_CB_LOOP, "TWEE" },
7966         { SSL_CB_LOOP, "TWSCC" },
7967         { SSL_CB_LOOP, "TWSCV" },
7968         { SSL_CB_LOOP, "TWFIN" },
7969         { SSL_CB_LOOP, "TED" },
7970         { SSL_CB_EXIT, NULL },
7971         { SSL_CB_LOOP, "TED" },
7972         { SSL_CB_LOOP, "TRFIN" },
7973         { SSL_CB_HANDSHAKE_DONE, NULL },
7974         { SSL_CB_LOOP, "TWST" },
7975         { SSL_CB_LOOP, "TWST" },
7976         { SSL_CB_EXIT, NULL },
7977         { SSL_CB_ALERT, NULL },
7978         { SSL_CB_HANDSHAKE_START, NULL },
7979         { SSL_CB_LOOP, "PINIT" },
7980         { SSL_CB_LOOP, "PINIT" },
7981         { SSL_CB_LOOP, "TRCH" },
7982         { SSL_CB_LOOP, "TWSH" },
7983         { SSL_CB_LOOP, "TWCCS" },
7984         { SSL_CB_LOOP, "TWEE" },
7985         { SSL_CB_LOOP, "TWFIN" },
7986         { SSL_CB_LOOP, "TED" },
7987         { SSL_CB_EXIT, NULL },
7988         { SSL_CB_LOOP, "TED" },
7989         { SSL_CB_LOOP, "TRFIN" },
7990         { SSL_CB_HANDSHAKE_DONE, NULL },
7991         { SSL_CB_LOOP, "TWST" },
7992         { SSL_CB_EXIT, NULL },
7993         { 0, NULL },
7994     },
7995     {
7996         /* TLSv1.3 client, certificate compression, followed by resumption */
7997         { SSL_CB_HANDSHAKE_START, NULL },
7998         { SSL_CB_LOOP, "PINIT" },
7999         { SSL_CB_LOOP, "TWCH" },
8000         { SSL_CB_EXIT, NULL },
8001         { SSL_CB_LOOP, "TWCH" },
8002         { SSL_CB_LOOP, "TRSH" },
8003         { SSL_CB_LOOP, "TREE" },
8004         { SSL_CB_LOOP, "TRSCC" },
8005         { SSL_CB_LOOP, "TRSCV" },
8006         { SSL_CB_LOOP, "TRFIN" },
8007         { SSL_CB_LOOP, "TWCCS" },
8008         { SSL_CB_LOOP, "TWFIN" },
8009         { SSL_CB_HANDSHAKE_DONE, NULL },
8010         { SSL_CB_EXIT, NULL },
8011         { SSL_CB_LOOP, "SSLOK" },
8012         { SSL_CB_LOOP, "SSLOK" },
8013         { SSL_CB_LOOP, "TRST" },
8014         { SSL_CB_EXIT, NULL },
8015         { SSL_CB_LOOP, "SSLOK" },
8016         { SSL_CB_LOOP, "SSLOK" },
8017         { SSL_CB_LOOP, "TRST" },
8018         { SSL_CB_EXIT, NULL },
8019         { SSL_CB_ALERT, NULL },
8020         { SSL_CB_HANDSHAKE_START, NULL },
8021         { SSL_CB_LOOP, "PINIT" },
8022         { SSL_CB_LOOP, "TWCH" },
8023         { SSL_CB_EXIT, NULL },
8024         { SSL_CB_LOOP, "TWCH" },
8025         { SSL_CB_LOOP, "TRSH" },
8026         { SSL_CB_LOOP, "TREE" },
8027         { SSL_CB_LOOP, "TRFIN" },
8028         { SSL_CB_LOOP, "TWCCS" },
8029         { SSL_CB_LOOP, "TWFIN" },
8030         { SSL_CB_HANDSHAKE_DONE, NULL },
8031         { SSL_CB_EXIT, NULL },
8032         { SSL_CB_LOOP, "SSLOK" },
8033         { SSL_CB_LOOP, "SSLOK" },
8034         { SSL_CB_LOOP, "TRST" },
8035         { SSL_CB_EXIT, NULL },
8036         { 0, NULL },
8037     },
8038     {
8039         { 0, NULL },
8040     }
8041 };
8042 
8043 static void sslapi_info_callback(const SSL *s, int where, int ret)
8044 {
8045     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
8046 
8047     /* We do not ever expect a connection to fail in this test */
8048     if (!TEST_false(ret == 0)) {
8049         info_cb_failed = 1;
8050         return;
8051     }
8052 
8053     /*
8054      * Do some sanity checks. We never expect these things to happen in this
8055      * test
8056      */
8057     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
8058         || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
8059         || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
8060         info_cb_failed = 1;
8061         return;
8062     }
8063 
8064     /* Now check we're in the right state */
8065     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
8066         info_cb_failed = 1;
8067         return;
8068     }
8069     if ((where & SSL_CB_LOOP) != 0
8070         && !TEST_int_eq(strcmp(SSL_state_string(s),
8071                             state[info_cb_this_state].statestr),
8072             0)) {
8073         info_cb_failed = 1;
8074         return;
8075     }
8076 
8077     /*
8078      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
8079      */
8080     if ((where & SSL_CB_HANDSHAKE_DONE)
8081         && SSL_in_init((SSL *)s) != 0) {
8082         info_cb_failed = 1;
8083         return;
8084     }
8085 }
8086 
8087 /*
8088  * Test the info callback gets called when we expect it to.
8089  *
8090  * Test 0: TLSv1.2, server
8091  * Test 1: TLSv1.2, client
8092  * Test 2: TLSv1.3, server
8093  * Test 3: TLSv1.3, client
8094  * Test 4: TLSv1.3, server, early_data
8095  * Test 5: TLSv1.3, client, early_data
8096  * Test 6: TLSv1.3, server, compressed certificate
8097  * Test 7: TLSv1.3, client, compressed certificate
8098  */
8099 static int test_info_callback(int tst)
8100 {
8101     SSL_CTX *cctx = NULL, *sctx = NULL;
8102     SSL *clientssl = NULL, *serverssl = NULL;
8103     SSL_SESSION *clntsess = NULL;
8104     int testresult = 0;
8105     int tlsvers;
8106 
8107     if (tst < 2) {
8108 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
8109 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH))
8110         tlsvers = TLS1_2_VERSION;
8111 #else
8112         return 1;
8113 #endif
8114     } else {
8115 #ifndef OSSL_NO_USABLE_TLS1_3
8116         tlsvers = TLS1_3_VERSION;
8117 #else
8118         return 1;
8119 #endif
8120     }
8121 
8122     /* Reset globals */
8123     info_cb_failed = 0;
8124     info_cb_this_state = -1;
8125     info_cb_offset = tst;
8126 
8127 #ifndef OSSL_NO_USABLE_TLS1_3
8128     if (tst >= 4 && tst < 6) {
8129         SSL_SESSION *sess = NULL;
8130         size_t written, readbytes;
8131         unsigned char buf[80];
8132         OSSL_TIME timer;
8133 
8134         /* early_data tests */
8135         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
8136                 &serverssl, &sess, 0,
8137                 SHA384_DIGEST_LENGTH)))
8138             goto end;
8139 
8140         /* We don't actually need this reference */
8141         SSL_SESSION_free(sess);
8142 
8143         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
8144             sslapi_info_callback);
8145 
8146         /* Write and read some early data and then complete the connection */
8147         timer = ossl_time_now();
8148         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
8149                 &written))
8150             || !TEST_size_t_eq(written, strlen(MSG1)))
8151             goto end;
8152 
8153         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf,
8154                              sizeof(buf), &readbytes),
8155                 SSL_READ_EARLY_DATA_SUCCESS)) {
8156             testresult = check_early_data_timeout(timer);
8157             goto end;
8158         }
8159 
8160         if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
8161             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
8162                 SSL_EARLY_DATA_ACCEPTED)
8163             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8164                 SSL_ERROR_NONE))
8165             || !TEST_false(info_cb_failed))
8166             goto end;
8167 
8168         testresult = 1;
8169         goto end;
8170     }
8171 #endif
8172 
8173     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8174             TLS_client_method(),
8175             tlsvers, tlsvers, &sctx, &cctx, cert,
8176             privkey)))
8177         goto end;
8178 
8179     if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
8180         goto end;
8181 
8182     /*
8183      * For even numbered tests we check the server callbacks. For odd numbers we
8184      * check the client.
8185      */
8186     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
8187         sslapi_info_callback);
8188     if (tst >= 6) {
8189         if (!SSL_CTX_compress_certs(sctx, 0))
8190             goto end;
8191     }
8192 
8193     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
8194             &clientssl, NULL, NULL))
8195         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8196             SSL_ERROR_NONE))
8197         || !TEST_false(info_cb_failed))
8198         goto end;
8199 
8200     clntsess = SSL_get1_session(clientssl);
8201     SSL_shutdown(clientssl);
8202     SSL_shutdown(serverssl);
8203     SSL_free(serverssl);
8204     SSL_free(clientssl);
8205     serverssl = clientssl = NULL;
8206 
8207     /* Now do a resumption */
8208     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8209             NULL))
8210         || !TEST_true(SSL_set_session(clientssl, clntsess))
8211         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8212             SSL_ERROR_NONE))
8213         || !TEST_true(SSL_session_reused(clientssl))
8214         || !TEST_false(info_cb_failed))
8215         goto end;
8216 
8217     testresult = 1;
8218 
8219 end:
8220     SSL_free(serverssl);
8221     SSL_free(clientssl);
8222     SSL_SESSION_free(clntsess);
8223     SSL_CTX_free(sctx);
8224     SSL_CTX_free(cctx);
8225     return testresult;
8226 }
8227 
8228 static int test_ssl_pending(int tst)
8229 {
8230     SSL_CTX *cctx = NULL, *sctx = NULL;
8231     SSL *clientssl = NULL, *serverssl = NULL;
8232     int testresult = 0;
8233     char msg[] = "A test message";
8234     char buf[5];
8235     size_t written, readbytes;
8236 
8237     if (tst == 0) {
8238         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8239                 TLS_client_method(),
8240                 TLS1_VERSION, 0,
8241                 &sctx, &cctx, cert, privkey)))
8242             goto end;
8243     } else {
8244 #ifndef OPENSSL_NO_DTLS
8245         if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
8246                 DTLS_client_method(),
8247                 DTLS1_VERSION, 0,
8248                 &sctx, &cctx, cert, privkey)))
8249             goto end;
8250 
8251 #ifdef OPENSSL_NO_DTLS1_2
8252         /* Not supported in the FIPS provider */
8253         if (is_fips) {
8254             testresult = 1;
8255             goto end;
8256         };
8257         /*
8258          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
8259          * level 0
8260          */
8261         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
8262             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
8263                 "DEFAULT:@SECLEVEL=0")))
8264             goto end;
8265 #endif
8266 #else
8267         return 1;
8268 #endif
8269     }
8270 
8271     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8272             NULL, NULL))
8273         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8274             SSL_ERROR_NONE)))
8275         goto end;
8276 
8277     if (!TEST_int_eq(SSL_pending(clientssl), 0)
8278         || !TEST_false(SSL_has_pending(clientssl))
8279         || !TEST_int_eq(SSL_pending(serverssl), 0)
8280         || !TEST_false(SSL_has_pending(serverssl))
8281         || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8282         || !TEST_size_t_eq(written, sizeof(msg))
8283         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
8284         || !TEST_size_t_eq(readbytes, sizeof(buf))
8285         || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
8286         || !TEST_true(SSL_has_pending(clientssl)))
8287         goto end;
8288 
8289     testresult = 1;
8290 
8291 end:
8292     SSL_free(serverssl);
8293     SSL_free(clientssl);
8294     SSL_CTX_free(sctx);
8295     SSL_CTX_free(cctx);
8296 
8297     return testresult;
8298 }
8299 
8300 static struct {
8301     unsigned int maxprot;
8302     const char *clntciphers;
8303     const char *clnttls13ciphers;
8304     const char *srvrciphers;
8305     const char *srvrtls13ciphers;
8306     const char *shared;
8307     const char *fipsshared;
8308 } shared_ciphers_data[] = {
8309 /*
8310  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
8311  * TLSv1.3 is enabled but TLSv1.2 is disabled.
8312  */
8313 #if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
8314     { TLS1_2_VERSION,
8315         "AES128-SHA:AES256-SHA",
8316         NULL,
8317         "AES256-SHA:DHE-RSA-AES128-SHA",
8318         NULL,
8319         "AES256-SHA",
8320         "AES256-SHA" },
8321 #if !defined(OPENSSL_NO_CHACHA)      \
8322     && !defined(OPENSSL_NO_POLY1305) \
8323     && !defined(OPENSSL_NO_EC)
8324     { TLS1_2_VERSION,
8325         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8326         NULL,
8327         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8328         NULL,
8329         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8330         "AES128-SHA" },
8331 #endif
8332     { TLS1_2_VERSION,
8333         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
8334         NULL,
8335         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
8336         NULL,
8337         "AES128-SHA:AES256-SHA",
8338         "AES128-SHA:AES256-SHA" },
8339     { TLS1_2_VERSION,
8340         "AES128-SHA:AES256-SHA",
8341         NULL,
8342         "AES128-SHA:DHE-RSA-AES128-SHA",
8343         NULL,
8344         "AES128-SHA",
8345         "AES128-SHA" },
8346 #endif
8347 /*
8348  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
8349  * enabled.
8350  */
8351 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
8352     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
8353     { TLS1_3_VERSION,
8354         "AES128-SHA:AES256-SHA",
8355         NULL,
8356         "AES256-SHA:AES128-SHA256",
8357         NULL,
8358         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
8359         "TLS_AES_128_GCM_SHA256:AES256-SHA",
8360         "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA" },
8361 #endif
8362 #ifndef OSSL_NO_USABLE_TLS1_3
8363     { TLS1_3_VERSION,
8364         "AES128-SHA",
8365         "TLS_AES_256_GCM_SHA384",
8366         "AES256-SHA",
8367         "TLS_AES_256_GCM_SHA384",
8368         "TLS_AES_256_GCM_SHA384",
8369         "TLS_AES_256_GCM_SHA384" },
8370 #endif
8371 };
8372 
8373 static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
8374 {
8375     SSL_CTX *cctx = NULL, *sctx = NULL;
8376     SSL *clientssl = NULL, *serverssl = NULL;
8377     int testresult = 0;
8378     char buf[1024];
8379     OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
8380 
8381     if (!TEST_ptr(tmplibctx))
8382         goto end;
8383 
8384     /*
8385      * Regardless of whether we're testing with the FIPS provider loaded into
8386      * libctx, we want one peer to always use the full set of ciphersuites
8387      * available. Therefore we use a separate libctx with the default provider
8388      * loaded into it. We run the same tests twice - once with the client side
8389      * having the full set of ciphersuites and once with the server side.
8390      */
8391     if (clnt) {
8392         cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
8393         if (!TEST_ptr(cctx))
8394             goto end;
8395     } else {
8396         sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
8397         if (!TEST_ptr(sctx))
8398             goto end;
8399     }
8400 
8401     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8402             TLS_client_method(),
8403             TLS1_VERSION,
8404             shared_ciphers_data[tst].maxprot,
8405             &sctx, &cctx, cert, privkey)))
8406         goto end;
8407 
8408     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
8409             shared_ciphers_data[tst].clntciphers))
8410         || (shared_ciphers_data[tst].clnttls13ciphers != NULL
8411             && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
8412                 shared_ciphers_data[tst].clnttls13ciphers)))
8413         || !TEST_true(SSL_CTX_set_cipher_list(sctx,
8414             shared_ciphers_data[tst].srvrciphers))
8415         || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
8416             && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
8417                 shared_ciphers_data[tst].srvrtls13ciphers))))
8418         goto end;
8419 
8420     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8421             NULL, NULL))
8422         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8423             SSL_ERROR_NONE)))
8424         goto end;
8425 
8426     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
8427         || !TEST_int_eq(strcmp(buf,
8428                             is_fips
8429                                 ? shared_ciphers_data[tst].fipsshared
8430                                 : shared_ciphers_data[tst].shared),
8431             0)) {
8432         TEST_info("Shared ciphers are: %s\n", buf);
8433         goto end;
8434     }
8435 
8436     testresult = 1;
8437 
8438 end:
8439     SSL_free(serverssl);
8440     SSL_free(clientssl);
8441     SSL_CTX_free(sctx);
8442     SSL_CTX_free(cctx);
8443     OSSL_LIB_CTX_free(tmplibctx);
8444 
8445     return testresult;
8446 }
8447 
8448 static int test_ssl_get_shared_ciphers(int tst)
8449 {
8450     return int_test_ssl_get_shared_ciphers(tst, 0)
8451         && int_test_ssl_get_shared_ciphers(tst, 1);
8452 }
8453 
8454 static const char *appdata = "Hello World";
8455 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
8456 static int tick_key_renew = 0;
8457 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8458 
8459 static int gen_tick_cb(SSL *s, void *arg)
8460 {
8461     gen_tick_called = 1;
8462 
8463     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
8464         strlen(appdata));
8465 }
8466 
8467 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
8468     const unsigned char *keyname,
8469     size_t keyname_length,
8470     SSL_TICKET_STATUS status,
8471     void *arg)
8472 {
8473     void *tickdata;
8474     size_t tickdlen;
8475 
8476     dec_tick_called = 1;
8477 
8478     if (status == SSL_TICKET_EMPTY)
8479         return SSL_TICKET_RETURN_IGNORE_RENEW;
8480 
8481     if (!TEST_true(status == SSL_TICKET_SUCCESS
8482             || status == SSL_TICKET_SUCCESS_RENEW))
8483         return SSL_TICKET_RETURN_ABORT;
8484 
8485     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
8486             &tickdlen))
8487         || !TEST_size_t_eq(tickdlen, strlen(appdata))
8488         || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
8489         return SSL_TICKET_RETURN_ABORT;
8490 
8491     if (tick_key_cb_called) {
8492         /* Don't change what the ticket key callback wanted to do */
8493         switch (status) {
8494         case SSL_TICKET_NO_DECRYPT:
8495             return SSL_TICKET_RETURN_IGNORE_RENEW;
8496 
8497         case SSL_TICKET_SUCCESS:
8498             return SSL_TICKET_RETURN_USE;
8499 
8500         case SSL_TICKET_SUCCESS_RENEW:
8501             return SSL_TICKET_RETURN_USE_RENEW;
8502 
8503         default:
8504             return SSL_TICKET_RETURN_ABORT;
8505         }
8506     }
8507     return tick_dec_ret;
8508 }
8509 
8510 #ifndef OPENSSL_NO_DEPRECATED_3_0
8511 static int tick_key_cb(SSL *s, unsigned char key_name[16],
8512     unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
8513     HMAC_CTX *hctx, int enc)
8514 {
8515     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8516     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
8517     EVP_CIPHER *aes128cbc;
8518     EVP_MD *sha256;
8519     int ret;
8520 
8521     tick_key_cb_called = 1;
8522 
8523     if (tick_key_renew == -1)
8524         return 0;
8525 
8526     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8527     if (!TEST_ptr(aes128cbc))
8528         return 0;
8529     sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
8530     if (!TEST_ptr(sha256)) {
8531         EVP_CIPHER_free(aes128cbc);
8532         return 0;
8533     }
8534 
8535     memset(iv, 0, AES_BLOCK_SIZE);
8536     memset(key_name, 0, 16);
8537     if (aes128cbc == NULL
8538         || sha256 == NULL
8539         || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8540         || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
8541             NULL))
8542         ret = -1;
8543     else
8544         ret = tick_key_renew ? 2 : 1;
8545 
8546     EVP_CIPHER_free(aes128cbc);
8547     EVP_MD_free(sha256);
8548 
8549     return ret;
8550 }
8551 #endif
8552 
8553 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
8554     unsigned char iv[EVP_MAX_IV_LENGTH],
8555     EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
8556 {
8557     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8558     unsigned char tick_hmac_key[16] = "0123456789abcdef";
8559     OSSL_PARAM params[2];
8560     EVP_CIPHER *aes128cbc;
8561     int ret;
8562 
8563     tick_key_cb_called = 1;
8564 
8565     if (tick_key_renew == -1)
8566         return 0;
8567 
8568     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8569     if (!TEST_ptr(aes128cbc))
8570         return 0;
8571 
8572     memset(iv, 0, AES_BLOCK_SIZE);
8573     memset(key_name, 0, 16);
8574     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
8575         "SHA256", 0);
8576     params[1] = OSSL_PARAM_construct_end();
8577     if (aes128cbc == NULL
8578         || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8579         || !EVP_MAC_init(hctx, tick_hmac_key, sizeof(tick_hmac_key),
8580             params))
8581         ret = -1;
8582     else
8583         ret = tick_key_renew ? 2 : 1;
8584 
8585     EVP_CIPHER_free(aes128cbc);
8586 
8587     return ret;
8588 }
8589 
8590 /*
8591  * Test the various ticket callbacks
8592  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
8593  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
8594  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
8595  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
8596  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
8597  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
8598  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
8599  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
8600  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
8601  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
8602  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
8603  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
8604  * Test 12: TLSv1.2, old ticket key callback, no ticket
8605  * Test 13: TLSv1.3, old ticket key callback, no ticket
8606  * Test 14: TLSv1.2, ticket key callback, ticket, no renewal
8607  * Test 15: TLSv1.3, ticket key callback, ticket, no renewal
8608  * Test 16: TLSv1.2, ticket key callback, ticket, renewal
8609  * Test 17: TLSv1.3, ticket key callback, ticket, renewal
8610  * Test 18: TLSv1.2, ticket key callback, no ticket
8611  * Test 19: TLSv1.3, ticket key callback, no ticket
8612  */
8613 static int test_ticket_callbacks(int tst)
8614 {
8615     SSL_CTX *cctx = NULL, *sctx = NULL;
8616     SSL *clientssl = NULL, *serverssl = NULL;
8617     SSL_SESSION *clntsess = NULL;
8618     int testresult = 0;
8619 
8620 #ifdef OPENSSL_NO_TLS1_2
8621     if (tst % 2 == 0)
8622         return 1;
8623 #endif
8624 #ifdef OSSL_NO_USABLE_TLS1_3
8625     if (tst % 2 == 1)
8626         return 1;
8627 #endif
8628 #ifdef OPENSSL_NO_DEPRECATED_3_0
8629     if (tst >= 8 && tst <= 13)
8630         return 1;
8631 #endif
8632 
8633     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
8634 
8635     /* Which tests the ticket key callback should request renewal for */
8636 
8637     if (tst == 10 || tst == 11 || tst == 16 || tst == 17)
8638         tick_key_renew = 1;
8639     else if (tst == 12 || tst == 13 || tst == 18 || tst == 19)
8640         tick_key_renew = -1; /* abort sending the ticket/0-length ticket */
8641     else
8642         tick_key_renew = 0;
8643 
8644     /* Which tests the decrypt ticket callback should request renewal for */
8645     switch (tst) {
8646     case 0:
8647     case 1:
8648         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
8649         break;
8650 
8651     case 2:
8652     case 3:
8653         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
8654         break;
8655 
8656     case 4:
8657     case 5:
8658         tick_dec_ret = SSL_TICKET_RETURN_USE;
8659         break;
8660 
8661     case 6:
8662     case 7:
8663         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
8664         break;
8665 
8666     default:
8667         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8668     }
8669 
8670     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8671             TLS_client_method(),
8672             TLS1_VERSION,
8673             ((tst % 2) == 0) ? TLS1_2_VERSION
8674                              : TLS1_3_VERSION,
8675             &sctx, &cctx, cert, privkey)))
8676         goto end;
8677 
8678     /*
8679      * We only want sessions to resume from tickets - not the session cache. So
8680      * switch the cache off.
8681      */
8682     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
8683         goto end;
8684 
8685     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
8686             NULL)))
8687         goto end;
8688 
8689     if (tst >= 14) {
8690         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
8691             goto end;
8692 #ifndef OPENSSL_NO_DEPRECATED_3_0
8693     } else if (tst >= 8) {
8694         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
8695             goto end;
8696 #endif
8697     }
8698 
8699     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8700             NULL, NULL))
8701         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8702             SSL_ERROR_NONE)))
8703         goto end;
8704 
8705     /*
8706      * The decrypt ticket key callback in TLSv1.2 should be called even though
8707      * we have no ticket yet, because it gets called with a status of
8708      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
8709      * actually send any ticket data). This does not happen in TLSv1.3 because
8710      * it is not valid to send empty ticket data in TLSv1.3.
8711      */
8712     if (!TEST_int_eq(gen_tick_called, 1)
8713         || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
8714         goto end;
8715 
8716     gen_tick_called = dec_tick_called = 0;
8717 
8718     clntsess = SSL_get1_session(clientssl);
8719     SSL_shutdown(clientssl);
8720     SSL_shutdown(serverssl);
8721     SSL_free(serverssl);
8722     SSL_free(clientssl);
8723     serverssl = clientssl = NULL;
8724 
8725     /* Now do a resumption */
8726     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8727             NULL))
8728         || !TEST_true(SSL_set_session(clientssl, clntsess))
8729         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8730             SSL_ERROR_NONE)))
8731         goto end;
8732 
8733     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
8734         || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8735         || tick_key_renew == -1) {
8736         if (!TEST_false(SSL_session_reused(clientssl)))
8737             goto end;
8738     } else {
8739         if (!TEST_true(SSL_session_reused(clientssl)))
8740             goto end;
8741     }
8742 
8743     if (!TEST_int_eq(gen_tick_called,
8744             (tick_key_renew
8745                 || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8746                 || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
8747                 ? 1
8748                 : 0)
8749         /* There is no ticket to decrypt in tests 13 and 19 */
8750         || !TEST_int_eq(dec_tick_called, (tst == 13 || tst == 19) ? 0 : 1))
8751         goto end;
8752 
8753     testresult = 1;
8754 
8755 end:
8756     SSL_SESSION_free(clntsess);
8757     SSL_free(serverssl);
8758     SSL_free(clientssl);
8759     SSL_CTX_free(sctx);
8760     SSL_CTX_free(cctx);
8761 
8762     return testresult;
8763 }
8764 
8765 /*
8766  * Test incorrect shutdown.
8767  * Test 0: client does not shutdown properly,
8768  *         server does not set SSL_OP_IGNORE_UNEXPECTED_EOF,
8769  *         server should get SSL_ERROR_SSL
8770  * Test 1: client does not shutdown properly,
8771  *         server sets SSL_OP_IGNORE_UNEXPECTED_EOF,
8772  *         server should get SSL_ERROR_ZERO_RETURN
8773  */
8774 static int test_incorrect_shutdown(int tst)
8775 {
8776     SSL_CTX *cctx = NULL, *sctx = NULL;
8777     SSL *clientssl = NULL, *serverssl = NULL;
8778     int testresult = 0;
8779     char buf[80];
8780     BIO *c2s;
8781 
8782     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8783             TLS_client_method(), 0, 0,
8784             &sctx, &cctx, cert, privkey)))
8785         goto end;
8786 
8787     if (tst == 1)
8788         SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
8789 
8790     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8791             NULL, NULL)))
8792         goto end;
8793 
8794     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8795             SSL_ERROR_NONE)))
8796         goto end;
8797 
8798     c2s = SSL_get_rbio(serverssl);
8799     BIO_set_mem_eof_return(c2s, 0);
8800 
8801     if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf))))
8802         goto end;
8803 
8804     if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
8805         goto end;
8806     if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN))
8807         goto end;
8808 
8809     testresult = 1;
8810 
8811 end:
8812     SSL_free(serverssl);
8813     SSL_free(clientssl);
8814     SSL_CTX_free(sctx);
8815     SSL_CTX_free(cctx);
8816 
8817     return testresult;
8818 }
8819 
8820 /*
8821  * Test bi-directional shutdown.
8822  * Test 0: TLSv1.2
8823  * Test 1: TLSv1.2, server continues to read/write after client shutdown
8824  * Test 2: TLSv1.3, no pending NewSessionTicket messages
8825  * Test 3: TLSv1.3, pending NewSessionTicket messages
8826  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
8827  *                  sends key update, client reads it
8828  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
8829  *                  sends CertificateRequest, client reads and ignores it
8830  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
8831  *                  doesn't read it
8832  */
8833 static int test_shutdown(int tst)
8834 {
8835     SSL_CTX *cctx = NULL, *sctx = NULL;
8836     SSL *clientssl = NULL, *serverssl = NULL;
8837     int testresult = 0;
8838     char msg[] = "A test message";
8839     char buf[80];
8840     size_t written, readbytes;
8841     SSL_SESSION *sess;
8842 
8843 #ifdef OPENSSL_NO_TLS1_2
8844     if (tst <= 1)
8845         return 1;
8846 #endif
8847 #ifdef OSSL_NO_USABLE_TLS1_3
8848     if (tst >= 2)
8849         return 1;
8850 #endif
8851 
8852     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8853             TLS_client_method(),
8854             TLS1_VERSION,
8855             (tst <= 1) ? TLS1_2_VERSION
8856                        : TLS1_3_VERSION,
8857             &sctx, &cctx, cert, privkey)))
8858         goto end;
8859 
8860     if (tst == 5)
8861         SSL_CTX_set_post_handshake_auth(cctx, 1);
8862 
8863     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8864             NULL, NULL)))
8865         goto end;
8866 
8867     if (tst == 3) {
8868         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
8869                 SSL_ERROR_NONE, 1, 0))
8870             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8871             || !TEST_false(SSL_SESSION_is_resumable(sess)))
8872             goto end;
8873     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8874                    SSL_ERROR_NONE))
8875         || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8876         || !TEST_true(SSL_SESSION_is_resumable(sess))) {
8877         goto end;
8878     }
8879 
8880     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8881         goto end;
8882 
8883     if (tst >= 4) {
8884         /*
8885          * Reading on the server after the client has sent close_notify should
8886          * fail and provide SSL_ERROR_ZERO_RETURN
8887          */
8888         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
8889             || !TEST_int_eq(SSL_get_error(serverssl, 0),
8890                 SSL_ERROR_ZERO_RETURN)
8891             || !TEST_int_eq(SSL_get_shutdown(serverssl),
8892                 SSL_RECEIVED_SHUTDOWN)
8893             /*
8894              * Even though we're shutdown on receive we should still be
8895              * able to write.
8896              */
8897             || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8898             goto end;
8899         if (tst == 4
8900             && !TEST_true(SSL_key_update(serverssl,
8901                 SSL_KEY_UPDATE_REQUESTED)))
8902             goto end;
8903         if (tst == 5) {
8904             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
8905             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
8906                 goto end;
8907         }
8908         if ((tst == 4 || tst == 5)
8909             && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8910             goto end;
8911         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8912             goto end;
8913         if (tst == 4 || tst == 5) {
8914             /* Should still be able to read data from server */
8915             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8916                     &readbytes))
8917                 || !TEST_size_t_eq(readbytes, sizeof(msg))
8918                 || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
8919                 || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8920                     &readbytes))
8921                 || !TEST_size_t_eq(readbytes, sizeof(msg))
8922                 || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
8923                 goto end;
8924         }
8925     }
8926 
8927     /* Writing on the client after sending close_notify shouldn't be possible */
8928     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
8929         goto end;
8930 
8931     if (tst < 4) {
8932         /*
8933          * For these tests the client has sent close_notify but it has not yet
8934          * been received by the server. The server has not sent close_notify
8935          * yet.
8936          */
8937         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
8938             /*
8939              * Writing on the server after sending close_notify shouldn't
8940              * be possible.
8941              */
8942             || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8943             || !TEST_int_eq(SSL_shutdown(clientssl), 1)
8944             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8945             || !TEST_true(SSL_SESSION_is_resumable(sess))
8946             || !TEST_int_eq(SSL_shutdown(serverssl), 1))
8947             goto end;
8948     } else if (tst == 4 || tst == 5) {
8949         /*
8950          * In this test the client has sent close_notify and it has been
8951          * received by the server which has responded with a close_notify. The
8952          * client needs to read the close_notify sent by the server.
8953          */
8954         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
8955             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8956             || !TEST_true(SSL_SESSION_is_resumable(sess)))
8957             goto end;
8958     } else {
8959         /*
8960          * tst == 6
8961          *
8962          * The client has sent close_notify and is expecting a close_notify
8963          * back, but instead there is application data first. The shutdown
8964          * should fail with a fatal error.
8965          */
8966         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
8967             || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
8968             goto end;
8969     }
8970 
8971     testresult = 1;
8972 
8973 end:
8974     SSL_free(serverssl);
8975     SSL_free(clientssl);
8976     SSL_CTX_free(sctx);
8977     SSL_CTX_free(cctx);
8978 
8979     return testresult;
8980 }
8981 
8982 /*
8983  * Test that sending close_notify alerts works correctly in the case of a
8984  * retryable write failure.
8985  */
8986 static int test_async_shutdown(void)
8987 {
8988     SSL_CTX *cctx = NULL, *sctx = NULL;
8989     SSL *clientssl = NULL, *serverssl = NULL;
8990     int testresult = 0;
8991     BIO *bretry = BIO_new(bio_s_always_retry()), *tmp = NULL;
8992 
8993     if (!TEST_ptr(bretry))
8994         goto end;
8995 
8996     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8997             TLS_client_method(),
8998             0, 0,
8999             &sctx, &cctx, cert, privkey)))
9000         goto end;
9001 
9002     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9003             NULL)))
9004         goto end;
9005 
9006     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9007         goto end;
9008 
9009     /* Close write side of clientssl */
9010     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
9011         goto end;
9012 
9013     tmp = SSL_get_wbio(serverssl);
9014     if (!TEST_true(BIO_up_ref(tmp))) {
9015         tmp = NULL;
9016         goto end;
9017     }
9018     SSL_set0_wbio(serverssl, bretry);
9019     bretry = NULL;
9020 
9021     /* First server shutdown should fail because of a retrable write failure */
9022     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
9023         || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
9024         goto end;
9025 
9026     /* Second server shutdown should fail for the same reason */
9027     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
9028         || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
9029         goto end;
9030 
9031     SSL_set0_wbio(serverssl, tmp);
9032     tmp = NULL;
9033 
9034     /* Third server shutdown should send close_notify */
9035     if (!TEST_int_eq(SSL_shutdown(serverssl), 0))
9036         goto end;
9037 
9038     /* Fourth server shutdown should read close_notify from client and finish */
9039     if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
9040         goto end;
9041 
9042     /* Client should also successfully fully shutdown */
9043     if (!TEST_int_eq(SSL_shutdown(clientssl), 1))
9044         goto end;
9045 
9046     testresult = 1;
9047 end:
9048     SSL_free(serverssl);
9049     SSL_free(clientssl);
9050     SSL_CTX_free(sctx);
9051     SSL_CTX_free(cctx);
9052     BIO_free(bretry);
9053     BIO_free(tmp);
9054 
9055     return testresult;
9056 }
9057 
9058 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
9059 static int cert_cb_cnt;
9060 
9061 static int load_chain(const char *file, EVP_PKEY **pkey, X509 **x509,
9062     STACK_OF(X509) *chain)
9063 {
9064     char *path = test_mk_file_path(certsdir, file);
9065     BIO *in = NULL;
9066     X509 *x = NULL;
9067     int ok = 0;
9068 
9069     if (path == NULL)
9070         return 0;
9071     if ((in = BIO_new(BIO_s_file())) == NULL
9072         || BIO_read_filename(in, path) <= 0)
9073         goto out;
9074     if (pkey == NULL) {
9075         if ((x = X509_new_ex(libctx, NULL)) == NULL
9076             || PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
9077             goto out;
9078         if (chain == NULL)
9079             *x509 = x;
9080         else if (!sk_X509_push(chain, x))
9081             goto out;
9082     } else if (PEM_read_bio_PrivateKey_ex(in, pkey, NULL, NULL,
9083                    libctx, NULL)
9084         == NULL) {
9085         goto out;
9086     }
9087 
9088     x = NULL;
9089     ok = 1;
9090 out:
9091     X509_free(x);
9092     BIO_free(in);
9093     OPENSSL_free(path);
9094     return ok;
9095 }
9096 
9097 static int cert_cb(SSL *s, void *arg)
9098 {
9099     SSL_CTX *ctx = (SSL_CTX *)arg;
9100     EVP_PKEY *pkey = NULL;
9101     X509 *x509 = NULL, *x = NULL;
9102     STACK_OF(X509) *chain = NULL;
9103     int ret = 0;
9104 
9105     if (cert_cb_cnt == 0) {
9106         /* Suspend the handshake */
9107         cert_cb_cnt++;
9108         return -1;
9109     } else if (cert_cb_cnt == 1) {
9110         /*
9111          * Update the SSL_CTX, set the certificate and private key and then
9112          * continue the handshake normally.
9113          */
9114         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
9115             return 0;
9116 
9117         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
9118             || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
9119                 SSL_FILETYPE_PEM))
9120             || !TEST_true(SSL_check_private_key(s)))
9121             return 0;
9122         cert_cb_cnt++;
9123         return 1;
9124     } else if (cert_cb_cnt == 3) {
9125         int rv;
9126 
9127         chain = sk_X509_new_null();
9128         if (!TEST_ptr(chain)
9129             || !TEST_true(load_chain("ca-cert.pem", NULL, NULL, chain))
9130             || !TEST_true(load_chain("root-cert.pem", NULL, NULL, chain))
9131             || !TEST_true(load_chain("p256-ee-rsa-ca-cert.pem", NULL,
9132                 &x509, NULL))
9133             || !TEST_true(load_chain("p256-ee-rsa-ca-key.pem", &pkey,
9134                 NULL, NULL)))
9135             goto out;
9136         rv = SSL_check_chain(s, x509, pkey, chain);
9137         /*
9138          * If the cert doesn't show as valid here (e.g., because we don't
9139          * have any shared sigalgs), then we will not set it, and there will
9140          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
9141          * will cause tls_choose_sigalgs() to fail the connection.
9142          */
9143         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
9144             == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
9145             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
9146                 goto out;
9147         }
9148 
9149         ret = 1;
9150     }
9151 
9152     /* Abort the handshake */
9153 out:
9154     EVP_PKEY_free(pkey);
9155     X509_free(x509);
9156     X509_free(x);
9157     OSSL_STACK_OF_X509_free(chain);
9158     return ret;
9159 }
9160 
9161 /*
9162  * Test the certificate callback.
9163  * Test 0: Callback fails
9164  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
9165  * Test 2: Success - SSL_set_SSL_CTX() in the callback
9166  * Test 3: Success - Call SSL_check_chain from the callback
9167  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
9168  *                   chain
9169  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
9170  */
9171 static int test_cert_cb_int(int prot, int tst)
9172 {
9173     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
9174     SSL *clientssl = NULL, *serverssl = NULL;
9175     int testresult = 0, ret;
9176 
9177 #ifdef OPENSSL_NO_EC
9178     /* We use an EC cert in these tests, so we skip in a no-ec build */
9179     if (tst >= 3)
9180         return 1;
9181 #endif
9182 
9183     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9184             TLS_client_method(),
9185             prot,
9186             prot,
9187             &sctx, &cctx, NULL, NULL)))
9188         goto end;
9189 
9190     if (tst == 0)
9191         cert_cb_cnt = -1;
9192     else if (tst >= 3)
9193         cert_cb_cnt = 3;
9194     else
9195         cert_cb_cnt = 0;
9196 
9197     if (tst == 2) {
9198         snictx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9199         if (!TEST_ptr(snictx))
9200             goto end;
9201     }
9202 
9203     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
9204 
9205     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9206             NULL, NULL)))
9207         goto end;
9208 
9209     if (tst == 4) {
9210         /*
9211          * We cause SSL_check_chain() to fail by specifying sig_algs that
9212          * the chain doesn't meet (the root uses an RSA cert)
9213          */
9214         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
9215                 "ecdsa_secp256r1_sha256")))
9216             goto end;
9217     } else if (tst == 5) {
9218         /*
9219          * We cause SSL_check_chain() to fail by specifying sig_algs that
9220          * the ee cert doesn't meet (the ee uses an ECDSA cert)
9221          */
9222         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
9223                 "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
9224             goto end;
9225     }
9226 
9227     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
9228     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
9229         || (tst > 0
9230             && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
9231         goto end;
9232     }
9233 
9234     testresult = 1;
9235 
9236 end:
9237     SSL_free(serverssl);
9238     SSL_free(clientssl);
9239     SSL_CTX_free(sctx);
9240     SSL_CTX_free(cctx);
9241     SSL_CTX_free(snictx);
9242 
9243     return testresult;
9244 }
9245 #endif
9246 
9247 static int test_cert_cb(int tst)
9248 {
9249     int testresult = 1;
9250 
9251 #ifndef OPENSSL_NO_TLS1_2
9252     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
9253 #endif
9254 #ifndef OSSL_NO_USABLE_TLS1_3
9255     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
9256 #endif
9257 
9258     return testresult;
9259 }
9260 
9261 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
9262 {
9263     X509 *xcert;
9264     EVP_PKEY *privpkey;
9265     BIO *in = NULL;
9266     BIO *priv_in = NULL;
9267 
9268     /* Check that SSL_get0_peer_certificate() returns something sensible */
9269     if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
9270         return 0;
9271 
9272     in = BIO_new_file(cert, "r");
9273     if (!TEST_ptr(in))
9274         return 0;
9275 
9276     if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL))
9277         || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
9278         || !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
9279         || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
9280                          NULL, NULL,
9281                          libctx, NULL)))
9282         goto err;
9283 
9284     *x509 = xcert;
9285     *pkey = privpkey;
9286 
9287     BIO_free(in);
9288     BIO_free(priv_in);
9289     return 1;
9290 err:
9291     X509_free(xcert);
9292     BIO_free(in);
9293     BIO_free(priv_in);
9294     return 0;
9295 }
9296 
9297 static int test_client_cert_cb(int tst)
9298 {
9299     SSL_CTX *cctx = NULL, *sctx = NULL;
9300     SSL *clientssl = NULL, *serverssl = NULL;
9301     int testresult = 0;
9302 
9303 #ifdef OPENSSL_NO_TLS1_2
9304     if (tst == 0)
9305         return 1;
9306 #endif
9307 #ifdef OSSL_NO_USABLE_TLS1_3
9308     if (tst == 1)
9309         return 1;
9310 #endif
9311 
9312     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9313             TLS_client_method(),
9314             TLS1_VERSION,
9315             tst == 0 ? TLS1_2_VERSION
9316                      : TLS1_3_VERSION,
9317             &sctx, &cctx, cert, privkey)))
9318         goto end;
9319 
9320     /*
9321      * Test that setting a client_cert_cb results in a client certificate being
9322      * sent.
9323      */
9324     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
9325     SSL_CTX_set_verify(sctx,
9326         SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
9327         verify_cb);
9328 
9329     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9330             NULL, NULL))
9331         || !TEST_true(create_ssl_connection(serverssl, clientssl,
9332             SSL_ERROR_NONE)))
9333         goto end;
9334 
9335     testresult = 1;
9336 
9337 end:
9338     SSL_free(serverssl);
9339     SSL_free(clientssl);
9340     SSL_CTX_free(sctx);
9341     SSL_CTX_free(cctx);
9342 
9343     return testresult;
9344 }
9345 
9346 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
9347 /*
9348  * Test setting certificate authorities on both client and server.
9349  *
9350  * Test 0: SSL_CTX_set0_CA_list() only
9351  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
9352  * Test 2: Only SSL_CTX_set_client_CA_list()
9353  */
9354 static int test_ca_names_int(int prot, int tst)
9355 {
9356     SSL_CTX *cctx = NULL, *sctx = NULL;
9357     SSL *clientssl = NULL, *serverssl = NULL;
9358     int testresult = 0;
9359     size_t i;
9360     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
9361     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
9362     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
9363     const STACK_OF(X509_NAME) *sktmp = NULL;
9364 
9365     for (i = 0; i < OSSL_NELEM(name); i++) {
9366         name[i] = X509_NAME_new();
9367         if (!TEST_ptr(name[i])
9368             || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
9369                 MBSTRING_ASC,
9370                 (unsigned char *)
9371                     strnames[i],
9372                 -1, -1, 0)))
9373             goto end;
9374     }
9375 
9376     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9377             TLS_client_method(),
9378             TLS1_VERSION,
9379             prot,
9380             &sctx, &cctx, cert, privkey)))
9381         goto end;
9382 
9383     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
9384 
9385     if (tst == 0 || tst == 1) {
9386         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9387             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
9388             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
9389             || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9390             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
9391             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
9392             goto end;
9393 
9394         SSL_CTX_set0_CA_list(sctx, sk1);
9395         SSL_CTX_set0_CA_list(cctx, sk2);
9396         sk1 = sk2 = NULL;
9397     }
9398     if (tst == 1 || tst == 2) {
9399         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9400             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
9401             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
9402             || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9403             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
9404             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
9405             goto end;
9406 
9407         SSL_CTX_set_client_CA_list(sctx, sk1);
9408         SSL_CTX_set_client_CA_list(cctx, sk2);
9409         sk1 = sk2 = NULL;
9410     }
9411 
9412     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9413             NULL, NULL))
9414         || !TEST_true(create_ssl_connection(serverssl, clientssl,
9415             SSL_ERROR_NONE)))
9416         goto end;
9417 
9418     /*
9419      * We only expect certificate authorities to have been sent to the server
9420      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
9421      */
9422     sktmp = SSL_get0_peer_CA_list(serverssl);
9423     if (prot == TLS1_3_VERSION
9424         && (tst == 0 || tst == 1)) {
9425         if (!TEST_ptr(sktmp)
9426             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9427             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9428                                 name[0]),
9429                 0)
9430             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9431                                 name[1]),
9432                 0))
9433             goto end;
9434     } else if (!TEST_ptr_null(sktmp)) {
9435         goto end;
9436     }
9437 
9438     /*
9439      * In all tests we expect certificate authorities to have been sent to the
9440      * client. However, SSL_set_client_CA_list() should override
9441      * SSL_set0_CA_list()
9442      */
9443     sktmp = SSL_get0_peer_CA_list(clientssl);
9444     if (!TEST_ptr(sktmp)
9445         || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9446         || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9447                             name[tst == 0 ? 0 : 2]),
9448             0)
9449         || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9450                             name[tst == 0 ? 1 : 3]),
9451             0))
9452         goto end;
9453 
9454     testresult = 1;
9455 
9456 end:
9457     SSL_free(serverssl);
9458     SSL_free(clientssl);
9459     SSL_CTX_free(sctx);
9460     SSL_CTX_free(cctx);
9461     for (i = 0; i < OSSL_NELEM(name); i++)
9462         X509_NAME_free(name[i]);
9463     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
9464     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
9465 
9466     return testresult;
9467 }
9468 #endif
9469 
9470 static int test_ca_names(int tst)
9471 {
9472     int testresult = 1;
9473 
9474 #ifndef OPENSSL_NO_TLS1_2
9475     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
9476 #endif
9477 #ifndef OSSL_NO_USABLE_TLS1_3
9478     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
9479 #endif
9480 
9481     return testresult;
9482 }
9483 
9484 #ifndef OPENSSL_NO_TLS1_2
9485 static const char *multiblock_cipherlist_data[] = {
9486     "AES128-SHA",
9487     "AES128-SHA256",
9488     "AES256-SHA",
9489     "AES256-SHA256",
9490 };
9491 
9492 /* Reduce the fragment size - so the multiblock test buffer can be small */
9493 #define MULTIBLOCK_FRAGSIZE 512
9494 
9495 static int test_multiblock_write(int test_index)
9496 {
9497     static const char *fetchable_ciphers[] = {
9498         "AES-128-CBC-HMAC-SHA1",
9499         "AES-128-CBC-HMAC-SHA256",
9500         "AES-256-CBC-HMAC-SHA1",
9501         "AES-256-CBC-HMAC-SHA256"
9502     };
9503     const char *cipherlist = multiblock_cipherlist_data[test_index];
9504     const SSL_METHOD *smeth = TLS_server_method();
9505     const SSL_METHOD *cmeth = TLS_client_method();
9506     int min_version = TLS1_VERSION;
9507     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
9508     SSL_CTX *cctx = NULL, *sctx = NULL;
9509     SSL *clientssl = NULL, *serverssl = NULL;
9510     int testresult = 0;
9511 
9512     /*
9513      * Choose a buffer large enough to perform a multi-block operation
9514      * i.e: write_len >= 4 * frag_size
9515      * 9 * is chosen so that multiple multiblocks are used + some leftover.
9516      */
9517     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
9518     unsigned char buf[sizeof(msg)], *p = buf;
9519     size_t readbytes, written, len;
9520     EVP_CIPHER *ciph = NULL;
9521 
9522     /*
9523      * Check if the cipher exists before attempting to use it since it only has
9524      * a hardware specific implementation.
9525      */
9526     ciph = EVP_CIPHER_fetch(libctx, fetchable_ciphers[test_index], "");
9527     if (ciph == NULL) {
9528         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
9529         return 1;
9530     }
9531     EVP_CIPHER_free(ciph);
9532 
9533     /* Set up a buffer with some data that will be sent to the client */
9534     RAND_bytes(msg, sizeof(msg));
9535 
9536     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
9537             max_version, &sctx, &cctx, cert,
9538             privkey)))
9539         goto end;
9540 
9541     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
9542         goto end;
9543 
9544     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9545             NULL, NULL)))
9546         goto end;
9547 
9548     /* settings to force it to use AES-CBC-HMAC_SHA */
9549     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
9550     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
9551         goto end;
9552 
9553     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9554         goto end;
9555 
9556     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
9557         || !TEST_size_t_eq(written, sizeof(msg)))
9558         goto end;
9559 
9560     len = written;
9561     while (len > 0) {
9562         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
9563             goto end;
9564         p += readbytes;
9565         len -= readbytes;
9566     }
9567     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
9568         goto end;
9569 
9570     testresult = 1;
9571 end:
9572     SSL_free(serverssl);
9573     SSL_free(clientssl);
9574     SSL_CTX_free(sctx);
9575     SSL_CTX_free(cctx);
9576 
9577     return testresult;
9578 }
9579 #endif /* OPENSSL_NO_TLS1_2 */
9580 
9581 static int test_session_timeout(int test)
9582 {
9583     /*
9584      * Test session ordering and timeout
9585      * Can't explicitly test performance of the new code,
9586      * but can test to see if the ordering of the sessions
9587      * are correct, and they are removed as expected
9588      */
9589     SSL_SESSION *early = NULL;
9590     SSL_SESSION *middle = NULL;
9591     SSL_SESSION *late = NULL;
9592     SSL_CTX *ctx;
9593     int testresult = 0;
9594     time_t now = time(NULL);
9595 #define TIMEOUT 10
9596 
9597     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
9598         || !TEST_ptr(early = SSL_SESSION_new())
9599         || !TEST_ptr(middle = SSL_SESSION_new())
9600         || !TEST_ptr(late = SSL_SESSION_new()))
9601         goto end;
9602 
9603     /* assign unique session ids */
9604     early->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9605     memset(early->session_id, 1, SSL3_SSL_SESSION_ID_LENGTH);
9606     middle->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9607     memset(middle->session_id, 2, SSL3_SSL_SESSION_ID_LENGTH);
9608     late->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9609     memset(late->session_id, 3, SSL3_SSL_SESSION_ID_LENGTH);
9610 
9611     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9612         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9613         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9614         goto end;
9615 
9616     /* Make sure they are all added */
9617     if (!TEST_ptr(early->prev)
9618         || !TEST_ptr(middle->prev)
9619         || !TEST_ptr(late->prev))
9620         goto end;
9621 
9622     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now - 10), 0)
9623         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(middle, now), 0)
9624         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(late, now + 10), 0))
9625         goto end;
9626 
9627     if (!TEST_int_ne(SSL_SESSION_set_timeout(early, TIMEOUT), 0)
9628         || !TEST_int_ne(SSL_SESSION_set_timeout(middle, TIMEOUT), 0)
9629         || !TEST_int_ne(SSL_SESSION_set_timeout(late, TIMEOUT), 0))
9630         goto end;
9631 
9632     /* Make sure they are all still there */
9633     if (!TEST_ptr(early->prev)
9634         || !TEST_ptr(middle->prev)
9635         || !TEST_ptr(late->prev))
9636         goto end;
9637 
9638     /* Make sure they are in the expected order */
9639     if (!TEST_ptr_eq(late->next, middle)
9640         || !TEST_ptr_eq(middle->next, early)
9641         || !TEST_ptr_eq(early->prev, middle)
9642         || !TEST_ptr_eq(middle->prev, late))
9643         goto end;
9644 
9645     /* This should remove "early" */
9646     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT - 1);
9647     if (!TEST_ptr_null(early->prev)
9648         || !TEST_ptr(middle->prev)
9649         || !TEST_ptr(late->prev))
9650         goto end;
9651 
9652     /* This should remove "middle" */
9653     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 1);
9654     if (!TEST_ptr_null(early->prev)
9655         || !TEST_ptr_null(middle->prev)
9656         || !TEST_ptr(late->prev))
9657         goto end;
9658 
9659     /* This should remove "late" */
9660     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 11);
9661     if (!TEST_ptr_null(early->prev)
9662         || !TEST_ptr_null(middle->prev)
9663         || !TEST_ptr_null(late->prev))
9664         goto end;
9665 
9666     /* Add them back in again */
9667     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9668         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9669         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9670         goto end;
9671 
9672     /* Make sure they are all added */
9673     if (!TEST_ptr(early->prev)
9674         || !TEST_ptr(middle->prev)
9675         || !TEST_ptr(late->prev))
9676         goto end;
9677 
9678     /* This should remove all of them */
9679     SSL_CTX_flush_sessions_ex(ctx, 0);
9680     if (!TEST_ptr_null(early->prev)
9681         || !TEST_ptr_null(middle->prev)
9682         || !TEST_ptr_null(late->prev))
9683         goto end;
9684 
9685     (void)SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_UPDATE_TIME | SSL_CTX_get_session_cache_mode(ctx));
9686 
9687     /* make sure |now| is NOT  equal to the current time */
9688     now -= 10;
9689     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now), 0)
9690         || !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9691         || !TEST_time_t_ne(SSL_SESSION_get_time_ex(early), now))
9692         goto end;
9693 
9694     testresult = 1;
9695 end:
9696     SSL_CTX_free(ctx);
9697     SSL_SESSION_free(early);
9698     SSL_SESSION_free(middle);
9699     SSL_SESSION_free(late);
9700     return testresult;
9701 }
9702 
9703 /*
9704  * Test that a session cache overflow works as expected
9705  * Test 0: TLSv1.3, timeout on new session later than old session
9706  * Test 1: TLSv1.2, timeout on new session later than old session
9707  * Test 2: TLSv1.3, timeout on new session earlier than old session
9708  * Test 3: TLSv1.2, timeout on new session earlier than old session
9709  */
9710 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
9711 static int test_session_cache_overflow(int idx)
9712 {
9713     SSL_CTX *sctx = NULL, *cctx = NULL;
9714     SSL *serverssl = NULL, *clientssl = NULL;
9715     int testresult = 0;
9716     SSL_SESSION *sess = NULL;
9717 
9718 #ifdef OSSL_NO_USABLE_TLS1_3
9719     /* If no TLSv1.3 available then do nothing in this case */
9720     if (idx % 2 == 0)
9721         return TEST_skip("No TLSv1.3 available");
9722 #endif
9723 #ifdef OPENSSL_NO_TLS1_2
9724     /* If no TLSv1.2 available then do nothing in this case */
9725     if (idx % 2 == 1)
9726         return TEST_skip("No TLSv1.2 available");
9727 #endif
9728 
9729     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9730             TLS_client_method(), TLS1_VERSION,
9731             (idx % 2 == 0) ? TLS1_3_VERSION
9732                            : TLS1_2_VERSION,
9733             &sctx, &cctx, cert, privkey))
9734         || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET)))
9735         goto end;
9736 
9737     SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
9738     get_sess_val = NULL;
9739 
9740     SSL_CTX_sess_set_cache_size(sctx, 1);
9741 
9742     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9743             NULL, NULL)))
9744         goto end;
9745 
9746     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9747         goto end;
9748 
9749     if (idx > 1) {
9750         sess = SSL_get_session(serverssl);
9751         if (!TEST_ptr(sess))
9752             goto end;
9753 
9754         /*
9755          * Cause this session to have a longer timeout than the next session to
9756          * be added.
9757          */
9758         if (!TEST_true(SSL_SESSION_set_timeout(sess, LONG_MAX))) {
9759             sess = NULL;
9760             goto end;
9761         }
9762         sess = NULL;
9763     }
9764 
9765     SSL_shutdown(serverssl);
9766     SSL_shutdown(clientssl);
9767     SSL_free(serverssl);
9768     SSL_free(clientssl);
9769     serverssl = clientssl = NULL;
9770 
9771     /*
9772      * Session cache size is 1 and we already populated the cache with a session
9773      * so the next connection should cause an overflow.
9774      */
9775 
9776     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9777             NULL, NULL)))
9778         goto end;
9779 
9780     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9781         goto end;
9782 
9783     /*
9784      * The session we just negotiated may have been already removed from the
9785      * internal cache - but we will return it anyway from our external cache.
9786      */
9787     get_sess_val = SSL_get_session(serverssl);
9788     if (!TEST_ptr(get_sess_val))
9789         goto end;
9790     sess = SSL_get1_session(clientssl);
9791     if (!TEST_ptr(sess))
9792         goto end;
9793 
9794     SSL_shutdown(serverssl);
9795     SSL_shutdown(clientssl);
9796     SSL_free(serverssl);
9797     SSL_free(clientssl);
9798     serverssl = clientssl = NULL;
9799 
9800     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9801             NULL, NULL)))
9802         goto end;
9803 
9804     if (!TEST_true(SSL_set_session(clientssl, sess)))
9805         goto end;
9806 
9807     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9808         goto end;
9809 
9810     testresult = 1;
9811 
9812 end:
9813     SSL_free(serverssl);
9814     SSL_free(clientssl);
9815     SSL_CTX_free(sctx);
9816     SSL_CTX_free(cctx);
9817     SSL_SESSION_free(sess);
9818 
9819     return testresult;
9820 }
9821 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
9822 
9823 /*
9824  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
9825  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
9826  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
9827  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
9828  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
9829  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
9830  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
9831  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
9832  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
9833  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
9834  */
9835 static int test_servername(int tst)
9836 {
9837     SSL_CTX *cctx = NULL, *sctx = NULL;
9838     SSL *clientssl = NULL, *serverssl = NULL;
9839     int testresult = 0;
9840     SSL_SESSION *sess = NULL;
9841     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
9842 
9843 #ifdef OPENSSL_NO_TLS1_2
9844     if (tst <= 4)
9845         return 1;
9846 #endif
9847 #ifdef OSSL_NO_USABLE_TLS1_3
9848     if (tst >= 5)
9849         return 1;
9850 #endif
9851 
9852     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9853             TLS_client_method(),
9854             TLS1_VERSION,
9855             (tst <= 4) ? TLS1_2_VERSION
9856                        : TLS1_3_VERSION,
9857             &sctx, &cctx, cert, privkey))
9858         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9859             NULL, NULL)))
9860         goto end;
9861 
9862     if (tst != 1 && tst != 6) {
9863         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
9864                 hostname_cb)))
9865             goto end;
9866     }
9867 
9868     if (tst != 3 && tst != 8) {
9869         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9870             goto end;
9871         sexpectedhost = cexpectedhost = "goodhost";
9872     }
9873 
9874     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9875         goto end;
9876 
9877     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
9878             cexpectedhost)
9879         || !TEST_str_eq(SSL_get_servername(serverssl,
9880                             TLSEXT_NAMETYPE_host_name),
9881             sexpectedhost))
9882         goto end;
9883 
9884     /* Now repeat with a resumption handshake */
9885 
9886     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
9887         || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
9888         || !TEST_true(SSL_SESSION_is_resumable(sess))
9889         || !TEST_int_eq(SSL_shutdown(serverssl), 0))
9890         goto end;
9891 
9892     SSL_free(clientssl);
9893     SSL_free(serverssl);
9894     clientssl = serverssl = NULL;
9895 
9896     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9897             NULL)))
9898         goto end;
9899 
9900     if (!TEST_true(SSL_set_session(clientssl, sess)))
9901         goto end;
9902 
9903     sexpectedhost = cexpectedhost = "goodhost";
9904     if (tst == 2 || tst == 7) {
9905         /* Set an inconsistent hostname */
9906         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
9907             goto end;
9908         /*
9909          * In TLSv1.2 we expect the hostname from the original handshake, in
9910          * TLSv1.3 we expect the hostname from this handshake
9911          */
9912         if (tst == 7)
9913             sexpectedhost = cexpectedhost = "altgoodhost";
9914 
9915         if (!TEST_str_eq(SSL_get_servername(clientssl,
9916                              TLSEXT_NAMETYPE_host_name),
9917                 "altgoodhost"))
9918             goto end;
9919     } else if (tst == 4 || tst == 9) {
9920         /*
9921          * A TLSv1.3 session does not associate a session with a servername,
9922          * but a TLSv1.2 session does.
9923          */
9924         if (tst == 9)
9925             sexpectedhost = cexpectedhost = NULL;
9926 
9927         if (!TEST_str_eq(SSL_get_servername(clientssl,
9928                              TLSEXT_NAMETYPE_host_name),
9929                 cexpectedhost))
9930             goto end;
9931     } else {
9932         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9933             goto end;
9934         /*
9935          * In a TLSv1.2 resumption where the hostname was not acknowledged
9936          * we expect the hostname on the server to be empty. On the client we
9937          * return what was requested in this case.
9938          *
9939          * Similarly if the client didn't set a hostname on an original TLSv1.2
9940          * session but is now, the server hostname will be empty, but the client
9941          * is as we set it.
9942          */
9943         if (tst == 1 || tst == 3)
9944             sexpectedhost = NULL;
9945 
9946         if (!TEST_str_eq(SSL_get_servername(clientssl,
9947                              TLSEXT_NAMETYPE_host_name),
9948                 "goodhost"))
9949             goto end;
9950     }
9951 
9952     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9953         goto end;
9954 
9955     if (!TEST_true(SSL_session_reused(clientssl))
9956         || !TEST_true(SSL_session_reused(serverssl))
9957         || !TEST_str_eq(SSL_get_servername(clientssl,
9958                             TLSEXT_NAMETYPE_host_name),
9959             cexpectedhost)
9960         || !TEST_str_eq(SSL_get_servername(serverssl,
9961                             TLSEXT_NAMETYPE_host_name),
9962             sexpectedhost))
9963         goto end;
9964 
9965     testresult = 1;
9966 
9967 end:
9968     SSL_SESSION_free(sess);
9969     SSL_free(serverssl);
9970     SSL_free(clientssl);
9971     SSL_CTX_free(sctx);
9972     SSL_CTX_free(cctx);
9973 
9974     return testresult;
9975 }
9976 
9977 static int test_unknown_sigalgs_groups(void)
9978 {
9979     int ret = 0;
9980     SSL_CTX *ctx = NULL;
9981 
9982     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
9983         goto end;
9984 
9985     if (!TEST_int_gt(SSL_CTX_set1_sigalgs_list(ctx,
9986                          "RSA+SHA256:?nonexistent:?RSA+SHA512"),
9987             0))
9988         goto end;
9989     if (!TEST_size_t_eq(ctx->cert->conf_sigalgslen, 2)
9990         || !TEST_int_eq(ctx->cert->conf_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
9991         || !TEST_int_eq(ctx->cert->conf_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
9992         goto end;
9993 
9994     if (!TEST_int_gt(SSL_CTX_set1_client_sigalgs_list(ctx,
9995                          "RSA+SHA256:?nonexistent:?RSA+SHA512"),
9996             0))
9997         goto end;
9998     if (!TEST_size_t_eq(ctx->cert->client_sigalgslen, 2)
9999         || !TEST_int_eq(ctx->cert->client_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
10000         || !TEST_int_eq(ctx->cert->client_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
10001         goto end;
10002 
10003     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
10004                          "nonexistent"),
10005             0))
10006         goto end;
10007 
10008     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx,
10009                          "?nonexistent1:?nonexistent2:?nonexistent3"),
10010             0))
10011         goto end;
10012 
10013 #ifndef OPENSSL_NO_EC
10014     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
10015                          "P-256:nonexistent"),
10016             0))
10017         goto end;
10018 
10019     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx,
10020                          "P-384:?nonexistent:?P-521"),
10021             0))
10022         goto end;
10023     if (!TEST_size_t_eq(ctx->ext.supportedgroups_len, 2)
10024         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp384r1)
10025         || !TEST_int_eq(ctx->ext.supportedgroups[1], OSSL_TLS_GROUP_ID_secp521r1))
10026         goto end;
10027 #endif
10028 
10029     ret = 1;
10030 end:
10031     SSL_CTX_free(ctx);
10032     return ret;
10033 }
10034 
10035 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM)
10036 static int test_configuration_of_groups(void)
10037 {
10038     int ret = 0;
10039     SSL_CTX *ctx = NULL;
10040     size_t groups_len;
10041 
10042     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
10043         goto end;
10044     groups_len = ctx->ext.supportedgroups_len;
10045 
10046     if (!TEST_size_t_gt(groups_len, 0)
10047         || !TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT"), 0)
10048         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len))
10049         goto end;
10050 
10051     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT:-?P-256"), 0)
10052 #if !defined(OPENSSL_NO_EC)
10053         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len - 1)
10054 #else
10055         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len)
10056 #endif
10057     )
10058         goto end;
10059 
10060 #if !defined(OPENSSL_NO_EC)
10061     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "?P-256:?P-521:-?P-256"), 0)
10062         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, 1)
10063         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp521r1))
10064         goto end;
10065 #endif
10066 
10067     ret = 1;
10068 
10069 end:
10070     SSL_CTX_free(ctx);
10071     return ret;
10072 }
10073 #endif
10074 
10075 #if !defined(OPENSSL_NO_EC) \
10076     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
10077 /*
10078  * Test that if signature algorithms are not available, then we do not offer or
10079  * accept them.
10080  * Test 0: Two RSA sig algs available: both RSA sig algs shared
10081  * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared
10082  * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared
10083  * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared
10084  * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared
10085  * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared
10086  */
10087 static int test_sigalgs_available(int idx)
10088 {
10089     SSL_CTX *cctx = NULL, *sctx = NULL;
10090     SSL *clientssl = NULL, *serverssl = NULL;
10091     int testresult = 0;
10092     OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
10093     OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx;
10094     OSSL_PROVIDER *filterprov = NULL;
10095     int sig, hash, numshared, numshared_expected, hash_expected, sig_expected;
10096     const char *sigalg_name, *signame_expected;
10097 
10098     if (!TEST_ptr(tmpctx))
10099         goto end;
10100 
10101     if (idx != 0 && idx != 3) {
10102         if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter",
10103                 filter_provider_init)))
10104             goto end;
10105 
10106         filterprov = OSSL_PROVIDER_load(tmpctx, "filter");
10107         if (!TEST_ptr(filterprov))
10108             goto end;
10109 
10110         if (idx < 3) {
10111             /*
10112              * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered
10113              * or accepted for the peer that uses this libctx. Note that libssl
10114              * *requires* SHA2-256 to be available so we cannot disable that. We
10115              * also need SHA1 for our certificate.
10116              */
10117             if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST,
10118                     "SHA2-256:SHA1")))
10119                 goto end;
10120         } else {
10121             if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE,
10122                     "ECDSA"))
10123 #ifdef OPENSSL_NO_ECX
10124                 || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT, "EC"))
10125 #else
10126                 || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
10127                     "EC:X25519:X448"))
10128 #endif
10129             )
10130                 goto end;
10131         }
10132 
10133         if (idx == 1 || idx == 4)
10134             clientctx = tmpctx;
10135         else
10136             serverctx = tmpctx;
10137     }
10138 
10139     cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method());
10140     sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method());
10141     if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
10142         goto end;
10143 
10144     /* Avoid MLKEM groups that depend on possibly filtered-out digests */
10145     if (!TEST_true(SSL_CTX_set1_groups_list(cctx,
10146             "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072"))
10147         || !TEST_true(SSL_CTX_set1_groups_list(sctx,
10148             "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072")))
10149         goto end;
10150 
10151     if (idx != 5) {
10152         /* RSA first server key */
10153         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10154                 TLS_client_method(),
10155                 TLS1_VERSION,
10156                 0,
10157                 &sctx, &cctx, cert, privkey)))
10158             goto end;
10159     } else {
10160         /* ECDSA P-256 first server key */
10161         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10162                 TLS_client_method(),
10163                 TLS1_VERSION,
10164                 0,
10165                 &sctx, &cctx, cert2, privkey2)))
10166             goto end;
10167     }
10168 
10169     /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */
10170     if (idx < 4) {
10171         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
10172                 "ECDHE-RSA-AES128-GCM-SHA256")))
10173             goto end;
10174     } else {
10175         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
10176                 "ECDHE-ECDSA-AES128-GCM-SHA256")))
10177             goto end;
10178     }
10179 
10180     if (idx < 3) {
10181         if (!SSL_CTX_set1_sigalgs_list(cctx,
10182                 "rsa_pss_rsae_sha384"
10183                 ":rsa_pss_rsae_sha256")
10184             || !SSL_CTX_set1_sigalgs_list(sctx,
10185                 "rsa_pss_rsae_sha384"
10186                 ":rsa_pss_rsae_sha256"))
10187             goto end;
10188     } else {
10189         if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")
10190             || !SSL_CTX_set1_sigalgs_list(sctx,
10191                 "rsa_pss_rsae_sha256:ECDSA+SHA256"))
10192             goto end;
10193     }
10194 
10195     /* ECDSA P-256 second server key, unless already first */
10196     if (idx != 5
10197         && (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2,
10198                              SSL_FILETYPE_PEM),
10199                 1)
10200             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
10201                                 privkey2,
10202                                 SSL_FILETYPE_PEM),
10203                 1)
10204             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)))
10205         goto end;
10206 
10207     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10208             NULL, NULL)))
10209         goto end;
10210 
10211     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10212         goto end;
10213 
10214     /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */
10215     numshared = SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash,
10216         NULL, NULL, NULL);
10217     numshared_expected = 1;
10218     hash_expected = NID_sha256;
10219     sig_expected = NID_rsassaPss;
10220     signame_expected = "rsa_pss_rsae_sha256";
10221     switch (idx) {
10222     case 0:
10223         hash_expected = NID_sha384;
10224         signame_expected = "rsa_pss_rsae_sha384";
10225         /* FALLTHROUGH */
10226     case 3:
10227         numshared_expected = 2;
10228         break;
10229     case 4:
10230     case 5:
10231         sig_expected = EVP_PKEY_EC;
10232         signame_expected = "ecdsa_secp256r1_sha256";
10233         break;
10234     }
10235     if (!TEST_int_eq(numshared, numshared_expected)
10236         || !TEST_int_eq(hash, hash_expected)
10237         || !TEST_int_eq(sig, sig_expected)
10238         || !TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name))
10239         || !TEST_ptr(sigalg_name)
10240         || !TEST_str_eq(sigalg_name, signame_expected))
10241         goto end;
10242 
10243     testresult = filter_provider_check_clean_finish();
10244 
10245 end:
10246     SSL_free(serverssl);
10247     SSL_free(clientssl);
10248     SSL_CTX_free(sctx);
10249     SSL_CTX_free(cctx);
10250     OSSL_PROVIDER_unload(filterprov);
10251     OSSL_LIB_CTX_free(tmpctx);
10252 
10253     return testresult;
10254 }
10255 #endif /*                                                                     \
10256         * !defined(OPENSSL_NO_EC)                                             \
10257         * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)) \
10258         */
10259 
10260 #ifndef OPENSSL_NO_TLS1_3
10261 /* This test can run in TLSv1.3 even if ec and dh are disabled */
10262 static int test_pluggable_group(int idx)
10263 {
10264     SSL_CTX *cctx = NULL, *sctx = NULL;
10265     SSL *clientssl = NULL, *serverssl = NULL;
10266     int testresult = 0;
10267     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
10268     /* Check that we are not impacted by a provider without any groups */
10269     OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy");
10270     const char *group_name = idx == 0 ? "xorkemgroup" : "xorgroup";
10271 
10272     if (!TEST_ptr(tlsprov))
10273         goto end;
10274 
10275     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10276             TLS_client_method(),
10277             TLS1_3_VERSION,
10278             TLS1_3_VERSION,
10279             &sctx, &cctx, cert, privkey))
10280         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10281             NULL, NULL)))
10282         goto end;
10283 
10284     /* ensure GROUPLIST_INCREMENT (=40) logic triggers: */
10285     if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup:xorkemgroup:dummy1:dummy2:dummy3:dummy4:dummy5:dummy6:dummy7:dummy8:dummy9:dummy10:dummy11:dummy12:dummy13:dummy14:dummy15:dummy16:dummy17:dummy18:dummy19:dummy20:dummy21:dummy22:dummy23:dummy24:dummy25:dummy26:dummy27:dummy28:dummy29:dummy30:dummy31:dummy32:dummy33:dummy34:dummy35:dummy36:dummy37:dummy38:dummy39:dummy40:dummy41:dummy42:dummy43"))
10286         /* removing a single algorithm from the list makes the test pass */
10287         || !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
10288         goto end;
10289 
10290     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10291         goto end;
10292 
10293     if (!TEST_str_eq(group_name,
10294             SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
10295         goto end;
10296 
10297     if (!TEST_str_eq(group_name, SSL_get0_group_name(serverssl))
10298         || !TEST_str_eq(group_name, SSL_get0_group_name(clientssl)))
10299         goto end;
10300 
10301     testresult = 1;
10302 
10303 end:
10304     SSL_free(serverssl);
10305     SSL_free(clientssl);
10306     SSL_CTX_free(sctx);
10307     SSL_CTX_free(cctx);
10308     OSSL_PROVIDER_unload(tlsprov);
10309     OSSL_PROVIDER_unload(legacyprov);
10310 
10311     return testresult;
10312 }
10313 
10314 /*
10315  * This function triggers encode, decode and sign functions
10316  * of the artificial "xorhmacsig" algorithm implemented in tls-provider
10317  * creating private key and certificate files for use in TLS testing.
10318  */
10319 static int create_cert_key(int idx, char *certfilename, char *privkeyfilename)
10320 {
10321     EVP_PKEY_CTX *evpctx = EVP_PKEY_CTX_new_from_name(libctx,
10322         (idx == 0) ? "xorhmacsig" : "xorhmacsha2sig", NULL);
10323     EVP_PKEY *pkey = NULL;
10324     X509 *x509 = X509_new();
10325     X509_NAME *name = NULL;
10326     BIO *keybio = NULL, *certbio = NULL;
10327     int ret = 1;
10328 
10329     if (!TEST_ptr(evpctx)
10330         || !TEST_int_gt(EVP_PKEY_keygen_init(evpctx), 0)
10331         || !TEST_true(EVP_PKEY_generate(evpctx, &pkey))
10332         || !TEST_ptr(pkey)
10333         || !TEST_ptr(x509)
10334         || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(x509), 1))
10335         || !TEST_true(X509_gmtime_adj(X509_getm_notBefore(x509), 0))
10336         || !TEST_true(X509_gmtime_adj(X509_getm_notAfter(x509), 31536000L))
10337         || !TEST_true(X509_set_pubkey(x509, pkey))
10338         || !TEST_ptr(name = X509_get_subject_name(x509))
10339         || !TEST_true(X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
10340             (unsigned char *)"CH", -1, -1, 0))
10341         || !TEST_true(X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
10342             (unsigned char *)"test.org", -1, -1, 0))
10343         || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
10344             (unsigned char *)"localhost", -1, -1, 0))
10345         || !TEST_true(X509_set_issuer_name(x509, name))
10346         || !TEST_true(X509_sign(x509, pkey, EVP_sha1()))
10347         || !TEST_ptr(keybio = BIO_new_file(privkeyfilename, "wb"))
10348         || !TEST_true(PEM_write_bio_PrivateKey(keybio, pkey, NULL, NULL, 0, NULL, NULL))
10349         || !TEST_ptr(certbio = BIO_new_file(certfilename, "wb"))
10350         || !TEST_true(PEM_write_bio_X509(certbio, x509)))
10351         ret = 0;
10352 
10353     EVP_PKEY_free(pkey);
10354     X509_free(x509);
10355     EVP_PKEY_CTX_free(evpctx);
10356     BIO_free(keybio);
10357     BIO_free(certbio);
10358     return ret;
10359 }
10360 
10361 /*
10362  * Test that signature algorithms loaded via the provider interface can
10363  * correctly establish a TLS (1.3) connection.
10364  * Test 0: Signature algorithm with built-in hashing functionality: "xorhmacsig"
10365  * Test 1: Signature algorithm using external SHA2 hashing: "xorhmacsha2sig"
10366  * Test 2: Signature algorithm with built-in hashing configured via SSL_CONF_cmd
10367  * Test 3: Test 0 using RPK
10368  * Test 4: Test 1 using RPK
10369  * Test 5: Test 2 using RPK
10370  */
10371 static int test_pluggable_signature(int idx)
10372 {
10373     static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
10374     SSL_CTX *cctx = NULL, *sctx = NULL;
10375     SSL *clientssl = NULL, *serverssl = NULL;
10376     int testresult = 0;
10377     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
10378     OSSL_PROVIDER *defaultprov = OSSL_PROVIDER_load(libctx, "default");
10379     char *certfilename = "tls-prov-cert.pem";
10380     char *privkeyfilename = "tls-prov-key.pem";
10381     const char *sigalg_name = NULL, *expected_sigalg_name;
10382     int sigidx = idx % 3;
10383     int rpkidx = idx / 3;
10384     int do_conf_cmd = 0;
10385 
10386     if (sigidx == 2) {
10387         sigidx = 0;
10388         do_conf_cmd = 1;
10389     }
10390 
10391     /* See create_cert_key() above */
10392     expected_sigalg_name = (sigidx == 0) ? "xorhmacsig" : "xorhmacsha2sig";
10393 
10394     /* create key and certificate for the different algorithm types */
10395     if (!TEST_ptr(tlsprov)
10396         || !TEST_true(create_cert_key(sigidx, certfilename, privkeyfilename)))
10397         goto end;
10398 
10399     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10400             TLS_client_method(),
10401             TLS1_3_VERSION,
10402             TLS1_3_VERSION,
10403             &sctx, &cctx, NULL, NULL)))
10404         goto end;
10405 
10406     if (do_conf_cmd) {
10407         SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
10408 
10409         if (!TEST_ptr(confctx))
10410             goto end;
10411         SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CERTIFICATE | SSL_CONF_FLAG_REQUIRE_PRIVATE | SSL_CONF_FLAG_SHOW_ERRORS);
10412         SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
10413         if (!TEST_int_gt(SSL_CONF_cmd(confctx, "Certificate", certfilename), 0)
10414             || !TEST_int_gt(SSL_CONF_cmd(confctx, "PrivateKey", privkeyfilename), 0)
10415             || !TEST_true(SSL_CONF_CTX_finish(confctx))) {
10416             SSL_CONF_CTX_free(confctx);
10417             goto end;
10418         }
10419         SSL_CONF_CTX_free(confctx);
10420     } else {
10421         if (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, certfilename,
10422                              SSL_FILETYPE_PEM),
10423                 1)
10424             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
10425                                 privkeyfilename,
10426                                 SSL_FILETYPE_PEM),
10427                 1))
10428             goto end;
10429     }
10430     if (!TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
10431         goto end;
10432 
10433     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10434             NULL, NULL)))
10435         goto end;
10436 
10437     /* Enable RPK for server cert */
10438     if (rpkidx) {
10439         if (!TEST_true(SSL_set1_server_cert_type(serverssl, cert_type_rpk, sizeof(cert_type_rpk)))
10440             || !TEST_true(SSL_set1_server_cert_type(clientssl, cert_type_rpk, sizeof(cert_type_rpk))))
10441             goto end;
10442     }
10443 
10444     /* This is necessary to pass minimal setup w/o other groups configured */
10445     if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup"))
10446         || !TEST_true(SSL_set1_groups_list(clientssl, "xorgroup")))
10447         goto end;
10448 
10449     /*
10450      * If this connection gets established, it must have been completed
10451      * via the tls-provider-implemented "hmacsig" algorithm, testing
10452      * both sign and verify functions during handshake.
10453      */
10454     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10455         goto end;
10456 
10457     /* If using RPK, make sure we got one */
10458     if (rpkidx && !TEST_long_eq(SSL_get_verify_result(clientssl), X509_V_ERR_RPK_UNTRUSTED))
10459         goto end;
10460 
10461     if (!TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name))
10462         || !TEST_str_eq(sigalg_name, expected_sigalg_name)
10463         || !TEST_ptr(sigalg_name))
10464         goto end;
10465 
10466     testresult = 1;
10467 
10468 end:
10469     SSL_free(serverssl);
10470     SSL_free(clientssl);
10471     SSL_CTX_free(sctx);
10472     SSL_CTX_free(cctx);
10473     OSSL_PROVIDER_unload(tlsprov);
10474     OSSL_PROVIDER_unload(defaultprov);
10475 
10476     return testresult;
10477 }
10478 #endif
10479 
10480 #ifndef OPENSSL_NO_TLS1_2
10481 static int test_ssl_dup(void)
10482 {
10483     SSL_CTX *cctx = NULL, *sctx = NULL;
10484     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
10485     int testresult = 0;
10486     BIO *rbio = NULL, *wbio = NULL;
10487 
10488     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10489             TLS_client_method(),
10490             0,
10491             0,
10492             &sctx, &cctx, cert, privkey)))
10493         goto end;
10494 
10495     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10496             NULL, NULL)))
10497         goto end;
10498 
10499     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10500         || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
10501         goto end;
10502 
10503     client2ssl = SSL_dup(clientssl);
10504     rbio = SSL_get_rbio(clientssl);
10505     if (!TEST_ptr(rbio)
10506         || !TEST_true(BIO_up_ref(rbio)))
10507         goto end;
10508     SSL_set0_rbio(client2ssl, rbio);
10509     rbio = NULL;
10510 
10511     wbio = SSL_get_wbio(clientssl);
10512     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
10513         goto end;
10514     SSL_set0_wbio(client2ssl, wbio);
10515     rbio = NULL;
10516 
10517     if (!TEST_ptr(client2ssl)
10518         /* Handshake not started so pointers should be different */
10519         || !TEST_ptr_ne(clientssl, client2ssl))
10520         goto end;
10521 
10522     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
10523         || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
10524         goto end;
10525 
10526     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
10527         goto end;
10528 
10529     SSL_free(clientssl);
10530     clientssl = SSL_dup(client2ssl);
10531     if (!TEST_ptr(clientssl)
10532         /* Handshake has finished so pointers should be the same */
10533         || !TEST_ptr_eq(clientssl, client2ssl))
10534         goto end;
10535 
10536     testresult = 1;
10537 
10538 end:
10539     SSL_free(serverssl);
10540     SSL_free(clientssl);
10541     SSL_free(client2ssl);
10542     SSL_CTX_free(sctx);
10543     SSL_CTX_free(cctx);
10544 
10545     return testresult;
10546 }
10547 
10548 static int secret_cb(SSL *s, void *secretin, int *secret_len,
10549     STACK_OF(SSL_CIPHER) *peer_ciphers,
10550     const SSL_CIPHER **cipher, void *arg)
10551 {
10552     int i;
10553     unsigned char *secret = secretin;
10554 
10555     /* Just use a fixed master secret */
10556     for (i = 0; i < *secret_len; i++)
10557         secret[i] = 0xff;
10558 
10559     /* We don't set a preferred cipher */
10560 
10561     return 1;
10562 }
10563 
10564 /*
10565  * Test the session_secret_cb which is designed for use with EAP-FAST
10566  */
10567 static int test_session_secret_cb(void)
10568 {
10569     SSL_CTX *cctx = NULL, *sctx = NULL;
10570     SSL *clientssl = NULL, *serverssl = NULL;
10571     SSL_SESSION *secret_sess = NULL;
10572     int testresult = 0;
10573 
10574     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10575             TLS_client_method(),
10576             0,
10577             0,
10578             &sctx, &cctx, cert, privkey)))
10579         goto end;
10580 
10581     /* Create an initial connection and save the session */
10582     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10583             NULL, NULL)))
10584         goto end;
10585 
10586     /* session_secret_cb does not support TLSv1.3 */
10587     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10588         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION)))
10589         goto end;
10590 
10591     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10592         goto end;
10593 
10594     if (!TEST_ptr(secret_sess = SSL_get1_session(clientssl)))
10595         goto end;
10596 
10597     shutdown_ssl_connection(serverssl, clientssl);
10598     serverssl = clientssl = NULL;
10599 
10600     /* Resume the earlier session */
10601     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10602             NULL, NULL)))
10603         goto end;
10604 
10605     /*
10606      * No session ids for EAP-FAST - otherwise the state machine gets very
10607      * confused.
10608      */
10609     if (!TEST_true(SSL_SESSION_set1_id(secret_sess, NULL, 0)))
10610         goto end;
10611 
10612     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10613         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10614         || !TEST_true(SSL_set_session_secret_cb(serverssl, secret_cb,
10615             NULL))
10616         || !TEST_true(SSL_set_session_secret_cb(clientssl, secret_cb,
10617             NULL))
10618         || !TEST_true(SSL_set_session(clientssl, secret_sess)))
10619         goto end;
10620 
10621     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10622         goto end;
10623 
10624     testresult = 1;
10625 
10626 end:
10627     SSL_SESSION_free(secret_sess);
10628     SSL_free(serverssl);
10629     SSL_free(clientssl);
10630     SSL_CTX_free(sctx);
10631     SSL_CTX_free(cctx);
10632 
10633     return testresult;
10634 }
10635 
10636 #ifndef OPENSSL_NO_DH
10637 
10638 static EVP_PKEY *tmp_dh_params = NULL;
10639 
10640 /* Helper function for the test_set_tmp_dh() tests */
10641 static EVP_PKEY *get_tmp_dh_params(void)
10642 {
10643     if (tmp_dh_params == NULL) {
10644         BIGNUM *p = NULL;
10645         OSSL_PARAM_BLD *tmpl = NULL;
10646         EVP_PKEY_CTX *pctx = NULL;
10647         OSSL_PARAM *params = NULL;
10648         EVP_PKEY *dhpkey = NULL;
10649 
10650         p = BN_get_rfc3526_prime_2048(NULL);
10651         if (!TEST_ptr(p))
10652             goto end;
10653 
10654         pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL);
10655         if (!TEST_ptr(pctx)
10656             || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx), 1))
10657             goto end;
10658 
10659         tmpl = OSSL_PARAM_BLD_new();
10660         if (!TEST_ptr(tmpl)
10661             || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl,
10662                 OSSL_PKEY_PARAM_FFC_P,
10663                 p))
10664             || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl,
10665                 OSSL_PKEY_PARAM_FFC_G,
10666                 2)))
10667             goto end;
10668 
10669         params = OSSL_PARAM_BLD_to_param(tmpl);
10670         if (!TEST_ptr(params)
10671             || !TEST_int_eq(EVP_PKEY_fromdata(pctx, &dhpkey,
10672                                 EVP_PKEY_KEY_PARAMETERS,
10673                                 params),
10674                 1))
10675             goto end;
10676 
10677         tmp_dh_params = dhpkey;
10678     end:
10679         BN_free(p);
10680         EVP_PKEY_CTX_free(pctx);
10681         OSSL_PARAM_BLD_free(tmpl);
10682         OSSL_PARAM_free(params);
10683     }
10684 
10685     if (tmp_dh_params != NULL && !EVP_PKEY_up_ref(tmp_dh_params))
10686         return NULL;
10687 
10688     return tmp_dh_params;
10689 }
10690 
10691 #ifndef OPENSSL_NO_DEPRECATED_3_0
10692 /* Callback used by test_set_tmp_dh() */
10693 static DH *tmp_dh_callback(SSL *s, int is_export, int keylen)
10694 {
10695     EVP_PKEY *dhpkey = get_tmp_dh_params();
10696     DH *ret = NULL;
10697 
10698     if (!TEST_ptr(dhpkey))
10699         return NULL;
10700 
10701     /*
10702      * libssl does not free the returned DH, so we free it now knowing that even
10703      * after we free dhpkey, there will still be a reference to the owning
10704      * EVP_PKEY in tmp_dh_params, and so the DH object will live for the length
10705      * of time we need it for.
10706      */
10707     ret = EVP_PKEY_get1_DH(dhpkey);
10708     DH_free(ret);
10709 
10710     EVP_PKEY_free(dhpkey);
10711 
10712     return ret;
10713 }
10714 #endif
10715 
10716 /*
10717  * Test the various methods for setting temporary DH parameters
10718  *
10719  * Test  0: Default (no auto) setting
10720  * Test  1: Explicit SSL_CTX auto off
10721  * Test  2: Explicit SSL auto off
10722  * Test  3: Explicit SSL_CTX auto on
10723  * Test  4: Explicit SSL auto on
10724  * Test  5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY
10725  * Test  6: Explicit SSL auto off, custom DH params via EVP_PKEY
10726  *
10727  * The following are testing deprecated APIs, so we only run them if available
10728  * Test  7: Explicit SSL_CTX auto off, custom DH params via DH
10729  * Test  8: Explicit SSL auto off, custom DH params via DH
10730  * Test  9: Explicit SSL_CTX auto off, custom DH params via callback
10731  * Test 10: Explicit SSL auto off, custom DH params via callback
10732  */
10733 static int test_set_tmp_dh(int idx)
10734 {
10735     SSL_CTX *cctx = NULL, *sctx = NULL;
10736     SSL *clientssl = NULL, *serverssl = NULL;
10737     int testresult = 0;
10738     int dhauto = (idx == 3 || idx == 4) ? 1 : 0;
10739     int expected = (idx <= 2) ? 0 : 1;
10740     EVP_PKEY *dhpkey = NULL;
10741 #ifndef OPENSSL_NO_DEPRECATED_3_0
10742     DH *dh = NULL;
10743 #else
10744 
10745     if (idx >= 7)
10746         return 1;
10747 #endif
10748 
10749     if (idx >= 5 && idx <= 8) {
10750         dhpkey = get_tmp_dh_params();
10751         if (!TEST_ptr(dhpkey))
10752             goto end;
10753     }
10754 #ifndef OPENSSL_NO_DEPRECATED_3_0
10755     if (idx == 7 || idx == 8) {
10756         dh = EVP_PKEY_get1_DH(dhpkey);
10757         if (!TEST_ptr(dh))
10758             goto end;
10759     }
10760 #endif
10761 
10762     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10763             TLS_client_method(),
10764             0,
10765             0,
10766             &sctx, &cctx, cert, privkey)))
10767         goto end;
10768 
10769     if ((idx & 1) == 1) {
10770         if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto)))
10771             goto end;
10772     }
10773 
10774     if (idx == 5) {
10775         if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey)))
10776             goto end;
10777         dhpkey = NULL;
10778     }
10779 #ifndef OPENSSL_NO_DEPRECATED_3_0
10780     else if (idx == 7) {
10781         if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh)))
10782             goto end;
10783     } else if (idx == 9) {
10784         SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback);
10785     }
10786 #endif
10787 
10788     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10789             NULL, NULL)))
10790         goto end;
10791 
10792     if ((idx & 1) == 0 && idx != 0) {
10793         if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto)))
10794             goto end;
10795     }
10796     if (idx == 6) {
10797         if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey)))
10798             goto end;
10799         dhpkey = NULL;
10800     }
10801 #ifndef OPENSSL_NO_DEPRECATED_3_0
10802     else if (idx == 8) {
10803         if (!TEST_true(SSL_set_tmp_dh(serverssl, dh)))
10804             goto end;
10805     } else if (idx == 10) {
10806         SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback);
10807     }
10808 #endif
10809 
10810     if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10811         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10812         || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA")))
10813         goto end;
10814 
10815     /*
10816      * If autoon then we should succeed. Otherwise we expect failure because
10817      * there are no parameters
10818      */
10819     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
10820                          SSL_ERROR_NONE),
10821             expected))
10822         goto end;
10823 
10824     testresult = 1;
10825 
10826 end:
10827 #ifndef OPENSSL_NO_DEPRECATED_3_0
10828     DH_free(dh);
10829 #endif
10830     SSL_free(serverssl);
10831     SSL_free(clientssl);
10832     SSL_CTX_free(sctx);
10833     SSL_CTX_free(cctx);
10834     EVP_PKEY_free(dhpkey);
10835 
10836     return testresult;
10837 }
10838 
10839 /*
10840  * Test the auto DH keys are appropriately sized
10841  */
10842 static int test_dh_auto(int idx)
10843 {
10844     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method());
10845     SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10846     SSL *clientssl = NULL, *serverssl = NULL;
10847     int testresult = 0;
10848     EVP_PKEY *tmpkey = NULL;
10849     char *thiscert = NULL, *thiskey = NULL;
10850     size_t expdhsize = 0;
10851     const char *ciphersuite = "DHE-RSA-AES128-SHA";
10852 
10853     if (!TEST_ptr(sctx) || !TEST_ptr(cctx))
10854         goto end;
10855 
10856     switch (idx) {
10857     case 0:
10858         /* The FIPS provider doesn't support this DH size - so we ignore it */
10859         if (is_fips) {
10860             testresult = 1;
10861             goto end;
10862         }
10863         thiscert = cert1024;
10864         thiskey = privkey1024;
10865         expdhsize = 1024;
10866         SSL_CTX_set_security_level(sctx, 1);
10867         SSL_CTX_set_security_level(cctx, 1);
10868         break;
10869     case 1:
10870         /* 2048 bit prime */
10871         thiscert = cert;
10872         thiskey = privkey;
10873         expdhsize = 2048;
10874         break;
10875     case 2:
10876         thiscert = cert3072;
10877         thiskey = privkey3072;
10878         expdhsize = 3072;
10879         break;
10880     case 3:
10881         thiscert = cert4096;
10882         thiskey = privkey4096;
10883         expdhsize = 4096;
10884         break;
10885     case 4:
10886         thiscert = cert8192;
10887         thiskey = privkey8192;
10888         expdhsize = 8192;
10889         break;
10890     /* No certificate cases */
10891     case 5:
10892         /* The FIPS provider doesn't support this DH size - so we ignore it */
10893         if (is_fips) {
10894             testresult = 1;
10895             goto end;
10896         }
10897         ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0";
10898         expdhsize = 1024;
10899         break;
10900     case 6:
10901         ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0";
10902         expdhsize = 3072;
10903         break;
10904     default:
10905         TEST_error("Invalid text index");
10906         goto end;
10907     }
10908 
10909     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL,
10910             NULL,
10911             0,
10912             0,
10913             &sctx, &cctx, thiscert, thiskey)))
10914         goto end;
10915 
10916     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10917             NULL, NULL)))
10918         goto end;
10919 
10920     if (!TEST_true(SSL_set_dh_auto(serverssl, 1))
10921         || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10922         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10923         || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite))
10924         || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite)))
10925         goto end;
10926 
10927     /*
10928      * Send the server's first flight. At this point the server has created the
10929      * temporary DH key but hasn't finished using it yet. Once used it is
10930      * removed, so we cannot test it.
10931      */
10932     if (!TEST_int_le(SSL_connect(clientssl), 0)
10933         || !TEST_int_le(SSL_accept(serverssl), 0))
10934         goto end;
10935 
10936     if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0))
10937         goto end;
10938     if (!TEST_size_t_eq(EVP_PKEY_get_bits(tmpkey), expdhsize))
10939         goto end;
10940 
10941     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10942         goto end;
10943 
10944     testresult = 1;
10945 
10946 end:
10947     SSL_free(serverssl);
10948     SSL_free(clientssl);
10949     SSL_CTX_free(sctx);
10950     SSL_CTX_free(cctx);
10951     EVP_PKEY_free(tmpkey);
10952 
10953     return testresult;
10954 }
10955 #endif /* OPENSSL_NO_DH */
10956 #endif /* OPENSSL_NO_TLS1_2 */
10957 
10958 #ifndef OSSL_NO_USABLE_TLS1_3
10959 /*
10960  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
10961  * that it works even without a certificate configured for the original
10962  * SSL_CTX
10963  */
10964 static int test_sni_tls13(void)
10965 {
10966     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
10967     SSL *clientssl = NULL, *serverssl = NULL;
10968     int testresult = 0;
10969 
10970     /* Reset callback counter */
10971     snicb = 0;
10972 
10973     /* Create an initial SSL_CTX with no certificate configured */
10974     sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10975     if (!TEST_ptr(sctx))
10976         goto end;
10977     /* Require TLSv1.3 as a minimum */
10978     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10979             TLS_client_method(), TLS1_3_VERSION, 0,
10980             &sctx2, &cctx, cert, privkey)))
10981         goto end;
10982 
10983     /* Set up SNI */
10984     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
10985         || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
10986         goto end;
10987 
10988     /*
10989      * Connection should still succeed because the final SSL_CTX has the right
10990      * certificates configured.
10991      */
10992     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10993             &clientssl, NULL, NULL))
10994         || !TEST_true(create_ssl_connection(serverssl, clientssl,
10995             SSL_ERROR_NONE)))
10996         goto end;
10997 
10998     /* We should have had the SNI callback called exactly once */
10999     if (!TEST_int_eq(snicb, 1))
11000         goto end;
11001 
11002     testresult = 1;
11003 
11004 end:
11005     SSL_free(serverssl);
11006     SSL_free(clientssl);
11007     SSL_CTX_free(sctx2);
11008     SSL_CTX_free(sctx);
11009     SSL_CTX_free(cctx);
11010     return testresult;
11011 }
11012 
11013 /*
11014  * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week
11015  * 0 = TLSv1.2
11016  * 1 = TLSv1.3
11017  */
11018 static int test_ticket_lifetime(int idx)
11019 {
11020     SSL_CTX *cctx = NULL, *sctx = NULL;
11021     SSL *clientssl = NULL, *serverssl = NULL;
11022     int testresult = 0;
11023     int version = TLS1_3_VERSION;
11024 
11025 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
11026 #define TWO_WEEK_SEC (2 * ONE_WEEK_SEC)
11027 
11028     if (idx == 0) {
11029 #ifdef OPENSSL_NO_TLS1_2
11030         return TEST_skip("TLS 1.2 is disabled.");
11031 #else
11032         version = TLS1_2_VERSION;
11033 #endif
11034     }
11035 
11036     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11037             TLS_client_method(), version, version,
11038             &sctx, &cctx, cert, privkey)))
11039         goto end;
11040 
11041     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11042             &clientssl, NULL, NULL)))
11043         goto end;
11044 
11045     /*
11046      * Set the timeout to be more than 1 week
11047      * make sure the returned value is the default
11048      */
11049     if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC),
11050             SSL_get_default_timeout(serverssl)))
11051         goto end;
11052 
11053     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11054         goto end;
11055 
11056     if (idx == 0) {
11057         /* TLSv1.2 uses the set value */
11058         if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC))
11059             goto end;
11060     } else {
11061         /* TLSv1.3 uses the limited value */
11062         if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC))
11063             goto end;
11064     }
11065     testresult = 1;
11066 
11067 end:
11068     SSL_free(serverssl);
11069     SSL_free(clientssl);
11070     SSL_CTX_free(sctx);
11071     SSL_CTX_free(cctx);
11072     return testresult;
11073 }
11074 #endif
11075 /*
11076  * Test that setting an ALPN does not violate RFC
11077  */
11078 static int test_set_alpn(void)
11079 {
11080     SSL_CTX *ctx = NULL;
11081     SSL *ssl = NULL;
11082     int testresult = 0;
11083 
11084     unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
11085     unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
11086     unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
11087     unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00 };
11088     unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd' };
11089     unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd' };
11090 
11091     /* Create an initial SSL_CTX with no certificate configured */
11092     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11093     if (!TEST_ptr(ctx))
11094         goto end;
11095 
11096     /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
11097     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
11098         goto end;
11099     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
11100         goto end;
11101     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
11102         goto end;
11103     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
11104         goto end;
11105     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
11106         goto end;
11107     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
11108         goto end;
11109     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
11110         goto end;
11111     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
11112         goto end;
11113     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
11114         goto end;
11115 
11116     ssl = SSL_new(ctx);
11117     if (!TEST_ptr(ssl))
11118         goto end;
11119 
11120     if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
11121         goto end;
11122     if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
11123         goto end;
11124     if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
11125         goto end;
11126     if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
11127         goto end;
11128     if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
11129         goto end;
11130     if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
11131         goto end;
11132     if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
11133         goto end;
11134     if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
11135         goto end;
11136     if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
11137         goto end;
11138 
11139     testresult = 1;
11140 
11141 end:
11142     SSL_free(ssl);
11143     SSL_CTX_free(ctx);
11144     return testresult;
11145 }
11146 
11147 /*
11148  * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store.
11149  */
11150 static int test_set_verify_cert_store_ssl_ctx(void)
11151 {
11152     SSL_CTX *ctx = NULL;
11153     int testresult = 0;
11154     X509_STORE *store = NULL, *new_store = NULL,
11155                *cstore = NULL, *new_cstore = NULL;
11156 
11157     /* Create an initial SSL_CTX. */
11158     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11159     if (!TEST_ptr(ctx))
11160         goto end;
11161 
11162     /* Retrieve verify store pointer. */
11163     if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11164         goto end;
11165 
11166     /* Retrieve chain store pointer. */
11167     if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11168         goto end;
11169 
11170     /* We haven't set any yet, so this should be NULL. */
11171     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11172         goto end;
11173 
11174     /* Create stores. We use separate stores so pointers are different. */
11175     new_store = X509_STORE_new();
11176     if (!TEST_ptr(new_store))
11177         goto end;
11178 
11179     new_cstore = X509_STORE_new();
11180     if (!TEST_ptr(new_cstore))
11181         goto end;
11182 
11183     /* Set stores. */
11184     if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store)))
11185         goto end;
11186 
11187     if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore)))
11188         goto end;
11189 
11190     /* Should be able to retrieve the same pointer. */
11191     if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11192         goto end;
11193 
11194     if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11195         goto end;
11196 
11197     if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
11198         goto end;
11199 
11200     /* Should be able to unset again. */
11201     if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL)))
11202         goto end;
11203 
11204     if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL)))
11205         goto end;
11206 
11207     /* Should now be NULL. */
11208     if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11209         goto end;
11210 
11211     if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11212         goto end;
11213 
11214     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11215         goto end;
11216 
11217     testresult = 1;
11218 
11219 end:
11220     X509_STORE_free(new_store);
11221     X509_STORE_free(new_cstore);
11222     SSL_CTX_free(ctx);
11223     return testresult;
11224 }
11225 
11226 /*
11227  * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store.
11228  */
11229 static int test_set_verify_cert_store_ssl(void)
11230 {
11231     SSL_CTX *ctx = NULL;
11232     SSL *ssl = NULL;
11233     int testresult = 0;
11234     X509_STORE *store = NULL, *new_store = NULL,
11235                *cstore = NULL, *new_cstore = NULL;
11236 
11237     /* Create an initial SSL_CTX. */
11238     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11239     if (!TEST_ptr(ctx))
11240         goto end;
11241 
11242     /* Create an SSL object. */
11243     ssl = SSL_new(ctx);
11244     if (!TEST_ptr(ssl))
11245         goto end;
11246 
11247     /* Retrieve verify store pointer. */
11248     if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11249         goto end;
11250 
11251     /* Retrieve chain store pointer. */
11252     if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11253         goto end;
11254 
11255     /* We haven't set any yet, so this should be NULL. */
11256     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11257         goto end;
11258 
11259     /* Create stores. We use separate stores so pointers are different. */
11260     new_store = X509_STORE_new();
11261     if (!TEST_ptr(new_store))
11262         goto end;
11263 
11264     new_cstore = X509_STORE_new();
11265     if (!TEST_ptr(new_cstore))
11266         goto end;
11267 
11268     /* Set stores. */
11269     if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store)))
11270         goto end;
11271 
11272     if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore)))
11273         goto end;
11274 
11275     /* Should be able to retrieve the same pointer. */
11276     if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11277         goto end;
11278 
11279     if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11280         goto end;
11281 
11282     if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
11283         goto end;
11284 
11285     /* Should be able to unset again. */
11286     if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL)))
11287         goto end;
11288 
11289     if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL)))
11290         goto end;
11291 
11292     /* Should now be NULL. */
11293     if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11294         goto end;
11295 
11296     if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11297         goto end;
11298 
11299     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11300         goto end;
11301 
11302     testresult = 1;
11303 
11304 end:
11305     X509_STORE_free(new_store);
11306     X509_STORE_free(new_cstore);
11307     SSL_free(ssl);
11308     SSL_CTX_free(ctx);
11309     return testresult;
11310 }
11311 
11312 static int test_inherit_verify_param(void)
11313 {
11314     int testresult = 0;
11315 
11316     SSL_CTX *ctx = NULL;
11317     X509_VERIFY_PARAM *cp = NULL;
11318     SSL *ssl = NULL;
11319     X509_VERIFY_PARAM *sp = NULL;
11320     int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
11321 
11322     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11323     if (!TEST_ptr(ctx))
11324         goto end;
11325 
11326     cp = SSL_CTX_get0_param(ctx);
11327     if (!TEST_ptr(cp))
11328         goto end;
11329     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
11330         goto end;
11331 
11332     X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
11333 
11334     ssl = SSL_new(ctx);
11335     if (!TEST_ptr(ssl))
11336         goto end;
11337 
11338     sp = SSL_get0_param(ssl);
11339     if (!TEST_ptr(sp))
11340         goto end;
11341     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
11342         goto end;
11343 
11344     testresult = 1;
11345 
11346 end:
11347     SSL_free(ssl);
11348     SSL_CTX_free(ctx);
11349 
11350     return testresult;
11351 }
11352 
11353 static int test_load_dhfile(void)
11354 {
11355 #ifndef OPENSSL_NO_DH
11356     int testresult = 0;
11357 
11358     SSL_CTX *ctx = NULL;
11359     SSL_CONF_CTX *cctx = NULL;
11360 
11361     if (dhfile == NULL)
11362         return 1;
11363 
11364     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()))
11365         || !TEST_ptr(cctx = SSL_CONF_CTX_new()))
11366         goto end;
11367 
11368     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
11369     SSL_CONF_CTX_set_flags(cctx,
11370         SSL_CONF_FLAG_CERTIFICATE
11371             | SSL_CONF_FLAG_SERVER
11372             | SSL_CONF_FLAG_FILE);
11373 
11374     if (!TEST_int_eq(SSL_CONF_cmd(cctx, "DHParameters", dhfile), 2))
11375         goto end;
11376 
11377     testresult = 1;
11378 end:
11379     SSL_CONF_CTX_free(cctx);
11380     SSL_CTX_free(ctx);
11381 
11382     return testresult;
11383 #else
11384     return TEST_skip("DH not supported by this build");
11385 #endif
11386 }
11387 
11388 #ifndef OSSL_NO_USABLE_TLS1_3
11389 /* Test that read_ahead works across a key change */
11390 static int test_read_ahead_key_change(void)
11391 {
11392     SSL_CTX *cctx = NULL, *sctx = NULL;
11393     SSL *clientssl = NULL, *serverssl = NULL;
11394     int testresult = 0;
11395     char *msg = "Hello World";
11396     size_t written, readbytes;
11397     char buf[80];
11398     int i;
11399 
11400     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11401             TLS_client_method(), TLS1_3_VERSION, 0,
11402             &sctx, &cctx, cert, privkey)))
11403         goto end;
11404 
11405     SSL_CTX_set_read_ahead(sctx, 1);
11406 
11407     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11408             &clientssl, NULL, NULL)))
11409         goto end;
11410 
11411     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11412         goto end;
11413 
11414     /* Write some data, send a key update, write more data */
11415     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11416         || !TEST_size_t_eq(written, strlen(msg)))
11417         goto end;
11418 
11419     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
11420         goto end;
11421 
11422     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11423         || !TEST_size_t_eq(written, strlen(msg)))
11424         goto end;
11425 
11426     /*
11427      * Since read_ahead is on the first read below should read the record with
11428      * the first app data, the second record with the key update message, and
11429      * the third record with the app data all in one go. We should be able to
11430      * still process the read_ahead data correctly even though it crosses
11431      * epochs
11432      */
11433     for (i = 0; i < 2; i++) {
11434         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11435                 &readbytes)))
11436             goto end;
11437 
11438         buf[readbytes] = '\0';
11439         if (!TEST_str_eq(buf, msg))
11440             goto end;
11441     }
11442 
11443     testresult = 1;
11444 
11445 end:
11446     SSL_free(serverssl);
11447     SSL_free(clientssl);
11448     SSL_CTX_free(sctx);
11449     SSL_CTX_free(cctx);
11450     return testresult;
11451 }
11452 
11453 static size_t record_pad_cb(SSL *s, int type, size_t len, void *arg)
11454 {
11455     int *called = arg;
11456 
11457     switch ((*called)++) {
11458     case 0:
11459         /* Add some padding to first record */
11460         return 512;
11461     case 1:
11462         /* Maximally pad the second record */
11463         return SSL3_RT_MAX_PLAIN_LENGTH - len;
11464     case 2:
11465         /*
11466          * Exceeding the maximum padding should be fine. It should just pad to
11467          * the maximum anyway
11468          */
11469         return SSL3_RT_MAX_PLAIN_LENGTH + 1 - len;
11470     case 3:
11471         /*
11472          * Very large padding should also be ok. Should just pad to the maximum
11473          * allowed
11474          */
11475         return SIZE_MAX;
11476     default:
11477         return 0;
11478     }
11479 }
11480 
11481 /*
11482  * Test that setting record padding in TLSv1.3 works as expected
11483  * Test 0: Record padding callback on the SSL_CTX
11484  * Test 1: Record padding callback on the SSL
11485  * Test 2: Record block padding on the SSL_CTX
11486  * Test 3: Record block padding on the SSL
11487  * Test 4: Extended record block padding on the SSL_CTX
11488  * Test 5: Extended record block padding on the SSL
11489  */
11490 static int test_tls13_record_padding(int idx)
11491 {
11492     SSL_CTX *cctx = NULL, *sctx = NULL;
11493     SSL *clientssl = NULL, *serverssl = NULL;
11494     int testresult = 0;
11495     char *msg = "Hello World";
11496     size_t written, readbytes;
11497     char buf[80];
11498     int i;
11499     int called = 0;
11500 
11501     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11502             TLS_client_method(), TLS1_3_VERSION, 0,
11503             &sctx, &cctx, cert, privkey)))
11504         goto end;
11505 
11506     if (idx == 0) {
11507         SSL_CTX_set_record_padding_callback(cctx, record_pad_cb);
11508         SSL_CTX_set_record_padding_callback_arg(cctx, &called);
11509         if (!TEST_ptr_eq(SSL_CTX_get_record_padding_callback_arg(cctx), &called))
11510             goto end;
11511     } else if (idx == 2) {
11512         /* Exceeding the max plain length should fail */
11513         if (!TEST_false(SSL_CTX_set_block_padding(cctx,
11514                 SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11515             goto end;
11516         if (!TEST_true(SSL_CTX_set_block_padding(cctx, 512)))
11517             goto end;
11518     } else if (idx == 4) {
11519         /* pad only handshake/alert messages */
11520         if (!TEST_true(SSL_CTX_set_block_padding_ex(cctx, 0, 512)))
11521             goto end;
11522     }
11523 
11524     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11525             &clientssl, NULL, NULL)))
11526         goto end;
11527 
11528     if (idx == 1) {
11529         SSL_set_record_padding_callback(clientssl, record_pad_cb);
11530         SSL_set_record_padding_callback_arg(clientssl, &called);
11531         if (!TEST_ptr_eq(SSL_get_record_padding_callback_arg(clientssl), &called))
11532             goto end;
11533     } else if (idx == 3) {
11534         /* Exceeding the max plain length should fail */
11535         if (!TEST_false(SSL_set_block_padding(clientssl,
11536                 SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11537             goto end;
11538         if (!TEST_true(SSL_set_block_padding(clientssl, 512)))
11539             goto end;
11540     } else if (idx == 5) {
11541         /* Exceeding the max plain length should fail */
11542         if (!TEST_false(SSL_set_block_padding_ex(clientssl, 0,
11543                 SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11544             goto end;
11545         /* pad server and client handshake only */
11546         if (!TEST_true(SSL_set_block_padding_ex(clientssl, 0, 512)))
11547             goto end;
11548         if (!TEST_true(SSL_set_block_padding_ex(serverssl, 0, 512)))
11549             goto end;
11550     }
11551 
11552     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11553         goto end;
11554 
11555     called = 0;
11556     /*
11557      * Write some data, then check we can read it. Do this four times to check
11558      * we can continue to write and read padded data after the initial record
11559      * padding has been added. We don't actually check that the padding has
11560      * been applied to the record - just that we can continue to communicate
11561      * normally and that the callback has been called (if appropriate).
11562      */
11563     for (i = 0; i < 4; i++) {
11564         if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11565             || !TEST_size_t_eq(written, strlen(msg)))
11566             goto end;
11567 
11568         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11569                 &readbytes))
11570             || !TEST_size_t_eq(written, readbytes))
11571             goto end;
11572 
11573         buf[readbytes] = '\0';
11574         if (!TEST_str_eq(buf, msg))
11575             goto end;
11576     }
11577 
11578     if ((idx == 0 || idx == 1) && !TEST_int_eq(called, 4))
11579         goto end;
11580 
11581     testresult = 1;
11582 end:
11583     SSL_free(serverssl);
11584     SSL_free(clientssl);
11585     SSL_CTX_free(sctx);
11586     SSL_CTX_free(cctx);
11587     return testresult;
11588 }
11589 #endif /* OSSL_NO_USABLE_TLS1_3 */
11590 
11591 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
11592 /*
11593  * Test TLSv1.2 with a pipeline capable cipher. TLSv1.3 and DTLS do not
11594  * support this yet. The only pipeline capable cipher that we have is in the
11595  * dasync engine (providers don't support this yet), so we have to use
11596  * deprecated APIs for this test.
11597  *
11598  * Test 0: Client has pipelining enabled, server does not
11599  * Test 1: Server has pipelining enabled, client does not
11600  * Test 2: Client has pipelining enabled, server does not: not enough data to
11601  *         fill all the pipelines
11602  * Test 3: Client has pipelining enabled, server does not: not enough data to
11603  *         fill all the pipelines by more than a full pipeline's worth
11604  * Test 4: Client has pipelining enabled, server does not: more data than all
11605  *         the available pipelines can take
11606  * Test 5: Client has pipelining enabled, server does not: Maximum size pipeline
11607  * Test 6: Repeat of test 0, but the engine is loaded late (after the SSL_CTX
11608  *         is created)
11609  */
11610 static int test_pipelining(int idx)
11611 {
11612     SSL_CTX *cctx = NULL, *sctx = NULL;
11613     SSL *clientssl = NULL, *serverssl = NULL, *peera, *peerb;
11614     int testresult = 0, numreads;
11615     /* A 55 byte message */
11616     unsigned char *msg = (unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123";
11617     size_t written, readbytes, offset, msglen, fragsize = 10, numpipes = 5;
11618     size_t expectedreads;
11619     unsigned char *buf = NULL;
11620     ENGINE *e = NULL;
11621 
11622     if (idx != 6) {
11623         e = load_dasync();
11624         if (e == NULL)
11625             return 0;
11626     }
11627 
11628     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11629             TLS_client_method(), 0,
11630             TLS1_2_VERSION, &sctx, &cctx, cert,
11631             privkey)))
11632         goto end;
11633 
11634     if (idx == 6) {
11635         e = load_dasync();
11636         if (e == NULL)
11637             goto end;
11638         /* Now act like test 0 */
11639         idx = 0;
11640     }
11641 
11642     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11643             &clientssl, NULL, NULL)))
11644         goto end;
11645 
11646     if (!TEST_true(SSL_set_cipher_list(clientssl, "AES128-SHA")))
11647         goto end;
11648 
11649     /* peera is always configured for pipelining, while peerb is not. */
11650     if (idx == 1) {
11651         peera = serverssl;
11652         peerb = clientssl;
11653 
11654     } else {
11655         peera = clientssl;
11656         peerb = serverssl;
11657     }
11658 
11659     if (idx == 5) {
11660         numpipes = 2;
11661         /* Maximum allowed fragment size */
11662         fragsize = SSL3_RT_MAX_PLAIN_LENGTH;
11663         msglen = fragsize * numpipes;
11664         msg = OPENSSL_malloc(msglen);
11665         if (!TEST_ptr(msg))
11666             goto end;
11667         if (!TEST_int_gt(RAND_bytes_ex(libctx, msg, msglen, 0), 0))
11668             goto end;
11669     } else if (idx == 4) {
11670         msglen = 55;
11671     } else {
11672         msglen = 50;
11673     }
11674     if (idx == 2)
11675         msglen -= 2; /* Send 2 less bytes */
11676     else if (idx == 3)
11677         msglen -= 12; /* Send 12 less bytes */
11678 
11679     buf = OPENSSL_malloc(msglen);
11680     if (!TEST_ptr(buf))
11681         goto end;
11682 
11683     if (idx == 5) {
11684         /*
11685          * Test that setting a split send fragment longer than the maximum
11686          * allowed fails
11687          */
11688         if (!TEST_false(SSL_set_split_send_fragment(peera, fragsize + 1)))
11689             goto end;
11690     }
11691 
11692     /*
11693      * In the normal case. We have 5 pipelines with 10 bytes per pipeline
11694      * (50 bytes in total). This is a ridiculously small number of bytes -
11695      * but sufficient for our purposes
11696      */
11697     if (!TEST_true(SSL_set_max_pipelines(peera, numpipes))
11698         || !TEST_true(SSL_set_split_send_fragment(peera, fragsize)))
11699         goto end;
11700 
11701     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11702         goto end;
11703 
11704     /* Write some data from peera to peerb */
11705     if (!TEST_true(SSL_write_ex(peera, msg, msglen, &written))
11706         || !TEST_size_t_eq(written, msglen))
11707         goto end;
11708 
11709     /*
11710      * If the pipelining code worked, then we expect all |numpipes| pipelines to
11711      * have been used - except in test 3 where only |numpipes - 1| pipelines
11712      * will be used. This will result in |numpipes| records (|numpipes - 1| for
11713      * test 3) having been sent to peerb. Since peerb is not using read_ahead we
11714      * expect this to be read in |numpipes| or |numpipes - 1| separate
11715      * SSL_read_ex calls. In the case of test 4, there is then one additional
11716      * read for left over data that couldn't fit in the previous pipelines
11717      */
11718     for (offset = 0, numreads = 0;
11719         offset < msglen;
11720         offset += readbytes, numreads++) {
11721         if (!TEST_true(SSL_read_ex(peerb, buf + offset,
11722                 msglen - offset, &readbytes)))
11723             goto end;
11724     }
11725 
11726     expectedreads = idx == 4 ? numpipes + 1
11727                              : (idx == 3 ? numpipes - 1 : numpipes);
11728     if (!TEST_mem_eq(msg, msglen, buf, offset)
11729         || !TEST_int_eq(numreads, expectedreads))
11730         goto end;
11731 
11732     /*
11733      * Write some data from peerb to peera. We do this in up to |numpipes + 1|
11734      * chunks to exercise the read pipelining code on peera.
11735      */
11736     for (offset = 0; offset < msglen; offset += fragsize) {
11737         size_t sendlen = msglen - offset;
11738 
11739         if (sendlen > fragsize)
11740             sendlen = fragsize;
11741         if (!TEST_true(SSL_write_ex(peerb, msg + offset, sendlen, &written))
11742             || !TEST_size_t_eq(written, sendlen))
11743             goto end;
11744     }
11745 
11746     /*
11747      * The data was written in |numpipes|, |numpipes - 1| or |numpipes + 1|
11748      * separate chunks (depending on which test we are running). If the
11749      * pipelining is working then we expect peera to read up to numpipes chunks
11750      * and process them in parallel, giving back the complete result in a single
11751      * call to SSL_read_ex
11752      */
11753     if (!TEST_true(SSL_read_ex(peera, buf, msglen, &readbytes))
11754         || !TEST_size_t_le(readbytes, msglen))
11755         goto end;
11756 
11757     if (idx == 4) {
11758         size_t readbytes2;
11759 
11760         if (!TEST_true(SSL_read_ex(peera, buf + readbytes,
11761                 msglen - readbytes, &readbytes2)))
11762             goto end;
11763         readbytes += readbytes2;
11764         if (!TEST_size_t_le(readbytes, msglen))
11765             goto end;
11766     }
11767 
11768     if (!TEST_mem_eq(msg, msglen, buf, readbytes))
11769         goto end;
11770 
11771     testresult = 1;
11772 end:
11773     SSL_free(serverssl);
11774     SSL_free(clientssl);
11775     SSL_CTX_free(sctx);
11776     SSL_CTX_free(cctx);
11777     if (e != NULL) {
11778         ENGINE_unregister_ciphers(e);
11779         ENGINE_finish(e);
11780         ENGINE_free(e);
11781     }
11782     OPENSSL_free(buf);
11783     if (fragsize == SSL3_RT_MAX_PLAIN_LENGTH)
11784         OPENSSL_free(msg);
11785     return testresult;
11786 }
11787 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */
11788 
11789 static int check_version_string(SSL *s, int version)
11790 {
11791     const char *verstr = NULL;
11792 
11793     switch (version) {
11794     case SSL3_VERSION:
11795         verstr = "SSLv3";
11796         break;
11797     case TLS1_VERSION:
11798         verstr = "TLSv1";
11799         break;
11800     case TLS1_1_VERSION:
11801         verstr = "TLSv1.1";
11802         break;
11803     case TLS1_2_VERSION:
11804         verstr = "TLSv1.2";
11805         break;
11806     case TLS1_3_VERSION:
11807         verstr = "TLSv1.3";
11808         break;
11809     case DTLS1_VERSION:
11810         verstr = "DTLSv1";
11811         break;
11812     case DTLS1_2_VERSION:
11813         verstr = "DTLSv1.2";
11814     }
11815 
11816     return TEST_str_eq(verstr, SSL_get_version(s));
11817 }
11818 
11819 /*
11820  * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and
11821  * SSL_is_dtls return the expected results for a (D)TLS connection. Compare with
11822  * test_version() in quicapitest.c which does the same thing for QUIC
11823  * connections.
11824  */
11825 static int test_version(int idx)
11826 {
11827     SSL_CTX *cctx = NULL, *sctx = NULL;
11828     SSL *clientssl = NULL, *serverssl = NULL;
11829     int testresult = 0, version;
11830     const SSL_METHOD *servmeth = TLS_server_method();
11831     const SSL_METHOD *clientmeth = TLS_client_method();
11832 
11833     switch (idx) {
11834 #if !defined(OPENSSL_NO_SSL3)
11835     case 0:
11836         version = SSL3_VERSION;
11837         break;
11838 #endif
11839 #if !defined(OPENSSL_NO_TLS1)
11840     case 1:
11841         version = TLS1_VERSION;
11842         break;
11843 #endif
11844 #if !defined(OPENSSL_NO_TLS1_2)
11845     case 2:
11846         version = TLS1_2_VERSION;
11847         break;
11848 #endif
11849 #if !defined(OSSL_NO_USABLE_TLS1_3)
11850     case 3:
11851         version = TLS1_3_VERSION;
11852         break;
11853 #endif
11854 #if !defined(OPENSSL_NO_DTLS1)
11855     case 4:
11856         version = DTLS1_VERSION;
11857         break;
11858 #endif
11859 #if !defined(OPENSSL_NO_DTLS1_2)
11860     case 5:
11861         version = DTLS1_2_VERSION;
11862         break;
11863 #endif
11864     /*
11865      * NB we do not support QUIC in this test. That is covered by quicapitest.c
11866      * We also don't support DTLS1_BAD_VER since we have no server support for
11867      * that.
11868      */
11869     default:
11870         TEST_skip("Unsupported protocol version");
11871         return 1;
11872     }
11873 
11874     if (is_fips
11875         && (version == SSL3_VERSION
11876             || version == TLS1_VERSION
11877             || version == DTLS1_VERSION)) {
11878         TEST_skip("Protocol version not supported with FIPS");
11879         return 1;
11880     }
11881 
11882 #if !defined(OPENSSL_NO_DTLS)
11883     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11884         servmeth = DTLS_server_method();
11885         clientmeth = DTLS_client_method();
11886     }
11887 #endif
11888 
11889     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, version,
11890             version, &sctx, &cctx, cert, privkey)))
11891         goto end;
11892 
11893     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
11894         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
11895             "DEFAULT:@SECLEVEL=0")))
11896         goto end;
11897 
11898     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11899             &clientssl, NULL, NULL)))
11900         goto end;
11901 
11902     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11903         goto end;
11904 
11905     if (!TEST_int_eq(SSL_version(serverssl), version)
11906         || !TEST_int_eq(SSL_version(clientssl), version)
11907         || !TEST_true(check_version_string(serverssl, version))
11908         || !TEST_true(check_version_string(clientssl, version)))
11909         goto end;
11910 
11911     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11912         if (!TEST_true(SSL_is_dtls(serverssl))
11913             || !TEST_true(SSL_is_dtls(clientssl))
11914             || !TEST_false(SSL_is_tls(serverssl))
11915             || !TEST_false(SSL_is_tls(clientssl))
11916             || !TEST_false(SSL_is_quic(serverssl))
11917             || !TEST_false(SSL_is_quic(clientssl)))
11918             goto end;
11919     } else {
11920         if (!TEST_true(SSL_is_tls(serverssl))
11921             || !TEST_true(SSL_is_tls(clientssl))
11922             || !TEST_false(SSL_is_dtls(serverssl))
11923             || !TEST_false(SSL_is_dtls(clientssl))
11924             || !TEST_false(SSL_is_quic(serverssl))
11925             || !TEST_false(SSL_is_quic(clientssl)))
11926             goto end;
11927     }
11928 
11929     testresult = 1;
11930 end:
11931     SSL_free(serverssl);
11932     SSL_free(clientssl);
11933     SSL_CTX_free(sctx);
11934     SSL_CTX_free(cctx);
11935     return testresult;
11936 }
11937 
11938 /*
11939  * Test that the SSL_rstate_string*() APIs return sane results
11940  */
11941 static int test_rstate_string(void)
11942 {
11943     SSL_CTX *cctx = NULL, *sctx = NULL;
11944     SSL *clientssl = NULL, *serverssl = NULL;
11945     int testresult = 0, version;
11946     const SSL_METHOD *servmeth = TLS_server_method();
11947     const SSL_METHOD *clientmeth = TLS_client_method();
11948     size_t written, readbytes;
11949     unsigned char buf[2];
11950     unsigned char dummyheader[SSL3_RT_HEADER_LENGTH] = {
11951         SSL3_RT_APPLICATION_DATA,
11952         TLS1_2_VERSION_MAJOR,
11953         0, /* To be filled in later */
11954         0,
11955         1
11956     };
11957 
11958     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, 0,
11959             0, &sctx, &cctx, cert, privkey)))
11960         goto end;
11961 
11962     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11963             &clientssl, NULL, NULL)))
11964         goto end;
11965 
11966     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11967         || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11968         goto end;
11969 
11970     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11971         goto end;
11972 
11973     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11974         || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11975         goto end;
11976 
11977     /* Fill in the correct version for the record header */
11978     version = SSL_version(serverssl);
11979     if (version == TLS1_3_VERSION)
11980         version = TLS1_2_VERSION;
11981     dummyheader[2] = version & 0xff;
11982 
11983     /*
11984      * Send a dummy header. If we continued to read the body as well this
11985      * would fail with a bad record mac, but we're not going to go that far.
11986      */
11987     if (!TEST_true(BIO_write_ex(SSL_get_rbio(serverssl), dummyheader,
11988             sizeof(dummyheader), &written))
11989         || !TEST_size_t_eq(written, SSL3_RT_HEADER_LENGTH))
11990         goto end;
11991 
11992     if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)))
11993         goto end;
11994 
11995     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RB")
11996         || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read body"))
11997         goto end;
11998 
11999     testresult = 1;
12000 end:
12001     SSL_free(serverssl);
12002     SSL_free(clientssl);
12003     SSL_CTX_free(sctx);
12004     SSL_CTX_free(cctx);
12005     return testresult;
12006 }
12007 
12008 /*
12009  * Force a write retry during handshaking. We test various combinations of
12010  * scenarios. We test a large certificate message which will fill the buffering
12011  * BIO used in the handshake. We try with client auth on and off. Finally we
12012  * also try a BIO that indicates retry via a 0 return. BIO_write() is documented
12013  * to indicate retry via -1 - but sometimes BIOs don't do that.
12014  *
12015  * Test 0: Standard certificate message
12016  * Test 1: Large certificate message
12017  * Test 2: Standard cert, verify peer
12018  * Test 3: Large cert, verify peer
12019  * Test 4: Standard cert, BIO returns 0 on retry
12020  * Test 5: Large cert, BIO returns 0 on retry
12021  * Test 6: Standard cert, verify peer, BIO returns 0 on retry
12022  * Test 7: Large cert, verify peer, BIO returns 0 on retry
12023  * Test 8-15: Repeat of above with TLSv1.2
12024  */
12025 static int test_handshake_retry(int idx)
12026 {
12027     SSL_CTX *cctx = NULL, *sctx = NULL;
12028     SSL *clientssl = NULL, *serverssl = NULL;
12029     int testresult = 0;
12030     BIO *tmp = NULL, *bretry = BIO_new(bio_s_always_retry());
12031     int maxversion = 0;
12032 
12033     if (!TEST_ptr(bretry))
12034         goto end;
12035 
12036 #ifndef OPENSSL_NO_TLS1_2
12037     if ((idx & 8) == 8)
12038         maxversion = TLS1_2_VERSION;
12039 #else
12040     if ((idx & 8) == 8)
12041         return TEST_skip("No TLSv1.2");
12042 #endif
12043 
12044     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12045             TLS_client_method(), 0, maxversion,
12046             &sctx, &cctx, cert, privkey)))
12047         goto end;
12048 
12049     /*
12050      * Add a large amount of data to fill the buffering BIO used by the SSL
12051      * object
12052      */
12053     if ((idx & 1) == 1 && !ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
12054         goto end;
12055 
12056     /*
12057      * We don't actually configure a client cert, but neither do we fail if one
12058      * isn't present.
12059      */
12060     if ((idx & 2) == 2)
12061         SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
12062 
12063     if ((idx & 4) == 4)
12064         set_always_retry_err_val(0);
12065 
12066     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
12067             &clientssl, NULL, NULL)))
12068         goto end;
12069 
12070     tmp = SSL_get_wbio(serverssl);
12071     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
12072         tmp = NULL;
12073         goto end;
12074     }
12075     SSL_set0_wbio(serverssl, bretry);
12076     bretry = NULL;
12077 
12078     if (!TEST_int_eq(SSL_connect(clientssl), -1))
12079         goto end;
12080 
12081     if (!TEST_int_eq(SSL_accept(serverssl), -1)
12082         || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
12083         goto end;
12084 
12085     /* Restore a BIO that will let the write succeed */
12086     SSL_set0_wbio(serverssl, tmp);
12087     tmp = NULL;
12088 
12089     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12090         goto end;
12091 
12092     testresult = 1;
12093 end:
12094     SSL_free(serverssl);
12095     SSL_free(clientssl);
12096     SSL_CTX_free(sctx);
12097     SSL_CTX_free(cctx);
12098     BIO_free(bretry);
12099     BIO_free(tmp);
12100     set_always_retry_err_val(-1);
12101     return testresult;
12102 }
12103 
12104 /*
12105  * Test that receiving retries when writing application data works as expected
12106  */
12107 static int test_data_retry(void)
12108 {
12109     SSL_CTX *cctx = NULL, *sctx = NULL;
12110     SSL *clientssl = NULL, *serverssl = NULL;
12111     int testresult = 0;
12112     unsigned char inbuf[1200], outbuf[1200];
12113     size_t i;
12114     BIO *tmp = NULL;
12115     BIO *bretry = BIO_new(bio_s_maybe_retry());
12116     size_t written, readbytes, totread = 0;
12117 
12118     if (!TEST_ptr(bretry))
12119         goto end;
12120 
12121     for (i = 0; i < sizeof(inbuf); i++)
12122         inbuf[i] = (unsigned char)(0xff & i);
12123     memset(outbuf, 0, sizeof(outbuf));
12124 
12125     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12126             TLS_client_method(), 0, 0, &sctx, &cctx,
12127             cert, privkey)))
12128         goto end;
12129 
12130     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12131             NULL)))
12132         goto end;
12133 
12134     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12135         goto end;
12136 
12137     /* Smallest possible max send fragment is 512 */
12138     if (!TEST_true(SSL_set_max_send_fragment(clientssl, 512)))
12139         goto end;
12140 
12141     tmp = SSL_get_wbio(clientssl);
12142     if (!TEST_ptr(tmp))
12143         goto end;
12144     if (!TEST_true(BIO_up_ref(tmp)))
12145         goto end;
12146     BIO_push(bretry, tmp);
12147     tmp = NULL;
12148     SSL_set0_wbio(clientssl, bretry);
12149     if (!BIO_up_ref(bretry)) {
12150         bretry = NULL;
12151         goto end;
12152     }
12153 
12154     for (i = 0; i < 3; i++) {
12155         /* We expect this call to make no progress and indicate retry */
12156         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12157             goto end;
12158         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
12159             goto end;
12160 
12161         /* Allow one write to progress, but the next one to signal retry */
12162         if (!TEST_true(BIO_ctrl(bretry, MAYBE_RETRY_CTRL_SET_RETRY_AFTER_CNT, 1,
12163                 NULL)))
12164             goto end;
12165 
12166         if (i == 2)
12167             break;
12168 
12169         /*
12170          * This call will hopefully make progress but will still indicate retry
12171          * because there is more data than will fit into a single record.
12172          */
12173         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12174             goto end;
12175         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
12176             goto end;
12177     }
12178 
12179     /* The final call should write the last chunk of data and succeed */
12180     if (!TEST_true(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12181         goto end;
12182     /* Read all the data available */
12183     while (SSL_read_ex(serverssl, outbuf + totread, sizeof(outbuf) - totread,
12184         &readbytes))
12185         totread += readbytes;
12186     if (!TEST_mem_eq(inbuf, sizeof(inbuf), outbuf, totread))
12187         goto end;
12188 
12189     testresult = 1;
12190 end:
12191     SSL_free(serverssl);
12192     SSL_free(clientssl);
12193     SSL_CTX_free(sctx);
12194     SSL_CTX_free(cctx);
12195     BIO_free_all(bretry);
12196     BIO_free(tmp);
12197     return testresult;
12198 }
12199 
12200 struct resume_servername_cb_data {
12201     int i;
12202     SSL_CTX *cctx;
12203     SSL_CTX *sctx;
12204     SSL_SESSION *sess;
12205     int recurse;
12206 };
12207 
12208 /*
12209  * Servername callback. We use it here to run another complete handshake using
12210  * the same session - and mark the session as not_resuamble at the end
12211  */
12212 static int resume_servername_cb(SSL *s, int *ad, void *arg)
12213 {
12214     struct resume_servername_cb_data *cbdata = arg;
12215     SSL *serverssl = NULL, *clientssl = NULL;
12216     int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
12217 
12218     if (cbdata->recurse)
12219         return SSL_TLSEXT_ERR_ALERT_FATAL;
12220 
12221     if ((cbdata->i % 3) != 1)
12222         return SSL_TLSEXT_ERR_OK;
12223 
12224     cbdata->recurse = 1;
12225 
12226     if (!TEST_true(create_ssl_objects(cbdata->sctx, cbdata->cctx, &serverssl,
12227             &clientssl, NULL, NULL))
12228         || !TEST_true(SSL_set_session(clientssl, cbdata->sess)))
12229         goto end;
12230 
12231     ERR_set_mark();
12232     /*
12233      * We expect this to fail - because the servername cb will fail. This will
12234      * mark the session as not_resumable.
12235      */
12236     if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) {
12237         ERR_clear_last_mark();
12238         goto end;
12239     }
12240     ERR_pop_to_mark();
12241 
12242     ret = SSL_TLSEXT_ERR_OK;
12243 end:
12244     SSL_free(serverssl);
12245     SSL_free(clientssl);
12246     cbdata->recurse = 0;
12247     return ret;
12248 }
12249 /*
12250  * Test multiple resumptions and cache size handling
12251  * Test 0: TLSv1.3 (max_early_data set)
12252  * Test 1: TLSv1.3 (SSL_OP_NO_TICKET set)
12253  * Test 2: TLSv1.3 (max_early_data and SSL_OP_NO_TICKET set)
12254  * Test 3: TLSv1.3 (SSL_OP_NO_TICKET, simultaneous resumes)
12255  * Test 4: TLSv1.2
12256  */
12257 static int test_multi_resume(int idx)
12258 {
12259     SSL_CTX *sctx = NULL, *cctx = NULL;
12260     SSL *serverssl = NULL, *clientssl = NULL;
12261     SSL_SESSION *sess = NULL;
12262     int max_version = TLS1_3_VERSION;
12263     int i, testresult = 0;
12264     struct resume_servername_cb_data cbdata;
12265 
12266 #if defined(OPENSSL_NO_TLS1_2)
12267     if (idx == 4)
12268         return TEST_skip("TLSv1.2 is disabled in this build");
12269 #else
12270     if (idx == 4)
12271         max_version = TLS1_2_VERSION;
12272 #endif
12273 #if defined(OSSL_NO_USABLE_TLS1_3)
12274     if (idx != 4)
12275         return TEST_skip("No usable TLSv1.3 in this build");
12276 #endif
12277 
12278     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12279             TLS_client_method(), TLS1_VERSION,
12280             max_version, &sctx, &cctx, cert,
12281             privkey)))
12282         goto end;
12283 
12284     /*
12285      * TLSv1.3 only uses a session cache if either max_early_data > 0 (used for
12286      * replay protection), or if SSL_OP_NO_TICKET is in use
12287      */
12288     if (idx == 0 || idx == 2) {
12289         if (!TEST_true(SSL_CTX_set_max_early_data(sctx, 1024)))
12290             goto end;
12291     }
12292     if (idx == 1 || idx == 2 || idx == 3)
12293         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
12294 
12295     SSL_CTX_sess_set_cache_size(sctx, 5);
12296 
12297     if (idx == 3) {
12298         SSL_CTX_set_tlsext_servername_callback(sctx, resume_servername_cb);
12299         SSL_CTX_set_tlsext_servername_arg(sctx, &cbdata);
12300         cbdata.cctx = cctx;
12301         cbdata.sctx = sctx;
12302         cbdata.recurse = 0;
12303     }
12304 
12305     for (i = 0; i < 30; i++) {
12306         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
12307                 NULL, NULL))
12308             || !TEST_true(SSL_set_session(clientssl, sess)))
12309             goto end;
12310 
12311         /*
12312          * Check simultaneous resumes. We pause the connection part way through
12313          * the handshake by (mis)using the servername_cb. The pause occurs after
12314          * session resumption has already occurred, but before any session
12315          * tickets have been issued. While paused we run another complete
12316          * handshake resuming the same session.
12317          */
12318         if (idx == 3) {
12319             cbdata.i = i;
12320             cbdata.sess = sess;
12321         }
12322 
12323         /*
12324          * Recreate a bug where dynamically changing the max_early_data value
12325          * can cause sessions in the session cache which cannot be deleted.
12326          */
12327         if ((idx == 0 || idx == 2) && (i % 3) == 2)
12328             SSL_set_max_early_data(serverssl, 0);
12329 
12330         if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12331             goto end;
12332 
12333         if (sess == NULL || (idx == 0 && (i % 3) == 2)) {
12334             if (!TEST_false(SSL_session_reused(clientssl)))
12335                 goto end;
12336         } else {
12337             if (!TEST_true(SSL_session_reused(clientssl)))
12338                 goto end;
12339         }
12340         SSL_SESSION_free(sess);
12341 
12342         /* Do a full handshake, followed by two resumptions */
12343         if ((i % 3) == 2) {
12344             sess = NULL;
12345         } else {
12346             if (!TEST_ptr((sess = SSL_get1_session(clientssl))))
12347                 goto end;
12348         }
12349 
12350         SSL_shutdown(clientssl);
12351         SSL_shutdown(serverssl);
12352         SSL_free(serverssl);
12353         SSL_free(clientssl);
12354         serverssl = clientssl = NULL;
12355     }
12356 
12357     /* We should never exceed the session cache size limit */
12358     if (!TEST_long_le(SSL_CTX_sess_number(sctx), 5))
12359         goto end;
12360 
12361     testresult = 1;
12362 end:
12363     SSL_free(serverssl);
12364     SSL_free(clientssl);
12365     SSL_CTX_free(sctx);
12366     SSL_CTX_free(cctx);
12367     SSL_SESSION_free(sess);
12368     return testresult;
12369 }
12370 
12371 static struct next_proto_st {
12372     int serverlen;
12373     unsigned char server[40];
12374     int clientlen;
12375     unsigned char client[40];
12376     int expected_ret;
12377     size_t selectedlen;
12378     unsigned char selected[40];
12379 } next_proto_tests[] = {
12380     { 4, { 3, 'a', 'b', 'c' },
12381         4, { 3, 'a', 'b', 'c' },
12382         OPENSSL_NPN_NEGOTIATED,
12383         3, { 'a', 'b', 'c' } },
12384     { 7, { 3, 'a', 'b', 'c', 2, 'a', 'b' },
12385         4, { 3, 'a', 'b', 'c' },
12386         OPENSSL_NPN_NEGOTIATED,
12387         3, { 'a', 'b', 'c' } },
12388     { 7, {
12389              2,
12390              'a',
12391              'b',
12392              3,
12393              'a',
12394              'b',
12395              'c',
12396          },
12397         4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } },
12398     { 4, { 3, 'a', 'b', 'c' }, 7, {
12399                                       3,
12400                                       'a',
12401                                       'b',
12402                                       'c',
12403                                       2,
12404                                       'a',
12405                                       'b',
12406                                   },
12407         OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } },
12408     { 4, { 3, 'a', 'b', 'c' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 7, { 2, 'b', 'c', 3, 'a', 'b', 'c' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 10, { 2, 'b', 'c', 3, 'a', 'b', 'c', 2, 'a', 'b' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'b', 'c', 'd' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 0, { 0 }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { -1, { 0 }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 0, { 0 }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }, { 4, { 3, 'a', 'b', 'c' }, -1, { 0 }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }, { 3, { 3, 'a', 'b', 'c' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 3, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }
12409 };
12410 
12411 static int test_select_next_proto(int idx)
12412 {
12413     struct next_proto_st *np = &next_proto_tests[idx];
12414     int ret = 0;
12415     unsigned char *out, *client, *server;
12416     unsigned char outlen;
12417     unsigned int clientlen, serverlen;
12418 
12419     if (np->clientlen == -1) {
12420         client = NULL;
12421         clientlen = 0;
12422     } else {
12423         client = np->client;
12424         clientlen = (unsigned int)np->clientlen;
12425     }
12426     if (np->serverlen == -1) {
12427         server = NULL;
12428         serverlen = 0;
12429     } else {
12430         server = np->server;
12431         serverlen = (unsigned int)np->serverlen;
12432     }
12433 
12434     if (!TEST_int_eq(SSL_select_next_proto(&out, &outlen, server, serverlen,
12435                          client, clientlen),
12436             np->expected_ret))
12437         goto err;
12438 
12439     if (np->selectedlen == 0) {
12440         if (!TEST_ptr_null(out) || !TEST_uchar_eq(outlen, 0))
12441             goto err;
12442     } else {
12443         if (!TEST_mem_eq(out, outlen, np->selected, np->selectedlen))
12444             goto err;
12445     }
12446 
12447     ret = 1;
12448 err:
12449     return ret;
12450 }
12451 
12452 static const unsigned char fooprot[] = { 3, 'f', 'o', 'o' };
12453 static const unsigned char barprot[] = { 3, 'b', 'a', 'r' };
12454 
12455 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
12456 static int npn_advert_cb(SSL *ssl, const unsigned char **out,
12457     unsigned int *outlen, void *arg)
12458 {
12459     int *idx = (int *)arg;
12460 
12461     switch (*idx) {
12462     default:
12463     case 0:
12464         *out = fooprot;
12465         *outlen = sizeof(fooprot);
12466         return SSL_TLSEXT_ERR_OK;
12467 
12468     case 1:
12469         *out = NULL;
12470         *outlen = 0;
12471         return SSL_TLSEXT_ERR_OK;
12472 
12473     case 2:
12474         return SSL_TLSEXT_ERR_NOACK;
12475     }
12476 }
12477 
12478 static int npn_select_cb(SSL *s, unsigned char **out, unsigned char *outlen,
12479     const unsigned char *in, unsigned int inlen, void *arg)
12480 {
12481     int *idx = (int *)arg;
12482 
12483     switch (*idx) {
12484     case 0:
12485     case 1:
12486         *out = (unsigned char *)(fooprot + 1);
12487         *outlen = *fooprot;
12488         return SSL_TLSEXT_ERR_OK;
12489 
12490     case 3:
12491         *out = (unsigned char *)(barprot + 1);
12492         *outlen = *barprot;
12493         return SSL_TLSEXT_ERR_OK;
12494 
12495     case 4:
12496         *outlen = 0;
12497         return SSL_TLSEXT_ERR_OK;
12498 
12499     default:
12500     case 2:
12501         return SSL_TLSEXT_ERR_ALERT_FATAL;
12502     }
12503 }
12504 
12505 /*
12506  * Test the NPN callbacks
12507  * Test 0: advert = foo, select = foo
12508  * Test 1: advert = <empty>, select = foo
12509  * Test 2: no advert
12510  * Test 3: advert = foo, select = bar
12511  * Test 4: advert = foo, select = <empty> (should fail)
12512  */
12513 static int test_npn(int idx)
12514 {
12515     SSL_CTX *sctx = NULL, *cctx = NULL;
12516     SSL *serverssl = NULL, *clientssl = NULL;
12517     int testresult = 0;
12518 
12519     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12520             TLS_client_method(), 0, TLS1_2_VERSION,
12521             &sctx, &cctx, cert, privkey)))
12522         goto end;
12523 
12524     SSL_CTX_set_next_protos_advertised_cb(sctx, npn_advert_cb, &idx);
12525     SSL_CTX_set_next_proto_select_cb(cctx, npn_select_cb, &idx);
12526 
12527     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12528             NULL)))
12529         goto end;
12530 
12531     if (idx == 4) {
12532         /* We don't allow empty selection of NPN, so this should fail */
12533         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12534                 SSL_ERROR_NONE)))
12535             goto end;
12536     } else {
12537         const unsigned char *prot;
12538         unsigned int protlen;
12539 
12540         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12541                 SSL_ERROR_NONE)))
12542             goto end;
12543 
12544         SSL_get0_next_proto_negotiated(serverssl, &prot, &protlen);
12545         switch (idx) {
12546         case 0:
12547         case 1:
12548             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12549                 goto end;
12550             break;
12551         case 2:
12552             if (!TEST_uint_eq(protlen, 0))
12553                 goto end;
12554             break;
12555         case 3:
12556             if (!TEST_mem_eq(prot, protlen, barprot + 1, *barprot))
12557                 goto end;
12558             break;
12559         default:
12560             TEST_error("Should not get here");
12561             goto end;
12562         }
12563     }
12564 
12565     testresult = 1;
12566 end:
12567     SSL_free(serverssl);
12568     SSL_free(clientssl);
12569     SSL_CTX_free(sctx);
12570     SSL_CTX_free(cctx);
12571 
12572     return testresult;
12573 }
12574 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) */
12575 
12576 static int alpn_select_cb2(SSL *ssl, const unsigned char **out,
12577     unsigned char *outlen, const unsigned char *in,
12578     unsigned int inlen, void *arg)
12579 {
12580     int *idx = (int *)arg;
12581 
12582     switch (*idx) {
12583     case 0:
12584         *out = (unsigned char *)(fooprot + 1);
12585         *outlen = *fooprot;
12586         return SSL_TLSEXT_ERR_OK;
12587 
12588     case 2:
12589         *out = (unsigned char *)(barprot + 1);
12590         *outlen = *barprot;
12591         return SSL_TLSEXT_ERR_OK;
12592 
12593     case 3:
12594         *outlen = 0;
12595         return SSL_TLSEXT_ERR_OK;
12596 
12597     default:
12598     case 1:
12599         return SSL_TLSEXT_ERR_ALERT_FATAL;
12600     }
12601     return 0;
12602 }
12603 
12604 /*
12605  * Test the ALPN callbacks
12606  * Test 0: client = foo, select = foo
12607  * Test 1: client = <empty>, select = none
12608  * Test 2: client = foo, select = bar (should fail)
12609  * Test 3: client = foo, select = <empty> (should fail)
12610  */
12611 static int test_alpn(int idx)
12612 {
12613     SSL_CTX *sctx = NULL, *cctx = NULL;
12614     SSL *serverssl = NULL, *clientssl = NULL;
12615     int testresult = 0;
12616     const unsigned char *prots = fooprot;
12617     unsigned int protslen = sizeof(fooprot);
12618 
12619     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12620             TLS_client_method(), 0, 0,
12621             &sctx, &cctx, cert, privkey)))
12622         goto end;
12623 
12624     SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb2, &idx);
12625 
12626     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12627             NULL)))
12628         goto end;
12629 
12630     if (idx == 1) {
12631         prots = NULL;
12632         protslen = 0;
12633     }
12634 
12635     /* SSL_set_alpn_protos returns 0 for success! */
12636     if (!TEST_false(SSL_set_alpn_protos(clientssl, prots, protslen)))
12637         goto end;
12638 
12639     if (idx == 2 || idx == 3) {
12640         /* We don't allow empty selection of NPN, so this should fail */
12641         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12642                 SSL_ERROR_NONE)))
12643             goto end;
12644     } else {
12645         const unsigned char *prot;
12646         unsigned int protlen;
12647 
12648         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12649                 SSL_ERROR_NONE)))
12650             goto end;
12651 
12652         SSL_get0_alpn_selected(clientssl, &prot, &protlen);
12653         switch (idx) {
12654         case 0:
12655             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12656                 goto end;
12657             break;
12658         case 1:
12659             if (!TEST_uint_eq(protlen, 0))
12660                 goto end;
12661             break;
12662         default:
12663             TEST_error("Should not get here");
12664             goto end;
12665         }
12666     }
12667 
12668     testresult = 1;
12669 end:
12670     SSL_free(serverssl);
12671     SSL_free(clientssl);
12672     SSL_CTX_free(sctx);
12673     SSL_CTX_free(cctx);
12674 
12675     return testresult;
12676 }
12677 
12678 #if !defined(OSSL_NO_USABLE_TLS1_3)
12679 struct quic_tls_test_data {
12680     struct quic_tls_test_data *peer;
12681     uint32_t renc_level;
12682     uint32_t wenc_level;
12683     unsigned char rcd_data[4][2048];
12684     size_t rcd_data_len[4];
12685     unsigned char rsecret[3][48];
12686     size_t rsecret_len[3];
12687     unsigned char wsecret[3][48];
12688     size_t wsecret_len[3];
12689     unsigned char params[3];
12690     size_t params_len;
12691     int alert;
12692     int err;
12693     int forcefail;
12694     int sm_count;
12695 };
12696 
12697 static int clientquicdata = 0xff, serverquicdata = 0xfe;
12698 
12699 static int check_app_data(SSL *s)
12700 {
12701     int *data, *comparedata;
12702 
12703     /* Check app data works */
12704     data = (int *)SSL_get_app_data(s);
12705     comparedata = SSL_is_server(s) ? &serverquicdata : &clientquicdata;
12706 
12707     if (!TEST_true(comparedata == data))
12708         return 0;
12709 
12710     return 1;
12711 }
12712 
12713 static int crypto_send_cb(SSL *s, const unsigned char *buf, size_t buf_len,
12714     size_t *consumed, void *arg)
12715 {
12716     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12717     struct quic_tls_test_data *peer = data->peer;
12718     size_t max_len = sizeof(peer->rcd_data[data->wenc_level])
12719         - peer->rcd_data_len[data->wenc_level];
12720 
12721     if (!check_app_data(s)) {
12722         data->err = 1;
12723         return 0;
12724     }
12725 
12726     if (buf_len > max_len)
12727         buf_len = max_len;
12728 
12729     if (buf_len == 0) {
12730         *consumed = 0;
12731         return 1;
12732     }
12733 
12734     memcpy(peer->rcd_data[data->wenc_level]
12735             + peer->rcd_data_len[data->wenc_level],
12736         buf, buf_len);
12737     peer->rcd_data_len[data->wenc_level] += buf_len;
12738 
12739     *consumed = buf_len;
12740     return 1;
12741 }
12742 static int crypto_recv_rcd_cb(SSL *s, const unsigned char **buf,
12743     size_t *bytes_read, void *arg)
12744 {
12745     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12746 
12747     if (!check_app_data(s)) {
12748         data->err = 1;
12749         return 0;
12750     }
12751 
12752     *bytes_read = data->rcd_data_len[data->renc_level];
12753     *buf = data->rcd_data[data->renc_level];
12754     return 1;
12755 }
12756 
12757 static int crypto_release_rcd_cb(SSL *s, size_t bytes_read, void *arg)
12758 {
12759     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12760 
12761     if (!check_app_data(s)) {
12762         data->err = 1;
12763         return 0;
12764     }
12765 
12766     /* See if we need to force a failure in this callback */
12767     if (data->forcefail) {
12768         data->forcefail = 0;
12769         data->err = 1;
12770         return 0;
12771     }
12772 
12773     if (!TEST_size_t_eq(bytes_read, data->rcd_data_len[data->renc_level])
12774         || !TEST_size_t_gt(bytes_read, 0)) {
12775         data->err = 1;
12776         return 0;
12777     }
12778     data->rcd_data_len[data->renc_level] = 0;
12779 
12780     return 1;
12781 }
12782 
12783 struct secret_yield_entry {
12784     uint8_t recorded;
12785     int prot_level;
12786     int direction;
12787     int sm_generation;
12788     SSL *ssl;
12789 };
12790 
12791 static struct secret_yield_entry secret_history[16];
12792 static int secret_history_idx = 0;
12793 /*
12794  * Note, this enum needs to match the direction values passed
12795  * to yield_secret_cb
12796  */
12797 typedef enum {
12798     LAST_DIR_READ = 0,
12799     LAST_DIR_WRITE = 1,
12800     LAST_DIR_UNSET = 2
12801 } last_dir_history_state;
12802 
12803 static int check_secret_history(SSL *s)
12804 {
12805     int i;
12806     int ret = 0;
12807     last_dir_history_state last_state = LAST_DIR_UNSET;
12808     int last_prot_level = 0;
12809     int last_generation = 0;
12810 
12811     TEST_info("Checking history for %p\n", (void *)s);
12812     for (i = 0; secret_history[i].recorded == 1; i++) {
12813         if (secret_history[i].ssl != s)
12814             continue;
12815         TEST_info("Got %s(%d) secret for level %d, last level %d, last state %d, gen %d\n",
12816             secret_history[i].direction == 1 ? "Write" : "Read", secret_history[i].direction,
12817             secret_history[i].prot_level, last_prot_level, last_state,
12818             secret_history[i].sm_generation);
12819 
12820         if (last_state == LAST_DIR_UNSET) {
12821             last_prot_level = secret_history[i].prot_level;
12822             last_state = secret_history[i].direction;
12823             last_generation = secret_history[i].sm_generation;
12824             continue;
12825         }
12826 
12827         switch (secret_history[i].direction) {
12828         case 1:
12829             /*
12830              * write case
12831              * NOTE: There is an odd corner case here.  It may occur that
12832              * in a single iteration of the state machine, the read key is yielded
12833              * prior to the write key for the same level.  This is undesirable
12834              * for quic, but it is ok, as the general implementation of every 3rd
12835              * party quic stack while preferring write keys before read, allows
12836              * for read before write if both keys are yielded in the same call
12837              * to SSL_do_handshake, as the tls adaptation code for that quic stack
12838              * can then cache keys until both are available, so we allow read before
12839              * write here iff they occur in the same iteration of SSL_do_handshake
12840              * as represented by the recorded sm_generation value.
12841              */
12842             if (last_prot_level == secret_history[i].prot_level
12843                 && last_state == LAST_DIR_READ) {
12844                 if (last_generation == secret_history[i].sm_generation) {
12845                     TEST_info("Read before write key in same SSL state machine iteration is ok");
12846                 } else {
12847                     TEST_error("Got read key before write key");
12848                     goto end;
12849                 }
12850             }
12851             /* FALLTHROUGH */
12852         case 0:
12853             /*
12854              * Read case
12855              */
12856             break;
12857         default:
12858             TEST_error("Unknown direction");
12859             goto end;
12860         }
12861         last_prot_level = secret_history[i].prot_level;
12862         last_state = secret_history[i].direction;
12863         last_generation = secret_history[i].sm_generation;
12864     }
12865 
12866     ret = 1;
12867 end:
12868     return ret;
12869 }
12870 
12871 static int yield_secret_cb(SSL *s, uint32_t prot_level, int direction,
12872     const unsigned char *secret, size_t secret_len,
12873     void *arg)
12874 {
12875     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12876 
12877     if (!check_app_data(s))
12878         goto err;
12879 
12880     if (prot_level < OSSL_RECORD_PROTECTION_LEVEL_EARLY
12881         || prot_level > OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
12882         goto err;
12883 
12884     switch (direction) {
12885     case 0: /* read */
12886         if (!TEST_size_t_le(secret_len, sizeof(data->rsecret)))
12887             goto err;
12888         data->renc_level = prot_level;
12889         memcpy(data->rsecret[prot_level - 1], secret, secret_len);
12890         data->rsecret_len[prot_level - 1] = secret_len;
12891         break;
12892 
12893     case 1: /* write */
12894         if (!TEST_size_t_le(secret_len, sizeof(data->wsecret)))
12895             goto err;
12896         data->wenc_level = prot_level;
12897         memcpy(data->wsecret[prot_level - 1], secret, secret_len);
12898         data->wsecret_len[prot_level - 1] = secret_len;
12899         break;
12900 
12901     default:
12902         goto err;
12903     }
12904 
12905     secret_history[secret_history_idx].direction = direction;
12906     secret_history[secret_history_idx].prot_level = (int)prot_level;
12907     secret_history[secret_history_idx].recorded = 1;
12908     secret_history[secret_history_idx].ssl = s;
12909     secret_history[secret_history_idx].sm_generation = data->sm_count;
12910     secret_history_idx++;
12911     return 1;
12912 err:
12913     data->err = 1;
12914     return 0;
12915 }
12916 
12917 static int yield_secret_cb_fail(SSL *s, uint32_t prot_level, int direction,
12918     const unsigned char *secret, size_t secret_len,
12919     void *arg)
12920 {
12921     (void)s;
12922     (void)prot_level;
12923     (void)direction;
12924     (void)secret;
12925     (void)secret_len;
12926     (void)arg;
12927     /*
12928      * This callback is to test double free in quic tls
12929      */
12930     return 0;
12931 }
12932 
12933 static int got_transport_params_cb(SSL *s, const unsigned char *params,
12934     size_t params_len,
12935     void *arg)
12936 {
12937     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12938 
12939     if (!check_app_data(s)) {
12940         data->err = 1;
12941         return 0;
12942     }
12943 
12944     if (!TEST_size_t_le(params_len, sizeof(data->params))) {
12945         data->err = 1;
12946         return 0;
12947     }
12948 
12949     memcpy(data->params, params, params_len);
12950     data->params_len = params_len;
12951 
12952     return 1;
12953 }
12954 
12955 static int alert_cb(SSL *s, unsigned char alert_code, void *arg)
12956 {
12957     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12958 
12959     if (!check_app_data(s)) {
12960         data->err = 1;
12961         return 0;
12962     }
12963 
12964     data->alert = 1;
12965     return 1;
12966 }
12967 
12968 /*
12969  * Test the QUIC TLS API
12970  * Test 0: Normal run
12971  * Test 1: Force a failure
12972  * Test 3: Use a CCM based ciphersuite
12973  * Test 4: fail yield_secret_cb to see double free
12974  * Test 5: Normal run with SNI
12975  */
12976 static int test_quic_tls(int idx)
12977 {
12978     SSL_CTX *sctx = NULL, *sctx2 = NULL, *cctx = NULL;
12979     SSL *serverssl = NULL, *clientssl = NULL;
12980     int testresult = 0;
12981     OSSL_DISPATCH qtdis[] = {
12982         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb },
12983         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD,
12984             (void (*)(void))crypto_recv_rcd_cb },
12985         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD,
12986             (void (*)(void))crypto_release_rcd_cb },
12987         { OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET,
12988             (void (*)(void))yield_secret_cb },
12989         { OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS,
12990             (void (*)(void))got_transport_params_cb },
12991         { OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb },
12992         { 0, NULL }
12993     };
12994     struct quic_tls_test_data sdata, cdata;
12995     const unsigned char cparams[] = {
12996         0xff, 0x01, 0x00
12997     };
12998     const unsigned char sparams[] = {
12999         0xfe, 0x01, 0x00
13000     };
13001     int i;
13002 
13003     if (idx == 4)
13004         qtdis[3].function = (void (*)(void))yield_secret_cb_fail;
13005 
13006     snicb = 0;
13007     memset(secret_history, 0, sizeof(secret_history));
13008     secret_history_idx = 0;
13009     memset(&sdata, 0, sizeof(sdata));
13010     memset(&cdata, 0, sizeof(cdata));
13011     sdata.peer = &cdata;
13012     cdata.peer = &sdata;
13013     if (idx == 1)
13014         sdata.forcefail = 1;
13015 
13016     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13017             TLS_client_method(), TLS1_3_VERSION, 0,
13018             &sctx, &cctx, cert, privkey)))
13019         goto end;
13020 
13021     if (idx == 5) {
13022         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
13023                 TLS1_3_VERSION, 0,
13024                 &sctx2, NULL, cert, privkey)))
13025             goto end;
13026 
13027         /* Set up SNI */
13028         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
13029             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
13030             goto end;
13031     }
13032 
13033     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13034             NULL)))
13035         goto end;
13036 
13037     /* Reset the BIOs we set in create_ssl_objects. We should not need them */
13038     SSL_set_bio(serverssl, NULL, NULL);
13039     SSL_set_bio(clientssl, NULL, NULL);
13040 
13041     if (idx == 2) {
13042         if (!TEST_true(SSL_set_ciphersuites(serverssl, "TLS_AES_128_CCM_SHA256"))
13043             || !TEST_true(SSL_set_ciphersuites(clientssl, "TLS_AES_128_CCM_SHA256")))
13044             goto end;
13045     }
13046 
13047     if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata))
13048         || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata)))
13049         goto end;
13050 
13051     if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata))
13052         || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata))
13053         || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams,
13054             sizeof(cparams)))
13055         || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams,
13056             sizeof(sparams))))
13057         goto end;
13058 
13059     if (idx != 1 && idx != 4) {
13060         if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
13061                 &cdata.sm_count, &sdata.sm_count)))
13062             goto end;
13063     } else {
13064         /* We expect this connection to fail */
13065         if (!TEST_false(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
13066                 &cdata.sm_count, &sdata.sm_count)))
13067             goto end;
13068         testresult = 1;
13069         sdata.err = 0;
13070         goto end;
13071     }
13072 
13073     /* We should have had the SNI callback called exactly once */
13074     if (idx == 5) {
13075         if (!TEST_int_eq(snicb, 1))
13076             goto end;
13077     }
13078 
13079     /* Check no problems during the handshake */
13080     if (!TEST_false(sdata.alert)
13081         || !TEST_false(cdata.alert)
13082         || !TEST_false(sdata.err)
13083         || !TEST_false(cdata.err))
13084         goto end;
13085 
13086     /* Check the secrets all match */
13087     for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1;
13088         i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION;
13089         i++) {
13090         if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i],
13091                 cdata.rsecret[i], cdata.rsecret_len[i]))
13092             goto end;
13093     }
13094 
13095     /*
13096      * Check that our secret history yields write secrets before read secrets
13097      */
13098     if (!TEST_int_eq(check_secret_history(serverssl), 1))
13099         goto end;
13100     if (!TEST_int_eq(check_secret_history(clientssl), 1))
13101         goto end;
13102 
13103     /* Check the transport params */
13104     if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams))
13105         || !TEST_mem_eq(cdata.params, cdata.params_len, sparams,
13106             sizeof(sparams)))
13107         goto end;
13108 
13109     /* Check the encryption levels are what we expect them to be */
13110     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13111         || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13112         || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13113         || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION))
13114         goto end;
13115 
13116     testresult = 1;
13117 end:
13118     SSL_free(serverssl);
13119     SSL_free(clientssl);
13120     SSL_CTX_free(sctx2);
13121     SSL_CTX_free(sctx);
13122     SSL_CTX_free(cctx);
13123 
13124     /* Check that we didn't suddenly hit an unexpected failure during cleanup */
13125     if (!TEST_false(sdata.err) || !TEST_false(cdata.err))
13126         testresult = 0;
13127 
13128     return testresult;
13129 }
13130 
13131 static void assert_no_end_of_early_data(int write_p, int version, int content_type,
13132     const void *buf, size_t msglen, SSL *ssl, void *arg)
13133 {
13134     const unsigned char *msg = buf;
13135 
13136     if (content_type == SSL3_RT_HANDSHAKE && msg[0] == SSL3_MT_END_OF_EARLY_DATA)
13137         end_of_early_data = 1;
13138 }
13139 
13140 static int test_quic_tls_early_data(void)
13141 {
13142     SSL_CTX *sctx = NULL, *cctx = NULL;
13143     SSL *serverssl = NULL, *clientssl = NULL;
13144     int testresult = 0;
13145     SSL_SESSION *sess = NULL;
13146     const OSSL_DISPATCH qtdis[] = {
13147         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb },
13148         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD,
13149             (void (*)(void))crypto_recv_rcd_cb },
13150         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD,
13151             (void (*)(void))crypto_release_rcd_cb },
13152         { OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET,
13153             (void (*)(void))yield_secret_cb },
13154         { OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS,
13155             (void (*)(void))got_transport_params_cb },
13156         { OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb },
13157         { 0, NULL }
13158     };
13159     struct quic_tls_test_data sdata, cdata;
13160     const unsigned char cparams[] = {
13161         0xff, 0x01, 0x00
13162     };
13163     const unsigned char sparams[] = {
13164         0xfe, 0x01, 0x00
13165     };
13166     int i;
13167 
13168     memset(secret_history, 0, sizeof(secret_history));
13169     secret_history_idx = 0;
13170     memset(&sdata, 0, sizeof(sdata));
13171     memset(&cdata, 0, sizeof(cdata));
13172     sdata.peer = &cdata;
13173     cdata.peer = &sdata;
13174     end_of_early_data = 0;
13175 
13176     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13177             TLS_client_method(), TLS1_3_VERSION, 0,
13178             &sctx, &cctx, cert, privkey)))
13179         goto end;
13180 
13181     SSL_CTX_set_max_early_data(sctx, 0xffffffff);
13182     SSL_CTX_set_max_early_data(cctx, 0xffffffff);
13183 
13184     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13185             NULL)))
13186         goto end;
13187 
13188     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13189         goto end;
13190 
13191     sess = SSL_get1_session(clientssl);
13192     SSL_shutdown(clientssl);
13193     SSL_shutdown(serverssl);
13194     SSL_free(serverssl);
13195     SSL_free(clientssl);
13196     serverssl = clientssl = NULL;
13197 
13198     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
13199             &clientssl, NULL, NULL))
13200         || !TEST_true(SSL_set_session(clientssl, sess)))
13201         goto end;
13202 
13203     /* Reset the BIOs we set in create_ssl_objects. We should not need them */
13204     SSL_set_bio(serverssl, NULL, NULL);
13205     SSL_set_bio(clientssl, NULL, NULL);
13206 
13207     if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata))
13208         || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata)))
13209         goto end;
13210 
13211     if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata))
13212         || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata))
13213         || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams,
13214             sizeof(cparams)))
13215         || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams,
13216             sizeof(sparams))))
13217         goto end;
13218 
13219     /*
13220      * Reset our secret history so we get the record of the second connection
13221      */
13222     memset(secret_history, 0, sizeof(secret_history));
13223     secret_history_idx = 0;
13224 
13225     SSL_set_quic_tls_early_data_enabled(serverssl, 1);
13226     SSL_set_quic_tls_early_data_enabled(clientssl, 1);
13227 
13228     SSL_set_msg_callback(serverssl, assert_no_end_of_early_data);
13229     SSL_set_msg_callback(clientssl, assert_no_end_of_early_data);
13230 
13231     if (!TEST_int_eq(SSL_connect(clientssl), -1)
13232         || !TEST_int_eq(SSL_accept(serverssl), -1)
13233         || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED)
13234         || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_READ)
13235         || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_READ))
13236         goto end;
13237 
13238     /* Check the encryption levels are what we expect them to be */
13239     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE)
13240         || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13241         || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
13242         || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_EARLY))
13243         goto end;
13244 
13245     sdata.sm_count = 0;
13246     cdata.sm_count = 0;
13247     if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
13248             &cdata.sm_count, &sdata.sm_count)))
13249         goto end;
13250 
13251     /* Check no problems during the handshake */
13252     if (!TEST_false(sdata.alert)
13253         || !TEST_false(cdata.alert)
13254         || !TEST_false(sdata.err)
13255         || !TEST_false(cdata.err))
13256         goto end;
13257 
13258     /* Check the secrets all match */
13259     for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1;
13260         i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION;
13261         i++) {
13262         if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i],
13263                 cdata.rsecret[i], cdata.rsecret_len[i]))
13264             goto end;
13265     }
13266 
13267     if (!TEST_int_eq(check_secret_history(serverssl), 1))
13268         goto end;
13269     if (!TEST_int_eq(check_secret_history(clientssl), 1))
13270         goto end;
13271 
13272     /* Check the transport params */
13273     if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams))
13274         || !TEST_mem_eq(cdata.params, cdata.params_len, sparams,
13275             sizeof(sparams)))
13276         goto end;
13277 
13278     /* Check the encryption levels are what we expect them to be */
13279     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13280         || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13281         || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13282         || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION))
13283         goto end;
13284 
13285     /* Check there is no EndOfEearlyData in handshake */
13286     if (!TEST_int_eq(end_of_early_data, 0))
13287         goto end;
13288 
13289     testresult = 1;
13290 end:
13291     SSL_SESSION_free(sess);
13292     SSL_SESSION_free(clientpsk);
13293     SSL_SESSION_free(serverpsk);
13294     clientpsk = serverpsk = NULL;
13295     SSL_free(serverssl);
13296     SSL_free(clientssl);
13297     SSL_CTX_free(sctx);
13298     SSL_CTX_free(cctx);
13299 
13300     return testresult;
13301 }
13302 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) */
13303 
13304 static int test_no_renegotiation(int idx)
13305 {
13306     SSL_CTX *sctx = NULL, *cctx = NULL;
13307     SSL *serverssl = NULL, *clientssl = NULL;
13308     int testresult = 0, ret;
13309     int max_proto;
13310     const SSL_METHOD *sm, *cm;
13311     unsigned char buf[5];
13312 
13313     if (idx == 0) {
13314 #ifndef OPENSSL_NO_TLS1_2
13315         max_proto = TLS1_2_VERSION;
13316         sm = TLS_server_method();
13317         cm = TLS_client_method();
13318 #else
13319         return TEST_skip("TLSv1.2 is disabled in this build");
13320 #endif
13321     } else {
13322 #ifndef OPENSSL_NO_DTLS1_2
13323         max_proto = DTLS1_2_VERSION;
13324         sm = DTLS_server_method();
13325         cm = DTLS_client_method();
13326 #else
13327         return TEST_skip("DTLSv1.2 is disabled in this build");
13328 #endif
13329     }
13330     if (!TEST_true(create_ssl_ctx_pair(libctx, sm, cm, 0, max_proto,
13331             &sctx, &cctx, cert, privkey)))
13332         goto end;
13333 
13334     SSL_CTX_set_options(sctx, SSL_OP_NO_RENEGOTIATION);
13335 
13336     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13337             NULL)))
13338         goto end;
13339 
13340     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13341         goto end;
13342 
13343     if (!TEST_true(SSL_renegotiate(clientssl))
13344         || !TEST_int_le(ret = SSL_connect(clientssl), 0)
13345         || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_WANT_READ))
13346         goto end;
13347 
13348     /*
13349      * We've not sent any application data, so we expect this to fail. It should
13350      * also read the renegotiation attempt, and send back a no_renegotiation
13351      * warning alert because we have renegotiation disabled.
13352      */
13353     if (!TEST_int_le(ret = SSL_read(serverssl, buf, sizeof(buf)), 0))
13354         goto end;
13355     if (!TEST_int_eq(SSL_get_error(serverssl, ret), SSL_ERROR_WANT_READ))
13356         goto end;
13357 
13358     /*
13359      * The client should now see the no_renegotiation warning and fail the
13360      * connection
13361      */
13362     if (!TEST_int_le(ret = SSL_connect(clientssl), 0)
13363         || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_SSL)
13364         || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_NO_RENEGOTIATION))
13365         goto end;
13366 
13367     testresult = 1;
13368 end:
13369     SSL_free(serverssl);
13370     SSL_free(clientssl);
13371     SSL_CTX_free(sctx);
13372     SSL_CTX_free(cctx);
13373 
13374     return testresult;
13375 }
13376 
13377 #if defined(DO_SSL_TRACE_TEST)
13378 /*
13379  * Tests that the SSL_trace() msg_callback works as expected with a PQ Groups.
13380  */
13381 static int test_ssl_trace(void)
13382 {
13383     SSL_CTX *sctx = NULL, *cctx = NULL;
13384     SSL *serverssl = NULL, *clientssl = NULL;
13385     int testresult = 0;
13386     BIO *bio = NULL;
13387     char *reffile = NULL;
13388     char *grouplist = "MLKEM512:MLKEM768:MLKEM1024:X25519MLKEM768:SecP256r1MLKEM768"
13389                       ":SecP384r1MLKEM1024:secp521r1:secp384r1:secp256r1";
13390 
13391     if (!fips_provider_version_ge(libctx, 3, 5, 0))
13392         return TEST_skip("FIPS provider does not support MLKEM algorithms");
13393 
13394     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13395             TLS_client_method(),
13396             TLS1_3_VERSION, TLS1_3_VERSION,
13397             &sctx, &cctx, cert, privkey))
13398         || !TEST_ptr(bio = BIO_new(BIO_s_mem()))
13399         || !TEST_true(SSL_CTX_set1_groups_list(sctx, grouplist))
13400         || !TEST_true(SSL_CTX_set1_groups_list(cctx, grouplist))
13401         || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
13402             "TLS_AES_128_GCM_SHA256"))
13403         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
13404             "TLS_AES_128_GCM_SHA256"))
13405 #ifdef SSL_OP_LEGACY_EC_POINT_FORMATS
13406         || !TEST_true(SSL_CTX_set_options(cctx, SSL_OP_LEGACY_EC_POINT_FORMATS))
13407         || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_LEGACY_EC_POINT_FORMATS))
13408 #endif
13409         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
13410             NULL, NULL)))
13411         goto err;
13412 
13413     SSL_set_msg_callback(clientssl, SSL_trace);
13414     SSL_set_msg_callback_arg(clientssl, bio);
13415 
13416     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13417         goto err;
13418 
13419     /* Skip the comparison of the trace when the fips provider is used. */
13420     if (is_fips) {
13421         /* Check whether there was something written. */
13422         if (!TEST_int_gt(BIO_pending(bio), 0))
13423             goto err;
13424     } else {
13425 
13426 #ifdef OPENSSL_NO_ZLIB
13427         reffile = test_mk_file_path(datadir, "ssltraceref.txt");
13428 #else
13429         reffile = test_mk_file_path(datadir, "ssltraceref-zlib.txt");
13430 #endif
13431         if (!TEST_true(compare_with_reference_file(bio, reffile)))
13432             goto err;
13433     }
13434 
13435     testresult = 1;
13436 err:
13437     BIO_free(bio);
13438     SSL_free(serverssl);
13439     SSL_free(clientssl);
13440     SSL_CTX_free(sctx);
13441     SSL_CTX_free(cctx);
13442     OPENSSL_free(reffile);
13443 
13444     return testresult;
13445 }
13446 #endif
13447 
13448 /*
13449  * Test that SSL_CTX_set1_groups() when called with a list where the first
13450  * entry is unsupported, will send a key_share that uses the next usable entry.
13451  */
13452 static int test_ssl_set_groups_unsupported_keyshare(int idx)
13453 {
13454 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
13455     int testresult = 0;
13456     SSL_CTX *sctx = NULL, *cctx = NULL;
13457     SSL *serverssl = NULL, *clientssl = NULL;
13458     int client_groups[] = {
13459         NID_brainpoolP256r1tls13,
13460         NID_sect163k1,
13461         NID_secp384r1,
13462         NID_ffdhe2048,
13463     };
13464 
13465     switch (idx) {
13466     case 1:
13467         client_groups[0] = NID_id_tc26_gost_3410_2012_512_paramSetC;
13468         if (sizeof(unsigned long) == 4) {
13469             return TEST_skip("SSL_CTX_set1_groups() is broken on 32-bit systems with TLS"
13470                              " group IDs > 0x20, see https://github.com/openssl/openssl/issues/29196");
13471         }
13472         break;
13473     }
13474 
13475     if (!TEST_true(create_ssl_ctx_pair(libctx,
13476             TLS_server_method(),
13477             TLS_client_method(),
13478             0, 0,
13479             &sctx,
13480             &cctx,
13481             cert,
13482             privkey)))
13483         goto end;
13484 
13485     if (!TEST_true(SSL_CTX_set1_groups(cctx,
13486             client_groups,
13487             OSSL_NELEM(client_groups))))
13488         goto end;
13489 
13490     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13491             NULL)))
13492         goto end;
13493 
13494     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13495         goto end;
13496 
13497     testresult = 1;
13498 end:
13499     SSL_free(serverssl);
13500     SSL_free(clientssl);
13501     SSL_CTX_free(sctx);
13502     SSL_CTX_free(cctx);
13503 
13504     return testresult;
13505 #else /* !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH) */
13506     return TEST_skip("No EC and DH support.");
13507 #endif /* !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH) */
13508 }
13509 
13510 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config dhfile\n")
13511 
13512 int setup_tests(void)
13513 {
13514     char *modulename;
13515     char *configfile;
13516 
13517     libctx = OSSL_LIB_CTX_new();
13518     if (!TEST_ptr(libctx))
13519         return 0;
13520 
13521     defctxnull = OSSL_PROVIDER_load(NULL, "null");
13522 
13523     /*
13524      * Verify that the default and fips providers in the default libctx are not
13525      * available
13526      */
13527     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
13528         || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
13529         return 0;
13530 
13531     if (!test_skip_common_options()) {
13532         TEST_error("Error parsing test options\n");
13533         return 0;
13534     }
13535 
13536     if (!TEST_ptr(certsdir = test_get_argument(0))
13537         || !TEST_ptr(srpvfile = test_get_argument(1))
13538         || !TEST_ptr(tmpfilename = test_get_argument(2))
13539         || !TEST_ptr(modulename = test_get_argument(3))
13540         || !TEST_ptr(configfile = test_get_argument(4))
13541         || !TEST_ptr(dhfile = test_get_argument(5)))
13542         return 0;
13543 
13544     datadir = test_get_argument(6);
13545 
13546     if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
13547         return 0;
13548 
13549     /* Check we have the expected provider available */
13550     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
13551         return 0;
13552 
13553     /* Check the default provider is not available */
13554     if (strcmp(modulename, "default") != 0
13555         && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
13556         return 0;
13557 
13558     if (strcmp(modulename, "fips") == 0) {
13559         OSSL_PROVIDER *prov = NULL;
13560         OSSL_PARAM params[2];
13561 
13562         is_fips = 1;
13563 
13564         prov = OSSL_PROVIDER_load(libctx, "fips");
13565         if (prov != NULL) {
13566             /* Query the fips provider to check if the check ems option is enabled */
13567             params[0] = OSSL_PARAM_construct_int(OSSL_PROV_PARAM_TLS1_PRF_EMS_CHECK,
13568                 &fips_ems_check);
13569             params[1] = OSSL_PARAM_construct_end();
13570             OSSL_PROVIDER_get_params(prov, params);
13571             OSSL_PROVIDER_unload(prov);
13572         }
13573     }
13574 
13575     /*
13576      * We add, but don't load the test "tls-provider". We'll load it when we
13577      * need it.
13578      */
13579     if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider",
13580             tls_provider_init)))
13581         return 0;
13582 
13583     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
13584 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
13585         TEST_error("not supported in this build");
13586         return 0;
13587 #else
13588         int i, mcount, rcount, fcount;
13589 
13590         for (i = 0; i < 4; i++)
13591             test_export_key_mat(i);
13592         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
13593         test_printf_stdout("malloc %d realloc %d free %d\n",
13594             mcount, rcount, fcount);
13595         return 1;
13596 #endif
13597     }
13598 
13599     cert = test_mk_file_path(certsdir, "servercert.pem");
13600     if (cert == NULL)
13601         goto err;
13602 
13603     privkey = test_mk_file_path(certsdir, "serverkey.pem");
13604     if (privkey == NULL)
13605         goto err;
13606 
13607     cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
13608     if (cert2 == NULL)
13609         goto err;
13610 
13611     privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
13612     if (privkey2 == NULL)
13613         goto err;
13614 
13615     cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem");
13616     if (cert1024 == NULL)
13617         goto err;
13618 
13619     privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem");
13620     if (privkey1024 == NULL)
13621         goto err;
13622 
13623     cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem");
13624     if (cert3072 == NULL)
13625         goto err;
13626 
13627     privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem");
13628     if (privkey3072 == NULL)
13629         goto err;
13630 
13631     cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem");
13632     if (cert4096 == NULL)
13633         goto err;
13634 
13635     privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem");
13636     if (privkey4096 == NULL)
13637         goto err;
13638 
13639     cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem");
13640     if (cert8192 == NULL)
13641         goto err;
13642 
13643     privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem");
13644     if (privkey8192 == NULL)
13645         goto err;
13646 
13647     if (fips_ems_check) {
13648 #ifndef OPENSSL_NO_TLS1_2
13649         ADD_TEST(test_no_ems);
13650 #endif
13651         return 1;
13652     }
13653 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
13654 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
13655     ADD_ALL_TESTS(test_ktls, NUM_KTLS_TEST_CIPHERS * 4);
13656     ADD_ALL_TESTS(test_ktls_sendfile, NUM_KTLS_TEST_CIPHERS * 2);
13657 #endif
13658 #endif
13659     ADD_TEST(test_large_message_tls);
13660     ADD_TEST(test_large_message_tls_read_ahead);
13661 #ifndef OPENSSL_NO_DTLS
13662     ADD_TEST(test_large_message_dtls);
13663 #endif
13664     ADD_ALL_TESTS(test_large_app_data, 28);
13665     ADD_TEST(test_cleanse_plaintext);
13666 #ifndef OPENSSL_NO_OCSP
13667     ADD_TEST(test_tlsext_status_type);
13668 #endif
13669     ADD_TEST(test_session_with_only_int_cache);
13670     ADD_TEST(test_session_with_only_ext_cache);
13671     ADD_TEST(test_session_with_both_cache);
13672     ADD_TEST(test_session_wo_ca_names);
13673 #ifndef OSSL_NO_USABLE_TLS1_3
13674     ADD_ALL_TESTS(test_stateful_tickets, 3);
13675     ADD_ALL_TESTS(test_stateless_tickets, 3);
13676     ADD_TEST(test_psk_tickets);
13677     ADD_ALL_TESTS(test_extra_tickets, 6);
13678 #endif
13679     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
13680     ADD_TEST(test_ssl_bio_pop_next_bio);
13681     ADD_TEST(test_ssl_bio_pop_ssl_bio);
13682     ADD_TEST(test_ssl_bio_change_rbio);
13683     ADD_TEST(test_ssl_bio_change_wbio);
13684 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
13685     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
13686     ADD_TEST(test_keylog);
13687 #endif
13688 #ifndef OSSL_NO_USABLE_TLS1_3
13689     ADD_TEST(test_keylog_no_master_key);
13690 #endif
13691     ADD_TEST(test_client_cert_verify_cb);
13692     ADD_TEST(test_ssl_build_cert_chain);
13693     ADD_TEST(test_ssl_ctx_build_cert_chain);
13694 #ifndef OPENSSL_NO_TLS1_2
13695     ADD_TEST(test_client_hello_cb);
13696     ADD_TEST(test_no_ems);
13697     ADD_TEST(test_ccs_change_cipher);
13698 #endif
13699 #ifndef OSSL_NO_USABLE_TLS1_3
13700     ADD_ALL_TESTS(test_early_data_read_write, 6);
13701     /*
13702      * We don't do replay tests for external PSK. Replay protection isn't used
13703      * in that scenario.
13704      */
13705     ADD_ALL_TESTS(test_early_data_replay, 2);
13706     ADD_ALL_TESTS(test_early_data_skip, OSSL_NELEM(ciphersuites) * 3);
13707     ADD_ALL_TESTS(test_early_data_skip_hrr, OSSL_NELEM(ciphersuites) * 3);
13708     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, OSSL_NELEM(ciphersuites) * 3);
13709     ADD_ALL_TESTS(test_early_data_skip_abort, OSSL_NELEM(ciphersuites) * 3);
13710     ADD_ALL_TESTS(test_early_data_not_sent, 3);
13711     ADD_ALL_TESTS(test_early_data_psk, 8);
13712     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 7);
13713     ADD_ALL_TESTS(test_early_data_not_expected, 3);
13714 #ifndef OPENSSL_NO_TLS1_2
13715     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
13716 #endif
13717 #endif
13718 #ifndef OSSL_NO_USABLE_TLS1_3
13719     ADD_ALL_TESTS(test_set_ciphersuite, 10);
13720     ADD_TEST(test_ciphersuite_change);
13721     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
13722 #ifdef OPENSSL_NO_PSK
13723     ADD_ALL_TESTS(test_tls13_psk, 1);
13724 #else
13725     ADD_ALL_TESTS(test_tls13_psk, 4);
13726 #endif /* OPENSSL_NO_PSK */
13727 #ifndef OSSL_NO_USABLE_TLS1_3
13728     ADD_ALL_TESTS(test_tls13_no_dhe_kex, 8);
13729 #endif /* OSSL_NO_USABLE_TLS1_3 */
13730 #ifndef OPENSSL_NO_TLS1_2
13731     /* Test with both TLSv1.3 and 1.2 versions */
13732     ADD_ALL_TESTS(test_key_exchange, 21);
13733 #if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH)
13734     ADD_ALL_TESTS(test_negotiated_group,
13735         4 * (OSSL_NELEM(ecdhe_kexch_groups) + OSSL_NELEM(ffdhe_kexch_groups)));
13736 #endif
13737 #else
13738     /* Test with only TLSv1.3 versions */
13739     ADD_ALL_TESTS(test_key_exchange, 18);
13740 #endif
13741     ADD_ALL_TESTS(test_custom_exts, 6);
13742     ADD_TEST(test_stateless);
13743     ADD_TEST(test_pha_key_update);
13744 #else
13745     ADD_ALL_TESTS(test_custom_exts, 3);
13746 #endif
13747     ADD_ALL_TESTS(test_export_key_mat, 6);
13748 #ifndef OSSL_NO_USABLE_TLS1_3
13749     ADD_ALL_TESTS(test_export_key_mat_early, 3);
13750     ADD_TEST(test_key_update);
13751     ADD_ALL_TESTS(test_key_update_peer_in_write, 2);
13752     ADD_ALL_TESTS(test_key_update_peer_in_read, 2);
13753     ADD_ALL_TESTS(test_key_update_local_in_write, 2);
13754     ADD_ALL_TESTS(test_key_update_local_in_read, 2);
13755 #endif
13756     ADD_ALL_TESTS(test_ssl_clear, 8);
13757     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
13758 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
13759     ADD_ALL_TESTS(test_srp, 6);
13760 #endif
13761 #if !defined(OPENSSL_NO_COMP_ALG)
13762     /* Add compression case */
13763     ADD_ALL_TESTS(test_info_callback, 8);
13764 #else
13765     ADD_ALL_TESTS(test_info_callback, 6);
13766 #endif
13767     ADD_ALL_TESTS(test_ssl_pending, 2);
13768     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
13769     ADD_ALL_TESTS(test_ticket_callbacks, 20);
13770     ADD_ALL_TESTS(test_shutdown, 7);
13771     ADD_TEST(test_async_shutdown);
13772     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
13773     ADD_ALL_TESTS(test_cert_cb, 6);
13774     ADD_ALL_TESTS(test_client_cert_cb, 2);
13775     ADD_ALL_TESTS(test_ca_names, 3);
13776 #ifndef OPENSSL_NO_TLS1_2
13777     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
13778 #endif
13779     ADD_ALL_TESTS(test_servername, 10);
13780     ADD_TEST(test_unknown_sigalgs_groups);
13781 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM)
13782     ADD_TEST(test_configuration_of_groups);
13783 #endif
13784 #if !defined(OPENSSL_NO_EC) \
13785     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
13786     ADD_ALL_TESTS(test_sigalgs_available, 6);
13787 #endif
13788 #ifndef OPENSSL_NO_TLS1_3
13789     ADD_ALL_TESTS(test_pluggable_group, 2);
13790     ADD_ALL_TESTS(test_pluggable_signature, 6);
13791 #endif
13792 #ifndef OPENSSL_NO_TLS1_2
13793     ADD_TEST(test_ssl_dup);
13794     ADD_TEST(test_session_secret_cb);
13795 #ifndef OPENSSL_NO_DH
13796     ADD_ALL_TESTS(test_set_tmp_dh, 11);
13797     ADD_ALL_TESTS(test_dh_auto, 7);
13798 #endif
13799 #endif
13800 #ifndef OSSL_NO_USABLE_TLS1_3
13801     ADD_TEST(test_sni_tls13);
13802     ADD_ALL_TESTS(test_ticket_lifetime, 2);
13803 #endif
13804     ADD_TEST(test_inherit_verify_param);
13805     ADD_TEST(test_set_alpn);
13806     ADD_TEST(test_set_verify_cert_store_ssl_ctx);
13807     ADD_TEST(test_set_verify_cert_store_ssl);
13808     ADD_ALL_TESTS(test_session_timeout, 1);
13809 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
13810     ADD_ALL_TESTS(test_session_cache_overflow, 4);
13811 #endif
13812     ADD_TEST(test_load_dhfile);
13813 #ifndef OSSL_NO_USABLE_TLS1_3
13814     ADD_TEST(test_read_ahead_key_change);
13815     ADD_ALL_TESTS(test_tls13_record_padding, 6);
13816 #endif
13817 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
13818     ADD_ALL_TESTS(test_serverinfo_custom, 4);
13819 #endif
13820 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
13821     ADD_ALL_TESTS(test_pipelining, 7);
13822 #endif
13823     ADD_ALL_TESTS(test_version, 6);
13824     ADD_TEST(test_rstate_string);
13825     ADD_ALL_TESTS(test_handshake_retry, 16);
13826     ADD_TEST(test_data_retry);
13827     ADD_ALL_TESTS(test_multi_resume, 5);
13828     ADD_ALL_TESTS(test_select_next_proto, OSSL_NELEM(next_proto_tests));
13829 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
13830     ADD_ALL_TESTS(test_npn, 5);
13831 #endif
13832     ADD_ALL_TESTS(test_alpn, 4);
13833 #if !defined(OSSL_NO_USABLE_TLS1_3)
13834     ADD_ALL_TESTS(test_quic_tls, 6);
13835     ADD_TEST(test_quic_tls_early_data);
13836 #endif
13837     ADD_ALL_TESTS(test_no_renegotiation, 2);
13838 #if defined(DO_SSL_TRACE_TEST)
13839     if (datadir != NULL)
13840         ADD_TEST(test_ssl_trace);
13841 #endif
13842     ADD_ALL_TESTS(test_ssl_set_groups_unsupported_keyshare, 2);
13843     return 1;
13844 
13845 err:
13846     OPENSSL_free(cert);
13847     OPENSSL_free(privkey);
13848     OPENSSL_free(cert2);
13849     OPENSSL_free(privkey2);
13850     return 0;
13851 }
13852 
13853 void cleanup_tests(void)
13854 {
13855 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH)
13856     EVP_PKEY_free(tmp_dh_params);
13857 #endif
13858     OPENSSL_free(cert);
13859     OPENSSL_free(privkey);
13860     OPENSSL_free(cert2);
13861     OPENSSL_free(privkey2);
13862     OPENSSL_free(cert1024);
13863     OPENSSL_free(privkey1024);
13864     OPENSSL_free(cert3072);
13865     OPENSSL_free(privkey3072);
13866     OPENSSL_free(cert4096);
13867     OPENSSL_free(privkey4096);
13868     OPENSSL_free(cert8192);
13869     OPENSSL_free(privkey8192);
13870     bio_s_mempacket_test_free();
13871     bio_s_always_retry_free();
13872     bio_s_maybe_retry_free();
13873     OSSL_PROVIDER_unload(defctxnull);
13874     OSSL_LIB_CTX_free(libctx);
13875 }
13876