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