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