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