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