Simplify the EVP_PKEY_XXX_fromdata_XX methods.
[openssl.git] / test / sslapitest.c
1 /*
2  * Copyright 2016-2021 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
35 #include "helpers/ssltestlib.h"
36 #include "testutil.h"
37 #include "testutil/output.h"
38 #include "internal/nelem.h"
39 #include "internal/ktls.h"
40 #include "../ssl/ssl_local.h"
41
42 #undef OSSL_NO_USABLE_TLS1_3
43 #if defined(OPENSSL_NO_TLS1_3) \
44     || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH))
45 /*
46  * If we don't have ec or dh then there are no built-in groups that are usable
47  * with TLSv1.3
48  */
49 # define OSSL_NO_USABLE_TLS1_3
50 #endif
51
52 /* Defined in filterprov.c */
53 OSSL_provider_init_fn filter_provider_init;
54 int filter_provider_set_filter(int operation, const char *name);
55
56 /* Defined in tls-provider.c */
57 int tls_provider_init(const OSSL_CORE_HANDLE *handle,
58                       const OSSL_DISPATCH *in,
59                       const OSSL_DISPATCH **out,
60                       void **provctx);
61
62 static OSSL_LIB_CTX *libctx = NULL;
63 static OSSL_PROVIDER *defctxnull = NULL;
64
65 #ifndef OSSL_NO_USABLE_TLS1_3
66
67 static SSL_SESSION *clientpsk = NULL;
68 static SSL_SESSION *serverpsk = NULL;
69 static const char *pskid = "Identity";
70 static const char *srvid;
71
72 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
73                           size_t *idlen, SSL_SESSION **sess);
74 static int find_session_cb(SSL *ssl, const unsigned char *identity,
75                            size_t identity_len, SSL_SESSION **sess);
76
77 static int use_session_cb_cnt = 0;
78 static int find_session_cb_cnt = 0;
79
80 static SSL_SESSION *create_a_psk(SSL *ssl);
81 #endif
82
83 static char *certsdir = NULL;
84 static char *cert = NULL;
85 static char *privkey = NULL;
86 static char *cert2 = NULL;
87 static char *privkey2 = NULL;
88 static char *cert1024 = NULL;
89 static char *privkey1024 = NULL;
90 static char *cert3072 = NULL;
91 static char *privkey3072 = NULL;
92 static char *cert4096 = NULL;
93 static char *privkey4096 = NULL;
94 static char *cert8192 = NULL;
95 static char *privkey8192 = NULL;
96 static char *srpvfile = NULL;
97 static char *tmpfilename = NULL;
98
99 static int is_fips = 0;
100
101 #define LOG_BUFFER_SIZE 2048
102 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
103 static size_t server_log_buffer_index = 0;
104 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
105 static size_t client_log_buffer_index = 0;
106 static int error_writing_log = 0;
107
108 #ifndef OPENSSL_NO_OCSP
109 static const unsigned char orespder[] = "Dummy OCSP Response";
110 static int ocsp_server_called = 0;
111 static int ocsp_client_called = 0;
112
113 static int cdummyarg = 1;
114 static X509 *ocspcert = NULL;
115 #endif
116
117 #define NUM_EXTRA_CERTS 40
118 #define CLIENT_VERSION_LEN      2
119
120 /*
121  * This structure is used to validate that the correct number of log messages
122  * of various types are emitted when emitting secret logs.
123  */
124 struct sslapitest_log_counts {
125     unsigned int rsa_key_exchange_count;
126     unsigned int master_secret_count;
127     unsigned int client_early_secret_count;
128     unsigned int client_handshake_secret_count;
129     unsigned int server_handshake_secret_count;
130     unsigned int client_application_secret_count;
131     unsigned int server_application_secret_count;
132     unsigned int early_exporter_secret_count;
133     unsigned int exporter_secret_count;
134 };
135
136
137 static unsigned char serverinfov1[] = {
138     0xff, 0xff, /* Dummy extension type */
139     0x00, 0x01, /* Extension length is 1 byte */
140     0xff        /* Dummy extension data */
141 };
142
143 static unsigned char serverinfov2[] = {
144     0x00, 0x00, 0x00,
145     (unsigned char)(SSL_EXT_CLIENT_HELLO & 0xff), /* Dummy context - 4 bytes */
146     0xff, 0xff, /* Dummy extension type */
147     0x00, 0x01, /* Extension length is 1 byte */
148     0xff        /* Dummy extension data */
149 };
150
151 static int hostname_cb(SSL *s, int *al, void *arg)
152 {
153     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
154
155     if (hostname != NULL && (strcmp(hostname, "goodhost") == 0
156                              || strcmp(hostname, "altgoodhost") == 0))
157         return  SSL_TLSEXT_ERR_OK;
158
159     return SSL_TLSEXT_ERR_NOACK;
160 }
161
162 static void client_keylog_callback(const SSL *ssl, const char *line)
163 {
164     int line_length = strlen(line);
165
166     /* If the log doesn't fit, error out. */
167     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
168         TEST_info("Client log too full");
169         error_writing_log = 1;
170         return;
171     }
172
173     strcat(client_log_buffer, line);
174     client_log_buffer_index += line_length;
175     client_log_buffer[client_log_buffer_index++] = '\n';
176 }
177
178 static void server_keylog_callback(const SSL *ssl, const char *line)
179 {
180     int line_length = strlen(line);
181
182     /* If the log doesn't fit, error out. */
183     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
184         TEST_info("Server log too full");
185         error_writing_log = 1;
186         return;
187     }
188
189     strcat(server_log_buffer, line);
190     server_log_buffer_index += line_length;
191     server_log_buffer[server_log_buffer_index++] = '\n';
192 }
193
194 static int compare_hex_encoded_buffer(const char *hex_encoded,
195                                       size_t hex_length,
196                                       const uint8_t *raw,
197                                       size_t raw_length)
198 {
199     size_t i, j;
200     char hexed[3];
201
202     if (!TEST_size_t_eq(raw_length * 2, hex_length))
203         return 1;
204
205     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
206         sprintf(hexed, "%02x", raw[i]);
207         if (!TEST_int_eq(hexed[0], hex_encoded[j])
208                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
209             return 1;
210     }
211
212     return 0;
213 }
214
215 static int test_keylog_output(char *buffer, const SSL *ssl,
216                               const SSL_SESSION *session,
217                               struct sslapitest_log_counts *expected)
218 {
219     char *token = NULL;
220     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
221     size_t client_random_size = SSL3_RANDOM_SIZE;
222     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
223     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
224     unsigned int rsa_key_exchange_count = 0;
225     unsigned int master_secret_count = 0;
226     unsigned int client_early_secret_count = 0;
227     unsigned int client_handshake_secret_count = 0;
228     unsigned int server_handshake_secret_count = 0;
229     unsigned int client_application_secret_count = 0;
230     unsigned int server_application_secret_count = 0;
231     unsigned int early_exporter_secret_count = 0;
232     unsigned int exporter_secret_count = 0;
233
234     for (token = strtok(buffer, " \n"); token != NULL;
235          token = strtok(NULL, " \n")) {
236         if (strcmp(token, "RSA") == 0) {
237             /*
238              * Premaster secret. Tokens should be: 16 ASCII bytes of
239              * hex-encoded encrypted secret, then the hex-encoded pre-master
240              * secret.
241              */
242             if (!TEST_ptr(token = strtok(NULL, " \n")))
243                 return 0;
244             if (!TEST_size_t_eq(strlen(token), 16))
245                 return 0;
246             if (!TEST_ptr(token = strtok(NULL, " \n")))
247                 return 0;
248             /*
249              * We can't sensibly check the log because the premaster secret is
250              * transient, and OpenSSL doesn't keep hold of it once the master
251              * secret is generated.
252              */
253             rsa_key_exchange_count++;
254         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
255             /*
256              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
257              * client random, then the hex-encoded master secret.
258              */
259             client_random_size = SSL_get_client_random(ssl,
260                                                        actual_client_random,
261                                                        SSL3_RANDOM_SIZE);
262             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
263                 return 0;
264
265             if (!TEST_ptr(token = strtok(NULL, " \n")))
266                 return 0;
267             if (!TEST_size_t_eq(strlen(token), 64))
268                 return 0;
269             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
270                                                        actual_client_random,
271                                                        client_random_size)))
272                 return 0;
273
274             if (!TEST_ptr(token = strtok(NULL, " \n")))
275                 return 0;
276             master_key_size = SSL_SESSION_get_master_key(session,
277                                                          actual_master_key,
278                                                          master_key_size);
279             if (!TEST_size_t_ne(master_key_size, 0))
280                 return 0;
281             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
282                                                        actual_master_key,
283                                                        master_key_size)))
284                 return 0;
285             master_secret_count++;
286         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
287                     || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
288                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
289                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
290                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
291                     || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
292                     || strcmp(token, "EXPORTER_SECRET") == 0) {
293             /*
294              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
295              * client random, and then the hex-encoded secret. In this case,
296              * we treat all of these secrets identically and then just
297              * distinguish between them when counting what we saw.
298              */
299             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
300                 client_early_secret_count++;
301             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
302                 client_handshake_secret_count++;
303             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
304                 server_handshake_secret_count++;
305             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
306                 client_application_secret_count++;
307             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
308                 server_application_secret_count++;
309             else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
310                 early_exporter_secret_count++;
311             else if (strcmp(token, "EXPORTER_SECRET") == 0)
312                 exporter_secret_count++;
313
314             client_random_size = SSL_get_client_random(ssl,
315                                                        actual_client_random,
316                                                        SSL3_RANDOM_SIZE);
317             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
318                 return 0;
319
320             if (!TEST_ptr(token = strtok(NULL, " \n")))
321                 return 0;
322             if (!TEST_size_t_eq(strlen(token), 64))
323                 return 0;
324             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
325                                                        actual_client_random,
326                                                        client_random_size)))
327                 return 0;
328
329             if (!TEST_ptr(token = strtok(NULL, " \n")))
330                 return 0;
331
332             /*
333              * TODO(TLS1.3): test that application traffic secrets are what
334              * we expect */
335         } else {
336             TEST_info("Unexpected token %s\n", token);
337             return 0;
338         }
339     }
340
341     /* Got what we expected? */
342     if (!TEST_size_t_eq(rsa_key_exchange_count,
343                         expected->rsa_key_exchange_count)
344             || !TEST_size_t_eq(master_secret_count,
345                                expected->master_secret_count)
346             || !TEST_size_t_eq(client_early_secret_count,
347                                expected->client_early_secret_count)
348             || !TEST_size_t_eq(client_handshake_secret_count,
349                                expected->client_handshake_secret_count)
350             || !TEST_size_t_eq(server_handshake_secret_count,
351                                expected->server_handshake_secret_count)
352             || !TEST_size_t_eq(client_application_secret_count,
353                                expected->client_application_secret_count)
354             || !TEST_size_t_eq(server_application_secret_count,
355                                expected->server_application_secret_count)
356             || !TEST_size_t_eq(early_exporter_secret_count,
357                                expected->early_exporter_secret_count)
358             || !TEST_size_t_eq(exporter_secret_count,
359                                expected->exporter_secret_count))
360         return 0;
361     return 1;
362 }
363
364 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
365 static int test_keylog(void)
366 {
367     SSL_CTX *cctx = NULL, *sctx = NULL;
368     SSL *clientssl = NULL, *serverssl = NULL;
369     int testresult = 0;
370     struct sslapitest_log_counts expected;
371
372     /* Clean up logging space */
373     memset(&expected, 0, sizeof(expected));
374     memset(client_log_buffer, 0, sizeof(client_log_buffer));
375     memset(server_log_buffer, 0, sizeof(server_log_buffer));
376     client_log_buffer_index = 0;
377     server_log_buffer_index = 0;
378     error_writing_log = 0;
379
380     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
381                                        TLS_client_method(),
382                                        TLS1_VERSION, 0,
383                                        &sctx, &cctx, cert, privkey)))
384         return 0;
385
386     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
387     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
388     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
389
390     /* We also want to ensure that we use RSA-based key exchange. */
391     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
392         goto end;
393
394     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
395             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
396         goto end;
397     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
398     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
399                    == client_keylog_callback))
400         goto end;
401     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
402     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
403                    == server_keylog_callback))
404         goto end;
405
406     /* Now do a handshake and check that the logs have been written to. */
407     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
408                                       &clientssl, NULL, NULL))
409             || !TEST_true(create_ssl_connection(serverssl, clientssl,
410                                                 SSL_ERROR_NONE))
411             || !TEST_false(error_writing_log)
412             || !TEST_int_gt(client_log_buffer_index, 0)
413             || !TEST_int_gt(server_log_buffer_index, 0))
414         goto end;
415
416     /*
417      * Now we want to test that our output data was vaguely sensible. We
418      * do that by using strtok and confirming that we have more or less the
419      * data we expect. For both client and server, we expect to see one master
420      * secret. The client should also see a RSA key exchange.
421      */
422     expected.rsa_key_exchange_count = 1;
423     expected.master_secret_count = 1;
424     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
425                                       SSL_get_session(clientssl), &expected)))
426         goto end;
427
428     expected.rsa_key_exchange_count = 0;
429     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
430                                       SSL_get_session(serverssl), &expected)))
431         goto end;
432
433     testresult = 1;
434
435 end:
436     SSL_free(serverssl);
437     SSL_free(clientssl);
438     SSL_CTX_free(sctx);
439     SSL_CTX_free(cctx);
440
441     return testresult;
442 }
443 #endif
444
445 #ifndef OSSL_NO_USABLE_TLS1_3
446 static int test_keylog_no_master_key(void)
447 {
448     SSL_CTX *cctx = NULL, *sctx = NULL;
449     SSL *clientssl = NULL, *serverssl = NULL;
450     SSL_SESSION *sess = NULL;
451     int testresult = 0;
452     struct sslapitest_log_counts expected;
453     unsigned char buf[1];
454     size_t readbytes, written;
455
456     /* Clean up logging space */
457     memset(&expected, 0, sizeof(expected));
458     memset(client_log_buffer, 0, sizeof(client_log_buffer));
459     memset(server_log_buffer, 0, sizeof(server_log_buffer));
460     client_log_buffer_index = 0;
461     server_log_buffer_index = 0;
462     error_writing_log = 0;
463
464     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
465                                        TLS_client_method(), TLS1_VERSION, 0,
466                                        &sctx, &cctx, cert, privkey))
467         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
468                                                  SSL3_RT_MAX_PLAIN_LENGTH)))
469         return 0;
470
471     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
472             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
473         goto end;
474
475     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
476     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
477                    == client_keylog_callback))
478         goto end;
479
480     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
481     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
482                    == server_keylog_callback))
483         goto end;
484
485     /* Now do a handshake and check that the logs have been written to. */
486     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
487                                       &clientssl, NULL, NULL))
488             || !TEST_true(create_ssl_connection(serverssl, clientssl,
489                                                 SSL_ERROR_NONE))
490             || !TEST_false(error_writing_log))
491         goto end;
492
493     /*
494      * Now we want to test that our output data was vaguely sensible. For this
495      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
496      * TLSv1.3, but we do expect both client and server to emit keys.
497      */
498     expected.client_handshake_secret_count = 1;
499     expected.server_handshake_secret_count = 1;
500     expected.client_application_secret_count = 1;
501     expected.server_application_secret_count = 1;
502     expected.exporter_secret_count = 1;
503     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
504                                       SSL_get_session(clientssl), &expected))
505             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
506                                              SSL_get_session(serverssl),
507                                              &expected)))
508         goto end;
509
510     /* Terminate old session and resume with early data. */
511     sess = SSL_get1_session(clientssl);
512     SSL_shutdown(clientssl);
513     SSL_shutdown(serverssl);
514     SSL_free(serverssl);
515     SSL_free(clientssl);
516     serverssl = clientssl = NULL;
517
518     /* Reset key log */
519     memset(client_log_buffer, 0, sizeof(client_log_buffer));
520     memset(server_log_buffer, 0, sizeof(server_log_buffer));
521     client_log_buffer_index = 0;
522     server_log_buffer_index = 0;
523
524     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
525                                       &clientssl, NULL, NULL))
526             || !TEST_true(SSL_set_session(clientssl, sess))
527             /* Here writing 0 length early data is enough. */
528             || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
529             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
530                                                 &readbytes),
531                             SSL_READ_EARLY_DATA_ERROR)
532             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
533                             SSL_EARLY_DATA_ACCEPTED)
534             || !TEST_true(create_ssl_connection(serverssl, clientssl,
535                           SSL_ERROR_NONE))
536             || !TEST_true(SSL_session_reused(clientssl)))
537         goto end;
538
539     /* In addition to the previous entries, expect early secrets. */
540     expected.client_early_secret_count = 1;
541     expected.early_exporter_secret_count = 1;
542     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
543                                       SSL_get_session(clientssl), &expected))
544             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
545                                              SSL_get_session(serverssl),
546                                              &expected)))
547         goto end;
548
549     testresult = 1;
550
551 end:
552     SSL_SESSION_free(sess);
553     SSL_free(serverssl);
554     SSL_free(clientssl);
555     SSL_CTX_free(sctx);
556     SSL_CTX_free(cctx);
557
558     return testresult;
559 }
560 #endif
561
562 static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg)
563 {
564     int res = X509_verify_cert(ctx);
565
566     if (res == 0 && X509_STORE_CTX_get_error(ctx) ==
567         X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
568         return -1; /* indicate SSL_ERROR_WANT_RETRY_VERIFY */
569     return res;
570 }
571
572 static int test_client_cert_verify_cb(void)
573 {
574     /* server key, cert, chain, and root */
575     char *skey = test_mk_file_path(certsdir, "leaf.key");
576     char *leaf = test_mk_file_path(certsdir, "leaf.pem");
577     char *int2 = test_mk_file_path(certsdir, "subinterCA.pem");
578     char *int1 = test_mk_file_path(certsdir, "interCA.pem");
579     char *root = test_mk_file_path(certsdir, "rootCA.pem");
580     X509 *crt1 = NULL, *crt2 = NULL;
581     STACK_OF(X509) *server_chain;
582     SSL_CTX *cctx = NULL, *sctx = NULL;
583     SSL *clientssl = NULL, *serverssl = NULL;
584     int testresult = 0;
585
586     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
587                                        TLS_client_method(), TLS1_VERSION, 0,
588                                        &sctx, &cctx, NULL, NULL)))
589         goto end;
590     if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(sctx, leaf), 1)
591             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, skey,
592                                                         SSL_FILETYPE_PEM), 1)
593             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
594         goto end;
595     if (!TEST_true(SSL_CTX_load_verify_locations(cctx, root, NULL)))
596         goto end;
597     SSL_CTX_set_verify(cctx, SSL_VERIFY_PEER, NULL);
598     SSL_CTX_set_cert_verify_callback(cctx, verify_retry_cb, NULL);
599     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
600                                       &clientssl, NULL, NULL)))
601         goto end;
602
603     /* attempt SSL_connect() with incomplete server chain */
604     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
605                                           SSL_ERROR_WANT_RETRY_VERIFY)))
606         goto end;
607
608     /* application provides intermediate certs needed to verify server cert */
609     if (!TEST_ptr((crt1 = load_cert_pem(int1, libctx)))
610         || !TEST_ptr((crt2 = load_cert_pem(int2, libctx)))
611         || !TEST_ptr((server_chain = SSL_get_peer_cert_chain(clientssl))))
612         goto end;
613     /* add certs in reverse order to demonstrate real chain building */
614     if (!TEST_true(sk_X509_push(server_chain, crt1)))
615         goto end;
616     crt1 = NULL;
617     if (!TEST_true(sk_X509_push(server_chain, crt2)))
618         goto end;
619     crt2 = NULL;
620
621     /* continue SSL_connect(), must now succeed with completed server chain */
622     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
623                                          SSL_ERROR_NONE)))
624         goto end;
625
626     testresult = 1;
627
628 end:
629     X509_free(crt1);
630     X509_free(crt2);
631     SSL_shutdown(clientssl);
632     SSL_shutdown(serverssl);
633     SSL_free(serverssl);
634     SSL_free(clientssl);
635     SSL_CTX_free(sctx);
636     SSL_CTX_free(cctx);
637
638     OPENSSL_free(skey);
639     OPENSSL_free(leaf);
640     OPENSSL_free(int2);
641     OPENSSL_free(int1);
642     OPENSSL_free(root);
643
644     return testresult;
645 }
646
647 #ifndef OPENSSL_NO_TLS1_2
648 static int full_client_hello_callback(SSL *s, int *al, void *arg)
649 {
650     int *ctr = arg;
651     const unsigned char *p;
652     int *exts;
653     /* We only configure two ciphers, but the SCSV is added automatically. */
654 #ifdef OPENSSL_NO_EC
655     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
656 #else
657     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
658                                               0x2c, 0x00, 0xff};
659 #endif
660     const int expected_extensions[] = {
661 #ifndef OPENSSL_NO_EC
662                                        11, 10,
663 #endif
664                                        35, 22, 23, 13};
665     size_t len;
666
667     /* Make sure we can defer processing and get called back. */
668     if ((*ctr)++ == 0)
669         return SSL_CLIENT_HELLO_RETRY;
670
671     len = SSL_client_hello_get0_ciphers(s, &p);
672     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
673             || !TEST_size_t_eq(
674                        SSL_client_hello_get0_compression_methods(s, &p), 1)
675             || !TEST_int_eq(*p, 0))
676         return SSL_CLIENT_HELLO_ERROR;
677     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
678         return SSL_CLIENT_HELLO_ERROR;
679     if (len != OSSL_NELEM(expected_extensions) ||
680         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
681         printf("ClientHello callback expected extensions mismatch\n");
682         OPENSSL_free(exts);
683         return SSL_CLIENT_HELLO_ERROR;
684     }
685     OPENSSL_free(exts);
686     return SSL_CLIENT_HELLO_SUCCESS;
687 }
688
689 static int test_client_hello_cb(void)
690 {
691     SSL_CTX *cctx = NULL, *sctx = NULL;
692     SSL *clientssl = NULL, *serverssl = NULL;
693     int testctr = 0, testresult = 0;
694
695     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
696                                        TLS_client_method(), TLS1_VERSION, 0,
697                                        &sctx, &cctx, cert, privkey)))
698         goto end;
699     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
700
701     /* The gimpy cipher list we configure can't do TLS 1.3. */
702     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
703
704     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
705                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
706             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
707                                              &clientssl, NULL, NULL))
708             || !TEST_false(create_ssl_connection(serverssl, clientssl,
709                         SSL_ERROR_WANT_CLIENT_HELLO_CB))
710                 /*
711                  * Passing a -1 literal is a hack since
712                  * the real value was lost.
713                  * */
714             || !TEST_int_eq(SSL_get_error(serverssl, -1),
715                             SSL_ERROR_WANT_CLIENT_HELLO_CB)
716             || !TEST_true(create_ssl_connection(serverssl, clientssl,
717                                                 SSL_ERROR_NONE)))
718         goto end;
719
720     testresult = 1;
721
722 end:
723     SSL_free(serverssl);
724     SSL_free(clientssl);
725     SSL_CTX_free(sctx);
726     SSL_CTX_free(cctx);
727
728     return testresult;
729 }
730
731 static int test_no_ems(void)
732 {
733     SSL_CTX *cctx = NULL, *sctx = NULL;
734     SSL *clientssl = NULL, *serverssl = NULL;
735     int testresult = 0;
736
737     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
738                              TLS1_VERSION, TLS1_2_VERSION,
739                              &sctx, &cctx, cert, privkey)) {
740         printf("Unable to create SSL_CTX pair\n");
741         goto end;
742     }
743
744     SSL_CTX_set_options(sctx, SSL_OP_NO_EXTENDED_MASTER_SECRET);
745
746     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
747         printf("Unable to create SSL objects\n");
748         goto end;
749     }
750
751     if (!create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) {
752         printf("Creating SSL connection failed\n");
753         goto end;
754     }
755
756     if (SSL_get_extms_support(serverssl)) {
757         printf("Server reports Extended Master Secret support\n");
758         goto end;
759     }
760
761     if (SSL_get_extms_support(clientssl)) {
762         printf("Client reports Extended Master Secret support\n");
763         goto end;
764     }
765     testresult = 1;
766
767 end:
768     SSL_free(serverssl);
769     SSL_free(clientssl);
770     SSL_CTX_free(sctx);
771     SSL_CTX_free(cctx);
772
773     return testresult;
774 }
775
776 /*
777  * Very focused test to exercise a single case in the server-side state
778  * machine, when the ChangeCipherState message needs to actually change
779  * from one cipher to a different cipher (i.e., not changing from null
780  * encryption to real encryption).
781  */
782 static int test_ccs_change_cipher(void)
783 {
784     SSL_CTX *cctx = NULL, *sctx = NULL;
785     SSL *clientssl = NULL, *serverssl = NULL;
786     SSL_SESSION *sess = NULL, *sesspre, *sesspost;
787     int testresult = 0;
788     int i;
789     unsigned char buf;
790     size_t readbytes;
791
792     /*
793      * Create a conection so we can resume and potentially (but not) use
794      * a different cipher in the second connection.
795      */
796     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
797                                        TLS_client_method(),
798                                        TLS1_VERSION, TLS1_2_VERSION,
799                                        &sctx, &cctx, cert, privkey))
800             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
801             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
802                           NULL, NULL))
803             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
804             || !TEST_true(create_ssl_connection(serverssl, clientssl,
805                                                 SSL_ERROR_NONE))
806             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
807             || !TEST_ptr(sess = SSL_get1_session(clientssl)))
808         goto end;
809
810     shutdown_ssl_connection(serverssl, clientssl);
811     serverssl = clientssl = NULL;
812
813     /* Resume, preferring a different cipher. Our server will force the
814      * same cipher to be used as the initial handshake. */
815     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
816                           NULL, NULL))
817             || !TEST_true(SSL_set_session(clientssl, sess))
818             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
819             || !TEST_true(create_ssl_connection(serverssl, clientssl,
820                                                 SSL_ERROR_NONE))
821             || !TEST_true(SSL_session_reused(clientssl))
822             || !TEST_true(SSL_session_reused(serverssl))
823             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
824             || !TEST_ptr_eq(sesspre, sesspost)
825             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
826                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
827         goto end;
828     shutdown_ssl_connection(serverssl, clientssl);
829     serverssl = clientssl = NULL;
830
831     /*
832      * Now create a fresh connection and try to renegotiate a different
833      * cipher on it.
834      */
835     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
836                                       NULL, NULL))
837             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
838             || !TEST_true(create_ssl_connection(serverssl, clientssl,
839                                                 SSL_ERROR_NONE))
840             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
841             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
842             || !TEST_true(SSL_renegotiate(clientssl))
843             || !TEST_true(SSL_renegotiate_pending(clientssl)))
844         goto end;
845     /* Actually drive the renegotiation. */
846     for (i = 0; i < 3; i++) {
847         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
848             if (!TEST_ulong_eq(readbytes, 0))
849                 goto end;
850         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
851                                 SSL_ERROR_WANT_READ)) {
852             goto end;
853         }
854         if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
855             if (!TEST_ulong_eq(readbytes, 0))
856                 goto end;
857         } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
858                                 SSL_ERROR_WANT_READ)) {
859             goto end;
860         }
861     }
862     /* sesspre and sesspost should be different since the cipher changed. */
863     if (!TEST_false(SSL_renegotiate_pending(clientssl))
864             || !TEST_false(SSL_session_reused(clientssl))
865             || !TEST_false(SSL_session_reused(serverssl))
866             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
867             || !TEST_ptr_ne(sesspre, sesspost)
868             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
869                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
870         goto end;
871
872     shutdown_ssl_connection(serverssl, clientssl);
873     serverssl = clientssl = NULL;
874
875     testresult = 1;
876
877 end:
878     SSL_free(serverssl);
879     SSL_free(clientssl);
880     SSL_CTX_free(sctx);
881     SSL_CTX_free(cctx);
882     SSL_SESSION_free(sess);
883
884     return testresult;
885 }
886 #endif
887
888 static int execute_test_large_message(const SSL_METHOD *smeth,
889                                       const SSL_METHOD *cmeth,
890                                       int min_version, int max_version,
891                                       int read_ahead)
892 {
893     SSL_CTX *cctx = NULL, *sctx = NULL;
894     SSL *clientssl = NULL, *serverssl = NULL;
895     int testresult = 0;
896     int i;
897     BIO *certbio = NULL;
898     X509 *chaincert = NULL;
899     int certlen;
900
901     if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
902         goto end;
903
904     if (!TEST_ptr(chaincert = X509_new_ex(libctx, NULL)))
905         goto end;
906
907     if (PEM_read_bio_X509(certbio, &chaincert, NULL, NULL) == NULL)
908         goto end;
909     BIO_free(certbio);
910     certbio = NULL;
911
912     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
913                                        max_version, &sctx, &cctx, cert,
914                                        privkey)))
915         goto end;
916
917     if (read_ahead) {
918         /*
919          * Test that read_ahead works correctly when dealing with large
920          * records
921          */
922         SSL_CTX_set_read_ahead(cctx, 1);
923     }
924
925     /*
926      * We assume the supplied certificate is big enough so that if we add
927      * NUM_EXTRA_CERTS it will make the overall message large enough. The
928      * default buffer size is requested to be 16k, but due to the way BUF_MEM
929      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
930      * test we need to have a message larger than that.
931      */
932     certlen = i2d_X509(chaincert, NULL);
933     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
934                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
935     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
936         if (!X509_up_ref(chaincert))
937             goto end;
938         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
939             X509_free(chaincert);
940             goto end;
941         }
942     }
943
944     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
945                                       NULL, NULL))
946             || !TEST_true(create_ssl_connection(serverssl, clientssl,
947                                                 SSL_ERROR_NONE)))
948         goto end;
949
950     /*
951      * Calling SSL_clear() first is not required but this tests that SSL_clear()
952      * doesn't leak.
953      */
954     if (!TEST_true(SSL_clear(serverssl)))
955         goto end;
956
957     testresult = 1;
958  end:
959     BIO_free(certbio);
960     X509_free(chaincert);
961     SSL_free(serverssl);
962     SSL_free(clientssl);
963     SSL_CTX_free(sctx);
964     SSL_CTX_free(cctx);
965
966     return testresult;
967 }
968
969 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_KTLS) && \
970     !(defined(OSSL_NO_USABLE_TLS1_3) && defined(OPENSSL_NO_TLS1_2))
971 #define TLS_CIPHER_MAX_REC_SEQ_SIZE 8
972 /* sock must be connected */
973 static int ktls_chk_platform(int sock)
974 {
975     if (!ktls_enable(sock))
976         return 0;
977     return 1;
978 }
979
980 static int ping_pong_query(SSL *clientssl, SSL *serverssl, int cfd, int sfd, int rec_seq_size)
981 {
982     static char count = 1;
983     unsigned char cbuf[16000] = {0};
984     unsigned char sbuf[16000];
985     size_t err = 0;
986     char crec_wseq_before[TLS_CIPHER_MAX_REC_SEQ_SIZE];
987     char crec_wseq_after[TLS_CIPHER_MAX_REC_SEQ_SIZE];
988     char crec_rseq_before[TLS_CIPHER_MAX_REC_SEQ_SIZE];
989     char crec_rseq_after[TLS_CIPHER_MAX_REC_SEQ_SIZE];
990     char srec_wseq_before[TLS_CIPHER_MAX_REC_SEQ_SIZE];
991     char srec_wseq_after[TLS_CIPHER_MAX_REC_SEQ_SIZE];
992     char srec_rseq_before[TLS_CIPHER_MAX_REC_SEQ_SIZE];
993     char srec_rseq_after[TLS_CIPHER_MAX_REC_SEQ_SIZE];
994
995     cbuf[0] = count++;
996     memcpy(crec_wseq_before, &clientssl->rlayer.write_sequence, rec_seq_size);
997     memcpy(crec_rseq_before, &clientssl->rlayer.read_sequence, rec_seq_size);
998     memcpy(srec_wseq_before, &serverssl->rlayer.write_sequence, rec_seq_size);
999     memcpy(srec_rseq_before, &serverssl->rlayer.read_sequence, rec_seq_size);
1000
1001     if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf)))
1002         goto end;
1003
1004     while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) {
1005         if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) {
1006             goto end;
1007         }
1008     }
1009
1010     if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf)))
1011         goto end;
1012
1013     while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) {
1014         if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) {
1015             goto end;
1016         }
1017     }
1018
1019     memcpy(crec_wseq_after, &clientssl->rlayer.write_sequence, rec_seq_size);
1020     memcpy(crec_rseq_after, &clientssl->rlayer.read_sequence, rec_seq_size);
1021     memcpy(srec_wseq_after, &serverssl->rlayer.write_sequence, rec_seq_size);
1022     memcpy(srec_rseq_after, &serverssl->rlayer.read_sequence, rec_seq_size);
1023
1024     /* verify the payload */
1025     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1026         goto end;
1027
1028     /* ktls is used then kernel sequences are used instead of OpenSSL sequences */
1029     if (clientssl->mode & SSL_MODE_NO_KTLS_TX) {
1030         if (!TEST_mem_ne(crec_wseq_before, rec_seq_size,
1031                          crec_wseq_after, rec_seq_size))
1032             goto end;
1033     } else {
1034         if (!TEST_mem_eq(crec_wseq_before, rec_seq_size,
1035                          crec_wseq_after, rec_seq_size))
1036             goto end;
1037     }
1038
1039     if (serverssl->mode & SSL_MODE_NO_KTLS_TX) {
1040         if (!TEST_mem_ne(srec_wseq_before, rec_seq_size,
1041                          srec_wseq_after, rec_seq_size))
1042             goto end;
1043     } else {
1044         if (!TEST_mem_eq(srec_wseq_before, rec_seq_size,
1045                          srec_wseq_after, rec_seq_size))
1046             goto end;
1047     }
1048
1049     if (clientssl->mode & SSL_MODE_NO_KTLS_RX) {
1050         if (!TEST_mem_ne(crec_rseq_before, rec_seq_size,
1051                          crec_rseq_after, rec_seq_size))
1052             goto end;
1053     } else {
1054         if (!TEST_mem_eq(crec_rseq_before, rec_seq_size,
1055                          crec_rseq_after, rec_seq_size))
1056             goto end;
1057     }
1058
1059     if (serverssl->mode & SSL_MODE_NO_KTLS_RX) {
1060         if (!TEST_mem_ne(srec_rseq_before, rec_seq_size,
1061                          srec_rseq_after, rec_seq_size))
1062             goto end;
1063     } else {
1064         if (!TEST_mem_eq(srec_rseq_before, rec_seq_size,
1065                          srec_rseq_after, rec_seq_size))
1066             goto end;
1067     }
1068
1069     return 1;
1070 end:
1071     return 0;
1072 }
1073
1074 static int execute_test_ktls(int cis_ktls_tx, int cis_ktls_rx,
1075                              int sis_ktls_tx, int sis_ktls_rx,
1076                              int tls_version, const char *cipher,
1077                              int rec_seq_size)
1078 {
1079     SSL_CTX *cctx = NULL, *sctx = NULL;
1080     SSL *clientssl = NULL, *serverssl = NULL;
1081     int testresult = 0;
1082     int cfd, sfd;
1083
1084     if (!TEST_true(create_test_sockets(&cfd, &sfd)))
1085         goto end;
1086
1087     /* Skip this test if the platform does not support ktls */
1088     if (!ktls_chk_platform(cfd))
1089         return 1;
1090
1091     /* Create a session based on SHA-256 */
1092     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1093                                        TLS_client_method(),
1094                                        tls_version, tls_version,
1095                                        &sctx, &cctx, cert, privkey))
1096             || !TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1097             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher))
1098             || !TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1099                                           &clientssl, sfd, cfd)))
1100         goto end;
1101
1102     if (!cis_ktls_tx) {
1103         if (!TEST_true(SSL_set_mode(clientssl, SSL_MODE_NO_KTLS_TX)))
1104             goto end;
1105     }
1106
1107     if (!sis_ktls_tx) {
1108         if (!TEST_true(SSL_set_mode(serverssl, SSL_MODE_NO_KTLS_TX)))
1109             goto end;
1110     }
1111
1112     if (!cis_ktls_rx) {
1113         if (!TEST_true(SSL_set_mode(clientssl, SSL_MODE_NO_KTLS_RX)))
1114             goto end;
1115     }
1116
1117     if (!sis_ktls_rx) {
1118         if (!TEST_true(SSL_set_mode(serverssl, SSL_MODE_NO_KTLS_RX)))
1119             goto end;
1120     }
1121
1122     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1123                                                 SSL_ERROR_NONE)))
1124         goto end;
1125
1126     if (!cis_ktls_tx) {
1127         if (!TEST_false(BIO_get_ktls_send(clientssl->wbio)))
1128             goto end;
1129     } else {
1130         if (!TEST_true(BIO_get_ktls_send(clientssl->wbio)))
1131             goto end;
1132     }
1133
1134     if (!sis_ktls_tx) {
1135         if (!TEST_false(BIO_get_ktls_send(serverssl->wbio)))
1136             goto end;
1137     } else {
1138         if (!TEST_true(BIO_get_ktls_send(serverssl->wbio)))
1139             goto end;
1140     }
1141
1142     if (!cis_ktls_rx) {
1143         if (!TEST_false(BIO_get_ktls_recv(clientssl->rbio)))
1144             goto end;
1145     } else {
1146         if (!TEST_true(BIO_get_ktls_recv(clientssl->rbio)))
1147             goto end;
1148     }
1149
1150     if (!sis_ktls_rx) {
1151         if (!TEST_false(BIO_get_ktls_recv(serverssl->rbio)))
1152             goto end;
1153     } else {
1154         if (!TEST_true(BIO_get_ktls_recv(serverssl->rbio)))
1155             goto end;
1156     }
1157
1158     if (!TEST_true(ping_pong_query(clientssl, serverssl, cfd, sfd,
1159                                    rec_seq_size)))
1160         goto end;
1161
1162     testresult = 1;
1163 end:
1164     if (clientssl) {
1165         SSL_shutdown(clientssl);
1166         SSL_free(clientssl);
1167     }
1168     if (serverssl) {
1169         SSL_shutdown(serverssl);
1170         SSL_free(serverssl);
1171     }
1172     SSL_CTX_free(sctx);
1173     SSL_CTX_free(cctx);
1174     serverssl = clientssl = NULL;
1175     return testresult;
1176 }
1177
1178 #define SENDFILE_SZ                     (16 * 4096)
1179 #define SENDFILE_CHUNK                  (4 * 4096)
1180 #define min(a,b)                        ((a) > (b) ? (b) : (a))
1181
1182 static int test_ktls_sendfile(int tls_version, const char *cipher)
1183 {
1184     SSL_CTX *cctx = NULL, *sctx = NULL;
1185     SSL *clientssl = NULL, *serverssl = NULL;
1186     unsigned char *buf, *buf_dst;
1187     BIO *out = NULL, *in = NULL;
1188     int cfd, sfd, ffd, err;
1189     ssize_t chunk_size = 0;
1190     off_t chunk_off = 0;
1191     int testresult = 0;
1192     FILE *ffdp;
1193
1194     buf = OPENSSL_zalloc(SENDFILE_SZ);
1195     buf_dst = OPENSSL_zalloc(SENDFILE_SZ);
1196     if (!TEST_ptr(buf) || !TEST_ptr(buf_dst)
1197         || !TEST_true(create_test_sockets(&cfd, &sfd)))
1198         goto end;
1199
1200     /* Skip this test if the platform does not support ktls */
1201     if (!ktls_chk_platform(sfd)) {
1202         testresult = 1;
1203         goto end;
1204     }
1205
1206     /* Create a session based on SHA-256 */
1207     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1208                                        TLS_client_method(),
1209                                        tls_version, tls_version,
1210                                        &sctx, &cctx, cert, privkey))
1211         || !TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1212         || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher))
1213         || !TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1214                                           &clientssl, sfd, cfd)))
1215         goto end;
1216
1217     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1218                                          SSL_ERROR_NONE))
1219         || !TEST_true(BIO_get_ktls_send(serverssl->wbio)))
1220         goto end;
1221
1222     if (!TEST_true(RAND_bytes_ex(libctx, buf, SENDFILE_SZ)))
1223         goto end;
1224
1225     out = BIO_new_file(tmpfilename, "wb");
1226     if (!TEST_ptr(out))
1227         goto end;
1228
1229     if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ)
1230         goto end;
1231
1232     BIO_free(out);
1233     out = NULL;
1234     in = BIO_new_file(tmpfilename, "rb");
1235     BIO_get_fp(in, &ffdp);
1236     ffd = fileno(ffdp);
1237
1238     while (chunk_off < SENDFILE_SZ) {
1239         chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off);
1240         while ((err = SSL_sendfile(serverssl,
1241                                    ffd,
1242                                    chunk_off,
1243                                    chunk_size,
1244                                    0)) != chunk_size) {
1245             if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE)
1246                 goto end;
1247         }
1248         while ((err = SSL_read(clientssl,
1249                                buf_dst + chunk_off,
1250                                chunk_size)) != chunk_size) {
1251             if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ)
1252                 goto end;
1253         }
1254
1255         /* verify the payload */
1256         if (!TEST_mem_eq(buf_dst + chunk_off,
1257                          chunk_size,
1258                          buf + chunk_off,
1259                          chunk_size))
1260             goto end;
1261
1262         chunk_off += chunk_size;
1263     }
1264
1265     testresult = 1;
1266 end:
1267     if (clientssl) {
1268         SSL_shutdown(clientssl);
1269         SSL_free(clientssl);
1270     }
1271     if (serverssl) {
1272         SSL_shutdown(serverssl);
1273         SSL_free(serverssl);
1274     }
1275     SSL_CTX_free(sctx);
1276     SSL_CTX_free(cctx);
1277     serverssl = clientssl = NULL;
1278     BIO_free(out);
1279     BIO_free(in);
1280     OPENSSL_free(buf);
1281     OPENSSL_free(buf_dst);
1282     return testresult;
1283 }
1284
1285 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
1286 static int test_ktls(int test)
1287 {
1288     int cis_ktls_tx, cis_ktls_rx, sis_ktls_tx, sis_ktls_rx;
1289     int tlsver, testresult;
1290
1291     if (test > 15) {
1292 #if defined(OSSL_NO_USABLE_TLS1_3)
1293         return 1;
1294 #else
1295         test -= 16;
1296         tlsver = TLS1_3_VERSION;
1297 #endif
1298     } else {
1299 #if defined(OPENSSL_NO_TLS1_2)
1300         return 1;
1301 #else
1302         tlsver = TLS1_2_VERSION;
1303 #endif
1304     }
1305
1306     cis_ktls_tx = (test & 1) != 0;
1307     cis_ktls_rx = (test & 2) != 0;
1308     sis_ktls_tx = (test & 4) != 0;
1309     sis_ktls_rx = (test & 8) != 0;
1310
1311 #if defined(OPENSSL_NO_KTLS_RX)
1312     if (cis_ktls_rx || sis_ktls_rx)
1313         return 1;
1314 #endif
1315 #if !defined(OSSL_NO_USABLE_TLS1_3)
1316     if (tlsver == TLS1_3_VERSION && (cis_ktls_rx || sis_ktls_rx))
1317         return 1;
1318 #endif
1319
1320     testresult = 1;
1321 #ifdef OPENSSL_KTLS_AES_GCM_128
1322     testresult &= execute_test_ktls(cis_ktls_tx, cis_ktls_rx, sis_ktls_tx,
1323                                     sis_ktls_rx, tlsver, "AES128-GCM-SHA256",
1324                                     TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
1325 #endif
1326 #ifdef OPENSSL_KTLS_AES_CCM_128
1327     testresult &= execute_test_ktls(cis_ktls_tx, cis_ktls_rx, sis_ktls_tx,
1328                                     sis_ktls_rx, tlsver, "AES128-CCM",
1329                                     TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE);
1330 #endif
1331 #ifdef OPENSSL_KTLS_AES_GCM_256
1332     testresult &= execute_test_ktls(cis_ktls_tx, cis_ktls_rx, sis_ktls_tx,
1333                                     sis_ktls_rx, tlsver, "AES256-GCM-SHA384",
1334                                     TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE);
1335 #endif
1336     return testresult;
1337 }
1338
1339 static int test_ktls_sendfile_anytls(int tst)
1340 {
1341     char *cipher[] = {"AES128-GCM-SHA256","AES128-CCM","AES256-GCM-SHA384"};
1342     int tlsver;
1343
1344     if (tst > 2) {
1345 #if defined(OSSL_NO_USABLE_TLS1_3)
1346         return 1;
1347 #else
1348         tst -= 3;
1349         tlsver = TLS1_3_VERSION;
1350 #endif
1351     } else {
1352 #if defined(OPENSSL_NO_TLS1_2)
1353         return 1;
1354 #else
1355         tlsver = TLS1_2_VERSION;
1356 #endif
1357     }
1358
1359 #ifndef OPENSSL_KTLS_AES_GCM_128
1360    if(tst == 0) return 1;
1361 #endif
1362 #ifndef OPENSSL_KTLS_AES_CCM_128
1363    if(tst == 1) return 1;
1364 #endif
1365 #ifndef OPENSSL_KTLS_AES_GCM_256
1366    if(tst == 2) return 1;
1367 #endif
1368    return test_ktls_sendfile(tlsver, cipher[tst]);
1369 }
1370
1371 #endif
1372 #endif
1373
1374 static int test_large_message_tls(void)
1375 {
1376     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1377                                       TLS1_VERSION, 0, 0);
1378 }
1379
1380 static int test_large_message_tls_read_ahead(void)
1381 {
1382     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1383                                       TLS1_VERSION, 0, 1);
1384 }
1385
1386 #ifndef OPENSSL_NO_DTLS
1387 static int test_large_message_dtls(void)
1388 {
1389     /*
1390      * read_ahead is not relevant to DTLS because DTLS always acts as if
1391      * read_ahead is set.
1392      */
1393     return execute_test_large_message(DTLS_server_method(),
1394                                       DTLS_client_method(),
1395                                       DTLS1_VERSION, 0, 0);
1396 }
1397 #endif
1398
1399 static int execute_cleanse_plaintext(const SSL_METHOD *smeth,
1400                                      const SSL_METHOD *cmeth,
1401                                      int min_version, int max_version)
1402 {
1403     size_t i;
1404     SSL_CTX *cctx = NULL, *sctx = NULL;
1405     SSL *clientssl = NULL, *serverssl = NULL;
1406     int testresult = 0;
1407     SSL3_RECORD *rr;
1408     void *zbuf;
1409
1410     static unsigned char cbuf[16000];
1411     static unsigned char sbuf[16000];
1412
1413     if (!TEST_true(create_ssl_ctx_pair(libctx,
1414                                        smeth, cmeth,
1415                                        min_version, max_version,
1416                                        &sctx, &cctx, cert,
1417                                        privkey)))
1418         goto end;
1419
1420     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1421                                       NULL, NULL)))
1422         goto end;
1423
1424     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_CLEANSE_PLAINTEXT)))
1425         goto end;
1426
1427     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1428                                          SSL_ERROR_NONE)))
1429         goto end;
1430
1431     for (i = 0; i < sizeof(cbuf); i++) {
1432         cbuf[i] = i & 0xff;
1433     }
1434
1435     if (!TEST_int_eq(SSL_write(clientssl, cbuf, sizeof(cbuf)), sizeof(cbuf)))
1436         goto end;
1437
1438     if (!TEST_int_eq(SSL_peek(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1439         goto end;
1440
1441     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1442         goto end;
1443
1444     /*
1445      * Since we called SSL_peek(), we know the data in the record
1446      * layer is a plaintext record. We can gather the pointer to check
1447      * for zeroization after SSL_read().
1448      */
1449     rr = serverssl->rlayer.rrec;
1450     zbuf = &rr->data[rr->off];
1451     if (!TEST_int_eq(rr->length, sizeof(cbuf)))
1452         goto end;
1453
1454     /*
1455      * After SSL_peek() the plaintext must still be stored in the
1456      * record.
1457      */
1458     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1459         goto end;
1460
1461     memset(sbuf, 0, sizeof(sbuf));
1462     if (!TEST_int_eq(SSL_read(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1463         goto end;
1464
1465     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(cbuf)))
1466         goto end;
1467
1468     /* Check if rbuf is cleansed */
1469     memset(cbuf, 0, sizeof(cbuf));
1470     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1471         goto end;
1472
1473     testresult = 1;
1474  end:
1475     SSL_free(serverssl);
1476     SSL_free(clientssl);
1477     SSL_CTX_free(sctx);
1478     SSL_CTX_free(cctx);
1479
1480     return testresult;
1481 }
1482
1483 static int test_cleanse_plaintext(void)
1484 {
1485 #if !defined(OPENSSL_NO_TLS1_2)
1486     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1487                                              TLS_client_method(),
1488                                              TLS1_2_VERSION,
1489                                              TLS1_2_VERSION)))
1490         return 0;
1491
1492 #endif
1493
1494 #if !defined(OSSL_NO_USABLE_TLS1_3)
1495     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1496                                              TLS_client_method(),
1497                                              TLS1_3_VERSION,
1498                                              TLS1_3_VERSION)))
1499         return 0;
1500 #endif
1501
1502 #if !defined(OPENSSL_NO_DTLS)
1503     if (!TEST_true(execute_cleanse_plaintext(DTLS_server_method(),
1504                                              DTLS_client_method(),
1505                                              DTLS1_VERSION,
1506                                              0)))
1507         return 0;
1508 #endif
1509     return 1;
1510 }
1511
1512 #ifndef OPENSSL_NO_OCSP
1513 static int ocsp_server_cb(SSL *s, void *arg)
1514 {
1515     int *argi = (int *)arg;
1516     unsigned char *copy = NULL;
1517     STACK_OF(OCSP_RESPID) *ids = NULL;
1518     OCSP_RESPID *id = NULL;
1519
1520     if (*argi == 2) {
1521         /* In this test we are expecting exactly 1 OCSP_RESPID */
1522         SSL_get_tlsext_status_ids(s, &ids);
1523         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
1524             return SSL_TLSEXT_ERR_ALERT_FATAL;
1525
1526         id = sk_OCSP_RESPID_value(ids, 0);
1527         if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL))
1528             return SSL_TLSEXT_ERR_ALERT_FATAL;
1529     } else if (*argi != 1) {
1530         return SSL_TLSEXT_ERR_ALERT_FATAL;
1531     }
1532
1533     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
1534         return SSL_TLSEXT_ERR_ALERT_FATAL;
1535
1536     SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder));
1537     ocsp_server_called = 1;
1538     return SSL_TLSEXT_ERR_OK;
1539 }
1540
1541 static int ocsp_client_cb(SSL *s, void *arg)
1542 {
1543     int *argi = (int *)arg;
1544     const unsigned char *respderin;
1545     size_t len;
1546
1547     if (*argi != 1 && *argi != 2)
1548         return 0;
1549
1550     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
1551     if (!TEST_mem_eq(orespder, len, respderin, len))
1552         return 0;
1553
1554     ocsp_client_called = 1;
1555     return 1;
1556 }
1557
1558 static int test_tlsext_status_type(void)
1559 {
1560     SSL_CTX *cctx = NULL, *sctx = NULL;
1561     SSL *clientssl = NULL, *serverssl = NULL;
1562     int testresult = 0;
1563     STACK_OF(OCSP_RESPID) *ids = NULL;
1564     OCSP_RESPID *id = NULL;
1565     BIO *certbio = NULL;
1566
1567     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
1568                              TLS1_VERSION, 0,
1569                              &sctx, &cctx, cert, privkey))
1570         return 0;
1571
1572     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
1573         goto end;
1574
1575     /* First just do various checks getting and setting tlsext_status_type */
1576
1577     clientssl = SSL_new(cctx);
1578     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
1579             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
1580                                                       TLSEXT_STATUSTYPE_ocsp))
1581             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
1582                             TLSEXT_STATUSTYPE_ocsp))
1583         goto end;
1584
1585     SSL_free(clientssl);
1586     clientssl = NULL;
1587
1588     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
1589      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
1590         goto end;
1591
1592     clientssl = SSL_new(cctx);
1593     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
1594         goto end;
1595     SSL_free(clientssl);
1596     clientssl = NULL;
1597
1598     /*
1599      * Now actually do a handshake and check OCSP information is exchanged and
1600      * the callbacks get called
1601      */
1602     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
1603     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
1604     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
1605     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
1606     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1607                                       &clientssl, NULL, NULL))
1608             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1609                                                 SSL_ERROR_NONE))
1610             || !TEST_true(ocsp_client_called)
1611             || !TEST_true(ocsp_server_called))
1612         goto end;
1613     SSL_free(serverssl);
1614     SSL_free(clientssl);
1615     serverssl = NULL;
1616     clientssl = NULL;
1617
1618     /* Try again but this time force the server side callback to fail */
1619     ocsp_client_called = 0;
1620     ocsp_server_called = 0;
1621     cdummyarg = 0;
1622     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1623                                       &clientssl, NULL, NULL))
1624                 /* This should fail because the callback will fail */
1625             || !TEST_false(create_ssl_connection(serverssl, clientssl,
1626                                                  SSL_ERROR_NONE))
1627             || !TEST_false(ocsp_client_called)
1628             || !TEST_false(ocsp_server_called))
1629         goto end;
1630     SSL_free(serverssl);
1631     SSL_free(clientssl);
1632     serverssl = NULL;
1633     clientssl = NULL;
1634
1635     /*
1636      * This time we'll get the client to send an OCSP_RESPID that it will
1637      * accept.
1638      */
1639     ocsp_client_called = 0;
1640     ocsp_server_called = 0;
1641     cdummyarg = 2;
1642     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1643                                       &clientssl, NULL, NULL)))
1644         goto end;
1645
1646     /*
1647      * We'll just use any old cert for this test - it doesn't have to be an OCSP
1648      * specific one. We'll use the server cert.
1649      */
1650     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
1651             || !TEST_ptr(id = OCSP_RESPID_new())
1652             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
1653             || !TEST_ptr(ocspcert = X509_new_ex(libctx, NULL))
1654             || !TEST_ptr(PEM_read_bio_X509(certbio, &ocspcert, NULL, NULL))
1655             || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL))
1656             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
1657         goto end;
1658     id = NULL;
1659     SSL_set_tlsext_status_ids(clientssl, ids);
1660     /* Control has been transferred */
1661     ids = NULL;
1662
1663     BIO_free(certbio);
1664     certbio = NULL;
1665
1666     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1667                                          SSL_ERROR_NONE))
1668             || !TEST_true(ocsp_client_called)
1669             || !TEST_true(ocsp_server_called))
1670         goto end;
1671
1672     testresult = 1;
1673
1674  end:
1675     SSL_free(serverssl);
1676     SSL_free(clientssl);
1677     SSL_CTX_free(sctx);
1678     SSL_CTX_free(cctx);
1679     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
1680     OCSP_RESPID_free(id);
1681     BIO_free(certbio);
1682     X509_free(ocspcert);
1683     ocspcert = NULL;
1684
1685     return testresult;
1686 }
1687 #endif
1688
1689 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
1690 static int new_called, remove_called, get_called;
1691
1692 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
1693 {
1694     new_called++;
1695     /*
1696      * sess has been up-refed for us, but we don't actually need it so free it
1697      * immediately.
1698      */
1699     SSL_SESSION_free(sess);
1700     return 1;
1701 }
1702
1703 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
1704 {
1705     remove_called++;
1706 }
1707
1708 static SSL_SESSION *get_sess_val = NULL;
1709
1710 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
1711                                    int *copy)
1712 {
1713     get_called++;
1714     *copy = 1;
1715     return get_sess_val;
1716 }
1717
1718 static int execute_test_session(int maxprot, int use_int_cache,
1719                                 int use_ext_cache, long s_options)
1720 {
1721     SSL_CTX *sctx = NULL, *cctx = NULL;
1722     SSL *serverssl1 = NULL, *clientssl1 = NULL;
1723     SSL *serverssl2 = NULL, *clientssl2 = NULL;
1724 # ifndef OPENSSL_NO_TLS1_1
1725     SSL *serverssl3 = NULL, *clientssl3 = NULL;
1726 # endif
1727     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
1728     int testresult = 0, numnewsesstick = 1;
1729
1730     new_called = remove_called = 0;
1731
1732     /* TLSv1.3 sends 2 NewSessionTickets */
1733     if (maxprot == TLS1_3_VERSION)
1734         numnewsesstick = 2;
1735
1736     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1737                                        TLS_client_method(), TLS1_VERSION, 0,
1738                                        &sctx, &cctx, cert, privkey)))
1739         return 0;
1740
1741     /*
1742      * Only allow the max protocol version so we can force a connection failure
1743      * later
1744      */
1745     SSL_CTX_set_min_proto_version(cctx, maxprot);
1746     SSL_CTX_set_max_proto_version(cctx, maxprot);
1747
1748     /* Set up session cache */
1749     if (use_ext_cache) {
1750         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
1751         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
1752     }
1753     if (use_int_cache) {
1754         /* Also covers instance where both are set */
1755         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
1756     } else {
1757         SSL_CTX_set_session_cache_mode(cctx,
1758                                        SSL_SESS_CACHE_CLIENT
1759                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1760     }
1761
1762     if (s_options) {
1763         SSL_CTX_set_options(sctx, s_options);
1764     }
1765
1766     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1767                                       NULL, NULL))
1768             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1769                                                 SSL_ERROR_NONE))
1770             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
1771         goto end;
1772
1773     /* Should fail because it should already be in the cache */
1774     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
1775         goto end;
1776     if (use_ext_cache
1777             && (!TEST_int_eq(new_called, numnewsesstick)
1778
1779                 || !TEST_int_eq(remove_called, 0)))
1780         goto end;
1781
1782     new_called = remove_called = 0;
1783     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1784                                       &clientssl2, NULL, NULL))
1785             || !TEST_true(SSL_set_session(clientssl2, sess1))
1786             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1787                                                 SSL_ERROR_NONE))
1788             || !TEST_true(SSL_session_reused(clientssl2)))
1789         goto end;
1790
1791     if (maxprot == TLS1_3_VERSION) {
1792         /*
1793          * In TLSv1.3 we should have created a new session even though we have
1794          * resumed. Since we attempted a resume we should also have removed the
1795          * old ticket from the cache so that we try to only use tickets once.
1796          */
1797         if (use_ext_cache
1798                 && (!TEST_int_eq(new_called, 1)
1799                     || !TEST_int_eq(remove_called, 1)))
1800             goto end;
1801     } else {
1802         /*
1803          * In TLSv1.2 we expect to have resumed so no sessions added or
1804          * removed.
1805          */
1806         if (use_ext_cache
1807                 && (!TEST_int_eq(new_called, 0)
1808                     || !TEST_int_eq(remove_called, 0)))
1809             goto end;
1810     }
1811
1812     SSL_SESSION_free(sess1);
1813     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
1814         goto end;
1815     shutdown_ssl_connection(serverssl2, clientssl2);
1816     serverssl2 = clientssl2 = NULL;
1817
1818     new_called = remove_called = 0;
1819     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1820                                       &clientssl2, NULL, NULL))
1821             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1822                                                 SSL_ERROR_NONE)))
1823         goto end;
1824
1825     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
1826         goto end;
1827
1828     if (use_ext_cache
1829             && (!TEST_int_eq(new_called, numnewsesstick)
1830                 || !TEST_int_eq(remove_called, 0)))
1831         goto end;
1832
1833     new_called = remove_called = 0;
1834     /*
1835      * This should clear sess2 from the cache because it is a "bad" session.
1836      * See SSL_set_session() documentation.
1837      */
1838     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
1839         goto end;
1840     if (use_ext_cache
1841             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1842         goto end;
1843     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
1844         goto end;
1845
1846     if (use_int_cache) {
1847         /* Should succeeded because it should not already be in the cache */
1848         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
1849                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
1850             goto end;
1851     }
1852
1853     new_called = remove_called = 0;
1854     /* This shouldn't be in the cache so should fail */
1855     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
1856         goto end;
1857
1858     if (use_ext_cache
1859             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1860         goto end;
1861
1862 # if !defined(OPENSSL_NO_TLS1_1)
1863     new_called = remove_called = 0;
1864     /* Force a connection failure */
1865     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
1866     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
1867                                       &clientssl3, NULL, NULL))
1868             || !TEST_true(SSL_set_session(clientssl3, sess1))
1869             /* This should fail because of the mismatched protocol versions */
1870             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
1871                                                  SSL_ERROR_NONE)))
1872         goto end;
1873
1874     /* We should have automatically removed the session from the cache */
1875     if (use_ext_cache
1876             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1877         goto end;
1878
1879     /* Should succeed because it should not already be in the cache */
1880     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
1881         goto end;
1882 # endif
1883
1884     /* Now do some tests for server side caching */
1885     if (use_ext_cache) {
1886         SSL_CTX_sess_set_new_cb(cctx, NULL);
1887         SSL_CTX_sess_set_remove_cb(cctx, NULL);
1888         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
1889         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
1890         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
1891         get_sess_val = NULL;
1892     }
1893
1894     SSL_CTX_set_session_cache_mode(cctx, 0);
1895     /* Internal caching is the default on the server side */
1896     if (!use_int_cache)
1897         SSL_CTX_set_session_cache_mode(sctx,
1898                                        SSL_SESS_CACHE_SERVER
1899                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1900
1901     SSL_free(serverssl1);
1902     SSL_free(clientssl1);
1903     serverssl1 = clientssl1 = NULL;
1904     SSL_free(serverssl2);
1905     SSL_free(clientssl2);
1906     serverssl2 = clientssl2 = NULL;
1907     SSL_SESSION_free(sess1);
1908     sess1 = NULL;
1909     SSL_SESSION_free(sess2);
1910     sess2 = NULL;
1911
1912     SSL_CTX_set_max_proto_version(sctx, maxprot);
1913     if (maxprot == TLS1_2_VERSION)
1914         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
1915     new_called = remove_called = get_called = 0;
1916     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1917                                       NULL, NULL))
1918             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1919                                                 SSL_ERROR_NONE))
1920             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
1921             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
1922         goto end;
1923
1924     if (use_int_cache) {
1925         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
1926             /*
1927              * In TLSv1.3 it should not have been added to the internal cache,
1928              * except in the case where we also have an external cache (in that
1929              * case it gets added to the cache in order to generate remove
1930              * events after timeout).
1931              */
1932             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
1933                 goto end;
1934         } else {
1935             /* Should fail because it should already be in the cache */
1936             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
1937                 goto end;
1938         }
1939     }
1940
1941     if (use_ext_cache) {
1942         SSL_SESSION *tmp = sess2;
1943
1944         if (!TEST_int_eq(new_called, numnewsesstick)
1945                 || !TEST_int_eq(remove_called, 0)
1946                 || !TEST_int_eq(get_called, 0))
1947             goto end;
1948         /*
1949          * Delete the session from the internal cache to force a lookup from
1950          * the external cache. We take a copy first because
1951          * SSL_CTX_remove_session() also marks the session as non-resumable.
1952          */
1953         if (use_int_cache && maxprot != TLS1_3_VERSION) {
1954             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
1955                     || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
1956                 goto end;
1957             SSL_SESSION_free(sess2);
1958         }
1959         sess2 = tmp;
1960     }
1961
1962     new_called = remove_called = get_called = 0;
1963     get_sess_val = sess2;
1964     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1965                                       &clientssl2, NULL, NULL))
1966             || !TEST_true(SSL_set_session(clientssl2, sess1))
1967             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1968                                                 SSL_ERROR_NONE))
1969             || !TEST_true(SSL_session_reused(clientssl2)))
1970         goto end;
1971
1972     if (use_ext_cache) {
1973         if (!TEST_int_eq(remove_called, 0))
1974             goto end;
1975
1976         if (maxprot == TLS1_3_VERSION) {
1977             if (!TEST_int_eq(new_called, 1)
1978                     || !TEST_int_eq(get_called, 0))
1979                 goto end;
1980         } else {
1981             if (!TEST_int_eq(new_called, 0)
1982                     || !TEST_int_eq(get_called, 1))
1983                 goto end;
1984         }
1985     }
1986
1987     testresult = 1;
1988
1989  end:
1990     SSL_free(serverssl1);
1991     SSL_free(clientssl1);
1992     SSL_free(serverssl2);
1993     SSL_free(clientssl2);
1994 # ifndef OPENSSL_NO_TLS1_1
1995     SSL_free(serverssl3);
1996     SSL_free(clientssl3);
1997 # endif
1998     SSL_SESSION_free(sess1);
1999     SSL_SESSION_free(sess2);
2000     SSL_CTX_free(sctx);
2001     SSL_CTX_free(cctx);
2002
2003     return testresult;
2004 }
2005 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
2006
2007 static int test_session_with_only_int_cache(void)
2008 {
2009 #ifndef OSSL_NO_USABLE_TLS1_3
2010     if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0))
2011         return 0;
2012 #endif
2013
2014 #ifndef OPENSSL_NO_TLS1_2
2015     return execute_test_session(TLS1_2_VERSION, 1, 0, 0);
2016 #else
2017     return 1;
2018 #endif
2019 }
2020
2021 static int test_session_with_only_ext_cache(void)
2022 {
2023 #ifndef OSSL_NO_USABLE_TLS1_3
2024     if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0))
2025         return 0;
2026 #endif
2027
2028 #ifndef OPENSSL_NO_TLS1_2
2029     return execute_test_session(TLS1_2_VERSION, 0, 1, 0);
2030 #else
2031     return 1;
2032 #endif
2033 }
2034
2035 static int test_session_with_both_cache(void)
2036 {
2037 #ifndef OSSL_NO_USABLE_TLS1_3
2038     if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0))
2039         return 0;
2040 #endif
2041
2042 #ifndef OPENSSL_NO_TLS1_2
2043     return execute_test_session(TLS1_2_VERSION, 1, 1, 0);
2044 #else
2045     return 1;
2046 #endif
2047 }
2048
2049 static int test_session_wo_ca_names(void)
2050 {
2051 #ifndef OSSL_NO_USABLE_TLS1_3
2052     if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES))
2053         return 0;
2054 #endif
2055
2056 #ifndef OPENSSL_NO_TLS1_2
2057     return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
2058 #else
2059     return 1;
2060 #endif
2061 }
2062
2063
2064 #ifndef OSSL_NO_USABLE_TLS1_3
2065 static SSL_SESSION *sesscache[6];
2066 static int do_cache;
2067
2068 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
2069 {
2070     if (do_cache) {
2071         sesscache[new_called] = sess;
2072     } else {
2073         /* We don't need the reference to the session, so free it */
2074         SSL_SESSION_free(sess);
2075     }
2076     new_called++;
2077
2078     return 1;
2079 }
2080
2081 static int post_handshake_verify(SSL *sssl, SSL *cssl)
2082 {
2083     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
2084     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
2085         return 0;
2086
2087     /* Start handshake on the server and client */
2088     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
2089             || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
2090             || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
2091             || !TEST_true(create_ssl_connection(sssl, cssl,
2092                                                 SSL_ERROR_NONE)))
2093         return 0;
2094
2095     return 1;
2096 }
2097
2098 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
2099                              SSL_CTX **cctx)
2100 {
2101     int sess_id_ctx = 1;
2102
2103     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2104                                        TLS_client_method(), TLS1_VERSION, 0,
2105                                        sctx, cctx, cert, privkey))
2106             || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
2107             || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
2108                                                          (void *)&sess_id_ctx,
2109                                                          sizeof(sess_id_ctx))))
2110         return 0;
2111
2112     if (stateful)
2113         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
2114
2115     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT
2116                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2117     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
2118
2119     return 1;
2120 }
2121
2122 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
2123 {
2124     SSL *serverssl = NULL, *clientssl = NULL;
2125     int i;
2126
2127     /* Test that we can resume with all the tickets we got given */
2128     for (i = 0; i < idx * 2; i++) {
2129         new_called = 0;
2130         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2131                                               &clientssl, NULL, NULL))
2132                 || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
2133             goto end;
2134
2135         SSL_set_post_handshake_auth(clientssl, 1);
2136
2137         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2138                                                     SSL_ERROR_NONE)))
2139             goto end;
2140
2141         /*
2142          * Following a successful resumption we only get 1 ticket. After a
2143          * failed one we should get idx tickets.
2144          */
2145         if (succ) {
2146             if (!TEST_true(SSL_session_reused(clientssl))
2147                     || !TEST_int_eq(new_called, 1))
2148                 goto end;
2149         } else {
2150             if (!TEST_false(SSL_session_reused(clientssl))
2151                     || !TEST_int_eq(new_called, idx))
2152                 goto end;
2153         }
2154
2155         new_called = 0;
2156         /* After a post-handshake authentication we should get 1 new ticket */
2157         if (succ
2158                 && (!post_handshake_verify(serverssl, clientssl)
2159                     || !TEST_int_eq(new_called, 1)))
2160             goto end;
2161
2162         SSL_shutdown(clientssl);
2163         SSL_shutdown(serverssl);
2164         SSL_free(serverssl);
2165         SSL_free(clientssl);
2166         serverssl = clientssl = NULL;
2167         SSL_SESSION_free(sesscache[i]);
2168         sesscache[i] = NULL;
2169     }
2170
2171     return 1;
2172
2173  end:
2174     SSL_free(clientssl);
2175     SSL_free(serverssl);
2176     return 0;
2177 }
2178
2179 static int test_tickets(int stateful, int idx)
2180 {
2181     SSL_CTX *sctx = NULL, *cctx = NULL;
2182     SSL *serverssl = NULL, *clientssl = NULL;
2183     int testresult = 0;
2184     size_t j;
2185
2186     /* idx is the test number, but also the number of tickets we want */
2187
2188     new_called = 0;
2189     do_cache = 1;
2190
2191     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2192         goto end;
2193
2194     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2195                                           &clientssl, NULL, NULL)))
2196         goto end;
2197
2198     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2199                                                 SSL_ERROR_NONE))
2200                /* Check we got the number of tickets we were expecting */
2201             || !TEST_int_eq(idx, new_called))
2202         goto end;
2203
2204     SSL_shutdown(clientssl);
2205     SSL_shutdown(serverssl);
2206     SSL_free(serverssl);
2207     SSL_free(clientssl);
2208     SSL_CTX_free(sctx);
2209     SSL_CTX_free(cctx);
2210     clientssl = serverssl = NULL;
2211     sctx = cctx = NULL;
2212
2213     /*
2214      * Now we try to resume with the tickets we previously created. The
2215      * resumption attempt is expected to fail (because we're now using a new
2216      * SSL_CTX). We should see idx number of tickets issued again.
2217      */
2218
2219     /* Stop caching sessions - just count them */
2220     do_cache = 0;
2221
2222     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2223         goto end;
2224
2225     if (!check_resumption(idx, sctx, cctx, 0))
2226         goto end;
2227
2228     /* Start again with caching sessions */
2229     new_called = 0;
2230     do_cache = 1;
2231     SSL_CTX_free(sctx);
2232     SSL_CTX_free(cctx);
2233     sctx = cctx = NULL;
2234
2235     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2236         goto end;
2237
2238     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2239                                           &clientssl, NULL, NULL)))
2240         goto end;
2241
2242     SSL_set_post_handshake_auth(clientssl, 1);
2243
2244     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2245                                                 SSL_ERROR_NONE))
2246                /* Check we got the number of tickets we were expecting */
2247             || !TEST_int_eq(idx, new_called))
2248         goto end;
2249
2250     /* After a post-handshake authentication we should get new tickets issued */
2251     if (!post_handshake_verify(serverssl, clientssl)
2252             || !TEST_int_eq(idx * 2, new_called))
2253         goto end;
2254
2255     SSL_shutdown(clientssl);
2256     SSL_shutdown(serverssl);
2257     SSL_free(serverssl);
2258     SSL_free(clientssl);
2259     serverssl = clientssl = NULL;
2260
2261     /* Stop caching sessions - just count them */
2262     do_cache = 0;
2263
2264     /*
2265      * Check we can resume with all the tickets we created. This time around the
2266      * resumptions should all be successful.
2267      */
2268     if (!check_resumption(idx, sctx, cctx, 1))
2269         goto end;
2270
2271     testresult = 1;
2272
2273  end:
2274     SSL_free(serverssl);
2275     SSL_free(clientssl);
2276     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2277         SSL_SESSION_free(sesscache[j]);
2278         sesscache[j] = NULL;
2279     }
2280     SSL_CTX_free(sctx);
2281     SSL_CTX_free(cctx);
2282
2283     return testresult;
2284 }
2285
2286 static int test_stateless_tickets(int idx)
2287 {
2288     return test_tickets(0, idx);
2289 }
2290
2291 static int test_stateful_tickets(int idx)
2292 {
2293     return test_tickets(1, idx);
2294 }
2295
2296 static int test_psk_tickets(void)
2297 {
2298     SSL_CTX *sctx = NULL, *cctx = NULL;
2299     SSL *serverssl = NULL, *clientssl = NULL;
2300     int testresult = 0;
2301     int sess_id_ctx = 1;
2302
2303     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2304                                        TLS_client_method(), TLS1_VERSION, 0,
2305                                        &sctx, &cctx, NULL, NULL))
2306             || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2307                                                          (void *)&sess_id_ctx,
2308                                                          sizeof(sess_id_ctx))))
2309         goto end;
2310
2311     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
2312                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2313     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2314     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2315     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2316     use_session_cb_cnt = 0;
2317     find_session_cb_cnt = 0;
2318     srvid = pskid;
2319     new_called = 0;
2320
2321     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2322                                       NULL, NULL)))
2323         goto end;
2324     clientpsk = serverpsk = create_a_psk(clientssl);
2325     if (!TEST_ptr(clientpsk))
2326         goto end;
2327     SSL_SESSION_up_ref(clientpsk);
2328
2329     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2330                                                 SSL_ERROR_NONE))
2331             || !TEST_int_eq(1, find_session_cb_cnt)
2332             || !TEST_int_eq(1, use_session_cb_cnt)
2333                /* We should always get 1 ticket when using external PSK */
2334             || !TEST_int_eq(1, new_called))
2335         goto end;
2336
2337     testresult = 1;
2338
2339  end:
2340     SSL_free(serverssl);
2341     SSL_free(clientssl);
2342     SSL_CTX_free(sctx);
2343     SSL_CTX_free(cctx);
2344     SSL_SESSION_free(clientpsk);
2345     SSL_SESSION_free(serverpsk);
2346     clientpsk = serverpsk = NULL;
2347
2348     return testresult;
2349 }
2350
2351 static int test_extra_tickets(int idx)
2352 {
2353     SSL_CTX *sctx = NULL, *cctx = NULL;
2354     SSL *serverssl = NULL, *clientssl = NULL;
2355     BIO *bretry = BIO_new(bio_s_always_retry());
2356     BIO *tmp = NULL;
2357     int testresult = 0;
2358     int stateful = 0;
2359     size_t nbytes;
2360     unsigned char c, buf[1];
2361
2362     new_called = 0;
2363     do_cache = 1;
2364
2365     if (idx >= 3) {
2366         idx -= 3;
2367         stateful = 1;
2368     }
2369
2370     if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2371         goto end;
2372     SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2373     /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2374     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2375
2376     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2377                                           &clientssl, NULL, NULL)))
2378         goto end;
2379
2380     /*
2381      * Note that we have new_session_cb on both sctx and cctx, so new_called is
2382      * incremented by both client and server.
2383      */
2384     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2385                                                 SSL_ERROR_NONE))
2386                /* Check we got the number of tickets we were expecting */
2387             || !TEST_int_eq(idx * 2, new_called)
2388             || !TEST_true(SSL_new_session_ticket(serverssl))
2389             || !TEST_true(SSL_new_session_ticket(serverssl))
2390             || !TEST_int_eq(idx * 2, new_called))
2391         goto end;
2392
2393     /* Now try a (real) write to actually send the tickets */
2394     c = '1';
2395     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2396             || !TEST_size_t_eq(1, nbytes)
2397             || !TEST_int_eq(idx * 2 + 2, new_called)
2398             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2399             || !TEST_int_eq(idx * 2 + 4, new_called)
2400             || !TEST_int_eq(sizeof(buf), nbytes)
2401             || !TEST_int_eq(c, buf[0])
2402             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2403         goto end;
2404
2405     /* Try with only requesting one new ticket, too */
2406     c = '2';
2407     new_called = 0;
2408     if (!TEST_true(SSL_new_session_ticket(serverssl))
2409             || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2410             || !TEST_size_t_eq(sizeof(c), nbytes)
2411             || !TEST_int_eq(1, new_called)
2412             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2413             || !TEST_int_eq(2, new_called)
2414             || !TEST_size_t_eq(sizeof(buf), nbytes)
2415             || !TEST_int_eq(c, buf[0]))
2416         goto end;
2417
2418     /* Do it again but use dummy writes to drive the ticket generation */
2419     c = '3';
2420     new_called = 0;
2421     if (!TEST_true(SSL_new_session_ticket(serverssl))
2422             || !TEST_true(SSL_new_session_ticket(serverssl))
2423             || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2424             || !TEST_size_t_eq(0, nbytes)
2425             || !TEST_int_eq(2, new_called)
2426             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2427             || !TEST_int_eq(4, new_called))
2428         goto end;
2429
2430     /*
2431      * Use the always-retry BIO to exercise the logic that forces ticket
2432      * generation to wait until a record boundary.
2433      */
2434     c = '4';
2435     new_called = 0;
2436     tmp = SSL_get_wbio(serverssl);
2437     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2438         tmp = NULL;
2439         goto end;
2440     }
2441     SSL_set0_wbio(serverssl, bretry);
2442     bretry = NULL;
2443     if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2444             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2445             || !TEST_size_t_eq(nbytes, 0))
2446         goto end;
2447     /* Restore a BIO that will let the write succeed */
2448     SSL_set0_wbio(serverssl, tmp);
2449     tmp = NULL;
2450     /* These calls should just queue the request and not send anything. */
2451     if (!TEST_true(SSL_new_session_ticket(serverssl))
2452             || !TEST_true(SSL_new_session_ticket(serverssl))
2453             || !TEST_int_eq(0, new_called))
2454         goto end;
2455     /* Re-do the write; still no tickets sent */
2456     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2457             || !TEST_size_t_eq(1, nbytes)
2458             || !TEST_int_eq(0, new_called)
2459             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2460             || !TEST_int_eq(0, new_called)
2461             || !TEST_int_eq(sizeof(buf), nbytes)
2462             || !TEST_int_eq(c, buf[0])
2463             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2464         goto end;
2465     /* Now the *next* write should send the tickets */
2466     c = '5';
2467     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2468             || !TEST_size_t_eq(1, nbytes)
2469             || !TEST_int_eq(2, new_called)
2470             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2471             || !TEST_int_eq(4, new_called)
2472             || !TEST_int_eq(sizeof(buf), nbytes)
2473             || !TEST_int_eq(c, buf[0])
2474             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2475         goto end;
2476
2477     SSL_shutdown(clientssl);
2478     SSL_shutdown(serverssl);
2479     testresult = 1;
2480
2481  end:
2482     BIO_free(bretry);
2483     BIO_free(tmp);
2484     SSL_free(serverssl);
2485     SSL_free(clientssl);
2486     SSL_CTX_free(sctx);
2487     SSL_CTX_free(cctx);
2488     clientssl = serverssl = NULL;
2489     sctx = cctx = NULL;
2490     return testresult;
2491 }
2492 #endif
2493
2494 #define USE_NULL            0
2495 #define USE_BIO_1           1
2496 #define USE_BIO_2           2
2497 #define USE_DEFAULT         3
2498
2499 #define CONNTYPE_CONNECTION_SUCCESS  0
2500 #define CONNTYPE_CONNECTION_FAIL     1
2501 #define CONNTYPE_NO_CONNECTION       2
2502
2503 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
2504 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
2505 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2506 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
2507 #else
2508 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
2509 #endif
2510
2511 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
2512                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2513                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2514
2515 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2516 {
2517     switch (type) {
2518     case USE_NULL:
2519         *res = NULL;
2520         break;
2521     case USE_BIO_1:
2522         *res = bio1;
2523         break;
2524     case USE_BIO_2:
2525         *res = bio2;
2526         break;
2527     }
2528 }
2529
2530
2531 /*
2532  * Tests calls to SSL_set_bio() under various conditions.
2533  *
2534  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2535  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2536  * then do more tests where we create a successful connection first using our
2537  * standard connection setup functions, and then call SSL_set_bio() with
2538  * various combinations of valid BIOs or NULL. We then repeat these tests
2539  * following a failed connection. In this last case we are looking to check that
2540  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2541  */
2542 static int test_ssl_set_bio(int idx)
2543 {
2544     SSL_CTX *sctx = NULL, *cctx = NULL;
2545     BIO *bio1 = NULL;
2546     BIO *bio2 = NULL;
2547     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2548     SSL *serverssl = NULL, *clientssl = NULL;
2549     int initrbio, initwbio, newrbio, newwbio, conntype;
2550     int testresult = 0;
2551
2552     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2553         initrbio = idx % 3;
2554         idx /= 3;
2555         initwbio = idx % 3;
2556         idx /= 3;
2557         newrbio = idx % 3;
2558         idx /= 3;
2559         newwbio = idx % 3;
2560         conntype = CONNTYPE_NO_CONNECTION;
2561     } else {
2562         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2563         initrbio = initwbio = USE_DEFAULT;
2564         newrbio = idx % 2;
2565         idx /= 2;
2566         newwbio = idx % 2;
2567         idx /= 2;
2568         conntype = idx % 2;
2569     }
2570
2571     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2572                                        TLS_client_method(), TLS1_VERSION, 0,
2573                                        &sctx, &cctx, cert, privkey)))
2574         goto end;
2575
2576     if (conntype == CONNTYPE_CONNECTION_FAIL) {
2577         /*
2578          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2579          * because we reduced the number of tests in the definition of
2580          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2581          * mismatched protocol versions we will force a connection failure.
2582          */
2583         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2584         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2585     }
2586
2587     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2588                                       NULL, NULL)))
2589         goto end;
2590
2591     if (initrbio == USE_BIO_1
2592             || initwbio == USE_BIO_1
2593             || newrbio == USE_BIO_1
2594             || newwbio == USE_BIO_1) {
2595         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2596             goto end;
2597     }
2598
2599     if (initrbio == USE_BIO_2
2600             || initwbio == USE_BIO_2
2601             || newrbio == USE_BIO_2
2602             || newwbio == USE_BIO_2) {
2603         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
2604             goto end;
2605     }
2606
2607     if (initrbio != USE_DEFAULT) {
2608         setupbio(&irbio, bio1, bio2, initrbio);
2609         setupbio(&iwbio, bio1, bio2, initwbio);
2610         SSL_set_bio(clientssl, irbio, iwbio);
2611
2612         /*
2613          * We want to maintain our own refs to these BIO, so do an up ref for
2614          * each BIO that will have ownership transferred in the SSL_set_bio()
2615          * call
2616          */
2617         if (irbio != NULL)
2618             BIO_up_ref(irbio);
2619         if (iwbio != NULL && iwbio != irbio)
2620             BIO_up_ref(iwbio);
2621     }
2622
2623     if (conntype != CONNTYPE_NO_CONNECTION
2624             && !TEST_true(create_ssl_connection(serverssl, clientssl,
2625                                                 SSL_ERROR_NONE)
2626                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
2627         goto end;
2628
2629     setupbio(&nrbio, bio1, bio2, newrbio);
2630     setupbio(&nwbio, bio1, bio2, newwbio);
2631
2632     /*
2633      * We will (maybe) transfer ownership again so do more up refs.
2634      * SSL_set_bio() has some really complicated ownership rules where BIOs have
2635      * already been set!
2636      */
2637     if (nrbio != NULL
2638             && nrbio != irbio
2639             && (nwbio != iwbio || nrbio != nwbio))
2640         BIO_up_ref(nrbio);
2641     if (nwbio != NULL
2642             && nwbio != nrbio
2643             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
2644         BIO_up_ref(nwbio);
2645
2646     SSL_set_bio(clientssl, nrbio, nwbio);
2647
2648     testresult = 1;
2649
2650  end:
2651     BIO_free(bio1);
2652     BIO_free(bio2);
2653
2654     /*
2655      * This test is checking that the ref counting for SSL_set_bio is correct.
2656      * If we get here and we did too many frees then we will fail in the above
2657      * functions.
2658      */
2659     SSL_free(serverssl);
2660     SSL_free(clientssl);
2661     SSL_CTX_free(sctx);
2662     SSL_CTX_free(cctx);
2663     return testresult;
2664 }
2665
2666 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
2667
2668 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
2669 {
2670     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
2671     SSL_CTX *ctx;
2672     SSL *ssl = NULL;
2673     int testresult = 0;
2674
2675     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
2676             || !TEST_ptr(ssl = SSL_new(ctx))
2677             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
2678             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
2679         goto end;
2680
2681     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
2682
2683     /*
2684      * If anything goes wrong here then we could leak memory.
2685      */
2686     BIO_push(sslbio, membio1);
2687
2688     /* Verify changing the rbio/wbio directly does not cause leaks */
2689     if (change_bio != NO_BIO_CHANGE) {
2690         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
2691             goto end;
2692         if (change_bio == CHANGE_RBIO)
2693             SSL_set0_rbio(ssl, membio2);
2694         else
2695             SSL_set0_wbio(ssl, membio2);
2696     }
2697     ssl = NULL;
2698
2699     if (pop_ssl)
2700         BIO_pop(sslbio);
2701     else
2702         BIO_pop(membio1);
2703
2704     testresult = 1;
2705  end:
2706     BIO_free(membio1);
2707     BIO_free(sslbio);
2708     SSL_free(ssl);
2709     SSL_CTX_free(ctx);
2710
2711     return testresult;
2712 }
2713
2714 static int test_ssl_bio_pop_next_bio(void)
2715 {
2716     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
2717 }
2718
2719 static int test_ssl_bio_pop_ssl_bio(void)
2720 {
2721     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
2722 }
2723
2724 static int test_ssl_bio_change_rbio(void)
2725 {
2726     return execute_test_ssl_bio(0, CHANGE_RBIO);
2727 }
2728
2729 static int test_ssl_bio_change_wbio(void)
2730 {
2731     return execute_test_ssl_bio(0, CHANGE_WBIO);
2732 }
2733
2734 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
2735 typedef struct {
2736     /* The list of sig algs */
2737     const int *list;
2738     /* The length of the list */
2739     size_t listlen;
2740     /* A sigalgs list in string format */
2741     const char *liststr;
2742     /* Whether setting the list should succeed */
2743     int valid;
2744     /* Whether creating a connection with the list should succeed */
2745     int connsuccess;
2746 } sigalgs_list;
2747
2748 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
2749 # ifndef OPENSSL_NO_EC
2750 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
2751 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
2752 # endif
2753 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
2754 static const int invalidlist2[] = {NID_sha256, NID_undef};
2755 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
2756 static const int invalidlist4[] = {NID_sha256};
2757 static const sigalgs_list testsigalgs[] = {
2758     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
2759 # ifndef OPENSSL_NO_EC
2760     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
2761     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
2762 # endif
2763     {NULL, 0, "RSA+SHA256", 1, 1},
2764 # ifndef OPENSSL_NO_EC
2765     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
2766     {NULL, 0, "ECDSA+SHA512", 1, 0},
2767 # endif
2768     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
2769     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
2770     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
2771     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
2772     {NULL, 0, "RSA", 0, 0},
2773     {NULL, 0, "SHA256", 0, 0},
2774     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
2775     {NULL, 0, "Invalid", 0, 0}
2776 };
2777
2778 static int test_set_sigalgs(int idx)
2779 {
2780     SSL_CTX *cctx = NULL, *sctx = NULL;
2781     SSL *clientssl = NULL, *serverssl = NULL;
2782     int testresult = 0;
2783     const sigalgs_list *curr;
2784     int testctx;
2785
2786     /* Should never happen */
2787     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
2788         return 0;
2789
2790     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
2791     curr = testctx ? &testsigalgs[idx]
2792                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
2793
2794     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2795                                        TLS_client_method(), TLS1_VERSION, 0,
2796                                        &sctx, &cctx, cert, privkey)))
2797         return 0;
2798
2799     /*
2800      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
2801      * for TLSv1.2 for now until we add a new API.
2802      */
2803     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2804
2805     if (testctx) {
2806         int ret;
2807
2808         if (curr->list != NULL)
2809             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
2810         else
2811             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
2812
2813         if (!ret) {
2814             if (curr->valid)
2815                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
2816             else
2817                 testresult = 1;
2818             goto end;
2819         }
2820         if (!curr->valid) {
2821             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
2822             goto end;
2823         }
2824     }
2825
2826     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2827                                       &clientssl, NULL, NULL)))
2828         goto end;
2829
2830     if (!testctx) {
2831         int ret;
2832
2833         if (curr->list != NULL)
2834             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
2835         else
2836             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
2837         if (!ret) {
2838             if (curr->valid)
2839                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
2840             else
2841                 testresult = 1;
2842             goto end;
2843         }
2844         if (!curr->valid)
2845             goto end;
2846     }
2847
2848     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
2849                                            SSL_ERROR_NONE),
2850                 curr->connsuccess))
2851         goto end;
2852
2853     testresult = 1;
2854
2855  end:
2856     SSL_free(serverssl);
2857     SSL_free(clientssl);
2858     SSL_CTX_free(sctx);
2859     SSL_CTX_free(cctx);
2860
2861     return testresult;
2862 }
2863 #endif
2864
2865 #ifndef OSSL_NO_USABLE_TLS1_3
2866 static int psk_client_cb_cnt = 0;
2867 static int psk_server_cb_cnt = 0;
2868
2869 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
2870                           size_t *idlen, SSL_SESSION **sess)
2871 {
2872     switch (++use_session_cb_cnt) {
2873     case 1:
2874         /* The first call should always have a NULL md */
2875         if (md != NULL)
2876             return 0;
2877         break;
2878
2879     case 2:
2880         /* The second call should always have an md */
2881         if (md == NULL)
2882             return 0;
2883         break;
2884
2885     default:
2886         /* We should only be called a maximum of twice */
2887         return 0;
2888     }
2889
2890     if (clientpsk != NULL)
2891         SSL_SESSION_up_ref(clientpsk);
2892
2893     *sess = clientpsk;
2894     *id = (const unsigned char *)pskid;
2895     *idlen = strlen(pskid);
2896
2897     return 1;
2898 }
2899
2900 #ifndef OPENSSL_NO_PSK
2901 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
2902                                   unsigned int max_id_len,
2903                                   unsigned char *psk,
2904                                   unsigned int max_psk_len)
2905 {
2906     unsigned int psklen = 0;
2907
2908     psk_client_cb_cnt++;
2909
2910     if (strlen(pskid) + 1 > max_id_len)
2911         return 0;
2912
2913     /* We should only ever be called a maximum of twice per connection */
2914     if (psk_client_cb_cnt > 2)
2915         return 0;
2916
2917     if (clientpsk == NULL)
2918         return 0;
2919
2920     /* We'll reuse the PSK we set up for TLSv1.3 */
2921     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
2922         return 0;
2923     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
2924     strncpy(id, pskid, max_id_len);
2925
2926     return psklen;
2927 }
2928 #endif /* OPENSSL_NO_PSK */
2929
2930 static int find_session_cb(SSL *ssl, const unsigned char *identity,
2931                            size_t identity_len, SSL_SESSION **sess)
2932 {
2933     find_session_cb_cnt++;
2934
2935     /* We should only ever be called a maximum of twice per connection */
2936     if (find_session_cb_cnt > 2)
2937         return 0;
2938
2939     if (serverpsk == NULL)
2940         return 0;
2941
2942     /* Identity should match that set by the client */
2943     if (strlen(srvid) != identity_len
2944             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
2945         /* No PSK found, continue but without a PSK */
2946         *sess = NULL;
2947         return 1;
2948     }
2949
2950     SSL_SESSION_up_ref(serverpsk);
2951     *sess = serverpsk;
2952
2953     return 1;
2954 }
2955
2956 #ifndef OPENSSL_NO_PSK
2957 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
2958                                   unsigned char *psk, unsigned int max_psk_len)
2959 {
2960     unsigned int psklen = 0;
2961
2962     psk_server_cb_cnt++;
2963
2964     /* We should only ever be called a maximum of twice per connection */
2965     if (find_session_cb_cnt > 2)
2966         return 0;
2967
2968     if (serverpsk == NULL)
2969         return 0;
2970
2971     /* Identity should match that set by the client */
2972     if (strcmp(srvid, identity) != 0) {
2973         return 0;
2974     }
2975
2976     /* We'll reuse the PSK we set up for TLSv1.3 */
2977     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
2978         return 0;
2979     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
2980
2981     return psklen;
2982 }
2983 #endif /* OPENSSL_NO_PSK */
2984
2985 #define MSG1    "Hello"
2986 #define MSG2    "World."
2987 #define MSG3    "This"
2988 #define MSG4    "is"
2989 #define MSG5    "a"
2990 #define MSG6    "test"
2991 #define MSG7    "message."
2992
2993 #define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
2994 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
2995 #define TLS13_CHACHA20_POLY1305_SHA256_BYTES ((const unsigned char *)"\x13\x03")
2996 #define TLS13_AES_128_CCM_SHA256_BYTES ((const unsigned char *)"\x13\x04")
2997 #define TLS13_AES_128_CCM_8_SHA256_BYTES ((const unsigned char *)"\x13\05")
2998
2999
3000 static SSL_SESSION *create_a_psk(SSL *ssl)
3001 {
3002     const SSL_CIPHER *cipher = NULL;
3003     const unsigned char key[] = {
3004         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
3005         0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
3006         0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
3007         0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
3008         0x2c, 0x2d, 0x2e, 0x2f
3009     };
3010     SSL_SESSION *sess = NULL;
3011
3012     cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES);
3013     sess = SSL_SESSION_new();
3014     if (!TEST_ptr(sess)
3015             || !TEST_ptr(cipher)
3016             || !TEST_true(SSL_SESSION_set1_master_key(sess, key,
3017                                                       sizeof(key)))
3018             || !TEST_true(SSL_SESSION_set_cipher(sess, cipher))
3019             || !TEST_true(
3020                     SSL_SESSION_set_protocol_version(sess,
3021                                                      TLS1_3_VERSION))) {
3022         SSL_SESSION_free(sess);
3023         return NULL;
3024     }
3025     return sess;
3026 }
3027
3028 /*
3029  * Helper method to setup objects for early data test. Caller frees objects on
3030  * error.
3031  */
3032 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
3033                                 SSL **serverssl, SSL_SESSION **sess, int idx)
3034 {
3035     if (*sctx == NULL
3036             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3037                                               TLS_client_method(),
3038                                               TLS1_VERSION, 0,
3039                                               sctx, cctx, cert, privkey)))
3040         return 0;
3041
3042     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
3043         return 0;
3044
3045     if (idx == 1) {
3046         /* When idx == 1 we repeat the tests with read_ahead set */
3047         SSL_CTX_set_read_ahead(*cctx, 1);
3048         SSL_CTX_set_read_ahead(*sctx, 1);
3049     } else if (idx == 2) {
3050         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
3051         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
3052         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
3053         use_session_cb_cnt = 0;
3054         find_session_cb_cnt = 0;
3055         srvid = pskid;
3056     }
3057
3058     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
3059                                       NULL, NULL)))
3060         return 0;
3061
3062     /*
3063      * For one of the run throughs (doesn't matter which one), we'll try sending
3064      * some SNI data in the initial ClientHello. This will be ignored (because
3065      * there is no SNI cb set up by the server), so it should not impact
3066      * early_data.
3067      */
3068     if (idx == 1
3069             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
3070         return 0;
3071
3072     if (idx == 2) {
3073         clientpsk = create_a_psk(*clientssl);
3074         if (!TEST_ptr(clientpsk)
3075                    /*
3076                     * We just choose an arbitrary value for max_early_data which
3077                     * should be big enough for testing purposes.
3078                     */
3079                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
3080                                                              0x100))
3081                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3082             SSL_SESSION_free(clientpsk);
3083             clientpsk = NULL;
3084             return 0;
3085         }
3086         serverpsk = clientpsk;
3087
3088         if (sess != NULL) {
3089             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3090                 SSL_SESSION_free(clientpsk);
3091                 SSL_SESSION_free(serverpsk);
3092                 clientpsk = serverpsk = NULL;
3093                 return 0;
3094             }
3095             *sess = clientpsk;
3096         }
3097         return 1;
3098     }
3099
3100     if (sess == NULL)
3101         return 1;
3102
3103     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
3104                                          SSL_ERROR_NONE)))
3105         return 0;
3106
3107     *sess = SSL_get1_session(*clientssl);
3108     SSL_shutdown(*clientssl);
3109     SSL_shutdown(*serverssl);
3110     SSL_free(*serverssl);
3111     SSL_free(*clientssl);
3112     *serverssl = *clientssl = NULL;
3113
3114     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
3115                                       clientssl, NULL, NULL))
3116             || !TEST_true(SSL_set_session(*clientssl, *sess)))
3117         return 0;
3118
3119     return 1;
3120 }
3121
3122 static int test_early_data_read_write(int idx)
3123 {
3124     SSL_CTX *cctx = NULL, *sctx = NULL;
3125     SSL *clientssl = NULL, *serverssl = NULL;
3126     int testresult = 0;
3127     SSL_SESSION *sess = NULL;
3128     unsigned char buf[20], data[1024];
3129     size_t readbytes, written, eoedlen, rawread, rawwritten;
3130     BIO *rbio;
3131
3132     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3133                                         &serverssl, &sess, idx)))
3134         goto end;
3135
3136     /* Write and read some early data */
3137     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3138                                         &written))
3139             || !TEST_size_t_eq(written, strlen(MSG1))
3140             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
3141                                                 sizeof(buf), &readbytes),
3142                             SSL_READ_EARLY_DATA_SUCCESS)
3143             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
3144             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3145                             SSL_EARLY_DATA_ACCEPTED))
3146         goto end;
3147
3148     /*
3149      * Server should be able to write data, and client should be able to
3150      * read it.
3151      */
3152     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
3153                                         &written))
3154             || !TEST_size_t_eq(written, strlen(MSG2))
3155             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3156             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3157         goto end;
3158
3159     /* Even after reading normal data, client should be able write early data */
3160     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
3161                                         &written))
3162             || !TEST_size_t_eq(written, strlen(MSG3)))
3163         goto end;
3164
3165     /* Server should still be able read early data after writing data */
3166     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3167                                          &readbytes),
3168                      SSL_READ_EARLY_DATA_SUCCESS)
3169             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
3170         goto end;
3171
3172     /* Write more data from server and read it from client */
3173     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
3174                                         &written))
3175             || !TEST_size_t_eq(written, strlen(MSG4))
3176             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3177             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
3178         goto end;
3179
3180     /*
3181      * If client writes normal data it should mean writing early data is no
3182      * longer possible.
3183      */
3184     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3185             || !TEST_size_t_eq(written, strlen(MSG5))
3186             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3187                             SSL_EARLY_DATA_ACCEPTED))
3188         goto end;
3189
3190     /*
3191      * At this point the client has written EndOfEarlyData, ClientFinished and
3192      * normal (fully protected) data. We are going to cause a delay between the
3193      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
3194      * in the read BIO, and then just put back the EndOfEarlyData message.
3195      */
3196     rbio = SSL_get_rbio(serverssl);
3197     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
3198             || !TEST_size_t_lt(rawread, sizeof(data))
3199             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
3200         goto end;
3201
3202     /* Record length is in the 4th and 5th bytes of the record header */
3203     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
3204     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
3205             || !TEST_size_t_eq(rawwritten, eoedlen))
3206         goto end;
3207
3208     /* Server should be told that there is no more early data */
3209     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3210                                          &readbytes),
3211                      SSL_READ_EARLY_DATA_FINISH)
3212             || !TEST_size_t_eq(readbytes, 0))
3213         goto end;
3214
3215     /*
3216      * Server has not finished init yet, so should still be able to write early
3217      * data.
3218      */
3219     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
3220                                         &written))
3221             || !TEST_size_t_eq(written, strlen(MSG6)))
3222         goto end;
3223
3224     /* Push the ClientFinished and the normal data back into the server rbio */
3225     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
3226                                 &rawwritten))
3227             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
3228         goto end;
3229
3230     /* Server should be able to read normal data */
3231     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3232             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3233         goto end;
3234
3235     /* Client and server should not be able to write/read early data now */
3236     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3237                                          &written)))
3238         goto end;
3239     ERR_clear_error();
3240     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3241                                          &readbytes),
3242                      SSL_READ_EARLY_DATA_ERROR))
3243         goto end;
3244     ERR_clear_error();
3245
3246     /* Client should be able to read the data sent by the server */
3247     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3248             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
3249         goto end;
3250
3251     /*
3252      * Make sure we process the two NewSessionTickets. These arrive
3253      * post-handshake. We attempt reads which we do not expect to return any
3254      * data.
3255      */
3256     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3257             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3258                            &readbytes)))
3259         goto end;
3260
3261     /* Server should be able to write normal data */
3262     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3263             || !TEST_size_t_eq(written, strlen(MSG7))
3264             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3265             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3266         goto end;
3267
3268     SSL_SESSION_free(sess);
3269     sess = SSL_get1_session(clientssl);
3270     use_session_cb_cnt = 0;
3271     find_session_cb_cnt = 0;
3272
3273     SSL_shutdown(clientssl);
3274     SSL_shutdown(serverssl);
3275     SSL_free(serverssl);
3276     SSL_free(clientssl);
3277     serverssl = clientssl = NULL;
3278     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3279                                       &clientssl, NULL, NULL))
3280             || !TEST_true(SSL_set_session(clientssl, sess)))
3281         goto end;
3282
3283     /* Write and read some early data */
3284     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3285                                         &written))
3286             || !TEST_size_t_eq(written, strlen(MSG1))
3287             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3288                                                 &readbytes),
3289                             SSL_READ_EARLY_DATA_SUCCESS)
3290             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3291         goto end;
3292
3293     if (!TEST_int_gt(SSL_connect(clientssl), 0)
3294             || !TEST_int_gt(SSL_accept(serverssl), 0))
3295         goto end;
3296
3297     /* Client and server should not be able to write/read early data now */
3298     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3299                                          &written)))
3300         goto end;
3301     ERR_clear_error();
3302     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3303                                          &readbytes),
3304                      SSL_READ_EARLY_DATA_ERROR))
3305         goto end;
3306     ERR_clear_error();
3307
3308     /* Client and server should be able to write/read normal data */
3309     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3310             || !TEST_size_t_eq(written, strlen(MSG5))
3311             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3312             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3313         goto end;
3314
3315     testresult = 1;
3316
3317  end:
3318     SSL_SESSION_free(sess);
3319     SSL_SESSION_free(clientpsk);
3320     SSL_SESSION_free(serverpsk);
3321     clientpsk = serverpsk = NULL;
3322     SSL_free(serverssl);
3323     SSL_free(clientssl);
3324     SSL_CTX_free(sctx);
3325     SSL_CTX_free(cctx);
3326     return testresult;
3327 }
3328
3329 static int allow_ed_cb_called = 0;
3330
3331 static int allow_early_data_cb(SSL *s, void *arg)
3332 {
3333     int *usecb = (int *)arg;
3334
3335     allow_ed_cb_called++;
3336
3337     if (*usecb == 1)
3338         return 0;
3339
3340     return 1;
3341 }
3342
3343 /*
3344  * idx == 0: Standard early_data setup
3345  * idx == 1: early_data setup using read_ahead
3346  * usecb == 0: Don't use a custom early data callback
3347  * usecb == 1: Use a custom early data callback and reject the early data
3348  * usecb == 2: Use a custom early data callback and accept the early data
3349  * confopt == 0: Configure anti-replay directly
3350  * confopt == 1: Configure anti-replay using SSL_CONF
3351  */
3352 static int test_early_data_replay_int(int idx, int usecb, int confopt)
3353 {
3354     SSL_CTX *cctx = NULL, *sctx = NULL;
3355     SSL *clientssl = NULL, *serverssl = NULL;
3356     int testresult = 0;
3357     SSL_SESSION *sess = NULL;
3358     size_t readbytes, written;
3359     unsigned char buf[20];
3360
3361     allow_ed_cb_called = 0;
3362
3363     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3364                                        TLS_client_method(), TLS1_VERSION, 0,
3365                                        &sctx, &cctx, cert, privkey)))
3366         return 0;
3367
3368     if (usecb > 0) {
3369         if (confopt == 0) {
3370             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3371         } else {
3372             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3373
3374             if (!TEST_ptr(confctx))
3375                 goto end;
3376             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
3377                                             | SSL_CONF_FLAG_SERVER);
3378             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3379             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3380                              2)) {
3381                 SSL_CONF_CTX_free(confctx);
3382                 goto end;
3383             }
3384             SSL_CONF_CTX_free(confctx);
3385         }
3386         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3387     }
3388
3389     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3390                                         &serverssl, &sess, idx)))
3391         goto end;
3392
3393     /*
3394      * The server is configured to accept early data. Create a connection to
3395      * "use up" the ticket
3396      */
3397     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3398             || !TEST_true(SSL_session_reused(clientssl)))
3399         goto end;
3400
3401     SSL_shutdown(clientssl);
3402     SSL_shutdown(serverssl);
3403     SSL_free(serverssl);
3404     SSL_free(clientssl);
3405     serverssl = clientssl = NULL;
3406
3407     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3408                                       &clientssl, NULL, NULL))
3409             || !TEST_true(SSL_set_session(clientssl, sess)))
3410         goto end;
3411
3412     /* Write and read some early data */
3413     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3414                                         &written))
3415             || !TEST_size_t_eq(written, strlen(MSG1)))
3416         goto end;
3417
3418     if (usecb <= 1) {
3419         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3420                                              &readbytes),
3421                          SSL_READ_EARLY_DATA_FINISH)
3422                    /*
3423                     * The ticket was reused, so the we should have rejected the
3424                     * early data
3425                     */
3426                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3427                                 SSL_EARLY_DATA_REJECTED))
3428             goto end;
3429     } else {
3430         /* In this case the callback decides to accept the early data */
3431         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3432                                              &readbytes),
3433                          SSL_READ_EARLY_DATA_SUCCESS)
3434                 || !TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3435                    /*
3436                     * Server will have sent its flight so client can now send
3437                     * end of early data and complete its half of the handshake
3438                     */
3439                 || !TEST_int_gt(SSL_connect(clientssl), 0)
3440                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3441                                              &readbytes),
3442                                 SSL_READ_EARLY_DATA_FINISH)
3443                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3444                                 SSL_EARLY_DATA_ACCEPTED))
3445             goto end;
3446     }
3447
3448     /* Complete the connection */
3449     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3450             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3451             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3452         goto end;
3453
3454     testresult = 1;
3455
3456  end:
3457     SSL_SESSION_free(sess);
3458     SSL_SESSION_free(clientpsk);
3459     SSL_SESSION_free(serverpsk);
3460     clientpsk = serverpsk = NULL;
3461     SSL_free(serverssl);
3462     SSL_free(clientssl);
3463     SSL_CTX_free(sctx);
3464     SSL_CTX_free(cctx);
3465     return testresult;
3466 }
3467
3468 static int test_early_data_replay(int idx)
3469 {
3470     int ret = 1, usecb, confopt;
3471
3472     for (usecb = 0; usecb < 3; usecb++) {
3473         for (confopt = 0; confopt < 2; confopt++)
3474             ret &= test_early_data_replay_int(idx, usecb, confopt);
3475     }
3476
3477     return ret;
3478 }
3479
3480 /*
3481  * Helper function to test that a server attempting to read early data can
3482  * handle a connection from a client where the early data should be skipped.
3483  * testtype: 0 == No HRR
3484  * testtype: 1 == HRR
3485  * testtype: 2 == HRR, invalid early_data sent after HRR
3486  * testtype: 3 == recv_max_early_data set to 0
3487  */
3488 static int early_data_skip_helper(int testtype, int idx)
3489 {
3490     SSL_CTX *cctx = NULL, *sctx = NULL;
3491     SSL *clientssl = NULL, *serverssl = NULL;
3492     int testresult = 0;
3493     SSL_SESSION *sess = NULL;
3494     unsigned char buf[20];
3495     size_t readbytes, written;
3496
3497     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3498                                         &serverssl, &sess, idx)))
3499         goto end;
3500
3501     if (testtype == 1 || testtype == 2) {
3502         /* Force an HRR to occur */
3503 #if defined(OPENSSL_NO_EC)
3504         if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
3505             goto end;
3506 #else
3507         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
3508             goto end;
3509 #endif
3510     } else if (idx == 2) {
3511         /*
3512          * We force early_data rejection by ensuring the PSK identity is
3513          * unrecognised
3514          */
3515         srvid = "Dummy Identity";
3516     } else {
3517         /*
3518          * Deliberately corrupt the creation time. We take 20 seconds off the
3519          * time. It could be any value as long as it is not within tolerance.
3520          * This should mean the ticket is rejected.
3521          */
3522         if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
3523             goto end;
3524     }
3525
3526     if (testtype == 3
3527             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
3528         goto end;
3529
3530     /* Write some early data */
3531     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3532                                         &written))
3533             || !TEST_size_t_eq(written, strlen(MSG1)))
3534         goto end;
3535
3536     /* Server should reject the early data */
3537     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3538                                          &readbytes),
3539                      SSL_READ_EARLY_DATA_FINISH)
3540             || !TEST_size_t_eq(readbytes, 0)
3541             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3542                             SSL_EARLY_DATA_REJECTED))
3543         goto end;
3544
3545     switch (testtype) {
3546     case 0:
3547         /* Nothing to do */
3548         break;
3549
3550     case 1:
3551         /*
3552          * Finish off the handshake. We perform the same writes and reads as
3553          * further down but we expect them to fail due to the incomplete
3554          * handshake.
3555          */
3556         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3557                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
3558                                &readbytes)))
3559             goto end;
3560         break;
3561
3562     case 2:
3563         {
3564             BIO *wbio = SSL_get_wbio(clientssl);
3565             /* A record that will appear as bad early_data */
3566             const unsigned char bad_early_data[] = {
3567                 0x17, 0x03, 0x03, 0x00, 0x01, 0x00
3568             };
3569
3570             /*
3571              * We force the client to attempt a write. This will fail because
3572              * we're still in the handshake. It will cause the second
3573              * ClientHello to be sent.
3574              */
3575             if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
3576                                          &written)))
3577                 goto end;
3578
3579             /*
3580              * Inject some early_data after the second ClientHello. This should
3581              * cause the server to fail
3582              */
3583             if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
3584                                         sizeof(bad_early_data), &written)))
3585                 goto end;
3586         }
3587         /* fallthrough */
3588
3589     case 3:
3590         /*
3591          * This client has sent more early_data than we are willing to skip
3592          * (case 3) or sent invalid early_data (case 2) so the connection should
3593          * abort.
3594          */
3595         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3596                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
3597             goto end;
3598
3599         /* Connection has failed - nothing more to do */
3600         testresult = 1;
3601         goto end;
3602
3603     default:
3604         TEST_error("Invalid test type");
3605         goto end;
3606     }
3607
3608     /*
3609      * Should be able to send normal data despite rejection of early data. The
3610      * early_data should be skipped.
3611      */
3612     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3613             || !TEST_size_t_eq(written, strlen(MSG2))
3614             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3615                             SSL_EARLY_DATA_REJECTED)
3616             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3617             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3618         goto end;
3619
3620     testresult = 1;
3621
3622  end:
3623     SSL_SESSION_free(clientpsk);
3624     SSL_SESSION_free(serverpsk);
3625     clientpsk = serverpsk = NULL;
3626     SSL_SESSION_free(sess);
3627     SSL_free(serverssl);
3628     SSL_free(clientssl);
3629     SSL_CTX_free(sctx);
3630     SSL_CTX_free(cctx);
3631     return testresult;
3632 }
3633
3634 /*
3635  * Test that a server attempting to read early data can handle a connection
3636  * from a client where the early data is not acceptable.
3637  */
3638 static int test_early_data_skip(int idx)
3639 {
3640     return early_data_skip_helper(0, idx);
3641 }
3642
3643 /*
3644  * Test that a server attempting to read early data can handle a connection
3645  * from a client where an HRR occurs.
3646  */
3647 static int test_early_data_skip_hrr(int idx)
3648 {
3649     return early_data_skip_helper(1, idx);
3650 }
3651
3652 /*
3653  * Test that a server attempting to read early data can handle a connection
3654  * from a client where an HRR occurs and correctly fails if early_data is sent
3655  * after the HRR
3656  */
3657 static int test_early_data_skip_hrr_fail(int idx)
3658 {
3659     return early_data_skip_helper(2, idx);
3660 }
3661
3662 /*
3663  * Test that a server attempting to read early data will abort if it tries to
3664  * skip over too much.
3665  */
3666 static int test_early_data_skip_abort(int idx)
3667 {
3668     return early_data_skip_helper(3, idx);
3669 }
3670
3671 /*
3672  * Test that a server attempting to read early data can handle a connection
3673  * from a client that doesn't send any.
3674  */
3675 static int test_early_data_not_sent(int idx)
3676 {
3677     SSL_CTX *cctx = NULL, *sctx = NULL;
3678     SSL *clientssl = NULL, *serverssl = NULL;
3679     int testresult = 0;
3680     SSL_SESSION *sess = NULL;
3681     unsigned char buf[20];
3682     size_t readbytes, written;
3683
3684     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3685                                         &serverssl, &sess, idx)))
3686         goto end;
3687
3688     /* Write some data - should block due to handshake with server */
3689     SSL_set_connect_state(clientssl);
3690     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
3691         goto end;
3692
3693     /* Server should detect that early data has not been sent */
3694     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3695                                          &readbytes),
3696                      SSL_READ_EARLY_DATA_FINISH)
3697             || !TEST_size_t_eq(readbytes, 0)
3698             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3699                             SSL_EARLY_DATA_NOT_SENT)
3700             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3701                             SSL_EARLY_DATA_NOT_SENT))
3702         goto end;
3703
3704     /* Continue writing the message we started earlier */
3705     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3706             || !TEST_size_t_eq(written, strlen(MSG1))
3707             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3708             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
3709             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
3710             || !TEST_size_t_eq(written, strlen(MSG2)))
3711         goto end;
3712
3713     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3714             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3715         goto end;
3716
3717     testresult = 1;
3718
3719  end:
3720     SSL_SESSION_free(sess);
3721     SSL_SESSION_free(clientpsk);
3722     SSL_SESSION_free(serverpsk);
3723     clientpsk = serverpsk = NULL;
3724     SSL_free(serverssl);
3725     SSL_free(clientssl);
3726     SSL_CTX_free(sctx);
3727     SSL_CTX_free(cctx);
3728     return testresult;
3729 }
3730
3731 static const char *servalpn;
3732
3733 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
3734                           unsigned char *outlen, const unsigned char *in,
3735                           unsigned int inlen, void *arg)
3736 {
3737     unsigned int protlen = 0;
3738     const unsigned char *prot;
3739
3740     for (prot = in; prot < in + inlen; prot += protlen) {
3741         protlen = *prot++;
3742         if (in + inlen < prot + protlen)
3743             return SSL_TLSEXT_ERR_NOACK;
3744
3745         if (protlen == strlen(servalpn)
3746                 && memcmp(prot, servalpn, protlen) == 0) {
3747             *out = prot;
3748             *outlen = protlen;
3749             return SSL_TLSEXT_ERR_OK;
3750         }
3751     }
3752
3753     return SSL_TLSEXT_ERR_NOACK;
3754 }
3755
3756 /* Test that a PSK can be used to send early_data */
3757 static int test_early_data_psk(int idx)
3758 {
3759     SSL_CTX *cctx = NULL, *sctx = NULL;
3760     SSL *clientssl = NULL, *serverssl = NULL;
3761     int testresult = 0;
3762     SSL_SESSION *sess = NULL;
3763     unsigned char alpnlist[] = {
3764         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
3765         'l', 'p', 'n'
3766     };
3767 #define GOODALPNLEN     9
3768 #define BADALPNLEN      8
3769 #define GOODALPN        (alpnlist)
3770 #define BADALPN         (alpnlist + GOODALPNLEN)
3771     int err = 0;
3772     unsigned char buf[20];
3773     size_t readbytes, written;
3774     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
3775     int edstatus = SSL_EARLY_DATA_ACCEPTED;
3776
3777     /* We always set this up with a final parameter of "2" for PSK */
3778     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3779                                         &serverssl, &sess, 2)))
3780         goto end;
3781
3782     servalpn = "goodalpn";
3783
3784     /*
3785      * Note: There is no test for inconsistent SNI with late client detection.
3786      * This is because servers do not acknowledge SNI even if they are using
3787      * it in a resumption handshake - so it is not actually possible for a
3788      * client to detect a problem.
3789      */
3790     switch (idx) {
3791     case 0:
3792         /* Set inconsistent SNI (early client detection) */
3793         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
3794         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
3795                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
3796             goto end;
3797         break;
3798
3799     case 1:
3800         /* Set inconsistent ALPN (early client detection) */
3801         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
3802         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
3803         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
3804                                                       GOODALPNLEN))
3805                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
3806                                                    BADALPNLEN)))
3807             goto end;
3808         break;
3809
3810     case 2:
3811         /*
3812          * Set invalid protocol version. Technically this affects PSKs without
3813          * early_data too, but we test it here because it is similar to the
3814          * SNI/ALPN consistency tests.
3815          */
3816         err = SSL_R_BAD_PSK;
3817         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
3818             goto end;
3819         break;
3820
3821     case 3:
3822         /*
3823          * Set inconsistent SNI (server side). In this case the connection
3824          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
3825          * is associated with each handshake - not the session. Therefore it
3826          * should not matter that we used a different server name last time.
3827          */
3828         SSL_SESSION_free(serverpsk);
3829         serverpsk = SSL_SESSION_dup(clientpsk);
3830         if (!TEST_ptr(serverpsk)
3831                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
3832             goto end;
3833         /* Fall through */
3834     case 4:
3835         /* Set consistent SNI */
3836         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
3837                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
3838                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
3839                                 hostname_cb)))
3840             goto end;
3841         break;
3842
3843     case 5:
3844         /*
3845          * Set inconsistent ALPN (server detected). In this case the connection
3846          * will succeed but reject early_data.
3847          */
3848         servalpn = "badalpn";
3849         edstatus = SSL_EARLY_DATA_REJECTED;
3850         readearlyres = SSL_READ_EARLY_DATA_FINISH;
3851         /* Fall through */
3852     case 6:
3853         /*
3854          * Set consistent ALPN.
3855          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
3856          * accepts a list of protos (each one length prefixed).
3857          * SSL_set1_alpn_selected accepts a single protocol (not length
3858          * prefixed)
3859          */
3860         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
3861                                                       GOODALPNLEN - 1))
3862                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
3863                                                    GOODALPNLEN)))
3864             goto end;
3865
3866         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3867         break;
3868
3869     case 7:
3870         /* Set inconsistent ALPN (late client detection) */
3871         SSL_SESSION_free(serverpsk);
3872         serverpsk = SSL_SESSION_dup(clientpsk);
3873         if (!TEST_ptr(serverpsk)
3874                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
3875                                                              BADALPN + 1,
3876                                                              BADALPNLEN - 1))
3877                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
3878                                                              GOODALPN + 1,
3879                                                              GOODALPNLEN - 1))
3880                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
3881                                                    sizeof(alpnlist))))
3882             goto end;
3883         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3884         edstatus = SSL_EARLY_DATA_ACCEPTED;
3885         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
3886         /* SSL_connect() call should fail */
3887         connectres = -1;
3888         break;
3889
3890     default:
3891         TEST_error("Bad test index");
3892         goto end;
3893     }
3894
3895     SSL_set_connect_state(clientssl);
3896     if (err != 0) {
3897         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3898                                             &written))
3899                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
3900                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
3901             goto end;
3902     } else {
3903         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3904                                             &written)))
3905             goto end;
3906
3907         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3908                                              &readbytes), readearlyres)
3909                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
3910                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3911                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
3912                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
3913             goto end;
3914     }
3915
3916     testresult = 1;
3917
3918  end:
3919     SSL_SESSION_free(sess);
3920     SSL_SESSION_free(clientpsk);
3921     SSL_SESSION_free(serverpsk);
3922     clientpsk = serverpsk = NULL;
3923     SSL_free(serverssl);
3924     SSL_free(clientssl);
3925     SSL_CTX_free(sctx);
3926     SSL_CTX_free(cctx);
3927     return testresult;
3928 }
3929
3930 /*
3931  * Test TLSv1.3 PSK can be used to send early_data with all 5 ciphersuites
3932  * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
3933  * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
3934  * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3935  * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
3936  * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
3937  */
3938 static int test_early_data_psk_with_all_ciphers(int idx)
3939 {
3940     SSL_CTX *cctx = NULL, *sctx = NULL;
3941     SSL *clientssl = NULL, *serverssl = NULL;
3942     int testresult = 0;
3943     SSL_SESSION *sess = NULL;
3944     unsigned char buf[20];
3945     size_t readbytes, written;
3946     const SSL_CIPHER *cipher;
3947     const char *cipher_str[] = {
3948         TLS1_3_RFC_AES_128_GCM_SHA256,
3949         TLS1_3_RFC_AES_256_GCM_SHA384,
3950 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3951         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
3952 # else
3953         NULL,
3954 # endif
3955         TLS1_3_RFC_AES_128_CCM_SHA256,
3956         TLS1_3_RFC_AES_128_CCM_8_SHA256
3957     };
3958     const unsigned char *cipher_bytes[] = {
3959         TLS13_AES_128_GCM_SHA256_BYTES,
3960         TLS13_AES_256_GCM_SHA384_BYTES,
3961 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3962         TLS13_CHACHA20_POLY1305_SHA256_BYTES,
3963 # else
3964         NULL,
3965 # endif
3966         TLS13_AES_128_CCM_SHA256_BYTES,
3967         TLS13_AES_128_CCM_8_SHA256_BYTES
3968     };
3969
3970     if (cipher_str[idx] == NULL)
3971         return 1;
3972     /* Skip ChaCha20Poly1305 as currently FIPS module does not support it */
3973     if (idx == 2 && is_fips == 1)
3974         return 1;
3975
3976     /* We always set this up with a final parameter of "2" for PSK */
3977     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3978                                         &serverssl, &sess, 2)))
3979         goto end;
3980
3981     if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
3982             || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
3983         goto end;
3984
3985     /*
3986      * 'setupearly_data_test' creates only one instance of SSL_SESSION
3987      * and assigns to both client and server with incremented reference
3988      * and the same instance is updated in 'sess'.
3989      * So updating ciphersuite in 'sess' which will get reflected in
3990      * PSK handshake using psk use sess and find sess cb.
3991      */
3992     cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
3993     if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
3994         goto end;
3995
3996     SSL_set_connect_state(clientssl);
3997     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3998                                         &written)))
3999         goto end;
4000
4001     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4002                                          &readbytes),
4003                                          SSL_READ_EARLY_DATA_SUCCESS)
4004             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4005             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4006                                                       SSL_EARLY_DATA_ACCEPTED)
4007             || !TEST_int_eq(SSL_connect(clientssl), 1)
4008             || !TEST_int_eq(SSL_accept(serverssl), 1))
4009         goto end;
4010
4011     /* Send some normal data from client to server */
4012     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4013             || !TEST_size_t_eq(written, strlen(MSG2)))
4014         goto end;
4015
4016     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4017             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4018         goto end;
4019
4020     testresult = 1;
4021  end:
4022     SSL_SESSION_free(sess);
4023     SSL_SESSION_free(clientpsk);
4024     SSL_SESSION_free(serverpsk);
4025     clientpsk = serverpsk = NULL;
4026     if (clientssl != NULL)
4027         SSL_shutdown(clientssl);
4028     if (serverssl != NULL)
4029         SSL_shutdown(serverssl);
4030     SSL_free(serverssl);
4031     SSL_free(clientssl);
4032     SSL_CTX_free(sctx);
4033     SSL_CTX_free(cctx);
4034     return testresult;
4035 }
4036
4037 /*
4038  * Test that a server that doesn't try to read early data can handle a
4039  * client sending some.
4040  */
4041 static int test_early_data_not_expected(int idx)
4042 {
4043     SSL_CTX *cctx = NULL, *sctx = NULL;
4044     SSL *clientssl = NULL, *serverssl = NULL;
4045     int testresult = 0;
4046     SSL_SESSION *sess = NULL;
4047     unsigned char buf[20];
4048     size_t readbytes, written;
4049
4050     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4051                                         &serverssl, &sess, idx)))
4052         goto end;
4053
4054     /* Write some early data */
4055     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4056                                         &written)))
4057         goto end;
4058
4059     /*
4060      * Server should skip over early data and then block waiting for client to
4061      * continue handshake
4062      */
4063     if (!TEST_int_le(SSL_accept(serverssl), 0)
4064      || !TEST_int_gt(SSL_connect(clientssl), 0)
4065      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4066                      SSL_EARLY_DATA_REJECTED)
4067      || !TEST_int_gt(SSL_accept(serverssl), 0)
4068      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4069                      SSL_EARLY_DATA_REJECTED))
4070         goto end;
4071
4072     /* Send some normal data from client to server */
4073     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4074             || !TEST_size_t_eq(written, strlen(MSG2)))
4075         goto end;
4076
4077     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4078             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4079         goto end;
4080
4081     testresult = 1;
4082
4083  end:
4084     SSL_SESSION_free(sess);
4085     SSL_SESSION_free(clientpsk);
4086     SSL_SESSION_free(serverpsk);
4087     clientpsk = serverpsk = NULL;
4088     SSL_free(serverssl);
4089     SSL_free(clientssl);
4090     SSL_CTX_free(sctx);
4091     SSL_CTX_free(cctx);
4092     return testresult;
4093 }
4094
4095
4096 # ifndef OPENSSL_NO_TLS1_2
4097 /*
4098  * Test that a server attempting to read early data can handle a connection
4099  * from a TLSv1.2 client.
4100  */
4101 static int test_early_data_tls1_2(int idx)
4102 {
4103     SSL_CTX *cctx = NULL, *sctx = NULL;
4104     SSL *clientssl = NULL, *serverssl = NULL;
4105     int testresult = 0;
4106     unsigned char buf[20];
4107     size_t readbytes, written;
4108
4109     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4110                                         &serverssl, NULL, idx)))
4111         goto end;
4112
4113     /* Write some data - should block due to handshake with server */
4114     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
4115     SSL_set_connect_state(clientssl);
4116     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4117         goto end;
4118
4119     /*
4120      * Server should do TLSv1.2 handshake. First it will block waiting for more
4121      * messages from client after ServerDone. Then SSL_read_early_data should
4122      * finish and detect that early data has not been sent
4123      */
4124     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4125                                          &readbytes),
4126                      SSL_READ_EARLY_DATA_ERROR))
4127         goto end;
4128
4129     /*
4130      * Continue writing the message we started earlier. Will still block waiting
4131      * for the CCS/Finished from server
4132      */
4133     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4134             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4135                                                 &readbytes),
4136                             SSL_READ_EARLY_DATA_FINISH)
4137             || !TEST_size_t_eq(readbytes, 0)
4138             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4139                             SSL_EARLY_DATA_NOT_SENT))
4140         goto end;
4141
4142     /* Continue writing the message we started earlier */
4143     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4144             || !TEST_size_t_eq(written, strlen(MSG1))
4145             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4146                             SSL_EARLY_DATA_NOT_SENT)
4147             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4148             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4149             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
4150             || !TEST_size_t_eq(written, strlen(MSG2))
4151             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
4152             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4153         goto end;
4154
4155     testresult = 1;
4156
4157  end:
4158     SSL_SESSION_free(clientpsk);
4159     SSL_SESSION_free(serverpsk);
4160     clientpsk = serverpsk = NULL;
4161     SSL_free(serverssl);
4162     SSL_free(clientssl);
4163     SSL_CTX_free(sctx);
4164     SSL_CTX_free(cctx);
4165
4166     return testresult;
4167 }
4168 # endif /* OPENSSL_NO_TLS1_2 */
4169
4170 /*
4171  * Test configuring the TLSv1.3 ciphersuites
4172  *
4173  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
4174  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
4175  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
4176  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
4177  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4178  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4179  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
4180  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
4181  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
4182  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
4183  */
4184 static int test_set_ciphersuite(int idx)
4185 {
4186     SSL_CTX *cctx = NULL, *sctx = NULL;
4187     SSL *clientssl = NULL, *serverssl = NULL;
4188     int testresult = 0;
4189
4190     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4191                                        TLS_client_method(), TLS1_VERSION, 0,
4192                                        &sctx, &cctx, cert, privkey))
4193             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4194                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
4195         goto end;
4196
4197     if (idx >=4 && idx <= 7) {
4198         /* SSL_CTX explicit cipher list */
4199         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
4200             goto end;
4201     }
4202
4203     if (idx == 0 || idx == 4) {
4204         /* Default ciphersuite */
4205         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4206                                                 "TLS_AES_128_GCM_SHA256")))
4207             goto end;
4208     } else if (idx == 1 || idx == 5) {
4209         /* Non default ciphersuite */
4210         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4211                                                 "TLS_AES_128_CCM_SHA256")))
4212             goto end;
4213     }
4214
4215     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4216                                           &clientssl, NULL, NULL)))
4217         goto end;
4218
4219     if (idx == 8 || idx == 9) {
4220         /* SSL explicit cipher list */
4221         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
4222             goto end;
4223     }
4224
4225     if (idx == 2 || idx == 6 || idx == 8) {
4226         /* Default ciphersuite */
4227         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4228                                             "TLS_AES_128_GCM_SHA256")))
4229             goto end;
4230     } else if (idx == 3 || idx == 7 || idx == 9) {
4231         /* Non default ciphersuite */
4232         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4233                                             "TLS_AES_128_CCM_SHA256")))
4234             goto end;
4235     }
4236
4237     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4238         goto end;
4239
4240     testresult = 1;
4241
4242  end:
4243     SSL_free(serverssl);
4244     SSL_free(clientssl);
4245     SSL_CTX_free(sctx);
4246     SSL_CTX_free(cctx);
4247
4248     return testresult;
4249 }
4250
4251 static int test_ciphersuite_change(void)
4252 {
4253     SSL_CTX *cctx = NULL, *sctx = NULL;
4254     SSL *clientssl = NULL, *serverssl = NULL;
4255     SSL_SESSION *clntsess = NULL;
4256     int testresult = 0;
4257     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
4258
4259     /* Create a session based on SHA-256 */
4260     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4261                                        TLS_client_method(), TLS1_VERSION, 0,
4262                                        &sctx, &cctx, cert, privkey))
4263             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4264                                                    "TLS_AES_128_GCM_SHA256:"
4265                                                    "TLS_AES_256_GCM_SHA384:"
4266                                                    "TLS_AES_128_CCM_SHA256"))
4267             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4268                                                    "TLS_AES_128_GCM_SHA256"))
4269             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4270                                           &clientssl, NULL, NULL))
4271             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4272                                                 SSL_ERROR_NONE)))
4273         goto end;
4274
4275     clntsess = SSL_get1_session(clientssl);
4276     /* Save for later */
4277     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
4278     SSL_shutdown(clientssl);
4279     SSL_shutdown(serverssl);
4280     SSL_free(serverssl);
4281     SSL_free(clientssl);
4282     serverssl = clientssl = NULL;
4283
4284     /* Check we can resume a session with a different SHA-256 ciphersuite */
4285     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4286                                             "TLS_AES_128_CCM_SHA256"))
4287             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4288                                              &clientssl, NULL, NULL))
4289             || !TEST_true(SSL_set_session(clientssl, clntsess))
4290             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4291                                                 SSL_ERROR_NONE))
4292             || !TEST_true(SSL_session_reused(clientssl)))
4293         goto end;
4294
4295     SSL_SESSION_free(clntsess);
4296     clntsess = SSL_get1_session(clientssl);
4297     SSL_shutdown(clientssl);
4298     SSL_shutdown(serverssl);
4299     SSL_free(serverssl);
4300     SSL_free(clientssl);
4301     serverssl = clientssl = NULL;
4302
4303     /*
4304      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
4305      * succeeds but does not resume.
4306      */
4307     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4308             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4309                                              NULL, NULL))
4310             || !TEST_true(SSL_set_session(clientssl, clntsess))
4311             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4312                                                 SSL_ERROR_SSL))
4313             || !TEST_false(SSL_session_reused(clientssl)))
4314         goto end;
4315
4316     SSL_SESSION_free(clntsess);
4317     clntsess = NULL;
4318     SSL_shutdown(clientssl);
4319     SSL_shutdown(serverssl);
4320     SSL_free(serverssl);
4321     SSL_free(clientssl);
4322     serverssl = clientssl = NULL;
4323
4324     /* Create a session based on SHA384 */
4325     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4326             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4327                                           &clientssl, NULL, NULL))
4328             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4329                                                 SSL_ERROR_NONE)))
4330         goto end;
4331
4332     clntsess = SSL_get1_session(clientssl);
4333     SSL_shutdown(clientssl);
4334     SSL_shutdown(serverssl);
4335     SSL_free(serverssl);
4336     SSL_free(clientssl);
4337     serverssl = clientssl = NULL;
4338
4339     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4340                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
4341             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4342                                                    "TLS_AES_256_GCM_SHA384"))
4343             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4344                                              NULL, NULL))
4345             || !TEST_true(SSL_set_session(clientssl, clntsess))
4346                /*
4347                 * We use SSL_ERROR_WANT_READ below so that we can pause the
4348                 * connection after the initial ClientHello has been sent to
4349                 * enable us to make some session changes.
4350                 */
4351             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4352                                                 SSL_ERROR_WANT_READ)))
4353         goto end;
4354
4355     /* Trick the client into thinking this session is for a different digest */
4356     clntsess->cipher = aes_128_gcm_sha256;
4357     clntsess->cipher_id = clntsess->cipher->id;
4358
4359     /*
4360      * Continue the previously started connection. Server has selected a SHA-384
4361      * ciphersuite, but client thinks the session is for SHA-256, so it should
4362      * bail out.
4363      */
4364     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4365                                                 SSL_ERROR_SSL))
4366             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4367                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4368         goto end;
4369
4370     testresult = 1;
4371
4372  end:
4373     SSL_SESSION_free(clntsess);
4374     SSL_free(serverssl);
4375     SSL_free(clientssl);
4376     SSL_CTX_free(sctx);
4377     SSL_CTX_free(cctx);
4378
4379     return testresult;
4380 }
4381
4382 /*
4383  * Test TLSv1.3 Key exchange
4384  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4385  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4386  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4387  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4388  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4389  * Test 5 = Test NID_X448 with TLSv1.3 client and server
4390  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4391  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4392  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4393  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4394  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4395  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4396  * Test 12 = Test all ECDHE with TLSv1.2 client and server
4397  * Test 13 = Test all FFDHE with TLSv1.2 client and server
4398  */
4399 static int test_key_exchange(int idx)
4400 {
4401     SSL_CTX *sctx = NULL, *cctx = NULL;
4402     SSL *serverssl = NULL, *clientssl = NULL;
4403     int testresult = 0;
4404 # ifndef OPENSSL_NO_EC
4405     int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
4406                                 NID_secp521r1, NID_X25519, NID_X448};
4407 # endif
4408 # ifndef OPENSSL_NO_DH
4409     int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4410                                 NID_ffdhe6144, NID_ffdhe8192};
4411 # endif
4412     int kexch_alg;
4413     int *kexch_groups = &kexch_alg;
4414     int kexch_groups_size = 1;
4415     int max_version = TLS1_3_VERSION;
4416     char *kexch_name0 = NULL;
4417
4418     switch (idx) {
4419 # ifndef OPENSSL_NO_EC
4420 # ifndef OPENSSL_NO_TLS1_2
4421         case 12:
4422             max_version = TLS1_2_VERSION;
4423 # endif
4424             /* Fall through */
4425         case 0:
4426             kexch_groups = ecdhe_kexch_groups;
4427             kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
4428             kexch_name0 = "secp256r1";
4429             break;
4430         case 1:
4431             kexch_alg = NID_X9_62_prime256v1;
4432             kexch_name0 = "secp256r1";
4433             break;
4434         case 2:
4435             kexch_alg = NID_secp384r1;
4436             kexch_name0 = "secp384r1";
4437             break;
4438         case 3:
4439             kexch_alg = NID_secp521r1;
4440             kexch_name0 = "secp521r1";
4441             break;
4442         case 4:
4443             kexch_alg = NID_X25519;
4444             kexch_name0 = "x25519";
4445             break;
4446         case 5:
4447             kexch_alg = NID_X448;
4448             kexch_name0 = "x448";
4449             break;
4450 # endif
4451 # ifndef OPENSSL_NO_DH
4452 # ifndef OPENSSL_NO_TLS1_2
4453         case 13:
4454             max_version = TLS1_2_VERSION;
4455             kexch_name0 = "ffdhe2048";
4456 # endif
4457             /* Fall through */
4458         case 6:
4459             kexch_groups = ffdhe_kexch_groups;
4460             kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
4461             kexch_name0 = "ffdhe2048";
4462             break;
4463         case 7:
4464             kexch_alg = NID_ffdhe2048;
4465             kexch_name0 = "ffdhe2048";
4466             break;
4467         case 8:
4468             kexch_alg = NID_ffdhe3072;
4469             kexch_name0 = "ffdhe3072";
4470             break;
4471         case 9:
4472             kexch_alg = NID_ffdhe4096;
4473             kexch_name0 = "ffdhe4096";
4474             break;
4475         case 10:
4476             kexch_alg = NID_ffdhe6144;
4477             kexch_name0 = "ffdhe6144";
4478             break;
4479         case 11:
4480             kexch_alg = NID_ffdhe8192;
4481             kexch_name0 = "ffdhe8192";
4482             break;
4483 # endif
4484         default:
4485             /* We're skipping this test */
4486             return 1;
4487     }
4488
4489     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4490                                        TLS_client_method(), TLS1_VERSION,
4491                                        max_version, &sctx, &cctx, cert,
4492                                        privkey)))
4493         goto end;
4494
4495     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
4496                    TLS1_3_RFC_AES_128_GCM_SHA256)))
4497         goto end;
4498
4499     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4500                    TLS1_3_RFC_AES_128_GCM_SHA256)))
4501         goto end;
4502
4503     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
4504                    TLS1_TXT_RSA_WITH_AES_128_SHA)))
4505         goto end;
4506
4507     /*
4508      * Must include an EC ciphersuite so that we send supported groups in
4509      * TLSv1.2
4510      */
4511 # ifndef OPENSSL_NO_TLS1_2
4512     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
4513                    TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM ":"
4514                    TLS1_TXT_RSA_WITH_AES_128_SHA)))
4515         goto end;
4516 # endif
4517
4518     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4519                                              NULL, NULL)))
4520         goto end;
4521
4522     if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
4523         || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
4524         goto end;
4525
4526     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4527         goto end;
4528
4529     /*
4530      * If Handshake succeeds the negotiated kexch alg should be the first one in
4531      * configured, except in the case of FFDHE groups (idx 13), which are
4532      * TLSv1.3 only so we expect no shared group to exist.
4533      */
4534     if (!TEST_int_eq(SSL_get_shared_group(serverssl, 0),
4535                      idx == 13 ? 0 : kexch_groups[0]))
4536         goto end;
4537
4538     if (!TEST_str_eq(SSL_group_to_name(serverssl, kexch_groups[0]),
4539                      kexch_name0))
4540         goto end;
4541
4542     if (max_version == TLS1_3_VERSION) {
4543         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), kexch_groups[0]))
4544             goto end;
4545         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), kexch_groups[0]))
4546             goto end;
4547     }
4548
4549     testresult = 1;
4550  end:
4551     SSL_free(serverssl);
4552     SSL_free(clientssl);
4553     SSL_CTX_free(sctx);
4554     SSL_CTX_free(cctx);
4555     return testresult;
4556 }
4557
4558 /*
4559  * Test TLSv1.3 Cipher Suite
4560  * Test 0 = Set TLS1.3 cipher on context
4561  * Test 1 = Set TLS1.3 cipher on SSL
4562  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
4563  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
4564  */
4565 static int test_tls13_ciphersuite(int idx)
4566 {
4567     SSL_CTX *sctx = NULL, *cctx = NULL;
4568     SSL *serverssl = NULL, *clientssl = NULL;
4569     static const struct {
4570         const char *ciphername;
4571         int fipscapable;
4572     } t13_ciphers[] = {
4573         { TLS1_3_RFC_AES_128_GCM_SHA256, 1 },
4574         { TLS1_3_RFC_AES_256_GCM_SHA384, 1 },
4575         { TLS1_3_RFC_AES_128_CCM_SHA256, 1 },
4576 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4577         { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
4578         { TLS1_3_RFC_AES_256_GCM_SHA384
4579           ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
4580 # endif
4581         { TLS1_3_RFC_AES_128_CCM_8_SHA256 ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1 }
4582     };
4583     const char *t13_cipher = NULL;
4584     const char *t12_cipher = NULL;
4585     const char *negotiated_scipher;
4586     const char *negotiated_ccipher;
4587     int set_at_ctx = 0;
4588     int set_at_ssl = 0;
4589     int testresult = 0;
4590     int max_ver;
4591     size_t i;
4592
4593     switch (idx) {
4594         case 0:
4595             set_at_ctx = 1;
4596             break;
4597         case 1:
4598             set_at_ssl = 1;
4599             break;
4600         case 2:
4601             set_at_ctx = 1;
4602             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
4603             break;
4604         case 3:
4605             set_at_ssl = 1;
4606             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
4607             break;
4608     }
4609
4610     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
4611 # ifdef OPENSSL_NO_TLS1_2
4612         if (max_ver == TLS1_2_VERSION)
4613             continue;
4614 # endif
4615         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
4616             if (is_fips && !t13_ciphers[i].fipscapable)
4617                 continue;
4618             t13_cipher = t13_ciphers[i].ciphername;
4619             if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4620                                                TLS_client_method(),
4621                                                TLS1_VERSION, max_ver,
4622                                                &sctx, &cctx, cert, privkey)))
4623                 goto end;
4624
4625             if (set_at_ctx) {
4626                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
4627                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
4628                     goto end;
4629                 if (t12_cipher != NULL) {
4630                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
4631                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
4632                                                               t12_cipher)))
4633                         goto end;
4634                 }
4635             }
4636
4637             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4638                                               &clientssl, NULL, NULL)))
4639                 goto end;
4640
4641             if (set_at_ssl) {
4642                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
4643                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
4644                     goto end;
4645                 if (t12_cipher != NULL) {
4646                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
4647                         || !TEST_true(SSL_set_cipher_list(clientssl,
4648                                                           t12_cipher)))
4649                         goto end;
4650                 }
4651             }
4652
4653             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4654                                                  SSL_ERROR_NONE)))
4655                 goto end;
4656
4657             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
4658                                                                  serverssl));
4659             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
4660                                                                  clientssl));
4661             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
4662                 goto end;
4663
4664             /*
4665              * TEST_strn_eq is used below because t13_cipher can contain
4666              * multiple ciphersuites
4667              */
4668             if (max_ver == TLS1_3_VERSION
4669                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
4670                                  strlen(negotiated_scipher)))
4671                 goto end;
4672
4673 # ifndef OPENSSL_NO_TLS1_2
4674             /* Below validation is not done when t12_cipher is NULL */
4675             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
4676                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
4677                 goto end;
4678 # endif
4679
4680             SSL_free(serverssl);
4681             serverssl = NULL;
4682             SSL_free(clientssl);
4683             clientssl = NULL;
4684             SSL_CTX_free(sctx);
4685             sctx = NULL;
4686             SSL_CTX_free(cctx);
4687             cctx = NULL;
4688         }
4689     }
4690
4691     testresult = 1;
4692  end:
4693     SSL_free(serverssl);
4694     SSL_free(clientssl);
4695     SSL_CTX_free(sctx);
4696     SSL_CTX_free(cctx);
4697     return testresult;
4698 }
4699
4700 /*
4701  * Test TLSv1.3 PSKs
4702  * Test 0 = Test new style callbacks
4703  * Test 1 = Test both new and old style callbacks
4704  * Test 2 = Test old style callbacks
4705  * Test 3 = Test old style callbacks with no certificate
4706  */
4707 static int test_tls13_psk(int idx)
4708 {
4709     SSL_CTX *sctx = NULL, *cctx = NULL;
4710     SSL *serverssl = NULL, *clientssl = NULL;
4711     const SSL_CIPHER *cipher = NULL;
4712     const unsigned char key[] = {
4713         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
4714         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4715         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
4716         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
4717     };
4718     int testresult = 0;
4719
4720     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4721                                        TLS_client_method(), TLS1_VERSION, 0,
4722                                        &sctx, &cctx, idx == 3 ? NULL : cert,
4723                                        idx == 3 ? NULL : privkey)))
4724         goto end;
4725
4726     if (idx != 3) {
4727         /*
4728          * We use a ciphersuite with SHA256 to ease testing old style PSK
4729          * callbacks which will always default to SHA256. This should not be
4730          * necessary if we have no cert/priv key. In that case the server should
4731          * prefer SHA256 automatically.
4732          */
4733         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4734                                                 "TLS_AES_128_GCM_SHA256")))
4735             goto end;
4736     } else {
4737         /*
4738          * As noted above the server should prefer SHA256 automatically. However
4739          * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
4740          * code works even if we are testing with only the FIPS provider loaded.
4741          */
4742         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4743                                                 "TLS_AES_256_GCM_SHA384:"
4744                                                 "TLS_AES_128_GCM_SHA256")))
4745             goto end;
4746     }
4747
4748     /*
4749      * Test 0: New style callbacks only
4750      * Test 1: New and old style callbacks (only the new ones should be used)
4751      * Test 2: Old style callbacks only
4752      */
4753     if (idx == 0 || idx == 1) {
4754         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
4755         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
4756     }
4757 #ifndef OPENSSL_NO_PSK
4758     if (idx >= 1) {
4759         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
4760         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
4761     }
4762 #endif
4763     srvid = pskid;
4764     use_session_cb_cnt = 0;
4765     find_session_cb_cnt = 0;
4766     psk_client_cb_cnt = 0;
4767     psk_server_cb_cnt = 0;
4768
4769     if (idx != 3) {
4770         /*
4771          * Check we can create a connection if callback decides not to send a
4772          * PSK
4773          */
4774         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4775                                                  NULL, NULL))
4776                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4777                                                     SSL_ERROR_NONE))
4778                 || !TEST_false(SSL_session_reused(clientssl))
4779                 || !TEST_false(SSL_session_reused(serverssl)))
4780             goto end;
4781
4782         if (idx == 0 || idx == 1) {
4783             if (!TEST_true(use_session_cb_cnt == 1)
4784                     || !TEST_true(find_session_cb_cnt == 0)
4785                        /*
4786                         * If no old style callback then below should be 0
4787                         * otherwise 1
4788                         */
4789                     || !TEST_true(psk_client_cb_cnt == idx)
4790                     || !TEST_true(psk_server_cb_cnt == 0))
4791                 goto end;
4792         } else {
4793             if (!TEST_true(use_session_cb_cnt == 0)
4794                     || !TEST_true(find_session_cb_cnt == 0)
4795                     || !TEST_true(psk_client_cb_cnt == 1)
4796                     || !TEST_true(psk_server_cb_cnt == 0))
4797                 goto end;
4798         }
4799
4800         shutdown_ssl_connection(serverssl, clientssl);
4801         serverssl = clientssl = NULL;
4802         use_session_cb_cnt = psk_client_cb_cnt = 0;
4803     }
4804
4805     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4806                                              NULL, NULL)))
4807         goto end;
4808
4809     /* Create the PSK */
4810     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
4811     clientpsk = SSL_SESSION_new();
4812     if (!TEST_ptr(clientpsk)
4813             || !TEST_ptr(cipher)
4814             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
4815                                                       sizeof(key)))
4816             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
4817             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
4818                                                            TLS1_3_VERSION))
4819             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
4820         goto end;
4821     serverpsk = clientpsk;
4822
4823     /* Check we can create a connection and the PSK is used */
4824     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
4825             || !TEST_true(SSL_session_reused(clientssl))
4826             || !TEST_true(SSL_session_reused(serverssl)))
4827         goto end;
4828
4829     if (idx == 0 || idx == 1) {
4830         if (!TEST_true(use_session_cb_cnt == 1)
4831                 || !TEST_true(find_session_cb_cnt == 1)
4832                 || !TEST_true(psk_client_cb_cnt == 0)
4833                 || !TEST_true(psk_server_cb_cnt == 0))
4834             goto end;
4835     } else {
4836         if (!TEST_true(use_session_cb_cnt == 0)
4837                 || !TEST_true(find_session_cb_cnt == 0)
4838                 || !TEST_true(psk_client_cb_cnt == 1)
4839                 || !TEST_true(psk_server_cb_cnt == 1))
4840             goto end;
4841     }
4842
4843     shutdown_ssl_connection(serverssl, clientssl);
4844     serverssl = clientssl = NULL;
4845     use_session_cb_cnt = find_session_cb_cnt = 0;
4846     psk_client_cb_cnt = psk_server_cb_cnt = 0;
4847
4848     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4849                                              NULL, NULL)))
4850         goto end;
4851
4852     /* Force an HRR */
4853 #if defined(OPENSSL_NO_EC)
4854     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
4855         goto end;
4856 #else
4857     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
4858         goto end;
4859 #endif
4860
4861     /*
4862      * Check we can create a connection, the PSK is used and the callbacks are
4863      * called twice.
4864      */
4865     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
4866             || !TEST_true(SSL_session_reused(clientssl))
4867             || !TEST_true(SSL_session_reused(serverssl)))
4868         goto end;
4869
4870     if (idx == 0 || idx == 1) {
4871         if (!TEST_true(use_session_cb_cnt == 2)
4872                 || !TEST_true(find_session_cb_cnt == 2)
4873                 || !TEST_true(psk_client_cb_cnt == 0)
4874                 || !TEST_true(psk_server_cb_cnt == 0))
4875             goto end;
4876     } else {
4877         if (!TEST_true(use_session_cb_cnt == 0)
4878                 || !TEST_true(find_session_cb_cnt == 0)
4879                 || !TEST_true(psk_client_cb_cnt == 2)
4880                 || !TEST_true(psk_server_cb_cnt == 2))
4881             goto end;
4882     }
4883
4884     shutdown_ssl_connection(serverssl, clientssl);
4885     serverssl = clientssl = NULL;
4886     use_session_cb_cnt = find_session_cb_cnt = 0;
4887     psk_client_cb_cnt = psk_server_cb_cnt = 0;
4888
4889     if (idx != 3) {
4890         /*
4891          * Check that if the server rejects the PSK we can still connect, but with
4892          * a full handshake
4893          */
4894         srvid = "Dummy Identity";
4895         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4896                                                  NULL, NULL))
4897                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4898                                                     SSL_ERROR_NONE))
4899                 || !TEST_false(SSL_session_reused(clientssl))
4900                 || !TEST_false(SSL_session_reused(serverssl)))
4901             goto end;
4902
4903         if (idx == 0 || idx == 1) {
4904             if (!TEST_true(use_session_cb_cnt == 1)
4905                     || !TEST_true(find_session_cb_cnt == 1)
4906                     || !TEST_true(psk_client_cb_cnt == 0)
4907                        /*
4908                         * If no old style callback then below should be 0
4909                         * otherwise 1
4910                         */
4911                     || !TEST_true(psk_server_cb_cnt == idx))
4912                 goto end;
4913         } else {
4914             if (!TEST_true(use_session_cb_cnt == 0)
4915                     || !TEST_true(find_session_cb_cnt == 0)
4916                     || !TEST_true(psk_client_cb_cnt == 1)
4917                     || !TEST_true(psk_server_cb_cnt == 1))
4918                 goto end;
4919         }
4920
4921         shutdown_ssl_connection(serverssl, clientssl);
4922         serverssl = clientssl = NULL;
4923     }
4924     testresult = 1;
4925
4926  end:
4927     SSL_SESSION_free(clientpsk);
4928     SSL_SESSION_free(serverpsk);
4929     clientpsk = serverpsk = NULL;
4930     SSL_free(serverssl);
4931     SSL_free(clientssl);
4932     SSL_CTX_free(sctx);
4933     SSL_CTX_free(cctx);
4934     return testresult;
4935 }
4936
4937 static unsigned char cookie_magic_value[] = "cookie magic";
4938
4939 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
4940                                     unsigned int *cookie_len)
4941 {
4942     /*
4943      * Not suitable as a real cookie generation function but good enough for
4944      * testing!
4945      */
4946     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
4947     *cookie_len = sizeof(cookie_magic_value) - 1;
4948
4949     return 1;
4950 }
4951
4952 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
4953                                   unsigned int cookie_len)
4954 {
4955     if (cookie_len == sizeof(cookie_magic_value) - 1
4956         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
4957         return 1;
4958
4959     return 0;
4960 }
4961
4962 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
4963                                         size_t *cookie_len)
4964 {
4965     unsigned int temp;
4966     int res = generate_cookie_callback(ssl, cookie, &temp);
4967     *cookie_len = temp;
4968     return res;
4969 }
4970
4971 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
4972                                       size_t cookie_len)
4973 {
4974     return verify_cookie_callback(ssl, cookie, cookie_len);
4975 }
4976
4977 static int test_stateless(void)
4978 {
4979     SSL_CTX *sctx = NULL, *cctx = NULL;
4980     SSL *serverssl = NULL, *clientssl = NULL;
4981     int testresult = 0;
4982
4983     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4984                                        TLS_client_method(), TLS1_VERSION, 0,
4985                                        &sctx, &cctx, cert, privkey)))
4986         goto end;
4987
4988     /* The arrival of CCS messages can confuse the test */
4989     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
4990
4991     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4992                                       NULL, NULL))
4993                /* Send the first ClientHello */
4994             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4995                                                  SSL_ERROR_WANT_READ))
4996                /*
4997                 * This should fail with a -1 return because we have no callbacks
4998                 * set up
4999                 */
5000             || !TEST_int_eq(SSL_stateless(serverssl), -1))
5001         goto end;
5002
5003     /* Fatal error so abandon the connection from this client */
5004     SSL_free(clientssl);
5005     clientssl = NULL;
5006
5007     /* Set up the cookie generation and verification callbacks */
5008     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
5009     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
5010
5011     /*
5012      * Create a new connection from the client (we can reuse the server SSL
5013      * object).
5014      */
5015     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5016                                              NULL, NULL))
5017                /* Send the first ClientHello */
5018             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5019                                                 SSL_ERROR_WANT_READ))
5020                /* This should fail because there is no cookie */
5021             || !TEST_int_eq(SSL_stateless(serverssl), 0))
5022         goto end;
5023
5024     /* Abandon the connection from this client */
5025     SSL_free(clientssl);
5026     clientssl = NULL;
5027
5028     /*
5029      * Now create a connection from a new client but with the same server SSL
5030      * object
5031      */
5032     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5033                                              NULL, NULL))
5034                /* Send the first ClientHello */
5035             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5036                                                 SSL_ERROR_WANT_READ))
5037                /* This should fail because there is no cookie */
5038             || !TEST_int_eq(SSL_stateless(serverssl), 0)
5039                /* Send the second ClientHello */
5040             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5041                                                 SSL_ERROR_WANT_READ))
5042                /* This should succeed because a cookie is now present */
5043             || !TEST_int_eq(SSL_stateless(serverssl), 1)
5044                /* Complete the connection */
5045             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5046                                                 SSL_ERROR_NONE)))
5047         goto end;
5048
5049     shutdown_ssl_connection(serverssl, clientssl);
5050     serverssl = clientssl = NULL;
5051     testresult = 1;
5052
5053  end:
5054     SSL_free(serverssl);
5055     SSL_free(clientssl);
5056     SSL_CTX_free(sctx);
5057     SSL_CTX_free(cctx);
5058     return testresult;
5059
5060 }
5061 #endif /* OSSL_NO_USABLE_TLS1_3 */
5062
5063 static int clntaddoldcb = 0;
5064 static int clntparseoldcb = 0;
5065 static int srvaddoldcb = 0;
5066 static int srvparseoldcb = 0;
5067 static int clntaddnewcb = 0;
5068 static int clntparsenewcb = 0;
5069 static int srvaddnewcb = 0;
5070 static int srvparsenewcb = 0;
5071 static int snicb = 0;
5072
5073 #define TEST_EXT_TYPE1  0xff00
5074
5075 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
5076                       size_t *outlen, int *al, void *add_arg)
5077 {
5078     int *server = (int *)add_arg;
5079     unsigned char *data;
5080
5081     if (SSL_is_server(s))
5082         srvaddoldcb++;
5083     else
5084         clntaddoldcb++;
5085
5086     if (*server != SSL_is_server(s)
5087             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
5088         return -1;
5089
5090     *data = 1;
5091     *out = data;
5092     *outlen = sizeof(char);
5093     return 1;
5094 }
5095
5096 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
5097                         void *add_arg)
5098 {
5099     OPENSSL_free((unsigned char *)out);
5100 }
5101
5102 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
5103                         size_t inlen, int *al, void *parse_arg)
5104 {
5105     int *server = (int *)parse_arg;
5106
5107     if (SSL_is_server(s))
5108         srvparseoldcb++;
5109     else
5110         clntparseoldcb++;
5111
5112     if (*server != SSL_is_server(s)
5113             || inlen != sizeof(char)
5114             || *in != 1)
5115         return -1;
5116
5117     return 1;
5118 }
5119
5120 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
5121                       const unsigned char **out, size_t *outlen, X509 *x,
5122                       size_t chainidx, int *al, void *add_arg)
5123 {
5124     int *server = (int *)add_arg;
5125     unsigned char *data;
5126
5127     if (SSL_is_server(s))
5128         srvaddnewcb++;
5129     else
5130         clntaddnewcb++;
5131
5132     if (*server != SSL_is_server(s)
5133             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
5134         return -1;
5135
5136     *data = 1;
5137     *out = data;
5138     *outlen = sizeof(*data);
5139     return 1;
5140 }
5141
5142 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
5143                         const unsigned char *out, void *add_arg)
5144 {
5145     OPENSSL_free((unsigned char *)out);
5146 }
5147
5148 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
5149                         const unsigned char *in, size_t inlen, X509 *x,
5150                         size_t chainidx, int *al, void *parse_arg)
5151 {
5152     int *server = (int *)parse_arg;
5153
5154     if (SSL_is_server(s))
5155         srvparsenewcb++;
5156     else
5157         clntparsenewcb++;
5158
5159     if (*server != SSL_is_server(s)
5160             || inlen != sizeof(char) || *in != 1)
5161         return -1;
5162
5163     return 1;
5164 }
5165
5166 static int sni_cb(SSL *s, int *al, void *arg)
5167 {
5168     SSL_CTX *ctx = (SSL_CTX *)arg;
5169
5170     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
5171         *al = SSL_AD_INTERNAL_ERROR;
5172         return SSL_TLSEXT_ERR_ALERT_FATAL;
5173     }
5174     snicb++;
5175     return SSL_TLSEXT_ERR_OK;
5176 }
5177
5178 /*
5179  * Custom call back tests.
5180  * Test 0: Old style callbacks in TLSv1.2
5181  * Test 1: New style callbacks in TLSv1.2
5182  * Test 2: New style callbacks in TLSv1.2 with SNI
5183  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
5184  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
5185  */
5186 static int test_custom_exts(int tst)
5187 {
5188     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
5189     SSL *clientssl = NULL, *serverssl = NULL;
5190     int testresult = 0;
5191     static int server = 1;
5192     static int client = 0;
5193     SSL_SESSION *sess = NULL;
5194     unsigned int context;
5195
5196 #if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
5197     /* Skip tests for TLSv1.2 and below in this case */
5198     if (tst < 3)
5199         return 1;
5200 #endif
5201
5202     /* Reset callback counters */
5203     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
5204     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
5205     snicb = 0;
5206
5207     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5208                                        TLS_client_method(), TLS1_VERSION, 0,
5209                                        &sctx, &cctx, cert, privkey)))
5210         goto end;
5211
5212     if (tst == 2
5213             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
5214                                               TLS1_VERSION, 0,
5215                                               &sctx2, NULL, cert, privkey)))
5216         goto end;
5217
5218
5219     if (tst < 3) {
5220         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
5221         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
5222         if (sctx2 != NULL)
5223             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
5224     }
5225
5226     if (tst == 4) {
5227         context = SSL_EXT_CLIENT_HELLO
5228                   | SSL_EXT_TLS1_2_SERVER_HELLO
5229                   | SSL_EXT_TLS1_3_SERVER_HELLO
5230                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
5231                   | SSL_EXT_TLS1_3_CERTIFICATE
5232                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
5233     } else {
5234         context = SSL_EXT_CLIENT_HELLO
5235                   | SSL_EXT_TLS1_2_SERVER_HELLO
5236                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
5237     }
5238
5239     /* Create a client side custom extension */
5240     if (tst == 0) {
5241         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
5242                                                      old_add_cb, old_free_cb,
5243                                                      &client, old_parse_cb,
5244                                                      &client)))
5245             goto end;
5246     } else {
5247         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
5248                                               new_add_cb, new_free_cb,
5249                                               &client, new_parse_cb, &client)))
5250             goto end;
5251     }
5252
5253     /* Should not be able to add duplicates */
5254     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
5255                                                   old_add_cb, old_free_cb,
5256                                                   &client, old_parse_cb,
5257                                                   &client))
5258             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
5259                                                   context, new_add_cb,
5260                                                   new_free_cb, &client,
5261                                                   new_parse_cb, &client)))
5262         goto end;
5263
5264     /* Create a server side custom extension */
5265     if (tst == 0) {
5266         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
5267                                                      old_add_cb, old_free_cb,
5268                                                      &server, old_parse_cb,
5269                                                      &server)))
5270             goto end;
5271     } else {
5272         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
5273                                               new_add_cb, new_free_cb,
5274                                               &server, new_parse_cb, &server)))
5275             goto end;
5276         if (sctx2 != NULL
5277                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
5278                                                      context, new_add_cb,
5279                                                      new_free_cb, &server,
5280                                                      new_parse_cb, &server)))
5281             goto end;
5282     }
5283
5284     /* Should not be able to add duplicates */
5285     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
5286                                                   old_add_cb, old_free_cb,
5287                                                   &server, old_parse_cb,
5288                                                   &server))
5289             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
5290                                                   context, new_add_cb,
5291                                                   new_free_cb, &server,
5292                                                   new_parse_cb, &server)))
5293         goto end;
5294
5295     if (tst == 2) {
5296         /* Set up SNI */
5297         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
5298                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
5299             goto end;
5300     }
5301
5302     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5303                                       &clientssl, NULL, NULL))
5304             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5305                                                 SSL_ERROR_NONE)))
5306         goto end;
5307
5308     if (tst == 0) {
5309         if (clntaddoldcb != 1
5310                 || clntparseoldcb != 1
5311                 || srvaddoldcb != 1
5312                 || srvparseoldcb != 1)
5313             goto end;
5314     } else if (tst == 1 || tst == 2 || tst == 3) {
5315         if (clntaddnewcb != 1
5316                 || clntparsenewcb != 1
5317                 || srvaddnewcb != 1
5318                 || srvparsenewcb != 1
5319                 || (tst != 2 && snicb != 0)
5320                 || (tst == 2 && snicb != 1))
5321             goto end;
5322     } else {
5323         /* In this case there 2 NewSessionTicket messages created */
5324         if (clntaddnewcb != 1
5325                 || clntparsenewcb != 5
5326                 || srvaddnewcb != 5
5327                 || srvparsenewcb != 1)
5328             goto end;
5329     }
5330
5331     sess = SSL_get1_session(clientssl);
5332     SSL_shutdown(clientssl);
5333     SSL_shutdown(serverssl);
5334     SSL_free(serverssl);
5335     SSL_free(clientssl);
5336     serverssl = clientssl = NULL;
5337
5338     if (tst == 3) {
5339         /* We don't bother with the resumption aspects for this test */
5340         testresult = 1;
5341         goto end;
5342     }
5343
5344     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5345                                       NULL, NULL))
5346             || !TEST_true(SSL_set_session(clientssl, sess))
5347             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5348                                                SSL_ERROR_NONE)))
5349         goto end;
5350
5351     /*
5352      * For a resumed session we expect to add the ClientHello extension. For the
5353      * old style callbacks we ignore it on the server side because they set
5354      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
5355      * them.
5356      */
5357     if (tst == 0) {
5358         if (clntaddoldcb != 2
5359                 || clntparseoldcb != 1
5360                 || srvaddoldcb != 1
5361                 || srvparseoldcb != 1)
5362             goto end;
5363     } else if (tst == 1 || tst == 2 || tst == 3) {
5364         if (clntaddnewcb != 2
5365                 || clntparsenewcb != 2
5366                 || srvaddnewcb != 2
5367                 || srvparsenewcb != 2)
5368             goto end;
5369     } else {
5370         /*
5371          * No Certificate message extensions in the resumption handshake,
5372          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
5373          */
5374         if (clntaddnewcb != 2
5375                 || clntparsenewcb != 8
5376                 || srvaddnewcb != 8
5377                 || srvparsenewcb != 2)
5378             goto end;
5379     }
5380
5381     testresult = 1;
5382
5383 end:
5384     SSL_SESSION_free(sess);
5385     SSL_free(serverssl);
5386     SSL_free(clientssl);
5387     SSL_CTX_free(sctx2);
5388     SSL_CTX_free(sctx);
5389     SSL_CTX_free(cctx);
5390     return testresult;
5391 }
5392
5393 /*
5394  * Test loading of serverinfo data in various formats. test_sslmessages actually
5395  * tests to make sure the extensions appear in the handshake
5396  */
5397 static int test_serverinfo(int tst)
5398 {
5399     unsigned int version;
5400     unsigned char *sibuf;
5401     size_t sibuflen;
5402     int ret, expected, testresult = 0;
5403     SSL_CTX *ctx;
5404
5405     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method());
5406     if (!TEST_ptr(ctx))
5407         goto end;
5408
5409     if ((tst & 0x01) == 0x01)
5410         version = SSL_SERVERINFOV2;
5411     else
5412         version = SSL_SERVERINFOV1;
5413
5414     if ((tst & 0x02) == 0x02) {
5415         sibuf = serverinfov2;
5416         sibuflen = sizeof(serverinfov2);
5417         expected = (version == SSL_SERVERINFOV2);
5418     } else {
5419         sibuf = serverinfov1;
5420         sibuflen = sizeof(serverinfov1);
5421         expected = (version == SSL_SERVERINFOV1);
5422     }
5423
5424     if ((tst & 0x04) == 0x04) {
5425         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
5426     } else {
5427         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
5428
5429         /*
5430          * The version variable is irrelevant in this case - it's what is in the
5431          * buffer that matters
5432          */
5433         if ((tst & 0x02) == 0x02)
5434             expected = 0;
5435         else
5436             expected = 1;
5437     }
5438
5439     if (!TEST_true(ret == expected))
5440         goto end;
5441
5442     testresult = 1;
5443
5444  end:
5445     SSL_CTX_free(ctx);
5446
5447     return testresult;
5448 }
5449
5450 /*
5451  * Test that SSL_export_keying_material() produces expected results. There are
5452  * no test vectors so all we do is test that both sides of the communication
5453  * produce the same results for different protocol versions.
5454  */
5455 #define SMALL_LABEL_LEN 10
5456 #define LONG_LABEL_LEN  249
5457 static int test_export_key_mat(int tst)
5458 {
5459     int testresult = 0;
5460     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
5461     SSL *clientssl = NULL, *serverssl = NULL;
5462     const char label[LONG_LABEL_LEN + 1] = "test label";
5463     const unsigned char context[] = "context";
5464     const unsigned char *emptycontext = NULL;
5465     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
5466     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
5467     size_t labellen;
5468     const int protocols[] = {
5469         TLS1_VERSION,
5470         TLS1_1_VERSION,
5471         TLS1_2_VERSION,
5472         TLS1_3_VERSION,
5473         TLS1_3_VERSION,
5474         TLS1_3_VERSION
5475     };
5476
5477 #ifdef OPENSSL_NO_TLS1
5478     if (tst == 0)
5479         return 1;
5480 #endif
5481 #ifdef OPENSSL_NO_TLS1_1
5482     if (tst == 1)
5483         return 1;
5484 #endif
5485     if (is_fips && (tst == 0 || tst == 1))
5486         return 1;
5487 #ifdef OPENSSL_NO_TLS1_2
5488     if (tst == 2)
5489         return 1;
5490 #endif
5491 #ifdef OSSL_NO_USABLE_TLS1_3
5492     if (tst >= 3)
5493         return 1;
5494 #endif
5495     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5496                                        TLS_client_method(), TLS1_VERSION, 0,
5497                                        &sctx, &cctx, cert, privkey)))
5498         goto end;
5499
5500     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
5501     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
5502     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
5503     if ((protocols[tst] < TLS1_2_VERSION) &&
5504         (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0")
5505         || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
5506         goto end;
5507
5508     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5509                                       NULL)))
5510         goto end;
5511
5512     /*
5513      * Premature call of SSL_export_keying_material should just fail.
5514      */
5515     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
5516                                                 sizeof(ckeymat1), label,
5517                                                 SMALL_LABEL_LEN + 1, context,
5518                                                 sizeof(context) - 1, 1), 0))
5519         goto end;
5520
5521     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5522                                          SSL_ERROR_NONE)))
5523         goto end;
5524
5525     if (tst == 5) {
5526         /*
5527          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
5528          * go over that.
5529          */
5530         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
5531                                                     sizeof(ckeymat1), label,
5532                                                     LONG_LABEL_LEN + 1, context,
5533                                                     sizeof(context) - 1, 1), 0))
5534             goto end;
5535
5536         testresult = 1;
5537         goto end;
5538     } else if (tst == 4) {
5539         labellen = LONG_LABEL_LEN;
5540     } else {
5541         labellen = SMALL_LABEL_LEN;
5542     }
5543
5544     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
5545                                                 sizeof(ckeymat1), label,
5546                                                 labellen, context,
5547                                                 sizeof(context) - 1, 1), 1)
5548             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
5549                                                        sizeof(ckeymat2), label,
5550                                                        labellen,
5551                                                        emptycontext,
5552                                                        0, 1), 1)
5553             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
5554                                                        sizeof(ckeymat3), label,
5555                                                        labellen,
5556                                                        NULL, 0, 0), 1)
5557             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
5558                                                        sizeof(skeymat1), label,
5559                                                        labellen,
5560                                                        context,
5561                                                        sizeof(context) -1, 1),
5562                             1)
5563             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
5564                                                        sizeof(skeymat2), label,
5565                                                        labellen,
5566                                                        emptycontext,
5567                                                        0, 1), 1)
5568             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
5569                                                        sizeof(skeymat3), label,
5570                                                        labellen,
5571                                                        NULL, 0, 0), 1)
5572                /*
5573                 * Check that both sides created the same key material with the
5574                 * same context.
5575                 */
5576             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
5577                             sizeof(skeymat1))
5578                /*
5579                 * Check that both sides created the same key material with an
5580                 * empty context.
5581                 */
5582             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
5583                             sizeof(skeymat2))
5584                /*
5585                 * Check that both sides created the same key material without a
5586                 * context.
5587                 */
5588             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
5589                             sizeof(skeymat3))
5590                /* Different contexts should produce different results */
5591             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
5592                             sizeof(ckeymat2)))
5593         goto end;
5594
5595     /*
5596      * Check that an empty context and no context produce different results in
5597      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
5598      */
5599     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
5600                                   sizeof(ckeymat3)))
5601             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
5602                                          sizeof(ckeymat3))))
5603         goto end;
5604
5605     testresult = 1;
5606
5607  end:
5608     SSL_free(serverssl);
5609     SSL_free(clientssl);
5610     SSL_CTX_free(sctx2);
5611     SSL_CTX_free(sctx);
5612     SSL_CTX_free(cctx);
5613
5614     return testresult;
5615 }
5616
5617 #ifndef OSSL_NO_USABLE_TLS1_3
5618 /*
5619  * Test that SSL_export_keying_material_early() produces expected
5620  * results. There are no test vectors so all we do is test that both
5621  * sides of the communication produce the same results for different
5622  * protocol versions.
5623  */
5624 static int test_export_key_mat_early(int idx)
5625 {
5626     static const char label[] = "test label";
5627     static const unsigned char context[] = "context";
5628     int testresult = 0;
5629     SSL_CTX *cctx = NULL, *sctx = NULL;
5630     SSL *clientssl = NULL, *serverssl = NULL;
5631     SSL_SESSION *sess = NULL;
5632     const unsigned char *emptycontext = NULL;
5633     unsigned char ckeymat1[80], ckeymat2[80];
5634     unsigned char skeymat1[80], skeymat2[80];
5635     unsigned char buf[1];
5636     size_t readbytes, written;
5637
5638     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
5639                                         &sess, idx)))
5640         goto end;
5641
5642     /* Here writing 0 length early data is enough. */
5643     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
5644             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
5645                                                 &readbytes),
5646                             SSL_READ_EARLY_DATA_ERROR)
5647             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
5648                             SSL_EARLY_DATA_ACCEPTED))
5649         goto end;
5650
5651     if (!TEST_int_eq(SSL_export_keying_material_early(
5652                      clientssl, ckeymat1, sizeof(ckeymat1), label,
5653                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
5654             || !TEST_int_eq(SSL_export_keying_material_early(
5655                             clientssl, ckeymat2, sizeof(ckeymat2), label,
5656                             sizeof(label) - 1, emptycontext, 0), 1)
5657             || !TEST_int_eq(SSL_export_keying_material_early(
5658                             serverssl, skeymat1, sizeof(skeymat1), label,
5659                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
5660             || !TEST_int_eq(SSL_export_keying_material_early(
5661                             serverssl, skeymat2, sizeof(skeymat2), label,
5662                             sizeof(label) - 1, emptycontext, 0), 1)
5663                /*
5664                 * Check that both sides created the same key material with the
5665                 * same context.
5666                 */
5667             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
5668                             sizeof(skeymat1))
5669                /*
5670                 * Check that both sides created the same key material with an
5671                 * empty context.
5672                 */
5673             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
5674                             sizeof(skeymat2))
5675                /* Different contexts should produce different results */
5676             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
5677                             sizeof(ckeymat2)))
5678         goto end;
5679
5680     testresult = 1;
5681
5682  end:
5683     SSL_SESSION_free(sess);
5684     SSL_SESSION_free(clientpsk);
5685     SSL_SESSION_free(serverpsk);
5686     clientpsk = serverpsk = NULL;
5687     SSL_free(serverssl);
5688     SSL_free(clientssl);
5689     SSL_CTX_free(sctx);
5690     SSL_CTX_free(cctx);
5691
5692     return testresult;
5693 }
5694
5695 #define NUM_KEY_UPDATE_MESSAGES 40
5696 /*
5697  * Test KeyUpdate.
5698  */
5699 static int test_key_update(void)
5700 {
5701     SSL_CTX *cctx = NULL, *sctx = NULL;
5702     SSL *clientssl = NULL, *serverssl = NULL;
5703     int testresult = 0, i, j;
5704     char buf[20];
5705     static char *mess = "A test message";
5706
5707     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5708                                        TLS_client_method(),
5709                                        TLS1_3_VERSION,
5710                                        0,
5711                                        &sctx, &cctx, cert, privkey))
5712             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5713                                              NULL, NULL))
5714             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5715                                                 SSL_ERROR_NONE)))
5716         goto end;
5717
5718     for (j = 0; j < 2; j++) {
5719         /* Send lots of KeyUpdate messages */
5720         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
5721             if (!TEST_true(SSL_key_update(clientssl,
5722                                           (j == 0)
5723                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
5724                                           : SSL_KEY_UPDATE_REQUESTED))
5725                     || !TEST_true(SSL_do_handshake(clientssl)))
5726                 goto end;
5727         }
5728
5729         /* Check that sending and receiving app data is ok */
5730         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
5731                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
5732                                          strlen(mess)))
5733             goto end;
5734
5735         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
5736                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
5737                                          strlen(mess)))
5738             goto end;
5739     }
5740
5741     testresult = 1;
5742
5743  end:
5744     SSL_free(serverssl);
5745     SSL_free(clientssl);
5746     SSL_CTX_free(sctx);
5747     SSL_CTX_free(cctx);
5748
5749     return testresult;
5750 }
5751
5752 /*
5753  * Test we can handle a KeyUpdate (update requested) message while write data
5754  * is pending.
5755  * Test 0: Client sends KeyUpdate while Server is writing
5756  * Test 1: Server sends KeyUpdate while Client is writing
5757  */
5758 static int test_key_update_in_write(int tst)
5759 {
5760     SSL_CTX *cctx = NULL, *sctx = NULL;
5761     SSL *clientssl = NULL, *serverssl = NULL;
5762     int testresult = 0;
5763     char buf[20];
5764     static char *mess = "A test message";
5765     BIO *bretry = BIO_new(bio_s_always_retry());
5766     BIO *tmp = NULL;
5767     SSL *peerupdate = NULL, *peerwrite = NULL;
5768
5769     if (!TEST_ptr(bretry)
5770             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5771                                               TLS_client_method(),
5772                                               TLS1_3_VERSION,
5773                                               0,
5774                                               &sctx, &cctx, cert, privkey))
5775             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5776                                              NULL, NULL))
5777             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5778                                                 SSL_ERROR_NONE)))
5779         goto end;
5780
5781     peerupdate = tst == 0 ? clientssl : serverssl;
5782     peerwrite = tst == 0 ? serverssl : clientssl;
5783
5784     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
5785             || !TEST_true(SSL_do_handshake(peerupdate)))
5786         goto end;
5787
5788     /* Swap the writing endpoint's write BIO to force a retry */
5789     tmp = SSL_get_wbio(peerwrite);
5790     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
5791         tmp = NULL;
5792         goto end;
5793     }
5794     SSL_set0_wbio(peerwrite, bretry);
5795     bretry = NULL;
5796
5797     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
5798     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
5799             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE))
5800         goto end;
5801
5802     /* Reinstate the original writing endpoint's write BIO */
5803     SSL_set0_wbio(peerwrite, tmp);
5804     tmp = NULL;
5805
5806     /* Now read some data - we will read the key update */
5807     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
5808             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ))
5809         goto end;
5810
5811     /*
5812      * Complete the write we started previously and read it from the other
5813      * endpoint
5814      */
5815     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
5816             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
5817         goto end;
5818
5819     /* Write more data to ensure we send the KeyUpdate message back */
5820     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
5821             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
5822         goto end;
5823
5824     testresult = 1;
5825
5826  end:
5827     SSL_free(serverssl);
5828     SSL_free(clientssl);
5829     SSL_CTX_free(sctx);
5830     SSL_CTX_free(cctx);
5831     BIO_free(bretry);
5832     BIO_free(tmp);
5833
5834     return testresult;
5835 }
5836 #endif /* OSSL_NO_USABLE_TLS1_3 */
5837
5838 static int test_ssl_clear(int idx)
5839 {
5840     SSL_CTX *cctx = NULL, *sctx = NULL;
5841     SSL *clientssl = NULL, *serverssl = NULL;
5842     int testresult = 0;
5843
5844 #ifdef OPENSSL_NO_TLS1_2
5845     if (idx == 1)
5846         return 1;
5847 #endif
5848
5849     /* Create an initial connection */
5850     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5851                                        TLS_client_method(), TLS1_VERSION, 0,
5852                                        &sctx, &cctx, cert, privkey))
5853             || (idx == 1
5854                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
5855                                                             TLS1_2_VERSION)))
5856             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5857                                           &clientssl, NULL, NULL))
5858             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5859                                                 SSL_ERROR_NONE)))
5860         goto end;
5861
5862     SSL_shutdown(clientssl);
5863     SSL_shutdown(serverssl);
5864     SSL_free(serverssl);
5865     serverssl = NULL;
5866
5867     /* Clear clientssl - we're going to reuse the object */
5868     if (!TEST_true(SSL_clear(clientssl)))
5869         goto end;
5870
5871     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5872                                              NULL, NULL))
5873             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5874                                                 SSL_ERROR_NONE))
5875             || !TEST_true(SSL_session_reused(clientssl)))
5876         goto end;
5877
5878     SSL_shutdown(clientssl);
5879     SSL_shutdown(serverssl);
5880
5881     testresult = 1;
5882
5883  end:
5884     SSL_free(serverssl);
5885     SSL_free(clientssl);
5886     SSL_CTX_free(sctx);
5887     SSL_CTX_free(cctx);
5888
5889     return testresult;
5890 }
5891
5892 /* Parse CH and retrieve any MFL extension value if present */
5893 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
5894 {
5895     long len;
5896     unsigned char *data;
5897     PACKET pkt, pkt2, pkt3;
5898     unsigned int MFL_code = 0, type = 0;
5899
5900     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
5901         goto end;
5902
5903     memset(&pkt, 0, sizeof(pkt));
5904     memset(&pkt2, 0, sizeof(pkt2));
5905     memset(&pkt3, 0, sizeof(pkt3));
5906
5907     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
5908                /* Skip the record header */
5909             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
5910                /* Skip the handshake message header */
5911             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
5912                /* Skip client version and random */
5913             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
5914                                                + SSL3_RANDOM_SIZE))
5915                /* Skip session id */
5916             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
5917                /* Skip ciphers */
5918             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
5919                /* Skip compression */
5920             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
5921                /* Extensions len */
5922             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
5923         goto end;
5924
5925     /* Loop through all extensions */
5926     while (PACKET_remaining(&pkt2)) {
5927         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
5928                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
5929             goto end;
5930
5931         if (type == TLSEXT_TYPE_max_fragment_length) {
5932             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
5933                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
5934                 goto end;
5935
5936             *mfl_codemfl_code = MFL_code;
5937             return 1;
5938         }
5939     }
5940
5941  end:
5942     return 0;
5943 }
5944
5945 /* Maximum-Fragment-Length TLS extension mode to test */
5946 static const unsigned char max_fragment_len_test[] = {
5947     TLSEXT_max_fragment_length_512,
5948     TLSEXT_max_fragment_length_1024,
5949     TLSEXT_max_fragment_length_2048,
5950     TLSEXT_max_fragment_length_4096
5951 };
5952
5953 static int test_max_fragment_len_ext(int idx_tst)
5954 {
5955     SSL_CTX *ctx = NULL;
5956     SSL *con = NULL;
5957     int testresult = 0, MFL_mode = 0;
5958     BIO *rbio, *wbio;
5959
5960     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(),
5961                                        TLS1_VERSION, 0, NULL, &ctx, NULL,
5962                                        NULL)))
5963         return 0;
5964
5965     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
5966                    ctx, max_fragment_len_test[idx_tst])))
5967         goto end;
5968
5969     con = SSL_new(ctx);
5970     if (!TEST_ptr(con))
5971         goto end;
5972
5973     rbio = BIO_new(BIO_s_mem());
5974     wbio = BIO_new(BIO_s_mem());
5975     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
5976         BIO_free(rbio);
5977         BIO_free(wbio);
5978         goto end;
5979     }
5980
5981     SSL_set_bio(con, rbio, wbio);
5982
5983     if (!TEST_int_le(SSL_connect(con), 0)) {
5984         /* This shouldn't succeed because we don't have a server! */
5985         goto end;
5986     }
5987
5988     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
5989         /* no MFL in client hello */
5990         goto end;
5991     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
5992         goto end;
5993
5994     testresult = 1;
5995
5996 end:
5997     SSL_free(con);
5998     SSL_CTX_free(ctx);
5999
6000     return testresult;
6001 }
6002
6003 #ifndef OSSL_NO_USABLE_TLS1_3
6004 static int test_pha_key_update(void)
6005 {
6006     SSL_CTX *cctx = NULL, *sctx = NULL;
6007     SSL *clientssl = NULL, *serverssl = NULL;
6008     int testresult = 0;
6009
6010     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6011                                        TLS_client_method(), TLS1_VERSION, 0,
6012                                        &sctx, &cctx, cert, privkey)))
6013         return 0;
6014
6015     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
6016         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
6017         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
6018         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
6019         goto end;
6020
6021     SSL_CTX_set_post_handshake_auth(cctx, 1);
6022
6023     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6024                                       NULL, NULL)))
6025         goto end;
6026
6027     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6028                                          SSL_ERROR_NONE)))
6029         goto end;
6030
6031     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
6032     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
6033         goto end;
6034
6035     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
6036         goto end;
6037
6038     /* Start handshake on the server */
6039     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
6040         goto end;
6041
6042     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
6043     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6044                                          SSL_ERROR_NONE)))
6045         goto end;
6046
6047     SSL_shutdown(clientssl);
6048     SSL_shutdown(serverssl);
6049
6050     testresult = 1;
6051
6052  end:
6053     SSL_free(serverssl);
6054     SSL_free(clientssl);
6055     SSL_CTX_free(sctx);
6056     SSL_CTX_free(cctx);
6057     return testresult;
6058 }
6059 #endif
6060
6061 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
6062
6063 static SRP_VBASE *vbase = NULL;
6064
6065 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
6066 {
6067     int ret = SSL3_AL_FATAL;
6068     char *username;
6069     SRP_user_pwd *user = NULL;
6070
6071     username = SSL_get_srp_username(s);
6072     if (username == NULL) {
6073         *ad = SSL_AD_INTERNAL_ERROR;
6074         goto err;
6075     }
6076
6077     user = SRP_VBASE_get1_by_user(vbase, username);
6078     if (user == NULL) {
6079         *ad = SSL_AD_INTERNAL_ERROR;
6080         goto err;
6081     }
6082
6083     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
6084                                  user->info) <= 0) {
6085         *ad = SSL_AD_INTERNAL_ERROR;
6086         goto err;
6087     }
6088
6089     ret = 0;
6090
6091  err:
6092     SRP_user_pwd_free(user);
6093     return ret;
6094 }
6095
6096 static int create_new_vfile(char *userid, char *password, const char *filename)
6097 {
6098     char *gNid = NULL;
6099     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
6100     TXT_DB *db = NULL;
6101     int ret = 0;
6102     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
6103     size_t i;
6104
6105     if (!TEST_ptr(dummy) || !TEST_ptr(row))
6106         goto end;
6107
6108     gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
6109                                   &row[DB_srpverifier], NULL, NULL, libctx, NULL);
6110     if (!TEST_ptr(gNid))
6111         goto end;
6112
6113     /*
6114      * The only way to create an empty TXT_DB is to provide a BIO with no data
6115      * in it!
6116      */
6117     db = TXT_DB_read(dummy, DB_NUMBER);
6118     if (!TEST_ptr(db))
6119         goto end;
6120
6121     out = BIO_new_file(filename, "w");
6122     if (!TEST_ptr(out))
6123         goto end;
6124
6125     row[DB_srpid] = OPENSSL_strdup(userid);
6126     row[DB_srptype] = OPENSSL_strdup("V");
6127     row[DB_srpgN] = OPENSSL_strdup(gNid);
6128
6129     if (!TEST_ptr(row[DB_srpid])
6130             || !TEST_ptr(row[DB_srptype])
6131             || !TEST_ptr(row[DB_srpgN])
6132             || !TEST_true(TXT_DB_insert(db, row)))
6133         goto end;
6134
6135     row = NULL;
6136
6137     if (!TXT_DB_write(out, db))
6138         goto end;
6139
6140     ret = 1;
6141  end:
6142     if (row != NULL) {
6143         for (i = 0; i < DB_NUMBER; i++)
6144             OPENSSL_free(row[i]);
6145     }
6146     OPENSSL_free(row);
6147     BIO_free(dummy);
6148     BIO_free(out);
6149     TXT_DB_free(db);
6150
6151     return ret;
6152 }
6153
6154 static int create_new_vbase(char *userid, char *password)
6155 {
6156     BIGNUM *verifier = NULL, *salt = NULL;
6157     const SRP_gN *lgN = NULL;
6158     SRP_user_pwd *user_pwd = NULL;
6159     int ret = 0;
6160
6161     lgN = SRP_get_default_gN(NULL);
6162     if (!TEST_ptr(lgN))
6163         goto end;
6164
6165     if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
6166                                              lgN->N, lgN->g, libctx, NULL)))
6167         goto end;
6168
6169     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
6170     if (!TEST_ptr(user_pwd))
6171         goto end;
6172
6173     user_pwd->N = lgN->N;
6174     user_pwd->g = lgN->g;
6175     user_pwd->id = OPENSSL_strdup(userid);
6176     if (!TEST_ptr(user_pwd->id))
6177         goto end;
6178
6179     user_pwd->v = verifier;
6180     user_pwd->s = salt;
6181     verifier = salt = NULL;
6182
6183     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
6184         goto end;
6185     user_pwd = NULL;
6186
6187     ret = 1;
6188 end:
6189     SRP_user_pwd_free(user_pwd);
6190     BN_free(salt);
6191     BN_free(verifier);
6192
6193     return ret;
6194 }
6195
6196 /*
6197  * SRP tests
6198  *
6199  * Test 0: Simple successful SRP connection, new vbase
6200  * Test 1: Connection failure due to bad password, new vbase
6201  * Test 2: Simple successful SRP connection, vbase loaded from existing file
6202  * Test 3: Connection failure due to bad password, vbase loaded from existing
6203  *         file
6204  * Test 4: Simple successful SRP connection, vbase loaded from new file
6205  * Test 5: Connection failure due to bad password, vbase loaded from new file
6206  */
6207 static int test_srp(int tst)
6208 {
6209     char *userid = "test", *password = "password", *tstsrpfile;
6210     SSL_CTX *cctx = NULL, *sctx = NULL;
6211     SSL *clientssl = NULL, *serverssl = NULL;
6212     int ret, testresult = 0;
6213
6214     vbase = SRP_VBASE_new(NULL);
6215     if (!TEST_ptr(vbase))
6216         goto end;
6217
6218     if (tst == 0 || tst == 1) {
6219         if (!TEST_true(create_new_vbase(userid, password)))
6220             goto end;
6221     } else {
6222         if (tst == 4 || tst == 5) {
6223             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
6224                 goto end;
6225             tstsrpfile = tmpfilename;
6226         } else {
6227             tstsrpfile = srpvfile;
6228         }
6229         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
6230             goto end;
6231     }
6232
6233     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6234                                        TLS_client_method(), TLS1_VERSION, 0,
6235                                        &sctx, &cctx, cert, privkey)))
6236         goto end;
6237
6238     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
6239             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
6240             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
6241             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
6242             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
6243         goto end;
6244
6245     if (tst % 2 == 1) {
6246         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
6247             goto end;
6248     } else {
6249         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
6250             goto end;
6251     }
6252
6253     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6254                                       NULL, NULL)))
6255         goto end;
6256
6257     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
6258     if (ret) {
6259         if (!TEST_true(tst % 2 == 0))
6260             goto end;
6261     } else {
6262         if (!TEST_true(tst % 2 == 1))
6263             goto end;
6264     }
6265
6266     testresult = 1;
6267
6268  end:
6269     SRP_VBASE_free(vbase);
6270     vbase = NULL;
6271     SSL_free(serverssl);
6272     SSL_free(clientssl);
6273     SSL_CTX_free(sctx);
6274     SSL_CTX_free(cctx);
6275
6276     return testresult;
6277 }
6278 #endif
6279
6280 static int info_cb_failed = 0;
6281 static int info_cb_offset = 0;
6282 static int info_cb_this_state = -1;
6283
6284 static struct info_cb_states_st {
6285     int where;
6286     const char *statestr;
6287 } info_cb_states[][60] = {
6288     {
6289         /* TLSv1.2 server followed by resumption */
6290         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6291         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
6292         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
6293         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
6294         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
6295         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
6296         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
6297         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
6298         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
6299         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
6300         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
6301         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
6302         {SSL_CB_EXIT, NULL}, {0, NULL},
6303     }, {
6304         /* TLSv1.2 client followed by resumption */
6305         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6306         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
6307         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
6308         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
6309         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
6310         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
6311         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
6312         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6313         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
6314         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
6315         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
6316         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
6317     }, {
6318         /* TLSv1.3 server followed by resumption */
6319         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6320         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
6321         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
6322         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
6323         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
6324         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
6325         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
6326         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6327         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
6328         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
6329         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
6330         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
6331         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
6332     }, {
6333         /* TLSv1.3 client followed by resumption */
6334         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6335         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
6336         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
6337         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
6338         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
6339         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
6340         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "},
6341         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
6342         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
6343         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
6344         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
6345         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
6346         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
6347         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
6348         {SSL_CB_EXIT, NULL}, {0, NULL},
6349     }, {
6350         /* TLSv1.3 server, early_data */
6351         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6352         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
6353         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
6354         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
6355         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
6356         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
6357         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
6358         {SSL_CB_EXIT, NULL}, {0, NULL},
6359     }, {
6360         /* TLSv1.3 client, early_data */
6361         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
6362         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
6363         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
6364         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
6365         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
6366         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
6367         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
6368         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
6369         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
6370     }, {
6371         {0, NULL},
6372     }
6373 };
6374
6375 static void sslapi_info_callback(const SSL *s, int where, int ret)
6376 {
6377     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
6378
6379     /* We do not ever expect a connection to fail in this test */
6380     if (!TEST_false(ret == 0)) {
6381         info_cb_failed = 1;
6382         return;
6383     }
6384
6385     /*
6386      * Do some sanity checks. We never expect these things to happen in this
6387      * test
6388      */
6389     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
6390             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
6391             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
6392         info_cb_failed = 1;
6393         return;
6394     }
6395
6396     /* Now check we're in the right state */
6397     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
6398         info_cb_failed = 1;
6399         return;
6400     }
6401     if ((where & SSL_CB_LOOP) != 0
6402             && !TEST_int_eq(strcmp(SSL_state_string(s),
6403                             state[info_cb_this_state].statestr), 0)) {
6404         info_cb_failed = 1;
6405         return;
6406     }
6407
6408     /*
6409      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
6410      */
6411     if ((where & SSL_CB_HANDSHAKE_DONE)
6412             && SSL_in_init((SSL *)s) != 0) {
6413         info_cb_failed = 1;
6414         return;
6415     }
6416 }
6417
6418 /*
6419  * Test the info callback gets called when we expect it to.
6420  *
6421  * Test 0: TLSv1.2, server
6422  * Test 1: TLSv1.2, client
6423  * Test 2: TLSv1.3, server
6424  * Test 3: TLSv1.3, client
6425  * Test 4: TLSv1.3, server, early_data
6426  * Test 5: TLSv1.3, client, early_data
6427  */
6428 static int test_info_callback(int tst)
6429 {
6430     SSL_CTX *cctx = NULL, *sctx = NULL;
6431     SSL *clientssl = NULL, *serverssl = NULL;
6432     SSL_SESSION *clntsess = NULL;
6433     int testresult = 0;
6434     int tlsvers;
6435
6436     if (tst < 2) {
6437 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
6438 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
6439                                     || !defined(OPENSSL_NO_DH))
6440         tlsvers = TLS1_2_VERSION;
6441 #else
6442         return 1;
6443 #endif
6444     } else {
6445 #ifndef OSSL_NO_USABLE_TLS1_3
6446         tlsvers = TLS1_3_VERSION;
6447 #else
6448         return 1;
6449 #endif
6450     }
6451
6452     /* Reset globals */
6453     info_cb_failed = 0;
6454     info_cb_this_state = -1;
6455     info_cb_offset = tst;
6456
6457 #ifndef OSSL_NO_USABLE_TLS1_3
6458     if (tst >= 4) {
6459         SSL_SESSION *sess = NULL;
6460         size_t written, readbytes;
6461         unsigned char buf[80];
6462
6463         /* early_data tests */
6464         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
6465                                             &serverssl, &sess, 0)))
6466             goto end;
6467
6468         /* We don't actually need this reference */
6469         SSL_SESSION_free(sess);
6470
6471         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
6472                               sslapi_info_callback);
6473
6474         /* Write and read some early data and then complete the connection */
6475         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
6476                                             &written))
6477                 || !TEST_size_t_eq(written, strlen(MSG1))
6478                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
6479                                                     sizeof(buf), &readbytes),
6480                                 SSL_READ_EARLY_DATA_SUCCESS)
6481                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
6482                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6483                                 SSL_EARLY_DATA_ACCEPTED)
6484                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
6485                                                     SSL_ERROR_NONE))
6486                 || !TEST_false(info_cb_failed))
6487             goto end;
6488
6489         testresult = 1;
6490         goto end;
6491     }
6492 #endif
6493
6494     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6495                                        TLS_client_method(),
6496                                        tlsvers, tlsvers, &sctx, &cctx, cert,
6497                                        privkey)))
6498         goto end;
6499
6500     if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
6501         goto end;
6502
6503     /*
6504      * For even numbered tests we check the server callbacks. For odd numbers we
6505      * check the client.
6506      */
6507     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
6508                               sslapi_info_callback);
6509
6510     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6511                                           &clientssl, NULL, NULL))
6512         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6513                                             SSL_ERROR_NONE))
6514         || !TEST_false(info_cb_failed))
6515     goto end;
6516
6517
6518
6519     clntsess = SSL_get1_session(clientssl);
6520     SSL_shutdown(clientssl);
6521     SSL_shutdown(serverssl);
6522     SSL_free(serverssl);
6523     SSL_free(clientssl);
6524     serverssl = clientssl = NULL;
6525
6526     /* Now do a resumption */
6527     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6528                                       NULL))
6529             || !TEST_true(SSL_set_session(clientssl, clntsess))
6530             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6531                                                 SSL_ERROR_NONE))
6532             || !TEST_true(SSL_session_reused(clientssl))
6533             || !TEST_false(info_cb_failed))
6534         goto end;
6535
6536     testresult = 1;
6537
6538  end:
6539     SSL_free(serverssl);
6540     SSL_free(clientssl);
6541     SSL_SESSION_free(clntsess);
6542     SSL_CTX_free(sctx);
6543     SSL_CTX_free(cctx);
6544     return testresult;
6545 }
6546
6547 static int test_ssl_pending(int tst)
6548 {
6549     SSL_CTX *cctx = NULL, *sctx = NULL;
6550     SSL *clientssl = NULL, *serverssl = NULL;
6551     int testresult = 0;
6552     char msg[] = "A test message";
6553     char buf[5];
6554     size_t written, readbytes;
6555
6556     if (tst == 0) {
6557         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6558                                            TLS_client_method(),
6559                                            TLS1_VERSION, 0,
6560                                            &sctx, &cctx, cert, privkey)))
6561             goto end;
6562     } else {
6563 #ifndef OPENSSL_NO_DTLS
6564         if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
6565                                            DTLS_client_method(),
6566                                            DTLS1_VERSION, 0,
6567                                            &sctx, &cctx, cert, privkey)))
6568             goto end;
6569 #else
6570         return 1;
6571 #endif
6572     }
6573
6574     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6575                                              NULL, NULL))
6576             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6577                                                 SSL_ERROR_NONE)))
6578         goto end;
6579
6580     if (!TEST_int_eq(SSL_pending(clientssl), 0)
6581             || !TEST_false(SSL_has_pending(clientssl))
6582             || !TEST_int_eq(SSL_pending(serverssl), 0)
6583             || !TEST_false(SSL_has_pending(serverssl))
6584             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
6585             || !TEST_size_t_eq(written, sizeof(msg))
6586             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
6587             || !TEST_size_t_eq(readbytes, sizeof(buf))
6588             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
6589             || !TEST_true(SSL_has_pending(clientssl)))
6590         goto end;
6591
6592     testresult = 1;
6593
6594  end:
6595     SSL_free(serverssl);
6596     SSL_free(clientssl);
6597     SSL_CTX_free(sctx);
6598     SSL_CTX_free(cctx);
6599
6600     return testresult;
6601 }
6602
6603 static struct {
6604     unsigned int maxprot;
6605     const char *clntciphers;
6606     const char *clnttls13ciphers;
6607     const char *srvrciphers;
6608     const char *srvrtls13ciphers;
6609     const char *shared;
6610     const char *fipsshared;
6611 } shared_ciphers_data[] = {
6612 /*
6613  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
6614  * TLSv1.3 is enabled but TLSv1.2 is disabled.
6615  */
6616 #if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
6617     {
6618         TLS1_2_VERSION,
6619         "AES128-SHA:AES256-SHA",
6620         NULL,
6621         "AES256-SHA:DHE-RSA-AES128-SHA",
6622         NULL,
6623         "AES256-SHA",
6624         "AES256-SHA"
6625     },
6626 # if !defined(OPENSSL_NO_CHACHA) \
6627      && !defined(OPENSSL_NO_POLY1305) \
6628      && !defined(OPENSSL_NO_EC)
6629     {
6630         TLS1_2_VERSION,
6631         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
6632         NULL,
6633         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
6634         NULL,
6635         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
6636         "AES128-SHA"
6637     },
6638 # endif
6639     {
6640         TLS1_2_VERSION,
6641         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
6642         NULL,
6643         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
6644         NULL,
6645         "AES128-SHA:AES256-SHA",
6646         "AES128-SHA:AES256-SHA"
6647     },
6648     {
6649         TLS1_2_VERSION,
6650         "AES128-SHA:AES256-SHA",
6651         NULL,
6652         "AES128-SHA:DHE-RSA-AES128-SHA",
6653         NULL,
6654         "AES128-SHA",
6655         "AES128-SHA"
6656     },
6657 #endif
6658 /*
6659  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
6660  * enabled.
6661  */
6662 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
6663     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
6664     {
6665         TLS1_3_VERSION,
6666         "AES128-SHA:AES256-SHA",
6667         NULL,
6668         "AES256-SHA:AES128-SHA256",
6669         NULL,
6670         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
6671         "TLS_AES_128_GCM_SHA256:AES256-SHA",
6672         "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA"
6673     },
6674 #endif
6675 #ifndef OSSL_NO_USABLE_TLS1_3
6676     {
6677         TLS1_3_VERSION,
6678         "AES128-SHA",
6679         "TLS_AES_256_GCM_SHA384",
6680         "AES256-SHA",
6681         "TLS_AES_256_GCM_SHA384",
6682         "TLS_AES_256_GCM_SHA384",
6683         "TLS_AES_256_GCM_SHA384"
6684     },
6685 #endif
6686 };
6687
6688 static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
6689 {
6690     SSL_CTX *cctx = NULL, *sctx = NULL;
6691     SSL *clientssl = NULL, *serverssl = NULL;
6692     int testresult = 0;
6693     char buf[1024];
6694     OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
6695
6696     if (!TEST_ptr(tmplibctx))
6697         goto end;
6698
6699     /*
6700      * Regardless of whether we're testing with the FIPS provider loaded into
6701      * libctx, we want one peer to always use the full set of ciphersuites
6702      * available. Therefore we use a separate libctx with the default provider
6703      * loaded into it. We run the same tests twice - once with the client side
6704      * having the full set of ciphersuites and once with the server side.
6705      */
6706     if (clnt) {
6707         cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
6708         if (!TEST_ptr(cctx))
6709             goto end;
6710     } else {
6711         sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
6712         if (!TEST_ptr(sctx))
6713             goto end;
6714     }
6715
6716     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6717                                        TLS_client_method(),
6718                                        TLS1_VERSION,
6719                                        shared_ciphers_data[tst].maxprot,
6720                                        &sctx, &cctx, cert, privkey)))
6721         goto end;
6722
6723     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
6724                                         shared_ciphers_data[tst].clntciphers))
6725             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
6726                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
6727                                     shared_ciphers_data[tst].clnttls13ciphers)))
6728             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
6729                                         shared_ciphers_data[tst].srvrciphers))
6730             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
6731                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
6732                                     shared_ciphers_data[tst].srvrtls13ciphers))))
6733         goto end;
6734
6735
6736     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6737                                              NULL, NULL))
6738             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6739                                                 SSL_ERROR_NONE)))
6740         goto end;
6741
6742     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
6743             || !TEST_int_eq(strcmp(buf,
6744                                    is_fips
6745                                    ? shared_ciphers_data[tst].fipsshared
6746                                    : shared_ciphers_data[tst].shared),
6747                                    0)) {
6748         TEST_info("Shared ciphers are: %s\n", buf);
6749         goto end;
6750     }
6751
6752     testresult = 1;
6753
6754  end:
6755     SSL_free(serverssl);
6756     SSL_free(clientssl);
6757     SSL_CTX_free(sctx);
6758     SSL_CTX_free(cctx);
6759     OSSL_LIB_CTX_free(tmplibctx);
6760
6761     return testresult;
6762 }
6763
6764 static int test_ssl_get_shared_ciphers(int tst)
6765 {
6766     return int_test_ssl_get_shared_ciphers(tst, 0)
6767            && int_test_ssl_get_shared_ciphers(tst, 1);
6768 }
6769
6770
6771 static const char *appdata = "Hello World";
6772 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
6773 static int tick_key_renew = 0;
6774 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
6775
6776 static int gen_tick_cb(SSL *s, void *arg)
6777 {
6778     gen_tick_called = 1;
6779
6780     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
6781                                            strlen(appdata));
6782 }
6783
6784 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
6785                                      const unsigned char *keyname,
6786                                      size_t keyname_length,
6787                                      SSL_TICKET_STATUS status,
6788                                      void *arg)
6789 {
6790     void *tickdata;
6791     size_t tickdlen;
6792
6793     dec_tick_called = 1;
6794
6795     if (status == SSL_TICKET_EMPTY)
6796         return SSL_TICKET_RETURN_IGNORE_RENEW;
6797
6798     if (!TEST_true(status == SSL_TICKET_SUCCESS
6799                    || status == SSL_TICKET_SUCCESS_RENEW))
6800         return SSL_TICKET_RETURN_ABORT;
6801
6802     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
6803                                                    &tickdlen))
6804             || !TEST_size_t_eq(tickdlen, strlen(appdata))
6805             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
6806         return SSL_TICKET_RETURN_ABORT;
6807
6808     if (tick_key_cb_called)  {
6809         /* Don't change what the ticket key callback wanted to do */
6810         switch (status) {
6811         case SSL_TICKET_NO_DECRYPT:
6812             return SSL_TICKET_RETURN_IGNORE_RENEW;
6813
6814         case SSL_TICKET_SUCCESS:
6815             return SSL_TICKET_RETURN_USE;
6816
6817         case SSL_TICKET_SUCCESS_RENEW:
6818             return SSL_TICKET_RETURN_USE_RENEW;
6819
6820         default:
6821             return SSL_TICKET_RETURN_ABORT;
6822         }
6823     }
6824     return tick_dec_ret;
6825
6826 }
6827
6828 #ifndef OPENSSL_NO_DEPRECATED_3_0
6829 static int tick_key_cb(SSL *s, unsigned char key_name[16],
6830                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
6831                        HMAC_CTX *hctx, int enc)
6832 {
6833     const unsigned char tick_aes_key[16] = "0123456789abcdef";
6834     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
6835     EVP_CIPHER *aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
6836     EVP_MD *sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
6837     int ret;
6838
6839     tick_key_cb_called = 1;
6840     memset(iv, 0, AES_BLOCK_SIZE);
6841     memset(key_name, 0, 16);
6842     if (aes128cbc == NULL
6843             || sha256 == NULL
6844             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
6845             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
6846                              NULL))
6847         ret = -1;
6848     else
6849         ret = tick_key_renew ? 2 : 1;
6850
6851     EVP_CIPHER_free(aes128cbc);
6852     EVP_MD_free(sha256);
6853
6854     return ret;
6855 }
6856 #endif
6857
6858 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
6859                            unsigned char iv[EVP_MAX_IV_LENGTH],
6860                            EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
6861 {
6862     const unsigned char tick_aes_key[16] = "0123456789abcdef";
6863     unsigned char tick_hmac_key[16] = "0123456789abcdef";
6864     OSSL_PARAM params[3];
6865     EVP_CIPHER *aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
6866     int ret;
6867
6868     tick_key_cb_called = 1;
6869     memset(iv, 0, AES_BLOCK_SIZE);
6870     memset(key_name, 0, 16);
6871     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
6872                                                  "SHA256", 0);
6873     params[1] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
6874                                                   tick_hmac_key,
6875                                                   sizeof(tick_hmac_key));
6876     params[2] = OSSL_PARAM_construct_end();
6877     if (aes128cbc == NULL
6878             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
6879             || !EVP_MAC_CTX_set_params(hctx, params)
6880             || !EVP_MAC_init(hctx))
6881         ret = -1;
6882     else
6883         ret = tick_key_renew ? 2 : 1;
6884
6885     EVP_CIPHER_free(aes128cbc);
6886
6887     return ret;
6888 }
6889
6890 /*
6891  * Test the various ticket callbacks
6892  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
6893  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
6894  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
6895  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
6896  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
6897  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
6898  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
6899  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
6900  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
6901  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
6902  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
6903  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
6904  * Test 12: TLSv1.2, ticket key callback, ticket, no renewal
6905  * Test 13: TLSv1.3, ticket key callback, ticket, no renewal
6906  * Test 14: TLSv1.2, ticket key callback, ticket, renewal
6907  * Test 15: TLSv1.3, ticket key callback, ticket, renewal
6908  */
6909 static int test_ticket_callbacks(int tst)
6910 {
6911     SSL_CTX *cctx = NULL, *sctx = NULL;
6912     SSL *clientssl = NULL, *serverssl = NULL;
6913     SSL_SESSION *clntsess = NULL;
6914     int testresult = 0;
6915
6916 #ifdef OPENSSL_NO_TLS1_2
6917     if (tst % 2 == 0)
6918         return 1;
6919 #endif
6920 #ifdef OSSL_NO_USABLE_TLS1_3
6921     if (tst % 2 == 1)
6922         return 1;
6923 #endif
6924 #ifdef OPENSSL_NO_DEPRECATED_3_0
6925     if (tst >= 8 && tst <= 11)
6926         return 1;
6927 #endif
6928
6929     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
6930
6931     /* Which tests the ticket key callback should request renewal for */
6932     if (tst == 10 || tst == 11 || tst == 14 || tst == 15)
6933         tick_key_renew = 1;
6934     else
6935         tick_key_renew = 0;
6936
6937     /* Which tests the decrypt ticket callback should request renewal for */
6938     switch (tst) {
6939     case 0:
6940     case 1:
6941         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
6942         break;
6943
6944     case 2:
6945     case 3:
6946         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
6947         break;
6948
6949     case 4:
6950     case 5:
6951         tick_dec_ret = SSL_TICKET_RETURN_USE;
6952         break;
6953
6954     case 6:
6955     case 7:
6956         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
6957         break;
6958
6959     default:
6960         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
6961     }
6962
6963     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6964                                        TLS_client_method(),
6965                                        TLS1_VERSION,
6966                                        ((tst % 2) == 0) ? TLS1_2_VERSION
6967                                                         : TLS1_3_VERSION,
6968                                        &sctx, &cctx, cert, privkey)))
6969         goto end;
6970
6971     /*
6972      * We only want sessions to resume from tickets - not the session cache. So
6973      * switch the cache off.
6974      */
6975     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
6976         goto end;
6977
6978     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
6979                                                  NULL)))
6980         goto end;
6981
6982     if (tst >= 12) {
6983         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
6984             goto end;
6985 #ifndef OPENSSL_NO_DEPRECATED_3_0
6986     } else if (tst >= 8) {
6987         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
6988             goto end;
6989 #endif
6990     }
6991
6992     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6993                                              NULL, NULL))
6994             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6995                                                 SSL_ERROR_NONE)))
6996         goto end;
6997
6998     /*
6999      * The decrypt ticket key callback in TLSv1.2 should be called even though
7000      * we have no ticket yet, because it gets called with a status of
7001      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
7002      * actually send any ticket data). This does not happen in TLSv1.3 because
7003      * it is not valid to send empty ticket data in TLSv1.3.
7004      */
7005     if (!TEST_int_eq(gen_tick_called, 1)
7006             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
7007         goto end;
7008
7009     gen_tick_called = dec_tick_called = 0;
7010
7011     clntsess = SSL_get1_session(clientssl);
7012     SSL_shutdown(clientssl);
7013     SSL_shutdown(serverssl);
7014     SSL_free(serverssl);
7015     SSL_free(clientssl);
7016     serverssl = clientssl = NULL;
7017
7018     /* Now do a resumption */
7019     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
7020                                       NULL))
7021             || !TEST_true(SSL_set_session(clientssl, clntsess))
7022             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7023                                                 SSL_ERROR_NONE)))
7024         goto end;
7025
7026     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
7027             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW) {
7028         if (!TEST_false(SSL_session_reused(clientssl)))
7029             goto end;
7030     } else {
7031         if (!TEST_true(SSL_session_reused(clientssl)))
7032             goto end;
7033     }
7034
7035     if (!TEST_int_eq(gen_tick_called,
7036                      (tick_key_renew
7037                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
7038                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
7039                      ? 1 : 0)
7040             || !TEST_int_eq(dec_tick_called, 1))
7041         goto end;
7042
7043     testresult = 1;
7044
7045  end:
7046     SSL_SESSION_free(clntsess);
7047     SSL_free(serverssl);
7048     SSL_free(clientssl);
7049     SSL_CTX_free(sctx);
7050     SSL_CTX_free(cctx);
7051
7052     return testresult;
7053 }
7054
7055 /*
7056  * Test incorrect shutdown.
7057  * Test 0: client does not shutdown properly,
7058  *         server does not set SSL_OP_IGNORE_UNEXPECTED_EOF,
7059  *         server should get SSL_ERROR_SSL
7060  * Test 1: client does not shutdown properly,
7061  *         server sets SSL_OP_IGNORE_UNEXPECTED_EOF,
7062  *         server should get SSL_ERROR_ZERO_RETURN
7063  */
7064 static int test_incorrect_shutdown(int tst)
7065 {
7066     SSL_CTX *cctx = NULL, *sctx = NULL;
7067     SSL *clientssl = NULL, *serverssl = NULL;
7068     int testresult = 0;
7069     char buf[80];
7070     BIO *c2s;
7071
7072     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7073                                        TLS_client_method(), 0, 0,
7074                                        &sctx, &cctx, cert, privkey)))
7075         goto end;
7076
7077     if (tst == 1)
7078         SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
7079
7080     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7081                                             NULL, NULL)))
7082         goto end;
7083
7084     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7085                                               SSL_ERROR_NONE)))
7086         goto end;
7087
7088     c2s = SSL_get_rbio(serverssl);
7089     BIO_set_mem_eof_return(c2s, 0);
7090
7091     if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf))))
7092         goto end;
7093
7094     if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL) )
7095         goto end;
7096     if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN) )
7097         goto end;
7098
7099     testresult = 1;
7100
7101  end:
7102     SSL_free(serverssl);
7103     SSL_free(clientssl);
7104     SSL_CTX_free(sctx);
7105     SSL_CTX_free(cctx);
7106
7107     return testresult;
7108 }
7109
7110 /*
7111  * Test bi-directional shutdown.
7112  * Test 0: TLSv1.2
7113  * Test 1: TLSv1.2, server continues to read/write after client shutdown
7114  * Test 2: TLSv1.3, no pending NewSessionTicket messages
7115  * Test 3: TLSv1.3, pending NewSessionTicket messages
7116  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
7117  *                  sends key update, client reads it
7118  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
7119  *                  sends CertificateRequest, client reads and ignores it
7120  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
7121  *                  doesn't read it
7122  */
7123 static int test_shutdown(int tst)
7124 {
7125     SSL_CTX *cctx = NULL, *sctx = NULL;
7126     SSL *clientssl = NULL, *serverssl = NULL;
7127     int testresult = 0;
7128     char msg[] = "A test message";
7129     char buf[80];
7130     size_t written, readbytes;
7131     SSL_SESSION *sess;
7132
7133 #ifdef OPENSSL_NO_TLS1_2
7134     if (tst <= 1)
7135         return 1;
7136 #endif
7137 #ifdef OSSL_NO_USABLE_TLS1_3
7138     if (tst >= 2)
7139         return 1;
7140 #endif
7141
7142     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7143                                        TLS_client_method(),
7144                                        TLS1_VERSION,
7145                                        (tst <= 1) ? TLS1_2_VERSION
7146                                                   : TLS1_3_VERSION,
7147                                        &sctx, &cctx, cert, privkey)))
7148         goto end;
7149
7150     if (tst == 5)
7151         SSL_CTX_set_post_handshake_auth(cctx, 1);
7152
7153     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7154                                              NULL, NULL)))
7155         goto end;
7156
7157     if (tst == 3) {
7158         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
7159                                                   SSL_ERROR_NONE, 1))
7160                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
7161                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
7162             goto end;
7163     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7164                                               SSL_ERROR_NONE))
7165             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
7166             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
7167         goto end;
7168     }
7169
7170     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
7171         goto end;
7172
7173     if (tst >= 4) {
7174         /*
7175          * Reading on the server after the client has sent close_notify should
7176          * fail and provide SSL_ERROR_ZERO_RETURN
7177          */
7178         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
7179                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
7180                                 SSL_ERROR_ZERO_RETURN)
7181                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
7182                                 SSL_RECEIVED_SHUTDOWN)
7183                    /*
7184                     * Even though we're shutdown on receive we should still be
7185                     * able to write.
7186                     */
7187                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
7188             goto end;
7189         if (tst == 4
7190                 && !TEST_true(SSL_key_update(serverssl,
7191                                              SSL_KEY_UPDATE_REQUESTED)))
7192             goto end;
7193         if (tst == 5) {
7194             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
7195             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
7196                 goto end;
7197         }
7198         if ((tst == 4 || tst == 5)
7199                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
7200             goto end;
7201         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
7202             goto end;
7203         if (tst == 4 || tst == 5) {
7204             /* Should still be able to read data from server */
7205             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
7206                                        &readbytes))
7207                     || !TEST_size_t_eq(readbytes, sizeof(msg))
7208                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
7209                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
7210                                               &readbytes))
7211                     || !TEST_size_t_eq(readbytes, sizeof(msg))
7212                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
7213                 goto end;
7214         }
7215     }
7216
7217     /* Writing on the client after sending close_notify shouldn't be possible */
7218     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
7219         goto end;
7220
7221     if (tst < 4) {
7222         /*
7223          * For these tests the client has sent close_notify but it has not yet
7224          * been received by the server. The server has not sent close_notify
7225          * yet.
7226          */
7227         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
7228                    /*
7229                     * Writing on the server after sending close_notify shouldn't
7230                     * be possible.
7231                     */
7232                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
7233                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
7234                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
7235                 || !TEST_true(SSL_SESSION_is_resumable(sess))
7236                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
7237             goto end;
7238     } else if (tst == 4 || tst == 5) {
7239         /*
7240          * In this test the client has sent close_notify and it has been
7241          * received by the server which has responded with a close_notify. The
7242          * client needs to read the close_notify sent by the server.
7243          */
7244         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
7245                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
7246                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
7247             goto end;
7248     } else {
7249         /*
7250          * tst == 6
7251          *
7252          * The client has sent close_notify and is expecting a close_notify
7253          * back, but instead there is application data first. The shutdown
7254          * should fail with a fatal error.
7255          */
7256         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
7257                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
7258             goto end;
7259     }
7260
7261     testresult = 1;
7262
7263  end:
7264     SSL_free(serverssl);
7265     SSL_free(clientssl);
7266     SSL_CTX_free(sctx);
7267     SSL_CTX_free(cctx);
7268
7269     return testresult;
7270 }
7271
7272 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
7273 static int cert_cb_cnt;
7274
7275 static int cert_cb(SSL *s, void *arg)
7276 {
7277     SSL_CTX *ctx = (SSL_CTX *)arg;
7278     BIO *in = NULL;
7279     EVP_PKEY *pkey = NULL;
7280     X509 *x509 = NULL, *rootx = NULL;
7281     STACK_OF(X509) *chain = NULL;
7282     char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
7283     int ret = 0;
7284
7285     if (cert_cb_cnt == 0) {
7286         /* Suspend the handshake */
7287         cert_cb_cnt++;
7288         return -1;
7289     } else if (cert_cb_cnt == 1) {
7290         /*
7291          * Update the SSL_CTX, set the certificate and private key and then
7292          * continue the handshake normally.
7293          */
7294         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
7295             return 0;
7296
7297         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
7298                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
7299                                                       SSL_FILETYPE_PEM))
7300                 || !TEST_true(SSL_check_private_key(s)))
7301             return 0;
7302         cert_cb_cnt++;
7303         return 1;
7304     } else if (cert_cb_cnt == 3) {
7305         int rv;
7306
7307         rootfile = test_mk_file_path(certsdir, "rootcert.pem");
7308         ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
7309         ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
7310         if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
7311             goto out;
7312         chain = sk_X509_new_null();
7313         if (!TEST_ptr(chain))
7314             goto out;
7315         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
7316                 || !TEST_int_ge(BIO_read_filename(in, rootfile), 0)
7317                 || !TEST_ptr(rootx = X509_new_ex(libctx, NULL))
7318                 || !TEST_ptr(PEM_read_bio_X509(in, &rootx, NULL, NULL))
7319                 || !TEST_true(sk_X509_push(chain, rootx)))
7320             goto out;
7321         rootx = NULL;
7322         BIO_free(in);
7323         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
7324                 || !TEST_int_ge(BIO_read_filename(in, ecdsacert), 0)
7325                 || !TEST_ptr(x509 = X509_new_ex(libctx, NULL))
7326                 || !TEST_ptr(PEM_read_bio_X509(in, &x509, NULL, NULL)))
7327             goto out;
7328         BIO_free(in);
7329         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
7330                 || !TEST_int_ge(BIO_read_filename(in, ecdsakey), 0)
7331                 || !TEST_ptr(pkey = PEM_read_bio_PrivateKey_ex(in, NULL,
7332                                                                NULL, NULL,
7333                                                                libctx, NULL)))
7334             goto out;
7335         rv = SSL_check_chain(s, x509, pkey, chain);
7336         /*
7337          * If the cert doesn't show as valid here (e.g., because we don't
7338          * have any shared sigalgs), then we will not set it, and there will
7339          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
7340          * will cause tls_choose_sigalgs() to fail the connection.
7341          */
7342         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
7343                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
7344             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
7345                 goto out;
7346         }
7347
7348         ret = 1;
7349     }
7350
7351     /* Abort the handshake */
7352  out:
7353     OPENSSL_free(ecdsacert);
7354     OPENSSL_free(ecdsakey);
7355     OPENSSL_free(rootfile);
7356     BIO_free(in);
7357     EVP_PKEY_free(pkey);
7358     X509_free(x509);
7359     X509_free(rootx);
7360     sk_X509_pop_free(chain, X509_free);
7361     return ret;
7362 }
7363
7364 /*
7365  * Test the certificate callback.
7366  * Test 0: Callback fails
7367  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
7368  * Test 2: Success - SSL_set_SSL_CTX() in the callback
7369  * Test 3: Success - Call SSL_check_chain from the callback
7370  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
7371  *                   chain
7372  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
7373  */
7374 static int test_cert_cb_int(int prot, int tst)
7375 {
7376     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
7377     SSL *clientssl = NULL, *serverssl = NULL;
7378     int testresult = 0, ret;
7379
7380 #ifdef OPENSSL_NO_EC
7381     /* We use an EC cert in these tests, so we skip in a no-ec build */
7382     if (tst >= 3)
7383         return 1;
7384 #endif
7385
7386     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7387                                        TLS_client_method(),
7388                                        TLS1_VERSION,
7389                                        prot,
7390                                        &sctx, &cctx, NULL, NULL)))
7391         goto end;
7392
7393     if (tst == 0)
7394         cert_cb_cnt = -1;
7395     else if (tst >= 3)
7396         cert_cb_cnt = 3;
7397     else
7398         cert_cb_cnt = 0;
7399
7400     if (tst == 2)
7401         snictx = SSL_CTX_new(TLS_server_method());
7402     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
7403
7404     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7405                                       NULL, NULL)))
7406         goto end;
7407
7408     if (tst == 4) {
7409         /*
7410          * We cause SSL_check_chain() to fail by specifying sig_algs that
7411          * the chain doesn't meet (the root uses an RSA cert)
7412          */
7413         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
7414                                              "ecdsa_secp256r1_sha256")))
7415             goto end;
7416     } else if (tst == 5) {
7417         /*
7418          * We cause SSL_check_chain() to fail by specifying sig_algs that
7419          * the ee cert doesn't meet (the ee uses an ECDSA cert)
7420          */
7421         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
7422                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
7423             goto end;
7424     }
7425
7426     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
7427     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
7428             || (tst > 0
7429                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
7430         goto end;
7431     }
7432
7433     testresult = 1;
7434
7435  end:
7436     SSL_free(serverssl);
7437     SSL_free(clientssl);
7438     SSL_CTX_free(sctx);
7439     SSL_CTX_free(cctx);
7440     SSL_CTX_free(snictx);
7441
7442     return testresult;
7443 }
7444 #endif
7445
7446 static int test_cert_cb(int tst)
7447 {
7448     int testresult = 1;
7449
7450 #ifndef OPENSSL_NO_TLS1_2
7451     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
7452 #endif
7453 #ifndef OSSL_NO_USABLE_TLS1_3
7454     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
7455 #endif
7456
7457     return testresult;
7458 }
7459
7460 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
7461 {
7462     X509 *xcert;
7463     EVP_PKEY *privpkey;
7464     BIO *in = NULL;
7465     BIO *priv_in = NULL;
7466
7467     /* Check that SSL_get0_peer_certificate() returns something sensible */
7468     if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
7469         return 0;
7470
7471     in = BIO_new_file(cert, "r");
7472     if (!TEST_ptr(in))
7473         return 0;
7474
7475     if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL))
7476             || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
7477             || !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
7478             || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
7479                                                                NULL, NULL,
7480                                                                libctx, NULL)))
7481         goto err;
7482
7483     *x509 = xcert;
7484     *pkey = privpkey;
7485
7486     BIO_free(in);
7487     BIO_free(priv_in);
7488     return 1;
7489 err:
7490     X509_free(xcert);
7491     BIO_free(in);
7492     BIO_free(priv_in);
7493     return 0;
7494 }
7495
7496 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
7497 {
7498     return 1;
7499 }
7500
7501 static int test_client_cert_cb(int tst)
7502 {
7503     SSL_CTX *cctx = NULL, *sctx = NULL;
7504     SSL *clientssl = NULL, *serverssl = NULL;
7505     int testresult = 0;
7506
7507 #ifdef OPENSSL_NO_TLS1_2
7508     if (tst == 0)
7509         return 1;
7510 #endif
7511 #ifdef OSSL_NO_USABLE_TLS1_3
7512     if (tst == 1)
7513         return 1;
7514 #endif
7515
7516     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7517                                        TLS_client_method(),
7518                                        TLS1_VERSION,
7519                                        tst == 0 ? TLS1_2_VERSION
7520                                                 : TLS1_3_VERSION,
7521                                        &sctx, &cctx, cert, privkey)))
7522         goto end;
7523
7524     /*
7525      * Test that setting a client_cert_cb results in a client certificate being
7526      * sent.
7527      */
7528     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
7529     SSL_CTX_set_verify(sctx,
7530                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
7531                        verify_cb);
7532
7533     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7534                                       NULL, NULL))
7535             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7536                                                 SSL_ERROR_NONE)))
7537         goto end;
7538
7539     testresult = 1;
7540
7541  end:
7542     SSL_free(serverssl);
7543     SSL_free(clientssl);
7544     SSL_CTX_free(sctx);
7545     SSL_CTX_free(cctx);
7546
7547     return testresult;
7548 }
7549
7550 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
7551 /*
7552  * Test setting certificate authorities on both client and server.
7553  *
7554  * Test 0: SSL_CTX_set0_CA_list() only
7555  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
7556  * Test 2: Only SSL_CTX_set_client_CA_list()
7557  */
7558 static int test_ca_names_int(int prot, int tst)
7559 {
7560     SSL_CTX *cctx = NULL, *sctx = NULL;
7561     SSL *clientssl = NULL, *serverssl = NULL;
7562     int testresult = 0;
7563     size_t i;
7564     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
7565     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
7566     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
7567     const STACK_OF(X509_NAME) *sktmp = NULL;
7568
7569     for (i = 0; i < OSSL_NELEM(name); i++) {
7570         name[i] = X509_NAME_new();
7571         if (!TEST_ptr(name[i])
7572                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
7573                                                          MBSTRING_ASC,
7574                                                          (unsigned char *)
7575                                                          strnames[i],
7576                                                          -1, -1, 0)))
7577             goto end;
7578     }
7579
7580     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7581                                        TLS_client_method(),
7582                                        TLS1_VERSION,
7583                                        prot,
7584                                        &sctx, &cctx, cert, privkey)))
7585         goto end;
7586
7587     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
7588
7589     if (tst == 0 || tst == 1) {
7590         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
7591                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
7592                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
7593                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
7594                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
7595                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
7596             goto end;
7597
7598         SSL_CTX_set0_CA_list(sctx, sk1);
7599         SSL_CTX_set0_CA_list(cctx, sk2);
7600         sk1 = sk2 = NULL;
7601     }
7602     if (tst == 1 || tst == 2) {
7603         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
7604                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
7605                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
7606                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
7607                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
7608                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
7609             goto end;
7610
7611         SSL_CTX_set_client_CA_list(sctx, sk1);
7612         SSL_CTX_set_client_CA_list(cctx, sk2);
7613         sk1 = sk2 = NULL;
7614     }
7615
7616     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7617                                       NULL, NULL))
7618             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7619                                                 SSL_ERROR_NONE)))
7620         goto end;
7621
7622     /*
7623      * We only expect certificate authorities to have been sent to the server
7624      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
7625      */
7626     sktmp = SSL_get0_peer_CA_list(serverssl);
7627     if (prot == TLS1_3_VERSION
7628             && (tst == 0 || tst == 1)) {
7629         if (!TEST_ptr(sktmp)
7630                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
7631                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
7632                                               name[0]), 0)
7633                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
7634                                               name[1]), 0))
7635             goto end;
7636     } else if (!TEST_ptr_null(sktmp)) {
7637         goto end;
7638     }
7639
7640     /*
7641      * In all tests we expect certificate authorities to have been sent to the
7642      * client. However, SSL_set_client_CA_list() should override
7643      * SSL_set0_CA_list()
7644      */
7645     sktmp = SSL_get0_peer_CA_list(clientssl);
7646     if (!TEST_ptr(sktmp)
7647             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
7648             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
7649                                           name[tst == 0 ? 0 : 2]), 0)
7650             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
7651                                           name[tst == 0 ? 1 : 3]), 0))
7652         goto end;
7653
7654     testresult = 1;
7655
7656  end:
7657     SSL_free(serverssl);
7658     SSL_free(clientssl);
7659     SSL_CTX_free(sctx);
7660     SSL_CTX_free(cctx);
7661     for (i = 0; i < OSSL_NELEM(name); i++)
7662         X509_NAME_free(name[i]);
7663     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
7664     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
7665
7666     return testresult;
7667 }
7668 #endif
7669
7670 static int test_ca_names(int tst)
7671 {
7672     int testresult = 1;
7673
7674 #ifndef OPENSSL_NO_TLS1_2
7675     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
7676 #endif
7677 #ifndef OSSL_NO_USABLE_TLS1_3
7678     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
7679 #endif
7680
7681     return testresult;
7682 }
7683
7684 #ifndef OPENSSL_NO_TLS1_2
7685 static const char *multiblock_cipherlist_data[]=
7686 {
7687     "AES128-SHA",
7688     "AES128-SHA256",
7689     "AES256-SHA",
7690     "AES256-SHA256",
7691 };
7692
7693 /* Reduce the fragment size - so the multiblock test buffer can be small */
7694 # define MULTIBLOCK_FRAGSIZE 512
7695
7696 static int test_multiblock_write(int test_index)
7697 {
7698     static const char *fetchable_ciphers[]=
7699     {
7700         "AES-128-CBC-HMAC-SHA1",
7701         "AES-128-CBC-HMAC-SHA256",
7702         "AES-256-CBC-HMAC-SHA1",
7703         "AES-256-CBC-HMAC-SHA256"
7704     };
7705     const char *cipherlist = multiblock_cipherlist_data[test_index];
7706     const SSL_METHOD *smeth = TLS_server_method();
7707     const SSL_METHOD *cmeth = TLS_client_method();
7708     int min_version = TLS1_VERSION;
7709     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
7710     SSL_CTX *cctx = NULL, *sctx = NULL;
7711     SSL *clientssl = NULL, *serverssl = NULL;
7712     int testresult = 0;
7713
7714     /*
7715      * Choose a buffer large enough to perform a multi-block operation
7716      * i.e: write_len >= 4 * frag_size
7717      * 9 * is chosen so that multiple multiblocks are used + some leftover.
7718      */
7719     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
7720     unsigned char buf[sizeof(msg)], *p = buf;
7721     size_t readbytes, written, len;
7722     EVP_CIPHER *ciph = NULL;
7723
7724     /*
7725      * Check if the cipher exists before attempting to use it since it only has
7726      * a hardware specific implementation.
7727      */
7728     ciph = EVP_CIPHER_fetch(NULL, fetchable_ciphers[test_index], "");
7729     if (ciph == NULL) {
7730         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
7731         return 1;
7732     }
7733     EVP_CIPHER_free(ciph);
7734
7735     /* Set up a buffer with some data that will be sent to the client */
7736     RAND_bytes(msg, sizeof(msg));
7737
7738     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
7739                                        max_version, &sctx, &cctx, cert,
7740                                        privkey)))
7741         goto end;
7742
7743     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
7744         goto end;
7745
7746     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7747                                       NULL, NULL)))
7748             goto end;
7749
7750     /* settings to force it to use AES-CBC-HMAC_SHA */
7751     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
7752     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
7753        goto end;
7754
7755     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
7756         goto end;
7757
7758     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
7759         || !TEST_size_t_eq(written, sizeof(msg)))
7760         goto end;
7761
7762     len = written;
7763     while (len > 0) {
7764         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
7765             goto end;
7766         p += readbytes;
7767         len -= readbytes;
7768     }
7769     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
7770         goto end;
7771
7772     testresult = 1;
7773 end:
7774     SSL_free(serverssl);
7775     SSL_free(clientssl);
7776     SSL_CTX_free(sctx);
7777     SSL_CTX_free(cctx);
7778
7779     return testresult;
7780 }
7781 #endif /* OPENSSL_NO_TLS1_2 */
7782
7783 /*
7784  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
7785  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
7786  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
7787  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
7788  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
7789  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
7790  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
7791  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
7792  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
7793  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
7794  */
7795 static int test_servername(int tst)
7796 {
7797     SSL_CTX *cctx = NULL, *sctx = NULL;
7798     SSL *clientssl = NULL, *serverssl = NULL;
7799     int testresult = 0;
7800     SSL_SESSION *sess = NULL;
7801     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
7802
7803 #ifdef OPENSSL_NO_TLS1_2
7804     if (tst <= 4)
7805         return 1;
7806 #endif
7807 #ifdef OSSL_NO_USABLE_TLS1_3
7808     if (tst >= 5)
7809         return 1;
7810 #endif
7811
7812     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7813                                        TLS_client_method(),
7814                                        TLS1_VERSION,
7815                                        (tst <= 4) ? TLS1_2_VERSION
7816                                                   : TLS1_3_VERSION,
7817                                        &sctx, &cctx, cert, privkey))
7818             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7819                                              NULL, NULL)))
7820         goto end;
7821
7822     if (tst != 1 && tst != 6) {
7823         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
7824                                                               hostname_cb)))
7825             goto end;
7826     }
7827
7828     if (tst != 3 && tst != 8) {
7829         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
7830             goto end;
7831         sexpectedhost = cexpectedhost = "goodhost";
7832     }
7833
7834     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
7835         goto end;
7836
7837     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
7838                      cexpectedhost)
7839             || !TEST_str_eq(SSL_get_servername(serverssl,
7840                                                TLSEXT_NAMETYPE_host_name),
7841                             sexpectedhost))
7842         goto end;
7843
7844     /* Now repeat with a resumption handshake */
7845
7846     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
7847             || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
7848             || !TEST_true(SSL_SESSION_is_resumable(sess))
7849             || !TEST_int_eq(SSL_shutdown(serverssl), 0))
7850         goto end;
7851
7852     SSL_free(clientssl);
7853     SSL_free(serverssl);
7854     clientssl = serverssl = NULL;
7855
7856     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
7857                                       NULL)))
7858         goto end;
7859
7860     if (!TEST_true(SSL_set_session(clientssl, sess)))
7861         goto end;
7862
7863     sexpectedhost = cexpectedhost = "goodhost";
7864     if (tst == 2 || tst == 7) {
7865         /* Set an inconsistent hostname */
7866         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
7867             goto end;
7868         /*
7869          * In TLSv1.2 we expect the hostname from the original handshake, in
7870          * TLSv1.3 we expect the hostname from this handshake
7871          */
7872         if (tst == 7)
7873             sexpectedhost = cexpectedhost = "altgoodhost";
7874
7875         if (!TEST_str_eq(SSL_get_servername(clientssl,
7876                                             TLSEXT_NAMETYPE_host_name),
7877                          "altgoodhost"))
7878             goto end;
7879     } else if (tst == 4 || tst == 9) {
7880         /*
7881          * A TLSv1.3 session does not associate a session with a servername,
7882          * but a TLSv1.2 session does.
7883          */
7884         if (tst == 9)
7885             sexpectedhost = cexpectedhost = NULL;
7886
7887         if (!TEST_str_eq(SSL_get_servername(clientssl,
7888                                             TLSEXT_NAMETYPE_host_name),
7889                          cexpectedhost))
7890             goto end;
7891     } else {
7892         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
7893             goto end;
7894         /*
7895          * In a TLSv1.2 resumption where the hostname was not acknowledged
7896          * we expect the hostname on the server to be empty. On the client we
7897          * return what was requested in this case.
7898          *
7899          * Similarly if the client didn't set a hostname on an original TLSv1.2
7900          * session but is now, the server hostname will be empty, but the client
7901          * is as we set it.
7902          */
7903         if (tst == 1 || tst == 3)
7904             sexpectedhost = NULL;
7905
7906         if (!TEST_str_eq(SSL_get_servername(clientssl,
7907                                             TLSEXT_NAMETYPE_host_name),
7908                          "goodhost"))
7909             goto end;
7910     }
7911
7912     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
7913         goto end;
7914
7915     if (!TEST_true(SSL_session_reused(clientssl))
7916             || !TEST_true(SSL_session_reused(serverssl))
7917             || !TEST_str_eq(SSL_get_servername(clientssl,
7918                                                TLSEXT_NAMETYPE_host_name),
7919                             cexpectedhost)
7920             || !TEST_str_eq(SSL_get_servername(serverssl,
7921                                                TLSEXT_NAMETYPE_host_name),
7922                             sexpectedhost))
7923         goto end;
7924
7925     testresult = 1;
7926
7927  end:
7928     SSL_SESSION_free(sess);
7929     SSL_free(serverssl);
7930     SSL_free(clientssl);
7931     SSL_CTX_free(sctx);
7932     SSL_CTX_free(cctx);
7933
7934     return testresult;
7935 }
7936
7937 #if !defined(OPENSSL_NO_EC) \
7938     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
7939 /*
7940  * Test that if signature algorithms are not available, then we do not offer or
7941  * accept them.
7942  * Test 0: Two RSA sig algs available: both RSA sig algs shared
7943  * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared
7944  * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared
7945  * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared
7946  * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared
7947  * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared
7948  */
7949 static int test_sigalgs_available(int idx)
7950 {
7951     SSL_CTX *cctx = NULL, *sctx = NULL;
7952     SSL *clientssl = NULL, *serverssl = NULL;
7953     int testresult = 0;
7954     OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
7955     OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx;
7956     OSSL_PROVIDER *filterprov = NULL;
7957     int sig, hash;
7958
7959     if (!TEST_ptr(tmpctx))
7960         goto end;
7961
7962     if (idx != 0 && idx != 3) {
7963         if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter",
7964                                                  filter_provider_init)))
7965             goto end;
7966
7967         filterprov = OSSL_PROVIDER_load(tmpctx, "filter");
7968         if (!TEST_ptr(filterprov))
7969             goto end;
7970
7971         if (idx < 3) {
7972             /*
7973              * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered
7974              * or accepted for the peer that uses this libctx. Note that libssl
7975              * *requires* SHA2-256 to be available so we cannot disable that. We
7976              * also need SHA1 for our certificate.
7977              */
7978             if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST,
7979                                                       "SHA2-256:SHA1")))
7980                 goto end;
7981         } else {
7982             if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE,
7983                                                       "ECDSA"))
7984                     || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
7985                                                              "EC:X25519:X448")))
7986                 goto end;
7987         }
7988
7989         if (idx == 1 || idx == 4)
7990             clientctx = tmpctx;
7991         else
7992             serverctx = tmpctx;
7993     }
7994
7995     cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method());
7996     sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method());
7997     if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
7998         goto end;
7999
8000     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8001                                        TLS_client_method(),
8002                                        TLS1_VERSION,
8003                                        0,
8004                                        &sctx, &cctx, cert, privkey)))
8005         goto end;
8006
8007     /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */
8008     if (idx < 4) {
8009         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
8010                                                "ECDHE-RSA-AES128-GCM-SHA256")))
8011             goto end;
8012     } else {
8013         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
8014                                                "ECDHE-ECDSA-AES128-GCM-SHA256")))
8015             goto end;
8016     }
8017
8018     if (idx < 3) {
8019         if (!SSL_CTX_set1_sigalgs_list(cctx,
8020                                        "rsa_pss_rsae_sha384"
8021                                        ":rsa_pss_rsae_sha256")
8022                 || !SSL_CTX_set1_sigalgs_list(sctx,
8023                                               "rsa_pss_rsae_sha384"
8024                                               ":rsa_pss_rsae_sha256"))
8025             goto end;
8026     } else {
8027         if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")
8028                 || !SSL_CTX_set1_sigalgs_list(sctx,
8029                                               "rsa_pss_rsae_sha256:ECDSA+SHA256"))
8030             goto end;
8031     }
8032
8033     if (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2,
8034                                                   SSL_FILETYPE_PEM), 1)
8035             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
8036                                                         privkey2,
8037                                                         SSL_FILETYPE_PEM), 1)
8038             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
8039         goto end;
8040
8041     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8042                                              NULL, NULL)))
8043         goto end;
8044
8045     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8046         goto end;
8047
8048     /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */
8049     if (!TEST_int_eq(SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash, NULL,
8050                                             NULL, NULL),
8051                      (idx == 0 || idx == 3) ? 2 : 1))
8052         goto end;
8053
8054     if (!TEST_int_eq(hash, idx == 0 ? NID_sha384 : NID_sha256))
8055         goto end;
8056
8057     if (!TEST_int_eq(sig, (idx == 4 || idx == 5) ? EVP_PKEY_EC
8058                                                  : NID_rsassaPss))
8059         goto end;
8060
8061     testresult = 1;
8062
8063  end:
8064     SSL_free(serverssl);
8065     SSL_free(clientssl);
8066     SSL_CTX_free(sctx);
8067     SSL_CTX_free(cctx);
8068     OSSL_PROVIDER_unload(filterprov);
8069     OSSL_LIB_CTX_free(tmpctx);
8070
8071     return testresult;
8072 }
8073 #endif /*
8074         * !defined(OPENSSL_NO_EC) \
8075         * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
8076         */
8077
8078 #ifndef OPENSSL_NO_TLS1_3
8079 /* This test can run in TLSv1.3 even if ec and dh are disabled */
8080 static int test_pluggable_group(int idx)
8081 {
8082     SSL_CTX *cctx = NULL, *sctx = NULL;
8083     SSL *clientssl = NULL, *serverssl = NULL;
8084     int testresult = 0;
8085     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
8086     /* Check that we are not impacted by a provider without any groups */
8087     OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy");
8088     const char *group_name = idx == 0 ? "xorgroup" : "xorkemgroup";
8089
8090     if (!TEST_ptr(tlsprov))
8091         goto end;
8092
8093     if (legacyprov == NULL) {
8094         /*
8095          * In this case we assume we've been built with "no-legacy" and skip
8096          * this test (there is no OPENSSL_NO_LEGACY)
8097          */
8098         testresult = 1;
8099         goto end;
8100     }
8101
8102     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8103                                        TLS_client_method(),
8104                                        TLS1_3_VERSION,
8105                                        TLS1_3_VERSION,
8106                                        &sctx, &cctx, cert, privkey))
8107             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8108                                              NULL, NULL)))
8109         goto end;
8110
8111     if (!TEST_true(SSL_set1_groups_list(serverssl, group_name))
8112             || !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
8113         goto end;
8114
8115     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8116         goto end;
8117
8118     if (!TEST_str_eq(group_name,
8119                      SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
8120         goto end;
8121
8122     testresult = 1;
8123
8124  end:
8125     SSL_free(serverssl);
8126     SSL_free(clientssl);
8127     SSL_CTX_free(sctx);
8128     SSL_CTX_free(cctx);
8129     OSSL_PROVIDER_unload(tlsprov);
8130     OSSL_PROVIDER_unload(legacyprov);
8131
8132     return testresult;
8133 }
8134 #endif
8135
8136 #ifndef OPENSSL_NO_TLS1_2
8137 static int test_ssl_dup(void)
8138 {
8139     SSL_CTX *cctx = NULL, *sctx = NULL;
8140     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
8141     int testresult = 0;
8142     BIO *rbio = NULL, *wbio = NULL;
8143
8144     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8145                                        TLS_client_method(),
8146                                        0,
8147                                        0,
8148                                        &sctx, &cctx, cert, privkey)))
8149         goto end;
8150
8151     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8152                                              NULL, NULL)))
8153         goto end;
8154
8155     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
8156             || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
8157         goto end;
8158
8159     client2ssl = SSL_dup(clientssl);
8160     rbio = SSL_get_rbio(clientssl);
8161     if (!TEST_ptr(rbio)
8162             || !TEST_true(BIO_up_ref(rbio)))
8163         goto end;
8164     SSL_set0_rbio(client2ssl, rbio);
8165     rbio = NULL;
8166
8167     wbio = SSL_get_wbio(clientssl);
8168     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
8169         goto end;
8170     SSL_set0_wbio(client2ssl, wbio);
8171     rbio = NULL;
8172
8173     if (!TEST_ptr(client2ssl)
8174                /* Handshake not started so pointers should be different */
8175             || !TEST_ptr_ne(clientssl, client2ssl))
8176         goto end;
8177
8178     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
8179             || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
8180         goto end;
8181
8182     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
8183         goto end;
8184
8185     SSL_free(clientssl);
8186     clientssl = SSL_dup(client2ssl);
8187     if (!TEST_ptr(clientssl)
8188                /* Handshake has finished so pointers should be the same */
8189             || !TEST_ptr_eq(clientssl, client2ssl))
8190         goto end;
8191
8192     testresult = 1;
8193
8194  end:
8195     SSL_free(serverssl);
8196     SSL_free(clientssl);
8197     SSL_free(client2ssl);
8198     SSL_CTX_free(sctx);
8199     SSL_CTX_free(cctx);
8200
8201     return testresult;
8202 }
8203
8204 # ifndef OPENSSL_NO_DH
8205
8206 static EVP_PKEY *tmp_dh_params = NULL;
8207
8208 /* Helper function for the test_set_tmp_dh() tests */
8209 static EVP_PKEY *get_tmp_dh_params(void)
8210 {
8211     if (tmp_dh_params == NULL) {
8212         BIGNUM *p = NULL;
8213         OSSL_PARAM_BLD *tmpl = NULL;
8214         EVP_PKEY_CTX *pctx = NULL;
8215         OSSL_PARAM *params = NULL;
8216         EVP_PKEY *dhpkey = NULL;
8217
8218         p = BN_get_rfc3526_prime_2048(NULL);
8219         if (!TEST_ptr(p))
8220             goto end;
8221
8222         pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL);
8223         if (!TEST_ptr(pctx)
8224                 || !TEST_true(EVP_PKEY_fromdata_init(pctx)))
8225             goto end;
8226
8227         tmpl = OSSL_PARAM_BLD_new();
8228         if (!TEST_ptr(tmpl)
8229                 || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl,
8230                                                         OSSL_PKEY_PARAM_FFC_P,
8231                                                         p))
8232                 || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl,
8233                                                         OSSL_PKEY_PARAM_FFC_G,
8234                                                         2)))
8235             goto end;
8236
8237         params = OSSL_PARAM_BLD_to_param(tmpl);
8238         if (!TEST_ptr(params)
8239                 || !TEST_true(EVP_PKEY_fromdata(pctx, &dhpkey,
8240                                                 EVP_PKEY_KEY_PARAMETERS, params)))
8241             goto end;
8242
8243         tmp_dh_params = dhpkey;
8244     end:
8245         BN_free(p);
8246         EVP_PKEY_CTX_free(pctx);
8247         OSSL_PARAM_BLD_free(tmpl);
8248         OSSL_PARAM_BLD_free_params(params);
8249     }
8250
8251     if (!EVP_PKEY_up_ref(tmp_dh_params))
8252         return NULL;
8253
8254     return tmp_dh_params;
8255 }
8256
8257 #  ifndef OPENSSL_NO_DEPRECATED_3_0
8258 /* Callback used by test_set_tmp_dh() */
8259 static DH *tmp_dh_callback(SSL *s, int is_export, int keylen)
8260 {
8261     EVP_PKEY *dhpkey = get_tmp_dh_params();
8262     DH *ret = NULL;
8263
8264     if (!TEST_ptr(dhpkey))
8265         return NULL;
8266
8267     ret = EVP_PKEY_get0_DH(dhpkey);
8268
8269     EVP_PKEY_free(dhpkey);
8270
8271     return ret;
8272 }
8273 #  endif
8274
8275 /*
8276  * Test the various methods for setting temporary DH parameters
8277  *
8278  * Test  0: Default (no auto) setting
8279  * Test  1: Explicit SSL_CTX auto off
8280  * Test  2: Explicit SSL auto off
8281  * Test  3: Explicit SSL_CTX auto on
8282  * Test  4: Explicit SSL auto on
8283  * Test  5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY
8284  * Test  6: Explicit SSL auto off, custom DH params via EVP_PKEY
8285  *
8286  * The following are testing deprecated APIs, so we only run them if available
8287  * Test  7: Explicit SSL_CTX auto off, custom DH params via DH
8288  * Test  8: Explicit SSL auto off, custom DH params via DH
8289  * Test  9: Explicit SSL_CTX auto off, custom DH params via callback
8290  * Test 10: Explicit SSL auto off, custom DH params via callback
8291  */
8292 static int test_set_tmp_dh(int idx)
8293 {
8294     SSL_CTX *cctx = NULL, *sctx = NULL;
8295     SSL *clientssl = NULL, *serverssl = NULL;
8296     int testresult = 0;
8297     int dhauto = (idx == 3 || idx == 4) ? 1 : 0;
8298     int expected = (idx <= 2) ? 0 : 1;
8299     EVP_PKEY *dhpkey = NULL;
8300 #  ifndef OPENSSL_NO_DEPRECATED_3_0
8301     DH *dh = NULL;
8302 #  else
8303
8304     if (idx >= 7)
8305         return 1;
8306 #  endif
8307
8308     if (idx >= 5 && idx <= 8) {
8309         dhpkey = get_tmp_dh_params();
8310         if (!TEST_ptr(dhpkey))
8311             goto end;
8312     }
8313 #  ifndef OPENSSL_NO_DEPRECATED_3_0
8314     if (idx == 7 || idx == 8) {
8315         dh = EVP_PKEY_get0_DH(dhpkey);
8316         if (!TEST_ptr(dh))
8317             goto end;
8318     }
8319 #  endif
8320
8321     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8322                                        TLS_client_method(),
8323                                        0,
8324                                        0,
8325                                        &sctx, &cctx, cert, privkey)))
8326         goto end;
8327
8328     if ((idx & 1) == 1) {
8329         if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto)))
8330             goto end;
8331     }
8332
8333     if (idx == 5) {
8334         if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey)))
8335             goto end;
8336         dhpkey = NULL;
8337     }
8338 #  ifndef OPENSSL_NO_DEPRECATED_3_0
8339     else if (idx == 7) {
8340         if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh)))
8341             goto end;
8342     } else if (idx == 9) {
8343         SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback);
8344     }
8345 #  endif
8346
8347     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8348                                       NULL, NULL)))
8349         goto end;
8350
8351     if ((idx & 1) == 0 && idx != 0) {
8352         if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto)))
8353             goto end;
8354     }
8355     if (idx == 6) {
8356         if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey)))
8357             goto end;
8358         dhpkey = NULL;
8359     }
8360 #  ifndef OPENSSL_NO_DEPRECATED_3_0
8361     else if (idx == 8) {
8362         if (!TEST_true(SSL_set_tmp_dh(serverssl, dh)))
8363             goto end;
8364     } else if (idx == 10) {
8365         SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback);
8366     }
8367 #  endif
8368
8369     if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
8370             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
8371             || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA")))
8372         goto end;
8373
8374     /*
8375      * If autoon then we should succeed. Otherwise we expect failure because
8376      * there are no parameters
8377      */
8378     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
8379                                            SSL_ERROR_NONE), expected))
8380         goto end;
8381
8382     testresult = 1;
8383
8384  end:
8385     SSL_free(serverssl);
8386     SSL_free(clientssl);
8387     SSL_CTX_free(sctx);
8388     SSL_CTX_free(cctx);
8389     EVP_PKEY_free(dhpkey);
8390
8391     return testresult;
8392 }
8393
8394 /*
8395  * Test the auto DH keys are appropriately sized
8396  */
8397 static int test_dh_auto(int idx)
8398 {
8399     SSL_CTX *cctx = NULL, *sctx = NULL;
8400     SSL *clientssl = NULL, *serverssl = NULL;
8401     int testresult = 0;
8402     EVP_PKEY *tmpkey = NULL;
8403     char *thiscert = NULL, *thiskey = NULL;
8404     size_t expdhsize = 0;
8405     const char *ciphersuite = "DHE-RSA-AES128-SHA";
8406
8407     switch (idx) {
8408     case 0:
8409         /* The FIPS provider doesn't support this DH size - so we ignore it */
8410         if (is_fips)
8411             return 1;
8412         thiscert = cert1024;
8413         thiskey = privkey1024;
8414         expdhsize = 1024;
8415         break;
8416     case 1:
8417         /* 2048 bit prime */
8418         thiscert = cert;
8419         thiskey = privkey;
8420         expdhsize = 2048;
8421         break;
8422     case 2:
8423         thiscert = cert3072;
8424         thiskey = privkey3072;
8425         expdhsize = 3072;
8426         break;
8427     case 3:
8428         thiscert = cert4096;
8429         thiskey = privkey4096;
8430         expdhsize = 4096;
8431         break;
8432     case 4:
8433         thiscert = cert8192;
8434         thiskey = privkey8192;
8435         expdhsize = 8192;
8436         break;
8437     /* No certificate cases */
8438     case 5:
8439         /* The FIPS provider doesn't support this DH size - so we ignore it */
8440         if (is_fips)
8441             return 1;
8442         ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0";
8443         expdhsize = 1024;
8444         break;
8445     case 6:
8446         ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0";
8447         expdhsize = 3072;
8448         break;
8449     default:
8450         TEST_error("Invalid text index");
8451         goto end;
8452     }
8453
8454     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8455                                        TLS_client_method(),
8456                                        0,
8457                                        0,
8458                                        &sctx, &cctx, thiscert, thiskey)))
8459         goto end;
8460
8461     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8462                                       NULL, NULL)))
8463         goto end;
8464
8465     if (!TEST_true(SSL_set_dh_auto(serverssl, 1))
8466             || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
8467             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
8468             || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite))
8469             || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite)))
8470         goto end;
8471
8472     /*
8473      * Send the server's first flight. At this point the server has created the
8474      * temporary DH key but hasn't finished using it yet. Once used it is
8475      * removed, so we cannot test it.
8476      */
8477     if (!TEST_int_le(SSL_connect(clientssl), 0)
8478             || !TEST_int_le(SSL_accept(serverssl), 0))
8479         goto end;
8480
8481     if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0))
8482         goto end;
8483     if (!TEST_size_t_eq(EVP_PKEY_bits(tmpkey), expdhsize))
8484         goto end;
8485
8486     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8487         goto end;
8488
8489     testresult = 1;
8490
8491  end:
8492     SSL_free(serverssl);
8493     SSL_free(clientssl);
8494     SSL_CTX_free(sctx);
8495     SSL_CTX_free(cctx);
8496     EVP_PKEY_free(tmpkey);
8497
8498     return testresult;
8499
8500 }
8501 # endif /* OPENSSL_NO_DH */
8502 #endif /* OPENSSL_NO_TLS1_2 */
8503
8504 #ifndef OSSL_NO_USABLE_TLS1_3
8505 /*
8506  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
8507  * that it works even without a certificate configured for the original
8508  * SSL_CTX
8509  */
8510 static int test_sni_tls13(void)
8511 {
8512     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
8513     SSL *clientssl = NULL, *serverssl = NULL;
8514     int testresult = 0;
8515
8516     /* Reset callback counter */
8517     snicb = 0;
8518
8519     /* Create an initial SSL_CTX with no certificate configured */
8520     sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
8521     if (!TEST_ptr(sctx))
8522         goto end;
8523     /* Require TLSv1.3 as a minimum */
8524     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8525                                        TLS_client_method(), TLS1_3_VERSION, 0,
8526                                        &sctx2, &cctx, cert, privkey)))
8527         goto end;
8528
8529     /* Set up SNI */
8530     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
8531             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
8532         goto end;
8533
8534     /*
8535      * Connection should still succeed because the final SSL_CTX has the right
8536      * certificates configured.
8537      */
8538     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
8539                                       &clientssl, NULL, NULL))
8540             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8541                                                 SSL_ERROR_NONE)))
8542         goto end;
8543
8544     /* We should have had the SNI callback called exactly once */
8545     if (!TEST_int_eq(snicb, 1))
8546         goto end;
8547
8548     testresult = 1;
8549
8550 end:
8551     SSL_free(serverssl);
8552     SSL_free(clientssl);
8553     SSL_CTX_free(sctx2);
8554     SSL_CTX_free(sctx);
8555     SSL_CTX_free(cctx);
8556     return testresult;
8557 }
8558 #endif
8559
8560 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config\n")
8561
8562 int setup_tests(void)
8563 {
8564     char *modulename;
8565     char *configfile;
8566
8567     libctx = OSSL_LIB_CTX_new();
8568     if (!TEST_ptr(libctx))
8569         return 0;
8570
8571     defctxnull = OSSL_PROVIDER_load(NULL, "null");
8572
8573     /*
8574      * Verify that the default and fips providers in the default libctx are not
8575      * available
8576      */
8577     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
8578             || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
8579         return 0;
8580
8581     if (!test_skip_common_options()) {
8582         TEST_error("Error parsing test options\n");
8583         return 0;
8584     }
8585
8586     if (!TEST_ptr(certsdir = test_get_argument(0))
8587             || !TEST_ptr(srpvfile = test_get_argument(1))
8588             || !TEST_ptr(tmpfilename = test_get_argument(2))
8589             || !TEST_ptr(modulename = test_get_argument(3))
8590             || !TEST_ptr(configfile = test_get_argument(4)))
8591         return 0;
8592
8593     if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
8594         return 0;
8595
8596     /* Check we have the expected provider available */
8597     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
8598         return 0;
8599
8600     /* Check the default provider is not available */
8601     if (strcmp(modulename, "default") != 0
8602             && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
8603         return 0;
8604
8605     if (strcmp(modulename, "fips") == 0)
8606         is_fips = 1;
8607
8608     /*
8609      * We add, but don't load the test "tls-provider". We'll load it when we
8610      * need it.
8611      */
8612     if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider",
8613                                              tls_provider_init)))
8614         return 0;
8615
8616
8617     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
8618 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
8619         TEST_error("not supported in this build");
8620         return 0;
8621 #else
8622         int i, mcount, rcount, fcount;
8623
8624         for (i = 0; i < 4; i++)
8625             test_export_key_mat(i);
8626         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
8627         test_printf_stdout("malloc %d realloc %d free %d\n",
8628                 mcount, rcount, fcount);
8629         return 1;
8630 #endif
8631     }
8632
8633     cert = test_mk_file_path(certsdir, "servercert.pem");
8634     if (cert == NULL)
8635         goto err;
8636
8637     privkey = test_mk_file_path(certsdir, "serverkey.pem");
8638     if (privkey == NULL)
8639         goto err;
8640
8641     cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
8642     if (cert2 == NULL)
8643         goto err;
8644
8645     privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
8646     if (privkey2 == NULL)
8647         goto err;
8648
8649     cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem");
8650     if (cert1024 == NULL)
8651         goto err;
8652
8653     privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem");
8654     if (privkey1024 == NULL)
8655         goto err;
8656
8657     cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem");
8658     if (cert3072 == NULL)
8659         goto err;
8660
8661     privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem");
8662     if (privkey3072 == NULL)
8663         goto err;
8664
8665     cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem");
8666     if (cert4096 == NULL)
8667         goto err;
8668
8669     privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem");
8670     if (privkey4096 == NULL)
8671         goto err;
8672
8673     cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem");
8674     if (cert8192 == NULL)
8675         goto err;
8676
8677     privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem");
8678     if (privkey8192 == NULL)
8679         goto err;
8680
8681 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
8682 # if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
8683     ADD_ALL_TESTS(test_ktls, 32);
8684     ADD_ALL_TESTS(test_ktls_sendfile_anytls, 6);
8685 # endif
8686 #endif
8687     ADD_TEST(test_large_message_tls);
8688     ADD_TEST(test_large_message_tls_read_ahead);
8689 #ifndef OPENSSL_NO_DTLS
8690     ADD_TEST(test_large_message_dtls);
8691 #endif
8692     ADD_TEST(test_cleanse_plaintext);
8693 #ifndef OPENSSL_NO_OCSP
8694     ADD_TEST(test_tlsext_status_type);
8695 #endif
8696     ADD_TEST(test_session_with_only_int_cache);
8697     ADD_TEST(test_session_with_only_ext_cache);
8698     ADD_TEST(test_session_with_both_cache);
8699     ADD_TEST(test_session_wo_ca_names);
8700 #ifndef OSSL_NO_USABLE_TLS1_3
8701     ADD_ALL_TESTS(test_stateful_tickets, 3);
8702     ADD_ALL_TESTS(test_stateless_tickets, 3);
8703     ADD_TEST(test_psk_tickets);
8704     ADD_ALL_TESTS(test_extra_tickets, 6);
8705 #endif
8706     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
8707     ADD_TEST(test_ssl_bio_pop_next_bio);
8708     ADD_TEST(test_ssl_bio_pop_ssl_bio);
8709     ADD_TEST(test_ssl_bio_change_rbio);
8710     ADD_TEST(test_ssl_bio_change_wbio);
8711 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
8712     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
8713     ADD_TEST(test_keylog);
8714 #endif
8715 #ifndef OSSL_NO_USABLE_TLS1_3
8716     ADD_TEST(test_keylog_no_master_key);
8717 #endif
8718     ADD_TEST(test_client_cert_verify_cb);
8719 #ifndef OPENSSL_NO_TLS1_2
8720     ADD_TEST(test_client_hello_cb);
8721     ADD_TEST(test_no_ems);
8722     ADD_TEST(test_ccs_change_cipher);
8723 #endif
8724 #ifndef OSSL_NO_USABLE_TLS1_3
8725     ADD_ALL_TESTS(test_early_data_read_write, 3);
8726     /*
8727      * We don't do replay tests for external PSK. Replay protection isn't used
8728      * in that scenario.
8729      */
8730     ADD_ALL_TESTS(test_early_data_replay, 2);
8731     ADD_ALL_TESTS(test_early_data_skip, 3);
8732     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
8733     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, 3);
8734     ADD_ALL_TESTS(test_early_data_skip_abort, 3);
8735     ADD_ALL_TESTS(test_early_data_not_sent, 3);
8736     ADD_ALL_TESTS(test_early_data_psk, 8);
8737     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 5);
8738     ADD_ALL_TESTS(test_early_data_not_expected, 3);
8739 # ifndef OPENSSL_NO_TLS1_2
8740     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
8741 # endif
8742 #endif
8743 #ifndef OSSL_NO_USABLE_TLS1_3
8744     ADD_ALL_TESTS(test_set_ciphersuite, 10);
8745     ADD_TEST(test_ciphersuite_change);
8746     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
8747 # ifdef OPENSSL_NO_PSK
8748     ADD_ALL_TESTS(test_tls13_psk, 1);
8749 # else
8750     ADD_ALL_TESTS(test_tls13_psk, 4);
8751 # endif  /* OPENSSL_NO_PSK */
8752 # ifndef OPENSSL_NO_TLS1_2
8753     /* Test with both TLSv1.3 and 1.2 versions */
8754     ADD_ALL_TESTS(test_key_exchange, 14);
8755 # else
8756     /* Test with only TLSv1.3 versions */
8757     ADD_ALL_TESTS(test_key_exchange, 12);
8758 # endif
8759     ADD_ALL_TESTS(test_custom_exts, 5);
8760     ADD_TEST(test_stateless);
8761     ADD_TEST(test_pha_key_update);
8762 #else
8763     ADD_ALL_TESTS(test_custom_exts, 3);
8764 #endif
8765     ADD_ALL_TESTS(test_serverinfo, 8);
8766     ADD_ALL_TESTS(test_export_key_mat, 6);
8767 #ifndef OSSL_NO_USABLE_TLS1_3
8768     ADD_ALL_TESTS(test_export_key_mat_early, 3);
8769     ADD_TEST(test_key_update);
8770     ADD_ALL_TESTS(test_key_update_in_write, 2);
8771 #endif
8772     ADD_ALL_TESTS(test_ssl_clear, 2);
8773     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
8774 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
8775     ADD_ALL_TESTS(test_srp, 6);
8776 #endif
8777     ADD_ALL_TESTS(test_info_callback, 6);
8778     ADD_ALL_TESTS(test_ssl_pending, 2);
8779     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
8780     ADD_ALL_TESTS(test_ticket_callbacks, 16);
8781     ADD_ALL_TESTS(test_shutdown, 7);
8782     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
8783     ADD_ALL_TESTS(test_cert_cb, 6);
8784     ADD_ALL_TESTS(test_client_cert_cb, 2);
8785     ADD_ALL_TESTS(test_ca_names, 3);
8786 #ifndef OPENSSL_NO_TLS1_2
8787     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
8788 #endif
8789     ADD_ALL_TESTS(test_servername, 10);
8790 #if !defined(OPENSSL_NO_EC) \
8791     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
8792     ADD_ALL_TESTS(test_sigalgs_available, 6);
8793 #endif
8794 #ifndef OPENSSL_NO_TLS1_3
8795     ADD_ALL_TESTS(test_pluggable_group, 2);
8796 #endif
8797 #ifndef OPENSSL_NO_TLS1_2
8798     ADD_TEST(test_ssl_dup);
8799 # ifndef OPENSSL_NO_DH
8800     ADD_ALL_TESTS(test_set_tmp_dh, 11);
8801     ADD_ALL_TESTS(test_dh_auto, 7);
8802 # endif
8803 #endif
8804 #ifndef OSSL_NO_USABLE_TLS1_3
8805     ADD_TEST(test_sni_tls13);
8806 #endif
8807     return 1;
8808
8809  err:
8810     OPENSSL_free(cert);
8811     OPENSSL_free(privkey);
8812     OPENSSL_free(cert2);
8813     OPENSSL_free(privkey2);
8814     return 0;
8815 }
8816
8817 void cleanup_tests(void)
8818 {
8819 # if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH)
8820     EVP_PKEY_free(tmp_dh_params);
8821 #endif
8822     OPENSSL_free(cert);
8823     OPENSSL_free(privkey);
8824     OPENSSL_free(cert2);
8825     OPENSSL_free(privkey2);
8826     OPENSSL_free(cert1024);
8827     OPENSSL_free(privkey1024);
8828     OPENSSL_free(cert3072);
8829     OPENSSL_free(privkey3072);
8830     OPENSSL_free(cert4096);
8831     OPENSSL_free(privkey4096);
8832     OPENSSL_free(cert8192);
8833     OPENSSL_free(privkey8192);
8834     bio_s_mempacket_test_free();
8835     bio_s_always_retry_free();
8836     OSSL_PROVIDER_unload(defctxnull);
8837     OSSL_LIB_CTX_free(libctx);
8838 }