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