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