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