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