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