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