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