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