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