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