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