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