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