42417918c8ce970711c698ab47d652952425c2fa
[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     const unsigned char *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(sess2->owner != NULL)
2289                 || !TEST_true(tmp->owner == NULL)
2290                 || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
2291                 goto end;
2292             SSL_SESSION_free(sess2);
2293         }
2294         sess2 = tmp;
2295     }
2296
2297     new_called = remove_called = get_called = 0;
2298     get_sess_val = sess2;
2299     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2300                                       &clientssl2, NULL, NULL))
2301             || !TEST_true(SSL_set_session(clientssl2, sess1))
2302             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2303                                                 SSL_ERROR_NONE))
2304             || !TEST_true(SSL_session_reused(clientssl2)))
2305         goto end;
2306
2307     if (use_ext_cache) {
2308         if (!TEST_int_eq(remove_called, 0))
2309             goto end;
2310
2311         if (maxprot == TLS1_3_VERSION) {
2312             if (!TEST_int_eq(new_called, 1)
2313                     || !TEST_int_eq(get_called, 0))
2314                 goto end;
2315         } else {
2316             if (!TEST_int_eq(new_called, 0)
2317                     || !TEST_int_eq(get_called, 1))
2318                 goto end;
2319         }
2320     }
2321     /*
2322      * Make a small cache, force out all other sessions but
2323      * sess2, try to add sess1, which should succeed. Then
2324      * make sure it's there by checking the owners. Despite
2325      * the timeouts, sess1 should have kicked out sess2
2326      */
2327
2328     /* Make sess1 expire before sess2 */
2329     if (!TEST_long_gt(SSL_SESSION_set_time(sess1, 1000), 0)
2330             || !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0)
2331             || !TEST_long_gt(SSL_SESSION_set_time(sess2, 2000), 0)
2332             || !TEST_long_gt(SSL_SESSION_set_timeout(sess2, 2000), 0))
2333         goto end;
2334
2335     if (!TEST_long_ne(SSL_CTX_sess_set_cache_size(sctx, 1), 0))
2336         goto end;
2337
2338     /* Don't care about results - cache should only be sess2 at end */
2339     SSL_CTX_add_session(sctx, sess1);
2340     SSL_CTX_add_session(sctx, sess2);
2341
2342     /* Now add sess1, and make sure it remains, despite timeout */
2343     if (!TEST_true(SSL_CTX_add_session(sctx, sess1))
2344             || !TEST_ptr(sess1->owner)
2345             || !TEST_ptr_null(sess2->owner))
2346         goto end;
2347
2348     testresult = 1;
2349
2350  end:
2351     SSL_free(serverssl1);
2352     SSL_free(clientssl1);
2353     SSL_free(serverssl2);
2354     SSL_free(clientssl2);
2355 # ifndef OPENSSL_NO_TLS1_1
2356     SSL_free(serverssl3);
2357     SSL_free(clientssl3);
2358 # endif
2359     SSL_SESSION_free(sess1);
2360     SSL_SESSION_free(sess2);
2361     SSL_CTX_free(sctx);
2362     SSL_CTX_free(cctx);
2363
2364     return testresult;
2365 }
2366 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
2367
2368 static int test_session_with_only_int_cache(void)
2369 {
2370 #ifndef OSSL_NO_USABLE_TLS1_3
2371     if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0))
2372         return 0;
2373 #endif
2374
2375 #ifndef OPENSSL_NO_TLS1_2
2376     return execute_test_session(TLS1_2_VERSION, 1, 0, 0);
2377 #else
2378     return 1;
2379 #endif
2380 }
2381
2382 static int test_session_with_only_ext_cache(void)
2383 {
2384 #ifndef OSSL_NO_USABLE_TLS1_3
2385     if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0))
2386         return 0;
2387 #endif
2388
2389 #ifndef OPENSSL_NO_TLS1_2
2390     return execute_test_session(TLS1_2_VERSION, 0, 1, 0);
2391 #else
2392     return 1;
2393 #endif
2394 }
2395
2396 static int test_session_with_both_cache(void)
2397 {
2398 #ifndef OSSL_NO_USABLE_TLS1_3
2399     if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0))
2400         return 0;
2401 #endif
2402
2403 #ifndef OPENSSL_NO_TLS1_2
2404     return execute_test_session(TLS1_2_VERSION, 1, 1, 0);
2405 #else
2406     return 1;
2407 #endif
2408 }
2409
2410 static int test_session_wo_ca_names(void)
2411 {
2412 #ifndef OSSL_NO_USABLE_TLS1_3
2413     if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES))
2414         return 0;
2415 #endif
2416
2417 #ifndef OPENSSL_NO_TLS1_2
2418     return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
2419 #else
2420     return 1;
2421 #endif
2422 }
2423
2424
2425 #ifndef OSSL_NO_USABLE_TLS1_3
2426 static SSL_SESSION *sesscache[6];
2427 static int do_cache;
2428
2429 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
2430 {
2431     if (do_cache) {
2432         sesscache[new_called] = sess;
2433     } else {
2434         /* We don't need the reference to the session, so free it */
2435         SSL_SESSION_free(sess);
2436     }
2437     new_called++;
2438
2439     return 1;
2440 }
2441
2442 static int post_handshake_verify(SSL *sssl, SSL *cssl)
2443 {
2444     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
2445     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
2446         return 0;
2447
2448     /* Start handshake on the server and client */
2449     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
2450             || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
2451             || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
2452             || !TEST_true(create_ssl_connection(sssl, cssl,
2453                                                 SSL_ERROR_NONE)))
2454         return 0;
2455
2456     return 1;
2457 }
2458
2459 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
2460                              SSL_CTX **cctx)
2461 {
2462     int sess_id_ctx = 1;
2463
2464     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2465                                        TLS_client_method(), TLS1_VERSION, 0,
2466                                        sctx, cctx, cert, privkey))
2467             || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
2468             || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
2469                                                          (void *)&sess_id_ctx,
2470                                                          sizeof(sess_id_ctx))))
2471         return 0;
2472
2473     if (stateful)
2474         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
2475
2476     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT
2477                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2478     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
2479
2480     return 1;
2481 }
2482
2483 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
2484 {
2485     SSL *serverssl = NULL, *clientssl = NULL;
2486     int i;
2487
2488     /* Test that we can resume with all the tickets we got given */
2489     for (i = 0; i < idx * 2; i++) {
2490         new_called = 0;
2491         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2492                                               &clientssl, NULL, NULL))
2493                 || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
2494             goto end;
2495
2496         SSL_set_post_handshake_auth(clientssl, 1);
2497
2498         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2499                                                     SSL_ERROR_NONE)))
2500             goto end;
2501
2502         /*
2503          * Following a successful resumption we only get 1 ticket. After a
2504          * failed one we should get idx tickets.
2505          */
2506         if (succ) {
2507             if (!TEST_true(SSL_session_reused(clientssl))
2508                     || !TEST_int_eq(new_called, 1))
2509                 goto end;
2510         } else {
2511             if (!TEST_false(SSL_session_reused(clientssl))
2512                     || !TEST_int_eq(new_called, idx))
2513                 goto end;
2514         }
2515
2516         new_called = 0;
2517         /* After a post-handshake authentication we should get 1 new ticket */
2518         if (succ
2519                 && (!post_handshake_verify(serverssl, clientssl)
2520                     || !TEST_int_eq(new_called, 1)))
2521             goto end;
2522
2523         SSL_shutdown(clientssl);
2524         SSL_shutdown(serverssl);
2525         SSL_free(serverssl);
2526         SSL_free(clientssl);
2527         serverssl = clientssl = NULL;
2528         SSL_SESSION_free(sesscache[i]);
2529         sesscache[i] = NULL;
2530     }
2531
2532     return 1;
2533
2534  end:
2535     SSL_free(clientssl);
2536     SSL_free(serverssl);
2537     return 0;
2538 }
2539
2540 static int test_tickets(int stateful, int idx)
2541 {
2542     SSL_CTX *sctx = NULL, *cctx = NULL;
2543     SSL *serverssl = NULL, *clientssl = NULL;
2544     int testresult = 0;
2545     size_t j;
2546
2547     /* idx is the test number, but also the number of tickets we want */
2548
2549     new_called = 0;
2550     do_cache = 1;
2551
2552     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2553         goto end;
2554
2555     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2556                                           &clientssl, NULL, NULL)))
2557         goto end;
2558
2559     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2560                                                 SSL_ERROR_NONE))
2561                /* Check we got the number of tickets we were expecting */
2562             || !TEST_int_eq(idx, new_called))
2563         goto end;
2564
2565     SSL_shutdown(clientssl);
2566     SSL_shutdown(serverssl);
2567     SSL_free(serverssl);
2568     SSL_free(clientssl);
2569     SSL_CTX_free(sctx);
2570     SSL_CTX_free(cctx);
2571     clientssl = serverssl = NULL;
2572     sctx = cctx = NULL;
2573
2574     /*
2575      * Now we try to resume with the tickets we previously created. The
2576      * resumption attempt is expected to fail (because we're now using a new
2577      * SSL_CTX). We should see idx number of tickets issued again.
2578      */
2579
2580     /* Stop caching sessions - just count them */
2581     do_cache = 0;
2582
2583     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2584         goto end;
2585
2586     if (!check_resumption(idx, sctx, cctx, 0))
2587         goto end;
2588
2589     /* Start again with caching sessions */
2590     new_called = 0;
2591     do_cache = 1;
2592     SSL_CTX_free(sctx);
2593     SSL_CTX_free(cctx);
2594     sctx = cctx = NULL;
2595
2596     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2597         goto end;
2598
2599     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2600                                           &clientssl, NULL, NULL)))
2601         goto end;
2602
2603     SSL_set_post_handshake_auth(clientssl, 1);
2604
2605     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2606                                                 SSL_ERROR_NONE))
2607                /* Check we got the number of tickets we were expecting */
2608             || !TEST_int_eq(idx, new_called))
2609         goto end;
2610
2611     /* After a post-handshake authentication we should get new tickets issued */
2612     if (!post_handshake_verify(serverssl, clientssl)
2613             || !TEST_int_eq(idx * 2, new_called))
2614         goto end;
2615
2616     SSL_shutdown(clientssl);
2617     SSL_shutdown(serverssl);
2618     SSL_free(serverssl);
2619     SSL_free(clientssl);
2620     serverssl = clientssl = NULL;
2621
2622     /* Stop caching sessions - just count them */
2623     do_cache = 0;
2624
2625     /*
2626      * Check we can resume with all the tickets we created. This time around the
2627      * resumptions should all be successful.
2628      */
2629     if (!check_resumption(idx, sctx, cctx, 1))
2630         goto end;
2631
2632     testresult = 1;
2633
2634  end:
2635     SSL_free(serverssl);
2636     SSL_free(clientssl);
2637     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2638         SSL_SESSION_free(sesscache[j]);
2639         sesscache[j] = NULL;
2640     }
2641     SSL_CTX_free(sctx);
2642     SSL_CTX_free(cctx);
2643
2644     return testresult;
2645 }
2646
2647 static int test_stateless_tickets(int idx)
2648 {
2649     return test_tickets(0, idx);
2650 }
2651
2652 static int test_stateful_tickets(int idx)
2653 {
2654     return test_tickets(1, idx);
2655 }
2656
2657 static int test_psk_tickets(void)
2658 {
2659     SSL_CTX *sctx = NULL, *cctx = NULL;
2660     SSL *serverssl = NULL, *clientssl = NULL;
2661     int testresult = 0;
2662     int sess_id_ctx = 1;
2663
2664     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2665                                        TLS_client_method(), TLS1_VERSION, 0,
2666                                        &sctx, &cctx, NULL, NULL))
2667             || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2668                                                          (void *)&sess_id_ctx,
2669                                                          sizeof(sess_id_ctx))))
2670         goto end;
2671
2672     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
2673                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2674     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2675     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2676     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2677     use_session_cb_cnt = 0;
2678     find_session_cb_cnt = 0;
2679     srvid = pskid;
2680     new_called = 0;
2681
2682     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2683                                       NULL, NULL)))
2684         goto end;
2685     clientpsk = serverpsk = create_a_psk(clientssl, SHA384_DIGEST_LENGTH);
2686     if (!TEST_ptr(clientpsk))
2687         goto end;
2688     SSL_SESSION_up_ref(clientpsk);
2689
2690     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2691                                                 SSL_ERROR_NONE))
2692             || !TEST_int_eq(1, find_session_cb_cnt)
2693             || !TEST_int_eq(1, use_session_cb_cnt)
2694                /* We should always get 1 ticket when using external PSK */
2695             || !TEST_int_eq(1, new_called))
2696         goto end;
2697
2698     testresult = 1;
2699
2700  end:
2701     SSL_free(serverssl);
2702     SSL_free(clientssl);
2703     SSL_CTX_free(sctx);
2704     SSL_CTX_free(cctx);
2705     SSL_SESSION_free(clientpsk);
2706     SSL_SESSION_free(serverpsk);
2707     clientpsk = serverpsk = NULL;
2708
2709     return testresult;
2710 }
2711
2712 static int test_extra_tickets(int idx)
2713 {
2714     SSL_CTX *sctx = NULL, *cctx = NULL;
2715     SSL *serverssl = NULL, *clientssl = NULL;
2716     BIO *bretry = BIO_new(bio_s_always_retry());
2717     BIO *tmp = NULL;
2718     int testresult = 0;
2719     int stateful = 0;
2720     size_t nbytes;
2721     unsigned char c, buf[1];
2722
2723     new_called = 0;
2724     do_cache = 1;
2725
2726     if (idx >= 3) {
2727         idx -= 3;
2728         stateful = 1;
2729     }
2730
2731     if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2732         goto end;
2733     SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2734     /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2735     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2736
2737     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2738                                           &clientssl, NULL, NULL)))
2739         goto end;
2740
2741     /*
2742      * Note that we have new_session_cb on both sctx and cctx, so new_called is
2743      * incremented by both client and server.
2744      */
2745     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2746                                                 SSL_ERROR_NONE))
2747                /* Check we got the number of tickets we were expecting */
2748             || !TEST_int_eq(idx * 2, new_called)
2749             || !TEST_true(SSL_new_session_ticket(serverssl))
2750             || !TEST_true(SSL_new_session_ticket(serverssl))
2751             || !TEST_int_eq(idx * 2, new_called))
2752         goto end;
2753
2754     /* Now try a (real) write to actually send the tickets */
2755     c = '1';
2756     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2757             || !TEST_size_t_eq(1, nbytes)
2758             || !TEST_int_eq(idx * 2 + 2, new_called)
2759             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2760             || !TEST_int_eq(idx * 2 + 4, new_called)
2761             || !TEST_int_eq(sizeof(buf), nbytes)
2762             || !TEST_int_eq(c, buf[0])
2763             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2764         goto end;
2765
2766     /* Try with only requesting one new ticket, too */
2767     c = '2';
2768     new_called = 0;
2769     if (!TEST_true(SSL_new_session_ticket(serverssl))
2770             || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2771             || !TEST_size_t_eq(sizeof(c), nbytes)
2772             || !TEST_int_eq(1, new_called)
2773             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2774             || !TEST_int_eq(2, new_called)
2775             || !TEST_size_t_eq(sizeof(buf), nbytes)
2776             || !TEST_int_eq(c, buf[0]))
2777         goto end;
2778
2779     /* Do it again but use dummy writes to drive the ticket generation */
2780     c = '3';
2781     new_called = 0;
2782     if (!TEST_true(SSL_new_session_ticket(serverssl))
2783             || !TEST_true(SSL_new_session_ticket(serverssl))
2784             || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2785             || !TEST_size_t_eq(0, nbytes)
2786             || !TEST_int_eq(2, new_called)
2787             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2788             || !TEST_int_eq(4, new_called))
2789         goto end;
2790
2791     /* Once more, but with SSL_do_handshake() to drive the ticket generation */
2792     c = '4';
2793     new_called = 0;
2794     if (!TEST_true(SSL_new_session_ticket(serverssl))
2795             || !TEST_true(SSL_new_session_ticket(serverssl))
2796             || !TEST_true(SSL_do_handshake(serverssl))
2797             || !TEST_int_eq(2, new_called)
2798             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2799             || !TEST_int_eq(4, new_called))
2800         goto end;
2801
2802     /*
2803      * Use the always-retry BIO to exercise the logic that forces ticket
2804      * generation to wait until a record boundary.
2805      */
2806     c = '5';
2807     new_called = 0;
2808     tmp = SSL_get_wbio(serverssl);
2809     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2810         tmp = NULL;
2811         goto end;
2812     }
2813     SSL_set0_wbio(serverssl, bretry);
2814     bretry = NULL;
2815     if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2816             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2817             || !TEST_size_t_eq(nbytes, 0))
2818         goto end;
2819     /* Restore a BIO that will let the write succeed */
2820     SSL_set0_wbio(serverssl, tmp);
2821     tmp = NULL;
2822     /*
2823      * These calls should just queue the request and not send anything
2824      * even if we explicitly try to hit the state machine.
2825      */
2826     if (!TEST_true(SSL_new_session_ticket(serverssl))
2827             || !TEST_true(SSL_new_session_ticket(serverssl))
2828             || !TEST_int_eq(0, new_called)
2829             || !TEST_true(SSL_do_handshake(serverssl))
2830             || !TEST_int_eq(0, new_called))
2831         goto end;
2832     /* Re-do the write; still no tickets sent */
2833     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2834             || !TEST_size_t_eq(1, nbytes)
2835             || !TEST_int_eq(0, new_called)
2836             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2837             || !TEST_int_eq(0, new_called)
2838             || !TEST_int_eq(sizeof(buf), nbytes)
2839             || !TEST_int_eq(c, buf[0])
2840             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2841         goto end;
2842     /* Even trying to hit the state machine now will still not send tickets */
2843     if (!TEST_true(SSL_do_handshake(serverssl))
2844             || !TEST_int_eq(0, new_called))
2845         goto end;
2846     /* Now the *next* write should send the tickets */
2847     c = '6';
2848     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2849             || !TEST_size_t_eq(1, nbytes)
2850             || !TEST_int_eq(2, new_called)
2851             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2852             || !TEST_int_eq(4, new_called)
2853             || !TEST_int_eq(sizeof(buf), nbytes)
2854             || !TEST_int_eq(c, buf[0])
2855             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2856         goto end;
2857
2858     SSL_shutdown(clientssl);
2859     SSL_shutdown(serverssl);
2860     testresult = 1;
2861
2862  end:
2863     BIO_free(bretry);
2864     BIO_free(tmp);
2865     SSL_free(serverssl);
2866     SSL_free(clientssl);
2867     SSL_CTX_free(sctx);
2868     SSL_CTX_free(cctx);
2869     clientssl = serverssl = NULL;
2870     sctx = cctx = NULL;
2871     return testresult;
2872 }
2873 #endif
2874
2875 #define USE_NULL            0
2876 #define USE_BIO_1           1
2877 #define USE_BIO_2           2
2878 #define USE_DEFAULT         3
2879
2880 #define CONNTYPE_CONNECTION_SUCCESS  0
2881 #define CONNTYPE_CONNECTION_FAIL     1
2882 #define CONNTYPE_NO_CONNECTION       2
2883
2884 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
2885 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
2886 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2887 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
2888 #else
2889 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
2890 #endif
2891
2892 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
2893                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2894                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2895
2896 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2897 {
2898     switch (type) {
2899     case USE_NULL:
2900         *res = NULL;
2901         break;
2902     case USE_BIO_1:
2903         *res = bio1;
2904         break;
2905     case USE_BIO_2:
2906         *res = bio2;
2907         break;
2908     }
2909 }
2910
2911
2912 /*
2913  * Tests calls to SSL_set_bio() under various conditions.
2914  *
2915  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2916  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2917  * then do more tests where we create a successful connection first using our
2918  * standard connection setup functions, and then call SSL_set_bio() with
2919  * various combinations of valid BIOs or NULL. We then repeat these tests
2920  * following a failed connection. In this last case we are looking to check that
2921  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2922  */
2923 static int test_ssl_set_bio(int idx)
2924 {
2925     SSL_CTX *sctx = NULL, *cctx = NULL;
2926     BIO *bio1 = NULL;
2927     BIO *bio2 = NULL;
2928     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2929     SSL *serverssl = NULL, *clientssl = NULL;
2930     int initrbio, initwbio, newrbio, newwbio, conntype;
2931     int testresult = 0;
2932
2933     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2934         initrbio = idx % 3;
2935         idx /= 3;
2936         initwbio = idx % 3;
2937         idx /= 3;
2938         newrbio = idx % 3;
2939         idx /= 3;
2940         newwbio = idx % 3;
2941         conntype = CONNTYPE_NO_CONNECTION;
2942     } else {
2943         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2944         initrbio = initwbio = USE_DEFAULT;
2945         newrbio = idx % 2;
2946         idx /= 2;
2947         newwbio = idx % 2;
2948         idx /= 2;
2949         conntype = idx % 2;
2950     }
2951
2952     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2953                                        TLS_client_method(), TLS1_VERSION, 0,
2954                                        &sctx, &cctx, cert, privkey)))
2955         goto end;
2956
2957     if (conntype == CONNTYPE_CONNECTION_FAIL) {
2958         /*
2959          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2960          * because we reduced the number of tests in the definition of
2961          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2962          * mismatched protocol versions we will force a connection failure.
2963          */
2964         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2965         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2966     }
2967
2968     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2969                                       NULL, NULL)))
2970         goto end;
2971
2972     if (initrbio == USE_BIO_1
2973             || initwbio == USE_BIO_1
2974             || newrbio == USE_BIO_1
2975             || newwbio == USE_BIO_1) {
2976         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2977             goto end;
2978     }
2979
2980     if (initrbio == USE_BIO_2
2981             || initwbio == USE_BIO_2
2982             || newrbio == USE_BIO_2
2983             || newwbio == USE_BIO_2) {
2984         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
2985             goto end;
2986     }
2987
2988     if (initrbio != USE_DEFAULT) {
2989         setupbio(&irbio, bio1, bio2, initrbio);
2990         setupbio(&iwbio, bio1, bio2, initwbio);
2991         SSL_set_bio(clientssl, irbio, iwbio);
2992
2993         /*
2994          * We want to maintain our own refs to these BIO, so do an up ref for
2995          * each BIO that will have ownership transferred in the SSL_set_bio()
2996          * call
2997          */
2998         if (irbio != NULL)
2999             BIO_up_ref(irbio);
3000         if (iwbio != NULL && iwbio != irbio)
3001             BIO_up_ref(iwbio);
3002     }
3003
3004     if (conntype != CONNTYPE_NO_CONNECTION
3005             && !TEST_true(create_ssl_connection(serverssl, clientssl,
3006                                                 SSL_ERROR_NONE)
3007                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
3008         goto end;
3009
3010     setupbio(&nrbio, bio1, bio2, newrbio);
3011     setupbio(&nwbio, bio1, bio2, newwbio);
3012
3013     /*
3014      * We will (maybe) transfer ownership again so do more up refs.
3015      * SSL_set_bio() has some really complicated ownership rules where BIOs have
3016      * already been set!
3017      */
3018     if (nrbio != NULL
3019             && nrbio != irbio
3020             && (nwbio != iwbio || nrbio != nwbio))
3021         BIO_up_ref(nrbio);
3022     if (nwbio != NULL
3023             && nwbio != nrbio
3024             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
3025         BIO_up_ref(nwbio);
3026
3027     SSL_set_bio(clientssl, nrbio, nwbio);
3028
3029     testresult = 1;
3030
3031  end:
3032     BIO_free(bio1);
3033     BIO_free(bio2);
3034
3035     /*
3036      * This test is checking that the ref counting for SSL_set_bio is correct.
3037      * If we get here and we did too many frees then we will fail in the above
3038      * functions.
3039      */
3040     SSL_free(serverssl);
3041     SSL_free(clientssl);
3042     SSL_CTX_free(sctx);
3043     SSL_CTX_free(cctx);
3044     return testresult;
3045 }
3046
3047 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
3048
3049 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
3050 {
3051     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
3052     SSL_CTX *ctx;
3053     SSL *ssl = NULL;
3054     int testresult = 0;
3055
3056     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
3057             || !TEST_ptr(ssl = SSL_new(ctx))
3058             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
3059             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
3060         goto end;
3061
3062     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
3063
3064     /*
3065      * If anything goes wrong here then we could leak memory.
3066      */
3067     BIO_push(sslbio, membio1);
3068
3069     /* Verify changing the rbio/wbio directly does not cause leaks */
3070     if (change_bio != NO_BIO_CHANGE) {
3071         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
3072             ssl = NULL;
3073             goto end;
3074         }
3075         if (change_bio == CHANGE_RBIO)
3076             SSL_set0_rbio(ssl, membio2);
3077         else
3078             SSL_set0_wbio(ssl, membio2);
3079     }
3080     ssl = NULL;
3081
3082     if (pop_ssl)
3083         BIO_pop(sslbio);
3084     else
3085         BIO_pop(membio1);
3086
3087     testresult = 1;
3088  end:
3089     BIO_free(membio1);
3090     BIO_free(sslbio);
3091     SSL_free(ssl);
3092     SSL_CTX_free(ctx);
3093
3094     return testresult;
3095 }
3096
3097 static int test_ssl_bio_pop_next_bio(void)
3098 {
3099     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
3100 }
3101
3102 static int test_ssl_bio_pop_ssl_bio(void)
3103 {
3104     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
3105 }
3106
3107 static int test_ssl_bio_change_rbio(void)
3108 {
3109     return execute_test_ssl_bio(0, CHANGE_RBIO);
3110 }
3111
3112 static int test_ssl_bio_change_wbio(void)
3113 {
3114     return execute_test_ssl_bio(0, CHANGE_WBIO);
3115 }
3116
3117 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
3118 typedef struct {
3119     /* The list of sig algs */
3120     const int *list;
3121     /* The length of the list */
3122     size_t listlen;
3123     /* A sigalgs list in string format */
3124     const char *liststr;
3125     /* Whether setting the list should succeed */
3126     int valid;
3127     /* Whether creating a connection with the list should succeed */
3128     int connsuccess;
3129 } sigalgs_list;
3130
3131 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
3132 # ifndef OPENSSL_NO_EC
3133 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
3134 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
3135 # endif
3136 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
3137 static const int invalidlist2[] = {NID_sha256, NID_undef};
3138 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
3139 static const int invalidlist4[] = {NID_sha256};
3140 static const sigalgs_list testsigalgs[] = {
3141     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
3142 # ifndef OPENSSL_NO_EC
3143     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
3144     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
3145 # endif
3146     {NULL, 0, "RSA+SHA256", 1, 1},
3147 # ifndef OPENSSL_NO_EC
3148     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
3149     {NULL, 0, "ECDSA+SHA512", 1, 0},
3150 # endif
3151     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
3152     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
3153     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
3154     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
3155     {NULL, 0, "RSA", 0, 0},
3156     {NULL, 0, "SHA256", 0, 0},
3157     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
3158     {NULL, 0, "Invalid", 0, 0}
3159 };
3160
3161 static int test_set_sigalgs(int idx)
3162 {
3163     SSL_CTX *cctx = NULL, *sctx = NULL;
3164     SSL *clientssl = NULL, *serverssl = NULL;
3165     int testresult = 0;
3166     const sigalgs_list *curr;
3167     int testctx;
3168
3169     /* Should never happen */
3170     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
3171         return 0;
3172
3173     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
3174     curr = testctx ? &testsigalgs[idx]
3175                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
3176
3177     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3178                                        TLS_client_method(), TLS1_VERSION, 0,
3179                                        &sctx, &cctx, cert, privkey)))
3180         return 0;
3181
3182     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
3183
3184     if (testctx) {
3185         int ret;
3186
3187         if (curr->list != NULL)
3188             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
3189         else
3190             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
3191
3192         if (!ret) {
3193             if (curr->valid)
3194                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
3195             else
3196                 testresult = 1;
3197             goto end;
3198         }
3199         if (!curr->valid) {
3200             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
3201             goto end;
3202         }
3203     }
3204
3205     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3206                                       &clientssl, NULL, NULL)))
3207         goto end;
3208
3209     if (!testctx) {
3210         int ret;
3211
3212         if (curr->list != NULL)
3213             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
3214         else
3215             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
3216         if (!ret) {
3217             if (curr->valid)
3218                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
3219             else
3220                 testresult = 1;
3221             goto end;
3222         }
3223         if (!curr->valid)
3224             goto end;
3225     }
3226
3227     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
3228                                            SSL_ERROR_NONE),
3229                 curr->connsuccess))
3230         goto end;
3231
3232     testresult = 1;
3233
3234  end:
3235     SSL_free(serverssl);
3236     SSL_free(clientssl);
3237     SSL_CTX_free(sctx);
3238     SSL_CTX_free(cctx);
3239
3240     return testresult;
3241 }
3242 #endif
3243
3244 #ifndef OSSL_NO_USABLE_TLS1_3
3245 static int psk_client_cb_cnt = 0;
3246 static int psk_server_cb_cnt = 0;
3247
3248 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
3249                           size_t *idlen, SSL_SESSION **sess)
3250 {
3251     switch (++use_session_cb_cnt) {
3252     case 1:
3253         /* The first call should always have a NULL md */
3254         if (md != NULL)
3255             return 0;
3256         break;
3257
3258     case 2:
3259         /* The second call should always have an md */
3260         if (md == NULL)
3261             return 0;
3262         break;
3263
3264     default:
3265         /* We should only be called a maximum of twice */
3266         return 0;
3267     }
3268
3269     if (clientpsk != NULL)
3270         SSL_SESSION_up_ref(clientpsk);
3271
3272     *sess = clientpsk;
3273     *id = (const unsigned char *)pskid;
3274     *idlen = strlen(pskid);
3275
3276     return 1;
3277 }
3278
3279 #ifndef OPENSSL_NO_PSK
3280 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
3281                                   unsigned int max_id_len,
3282                                   unsigned char *psk,
3283                                   unsigned int max_psk_len)
3284 {
3285     unsigned int psklen = 0;
3286
3287     psk_client_cb_cnt++;
3288
3289     if (strlen(pskid) + 1 > max_id_len)
3290         return 0;
3291
3292     /* We should only ever be called a maximum of twice per connection */
3293     if (psk_client_cb_cnt > 2)
3294         return 0;
3295
3296     if (clientpsk == NULL)
3297         return 0;
3298
3299     /* We'll reuse the PSK we set up for TLSv1.3 */
3300     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
3301         return 0;
3302     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
3303     strncpy(id, pskid, max_id_len);
3304
3305     return psklen;
3306 }
3307 #endif /* OPENSSL_NO_PSK */
3308
3309 static int find_session_cb(SSL *ssl, const unsigned char *identity,
3310                            size_t identity_len, SSL_SESSION **sess)
3311 {
3312     find_session_cb_cnt++;
3313
3314     /* We should only ever be called a maximum of twice per connection */
3315     if (find_session_cb_cnt > 2)
3316         return 0;
3317
3318     if (serverpsk == NULL)
3319         return 0;
3320
3321     /* Identity should match that set by the client */
3322     if (strlen(srvid) != identity_len
3323             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
3324         /* No PSK found, continue but without a PSK */
3325         *sess = NULL;
3326         return 1;
3327     }
3328
3329     SSL_SESSION_up_ref(serverpsk);
3330     *sess = serverpsk;
3331
3332     return 1;
3333 }
3334
3335 #ifndef OPENSSL_NO_PSK
3336 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
3337                                   unsigned char *psk, unsigned int max_psk_len)
3338 {
3339     unsigned int psklen = 0;
3340
3341     psk_server_cb_cnt++;
3342
3343     /* We should only ever be called a maximum of twice per connection */
3344     if (find_session_cb_cnt > 2)
3345         return 0;
3346
3347     if (serverpsk == NULL)
3348         return 0;
3349
3350     /* Identity should match that set by the client */
3351     if (strcmp(srvid, identity) != 0) {
3352         return 0;
3353     }
3354
3355     /* We'll reuse the PSK we set up for TLSv1.3 */
3356     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
3357         return 0;
3358     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
3359
3360     return psklen;
3361 }
3362 #endif /* OPENSSL_NO_PSK */
3363
3364 #define MSG1    "Hello"
3365 #define MSG2    "World."
3366 #define MSG3    "This"
3367 #define MSG4    "is"
3368 #define MSG5    "a"
3369 #define MSG6    "test"
3370 #define MSG7    "message."
3371
3372 #define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
3373 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
3374 #define TLS13_CHACHA20_POLY1305_SHA256_BYTES ((const unsigned char *)"\x13\x03")
3375 #define TLS13_AES_128_CCM_SHA256_BYTES ((const unsigned char *)"\x13\x04")
3376 #define TLS13_AES_128_CCM_8_SHA256_BYTES ((const unsigned char *)"\x13\05")
3377
3378
3379 static SSL_SESSION *create_a_psk(SSL *ssl, size_t mdsize)
3380 {
3381     const SSL_CIPHER *cipher = NULL;
3382     const unsigned char key[] = {
3383         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
3384         0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
3385         0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
3386         0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
3387         0x2c, 0x2d, 0x2e, 0x2f /* SHA384_DIGEST_LENGTH bytes */
3388     };
3389     SSL_SESSION *sess = NULL;
3390
3391     if (mdsize == SHA384_DIGEST_LENGTH) {
3392         cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES);
3393     } else if (mdsize == SHA256_DIGEST_LENGTH) {
3394         /*
3395          * Any ciphersuite using SHA256 will do - it will be compatible with
3396          * the actual ciphersuite selected as long as it too is based on SHA256
3397          */
3398         cipher = SSL_CIPHER_find(ssl, TLS13_AES_128_GCM_SHA256_BYTES);
3399     } else {
3400         /* Should not happen */
3401         return NULL;
3402     }
3403     sess = SSL_SESSION_new();
3404     if (!TEST_ptr(sess)
3405             || !TEST_ptr(cipher)
3406             || !TEST_true(SSL_SESSION_set1_master_key(sess, key, mdsize))
3407             || !TEST_true(SSL_SESSION_set_cipher(sess, cipher))
3408             || !TEST_true(
3409                     SSL_SESSION_set_protocol_version(sess,
3410                                                      TLS1_3_VERSION))) {
3411         SSL_SESSION_free(sess);
3412         return NULL;
3413     }
3414     return sess;
3415 }
3416
3417 static int artificial_ticket_time = 0;
3418
3419 static int ed_gen_cb(SSL *s, void *arg)
3420 {
3421     SSL_SESSION *sess = SSL_get0_session(s);
3422
3423     if (sess == NULL)
3424         return 0;
3425
3426     /*
3427      * Artificially give the ticket some age. Just do it for the number of
3428      * tickets we've been told to do.
3429      */
3430     if (artificial_ticket_time == 0)
3431         return 1;
3432     artificial_ticket_time--;
3433
3434     if (SSL_SESSION_set_time(sess, SSL_SESSION_get_time(sess) - 10) == 0)
3435         return 0;
3436
3437     return 1;
3438 }
3439
3440 /*
3441  * Helper method to setup objects for early data test. Caller frees objects on
3442  * error.
3443  */
3444 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
3445                                 SSL **serverssl, SSL_SESSION **sess, int idx,
3446                                 size_t mdsize)
3447 {
3448     int artificial = (artificial_ticket_time > 0);
3449
3450     if (*sctx == NULL
3451             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3452                                               TLS_client_method(),
3453                                               TLS1_VERSION, 0,
3454                                               sctx, cctx, cert, privkey)))
3455         return 0;
3456
3457     if (artificial)
3458         SSL_CTX_set_session_ticket_cb(*sctx, ed_gen_cb, NULL, NULL);
3459
3460     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
3461         return 0;
3462
3463     if (idx == 1) {
3464         /* When idx == 1 we repeat the tests with read_ahead set */
3465         SSL_CTX_set_read_ahead(*cctx, 1);
3466         SSL_CTX_set_read_ahead(*sctx, 1);
3467     } else if (idx == 2) {
3468         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
3469         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
3470         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
3471         use_session_cb_cnt = 0;
3472         find_session_cb_cnt = 0;
3473         srvid = pskid;
3474     }
3475
3476     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
3477                                       NULL, NULL)))
3478         return 0;
3479
3480     /*
3481      * For one of the run throughs (doesn't matter which one), we'll try sending
3482      * some SNI data in the initial ClientHello. This will be ignored (because
3483      * there is no SNI cb set up by the server), so it should not impact
3484      * early_data.
3485      */
3486     if (idx == 1
3487             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
3488         return 0;
3489
3490     if (idx == 2) {
3491         clientpsk = create_a_psk(*clientssl, mdsize);
3492         if (!TEST_ptr(clientpsk)
3493                    /*
3494                     * We just choose an arbitrary value for max_early_data which
3495                     * should be big enough for testing purposes.
3496                     */
3497                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
3498                                                              0x100))
3499                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3500             SSL_SESSION_free(clientpsk);
3501             clientpsk = NULL;
3502             return 0;
3503         }
3504         serverpsk = clientpsk;
3505
3506         if (sess != NULL) {
3507             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3508                 SSL_SESSION_free(clientpsk);
3509                 SSL_SESSION_free(serverpsk);
3510                 clientpsk = serverpsk = NULL;
3511                 return 0;
3512             }
3513             *sess = clientpsk;
3514         }
3515         return 1;
3516     }
3517
3518     if (sess == NULL)
3519         return 1;
3520
3521     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
3522                                          SSL_ERROR_NONE)))
3523         return 0;
3524
3525     *sess = SSL_get1_session(*clientssl);
3526     SSL_shutdown(*clientssl);
3527     SSL_shutdown(*serverssl);
3528     SSL_free(*serverssl);
3529     SSL_free(*clientssl);
3530     *serverssl = *clientssl = NULL;
3531
3532     /*
3533      * Artificially give the ticket some age to match the artificial age we
3534      * gave it on the server side
3535      */
3536     if (artificial
3537             && !TEST_long_gt(SSL_SESSION_set_time(*sess,
3538                                                   SSL_SESSION_get_time(*sess) - 10), 0))
3539         return 0;
3540
3541     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
3542                                       clientssl, NULL, NULL))
3543             || !TEST_true(SSL_set_session(*clientssl, *sess)))
3544         return 0;
3545
3546     return 1;
3547 }
3548
3549 static int test_early_data_read_write(int idx)
3550 {
3551     SSL_CTX *cctx = NULL, *sctx = NULL;
3552     SSL *clientssl = NULL, *serverssl = NULL;
3553     int testresult = 0;
3554     SSL_SESSION *sess = NULL;
3555     unsigned char buf[20], data[1024];
3556     size_t readbytes, written, eoedlen, rawread, rawwritten;
3557     BIO *rbio;
3558
3559     /* Artificially give the next 2 tickets some age for non PSK sessions */
3560     if (idx != 2)
3561         artificial_ticket_time = 2;
3562     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3563                                         &serverssl, &sess, idx,
3564                                         SHA384_DIGEST_LENGTH))) {
3565         artificial_ticket_time = 0;
3566         goto end;
3567     }
3568     artificial_ticket_time = 0;
3569
3570     /* Write and read some early data */
3571     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3572                                         &written))
3573             || !TEST_size_t_eq(written, strlen(MSG1))
3574             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
3575                                                 sizeof(buf), &readbytes),
3576                             SSL_READ_EARLY_DATA_SUCCESS)
3577             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
3578             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3579                             SSL_EARLY_DATA_ACCEPTED))
3580         goto end;
3581
3582     /*
3583      * Server should be able to write data, and client should be able to
3584      * read it.
3585      */
3586     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
3587                                         &written))
3588             || !TEST_size_t_eq(written, strlen(MSG2))
3589             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3590             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3591         goto end;
3592
3593     /* Even after reading normal data, client should be able write early data */
3594     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
3595                                         &written))
3596             || !TEST_size_t_eq(written, strlen(MSG3)))
3597         goto end;
3598
3599     /* Server should still be able read early data after writing data */
3600     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3601                                          &readbytes),
3602                      SSL_READ_EARLY_DATA_SUCCESS)
3603             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
3604         goto end;
3605
3606     /* Write more data from server and read it from client */
3607     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
3608                                         &written))
3609             || !TEST_size_t_eq(written, strlen(MSG4))
3610             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3611             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
3612         goto end;
3613
3614     /*
3615      * If client writes normal data it should mean writing early data is no
3616      * longer possible.
3617      */
3618     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3619             || !TEST_size_t_eq(written, strlen(MSG5))
3620             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3621                             SSL_EARLY_DATA_ACCEPTED))
3622         goto end;
3623
3624     /*
3625      * At this point the client has written EndOfEarlyData, ClientFinished and
3626      * normal (fully protected) data. We are going to cause a delay between the
3627      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
3628      * in the read BIO, and then just put back the EndOfEarlyData message.
3629      */
3630     rbio = SSL_get_rbio(serverssl);
3631     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
3632             || !TEST_size_t_lt(rawread, sizeof(data))
3633             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
3634         goto end;
3635
3636     /* Record length is in the 4th and 5th bytes of the record header */
3637     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
3638     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
3639             || !TEST_size_t_eq(rawwritten, eoedlen))
3640         goto end;
3641
3642     /* Server should be told that there is no more early data */
3643     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3644                                          &readbytes),
3645                      SSL_READ_EARLY_DATA_FINISH)
3646             || !TEST_size_t_eq(readbytes, 0))
3647         goto end;
3648
3649     /*
3650      * Server has not finished init yet, so should still be able to write early
3651      * data.
3652      */
3653     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
3654                                         &written))
3655             || !TEST_size_t_eq(written, strlen(MSG6)))
3656         goto end;
3657
3658     /* Push the ClientFinished and the normal data back into the server rbio */
3659     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
3660                                 &rawwritten))
3661             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
3662         goto end;
3663
3664     /* Server should be able to read normal data */
3665     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3666             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3667         goto end;
3668
3669     /* Client and server should not be able to write/read early data now */
3670     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3671                                          &written)))
3672         goto end;
3673     ERR_clear_error();
3674     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3675                                          &readbytes),
3676                      SSL_READ_EARLY_DATA_ERROR))
3677         goto end;
3678     ERR_clear_error();
3679
3680     /* Client should be able to read the data sent by the server */
3681     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3682             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
3683         goto end;
3684
3685     /*
3686      * Make sure we process the two NewSessionTickets. These arrive
3687      * post-handshake. We attempt reads which we do not expect to return any
3688      * data.
3689      */
3690     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3691             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3692                            &readbytes)))
3693         goto end;
3694
3695     /* Server should be able to write normal data */
3696     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3697             || !TEST_size_t_eq(written, strlen(MSG7))
3698             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3699             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3700         goto end;
3701
3702     SSL_SESSION_free(sess);
3703     sess = SSL_get1_session(clientssl);
3704     use_session_cb_cnt = 0;
3705     find_session_cb_cnt = 0;
3706
3707     SSL_shutdown(clientssl);
3708     SSL_shutdown(serverssl);
3709     SSL_free(serverssl);
3710     SSL_free(clientssl);
3711     serverssl = clientssl = NULL;
3712     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3713                                       &clientssl, NULL, NULL))
3714             || !TEST_true(SSL_set_session(clientssl, sess)))
3715         goto end;
3716
3717     /* Write and read some early data */
3718     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3719                                         &written))
3720             || !TEST_size_t_eq(written, strlen(MSG1))
3721             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3722                                                 &readbytes),
3723                             SSL_READ_EARLY_DATA_SUCCESS)
3724             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3725         goto end;
3726
3727     if (!TEST_int_gt(SSL_connect(clientssl), 0)
3728             || !TEST_int_gt(SSL_accept(serverssl), 0))
3729         goto end;
3730
3731     /* Client and server should not be able to write/read early data now */
3732     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3733                                          &written)))
3734         goto end;
3735     ERR_clear_error();
3736     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3737                                          &readbytes),
3738                      SSL_READ_EARLY_DATA_ERROR))
3739         goto end;
3740     ERR_clear_error();
3741
3742     /* Client and server should be able to write/read normal data */
3743     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3744             || !TEST_size_t_eq(written, strlen(MSG5))
3745             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3746             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3747         goto end;
3748
3749     testresult = 1;
3750
3751  end:
3752     SSL_SESSION_free(sess);
3753     SSL_SESSION_free(clientpsk);
3754     SSL_SESSION_free(serverpsk);
3755     clientpsk = serverpsk = NULL;
3756     SSL_free(serverssl);
3757     SSL_free(clientssl);
3758     SSL_CTX_free(sctx);
3759     SSL_CTX_free(cctx);
3760     return testresult;
3761 }
3762
3763 static int allow_ed_cb_called = 0;
3764
3765 static int allow_early_data_cb(SSL *s, void *arg)
3766 {
3767     int *usecb = (int *)arg;
3768
3769     allow_ed_cb_called++;
3770
3771     if (*usecb == 1)
3772         return 0;
3773
3774     return 1;
3775 }
3776
3777 /*
3778  * idx == 0: Standard early_data setup
3779  * idx == 1: early_data setup using read_ahead
3780  * usecb == 0: Don't use a custom early data callback
3781  * usecb == 1: Use a custom early data callback and reject the early data
3782  * usecb == 2: Use a custom early data callback and accept the early data
3783  * confopt == 0: Configure anti-replay directly
3784  * confopt == 1: Configure anti-replay using SSL_CONF
3785  */
3786 static int test_early_data_replay_int(int idx, int usecb, int confopt)
3787 {
3788     SSL_CTX *cctx = NULL, *sctx = NULL;
3789     SSL *clientssl = NULL, *serverssl = NULL;
3790     int testresult = 0;
3791     SSL_SESSION *sess = NULL;
3792     size_t readbytes, written;
3793     unsigned char buf[20];
3794
3795     allow_ed_cb_called = 0;
3796
3797     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3798                                        TLS_client_method(), TLS1_VERSION, 0,
3799                                        &sctx, &cctx, cert, privkey)))
3800         return 0;
3801
3802     if (usecb > 0) {
3803         if (confopt == 0) {
3804             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3805         } else {
3806             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3807
3808             if (!TEST_ptr(confctx))
3809                 goto end;
3810             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
3811                                             | SSL_CONF_FLAG_SERVER);
3812             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3813             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3814                              2)) {
3815                 SSL_CONF_CTX_free(confctx);
3816                 goto end;
3817             }
3818             SSL_CONF_CTX_free(confctx);
3819         }
3820         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3821     }
3822
3823     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3824                                         &serverssl, &sess, idx,
3825                                         SHA384_DIGEST_LENGTH)))
3826         goto end;
3827
3828     /*
3829      * The server is configured to accept early data. Create a connection to
3830      * "use up" the ticket
3831      */
3832     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3833             || !TEST_true(SSL_session_reused(clientssl)))
3834         goto end;
3835
3836     SSL_shutdown(clientssl);
3837     SSL_shutdown(serverssl);
3838     SSL_free(serverssl);
3839     SSL_free(clientssl);
3840     serverssl = clientssl = NULL;
3841
3842     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3843                                       &clientssl, NULL, NULL))
3844             || !TEST_true(SSL_set_session(clientssl, sess)))
3845         goto end;
3846
3847     /* Write and read some early data */
3848     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3849                                         &written))
3850             || !TEST_size_t_eq(written, strlen(MSG1)))
3851         goto end;
3852
3853     if (usecb <= 1) {
3854         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3855                                              &readbytes),
3856                          SSL_READ_EARLY_DATA_FINISH)
3857                    /*
3858                     * The ticket was reused, so the we should have rejected the
3859                     * early data
3860                     */
3861                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3862                                 SSL_EARLY_DATA_REJECTED))
3863             goto end;
3864     } else {
3865         /* In this case the callback decides to accept the early data */
3866         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3867                                              &readbytes),
3868                          SSL_READ_EARLY_DATA_SUCCESS)
3869                 || !TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3870                    /*
3871                     * Server will have sent its flight so client can now send
3872                     * end of early data and complete its half of the handshake
3873                     */
3874                 || !TEST_int_gt(SSL_connect(clientssl), 0)
3875                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3876                                              &readbytes),
3877                                 SSL_READ_EARLY_DATA_FINISH)
3878                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3879                                 SSL_EARLY_DATA_ACCEPTED))
3880             goto end;
3881     }
3882
3883     /* Complete the connection */
3884     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3885             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3886             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3887         goto end;
3888
3889     testresult = 1;
3890
3891  end:
3892     SSL_SESSION_free(sess);
3893     SSL_SESSION_free(clientpsk);
3894     SSL_SESSION_free(serverpsk);
3895     clientpsk = serverpsk = NULL;
3896     SSL_free(serverssl);
3897     SSL_free(clientssl);
3898     SSL_CTX_free(sctx);
3899     SSL_CTX_free(cctx);
3900     return testresult;
3901 }
3902
3903 static int test_early_data_replay(int idx)
3904 {
3905     int ret = 1, usecb, confopt;
3906
3907     for (usecb = 0; usecb < 3; usecb++) {
3908         for (confopt = 0; confopt < 2; confopt++)
3909             ret &= test_early_data_replay_int(idx, usecb, confopt);
3910     }
3911
3912     return ret;
3913 }
3914
3915 static const char *ciphersuites[] = {
3916     "TLS_AES_128_CCM_8_SHA256",
3917     "TLS_AES_128_GCM_SHA256",
3918     "TLS_AES_256_GCM_SHA384",
3919     "TLS_AES_128_CCM_SHA256",
3920 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3921     "TLS_CHACHA20_POLY1305_SHA256"
3922 #endif
3923 };
3924
3925 /*
3926  * Helper function to test that a server attempting to read early data can
3927  * handle a connection from a client where the early data should be skipped.
3928  * testtype: 0 == No HRR
3929  * testtype: 1 == HRR
3930  * testtype: 2 == HRR, invalid early_data sent after HRR
3931  * testtype: 3 == recv_max_early_data set to 0
3932  */
3933 static int early_data_skip_helper(int testtype, int cipher, int idx)
3934 {
3935     SSL_CTX *cctx = NULL, *sctx = NULL;
3936     SSL *clientssl = NULL, *serverssl = NULL;
3937     int testresult = 0;
3938     SSL_SESSION *sess = NULL;
3939     unsigned char buf[20];
3940     size_t readbytes, written;
3941
3942     if (is_fips && cipher == 4)
3943         return 1;
3944
3945     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3946                                               TLS_client_method(),
3947                                               TLS1_VERSION, 0,
3948                                               &sctx, &cctx, cert, privkey)))
3949         goto end;
3950
3951     if (cipher == 0) {
3952         SSL_CTX_set_security_level(sctx, 0);
3953         SSL_CTX_set_security_level(cctx, 0);
3954     }
3955
3956     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, ciphersuites[cipher]))
3957             || !TEST_true(SSL_CTX_set_ciphersuites(cctx, ciphersuites[cipher])))
3958         goto end;
3959
3960     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3961                                         &serverssl, &sess, idx,
3962                                         cipher == 2 ? SHA384_DIGEST_LENGTH
3963                                                     : SHA256_DIGEST_LENGTH)))
3964         goto end;
3965
3966     if (testtype == 1 || testtype == 2) {
3967         /* Force an HRR to occur */
3968 #if defined(OPENSSL_NO_EC)
3969         if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
3970             goto end;
3971 #else
3972         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
3973             goto end;
3974 #endif
3975     } else if (idx == 2) {
3976         /*
3977          * We force early_data rejection by ensuring the PSK identity is
3978          * unrecognised
3979          */
3980         srvid = "Dummy Identity";
3981     } else {
3982         /*
3983          * Deliberately corrupt the creation time. We take 20 seconds off the
3984          * time. It could be any value as long as it is not within tolerance.
3985          * This should mean the ticket is rejected.
3986          */
3987         if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
3988             goto end;
3989     }
3990
3991     if (testtype == 3
3992             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
3993         goto end;
3994
3995     /* Write some early data */
3996     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3997                                         &written))
3998             || !TEST_size_t_eq(written, strlen(MSG1)))
3999         goto end;
4000
4001     /* Server should reject the early data */
4002     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4003                                          &readbytes),
4004                      SSL_READ_EARLY_DATA_FINISH)
4005             || !TEST_size_t_eq(readbytes, 0)
4006             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4007                             SSL_EARLY_DATA_REJECTED))
4008         goto end;
4009
4010     switch (testtype) {
4011     case 0:
4012         /* Nothing to do */
4013         break;
4014
4015     case 1:
4016         /*
4017          * Finish off the handshake. We perform the same writes and reads as
4018          * further down but we expect them to fail due to the incomplete
4019          * handshake.
4020          */
4021         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4022                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
4023                                &readbytes)))
4024             goto end;
4025         break;
4026
4027     case 2:
4028         {
4029             BIO *wbio = SSL_get_wbio(clientssl);
4030             /* A record that will appear as bad early_data */
4031             const unsigned char bad_early_data[] = {
4032                 0x17, 0x03, 0x03, 0x00, 0x01, 0x00
4033             };
4034
4035             /*
4036              * We force the client to attempt a write. This will fail because
4037              * we're still in the handshake. It will cause the second
4038              * ClientHello to be sent.
4039              */
4040             if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
4041                                          &written)))
4042                 goto end;
4043
4044             /*
4045              * Inject some early_data after the second ClientHello. This should
4046              * cause the server to fail
4047              */
4048             if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
4049                                         sizeof(bad_early_data), &written)))
4050                 goto end;
4051         }
4052         /* fallthrough */
4053
4054     case 3:
4055         /*
4056          * This client has sent more early_data than we are willing to skip
4057          * (case 3) or sent invalid early_data (case 2) so the connection should
4058          * abort.
4059          */
4060         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4061                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
4062             goto end;
4063
4064         /* Connection has failed - nothing more to do */
4065         testresult = 1;
4066         goto end;
4067
4068     default:
4069         TEST_error("Invalid test type");
4070         goto end;
4071     }
4072
4073     ERR_clear_error();
4074     /*
4075      * Should be able to send normal data despite rejection of early data. The
4076      * early_data should be skipped.
4077      */
4078     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4079             || !TEST_size_t_eq(written, strlen(MSG2))
4080             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4081                             SSL_EARLY_DATA_REJECTED)
4082             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4083             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4084         goto end;
4085
4086     /*
4087      * Failure to decrypt early data records should not leave spurious errors
4088      * on the error stack
4089      */
4090     if (!TEST_long_eq(ERR_peek_error(), 0))
4091         goto end;
4092
4093     testresult = 1;
4094
4095  end:
4096     SSL_SESSION_free(clientpsk);
4097     SSL_SESSION_free(serverpsk);
4098     clientpsk = serverpsk = NULL;
4099     SSL_SESSION_free(sess);
4100     SSL_free(serverssl);
4101     SSL_free(clientssl);
4102     SSL_CTX_free(sctx);
4103     SSL_CTX_free(cctx);
4104     return testresult;
4105 }
4106
4107 /*
4108  * Test that a server attempting to read early data can handle a connection
4109  * from a client where the early data is not acceptable.
4110  */
4111 static int test_early_data_skip(int idx)
4112 {
4113     return early_data_skip_helper(0,
4114                                   idx % OSSL_NELEM(ciphersuites),
4115                                   idx / OSSL_NELEM(ciphersuites));
4116 }
4117
4118 /*
4119  * Test that a server attempting to read early data can handle a connection
4120  * from a client where an HRR occurs.
4121  */
4122 static int test_early_data_skip_hrr(int idx)
4123 {
4124     return early_data_skip_helper(1,
4125                                   idx % OSSL_NELEM(ciphersuites),
4126                                   idx / OSSL_NELEM(ciphersuites));
4127 }
4128
4129 /*
4130  * Test that a server attempting to read early data can handle a connection
4131  * from a client where an HRR occurs and correctly fails if early_data is sent
4132  * after the HRR
4133  */
4134 static int test_early_data_skip_hrr_fail(int idx)
4135 {
4136     return early_data_skip_helper(2,
4137                                   idx % OSSL_NELEM(ciphersuites),
4138                                   idx / OSSL_NELEM(ciphersuites));
4139 }
4140
4141 /*
4142  * Test that a server attempting to read early data will abort if it tries to
4143  * skip over too much.
4144  */
4145 static int test_early_data_skip_abort(int idx)
4146 {
4147     return early_data_skip_helper(3,
4148                                   idx % OSSL_NELEM(ciphersuites),
4149                                   idx / OSSL_NELEM(ciphersuites));
4150 }
4151
4152 /*
4153  * Test that a server attempting to read early data can handle a connection
4154  * from a client that doesn't send any.
4155  */
4156 static int test_early_data_not_sent(int idx)
4157 {
4158     SSL_CTX *cctx = NULL, *sctx = NULL;
4159     SSL *clientssl = NULL, *serverssl = NULL;
4160     int testresult = 0;
4161     SSL_SESSION *sess = NULL;
4162     unsigned char buf[20];
4163     size_t readbytes, written;
4164
4165     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4166                                         &serverssl, &sess, idx,
4167                                         SHA384_DIGEST_LENGTH)))
4168         goto end;
4169
4170     /* Write some data - should block due to handshake with server */
4171     SSL_set_connect_state(clientssl);
4172     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4173         goto end;
4174
4175     /* Server should detect that early data has not been sent */
4176     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4177                                          &readbytes),
4178                      SSL_READ_EARLY_DATA_FINISH)
4179             || !TEST_size_t_eq(readbytes, 0)
4180             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4181                             SSL_EARLY_DATA_NOT_SENT)
4182             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4183                             SSL_EARLY_DATA_NOT_SENT))
4184         goto end;
4185
4186     /* Continue writing the message we started earlier */
4187     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4188             || !TEST_size_t_eq(written, strlen(MSG1))
4189             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4190             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4191             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
4192             || !TEST_size_t_eq(written, strlen(MSG2)))
4193         goto end;
4194
4195     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4196             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4197         goto end;
4198
4199     testresult = 1;
4200
4201  end:
4202     SSL_SESSION_free(sess);
4203     SSL_SESSION_free(clientpsk);
4204     SSL_SESSION_free(serverpsk);
4205     clientpsk = serverpsk = NULL;
4206     SSL_free(serverssl);
4207     SSL_free(clientssl);
4208     SSL_CTX_free(sctx);
4209     SSL_CTX_free(cctx);
4210     return testresult;
4211 }
4212
4213 static const char *servalpn;
4214
4215 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
4216                           unsigned char *outlen, const unsigned char *in,
4217                           unsigned int inlen, void *arg)
4218 {
4219     unsigned int protlen = 0;
4220     const unsigned char *prot;
4221
4222     for (prot = in; prot < in + inlen; prot += protlen) {
4223         protlen = *prot++;
4224         if (in + inlen < prot + protlen)
4225             return SSL_TLSEXT_ERR_NOACK;
4226
4227         if (protlen == strlen(servalpn)
4228                 && memcmp(prot, servalpn, protlen) == 0) {
4229             *out = prot;
4230             *outlen = protlen;
4231             return SSL_TLSEXT_ERR_OK;
4232         }
4233     }
4234
4235     return SSL_TLSEXT_ERR_NOACK;
4236 }
4237
4238 /* Test that a PSK can be used to send early_data */
4239 static int test_early_data_psk(int idx)
4240 {
4241     SSL_CTX *cctx = NULL, *sctx = NULL;
4242     SSL *clientssl = NULL, *serverssl = NULL;
4243     int testresult = 0;
4244     SSL_SESSION *sess = NULL;
4245     unsigned char alpnlist[] = {
4246         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
4247         'l', 'p', 'n'
4248     };
4249 #define GOODALPNLEN     9
4250 #define BADALPNLEN      8
4251 #define GOODALPN        (alpnlist)
4252 #define BADALPN         (alpnlist + GOODALPNLEN)
4253     int err = 0;
4254     unsigned char buf[20];
4255     size_t readbytes, written;
4256     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
4257     int edstatus = SSL_EARLY_DATA_ACCEPTED;
4258
4259     /* We always set this up with a final parameter of "2" for PSK */
4260     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4261                                         &serverssl, &sess, 2,
4262                                         SHA384_DIGEST_LENGTH)))
4263         goto end;
4264
4265     servalpn = "goodalpn";
4266
4267     /*
4268      * Note: There is no test for inconsistent SNI with late client detection.
4269      * This is because servers do not acknowledge SNI even if they are using
4270      * it in a resumption handshake - so it is not actually possible for a
4271      * client to detect a problem.
4272      */
4273     switch (idx) {
4274     case 0:
4275         /* Set inconsistent SNI (early client detection) */
4276         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
4277         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4278                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
4279             goto end;
4280         break;
4281
4282     case 1:
4283         /* Set inconsistent ALPN (early client detection) */
4284         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
4285         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
4286         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
4287                                                       GOODALPNLEN))
4288                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
4289                                                    BADALPNLEN)))
4290             goto end;
4291         break;
4292
4293     case 2:
4294         /*
4295          * Set invalid protocol version. Technically this affects PSKs without
4296          * early_data too, but we test it here because it is similar to the
4297          * SNI/ALPN consistency tests.
4298          */
4299         err = SSL_R_BAD_PSK;
4300         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
4301             goto end;
4302         break;
4303
4304     case 3:
4305         /*
4306          * Set inconsistent SNI (server side). In this case the connection
4307          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
4308          * is associated with each handshake - not the session. Therefore it
4309          * should not matter that we used a different server name last time.
4310          */
4311         SSL_SESSION_free(serverpsk);
4312         serverpsk = SSL_SESSION_dup(clientpsk);
4313         if (!TEST_ptr(serverpsk)
4314                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
4315             goto end;
4316         /* Fall through */
4317     case 4:
4318         /* Set consistent SNI */
4319         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4320                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
4321                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
4322                                 hostname_cb)))
4323             goto end;
4324         break;
4325
4326     case 5:
4327         /*
4328          * Set inconsistent ALPN (server detected). In this case the connection
4329          * will succeed but reject early_data.
4330          */
4331         servalpn = "badalpn";
4332         edstatus = SSL_EARLY_DATA_REJECTED;
4333         readearlyres = SSL_READ_EARLY_DATA_FINISH;
4334         /* Fall through */
4335     case 6:
4336         /*
4337          * Set consistent ALPN.
4338          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
4339          * accepts a list of protos (each one length prefixed).
4340          * SSL_set1_alpn_selected accepts a single protocol (not length
4341          * prefixed)
4342          */
4343         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
4344                                                       GOODALPNLEN - 1))
4345                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
4346                                                    GOODALPNLEN)))
4347             goto end;
4348
4349         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4350         break;
4351
4352     case 7:
4353         /* Set inconsistent ALPN (late client detection) */
4354         SSL_SESSION_free(serverpsk);
4355         serverpsk = SSL_SESSION_dup(clientpsk);
4356         if (!TEST_ptr(serverpsk)
4357                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
4358                                                              BADALPN + 1,
4359                                                              BADALPNLEN - 1))
4360                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
4361                                                              GOODALPN + 1,
4362                                                              GOODALPNLEN - 1))
4363                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
4364                                                    sizeof(alpnlist))))
4365             goto end;
4366         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4367         edstatus = SSL_EARLY_DATA_ACCEPTED;
4368         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
4369         /* SSL_connect() call should fail */
4370         connectres = -1;
4371         break;
4372
4373     default:
4374         TEST_error("Bad test index");
4375         goto end;
4376     }
4377
4378     SSL_set_connect_state(clientssl);
4379     if (err != 0) {
4380         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4381                                             &written))
4382                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
4383                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
4384             goto end;
4385     } else {
4386         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4387                                             &written)))
4388             goto end;
4389
4390         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4391                                              &readbytes), readearlyres)
4392                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
4393                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
4394                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
4395                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
4396             goto end;
4397     }
4398
4399     testresult = 1;
4400
4401  end:
4402     SSL_SESSION_free(sess);
4403     SSL_SESSION_free(clientpsk);
4404     SSL_SESSION_free(serverpsk);
4405     clientpsk = serverpsk = NULL;
4406     SSL_free(serverssl);
4407     SSL_free(clientssl);
4408     SSL_CTX_free(sctx);
4409     SSL_CTX_free(cctx);
4410     return testresult;
4411 }
4412
4413 /*
4414  * Test TLSv1.3 PSK can be used to send early_data with all 5 ciphersuites
4415  * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
4416  * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
4417  * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4418  * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
4419  * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
4420  */
4421 static int test_early_data_psk_with_all_ciphers(int idx)
4422 {
4423     SSL_CTX *cctx = NULL, *sctx = NULL;
4424     SSL *clientssl = NULL, *serverssl = NULL;
4425     int testresult = 0;
4426     SSL_SESSION *sess = NULL;
4427     unsigned char buf[20];
4428     size_t readbytes, written;
4429     const SSL_CIPHER *cipher;
4430     const char *cipher_str[] = {
4431         TLS1_3_RFC_AES_128_GCM_SHA256,
4432         TLS1_3_RFC_AES_256_GCM_SHA384,
4433 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4434         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4435 # else
4436         NULL,
4437 # endif
4438         TLS1_3_RFC_AES_128_CCM_SHA256,
4439         TLS1_3_RFC_AES_128_CCM_8_SHA256
4440     };
4441     const unsigned char *cipher_bytes[] = {
4442         TLS13_AES_128_GCM_SHA256_BYTES,
4443         TLS13_AES_256_GCM_SHA384_BYTES,
4444 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4445         TLS13_CHACHA20_POLY1305_SHA256_BYTES,
4446 # else
4447         NULL,
4448 # endif
4449         TLS13_AES_128_CCM_SHA256_BYTES,
4450         TLS13_AES_128_CCM_8_SHA256_BYTES
4451     };
4452
4453     if (cipher_str[idx] == NULL)
4454         return 1;
4455     /* Skip ChaCha20Poly1305 as currently FIPS module does not support it */
4456     if (idx == 2 && is_fips == 1)
4457         return 1;
4458
4459     /* We always set this up with a final parameter of "2" for PSK */
4460     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4461                                         &serverssl, &sess, 2,
4462                                         SHA384_DIGEST_LENGTH)))
4463         goto end;
4464
4465     if (idx == 4) {
4466         /* CCM8 ciphers are considered low security due to their short tag */
4467         SSL_set_security_level(clientssl, 0);
4468         SSL_set_security_level(serverssl, 0);
4469     }
4470
4471     if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
4472             || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
4473         goto end;
4474
4475     /*
4476      * 'setupearly_data_test' creates only one instance of SSL_SESSION
4477      * and assigns to both client and server with incremented reference
4478      * and the same instance is updated in 'sess'.
4479      * So updating ciphersuite in 'sess' which will get reflected in
4480      * PSK handshake using psk use sess and find sess cb.
4481      */
4482     cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
4483     if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
4484         goto end;
4485
4486     SSL_set_connect_state(clientssl);
4487     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4488                                         &written)))
4489         goto end;
4490
4491     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4492                                          &readbytes),
4493                                          SSL_READ_EARLY_DATA_SUCCESS)
4494             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4495             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4496                                                       SSL_EARLY_DATA_ACCEPTED)
4497             || !TEST_int_eq(SSL_connect(clientssl), 1)
4498             || !TEST_int_eq(SSL_accept(serverssl), 1))
4499         goto end;
4500
4501     /* Send some normal data from client to server */
4502     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4503             || !TEST_size_t_eq(written, strlen(MSG2)))
4504         goto end;
4505
4506     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4507             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4508         goto end;
4509
4510     testresult = 1;
4511  end:
4512     SSL_SESSION_free(sess);
4513     SSL_SESSION_free(clientpsk);
4514     SSL_SESSION_free(serverpsk);
4515     clientpsk = serverpsk = NULL;
4516     if (clientssl != NULL)
4517         SSL_shutdown(clientssl);
4518     if (serverssl != NULL)
4519         SSL_shutdown(serverssl);
4520     SSL_free(serverssl);
4521     SSL_free(clientssl);
4522     SSL_CTX_free(sctx);
4523     SSL_CTX_free(cctx);
4524     return testresult;
4525 }
4526
4527 /*
4528  * Test that a server that doesn't try to read early data can handle a
4529  * client sending some.
4530  */
4531 static int test_early_data_not_expected(int idx)
4532 {
4533     SSL_CTX *cctx = NULL, *sctx = NULL;
4534     SSL *clientssl = NULL, *serverssl = NULL;
4535     int testresult = 0;
4536     SSL_SESSION *sess = NULL;
4537     unsigned char buf[20];
4538     size_t readbytes, written;
4539
4540     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4541                                         &serverssl, &sess, idx,
4542                                         SHA384_DIGEST_LENGTH)))
4543         goto end;
4544
4545     /* Write some early data */
4546     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4547                                         &written)))
4548         goto end;
4549
4550     /*
4551      * Server should skip over early data and then block waiting for client to
4552      * continue handshake
4553      */
4554     if (!TEST_int_le(SSL_accept(serverssl), 0)
4555      || !TEST_int_gt(SSL_connect(clientssl), 0)
4556      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4557                      SSL_EARLY_DATA_REJECTED)
4558      || !TEST_int_gt(SSL_accept(serverssl), 0)
4559      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4560                      SSL_EARLY_DATA_REJECTED))
4561         goto end;
4562
4563     /* Send some normal data from client to server */
4564     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4565             || !TEST_size_t_eq(written, strlen(MSG2)))
4566         goto end;
4567
4568     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4569             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4570         goto end;
4571
4572     testresult = 1;
4573
4574  end:
4575     SSL_SESSION_free(sess);
4576     SSL_SESSION_free(clientpsk);
4577     SSL_SESSION_free(serverpsk);
4578     clientpsk = serverpsk = NULL;
4579     SSL_free(serverssl);
4580     SSL_free(clientssl);
4581     SSL_CTX_free(sctx);
4582     SSL_CTX_free(cctx);
4583     return testresult;
4584 }
4585
4586
4587 # ifndef OPENSSL_NO_TLS1_2
4588 /*
4589  * Test that a server attempting to read early data can handle a connection
4590  * from a TLSv1.2 client.
4591  */
4592 static int test_early_data_tls1_2(int idx)
4593 {
4594     SSL_CTX *cctx = NULL, *sctx = NULL;
4595     SSL *clientssl = NULL, *serverssl = NULL;
4596     int testresult = 0;
4597     unsigned char buf[20];
4598     size_t readbytes, written;
4599
4600     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4601                                         &serverssl, NULL, idx,
4602                                         SHA384_DIGEST_LENGTH)))
4603         goto end;
4604
4605     /* Write some data - should block due to handshake with server */
4606     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
4607     SSL_set_connect_state(clientssl);
4608     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4609         goto end;
4610
4611     /*
4612      * Server should do TLSv1.2 handshake. First it will block waiting for more
4613      * messages from client after ServerDone. Then SSL_read_early_data should
4614      * finish and detect that early data has not been sent
4615      */
4616     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4617                                          &readbytes),
4618                      SSL_READ_EARLY_DATA_ERROR))
4619         goto end;
4620
4621     /*
4622      * Continue writing the message we started earlier. Will still block waiting
4623      * for the CCS/Finished from server
4624      */
4625     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4626             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4627                                                 &readbytes),
4628                             SSL_READ_EARLY_DATA_FINISH)
4629             || !TEST_size_t_eq(readbytes, 0)
4630             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4631                             SSL_EARLY_DATA_NOT_SENT))
4632         goto end;
4633
4634     /* Continue writing the message we started earlier */
4635     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4636             || !TEST_size_t_eq(written, strlen(MSG1))
4637             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4638                             SSL_EARLY_DATA_NOT_SENT)
4639             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4640             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4641             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
4642             || !TEST_size_t_eq(written, strlen(MSG2))
4643             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
4644             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4645         goto end;
4646
4647     testresult = 1;
4648
4649  end:
4650     SSL_SESSION_free(clientpsk);
4651     SSL_SESSION_free(serverpsk);
4652     clientpsk = serverpsk = NULL;
4653     SSL_free(serverssl);
4654     SSL_free(clientssl);
4655     SSL_CTX_free(sctx);
4656     SSL_CTX_free(cctx);
4657
4658     return testresult;
4659 }
4660 # endif /* OPENSSL_NO_TLS1_2 */
4661
4662 /*
4663  * Test configuring the TLSv1.3 ciphersuites
4664  *
4665  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
4666  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
4667  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
4668  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
4669  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4670  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4671  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
4672  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
4673  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
4674  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
4675  */
4676 static int test_set_ciphersuite(int idx)
4677 {
4678     SSL_CTX *cctx = NULL, *sctx = NULL;
4679     SSL *clientssl = NULL, *serverssl = NULL;
4680     int testresult = 0;
4681
4682     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4683                                        TLS_client_method(), TLS1_VERSION, 0,
4684                                        &sctx, &cctx, cert, privkey))
4685             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4686                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
4687         goto end;
4688
4689     if (idx >=4 && idx <= 7) {
4690         /* SSL_CTX explicit cipher list */
4691         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
4692             goto end;
4693     }
4694
4695     if (idx == 0 || idx == 4) {
4696         /* Default ciphersuite */
4697         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4698                                                 "TLS_AES_128_GCM_SHA256")))
4699             goto end;
4700     } else if (idx == 1 || idx == 5) {
4701         /* Non default ciphersuite */
4702         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4703                                                 "TLS_AES_128_CCM_SHA256")))
4704             goto end;
4705     }
4706
4707     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4708                                           &clientssl, NULL, NULL)))
4709         goto end;
4710
4711     if (idx == 8 || idx == 9) {
4712         /* SSL explicit cipher list */
4713         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
4714             goto end;
4715     }
4716
4717     if (idx == 2 || idx == 6 || idx == 8) {
4718         /* Default ciphersuite */
4719         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4720                                             "TLS_AES_128_GCM_SHA256")))
4721             goto end;
4722     } else if (idx == 3 || idx == 7 || idx == 9) {
4723         /* Non default ciphersuite */
4724         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4725                                             "TLS_AES_128_CCM_SHA256")))
4726             goto end;
4727     }
4728
4729     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4730         goto end;
4731
4732     testresult = 1;
4733
4734  end:
4735     SSL_free(serverssl);
4736     SSL_free(clientssl);
4737     SSL_CTX_free(sctx);
4738     SSL_CTX_free(cctx);
4739
4740     return testresult;
4741 }
4742
4743 static int test_ciphersuite_change(void)
4744 {
4745     SSL_CTX *cctx = NULL, *sctx = NULL;
4746     SSL *clientssl = NULL, *serverssl = NULL;
4747     SSL_SESSION *clntsess = NULL;
4748     int testresult = 0;
4749     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
4750
4751     /* Create a session based on SHA-256 */
4752     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4753                                        TLS_client_method(), TLS1_VERSION, 0,
4754                                        &sctx, &cctx, cert, privkey))
4755             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4756                                                    "TLS_AES_128_GCM_SHA256:"
4757                                                    "TLS_AES_256_GCM_SHA384:"
4758                                                    "TLS_AES_128_CCM_SHA256"))
4759             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4760                                                    "TLS_AES_128_GCM_SHA256")))
4761         goto end;
4762
4763     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4764                                       NULL, NULL))
4765             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4766                                                 SSL_ERROR_NONE)))
4767         goto end;
4768
4769     clntsess = SSL_get1_session(clientssl);
4770     /* Save for later */
4771     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
4772     SSL_shutdown(clientssl);
4773     SSL_shutdown(serverssl);
4774     SSL_free(serverssl);
4775     SSL_free(clientssl);
4776     serverssl = clientssl = NULL;
4777
4778     /* Check we can resume a session with a different SHA-256 ciphersuite */
4779     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4780                                             "TLS_AES_128_CCM_SHA256"))
4781             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4782                                              &clientssl, NULL, NULL))
4783             || !TEST_true(SSL_set_session(clientssl, clntsess))
4784             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4785                                                 SSL_ERROR_NONE))
4786             || !TEST_true(SSL_session_reused(clientssl)))
4787         goto end;
4788
4789     SSL_SESSION_free(clntsess);
4790     clntsess = SSL_get1_session(clientssl);
4791     SSL_shutdown(clientssl);
4792     SSL_shutdown(serverssl);
4793     SSL_free(serverssl);
4794     SSL_free(clientssl);
4795     serverssl = clientssl = NULL;
4796
4797     /*
4798      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
4799      * succeeds but does not resume.
4800      */
4801     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4802             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4803                                              NULL, NULL))
4804             || !TEST_true(SSL_set_session(clientssl, clntsess))
4805             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4806                                                 SSL_ERROR_SSL))
4807             || !TEST_false(SSL_session_reused(clientssl)))
4808         goto end;
4809
4810     SSL_SESSION_free(clntsess);
4811     clntsess = NULL;
4812     SSL_shutdown(clientssl);
4813     SSL_shutdown(serverssl);
4814     SSL_free(serverssl);
4815     SSL_free(clientssl);
4816     serverssl = clientssl = NULL;
4817
4818     /* Create a session based on SHA384 */
4819     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4820             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4821                                           &clientssl, NULL, NULL))
4822             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4823                                                 SSL_ERROR_NONE)))
4824         goto end;
4825
4826     clntsess = SSL_get1_session(clientssl);
4827     SSL_shutdown(clientssl);
4828     SSL_shutdown(serverssl);
4829     SSL_free(serverssl);
4830     SSL_free(clientssl);
4831     serverssl = clientssl = NULL;
4832
4833     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4834                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
4835             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4836                                                    "TLS_AES_256_GCM_SHA384"))
4837             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4838                                              NULL, NULL))
4839             || !TEST_true(SSL_set_session(clientssl, clntsess))
4840                /*
4841                 * We use SSL_ERROR_WANT_READ below so that we can pause the
4842                 * connection after the initial ClientHello has been sent to
4843                 * enable us to make some session changes.
4844                 */
4845             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4846                                                 SSL_ERROR_WANT_READ)))
4847         goto end;
4848
4849     /* Trick the client into thinking this session is for a different digest */
4850     clntsess->cipher = aes_128_gcm_sha256;
4851     clntsess->cipher_id = clntsess->cipher->id;
4852
4853     /*
4854      * Continue the previously started connection. Server has selected a SHA-384
4855      * ciphersuite, but client thinks the session is for SHA-256, so it should
4856      * bail out.
4857      */
4858     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4859                                                 SSL_ERROR_SSL))
4860             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4861                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4862         goto end;
4863
4864     testresult = 1;
4865
4866  end:
4867     SSL_SESSION_free(clntsess);
4868     SSL_free(serverssl);
4869     SSL_free(clientssl);
4870     SSL_CTX_free(sctx);
4871     SSL_CTX_free(cctx);
4872
4873     return testresult;
4874 }
4875
4876 /*
4877  * Test TLSv1.3 Key exchange
4878  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4879  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4880  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4881  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4882  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4883  * Test 5 = Test NID_X448 with TLSv1.3 client and server
4884  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4885  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4886  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4887  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4888  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4889  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4890  * Test 12 = Test all ECDHE with TLSv1.2 client and server
4891  * Test 13 = Test all FFDHE with TLSv1.2 client and server
4892  */
4893 # ifndef OPENSSL_NO_EC
4894 static int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
4895                                    NID_secp521r1,
4896 #  ifndef OPENSSL_NO_ECX
4897                                    NID_X25519, NID_X448
4898 #  endif
4899                                    };
4900 # endif
4901 # ifndef OPENSSL_NO_DH
4902 static int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4903                                    NID_ffdhe6144, NID_ffdhe8192};
4904 # endif
4905 static int test_key_exchange(int idx)
4906 {
4907     SSL_CTX *sctx = NULL, *cctx = NULL;
4908     SSL *serverssl = NULL, *clientssl = NULL;
4909     int testresult = 0;
4910     int kexch_alg;
4911     int *kexch_groups = &kexch_alg;
4912     int kexch_groups_size = 1;
4913     int max_version = TLS1_3_VERSION;
4914     char *kexch_name0 = NULL;
4915
4916     switch (idx) {
4917 # ifndef OPENSSL_NO_EC
4918 # ifndef OPENSSL_NO_TLS1_2
4919         case 12:
4920             max_version = TLS1_2_VERSION;
4921 # endif
4922             /* Fall through */
4923         case 0:
4924             kexch_groups = ecdhe_kexch_groups;
4925             kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
4926             kexch_name0 = "secp256r1";
4927             break;
4928         case 1:
4929             kexch_alg = NID_X9_62_prime256v1;
4930             kexch_name0 = "secp256r1";
4931             break;
4932         case 2:
4933             kexch_alg = NID_secp384r1;
4934             kexch_name0 = "secp384r1";
4935             break;
4936         case 3:
4937             kexch_alg = NID_secp521r1;
4938             kexch_name0 = "secp521r1";
4939             break;
4940 #  ifndef OPENSSL_NO_ECX
4941         case 4:
4942             kexch_alg = NID_X25519;
4943             kexch_name0 = "x25519";
4944             break;
4945         case 5:
4946             kexch_alg = NID_X448;
4947             kexch_name0 = "x448";
4948             break;
4949 #  endif
4950 # endif
4951 # ifndef OPENSSL_NO_DH
4952 # ifndef OPENSSL_NO_TLS1_2
4953         case 13:
4954             max_version = TLS1_2_VERSION;
4955             kexch_name0 = "ffdhe2048";
4956 # endif
4957             /* Fall through */
4958         case 6:
4959             kexch_groups = ffdhe_kexch_groups;
4960             kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
4961             kexch_name0 = "ffdhe2048";
4962             break;
4963         case 7:
4964             kexch_alg = NID_ffdhe2048;
4965             kexch_name0 = "ffdhe2048";
4966             break;
4967         case 8:
4968             kexch_alg = NID_ffdhe3072;
4969             kexch_name0 = "ffdhe3072";
4970             break;
4971         case 9:
4972             kexch_alg = NID_ffdhe4096;
4973             kexch_name0 = "ffdhe4096";
4974             break;
4975         case 10:
4976             kexch_alg = NID_ffdhe6144;
4977             kexch_name0 = "ffdhe6144";
4978             break;
4979         case 11:
4980             kexch_alg = NID_ffdhe8192;
4981             kexch_name0 = "ffdhe8192";
4982             break;
4983 # endif
4984         default:
4985             /* We're skipping this test */
4986             return 1;
4987     }
4988
4989     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4990                                        TLS_client_method(), TLS1_VERSION,
4991                                        max_version, &sctx, &cctx, cert,
4992                                        privkey)))
4993         goto end;
4994
4995     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
4996                    TLS1_3_RFC_AES_128_GCM_SHA256)))
4997         goto end;
4998
4999     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5000                    TLS1_3_RFC_AES_128_GCM_SHA256)))
5001         goto end;
5002
5003     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5004                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5005                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5006             || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5007         goto end;
5008
5009     /*
5010      * Must include an EC ciphersuite so that we send supported groups in
5011      * TLSv1.2
5012      */
5013 # ifndef OPENSSL_NO_TLS1_2
5014     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5015                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5016                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5017         goto end;
5018 # endif
5019
5020     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5021                                              NULL, NULL)))
5022         goto end;
5023
5024     if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
5025         || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
5026         goto end;
5027
5028     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5029         goto end;
5030
5031     /*
5032      * If Handshake succeeds the negotiated kexch alg should be the first one in
5033      * configured, except in the case of FFDHE groups (idx 13), which are
5034      * TLSv1.3 only so we expect no shared group to exist.
5035      */
5036     if (!TEST_int_eq(SSL_get_shared_group(serverssl, 0),
5037                      idx == 13 ? 0 : kexch_groups[0]))
5038         goto end;
5039
5040     if (!TEST_str_eq(SSL_group_to_name(serverssl, kexch_groups[0]),
5041                      kexch_name0))
5042         goto end;
5043
5044     /* We don't implement RFC 7919 named groups for TLS 1.2. */
5045     if (idx != 13) {
5046         if (!TEST_str_eq(SSL_get0_group_name(serverssl), kexch_name0)
5047             || !TEST_str_eq(SSL_get0_group_name(clientssl), kexch_name0))
5048             goto end;
5049         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), kexch_groups[0]))
5050             goto end;
5051         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), kexch_groups[0]))
5052             goto end;
5053     }
5054
5055     testresult = 1;
5056  end:
5057     SSL_free(serverssl);
5058     SSL_free(clientssl);
5059     SSL_CTX_free(sctx);
5060     SSL_CTX_free(cctx);
5061     return testresult;
5062 }
5063
5064 # if !defined(OPENSSL_NO_TLS1_2) \
5065      && !defined(OPENSSL_NO_EC)  \
5066      && !defined(OPENSSL_NO_DH)
5067 static int set_ssl_groups(SSL *serverssl, SSL *clientssl, int clientmulti,
5068                           int isecdhe, int idx)
5069 {
5070     int kexch_alg;
5071     int *kexch_groups = &kexch_alg;
5072     int numec, numff;
5073
5074     numec = OSSL_NELEM(ecdhe_kexch_groups);
5075     numff = OSSL_NELEM(ffdhe_kexch_groups);
5076     if (isecdhe)
5077         kexch_alg = ecdhe_kexch_groups[idx];
5078     else
5079         kexch_alg = ffdhe_kexch_groups[idx];
5080
5081     if (clientmulti) {
5082         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, 1)))
5083             return 0;
5084         if (isecdhe) {
5085             if (!TEST_true(SSL_set1_groups(clientssl, ecdhe_kexch_groups,
5086                                            numec)))
5087                 return 0;
5088         } else {
5089             if (!TEST_true(SSL_set1_groups(clientssl, ffdhe_kexch_groups,
5090                                            numff)))
5091                 return 0;
5092         }
5093     } else {
5094         if (!TEST_true(SSL_set1_groups(clientssl, kexch_groups, 1)))
5095             return 0;
5096         if (isecdhe) {
5097             if (!TEST_true(SSL_set1_groups(serverssl, ecdhe_kexch_groups,
5098                                            numec)))
5099                 return 0;
5100         } else {
5101             if (!TEST_true(SSL_set1_groups(serverssl, ffdhe_kexch_groups,
5102                                            numff)))
5103                 return 0;
5104         }
5105     }
5106     return 1;
5107 }
5108
5109 /*-
5110  * Test the SSL_get_negotiated_group() API across a battery of scenarios.
5111  * Run through both the ECDHE and FFDHE group lists used in the previous
5112  * test, for both TLS 1.2 and TLS 1.3, negotiating each group in turn,
5113  * confirming the expected result; then perform a resumption handshake
5114  * while offering the same group list, and another resumption handshake
5115  * offering a different group list.  The returned value should be the
5116  * negotiated group for the initial handshake; for TLS 1.3 resumption
5117  * handshakes the returned value will be negotiated on the resumption
5118  * handshake itself, but for TLS 1.2 resumption handshakes the value will
5119  * be cached in the session from the original handshake, regardless of what
5120  * was offered in the resumption ClientHello.
5121  *
5122  * Using E for the number of EC groups and F for the number of FF groups:
5123  * E tests of ECDHE with TLS 1.3, server only has one group
5124  * F tests of FFDHE with TLS 1.3, server only has one group
5125  * E tests of ECDHE with TLS 1.2, server only has one group
5126  * F tests of FFDHE with TLS 1.2, server only has one group
5127  * E tests of ECDHE with TLS 1.3, client sends only one group
5128  * F tests of FFDHE with TLS 1.3, client sends only one group
5129  * E tests of ECDHE with TLS 1.2, client sends only one group
5130  * F tests of FFDHE with TLS 1.2, client sends only one group
5131  */
5132 static int test_negotiated_group(int idx)
5133 {
5134     int clientmulti, istls13, isecdhe, numec, numff, numgroups;
5135     int expectednid;
5136     SSL_CTX *sctx = NULL, *cctx = NULL;
5137     SSL *serverssl = NULL, *clientssl = NULL;
5138     SSL_SESSION *origsess = NULL;
5139     int testresult = 0;
5140     int kexch_alg;
5141     int max_version = TLS1_3_VERSION;
5142
5143     numec = OSSL_NELEM(ecdhe_kexch_groups);
5144     numff = OSSL_NELEM(ffdhe_kexch_groups);
5145     numgroups = numec + numff;
5146     clientmulti = (idx < 2 * numgroups);
5147     idx = idx % (2 * numgroups);
5148     istls13 = (idx < numgroups);
5149     idx = idx % numgroups;
5150     isecdhe = (idx < numec);
5151     if (!isecdhe)
5152         idx -= numec;
5153     /* Now 'idx' is an index into ecdhe_kexch_groups or ffdhe_kexch_groups */
5154     if (isecdhe)
5155         kexch_alg = ecdhe_kexch_groups[idx];
5156     else
5157         kexch_alg = ffdhe_kexch_groups[idx];
5158     /* We expect nothing for the unimplemented TLS 1.2 FFDHE named groups */
5159     if (!istls13 && !isecdhe)
5160         expectednid = NID_undef;
5161     else
5162         expectednid = kexch_alg;
5163
5164     if (!istls13)
5165         max_version = TLS1_2_VERSION;
5166
5167     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5168                                        TLS_client_method(), TLS1_VERSION,
5169                                        max_version, &sctx, &cctx, cert,
5170                                        privkey)))
5171         goto end;
5172
5173     /*
5174      * Force (EC)DHE ciphers for TLS 1.2.
5175      * Be sure to enable auto tmp DH so that FFDHE can succeed.
5176      */
5177     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5178                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5179                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5180             || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5181         goto end;
5182     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5183                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5184                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5185         goto end;
5186
5187     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5188                                              NULL, NULL)))
5189         goto end;
5190
5191     if (!TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe,
5192                                   idx)))
5193         goto end;
5194
5195     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5196         goto end;
5197
5198     /* Initial handshake; always the configured one */
5199     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5200             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5201         goto end;
5202
5203     if (!TEST_ptr((origsess = SSL_get1_session(clientssl))))
5204         goto end;
5205
5206     SSL_shutdown(clientssl);
5207     SSL_shutdown(serverssl);
5208     SSL_free(serverssl);
5209     SSL_free(clientssl);
5210     serverssl = clientssl = NULL;
5211
5212     /* First resumption attempt; use the same config as initial handshake */
5213     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5214                                              NULL, NULL))
5215             || !TEST_true(SSL_set_session(clientssl, origsess))
5216             || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5217                                          isecdhe, idx)))
5218         goto end;
5219
5220     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5221             || !TEST_true(SSL_session_reused(clientssl)))
5222         goto end;
5223
5224     /* Still had better agree, since nothing changed... */
5225     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5226             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5227         goto end;
5228
5229     SSL_shutdown(clientssl);
5230     SSL_shutdown(serverssl);
5231     SSL_free(serverssl);
5232     SSL_free(clientssl);
5233     serverssl = clientssl = NULL;
5234
5235     /*-
5236      * Second resumption attempt
5237      * The party that picks one group changes it, which we effectuate by
5238      * changing 'idx' and updating what we expect.
5239      */
5240     if (idx == 0)
5241         idx = 1;
5242     else
5243         idx--;
5244     if (istls13) {
5245         if (isecdhe)
5246             expectednid = ecdhe_kexch_groups[idx];
5247         else
5248             expectednid = ffdhe_kexch_groups[idx];
5249         /* Verify that we are changing what we expect. */
5250         if (!TEST_int_ne(expectednid, kexch_alg))
5251             goto end;
5252     } else {
5253         /* TLS 1.2 only supports named groups for ECDHE. */
5254         if (isecdhe)
5255             expectednid = kexch_alg;
5256         else
5257             expectednid = 0;
5258     }
5259     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5260                                              NULL, NULL))
5261             || !TEST_true(SSL_set_session(clientssl, origsess))
5262             || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5263                                          isecdhe, idx)))
5264         goto end;
5265
5266     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5267             || !TEST_true(SSL_session_reused(clientssl)))
5268         goto end;
5269
5270     /* Check that we get what we expected */
5271     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5272             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5273         goto end;
5274
5275     testresult = 1;
5276  end:
5277     SSL_free(serverssl);
5278     SSL_free(clientssl);
5279     SSL_CTX_free(sctx);
5280     SSL_CTX_free(cctx);
5281     SSL_SESSION_free(origsess);
5282     return testresult;
5283 }
5284 # endif /* !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) */
5285
5286 /*
5287  * Test TLSv1.3 Cipher Suite
5288  * Test 0 = Set TLS1.3 cipher on context
5289  * Test 1 = Set TLS1.3 cipher on SSL
5290  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
5291  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
5292  */
5293 static int test_tls13_ciphersuite(int idx)
5294 {
5295     SSL_CTX *sctx = NULL, *cctx = NULL;
5296     SSL *serverssl = NULL, *clientssl = NULL;
5297     static const struct {
5298         const char *ciphername;
5299         int fipscapable;
5300         int low_security;
5301     } t13_ciphers[] = {
5302         { TLS1_3_RFC_AES_128_GCM_SHA256, 1, 0 },
5303         { TLS1_3_RFC_AES_256_GCM_SHA384, 1, 0 },
5304         { TLS1_3_RFC_AES_128_CCM_SHA256, 1, 0 },
5305 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5306         { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5307         { TLS1_3_RFC_AES_256_GCM_SHA384
5308           ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5309 # endif
5310         /* CCM8 ciphers are considered low security due to their short tag */
5311         { TLS1_3_RFC_AES_128_CCM_8_SHA256
5312           ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1, 1 }
5313     };
5314     const char *t13_cipher = NULL;
5315     const char *t12_cipher = NULL;
5316     const char *negotiated_scipher;
5317     const char *negotiated_ccipher;
5318     int set_at_ctx = 0;
5319     int set_at_ssl = 0;
5320     int testresult = 0;
5321     int max_ver;
5322     size_t i;
5323
5324     switch (idx) {
5325         case 0:
5326             set_at_ctx = 1;
5327             break;
5328         case 1:
5329             set_at_ssl = 1;
5330             break;
5331         case 2:
5332             set_at_ctx = 1;
5333             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5334             break;
5335         case 3:
5336             set_at_ssl = 1;
5337             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5338             break;
5339     }
5340
5341     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
5342 # ifdef OPENSSL_NO_TLS1_2
5343         if (max_ver == TLS1_2_VERSION)
5344             continue;
5345 # endif
5346         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
5347             if (is_fips && !t13_ciphers[i].fipscapable)
5348                 continue;
5349             t13_cipher = t13_ciphers[i].ciphername;
5350             if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5351                                                TLS_client_method(),
5352                                                TLS1_VERSION, max_ver,
5353                                                &sctx, &cctx, cert, privkey)))
5354                 goto end;
5355
5356             if (t13_ciphers[i].low_security) {
5357                 SSL_CTX_set_security_level(sctx, 0);
5358                 SSL_CTX_set_security_level(cctx, 0);
5359             }
5360
5361             if (set_at_ctx) {
5362                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
5363                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
5364                     goto end;
5365                 if (t12_cipher != NULL) {
5366                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
5367                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
5368                                                               t12_cipher)))
5369                         goto end;
5370                 }
5371             }
5372
5373             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5374                                               &clientssl, NULL, NULL)))
5375                 goto end;
5376
5377             if (set_at_ssl) {
5378                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
5379                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
5380                     goto end;
5381                 if (t12_cipher != NULL) {
5382                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
5383                         || !TEST_true(SSL_set_cipher_list(clientssl,
5384                                                           t12_cipher)))
5385                         goto end;
5386                 }
5387             }
5388
5389             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5390                                                  SSL_ERROR_NONE)))
5391                 goto end;
5392
5393             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5394                                                                  serverssl));
5395             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5396                                                                  clientssl));
5397             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
5398                 goto end;
5399
5400             /*
5401              * TEST_strn_eq is used below because t13_cipher can contain
5402              * multiple ciphersuites
5403              */
5404             if (max_ver == TLS1_3_VERSION
5405                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
5406                                  strlen(negotiated_scipher)))
5407                 goto end;
5408
5409 # ifndef OPENSSL_NO_TLS1_2
5410             /* Below validation is not done when t12_cipher is NULL */
5411             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
5412                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
5413                 goto end;
5414 # endif
5415
5416             SSL_free(serverssl);
5417             serverssl = NULL;
5418             SSL_free(clientssl);
5419             clientssl = NULL;
5420             SSL_CTX_free(sctx);
5421             sctx = NULL;
5422             SSL_CTX_free(cctx);
5423             cctx = NULL;
5424         }
5425     }
5426
5427     testresult = 1;
5428  end:
5429     SSL_free(serverssl);
5430     SSL_free(clientssl);
5431     SSL_CTX_free(sctx);
5432     SSL_CTX_free(cctx);
5433     return testresult;
5434 }
5435
5436 /*
5437  * Test TLSv1.3 PSKs
5438  * Test 0 = Test new style callbacks
5439  * Test 1 = Test both new and old style callbacks
5440  * Test 2 = Test old style callbacks
5441  * Test 3 = Test old style callbacks with no certificate
5442  */
5443 static int test_tls13_psk(int idx)
5444 {
5445     SSL_CTX *sctx = NULL, *cctx = NULL;
5446     SSL *serverssl = NULL, *clientssl = NULL;
5447     const SSL_CIPHER *cipher = NULL;
5448     const unsigned char key[] = {
5449         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
5450         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5451         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
5452         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
5453     };
5454     int testresult = 0;
5455
5456     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5457                                        TLS_client_method(), TLS1_VERSION, 0,
5458                                        &sctx, &cctx, idx == 3 ? NULL : cert,
5459                                        idx == 3 ? NULL : privkey)))
5460         goto end;
5461
5462     if (idx != 3) {
5463         /*
5464          * We use a ciphersuite with SHA256 to ease testing old style PSK
5465          * callbacks which will always default to SHA256. This should not be
5466          * necessary if we have no cert/priv key. In that case the server should
5467          * prefer SHA256 automatically.
5468          */
5469         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5470                                                 "TLS_AES_128_GCM_SHA256")))
5471             goto end;
5472     } else {
5473         /*
5474          * As noted above the server should prefer SHA256 automatically. However
5475          * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
5476          * code works even if we are testing with only the FIPS provider loaded.
5477          */
5478         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5479                                                 "TLS_AES_256_GCM_SHA384:"
5480                                                 "TLS_AES_128_GCM_SHA256")))
5481             goto end;
5482     }
5483
5484     /*
5485      * Test 0: New style callbacks only
5486      * Test 1: New and old style callbacks (only the new ones should be used)
5487      * Test 2: Old style callbacks only
5488      */
5489     if (idx == 0 || idx == 1) {
5490         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
5491         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
5492     }
5493 #ifndef OPENSSL_NO_PSK
5494     if (idx >= 1) {
5495         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
5496         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
5497     }
5498 #endif
5499     srvid = pskid;
5500     use_session_cb_cnt = 0;
5501     find_session_cb_cnt = 0;
5502     psk_client_cb_cnt = 0;
5503     psk_server_cb_cnt = 0;
5504
5505     if (idx != 3) {
5506         /*
5507          * Check we can create a connection if callback decides not to send a
5508          * PSK
5509          */
5510         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5511                                                  NULL, NULL))
5512                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5513                                                     SSL_ERROR_NONE))
5514                 || !TEST_false(SSL_session_reused(clientssl))
5515                 || !TEST_false(SSL_session_reused(serverssl)))
5516             goto end;
5517
5518         if (idx == 0 || idx == 1) {
5519             if (!TEST_true(use_session_cb_cnt == 1)
5520                     || !TEST_true(find_session_cb_cnt == 0)
5521                        /*
5522                         * If no old style callback then below should be 0
5523                         * otherwise 1
5524                         */
5525                     || !TEST_true(psk_client_cb_cnt == idx)
5526                     || !TEST_true(psk_server_cb_cnt == 0))
5527                 goto end;
5528         } else {
5529             if (!TEST_true(use_session_cb_cnt == 0)
5530                     || !TEST_true(find_session_cb_cnt == 0)
5531                     || !TEST_true(psk_client_cb_cnt == 1)
5532                     || !TEST_true(psk_server_cb_cnt == 0))
5533                 goto end;
5534         }
5535
5536         shutdown_ssl_connection(serverssl, clientssl);
5537         serverssl = clientssl = NULL;
5538         use_session_cb_cnt = psk_client_cb_cnt = 0;
5539     }
5540
5541     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5542                                              NULL, NULL)))
5543         goto end;
5544
5545     /* Create the PSK */
5546     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
5547     clientpsk = SSL_SESSION_new();
5548     if (!TEST_ptr(clientpsk)
5549             || !TEST_ptr(cipher)
5550             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
5551                                                       sizeof(key)))
5552             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
5553             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
5554                                                            TLS1_3_VERSION))
5555             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
5556         goto end;
5557     serverpsk = clientpsk;
5558
5559     /* Check we can create a connection and the PSK is used */
5560     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5561             || !TEST_true(SSL_session_reused(clientssl))
5562             || !TEST_true(SSL_session_reused(serverssl)))
5563         goto end;
5564
5565     if (idx == 0 || idx == 1) {
5566         if (!TEST_true(use_session_cb_cnt == 1)
5567                 || !TEST_true(find_session_cb_cnt == 1)
5568                 || !TEST_true(psk_client_cb_cnt == 0)
5569                 || !TEST_true(psk_server_cb_cnt == 0))
5570             goto end;
5571     } else {
5572         if (!TEST_true(use_session_cb_cnt == 0)
5573                 || !TEST_true(find_session_cb_cnt == 0)
5574                 || !TEST_true(psk_client_cb_cnt == 1)
5575                 || !TEST_true(psk_server_cb_cnt == 1))
5576             goto end;
5577     }
5578
5579     shutdown_ssl_connection(serverssl, clientssl);
5580     serverssl = clientssl = NULL;
5581     use_session_cb_cnt = find_session_cb_cnt = 0;
5582     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5583
5584     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5585                                              NULL, NULL)))
5586         goto end;
5587
5588     /* Force an HRR */
5589 #if defined(OPENSSL_NO_EC)
5590     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
5591         goto end;
5592 #else
5593     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
5594         goto end;
5595 #endif
5596
5597     /*
5598      * Check we can create a connection, the PSK is used and the callbacks are
5599      * called twice.
5600      */
5601     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5602             || !TEST_true(SSL_session_reused(clientssl))
5603             || !TEST_true(SSL_session_reused(serverssl)))
5604         goto end;
5605
5606     if (idx == 0 || idx == 1) {
5607         if (!TEST_true(use_session_cb_cnt == 2)
5608                 || !TEST_true(find_session_cb_cnt == 2)
5609                 || !TEST_true(psk_client_cb_cnt == 0)
5610                 || !TEST_true(psk_server_cb_cnt == 0))
5611             goto end;
5612     } else {
5613         if (!TEST_true(use_session_cb_cnt == 0)
5614                 || !TEST_true(find_session_cb_cnt == 0)
5615                 || !TEST_true(psk_client_cb_cnt == 2)
5616                 || !TEST_true(psk_server_cb_cnt == 2))
5617             goto end;
5618     }
5619
5620     shutdown_ssl_connection(serverssl, clientssl);
5621     serverssl = clientssl = NULL;
5622     use_session_cb_cnt = find_session_cb_cnt = 0;
5623     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5624
5625     if (idx != 3) {
5626         /*
5627          * Check that if the server rejects the PSK we can still connect, but with
5628          * a full handshake
5629          */
5630         srvid = "Dummy Identity";
5631         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5632                                                  NULL, NULL))
5633                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5634                                                     SSL_ERROR_NONE))
5635                 || !TEST_false(SSL_session_reused(clientssl))
5636                 || !TEST_false(SSL_session_reused(serverssl)))
5637             goto end;
5638
5639         if (idx == 0 || idx == 1) {
5640             if (!TEST_true(use_session_cb_cnt == 1)
5641                     || !TEST_true(find_session_cb_cnt == 1)
5642                     || !TEST_true(psk_client_cb_cnt == 0)
5643                        /*
5644                         * If no old style callback then below should be 0
5645                         * otherwise 1
5646                         */
5647                     || !TEST_true(psk_server_cb_cnt == idx))
5648                 goto end;
5649         } else {
5650             if (!TEST_true(use_session_cb_cnt == 0)
5651                     || !TEST_true(find_session_cb_cnt == 0)
5652                     || !TEST_true(psk_client_cb_cnt == 1)
5653                     || !TEST_true(psk_server_cb_cnt == 1))
5654                 goto end;
5655         }
5656
5657         shutdown_ssl_connection(serverssl, clientssl);
5658         serverssl = clientssl = NULL;
5659     }
5660     testresult = 1;
5661
5662  end:
5663     SSL_SESSION_free(clientpsk);
5664     SSL_SESSION_free(serverpsk);
5665     clientpsk = serverpsk = NULL;
5666     SSL_free(serverssl);
5667     SSL_free(clientssl);
5668     SSL_CTX_free(sctx);
5669     SSL_CTX_free(cctx);
5670     return testresult;
5671 }
5672
5673 static unsigned char cookie_magic_value[] = "cookie magic";
5674
5675 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
5676                                     unsigned int *cookie_len)
5677 {
5678     /*
5679      * Not suitable as a real cookie generation function but good enough for
5680      * testing!
5681      */
5682     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
5683     *cookie_len = sizeof(cookie_magic_value) - 1;
5684
5685     return 1;
5686 }
5687
5688 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
5689                                   unsigned int cookie_len)
5690 {
5691     if (cookie_len == sizeof(cookie_magic_value) - 1
5692         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
5693         return 1;
5694
5695     return 0;
5696 }
5697
5698 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
5699                                         size_t *cookie_len)
5700 {
5701     unsigned int temp;
5702     int res = generate_cookie_callback(ssl, cookie, &temp);
5703     *cookie_len = temp;
5704     return res;
5705 }
5706
5707 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
5708                                       size_t cookie_len)
5709 {
5710     return verify_cookie_callback(ssl, cookie, cookie_len);
5711 }
5712
5713 static int test_stateless(void)
5714 {
5715     SSL_CTX *sctx = NULL, *cctx = NULL;
5716     SSL *serverssl = NULL, *clientssl = NULL;
5717     int testresult = 0;
5718
5719     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5720                                        TLS_client_method(), TLS1_VERSION, 0,
5721                                        &sctx, &cctx, cert, privkey)))
5722         goto end;
5723
5724     /* The arrival of CCS messages can confuse the test */
5725     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5726
5727     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5728                                       NULL, NULL))
5729                /* Send the first ClientHello */
5730             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5731                                                  SSL_ERROR_WANT_READ))
5732                /*
5733                 * This should fail with a -1 return because we have no callbacks
5734                 * set up
5735                 */
5736             || !TEST_int_eq(SSL_stateless(serverssl), -1))
5737         goto end;
5738
5739     /* Fatal error so abandon the connection from this client */
5740     SSL_free(clientssl);
5741     clientssl = NULL;
5742
5743     /* Set up the cookie generation and verification callbacks */
5744     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
5745     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
5746
5747     /*
5748      * Create a new connection from the client (we can reuse the server SSL
5749      * object).
5750      */
5751     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5752                                              NULL, NULL))
5753                /* Send the first ClientHello */
5754             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5755                                                 SSL_ERROR_WANT_READ))
5756                /* This should fail because there is no cookie */
5757             || !TEST_int_eq(SSL_stateless(serverssl), 0))
5758         goto end;
5759
5760     /* Abandon the connection from this client */
5761     SSL_free(clientssl);
5762     clientssl = NULL;
5763
5764     /*
5765      * Now create a connection from a new client but with the same server SSL
5766      * object
5767      */
5768     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5769                                              NULL, NULL))
5770                /* Send the first ClientHello */
5771             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5772                                                 SSL_ERROR_WANT_READ))
5773                /* This should fail because there is no cookie */
5774             || !TEST_int_eq(SSL_stateless(serverssl), 0)
5775                /* Send the second ClientHello */
5776             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5777                                                 SSL_ERROR_WANT_READ))
5778                /* This should succeed because a cookie is now present */
5779             || !TEST_int_eq(SSL_stateless(serverssl), 1)
5780                /* Complete the connection */
5781             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5782                                                 SSL_ERROR_NONE)))
5783         goto end;
5784
5785     shutdown_ssl_connection(serverssl, clientssl);
5786     serverssl = clientssl = NULL;
5787     testresult = 1;
5788
5789  end:
5790     SSL_free(serverssl);
5791     SSL_free(clientssl);
5792     SSL_CTX_free(sctx);
5793     SSL_CTX_free(cctx);
5794     return testresult;
5795
5796 }
5797 #endif /* OSSL_NO_USABLE_TLS1_3 */
5798
5799 static int clntaddoldcb = 0;
5800 static int clntparseoldcb = 0;
5801 static int srvaddoldcb = 0;
5802 static int srvparseoldcb = 0;
5803 static int clntaddnewcb = 0;
5804 static int clntparsenewcb = 0;
5805 static int srvaddnewcb = 0;
5806 static int srvparsenewcb = 0;
5807 static int snicb = 0;
5808
5809 #define TEST_EXT_TYPE1  0xff00
5810
5811 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
5812                       size_t *outlen, int *al, void *add_arg)
5813 {
5814     int *server = (int *)add_arg;
5815     unsigned char *data;
5816
5817     if (SSL_is_server(s))
5818         srvaddoldcb++;
5819     else
5820         clntaddoldcb++;
5821
5822     if (*server != SSL_is_server(s)
5823             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
5824         return -1;
5825
5826     *data = 1;
5827     *out = data;
5828     *outlen = sizeof(char);
5829     return 1;
5830 }
5831
5832 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
5833                         void *add_arg)
5834 {
5835     OPENSSL_free((unsigned char *)out);
5836 }
5837
5838 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
5839                         size_t inlen, int *al, void *parse_arg)
5840 {
5841     int *server = (int *)parse_arg;
5842
5843     if (SSL_is_server(s))
5844         srvparseoldcb++;
5845     else
5846         clntparseoldcb++;
5847
5848     if (*server != SSL_is_server(s)
5849             || inlen != sizeof(char)
5850             || *in != 1)
5851         return -1;
5852
5853     return 1;
5854 }
5855
5856 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
5857                       const unsigned char **out, size_t *outlen, X509 *x,
5858                       size_t chainidx, int *al, void *add_arg)
5859 {
5860     int *server = (int *)add_arg;
5861     unsigned char *data;
5862
5863     if (SSL_is_server(s))
5864         srvaddnewcb++;
5865     else
5866         clntaddnewcb++;
5867
5868     if (*server != SSL_is_server(s)
5869             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
5870         return -1;
5871
5872     *data = 1;
5873     *out = data;
5874     *outlen = sizeof(*data);
5875     return 1;
5876 }
5877
5878 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
5879                         const unsigned char *out, void *add_arg)
5880 {
5881     OPENSSL_free((unsigned char *)out);
5882 }
5883
5884 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
5885                         const unsigned char *in, size_t inlen, X509 *x,
5886                         size_t chainidx, int *al, void *parse_arg)
5887 {
5888     int *server = (int *)parse_arg;
5889
5890     if (SSL_is_server(s))
5891         srvparsenewcb++;
5892     else
5893         clntparsenewcb++;
5894
5895     if (*server != SSL_is_server(s)
5896             || inlen != sizeof(char) || *in != 1)
5897         return -1;
5898
5899     return 1;
5900 }
5901
5902 static int sni_cb(SSL *s, int *al, void *arg)
5903 {
5904     SSL_CTX *ctx = (SSL_CTX *)arg;
5905
5906     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
5907         *al = SSL_AD_INTERNAL_ERROR;
5908         return SSL_TLSEXT_ERR_ALERT_FATAL;
5909     }
5910     snicb++;
5911     return SSL_TLSEXT_ERR_OK;
5912 }
5913
5914 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
5915 {
5916     return 1;
5917 }
5918
5919 /*
5920  * Custom call back tests.
5921  * Test 0: Old style callbacks in TLSv1.2
5922  * Test 1: New style callbacks in TLSv1.2
5923  * Test 2: New style callbacks in TLSv1.2 with SNI
5924  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
5925  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
5926  * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
5927  */
5928 static int test_custom_exts(int tst)
5929 {
5930     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
5931     SSL *clientssl = NULL, *serverssl = NULL;
5932     int testresult = 0;
5933     static int server = 1;
5934     static int client = 0;
5935     SSL_SESSION *sess = NULL;
5936     unsigned int context;
5937
5938 #if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
5939     /* Skip tests for TLSv1.2 and below in this case */
5940     if (tst < 3)
5941         return 1;
5942 #endif
5943
5944     /* Reset callback counters */
5945     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
5946     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
5947     snicb = 0;
5948
5949     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5950                                        TLS_client_method(), TLS1_VERSION, 0,
5951                                        &sctx, &cctx, cert, privkey)))
5952         goto end;
5953
5954     if (tst == 2
5955             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
5956                                               TLS1_VERSION, 0,
5957                                               &sctx2, NULL, cert, privkey)))
5958         goto end;
5959
5960
5961     if (tst < 3) {
5962         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
5963         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
5964         if (sctx2 != NULL)
5965             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
5966     }
5967
5968     if (tst == 5) {
5969         context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
5970                   | SSL_EXT_TLS1_3_CERTIFICATE;
5971         SSL_CTX_set_verify(sctx,
5972                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
5973                            verify_cb);
5974         if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
5975                                                       SSL_FILETYPE_PEM), 1)
5976                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
5977                                                             SSL_FILETYPE_PEM), 1)
5978                 || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
5979             goto end;
5980     } else if (tst == 4) {
5981         context = SSL_EXT_CLIENT_HELLO
5982                   | SSL_EXT_TLS1_2_SERVER_HELLO
5983                   | SSL_EXT_TLS1_3_SERVER_HELLO
5984                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
5985                   | SSL_EXT_TLS1_3_CERTIFICATE
5986                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
5987     } else {
5988         context = SSL_EXT_CLIENT_HELLO
5989                   | SSL_EXT_TLS1_2_SERVER_HELLO
5990                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
5991     }
5992
5993     /* Create a client side custom extension */
5994     if (tst == 0) {
5995         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
5996                                                      old_add_cb, old_free_cb,
5997                                                      &client, old_parse_cb,
5998                                                      &client)))
5999             goto end;
6000     } else {
6001         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
6002                                               new_add_cb, new_free_cb,
6003                                               &client, new_parse_cb, &client)))
6004             goto end;
6005     }
6006
6007     /* Should not be able to add duplicates */
6008     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6009                                                   old_add_cb, old_free_cb,
6010                                                   &client, old_parse_cb,
6011                                                   &client))
6012             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
6013                                                   context, new_add_cb,
6014                                                   new_free_cb, &client,
6015                                                   new_parse_cb, &client)))
6016         goto end;
6017
6018     /* Create a server side custom extension */
6019     if (tst == 0) {
6020         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6021                                                      old_add_cb, old_free_cb,
6022                                                      &server, old_parse_cb,
6023                                                      &server)))
6024             goto end;
6025     } else {
6026         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
6027                                               new_add_cb, new_free_cb,
6028                                               &server, new_parse_cb, &server)))
6029             goto end;
6030         if (sctx2 != NULL
6031                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
6032                                                      context, new_add_cb,
6033                                                      new_free_cb, &server,
6034                                                      new_parse_cb, &server)))
6035             goto end;
6036     }
6037
6038     /* Should not be able to add duplicates */
6039     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6040                                                   old_add_cb, old_free_cb,
6041                                                   &server, old_parse_cb,
6042                                                   &server))
6043             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
6044                                                   context, new_add_cb,
6045                                                   new_free_cb, &server,
6046                                                   new_parse_cb, &server)))
6047         goto end;
6048
6049     if (tst == 2) {
6050         /* Set up SNI */
6051         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
6052                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
6053             goto end;
6054     }
6055
6056     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6057                                       &clientssl, NULL, NULL))
6058             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6059                                                 SSL_ERROR_NONE)))
6060         goto end;
6061
6062     if (tst == 0) {
6063         if (clntaddoldcb != 1
6064                 || clntparseoldcb != 1
6065                 || srvaddoldcb != 1
6066                 || srvparseoldcb != 1)
6067             goto end;
6068     } else if (tst == 1 || tst == 2 || tst == 3) {
6069         if (clntaddnewcb != 1
6070                 || clntparsenewcb != 1
6071                 || srvaddnewcb != 1
6072                 || srvparsenewcb != 1
6073                 || (tst != 2 && snicb != 0)
6074                 || (tst == 2 && snicb != 1))
6075             goto end;
6076     } else if (tst == 5) {
6077         if (clntaddnewcb != 1
6078                 || clntparsenewcb != 1
6079                 || srvaddnewcb != 1
6080                 || srvparsenewcb != 1)
6081             goto end;
6082     } else {
6083         /* In this case there 2 NewSessionTicket messages created */
6084         if (clntaddnewcb != 1
6085                 || clntparsenewcb != 5
6086                 || srvaddnewcb != 5
6087                 || srvparsenewcb != 1)
6088             goto end;
6089     }
6090
6091     sess = SSL_get1_session(clientssl);
6092     SSL_shutdown(clientssl);
6093     SSL_shutdown(serverssl);
6094     SSL_free(serverssl);
6095     SSL_free(clientssl);
6096     serverssl = clientssl = NULL;
6097
6098     if (tst == 3 || tst == 5) {
6099         /* We don't bother with the resumption aspects for these tests */
6100         testresult = 1;
6101         goto end;
6102     }
6103
6104     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6105                                       NULL, NULL))
6106             || !TEST_true(SSL_set_session(clientssl, sess))
6107             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6108                                                SSL_ERROR_NONE)))
6109         goto end;
6110
6111     /*
6112      * For a resumed session we expect to add the ClientHello extension. For the
6113      * old style callbacks we ignore it on the server side because they set
6114      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
6115      * them.
6116      */
6117     if (tst == 0) {
6118         if (clntaddoldcb != 2
6119                 || clntparseoldcb != 1
6120                 || srvaddoldcb != 1
6121                 || srvparseoldcb != 1)
6122             goto end;
6123     } else if (tst == 1 || tst == 2 || tst == 3) {
6124         if (clntaddnewcb != 2
6125                 || clntparsenewcb != 2
6126                 || srvaddnewcb != 2
6127                 || srvparsenewcb != 2)
6128             goto end;
6129     } else {
6130         /*
6131          * No Certificate message extensions in the resumption handshake,
6132          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
6133          */
6134         if (clntaddnewcb != 2
6135                 || clntparsenewcb != 8
6136                 || srvaddnewcb != 8
6137                 || srvparsenewcb != 2)
6138             goto end;
6139     }
6140
6141     testresult = 1;
6142
6143 end:
6144     SSL_SESSION_free(sess);
6145     SSL_free(serverssl);
6146     SSL_free(clientssl);
6147     SSL_CTX_free(sctx2);
6148     SSL_CTX_free(sctx);
6149     SSL_CTX_free(cctx);
6150     return testresult;
6151 }
6152
6153 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6154
6155 #define  SYNTHV1CONTEXT     (SSL_EXT_TLS1_2_AND_BELOW_ONLY \
6156                              | SSL_EXT_CLIENT_HELLO \
6157                              | SSL_EXT_TLS1_2_SERVER_HELLO \
6158                              | SSL_EXT_IGNORE_ON_RESUMPTION)
6159
6160 #define TLS13CONTEXT (SSL_EXT_TLS1_3_CERTIFICATE \
6161                       | SSL_EXT_TLS1_2_SERVER_HELLO \
6162                       | SSL_EXT_CLIENT_HELLO)
6163
6164 #define SERVERINFO_CUSTOM                                 \
6165     0x00, (char)TLSEXT_TYPE_signed_certificate_timestamp, \
6166     0x00, 0x03,                                           \
6167     0x04, 0x05, 0x06                                      \
6168
6169 static const unsigned char serverinfo_custom_tls13[] = {
6170     0x00, 0x00, (TLS13CONTEXT >> 8) & 0xff, TLS13CONTEXT & 0xff,
6171     SERVERINFO_CUSTOM
6172 };
6173 static const unsigned char serverinfo_custom_v2[] = {
6174     0x00, 0x00, (SYNTHV1CONTEXT >> 8) & 0xff,  SYNTHV1CONTEXT & 0xff,
6175     SERVERINFO_CUSTOM
6176 };
6177 static const unsigned char serverinfo_custom_v1[] = {
6178     SERVERINFO_CUSTOM
6179 };
6180 static const size_t serverinfo_custom_tls13_len = sizeof(serverinfo_custom_tls13);
6181 static const size_t serverinfo_custom_v2_len = sizeof(serverinfo_custom_v2);
6182 static const size_t serverinfo_custom_v1_len = sizeof(serverinfo_custom_v1);
6183
6184 static int serverinfo_custom_parse_cb(SSL *s, unsigned int ext_type,
6185                                       unsigned int context,
6186                                       const unsigned char *in,
6187                                       size_t inlen, X509 *x,
6188                                       size_t chainidx, int *al,
6189                                       void *parse_arg)
6190 {
6191     const size_t len = serverinfo_custom_v1_len;
6192     const unsigned char *si = &serverinfo_custom_v1[len - 3];
6193     int *p_cb_result = (int*)parse_arg;
6194     *p_cb_result = TEST_mem_eq(in, inlen, si, 3);
6195     return 1;
6196 }
6197
6198 static int test_serverinfo_custom(const int idx)
6199 {
6200     SSL_CTX *sctx = NULL, *cctx = NULL;
6201     SSL *clientssl = NULL, *serverssl = NULL;
6202     int testresult = 0;
6203     int cb_result = 0;
6204
6205     /*
6206      * Following variables are set in the switch statement
6207      *  according to the test iteration.
6208      * Default values do not make much sense: test would fail with them.
6209      */
6210     int serverinfo_version = 0;
6211     int protocol_version = 0;
6212     unsigned int extension_context = 0;
6213     const unsigned char *si = NULL;
6214     size_t si_len = 0;
6215
6216     const int call_use_serverinfo_ex = idx > 0;
6217     switch (idx) {
6218     case 0: /* FALLTHROUGH */
6219     case 1:
6220         serverinfo_version = SSL_SERVERINFOV1;
6221         protocol_version = TLS1_2_VERSION;
6222         extension_context = SYNTHV1CONTEXT;
6223         si = serverinfo_custom_v1;
6224         si_len = serverinfo_custom_v1_len;
6225         break;
6226     case 2:
6227         serverinfo_version = SSL_SERVERINFOV2;
6228         protocol_version = TLS1_2_VERSION;
6229         extension_context = SYNTHV1CONTEXT;
6230         si = serverinfo_custom_v2;
6231         si_len = serverinfo_custom_v2_len;
6232         break;
6233     case 3:
6234         serverinfo_version = SSL_SERVERINFOV2;
6235         protocol_version = TLS1_3_VERSION;
6236         extension_context = TLS13CONTEXT;
6237         si = serverinfo_custom_tls13;
6238         si_len = serverinfo_custom_tls13_len;
6239         break;
6240     }
6241
6242     if (!TEST_true(create_ssl_ctx_pair(libctx,
6243                                        TLS_method(),
6244                                        TLS_method(),
6245                                        protocol_version,
6246                                        protocol_version,
6247                                        &sctx, &cctx, cert, privkey)))
6248         goto end;
6249
6250     if (call_use_serverinfo_ex) {
6251         if (!TEST_true(SSL_CTX_use_serverinfo_ex(sctx, serverinfo_version,
6252                                                  si, si_len)))
6253             goto end;
6254     } else {
6255         if (!TEST_true(SSL_CTX_use_serverinfo(sctx, si, si_len)))
6256             goto end;
6257     }
6258
6259     if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TLSEXT_TYPE_signed_certificate_timestamp,
6260                                           extension_context,
6261                                           NULL, NULL, NULL,
6262                                           serverinfo_custom_parse_cb,
6263                                           &cb_result))
6264         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6265                                          NULL, NULL))
6266         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6267                                             SSL_ERROR_NONE))
6268         || !TEST_int_eq(SSL_do_handshake(clientssl), 1))
6269         goto end;
6270
6271     if (!TEST_true(cb_result))
6272         goto end;
6273
6274     testresult = 1;
6275
6276  end:
6277     SSL_free(serverssl);
6278     SSL_free(clientssl);
6279     SSL_CTX_free(sctx);
6280     SSL_CTX_free(cctx);
6281
6282     return testresult;
6283 }
6284 #endif
6285
6286 /*
6287  * Test that SSL_export_keying_material() produces expected results. There are
6288  * no test vectors so all we do is test that both sides of the communication
6289  * produce the same results for different protocol versions.
6290  */
6291 #define SMALL_LABEL_LEN 10
6292 #define LONG_LABEL_LEN  249
6293 static int test_export_key_mat(int tst)
6294 {
6295     int testresult = 0;
6296     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6297     SSL *clientssl = NULL, *serverssl = NULL;
6298     const char label[LONG_LABEL_LEN + 1] = "test label";
6299     const unsigned char context[] = "context";
6300     const unsigned char *emptycontext = NULL;
6301     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
6302     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
6303     size_t labellen;
6304     const int protocols[] = {
6305         TLS1_VERSION,
6306         TLS1_1_VERSION,
6307         TLS1_2_VERSION,
6308         TLS1_3_VERSION,
6309         TLS1_3_VERSION,
6310         TLS1_3_VERSION
6311     };
6312
6313 #ifdef OPENSSL_NO_TLS1
6314     if (tst == 0)
6315         return 1;
6316 #endif
6317 #ifdef OPENSSL_NO_TLS1_1
6318     if (tst == 1)
6319         return 1;
6320 #endif
6321     if (is_fips && (tst == 0 || tst == 1))
6322         return 1;
6323 #ifdef OPENSSL_NO_TLS1_2
6324     if (tst == 2)
6325         return 1;
6326 #endif
6327 #ifdef OSSL_NO_USABLE_TLS1_3
6328     if (tst >= 3)
6329         return 1;
6330 #endif
6331     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6332                                        TLS_client_method(), TLS1_VERSION, 0,
6333                                        &sctx, &cctx, cert, privkey)))
6334         goto end;
6335
6336     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
6337     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
6338     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
6339     if ((protocols[tst] < TLS1_2_VERSION) &&
6340         (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0")
6341         || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
6342         goto end;
6343
6344     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6345                                       NULL)))
6346         goto end;
6347
6348     /*
6349      * Premature call of SSL_export_keying_material should just fail.
6350      */
6351     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6352                                                 sizeof(ckeymat1), label,
6353                                                 SMALL_LABEL_LEN + 1, context,
6354                                                 sizeof(context) - 1, 1), 0))
6355         goto end;
6356
6357     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6358                                          SSL_ERROR_NONE)))
6359         goto end;
6360
6361     if (tst == 5) {
6362         /*
6363          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
6364          * go over that.
6365          */
6366         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6367                                                     sizeof(ckeymat1), label,
6368                                                     LONG_LABEL_LEN + 1, context,
6369                                                     sizeof(context) - 1, 1), 0))
6370             goto end;
6371
6372         testresult = 1;
6373         goto end;
6374     } else if (tst == 4) {
6375         labellen = LONG_LABEL_LEN;
6376     } else {
6377         labellen = SMALL_LABEL_LEN;
6378     }
6379
6380     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
6381                                                 sizeof(ckeymat1), label,
6382                                                 labellen, context,
6383                                                 sizeof(context) - 1, 1), 1)
6384             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
6385                                                        sizeof(ckeymat2), label,
6386                                                        labellen,
6387                                                        emptycontext,
6388                                                        0, 1), 1)
6389             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
6390                                                        sizeof(ckeymat3), label,
6391                                                        labellen,
6392                                                        NULL, 0, 0), 1)
6393             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
6394                                                        sizeof(skeymat1), label,
6395                                                        labellen,
6396                                                        context,
6397                                                        sizeof(context) -1, 1),
6398                             1)
6399             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
6400                                                        sizeof(skeymat2), label,
6401                                                        labellen,
6402                                                        emptycontext,
6403                                                        0, 1), 1)
6404             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
6405                                                        sizeof(skeymat3), label,
6406                                                        labellen,
6407                                                        NULL, 0, 0), 1)
6408                /*
6409                 * Check that both sides created the same key material with the
6410                 * same context.
6411                 */
6412             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6413                             sizeof(skeymat1))
6414                /*
6415                 * Check that both sides created the same key material with an
6416                 * empty context.
6417                 */
6418             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6419                             sizeof(skeymat2))
6420                /*
6421                 * Check that both sides created the same key material without a
6422                 * context.
6423                 */
6424             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
6425                             sizeof(skeymat3))
6426                /* Different contexts should produce different results */
6427             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6428                             sizeof(ckeymat2)))
6429         goto end;
6430
6431     /*
6432      * Check that an empty context and no context produce different results in
6433      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
6434      */
6435     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
6436                                   sizeof(ckeymat3)))
6437             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
6438                                          sizeof(ckeymat3))))
6439         goto end;
6440
6441     testresult = 1;
6442
6443  end:
6444     SSL_free(serverssl);
6445     SSL_free(clientssl);
6446     SSL_CTX_free(sctx2);
6447     SSL_CTX_free(sctx);
6448     SSL_CTX_free(cctx);
6449
6450     return testresult;
6451 }
6452
6453 #ifndef OSSL_NO_USABLE_TLS1_3
6454 /*
6455  * Test that SSL_export_keying_material_early() produces expected
6456  * results. There are no test vectors so all we do is test that both
6457  * sides of the communication produce the same results for different
6458  * protocol versions.
6459  */
6460 static int test_export_key_mat_early(int idx)
6461 {
6462     static const char label[] = "test label";
6463     static const unsigned char context[] = "context";
6464     int testresult = 0;
6465     SSL_CTX *cctx = NULL, *sctx = NULL;
6466     SSL *clientssl = NULL, *serverssl = NULL;
6467     SSL_SESSION *sess = NULL;
6468     const unsigned char *emptycontext = NULL;
6469     unsigned char ckeymat1[80], ckeymat2[80];
6470     unsigned char skeymat1[80], skeymat2[80];
6471     unsigned char buf[1];
6472     size_t readbytes, written;
6473
6474     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
6475                                         &sess, idx, SHA384_DIGEST_LENGTH)))
6476         goto end;
6477
6478     /* Here writing 0 length early data is enough. */
6479     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
6480             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
6481                                                 &readbytes),
6482                             SSL_READ_EARLY_DATA_ERROR)
6483             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6484                             SSL_EARLY_DATA_ACCEPTED))
6485         goto end;
6486
6487     if (!TEST_int_eq(SSL_export_keying_material_early(
6488                      clientssl, ckeymat1, sizeof(ckeymat1), label,
6489                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
6490             || !TEST_int_eq(SSL_export_keying_material_early(
6491                             clientssl, ckeymat2, sizeof(ckeymat2), label,
6492                             sizeof(label) - 1, emptycontext, 0), 1)
6493             || !TEST_int_eq(SSL_export_keying_material_early(
6494                             serverssl, skeymat1, sizeof(skeymat1), label,
6495                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
6496             || !TEST_int_eq(SSL_export_keying_material_early(
6497                             serverssl, skeymat2, sizeof(skeymat2), label,
6498                             sizeof(label) - 1, emptycontext, 0), 1)
6499                /*
6500                 * Check that both sides created the same key material with the
6501                 * same context.
6502                 */
6503             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6504                             sizeof(skeymat1))
6505                /*
6506                 * Check that both sides created the same key material with an
6507                 * empty context.
6508                 */
6509             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6510                             sizeof(skeymat2))
6511                /* Different contexts should produce different results */
6512             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6513                             sizeof(ckeymat2)))
6514         goto end;
6515
6516     testresult = 1;
6517
6518  end:
6519     SSL_SESSION_free(sess);
6520     SSL_SESSION_free(clientpsk);
6521     SSL_SESSION_free(serverpsk);
6522     clientpsk = serverpsk = NULL;
6523     SSL_free(serverssl);
6524     SSL_free(clientssl);
6525     SSL_CTX_free(sctx);
6526     SSL_CTX_free(cctx);
6527
6528     return testresult;
6529 }
6530
6531 #define NUM_KEY_UPDATE_MESSAGES 40
6532 /*
6533  * Test KeyUpdate.
6534  */
6535 static int test_key_update(void)
6536 {
6537     SSL_CTX *cctx = NULL, *sctx = NULL;
6538     SSL *clientssl = NULL, *serverssl = NULL;
6539     int testresult = 0, i, j;
6540     char buf[20];
6541     static char *mess = "A test message";
6542
6543     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6544                                        TLS_client_method(),
6545                                        TLS1_3_VERSION,
6546                                        0,
6547                                        &sctx, &cctx, cert, privkey))
6548             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6549                                              NULL, NULL))
6550             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6551                                                 SSL_ERROR_NONE)))
6552         goto end;
6553
6554     for (j = 0; j < 2; j++) {
6555         /* Send lots of KeyUpdate messages */
6556         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
6557             if (!TEST_true(SSL_key_update(clientssl,
6558                                           (j == 0)
6559                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
6560                                           : SSL_KEY_UPDATE_REQUESTED))
6561                     || !TEST_true(SSL_do_handshake(clientssl)))
6562                 goto end;
6563         }
6564
6565         /* Check that sending and receiving app data is ok */
6566         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
6567                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
6568                                          strlen(mess)))
6569             goto end;
6570
6571         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
6572                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
6573                                          strlen(mess)))
6574             goto end;
6575     }
6576
6577     testresult = 1;
6578
6579  end:
6580     SSL_free(serverssl);
6581     SSL_free(clientssl);
6582     SSL_CTX_free(sctx);
6583     SSL_CTX_free(cctx);
6584
6585     return testresult;
6586 }
6587
6588 /*
6589  * Test we can handle a KeyUpdate (update requested) message while
6590  * write data is pending in peer.
6591  * Test 0: Client sends KeyUpdate while Server is writing
6592  * Test 1: Server sends KeyUpdate while Client is writing
6593  */
6594 static int test_key_update_peer_in_write(int tst)
6595 {
6596     SSL_CTX *cctx = NULL, *sctx = NULL;
6597     SSL *clientssl = NULL, *serverssl = NULL;
6598     int testresult = 0;
6599     char buf[20];
6600     static char *mess = "A test message";
6601     BIO *bretry = BIO_new(bio_s_always_retry());
6602     BIO *tmp = NULL;
6603     SSL *peerupdate = NULL, *peerwrite = NULL;
6604
6605     if (!TEST_ptr(bretry)
6606             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6607                                               TLS_client_method(),
6608                                               TLS1_3_VERSION,
6609                                               0,
6610                                               &sctx, &cctx, cert, privkey))
6611             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6612                                              NULL, NULL))
6613             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6614                                                 SSL_ERROR_NONE)))
6615         goto end;
6616
6617     peerupdate = tst == 0 ? clientssl : serverssl;
6618     peerwrite = tst == 0 ? serverssl : clientssl;
6619
6620     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
6621             || !TEST_int_eq(SSL_do_handshake(peerupdate), 1))
6622         goto end;
6623
6624     /* Swap the writing endpoint's write BIO to force a retry */
6625     tmp = SSL_get_wbio(peerwrite);
6626     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6627         tmp = NULL;
6628         goto end;
6629     }
6630     SSL_set0_wbio(peerwrite, bretry);
6631     bretry = NULL;
6632
6633     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
6634     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
6635             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE))
6636         goto end;
6637
6638     /* Reinstate the original writing endpoint's write BIO */
6639     SSL_set0_wbio(peerwrite, tmp);
6640     tmp = NULL;
6641
6642     /* Now read some data - we will read the key update */
6643     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
6644             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ))
6645         goto end;
6646
6647     /*
6648      * Complete the write we started previously and read it from the other
6649      * endpoint
6650      */
6651     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6652             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6653         goto end;
6654
6655     /* Write more data to ensure we send the KeyUpdate message back */
6656     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6657             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6658         goto end;
6659
6660     testresult = 1;
6661
6662  end:
6663     SSL_free(serverssl);
6664     SSL_free(clientssl);
6665     SSL_CTX_free(sctx);
6666     SSL_CTX_free(cctx);
6667     BIO_free(bretry);
6668     BIO_free(tmp);
6669
6670     return testresult;
6671 }
6672
6673 /*
6674  * Test we can handle a KeyUpdate (update requested) message while
6675  * peer read data is pending after peer accepted keyupdate(the msg header
6676  * had been read 5 bytes).
6677  * Test 0: Client sends KeyUpdate while Server is reading
6678  * Test 1: Server sends KeyUpdate while Client is reading
6679  */
6680 static int test_key_update_peer_in_read(int tst)
6681 {
6682     SSL_CTX *cctx = NULL, *sctx = NULL;
6683     SSL *clientssl = NULL, *serverssl = NULL;
6684     int testresult = 0;
6685     char prbuf[515], lwbuf[515] = {0};
6686     static char *mess = "A test message";
6687     BIO *lbio = NULL, *pbio = NULL;
6688     SSL *local = NULL, *peer = NULL;
6689
6690     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6691                                               TLS_client_method(),
6692                                               TLS1_3_VERSION,
6693                                               0,
6694                                               &sctx, &cctx, cert, privkey))
6695             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6696                                              NULL, NULL))
6697             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6698                                                 SSL_ERROR_NONE)))
6699         goto end;
6700
6701     local = tst == 0 ? clientssl : serverssl;
6702     peer = tst == 0 ? serverssl : clientssl;
6703
6704     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
6705         goto end;
6706
6707     SSL_set_bio(local, lbio, lbio);
6708     SSL_set_bio(peer, pbio, pbio);
6709
6710     /*
6711      * we first write keyupdate msg then appdata in local
6712      * write data in local will fail with SSL_ERROR_WANT_WRITE,because
6713      * lwbuf app data msg size + key updata msg size > 512(the size of
6714      * the bio pair buffer)
6715      */
6716     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6717             || !TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), -1)
6718             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
6719         goto end;
6720
6721     /*
6722      * first read keyupdate msg in peer in peer
6723      * then read appdata that we know will fail with SSL_ERROR_WANT_READ
6724      */
6725     if (!TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), -1)
6726             || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_READ))
6727         goto end;
6728
6729     /* Now write some data in peer - we will write the key update */
6730     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)))
6731         goto end;
6732
6733     /*
6734      * write data in local previously that we will complete
6735      * read data in peer previously that we will complete
6736      */
6737     if (!TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), sizeof(lwbuf))
6738             || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), sizeof(prbuf)))
6739         goto end;
6740
6741     /* check that sending and receiving appdata ok */
6742     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
6743             || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
6744         goto end;
6745
6746     testresult = 1;
6747
6748  end:
6749     SSL_free(serverssl);
6750     SSL_free(clientssl);
6751     SSL_CTX_free(sctx);
6752     SSL_CTX_free(cctx);
6753
6754     return testresult;
6755 }
6756
6757 /*
6758  * Test we can't send a KeyUpdate (update requested) message while
6759  * local write data is pending.
6760  * Test 0: Client sends KeyUpdate while Client is writing
6761  * Test 1: Server sends KeyUpdate while Server is writing
6762  */
6763 static int test_key_update_local_in_write(int tst)
6764 {
6765     SSL_CTX *cctx = NULL, *sctx = NULL;
6766     SSL *clientssl = NULL, *serverssl = NULL;
6767     int testresult = 0;
6768     char buf[20];
6769     static char *mess = "A test message";
6770     BIO *bretry = BIO_new(bio_s_always_retry());
6771     BIO *tmp = NULL;
6772     SSL *local = NULL, *peer = NULL;
6773
6774     if (!TEST_ptr(bretry)
6775             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6776                                               TLS_client_method(),
6777                                               TLS1_3_VERSION,
6778                                               0,
6779                                               &sctx, &cctx, cert, privkey))
6780             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6781                                              NULL, NULL))
6782             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6783                                                 SSL_ERROR_NONE)))
6784         goto end;
6785
6786     local = tst == 0 ? clientssl : serverssl;
6787     peer = tst == 0 ? serverssl : clientssl;
6788
6789     /* Swap the writing endpoint's write BIO to force a retry */
6790     tmp = SSL_get_wbio(local);
6791     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6792         tmp = NULL;
6793         goto end;
6794     }
6795     SSL_set0_wbio(local, bretry);
6796     bretry = NULL;
6797
6798     /* write data in local will fail with SSL_ERROR_WANT_WRITE */
6799     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), -1)
6800             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
6801         goto end;
6802
6803     /* Reinstate the original writing endpoint's write BIO */
6804     SSL_set0_wbio(local, tmp);
6805     tmp = NULL;
6806
6807     /* SSL_key_update will fail, because writing in local*/
6808     if (!TEST_false(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6809         || !TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_BAD_WRITE_RETRY))
6810     goto end;
6811
6812     ERR_clear_error();
6813     /* write data in local previously that we will complete */
6814     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)))
6815         goto end;
6816
6817     /* SSL_key_update will succeed because there is no pending write data */
6818     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6819         || !TEST_int_eq(SSL_do_handshake(local), 1))
6820         goto end;
6821
6822     /*
6823      * we write some appdata in local
6824      * read data in peer - we will read the keyupdate msg
6825      */
6826     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
6827         || !TEST_int_eq(SSL_read(peer, buf, sizeof(buf)), strlen(mess)))
6828         goto end;
6829
6830     /* Write more peer more data to ensure we send the keyupdate message back */
6831     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
6832             || !TEST_int_eq(SSL_read(local, buf, sizeof(buf)), strlen(mess)))
6833         goto end;
6834
6835     testresult = 1;
6836
6837  end:
6838     SSL_free(serverssl);
6839     SSL_free(clientssl);
6840     SSL_CTX_free(sctx);
6841     SSL_CTX_free(cctx);
6842     BIO_free(bretry);
6843     BIO_free(tmp);
6844
6845     return testresult;
6846 }
6847
6848 /*
6849  * Test we can handle a KeyUpdate (update requested) message while
6850  * local read data is pending(the msg header had been read 5 bytes).
6851  * Test 0: Client sends KeyUpdate while Client is reading
6852  * Test 1: Server sends KeyUpdate while Server is reading
6853  */
6854 static int test_key_update_local_in_read(int tst)
6855 {
6856     SSL_CTX *cctx = NULL, *sctx = NULL;
6857     SSL *clientssl = NULL, *serverssl = NULL;
6858     int testresult = 0;
6859     char lrbuf[515], pwbuf[515] = {0}, prbuf[20];
6860     static char *mess = "A test message";
6861     BIO *lbio = NULL, *pbio = NULL;
6862     SSL *local = NULL, *peer = NULL;
6863
6864     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6865                                               TLS_client_method(),
6866                                               TLS1_3_VERSION,
6867                                               0,
6868                                               &sctx, &cctx, cert, privkey))
6869             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6870                                              NULL, NULL))
6871             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6872                                                 SSL_ERROR_NONE)))
6873         goto end;
6874
6875     local = tst == 0 ? clientssl : serverssl;
6876     peer = tst == 0 ? serverssl : clientssl;
6877
6878     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
6879         goto end;
6880
6881     SSL_set_bio(local, lbio, lbio);
6882     SSL_set_bio(peer, pbio, pbio);
6883
6884     /* write app data in peer will fail with SSL_ERROR_WANT_WRITE */
6885     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), -1)
6886         || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_WRITE))
6887         goto end;
6888
6889     /* read appdata in local will fail with SSL_ERROR_WANT_READ */
6890     if (!TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), -1)
6891             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_READ))
6892         goto end;
6893
6894     /* SSL_do_handshake will send keyupdate msg */
6895     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6896             || !TEST_int_eq(SSL_do_handshake(local), 1))
6897         goto end;
6898
6899     /*
6900      * write data in peer previously that we will complete
6901      * read data in local previously that we will complete
6902      */
6903     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), sizeof(pwbuf))
6904         || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), sizeof(lrbuf)))
6905         goto end;
6906
6907     /*
6908      * write data in local
6909      * read data in peer - we will read the key update
6910      */
6911     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
6912         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
6913         goto end;
6914
6915   /* Write more peer data to ensure we send the keyupdate message back */
6916     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
6917             || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), strlen(mess)))
6918         goto end;
6919
6920     testresult = 1;
6921
6922  end:
6923     SSL_free(serverssl);
6924     SSL_free(clientssl);
6925     SSL_CTX_free(sctx);
6926     SSL_CTX_free(cctx);
6927
6928     return testresult;
6929 }
6930 #endif /* OSSL_NO_USABLE_TLS1_3 */
6931
6932 static int test_ssl_clear(int idx)
6933 {
6934     SSL_CTX *cctx = NULL, *sctx = NULL;
6935     SSL *clientssl = NULL, *serverssl = NULL;
6936     int testresult = 0;
6937
6938 #ifdef OPENSSL_NO_TLS1_2
6939     if (idx == 1)
6940         return 1;
6941 #endif
6942
6943     /* Create an initial connection */
6944     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6945                                        TLS_client_method(), TLS1_VERSION, 0,
6946                                        &sctx, &cctx, cert, privkey))
6947             || (idx == 1
6948                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
6949                                                             TLS1_2_VERSION)))
6950             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6951                                           &clientssl, NULL, NULL))
6952             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6953                                                 SSL_ERROR_NONE)))
6954         goto end;
6955
6956     SSL_shutdown(clientssl);
6957     SSL_shutdown(serverssl);
6958     SSL_free(serverssl);
6959     serverssl = NULL;
6960
6961     /* Clear clientssl - we're going to reuse the object */
6962     if (!TEST_true(SSL_clear(clientssl)))
6963         goto end;
6964
6965     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6966                                              NULL, NULL))
6967             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6968                                                 SSL_ERROR_NONE))
6969             || !TEST_true(SSL_session_reused(clientssl)))
6970         goto end;
6971
6972     SSL_shutdown(clientssl);
6973     SSL_shutdown(serverssl);
6974
6975     testresult = 1;
6976
6977  end:
6978     SSL_free(serverssl);
6979     SSL_free(clientssl);
6980     SSL_CTX_free(sctx);
6981     SSL_CTX_free(cctx);
6982
6983     return testresult;
6984 }
6985
6986 /* Parse CH and retrieve any MFL extension value if present */
6987 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
6988 {
6989     long len;
6990     unsigned char *data;
6991     PACKET pkt, pkt2, pkt3;
6992     unsigned int MFL_code = 0, type = 0;
6993
6994     if (!TEST_uint_gt(len = BIO_get_mem_data(bio, (char **) &data), 0))
6995         goto end;
6996
6997     memset(&pkt, 0, sizeof(pkt));
6998     memset(&pkt2, 0, sizeof(pkt2));
6999     memset(&pkt3, 0, sizeof(pkt3));
7000
7001     if (!TEST_long_gt(len, 0)
7002             || !TEST_true(PACKET_buf_init(&pkt, data, len))
7003                /* Skip the record header */
7004             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
7005                /* Skip the handshake message header */
7006             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
7007                /* Skip client version and random */
7008             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
7009                                                + SSL3_RANDOM_SIZE))
7010                /* Skip session id */
7011             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7012                /* Skip ciphers */
7013             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
7014                /* Skip compression */
7015             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7016                /* Extensions len */
7017             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
7018         goto end;
7019
7020     /* Loop through all extensions */
7021     while (PACKET_remaining(&pkt2)) {
7022         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
7023                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
7024             goto end;
7025
7026         if (type == TLSEXT_TYPE_max_fragment_length) {
7027             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
7028                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
7029                 goto end;
7030
7031             *mfl_codemfl_code = MFL_code;
7032             return 1;
7033         }
7034     }
7035
7036  end:
7037     return 0;
7038 }
7039
7040 /* Maximum-Fragment-Length TLS extension mode to test */
7041 static const unsigned char max_fragment_len_test[] = {
7042     TLSEXT_max_fragment_length_512,
7043     TLSEXT_max_fragment_length_1024,
7044     TLSEXT_max_fragment_length_2048,
7045     TLSEXT_max_fragment_length_4096
7046 };
7047
7048 static int test_max_fragment_len_ext(int idx_tst)
7049 {
7050     SSL_CTX *ctx = NULL;
7051     SSL *con = NULL;
7052     int testresult = 0, MFL_mode = 0;
7053     BIO *rbio, *wbio;
7054
7055     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(),
7056                                        TLS1_VERSION, 0, NULL, &ctx, NULL,
7057                                        NULL)))
7058         return 0;
7059
7060     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
7061                    ctx, max_fragment_len_test[idx_tst])))
7062         goto end;
7063
7064     con = SSL_new(ctx);
7065     if (!TEST_ptr(con))
7066         goto end;
7067
7068     rbio = BIO_new(BIO_s_mem());
7069     wbio = BIO_new(BIO_s_mem());
7070     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
7071         BIO_free(rbio);
7072         BIO_free(wbio);
7073         goto end;
7074     }
7075
7076     SSL_set_bio(con, rbio, wbio);
7077
7078     if (!TEST_int_le(SSL_connect(con), 0)) {
7079         /* This shouldn't succeed because we don't have a server! */
7080         goto end;
7081     }
7082
7083     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
7084         /* no MFL in client hello */
7085         goto end;
7086     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
7087         goto end;
7088
7089     testresult = 1;
7090
7091 end:
7092     SSL_free(con);
7093     SSL_CTX_free(ctx);
7094
7095     return testresult;
7096 }
7097
7098 #ifndef OSSL_NO_USABLE_TLS1_3
7099 static int test_pha_key_update(void)
7100 {
7101     SSL_CTX *cctx = NULL, *sctx = NULL;
7102     SSL *clientssl = NULL, *serverssl = NULL;
7103     int testresult = 0;
7104
7105     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7106                                        TLS_client_method(), TLS1_VERSION, 0,
7107                                        &sctx, &cctx, cert, privkey)))
7108         return 0;
7109
7110     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
7111         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
7112         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
7113         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
7114         goto end;
7115
7116     SSL_CTX_set_post_handshake_auth(cctx, 1);
7117
7118     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7119                                       NULL, NULL)))
7120         goto end;
7121
7122     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7123                                          SSL_ERROR_NONE)))
7124         goto end;
7125
7126     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
7127     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
7128         goto end;
7129
7130     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
7131         goto end;
7132
7133     /* Start handshake on the server */
7134     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
7135         goto end;
7136
7137     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
7138     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7139                                          SSL_ERROR_NONE)))
7140         goto end;
7141
7142     SSL_shutdown(clientssl);
7143     SSL_shutdown(serverssl);
7144
7145     testresult = 1;
7146
7147  end:
7148     SSL_free(serverssl);
7149     SSL_free(clientssl);
7150     SSL_CTX_free(sctx);
7151     SSL_CTX_free(cctx);
7152     return testresult;
7153 }
7154 #endif
7155
7156 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7157
7158 static SRP_VBASE *vbase = NULL;
7159
7160 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
7161 {
7162     int ret = SSL3_AL_FATAL;
7163     char *username;
7164     SRP_user_pwd *user = NULL;
7165
7166     username = SSL_get_srp_username(s);
7167     if (username == NULL) {
7168         *ad = SSL_AD_INTERNAL_ERROR;
7169         goto err;
7170     }
7171
7172     user = SRP_VBASE_get1_by_user(vbase, username);
7173     if (user == NULL) {
7174         *ad = SSL_AD_INTERNAL_ERROR;
7175         goto err;
7176     }
7177
7178     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
7179                                  user->info) <= 0) {
7180         *ad = SSL_AD_INTERNAL_ERROR;
7181         goto err;
7182     }
7183
7184     ret = 0;
7185
7186  err:
7187     SRP_user_pwd_free(user);
7188     return ret;
7189 }
7190
7191 static int create_new_vfile(char *userid, char *password, const char *filename)
7192 {
7193     char *gNid = NULL;
7194     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
7195     TXT_DB *db = NULL;
7196     int ret = 0;
7197     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
7198     size_t i;
7199
7200     if (!TEST_ptr(dummy) || !TEST_ptr(row))
7201         goto end;
7202
7203     gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
7204                                   &row[DB_srpverifier], NULL, NULL, libctx, NULL);
7205     if (!TEST_ptr(gNid))
7206         goto end;
7207
7208     /*
7209      * The only way to create an empty TXT_DB is to provide a BIO with no data
7210      * in it!
7211      */
7212     db = TXT_DB_read(dummy, DB_NUMBER);
7213     if (!TEST_ptr(db))
7214         goto end;
7215
7216     out = BIO_new_file(filename, "w");
7217     if (!TEST_ptr(out))
7218         goto end;
7219
7220     row[DB_srpid] = OPENSSL_strdup(userid);
7221     row[DB_srptype] = OPENSSL_strdup("V");
7222     row[DB_srpgN] = OPENSSL_strdup(gNid);
7223
7224     if (!TEST_ptr(row[DB_srpid])
7225             || !TEST_ptr(row[DB_srptype])
7226             || !TEST_ptr(row[DB_srpgN])
7227             || !TEST_true(TXT_DB_insert(db, row)))
7228         goto end;
7229
7230     row = NULL;
7231
7232     if (TXT_DB_write(out, db) <= 0)
7233         goto end;
7234
7235     ret = 1;
7236  end:
7237     if (row != NULL) {
7238         for (i = 0; i < DB_NUMBER; i++)
7239             OPENSSL_free(row[i]);
7240     }
7241     OPENSSL_free(row);
7242     BIO_free(dummy);
7243     BIO_free(out);
7244     TXT_DB_free(db);
7245
7246     return ret;
7247 }
7248
7249 static int create_new_vbase(char *userid, char *password)
7250 {
7251     BIGNUM *verifier = NULL, *salt = NULL;
7252     const SRP_gN *lgN = NULL;
7253     SRP_user_pwd *user_pwd = NULL;
7254     int ret = 0;
7255
7256     lgN = SRP_get_default_gN(NULL);
7257     if (!TEST_ptr(lgN))
7258         goto end;
7259
7260     if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
7261                                              lgN->N, lgN->g, libctx, NULL)))
7262         goto end;
7263
7264     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
7265     if (!TEST_ptr(user_pwd))
7266         goto end;
7267
7268     user_pwd->N = lgN->N;
7269     user_pwd->g = lgN->g;
7270     user_pwd->id = OPENSSL_strdup(userid);
7271     if (!TEST_ptr(user_pwd->id))
7272         goto end;
7273
7274     user_pwd->v = verifier;
7275     user_pwd->s = salt;
7276     verifier = salt = NULL;
7277
7278     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
7279         goto end;
7280     user_pwd = NULL;
7281
7282     ret = 1;
7283 end:
7284     SRP_user_pwd_free(user_pwd);
7285     BN_free(salt);
7286     BN_free(verifier);
7287
7288     return ret;
7289 }
7290
7291 /*
7292  * SRP tests
7293  *
7294  * Test 0: Simple successful SRP connection, new vbase
7295  * Test 1: Connection failure due to bad password, new vbase
7296  * Test 2: Simple successful SRP connection, vbase loaded from existing file
7297  * Test 3: Connection failure due to bad password, vbase loaded from existing
7298  *         file
7299  * Test 4: Simple successful SRP connection, vbase loaded from new file
7300  * Test 5: Connection failure due to bad password, vbase loaded from new file
7301  */
7302 static int test_srp(int tst)
7303 {
7304     char *userid = "test", *password = "password", *tstsrpfile;
7305     SSL_CTX *cctx = NULL, *sctx = NULL;
7306     SSL *clientssl = NULL, *serverssl = NULL;
7307     int ret, testresult = 0;
7308
7309     vbase = SRP_VBASE_new(NULL);
7310     if (!TEST_ptr(vbase))
7311         goto end;
7312
7313     if (tst == 0 || tst == 1) {
7314         if (!TEST_true(create_new_vbase(userid, password)))
7315             goto end;
7316     } else {
7317         if (tst == 4 || tst == 5) {
7318             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
7319                 goto end;
7320             tstsrpfile = tmpfilename;
7321         } else {
7322             tstsrpfile = srpvfile;
7323         }
7324         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
7325             goto end;
7326     }
7327
7328     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7329                                        TLS_client_method(), TLS1_VERSION, 0,
7330                                        &sctx, &cctx, cert, privkey)))
7331         goto end;
7332
7333     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
7334             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
7335             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
7336             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
7337             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
7338         goto end;
7339
7340     if (tst % 2 == 1) {
7341         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
7342             goto end;
7343     } else {
7344         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
7345             goto end;
7346     }
7347
7348     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7349                                       NULL, NULL)))
7350         goto end;
7351
7352     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
7353     if (ret) {
7354         if (!TEST_true(tst % 2 == 0))
7355             goto end;
7356     } else {
7357         if (!TEST_true(tst % 2 == 1))
7358             goto end;
7359     }
7360
7361     testresult = 1;
7362
7363  end:
7364     SRP_VBASE_free(vbase);
7365     vbase = NULL;
7366     SSL_free(serverssl);
7367     SSL_free(clientssl);
7368     SSL_CTX_free(sctx);
7369     SSL_CTX_free(cctx);
7370
7371     return testresult;
7372 }
7373 #endif
7374
7375 static int info_cb_failed = 0;
7376 static int info_cb_offset = 0;
7377 static int info_cb_this_state = -1;
7378
7379 static struct info_cb_states_st {
7380     int where;
7381     const char *statestr;
7382 } info_cb_states[][60] = {
7383     {
7384         /* TLSv1.2 server followed by resumption */
7385         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7386         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7387         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
7388         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
7389         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
7390         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7391         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7392         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7393         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"},
7394         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7395         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
7396         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7397         {SSL_CB_EXIT, NULL}, {0, NULL},
7398     }, {
7399         /* TLSv1.2 client followed by resumption */
7400         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7401         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7402         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
7403         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
7404         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
7405         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7406         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7407         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7408         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7409         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7410         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
7411         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
7412     }, {
7413         /* TLSv1.3 server followed by resumption */
7414         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7415         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7416         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
7417         {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
7418         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
7419         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7420         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7421         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7422         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7423         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7424         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
7425         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7426         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7427     }, {
7428         /* TLSv1.3 client followed by resumption */
7429         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7430         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7431         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
7432         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
7433         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
7434         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7435         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"},
7436         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
7437         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7438         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
7439         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
7440         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7441         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7442         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"},
7443         {SSL_CB_EXIT, NULL}, {0, NULL},
7444     }, {
7445         /* TLSv1.3 server, early_data */
7446         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7447         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7448         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7449         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7450         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7451         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
7452         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7453         {SSL_CB_EXIT, NULL}, {0, NULL},
7454     }, {
7455         /* TLSv1.3 client, early_data */
7456         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7457         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
7458         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7459         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7460         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
7461         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
7462         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7463         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7464         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7465     }, {
7466         /* TLSv1.3 server, certificate compression, followed by resumption */
7467         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7468         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7469         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSCC"},
7470         {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
7471         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
7472         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7473         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7474         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7475         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7476         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7477         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
7478         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7479         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7480     }, {
7481         /* TLSv1.3 client, certificate compression, followed by resumption */
7482         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7483         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7484         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSCC"},
7485         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
7486         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
7487         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7488         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"},
7489         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
7490         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7491         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
7492         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
7493         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7494         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7495         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"},
7496         {SSL_CB_EXIT, NULL}, {0, NULL},
7497     }, {
7498         {0, NULL},
7499     }
7500 };
7501
7502 static void sslapi_info_callback(const SSL *s, int where, int ret)
7503 {
7504     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
7505
7506     /* We do not ever expect a connection to fail in this test */
7507     if (!TEST_false(ret == 0)) {
7508         info_cb_failed = 1;
7509         return;
7510     }
7511
7512     /*
7513      * Do some sanity checks. We never expect these things to happen in this
7514      * test
7515      */
7516     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
7517             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
7518             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
7519         info_cb_failed = 1;
7520         return;
7521     }
7522
7523     /* Now check we're in the right state */
7524     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
7525         info_cb_failed = 1;
7526         return;
7527     }
7528     if ((where & SSL_CB_LOOP) != 0
7529             && !TEST_int_eq(strcmp(SSL_state_string(s),
7530                             state[info_cb_this_state].statestr), 0)) {
7531         info_cb_failed = 1;
7532         return;
7533     }
7534
7535     /*
7536      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
7537      */
7538     if ((where & SSL_CB_HANDSHAKE_DONE)
7539             && SSL_in_init((SSL *)s) != 0) {
7540         info_cb_failed = 1;
7541         return;
7542     }
7543 }
7544
7545 /*
7546  * Test the info callback gets called when we expect it to.
7547  *
7548  * Test 0: TLSv1.2, server
7549  * Test 1: TLSv1.2, client
7550  * Test 2: TLSv1.3, server
7551  * Test 3: TLSv1.3, client
7552  * Test 4: TLSv1.3, server, early_data
7553  * Test 5: TLSv1.3, client, early_data
7554  * Test 6: TLSv1.3, server, compressed certificate
7555  * Test 7: TLSv1.3, client, compressed certificate
7556  */
7557 static int test_info_callback(int tst)
7558 {
7559     SSL_CTX *cctx = NULL, *sctx = NULL;
7560     SSL *clientssl = NULL, *serverssl = NULL;
7561     SSL_SESSION *clntsess = NULL;
7562     int testresult = 0;
7563     int tlsvers;
7564
7565     if (tst < 2) {
7566 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
7567 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
7568                                     || !defined(OPENSSL_NO_DH))
7569         tlsvers = TLS1_2_VERSION;
7570 #else
7571         return 1;
7572 #endif
7573     } else {
7574 #ifndef OSSL_NO_USABLE_TLS1_3
7575         tlsvers = TLS1_3_VERSION;
7576 #else
7577         return 1;
7578 #endif
7579     }
7580
7581     /* Reset globals */
7582     info_cb_failed = 0;
7583     info_cb_this_state = -1;
7584     info_cb_offset = tst;
7585
7586 #ifndef OSSL_NO_USABLE_TLS1_3
7587     if (tst >= 4 && tst < 6) {
7588         SSL_SESSION *sess = NULL;
7589         size_t written, readbytes;
7590         unsigned char buf[80];
7591
7592         /* early_data tests */
7593         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
7594                                             &serverssl, &sess, 0,
7595                                             SHA384_DIGEST_LENGTH)))
7596             goto end;
7597
7598         /* We don't actually need this reference */
7599         SSL_SESSION_free(sess);
7600
7601         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
7602                               sslapi_info_callback);
7603
7604         /* Write and read some early data and then complete the connection */
7605         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
7606                                             &written))
7607                 || !TEST_size_t_eq(written, strlen(MSG1))
7608                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
7609                                                     sizeof(buf), &readbytes),
7610                                 SSL_READ_EARLY_DATA_SUCCESS)
7611                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
7612                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
7613                                 SSL_EARLY_DATA_ACCEPTED)
7614                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
7615                                                     SSL_ERROR_NONE))
7616                 || !TEST_false(info_cb_failed))
7617             goto end;
7618
7619         testresult = 1;
7620         goto end;
7621     }
7622 #endif
7623
7624     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7625                                        TLS_client_method(),
7626                                        tlsvers, tlsvers, &sctx, &cctx, cert,
7627                                        privkey)))
7628         goto end;
7629
7630     if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
7631         goto end;
7632
7633     /*
7634      * For even numbered tests we check the server callbacks. For odd numbers we
7635      * check the client.
7636      */
7637     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
7638                               sslapi_info_callback);
7639     if (tst >= 6) {
7640         if (!SSL_CTX_compress_certs(sctx, 0))
7641             goto end;
7642     }
7643
7644     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
7645                                           &clientssl, NULL, NULL))
7646         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7647                                             SSL_ERROR_NONE))
7648         || !TEST_false(info_cb_failed))
7649     goto end;
7650
7651
7652
7653     clntsess = SSL_get1_session(clientssl);
7654     SSL_shutdown(clientssl);
7655     SSL_shutdown(serverssl);
7656     SSL_free(serverssl);
7657     SSL_free(clientssl);
7658     serverssl = clientssl = NULL;
7659
7660     /* Now do a resumption */
7661     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
7662                                       NULL))
7663             || !TEST_true(SSL_set_session(clientssl, clntsess))
7664             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7665                                                 SSL_ERROR_NONE))
7666             || !TEST_true(SSL_session_reused(clientssl))
7667             || !TEST_false(info_cb_failed))
7668         goto end;
7669
7670     testresult = 1;
7671
7672  end:
7673     SSL_free(serverssl);
7674     SSL_free(clientssl);
7675     SSL_SESSION_free(clntsess);
7676     SSL_CTX_free(sctx);
7677     SSL_CTX_free(cctx);
7678     return testresult;
7679 }
7680
7681 static int test_ssl_pending(int tst)
7682 {
7683     SSL_CTX *cctx = NULL, *sctx = NULL;
7684     SSL *clientssl = NULL, *serverssl = NULL;
7685     int testresult = 0;
7686     char msg[] = "A test message";
7687     char buf[5];
7688     size_t written, readbytes;
7689
7690     if (tst == 0) {
7691         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7692                                            TLS_client_method(),
7693                                            TLS1_VERSION, 0,
7694                                            &sctx, &cctx, cert, privkey)))
7695             goto end;
7696     } else {
7697 #ifndef OPENSSL_NO_DTLS
7698         if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
7699                                            DTLS_client_method(),
7700                                            DTLS1_VERSION, 0,
7701                                            &sctx, &cctx, cert, privkey)))
7702             goto end;
7703
7704 # ifdef OPENSSL_NO_DTLS1_2
7705         /* Not supported in the FIPS provider */
7706         if (is_fips) {
7707             testresult = 1;
7708             goto end;
7709         };
7710         /*
7711          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
7712          * level 0
7713          */
7714         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
7715                 || !TEST_true(SSL_CTX_set_cipher_list(cctx,
7716                                                     "DEFAULT:@SECLEVEL=0")))
7717             goto end;
7718 # endif
7719 #else
7720         return 1;
7721 #endif
7722     }
7723
7724     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7725                                              NULL, NULL))
7726             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7727                                                 SSL_ERROR_NONE)))
7728         goto end;
7729
7730     if (!TEST_int_eq(SSL_pending(clientssl), 0)
7731             || !TEST_false(SSL_has_pending(clientssl))
7732             || !TEST_int_eq(SSL_pending(serverssl), 0)
7733             || !TEST_false(SSL_has_pending(serverssl))
7734             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
7735             || !TEST_size_t_eq(written, sizeof(msg))
7736             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
7737             || !TEST_size_t_eq(readbytes, sizeof(buf))
7738             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
7739             || !TEST_true(SSL_has_pending(clientssl)))
7740         goto end;
7741
7742     testresult = 1;
7743
7744  end:
7745     SSL_free(serverssl);
7746     SSL_free(clientssl);
7747     SSL_CTX_free(sctx);
7748     SSL_CTX_free(cctx);
7749
7750     return testresult;
7751 }
7752
7753 static struct {
7754     unsigned int maxprot;
7755     const char *clntciphers;
7756     const char *clnttls13ciphers;
7757     const char *srvrciphers;
7758     const char *srvrtls13ciphers;
7759     const char *shared;
7760     const char *fipsshared;
7761 } shared_ciphers_data[] = {
7762 /*
7763  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
7764  * TLSv1.3 is enabled but TLSv1.2 is disabled.
7765  */
7766 #if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
7767     {
7768         TLS1_2_VERSION,
7769         "AES128-SHA:AES256-SHA",
7770         NULL,
7771         "AES256-SHA:DHE-RSA-AES128-SHA",
7772         NULL,
7773         "AES256-SHA",
7774         "AES256-SHA"
7775     },
7776 # if !defined(OPENSSL_NO_CHACHA) \
7777      && !defined(OPENSSL_NO_POLY1305) \
7778      && !defined(OPENSSL_NO_EC)
7779     {
7780         TLS1_2_VERSION,
7781         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
7782         NULL,
7783         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
7784         NULL,
7785         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
7786         "AES128-SHA"
7787     },
7788 # endif
7789     {
7790         TLS1_2_VERSION,
7791         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
7792         NULL,
7793         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
7794         NULL,
7795         "AES128-SHA:AES256-SHA",
7796         "AES128-SHA:AES256-SHA"
7797     },
7798     {
7799         TLS1_2_VERSION,
7800         "AES128-SHA:AES256-SHA",
7801         NULL,
7802         "AES128-SHA:DHE-RSA-AES128-SHA",
7803         NULL,
7804         "AES128-SHA",
7805         "AES128-SHA"
7806     },
7807 #endif
7808 /*
7809  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
7810  * enabled.
7811  */
7812 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
7813     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
7814     {
7815         TLS1_3_VERSION,
7816         "AES128-SHA:AES256-SHA",
7817         NULL,
7818         "AES256-SHA:AES128-SHA256",
7819         NULL,
7820         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
7821         "TLS_AES_128_GCM_SHA256:AES256-SHA",
7822         "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA"
7823     },
7824 #endif
7825 #ifndef OSSL_NO_USABLE_TLS1_3
7826     {
7827         TLS1_3_VERSION,
7828         "AES128-SHA",
7829         "TLS_AES_256_GCM_SHA384",
7830         "AES256-SHA",
7831         "TLS_AES_256_GCM_SHA384",
7832         "TLS_AES_256_GCM_SHA384",
7833         "TLS_AES_256_GCM_SHA384"
7834     },
7835 #endif
7836 };
7837
7838 static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
7839 {
7840     SSL_CTX *cctx = NULL, *sctx = NULL;
7841     SSL *clientssl = NULL, *serverssl = NULL;
7842     int testresult = 0;
7843     char buf[1024];
7844     OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
7845
7846     if (!TEST_ptr(tmplibctx))
7847         goto end;
7848
7849     /*
7850      * Regardless of whether we're testing with the FIPS provider loaded into
7851      * libctx, we want one peer to always use the full set of ciphersuites
7852      * available. Therefore we use a separate libctx with the default provider
7853      * loaded into it. We run the same tests twice - once with the client side
7854      * having the full set of ciphersuites and once with the server side.
7855      */
7856     if (clnt) {
7857         cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
7858         if (!TEST_ptr(cctx))
7859             goto end;
7860     } else {
7861         sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
7862         if (!TEST_ptr(sctx))
7863             goto end;
7864     }
7865
7866     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7867                                        TLS_client_method(),
7868                                        TLS1_VERSION,
7869                                        shared_ciphers_data[tst].maxprot,
7870                                        &sctx, &cctx, cert, privkey)))
7871         goto end;
7872
7873     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
7874                                         shared_ciphers_data[tst].clntciphers))
7875             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
7876                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
7877                                     shared_ciphers_data[tst].clnttls13ciphers)))
7878             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
7879                                         shared_ciphers_data[tst].srvrciphers))
7880             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
7881                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
7882                                     shared_ciphers_data[tst].srvrtls13ciphers))))
7883         goto end;
7884
7885
7886     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7887                                              NULL, NULL))
7888             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7889                                                 SSL_ERROR_NONE)))
7890         goto end;
7891
7892     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
7893             || !TEST_int_eq(strcmp(buf,
7894                                    is_fips
7895                                    ? shared_ciphers_data[tst].fipsshared
7896                                    : shared_ciphers_data[tst].shared),
7897                                    0)) {
7898         TEST_info("Shared ciphers are: %s\n", buf);
7899         goto end;
7900     }
7901
7902     testresult = 1;
7903
7904  end:
7905     SSL_free(serverssl);
7906     SSL_free(clientssl);
7907     SSL_CTX_free(sctx);
7908     SSL_CTX_free(cctx);
7909     OSSL_LIB_CTX_free(tmplibctx);
7910
7911     return testresult;
7912 }
7913
7914 static int test_ssl_get_shared_ciphers(int tst)
7915 {
7916     return int_test_ssl_get_shared_ciphers(tst, 0)
7917            && int_test_ssl_get_shared_ciphers(tst, 1);
7918 }
7919
7920
7921 static const char *appdata = "Hello World";
7922 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
7923 static int tick_key_renew = 0;
7924 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
7925
7926 static int gen_tick_cb(SSL *s, void *arg)
7927 {
7928     gen_tick_called = 1;
7929
7930     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
7931                                            strlen(appdata));
7932 }
7933
7934 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
7935                                      const unsigned char *keyname,
7936                                      size_t keyname_length,
7937                                      SSL_TICKET_STATUS status,
7938                                      void *arg)
7939 {
7940     void *tickdata;
7941     size_t tickdlen;
7942
7943     dec_tick_called = 1;
7944
7945     if (status == SSL_TICKET_EMPTY)
7946         return SSL_TICKET_RETURN_IGNORE_RENEW;
7947
7948     if (!TEST_true(status == SSL_TICKET_SUCCESS
7949                    || status == SSL_TICKET_SUCCESS_RENEW))
7950         return SSL_TICKET_RETURN_ABORT;
7951
7952     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
7953                                                    &tickdlen))
7954             || !TEST_size_t_eq(tickdlen, strlen(appdata))
7955             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
7956         return SSL_TICKET_RETURN_ABORT;
7957
7958     if (tick_key_cb_called)  {
7959         /* Don't change what the ticket key callback wanted to do */
7960         switch (status) {
7961         case SSL_TICKET_NO_DECRYPT:
7962             return SSL_TICKET_RETURN_IGNORE_RENEW;
7963
7964         case SSL_TICKET_SUCCESS:
7965             return SSL_TICKET_RETURN_USE;
7966
7967         case SSL_TICKET_SUCCESS_RENEW:
7968             return SSL_TICKET_RETURN_USE_RENEW;
7969
7970         default:
7971             return SSL_TICKET_RETURN_ABORT;
7972         }
7973     }
7974     return tick_dec_ret;
7975
7976 }
7977
7978 #ifndef OPENSSL_NO_DEPRECATED_3_0
7979 static int tick_key_cb(SSL *s, unsigned char key_name[16],
7980                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
7981                        HMAC_CTX *hctx, int enc)
7982 {
7983     const unsigned char tick_aes_key[16] = "0123456789abcdef";
7984     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
7985     EVP_CIPHER *aes128cbc;
7986     EVP_MD *sha256;
7987     int ret;
7988
7989     tick_key_cb_called = 1;
7990
7991     if (tick_key_renew == -1)
7992         return 0;
7993
7994     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
7995     if (!TEST_ptr(aes128cbc))
7996         return 0;
7997     sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
7998     if (!TEST_ptr(sha256)) {
7999         EVP_CIPHER_free(aes128cbc);
8000         return 0;
8001     }
8002
8003     memset(iv, 0, AES_BLOCK_SIZE);
8004     memset(key_name, 0, 16);
8005     if (aes128cbc == NULL
8006             || sha256 == NULL
8007             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8008             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
8009                              NULL))
8010         ret = -1;
8011     else
8012         ret = tick_key_renew ? 2 : 1;
8013
8014     EVP_CIPHER_free(aes128cbc);
8015     EVP_MD_free(sha256);
8016
8017     return ret;
8018 }
8019 #endif
8020
8021 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
8022                            unsigned char iv[EVP_MAX_IV_LENGTH],
8023                            EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
8024 {
8025     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8026     unsigned char tick_hmac_key[16] = "0123456789abcdef";
8027     OSSL_PARAM params[2];
8028     EVP_CIPHER *aes128cbc;
8029     int ret;
8030
8031     tick_key_cb_called = 1;
8032
8033     if (tick_key_renew == -1)
8034         return 0;
8035
8036     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8037     if (!TEST_ptr(aes128cbc))
8038         return 0;
8039
8040     memset(iv, 0, AES_BLOCK_SIZE);
8041     memset(key_name, 0, 16);
8042     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
8043                                                  "SHA256", 0);
8044     params[1] = OSSL_PARAM_construct_end();
8045     if (aes128cbc == NULL
8046             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8047             || !EVP_MAC_init(hctx, tick_hmac_key, sizeof(tick_hmac_key),
8048                              params))
8049         ret = -1;
8050     else
8051         ret = tick_key_renew ? 2 : 1;
8052
8053     EVP_CIPHER_free(aes128cbc);
8054
8055     return ret;
8056 }
8057
8058 /*
8059  * Test the various ticket callbacks
8060  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
8061  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
8062  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
8063  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
8064  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
8065  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
8066  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
8067  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
8068  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
8069  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
8070  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
8071  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
8072  * Test 12: TLSv1.2, old ticket key callback, no ticket
8073  * Test 13: TLSv1.3, old ticket key callback, no ticket
8074  * Test 14: TLSv1.2, ticket key callback, ticket, no renewal
8075  * Test 15: TLSv1.3, ticket key callback, ticket, no renewal
8076  * Test 16: TLSv1.2, ticket key callback, ticket, renewal
8077  * Test 17: TLSv1.3, ticket key callback, ticket, renewal
8078  * Test 18: TLSv1.2, ticket key callback, no ticket
8079  * Test 19: TLSv1.3, ticket key callback, no ticket
8080  */
8081 static int test_ticket_callbacks(int tst)
8082 {
8083     SSL_CTX *cctx = NULL, *sctx = NULL;
8084     SSL *clientssl = NULL, *serverssl = NULL;
8085     SSL_SESSION *clntsess = NULL;
8086     int testresult = 0;
8087
8088 #ifdef OPENSSL_NO_TLS1_2
8089     if (tst % 2 == 0)
8090         return 1;
8091 #endif
8092 #ifdef OSSL_NO_USABLE_TLS1_3
8093     if (tst % 2 == 1)
8094         return 1;
8095 #endif
8096 #ifdef OPENSSL_NO_DEPRECATED_3_0
8097     if (tst >= 8 && tst <= 13)
8098         return 1;
8099 #endif
8100
8101     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
8102
8103     /* Which tests the ticket key callback should request renewal for */
8104
8105     if (tst == 10 || tst == 11 || tst == 16 || tst == 17)
8106         tick_key_renew = 1;
8107     else if (tst == 12 || tst == 13 || tst == 18 || tst == 19)
8108         tick_key_renew = -1; /* abort sending the ticket/0-length ticket */
8109     else
8110         tick_key_renew = 0;
8111
8112     /* Which tests the decrypt ticket callback should request renewal for */
8113     switch (tst) {
8114     case 0:
8115     case 1:
8116         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
8117         break;
8118
8119     case 2:
8120     case 3:
8121         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
8122         break;
8123
8124     case 4:
8125     case 5:
8126         tick_dec_ret = SSL_TICKET_RETURN_USE;
8127         break;
8128
8129     case 6:
8130     case 7:
8131         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
8132         break;
8133
8134     default:
8135         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8136     }
8137
8138     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8139                                        TLS_client_method(),
8140                                        TLS1_VERSION,
8141                                        ((tst % 2) == 0) ? TLS1_2_VERSION
8142                                                         : TLS1_3_VERSION,
8143                                        &sctx, &cctx, cert, privkey)))
8144         goto end;
8145
8146     /*
8147      * We only want sessions to resume from tickets - not the session cache. So
8148      * switch the cache off.
8149      */
8150     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
8151         goto end;
8152
8153     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
8154                                                  NULL)))
8155         goto end;
8156
8157     if (tst >= 14) {
8158         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
8159             goto end;
8160 #ifndef OPENSSL_NO_DEPRECATED_3_0
8161     } else if (tst >= 8) {
8162         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
8163             goto end;
8164 #endif
8165     }
8166
8167     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8168                                              NULL, NULL))
8169             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8170                                                 SSL_ERROR_NONE)))
8171         goto end;
8172
8173     /*
8174      * The decrypt ticket key callback in TLSv1.2 should be called even though
8175      * we have no ticket yet, because it gets called with a status of
8176      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
8177      * actually send any ticket data). This does not happen in TLSv1.3 because
8178      * it is not valid to send empty ticket data in TLSv1.3.
8179      */
8180     if (!TEST_int_eq(gen_tick_called, 1)
8181             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
8182         goto end;
8183
8184     gen_tick_called = dec_tick_called = 0;
8185
8186     clntsess = SSL_get1_session(clientssl);
8187     SSL_shutdown(clientssl);
8188     SSL_shutdown(serverssl);
8189     SSL_free(serverssl);
8190     SSL_free(clientssl);
8191     serverssl = clientssl = NULL;
8192
8193     /* Now do a resumption */
8194     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8195                                       NULL))
8196             || !TEST_true(SSL_set_session(clientssl, clntsess))
8197             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8198                                                 SSL_ERROR_NONE)))
8199         goto end;
8200
8201     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
8202             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8203             || tick_key_renew == -1) {
8204         if (!TEST_false(SSL_session_reused(clientssl)))
8205             goto end;
8206     } else {
8207         if (!TEST_true(SSL_session_reused(clientssl)))
8208             goto end;
8209     }
8210
8211     if (!TEST_int_eq(gen_tick_called,
8212                      (tick_key_renew
8213                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8214                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
8215                      ? 1 : 0)
8216                /* There is no ticket to decrypt in tests 13 and 19 */
8217             || !TEST_int_eq(dec_tick_called, (tst == 13 || tst == 19) ? 0 : 1))
8218         goto end;
8219
8220     testresult = 1;
8221
8222  end:
8223     SSL_SESSION_free(clntsess);
8224     SSL_free(serverssl);
8225     SSL_free(clientssl);
8226     SSL_CTX_free(sctx);
8227     SSL_CTX_free(cctx);
8228
8229     return testresult;
8230 }
8231
8232 /*
8233  * Test incorrect shutdown.
8234  * Test 0: client does not shutdown properly,
8235  *         server does not set SSL_OP_IGNORE_UNEXPECTED_EOF,
8236  *         server should get SSL_ERROR_SSL
8237  * Test 1: client does not shutdown properly,
8238  *         server sets SSL_OP_IGNORE_UNEXPECTED_EOF,
8239  *         server should get SSL_ERROR_ZERO_RETURN
8240  */
8241 static int test_incorrect_shutdown(int tst)
8242 {
8243     SSL_CTX *cctx = NULL, *sctx = NULL;
8244     SSL *clientssl = NULL, *serverssl = NULL;
8245     int testresult = 0;
8246     char buf[80];
8247     BIO *c2s;
8248
8249     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8250                                        TLS_client_method(), 0, 0,
8251                                        &sctx, &cctx, cert, privkey)))
8252         goto end;
8253
8254     if (tst == 1)
8255         SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
8256
8257     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8258                                             NULL, NULL)))
8259         goto end;
8260
8261     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8262                                               SSL_ERROR_NONE)))
8263         goto end;
8264
8265     c2s = SSL_get_rbio(serverssl);
8266     BIO_set_mem_eof_return(c2s, 0);
8267
8268     if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf))))
8269         goto end;
8270
8271     if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL) )
8272         goto end;
8273     if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN) )
8274         goto end;
8275
8276     testresult = 1;
8277
8278  end:
8279     SSL_free(serverssl);
8280     SSL_free(clientssl);
8281     SSL_CTX_free(sctx);
8282     SSL_CTX_free(cctx);
8283
8284     return testresult;
8285 }
8286
8287 /*
8288  * Test bi-directional shutdown.
8289  * Test 0: TLSv1.2
8290  * Test 1: TLSv1.2, server continues to read/write after client shutdown
8291  * Test 2: TLSv1.3, no pending NewSessionTicket messages
8292  * Test 3: TLSv1.3, pending NewSessionTicket messages
8293  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
8294  *                  sends key update, client reads it
8295  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
8296  *                  sends CertificateRequest, client reads and ignores it
8297  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
8298  *                  doesn't read it
8299  */
8300 static int test_shutdown(int tst)
8301 {
8302     SSL_CTX *cctx = NULL, *sctx = NULL;
8303     SSL *clientssl = NULL, *serverssl = NULL;
8304     int testresult = 0;
8305     char msg[] = "A test message";
8306     char buf[80];
8307     size_t written, readbytes;
8308     SSL_SESSION *sess;
8309
8310 #ifdef OPENSSL_NO_TLS1_2
8311     if (tst <= 1)
8312         return 1;
8313 #endif
8314 #ifdef OSSL_NO_USABLE_TLS1_3
8315     if (tst >= 2)
8316         return 1;
8317 #endif
8318
8319     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8320                                        TLS_client_method(),
8321                                        TLS1_VERSION,
8322                                        (tst <= 1) ? TLS1_2_VERSION
8323                                                   : TLS1_3_VERSION,
8324                                        &sctx, &cctx, cert, privkey)))
8325         goto end;
8326
8327     if (tst == 5)
8328         SSL_CTX_set_post_handshake_auth(cctx, 1);
8329
8330     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8331                                              NULL, NULL)))
8332         goto end;
8333
8334     if (tst == 3) {
8335         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
8336                                                   SSL_ERROR_NONE, 1, 0))
8337                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8338                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
8339             goto end;
8340     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8341                                               SSL_ERROR_NONE))
8342             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8343             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
8344         goto end;
8345     }
8346
8347     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8348         goto end;
8349
8350     if (tst >= 4) {
8351         /*
8352          * Reading on the server after the client has sent close_notify should
8353          * fail and provide SSL_ERROR_ZERO_RETURN
8354          */
8355         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
8356                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
8357                                 SSL_ERROR_ZERO_RETURN)
8358                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
8359                                 SSL_RECEIVED_SHUTDOWN)
8360                    /*
8361                     * Even though we're shutdown on receive we should still be
8362                     * able to write.
8363                     */
8364                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8365             goto end;
8366         if (tst == 4
8367                 && !TEST_true(SSL_key_update(serverssl,
8368                                              SSL_KEY_UPDATE_REQUESTED)))
8369             goto end;
8370         if (tst == 5) {
8371             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
8372             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
8373                 goto end;
8374         }
8375         if ((tst == 4 || tst == 5)
8376                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8377             goto end;
8378         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8379             goto end;
8380         if (tst == 4 || tst == 5) {
8381             /* Should still be able to read data from server */
8382             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8383                                        &readbytes))
8384                     || !TEST_size_t_eq(readbytes, sizeof(msg))
8385                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
8386                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8387                                               &readbytes))
8388                     || !TEST_size_t_eq(readbytes, sizeof(msg))
8389                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
8390                 goto end;
8391         }
8392     }
8393
8394     /* Writing on the client after sending close_notify shouldn't be possible */
8395     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
8396         goto end;
8397
8398     if (tst < 4) {
8399         /*
8400          * For these tests the client has sent close_notify but it has not yet
8401          * been received by the server. The server has not sent close_notify
8402          * yet.
8403          */
8404         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
8405                    /*
8406                     * Writing on the server after sending close_notify shouldn't
8407                     * be possible.
8408                     */
8409                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8410                 || !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                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
8414             goto end;
8415     } else if (tst == 4 || tst == 5) {
8416         /*
8417          * In this test the client has sent close_notify and it has been
8418          * received by the server which has responded with a close_notify. The
8419          * client needs to read the close_notify sent by the server.
8420          */
8421         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
8422                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8423                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
8424             goto end;
8425     } else {
8426         /*
8427          * tst == 6
8428          *
8429          * The client has sent close_notify and is expecting a close_notify
8430          * back, but instead there is application data first. The shutdown
8431          * should fail with a fatal error.
8432          */
8433         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
8434                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
8435             goto end;
8436     }
8437
8438     testresult = 1;
8439
8440  end:
8441     SSL_free(serverssl);
8442     SSL_free(clientssl);
8443     SSL_CTX_free(sctx);
8444     SSL_CTX_free(cctx);
8445
8446     return testresult;
8447 }
8448
8449 /*
8450  * Test that sending close_notify alerts works correctly in the case of a
8451  * retryable write failure.
8452  */
8453 static int test_async_shutdown(void)
8454 {
8455     SSL_CTX *cctx = NULL, *sctx = NULL;
8456     SSL *clientssl = NULL, *serverssl = NULL;
8457     int testresult = 0;
8458     BIO *bretry = BIO_new(bio_s_always_retry()), *tmp = NULL;
8459
8460     if (!TEST_ptr(bretry))
8461         goto end;
8462
8463     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8464                                        TLS_client_method(),
8465                                        0, 0,
8466                                        &sctx, &cctx, cert, privkey)))
8467         goto end;
8468
8469     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8470                                       NULL)))
8471         goto end;
8472
8473     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8474         goto end;
8475
8476     /* Close write side of clientssl */
8477     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8478         goto end;
8479
8480     tmp = SSL_get_wbio(serverssl);
8481     if (!TEST_true(BIO_up_ref(tmp))) {
8482         tmp = NULL;
8483         goto end;
8484     }
8485     SSL_set0_wbio(serverssl, bretry);
8486     bretry = NULL;
8487
8488     /* First server shutdown should fail because of a retrable write failure */
8489     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
8490             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
8491         goto end;
8492
8493     /* Second server shutdown should fail for the same reason */
8494     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
8495             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
8496         goto end;
8497
8498     SSL_set0_wbio(serverssl, tmp);
8499     tmp = NULL;
8500
8501     /* Third server shutdown should send close_notify */
8502     if (!TEST_int_eq(SSL_shutdown(serverssl), 0))
8503         goto end;
8504
8505     /* Fourth server shutdown should read close_notify from client and finish */
8506     if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8507         goto end;
8508
8509     /* Client should also successfully fully shutdown */
8510     if (!TEST_int_eq(SSL_shutdown(clientssl), 1))
8511         goto end;
8512
8513     testresult = 1;
8514  end:
8515     SSL_free(serverssl);
8516     SSL_free(clientssl);
8517     SSL_CTX_free(sctx);
8518     SSL_CTX_free(cctx);
8519     BIO_free(bretry);
8520     BIO_free(tmp);
8521
8522     return testresult;
8523 }
8524
8525 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
8526 static int cert_cb_cnt;
8527
8528 static int cert_cb(SSL *s, void *arg)
8529 {
8530     SSL_CTX *ctx = (SSL_CTX *)arg;
8531     BIO *in = NULL;
8532     EVP_PKEY *pkey = NULL;
8533     X509 *x509 = NULL, *rootx = NULL;
8534     STACK_OF(X509) *chain = NULL;
8535     char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
8536     int ret = 0;
8537
8538     if (cert_cb_cnt == 0) {
8539         /* Suspend the handshake */
8540         cert_cb_cnt++;
8541         return -1;
8542     } else if (cert_cb_cnt == 1) {
8543         /*
8544          * Update the SSL_CTX, set the certificate and private key and then
8545          * continue the handshake normally.
8546          */
8547         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
8548             return 0;
8549
8550         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
8551                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
8552                                                       SSL_FILETYPE_PEM))
8553                 || !TEST_true(SSL_check_private_key(s)))
8554             return 0;
8555         cert_cb_cnt++;
8556         return 1;
8557     } else if (cert_cb_cnt == 3) {
8558         int rv;
8559
8560         rootfile = test_mk_file_path(certsdir, "rootcert.pem");
8561         ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
8562         ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
8563         if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
8564             goto out;
8565         chain = sk_X509_new_null();
8566         if (!TEST_ptr(chain))
8567             goto out;
8568         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8569                 || !TEST_int_gt(BIO_read_filename(in, rootfile), 0)
8570                 || !TEST_ptr(rootx = X509_new_ex(libctx, NULL))
8571                 || !TEST_ptr(PEM_read_bio_X509(in, &rootx, NULL, NULL))
8572                 || !TEST_true(sk_X509_push(chain, rootx)))
8573             goto out;
8574         rootx = NULL;
8575         BIO_free(in);
8576         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8577                 || !TEST_int_gt(BIO_read_filename(in, ecdsacert), 0)
8578                 || !TEST_ptr(x509 = X509_new_ex(libctx, NULL))
8579                 || !TEST_ptr(PEM_read_bio_X509(in, &x509, NULL, NULL)))
8580             goto out;
8581         BIO_free(in);
8582         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8583                 || !TEST_int_gt(BIO_read_filename(in, ecdsakey), 0)
8584                 || !TEST_ptr(pkey = PEM_read_bio_PrivateKey_ex(in, NULL,
8585                                                                NULL, NULL,
8586                                                                libctx, NULL)))
8587             goto out;
8588         rv = SSL_check_chain(s, x509, pkey, chain);
8589         /*
8590          * If the cert doesn't show as valid here (e.g., because we don't
8591          * have any shared sigalgs), then we will not set it, and there will
8592          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
8593          * will cause tls_choose_sigalgs() to fail the connection.
8594          */
8595         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
8596                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
8597             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
8598                 goto out;
8599         }
8600
8601         ret = 1;
8602     }
8603
8604     /* Abort the handshake */
8605  out:
8606     OPENSSL_free(ecdsacert);
8607     OPENSSL_free(ecdsakey);
8608     OPENSSL_free(rootfile);
8609     BIO_free(in);
8610     EVP_PKEY_free(pkey);
8611     X509_free(x509);
8612     X509_free(rootx);
8613     OSSL_STACK_OF_X509_free(chain);
8614     return ret;
8615 }
8616
8617 /*
8618  * Test the certificate callback.
8619  * Test 0: Callback fails
8620  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
8621  * Test 2: Success - SSL_set_SSL_CTX() in the callback
8622  * Test 3: Success - Call SSL_check_chain from the callback
8623  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
8624  *                   chain
8625  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
8626  */
8627 static int test_cert_cb_int(int prot, int tst)
8628 {
8629     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
8630     SSL *clientssl = NULL, *serverssl = NULL;
8631     int testresult = 0, ret;
8632
8633 #ifdef OPENSSL_NO_EC
8634     /* We use an EC cert in these tests, so we skip in a no-ec build */
8635     if (tst >= 3)
8636         return 1;
8637 #endif
8638
8639     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8640                                        TLS_client_method(),
8641                                        TLS1_VERSION,
8642                                        prot,
8643                                        &sctx, &cctx, NULL, NULL)))
8644         goto end;
8645
8646     if (tst == 0)
8647         cert_cb_cnt = -1;
8648     else if (tst >= 3)
8649         cert_cb_cnt = 3;
8650     else
8651         cert_cb_cnt = 0;
8652
8653     if (tst == 2) {
8654         snictx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
8655         if (!TEST_ptr(snictx))
8656             goto end;
8657     }
8658
8659     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
8660
8661     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8662                                       NULL, NULL)))
8663         goto end;
8664
8665     if (tst == 4) {
8666         /*
8667          * We cause SSL_check_chain() to fail by specifying sig_algs that
8668          * the chain doesn't meet (the root uses an RSA cert)
8669          */
8670         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
8671                                              "ecdsa_secp256r1_sha256")))
8672             goto end;
8673     } else if (tst == 5) {
8674         /*
8675          * We cause SSL_check_chain() to fail by specifying sig_algs that
8676          * the ee cert doesn't meet (the ee uses an ECDSA cert)
8677          */
8678         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
8679                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
8680             goto end;
8681     }
8682
8683     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
8684     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
8685             || (tst > 0
8686                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
8687         goto end;
8688     }
8689
8690     testresult = 1;
8691
8692  end:
8693     SSL_free(serverssl);
8694     SSL_free(clientssl);
8695     SSL_CTX_free(sctx);
8696     SSL_CTX_free(cctx);
8697     SSL_CTX_free(snictx);
8698
8699     return testresult;
8700 }
8701 #endif
8702
8703 static int test_cert_cb(int tst)
8704 {
8705     int testresult = 1;
8706
8707 #ifndef OPENSSL_NO_TLS1_2
8708     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
8709 #endif
8710 #ifndef OSSL_NO_USABLE_TLS1_3
8711     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
8712 #endif
8713
8714     return testresult;
8715 }
8716
8717 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
8718 {
8719     X509 *xcert;
8720     EVP_PKEY *privpkey;
8721     BIO *in = NULL;
8722     BIO *priv_in = NULL;
8723
8724     /* Check that SSL_get0_peer_certificate() returns something sensible */
8725     if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
8726         return 0;
8727
8728     in = BIO_new_file(cert, "r");
8729     if (!TEST_ptr(in))
8730         return 0;
8731
8732     if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL))
8733             || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
8734             || !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
8735             || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
8736                                                                NULL, NULL,
8737                                                                libctx, NULL)))
8738         goto err;
8739
8740     *x509 = xcert;
8741     *pkey = privpkey;
8742
8743     BIO_free(in);
8744     BIO_free(priv_in);
8745     return 1;
8746 err:
8747     X509_free(xcert);
8748     BIO_free(in);
8749     BIO_free(priv_in);
8750     return 0;
8751 }
8752
8753 static int test_client_cert_cb(int tst)
8754 {
8755     SSL_CTX *cctx = NULL, *sctx = NULL;
8756     SSL *clientssl = NULL, *serverssl = NULL;
8757     int testresult = 0;
8758
8759 #ifdef OPENSSL_NO_TLS1_2
8760     if (tst == 0)
8761         return 1;
8762 #endif
8763 #ifdef OSSL_NO_USABLE_TLS1_3
8764     if (tst == 1)
8765         return 1;
8766 #endif
8767
8768     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8769                                        TLS_client_method(),
8770                                        TLS1_VERSION,
8771                                        tst == 0 ? TLS1_2_VERSION
8772                                                 : TLS1_3_VERSION,
8773                                        &sctx, &cctx, cert, privkey)))
8774         goto end;
8775
8776     /*
8777      * Test that setting a client_cert_cb results in a client certificate being
8778      * sent.
8779      */
8780     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
8781     SSL_CTX_set_verify(sctx,
8782                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
8783                        verify_cb);
8784
8785     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8786                                       NULL, NULL))
8787             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8788                                                 SSL_ERROR_NONE)))
8789         goto end;
8790
8791     testresult = 1;
8792
8793  end:
8794     SSL_free(serverssl);
8795     SSL_free(clientssl);
8796     SSL_CTX_free(sctx);
8797     SSL_CTX_free(cctx);
8798
8799     return testresult;
8800 }
8801
8802 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
8803 /*
8804  * Test setting certificate authorities on both client and server.
8805  *
8806  * Test 0: SSL_CTX_set0_CA_list() only
8807  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
8808  * Test 2: Only SSL_CTX_set_client_CA_list()
8809  */
8810 static int test_ca_names_int(int prot, int tst)
8811 {
8812     SSL_CTX *cctx = NULL, *sctx = NULL;
8813     SSL *clientssl = NULL, *serverssl = NULL;
8814     int testresult = 0;
8815     size_t i;
8816     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
8817     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
8818     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
8819     const STACK_OF(X509_NAME) *sktmp = NULL;
8820
8821     for (i = 0; i < OSSL_NELEM(name); i++) {
8822         name[i] = X509_NAME_new();
8823         if (!TEST_ptr(name[i])
8824                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
8825                                                          MBSTRING_ASC,
8826                                                          (unsigned char *)
8827                                                          strnames[i],
8828                                                          -1, -1, 0)))
8829             goto end;
8830     }
8831
8832     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8833                                        TLS_client_method(),
8834                                        TLS1_VERSION,
8835                                        prot,
8836                                        &sctx, &cctx, cert, privkey)))
8837         goto end;
8838
8839     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
8840
8841     if (tst == 0 || tst == 1) {
8842         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
8843                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
8844                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
8845                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
8846                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
8847                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
8848             goto end;
8849
8850         SSL_CTX_set0_CA_list(sctx, sk1);
8851         SSL_CTX_set0_CA_list(cctx, sk2);
8852         sk1 = sk2 = NULL;
8853     }
8854     if (tst == 1 || tst == 2) {
8855         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
8856                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
8857                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
8858                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
8859                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
8860                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
8861             goto end;
8862
8863         SSL_CTX_set_client_CA_list(sctx, sk1);
8864         SSL_CTX_set_client_CA_list(cctx, sk2);
8865         sk1 = sk2 = NULL;
8866     }
8867
8868     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8869                                       NULL, NULL))
8870             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8871                                                 SSL_ERROR_NONE)))
8872         goto end;
8873
8874     /*
8875      * We only expect certificate authorities to have been sent to the server
8876      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
8877      */
8878     sktmp = SSL_get0_peer_CA_list(serverssl);
8879     if (prot == TLS1_3_VERSION
8880             && (tst == 0 || tst == 1)) {
8881         if (!TEST_ptr(sktmp)
8882                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
8883                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
8884                                               name[0]), 0)
8885                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
8886                                               name[1]), 0))
8887             goto end;
8888     } else if (!TEST_ptr_null(sktmp)) {
8889         goto end;
8890     }
8891
8892     /*
8893      * In all tests we expect certificate authorities to have been sent to the
8894      * client. However, SSL_set_client_CA_list() should override
8895      * SSL_set0_CA_list()
8896      */
8897     sktmp = SSL_get0_peer_CA_list(clientssl);
8898     if (!TEST_ptr(sktmp)
8899             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
8900             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
8901                                           name[tst == 0 ? 0 : 2]), 0)
8902             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
8903                                           name[tst == 0 ? 1 : 3]), 0))
8904         goto end;
8905
8906     testresult = 1;
8907
8908  end:
8909     SSL_free(serverssl);
8910     SSL_free(clientssl);
8911     SSL_CTX_free(sctx);
8912     SSL_CTX_free(cctx);
8913     for (i = 0; i < OSSL_NELEM(name); i++)
8914         X509_NAME_free(name[i]);
8915     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
8916     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
8917
8918     return testresult;
8919 }
8920 #endif
8921
8922 static int test_ca_names(int tst)
8923 {
8924     int testresult = 1;
8925
8926 #ifndef OPENSSL_NO_TLS1_2
8927     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
8928 #endif
8929 #ifndef OSSL_NO_USABLE_TLS1_3
8930     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
8931 #endif
8932
8933     return testresult;
8934 }
8935
8936 #ifndef OPENSSL_NO_TLS1_2
8937 static const char *multiblock_cipherlist_data[]=
8938 {
8939     "AES128-SHA",
8940     "AES128-SHA256",
8941     "AES256-SHA",
8942     "AES256-SHA256",
8943 };
8944
8945 /* Reduce the fragment size - so the multiblock test buffer can be small */
8946 # define MULTIBLOCK_FRAGSIZE 512
8947
8948 static int test_multiblock_write(int test_index)
8949 {
8950     static const char *fetchable_ciphers[]=
8951     {
8952         "AES-128-CBC-HMAC-SHA1",
8953         "AES-128-CBC-HMAC-SHA256",
8954         "AES-256-CBC-HMAC-SHA1",
8955         "AES-256-CBC-HMAC-SHA256"
8956     };
8957     const char *cipherlist = multiblock_cipherlist_data[test_index];
8958     const SSL_METHOD *smeth = TLS_server_method();
8959     const SSL_METHOD *cmeth = TLS_client_method();
8960     int min_version = TLS1_VERSION;
8961     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
8962     SSL_CTX *cctx = NULL, *sctx = NULL;
8963     SSL *clientssl = NULL, *serverssl = NULL;
8964     int testresult = 0;
8965
8966     /*
8967      * Choose a buffer large enough to perform a multi-block operation
8968      * i.e: write_len >= 4 * frag_size
8969      * 9 * is chosen so that multiple multiblocks are used + some leftover.
8970      */
8971     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
8972     unsigned char buf[sizeof(msg)], *p = buf;
8973     size_t readbytes, written, len;
8974     EVP_CIPHER *ciph = NULL;
8975
8976     /*
8977      * Check if the cipher exists before attempting to use it since it only has
8978      * a hardware specific implementation.
8979      */
8980     ciph = EVP_CIPHER_fetch(libctx, fetchable_ciphers[test_index], "");
8981     if (ciph == NULL) {
8982         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
8983         return 1;
8984     }
8985     EVP_CIPHER_free(ciph);
8986
8987     /* Set up a buffer with some data that will be sent to the client */
8988     RAND_bytes(msg, sizeof(msg));
8989
8990     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
8991                                        max_version, &sctx, &cctx, cert,
8992                                        privkey)))
8993         goto end;
8994
8995     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
8996         goto end;
8997
8998     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8999                                       NULL, NULL)))
9000             goto end;
9001
9002     /* settings to force it to use AES-CBC-HMAC_SHA */
9003     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
9004     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
9005        goto end;
9006
9007     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9008         goto end;
9009
9010     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
9011         || !TEST_size_t_eq(written, sizeof(msg)))
9012         goto end;
9013
9014     len = written;
9015     while (len > 0) {
9016         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
9017             goto end;
9018         p += readbytes;
9019         len -= readbytes;
9020     }
9021     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
9022         goto end;
9023
9024     testresult = 1;
9025 end:
9026     SSL_free(serverssl);
9027     SSL_free(clientssl);
9028     SSL_CTX_free(sctx);
9029     SSL_CTX_free(cctx);
9030
9031     return testresult;
9032 }
9033 #endif /* OPENSSL_NO_TLS1_2 */
9034
9035 static int test_session_timeout(int test)
9036 {
9037     /*
9038      * Test session ordering and timeout
9039      * Can't explicitly test performance of the new code,
9040      * but can test to see if the ordering of the sessions
9041      * are correct, and they they are removed as expected
9042      */
9043     SSL_SESSION *early = NULL;
9044     SSL_SESSION *middle = NULL;
9045     SSL_SESSION *late = NULL;
9046     SSL_CTX *ctx;
9047     int testresult = 0;
9048     long now = (long)time(NULL);
9049 #define TIMEOUT 10
9050
9051     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
9052         || !TEST_ptr(early = SSL_SESSION_new())
9053         || !TEST_ptr(middle = SSL_SESSION_new())
9054         || !TEST_ptr(late = SSL_SESSION_new()))
9055         goto end;
9056
9057     /* assign unique session ids */
9058     early->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9059     memset(early->session_id, 1, SSL3_SSL_SESSION_ID_LENGTH);
9060     middle->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9061     memset(middle->session_id, 2, SSL3_SSL_SESSION_ID_LENGTH);
9062     late->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9063     memset(late->session_id, 3, SSL3_SSL_SESSION_ID_LENGTH);
9064
9065     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9066         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9067         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9068         goto end;
9069
9070     /* Make sure they are all added */
9071     if (!TEST_ptr(early->prev)
9072         || !TEST_ptr(middle->prev)
9073         || !TEST_ptr(late->prev))
9074         goto end;
9075
9076     if (!TEST_int_ne(SSL_SESSION_set_time(early, now - 10), 0)
9077         || !TEST_int_ne(SSL_SESSION_set_time(middle, now), 0)
9078         || !TEST_int_ne(SSL_SESSION_set_time(late, now + 10), 0))
9079         goto end;
9080
9081     if (!TEST_int_ne(SSL_SESSION_set_timeout(early, TIMEOUT), 0)
9082         || !TEST_int_ne(SSL_SESSION_set_timeout(middle, TIMEOUT), 0)
9083         || !TEST_int_ne(SSL_SESSION_set_timeout(late, TIMEOUT), 0))
9084         goto end;
9085
9086     /* Make sure they are all still there */
9087     if (!TEST_ptr(early->prev)
9088         || !TEST_ptr(middle->prev)
9089         || !TEST_ptr(late->prev))
9090         goto end;
9091
9092     /* Make sure they are in the expected order */
9093     if (!TEST_ptr_eq(late->next, middle)
9094         || !TEST_ptr_eq(middle->next, early)
9095         || !TEST_ptr_eq(early->prev, middle)
9096         || !TEST_ptr_eq(middle->prev, late))
9097         goto end;
9098
9099     /* This should remove "early" */
9100     SSL_CTX_flush_sessions(ctx, now + TIMEOUT - 1);
9101     if (!TEST_ptr_null(early->prev)
9102         || !TEST_ptr(middle->prev)
9103         || !TEST_ptr(late->prev))
9104         goto end;
9105
9106     /* This should remove "middle" */
9107     SSL_CTX_flush_sessions(ctx, now + TIMEOUT + 1);
9108     if (!TEST_ptr_null(early->prev)
9109         || !TEST_ptr_null(middle->prev)
9110         || !TEST_ptr(late->prev))
9111         goto end;
9112
9113     /* This should remove "late" */
9114     SSL_CTX_flush_sessions(ctx, now + TIMEOUT + 11);
9115     if (!TEST_ptr_null(early->prev)
9116         || !TEST_ptr_null(middle->prev)
9117         || !TEST_ptr_null(late->prev))
9118         goto end;
9119
9120     /* Add them back in again */
9121     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9122         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9123         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9124         goto end;
9125
9126     /* Make sure they are all added */
9127     if (!TEST_ptr(early->prev)
9128         || !TEST_ptr(middle->prev)
9129         || !TEST_ptr(late->prev))
9130         goto end;
9131
9132     /* This should remove all of them */
9133     SSL_CTX_flush_sessions(ctx, 0);
9134     if (!TEST_ptr_null(early->prev)
9135         || !TEST_ptr_null(middle->prev)
9136         || !TEST_ptr_null(late->prev))
9137         goto end;
9138
9139     (void)SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_UPDATE_TIME
9140                                          | SSL_CTX_get_session_cache_mode(ctx));
9141
9142     /* make sure |now| is NOT  equal to the current time */
9143     now -= 10;
9144     if (!TEST_int_ne(SSL_SESSION_set_time(early, now), 0)
9145         || !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9146         || !TEST_long_ne(SSL_SESSION_get_time(early), now))
9147         goto end;
9148
9149     testresult = 1;
9150  end:
9151     SSL_CTX_free(ctx);
9152     SSL_SESSION_free(early);
9153     SSL_SESSION_free(middle);
9154     SSL_SESSION_free(late);
9155     return testresult;
9156 }
9157
9158 /*
9159  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
9160  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
9161  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
9162  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
9163  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
9164  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
9165  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
9166  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
9167  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
9168  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
9169  */
9170 static int test_servername(int tst)
9171 {
9172     SSL_CTX *cctx = NULL, *sctx = NULL;
9173     SSL *clientssl = NULL, *serverssl = NULL;
9174     int testresult = 0;
9175     SSL_SESSION *sess = NULL;
9176     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
9177
9178 #ifdef OPENSSL_NO_TLS1_2
9179     if (tst <= 4)
9180         return 1;
9181 #endif
9182 #ifdef OSSL_NO_USABLE_TLS1_3
9183     if (tst >= 5)
9184         return 1;
9185 #endif
9186
9187     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9188                                        TLS_client_method(),
9189                                        TLS1_VERSION,
9190                                        (tst <= 4) ? TLS1_2_VERSION
9191                                                   : TLS1_3_VERSION,
9192                                        &sctx, &cctx, cert, privkey))
9193             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9194                                              NULL, NULL)))
9195         goto end;
9196
9197     if (tst != 1 && tst != 6) {
9198         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
9199                                                               hostname_cb)))
9200             goto end;
9201     }
9202
9203     if (tst != 3 && tst != 8) {
9204         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9205             goto end;
9206         sexpectedhost = cexpectedhost = "goodhost";
9207     }
9208
9209     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9210         goto end;
9211
9212     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
9213                      cexpectedhost)
9214             || !TEST_str_eq(SSL_get_servername(serverssl,
9215                                                TLSEXT_NAMETYPE_host_name),
9216                             sexpectedhost))
9217         goto end;
9218
9219     /* Now repeat with a resumption handshake */
9220
9221     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
9222             || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
9223             || !TEST_true(SSL_SESSION_is_resumable(sess))
9224             || !TEST_int_eq(SSL_shutdown(serverssl), 0))
9225         goto end;
9226
9227     SSL_free(clientssl);
9228     SSL_free(serverssl);
9229     clientssl = serverssl = NULL;
9230
9231     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9232                                       NULL)))
9233         goto end;
9234
9235     if (!TEST_true(SSL_set_session(clientssl, sess)))
9236         goto end;
9237
9238     sexpectedhost = cexpectedhost = "goodhost";
9239     if (tst == 2 || tst == 7) {
9240         /* Set an inconsistent hostname */
9241         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
9242             goto end;
9243         /*
9244          * In TLSv1.2 we expect the hostname from the original handshake, in
9245          * TLSv1.3 we expect the hostname from this handshake
9246          */
9247         if (tst == 7)
9248             sexpectedhost = cexpectedhost = "altgoodhost";
9249
9250         if (!TEST_str_eq(SSL_get_servername(clientssl,
9251                                             TLSEXT_NAMETYPE_host_name),
9252                          "altgoodhost"))
9253             goto end;
9254     } else if (tst == 4 || tst == 9) {
9255         /*
9256          * A TLSv1.3 session does not associate a session with a servername,
9257          * but a TLSv1.2 session does.
9258          */
9259         if (tst == 9)
9260             sexpectedhost = cexpectedhost = NULL;
9261
9262         if (!TEST_str_eq(SSL_get_servername(clientssl,
9263                                             TLSEXT_NAMETYPE_host_name),
9264                          cexpectedhost))
9265             goto end;
9266     } else {
9267         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9268             goto end;
9269         /*
9270          * In a TLSv1.2 resumption where the hostname was not acknowledged
9271          * we expect the hostname on the server to be empty. On the client we
9272          * return what was requested in this case.
9273          *
9274          * Similarly if the client didn't set a hostname on an original TLSv1.2
9275          * session but is now, the server hostname will be empty, but the client
9276          * is as we set it.
9277          */
9278         if (tst == 1 || tst == 3)
9279             sexpectedhost = NULL;
9280
9281         if (!TEST_str_eq(SSL_get_servername(clientssl,
9282                                             TLSEXT_NAMETYPE_host_name),
9283                          "goodhost"))
9284             goto end;
9285     }
9286
9287     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9288         goto end;
9289
9290     if (!TEST_true(SSL_session_reused(clientssl))
9291             || !TEST_true(SSL_session_reused(serverssl))
9292             || !TEST_str_eq(SSL_get_servername(clientssl,
9293                                                TLSEXT_NAMETYPE_host_name),
9294                             cexpectedhost)
9295             || !TEST_str_eq(SSL_get_servername(serverssl,
9296                                                TLSEXT_NAMETYPE_host_name),
9297                             sexpectedhost))
9298         goto end;
9299
9300     testresult = 1;
9301
9302  end:
9303     SSL_SESSION_free(sess);
9304     SSL_free(serverssl);
9305     SSL_free(clientssl);
9306     SSL_CTX_free(sctx);
9307     SSL_CTX_free(cctx);
9308
9309     return testresult;
9310 }
9311
9312 #if !defined(OPENSSL_NO_EC) \
9313     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
9314 /*
9315  * Test that if signature algorithms are not available, then we do not offer or
9316  * accept them.
9317  * Test 0: Two RSA sig algs available: both RSA sig algs shared
9318  * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared
9319  * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared
9320  * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared
9321  * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared
9322  * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared
9323  */
9324 static int test_sigalgs_available(int idx)
9325 {
9326     SSL_CTX *cctx = NULL, *sctx = NULL;
9327     SSL *clientssl = NULL, *serverssl = NULL;
9328     int testresult = 0;
9329     OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
9330     OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx;
9331     OSSL_PROVIDER *filterprov = NULL;
9332     int sig, hash;
9333
9334     if (!TEST_ptr(tmpctx))
9335         goto end;
9336
9337     if (idx != 0 && idx != 3) {
9338         if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter",
9339                                                  filter_provider_init)))
9340             goto end;
9341
9342         filterprov = OSSL_PROVIDER_load(tmpctx, "filter");
9343         if (!TEST_ptr(filterprov))
9344             goto end;
9345
9346         if (idx < 3) {
9347             /*
9348              * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered
9349              * or accepted for the peer that uses this libctx. Note that libssl
9350              * *requires* SHA2-256 to be available so we cannot disable that. We
9351              * also need SHA1 for our certificate.
9352              */
9353             if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST,
9354                                                       "SHA2-256:SHA1")))
9355                 goto end;
9356         } else {
9357             if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE,
9358                                                       "ECDSA"))
9359 # ifdef OPENSSL_NO_ECX
9360                     || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT, "EC"))
9361 # else
9362                     || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
9363                                                              "EC:X25519:X448"))
9364 # endif
9365                 )
9366                 goto end;
9367         }
9368
9369         if (idx == 1 || idx == 4)
9370             clientctx = tmpctx;
9371         else
9372             serverctx = tmpctx;
9373     }
9374
9375     cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method());
9376     sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method());
9377     if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
9378         goto end;
9379
9380     if (idx != 5) {
9381         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9382                                            TLS_client_method(),
9383                                            TLS1_VERSION,
9384                                            0,
9385                                            &sctx, &cctx, cert, privkey)))
9386             goto end;
9387     } else {
9388         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9389                                            TLS_client_method(),
9390                                            TLS1_VERSION,
9391                                            0,
9392                                            &sctx, &cctx, cert2, privkey2)))
9393             goto end;
9394     }
9395
9396     /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */
9397     if (idx < 4) {
9398         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
9399                                                "ECDHE-RSA-AES128-GCM-SHA256")))
9400             goto end;
9401     } else {
9402         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
9403                                                "ECDHE-ECDSA-AES128-GCM-SHA256")))
9404             goto end;
9405     }
9406
9407     if (idx < 3) {
9408         if (!SSL_CTX_set1_sigalgs_list(cctx,
9409                                        "rsa_pss_rsae_sha384"
9410                                        ":rsa_pss_rsae_sha256")
9411                 || !SSL_CTX_set1_sigalgs_list(sctx,
9412                                               "rsa_pss_rsae_sha384"
9413                                               ":rsa_pss_rsae_sha256"))
9414             goto end;
9415     } else {
9416         if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")
9417                 || !SSL_CTX_set1_sigalgs_list(sctx,
9418                                               "rsa_pss_rsae_sha256:ECDSA+SHA256"))
9419             goto end;
9420     }
9421
9422     if (idx != 5
9423         && (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2,
9424                                                       SSL_FILETYPE_PEM), 1)
9425             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
9426                                                         privkey2,
9427                                                         SSL_FILETYPE_PEM), 1)
9428             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)))
9429         goto end;
9430
9431     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9432                                       NULL, NULL)))
9433         goto end;
9434
9435     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9436         goto end;
9437
9438     /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */
9439     if (!TEST_int_eq(SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash, NULL,
9440                                             NULL, NULL),
9441                      (idx == 0 || idx == 3) ? 2 : 1))
9442         goto end;
9443
9444     if (!TEST_int_eq(hash, idx == 0 ? NID_sha384 : NID_sha256))
9445         goto end;
9446
9447     if (!TEST_int_eq(sig, (idx == 4 || idx == 5) ? EVP_PKEY_EC
9448                                                  : NID_rsassaPss))
9449         goto end;
9450
9451     testresult = filter_provider_check_clean_finish();
9452
9453  end:
9454     SSL_free(serverssl);
9455     SSL_free(clientssl);
9456     SSL_CTX_free(sctx);
9457     SSL_CTX_free(cctx);
9458     OSSL_PROVIDER_unload(filterprov);
9459     OSSL_LIB_CTX_free(tmpctx);
9460
9461     return testresult;
9462 }
9463 #endif /*
9464         * !defined(OPENSSL_NO_EC) \
9465         * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
9466         */
9467
9468 #ifndef OPENSSL_NO_TLS1_3
9469 /* This test can run in TLSv1.3 even if ec and dh are disabled */
9470 static int test_pluggable_group(int idx)
9471 {
9472     SSL_CTX *cctx = NULL, *sctx = NULL;
9473     SSL *clientssl = NULL, *serverssl = NULL;
9474     int testresult = 0;
9475     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
9476     /* Check that we are not impacted by a provider without any groups */
9477     OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy");
9478     const char *group_name = idx == 0 ? "xorgroup" : "xorkemgroup";
9479
9480     if (!TEST_ptr(tlsprov))
9481         goto end;
9482
9483     if (legacyprov == NULL) {
9484         /*
9485          * In this case we assume we've been built with "no-legacy" and skip
9486          * this test (there is no OPENSSL_NO_LEGACY)
9487          */
9488         testresult = 1;
9489         goto end;
9490     }
9491
9492     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9493                                        TLS_client_method(),
9494                                        TLS1_3_VERSION,
9495                                        TLS1_3_VERSION,
9496                                        &sctx, &cctx, cert, privkey))
9497             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9498                                              NULL, NULL)))
9499         goto end;
9500
9501     if (!TEST_true(SSL_set1_groups_list(serverssl, group_name))
9502             || !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
9503         goto end;
9504
9505     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9506         goto end;
9507
9508     if (!TEST_str_eq(group_name,
9509                      SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
9510         goto end;
9511
9512     if (!TEST_str_eq(group_name, SSL_get0_group_name(serverssl))
9513         || !TEST_str_eq(group_name, SSL_get0_group_name(clientssl)))
9514         goto end;
9515
9516     testresult = 1;
9517
9518  end:
9519     SSL_free(serverssl);
9520     SSL_free(clientssl);
9521     SSL_CTX_free(sctx);
9522     SSL_CTX_free(cctx);
9523     OSSL_PROVIDER_unload(tlsprov);
9524     OSSL_PROVIDER_unload(legacyprov);
9525
9526     return testresult;
9527 }
9528
9529 /*
9530  * This function triggers encode, decode and sign functions
9531  * of the artificial "xorhmacsig" algorithm implemented in tls-provider
9532  * creating private key and certificate files for use in TLS testing.
9533  */
9534 static int create_cert_key(int idx, char *certfilename, char *privkeyfilename)
9535 {
9536     EVP_PKEY_CTX * evpctx = EVP_PKEY_CTX_new_from_name(libctx,
9537                              (idx == 0) ? "xorhmacsig" : "xorhmacsha2sig", NULL);
9538     EVP_PKEY *pkey = NULL;
9539     X509 *x509 = X509_new();
9540     X509_NAME *name = NULL;
9541     BIO *keybio = NULL, *certbio = NULL;
9542     int ret = 1;
9543
9544     if (!TEST_ptr(evpctx)
9545         || !TEST_true(EVP_PKEY_keygen_init(evpctx))
9546         || !TEST_true(EVP_PKEY_generate(evpctx, &pkey))
9547         || !TEST_ptr(pkey)
9548         || !TEST_ptr(x509)
9549         || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(x509), 1))
9550         || !TEST_true(X509_gmtime_adj(X509_getm_notBefore(x509), 0))
9551         || !TEST_true(X509_gmtime_adj(X509_getm_notAfter(x509), 31536000L))
9552         || !TEST_true(X509_set_pubkey(x509, pkey))
9553         || !TEST_ptr(name = X509_get_subject_name(x509))
9554         || !TEST_true(X509_NAME_add_entry_by_txt(name, "C",  MBSTRING_ASC,
9555                            (unsigned char *)"CH", -1, -1, 0))
9556         || !TEST_true(X509_NAME_add_entry_by_txt(name, "O",  MBSTRING_ASC,
9557                            (unsigned char *)"test.org", -1, -1, 0))
9558         || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
9559                            (unsigned char *)"localhost", -1, -1, 0))
9560         || !TEST_true(X509_set_issuer_name(x509, name))
9561         || !TEST_true(X509_sign(x509, pkey, EVP_sha1()))
9562         || !TEST_ptr(keybio = BIO_new_file(privkeyfilename, "wb"))
9563         || !TEST_true(PEM_write_bio_PrivateKey(keybio, pkey, NULL, NULL, 0, NULL, NULL))
9564         || !TEST_ptr(certbio = BIO_new_file(certfilename, "wb"))
9565         || !TEST_true(PEM_write_bio_X509(certbio, x509)))
9566         ret = 0;
9567
9568     EVP_PKEY_free(pkey);
9569     X509_free(x509);
9570     EVP_PKEY_CTX_free(evpctx);
9571     BIO_free(keybio);
9572     BIO_free(certbio);
9573     return ret;
9574 }
9575
9576 /*
9577  * Test that signature algorithms loaded via the provider interface can
9578  * correctly establish a TLS (1.3) connection.
9579  * Test 0: Signature algorithm with built-in hashing functionality: "xorhmacsig"
9580  * Test 1: Signature algorithm using external SHA2 hashing: "xorhmacsha2sig"
9581  * Test 2: Test 0 using RPK
9582  * Test 3: Test 1 using RPK
9583  */
9584 static int test_pluggable_signature(int idx)
9585 {
9586     static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
9587     SSL_CTX *cctx = NULL, *sctx = NULL;
9588     SSL *clientssl = NULL, *serverssl = NULL;
9589     int testresult = 0;
9590     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
9591     OSSL_PROVIDER *defaultprov = OSSL_PROVIDER_load(libctx, "default");
9592     char *certfilename = "tls-prov-cert.pem";
9593     char *privkeyfilename = "tls-prov-key.pem";
9594     int sigidx = idx % 2;
9595     int rpkidx = idx / 2;
9596
9597     /* create key and certificate for the different algorithm types */
9598     if (!TEST_ptr(tlsprov)
9599         || !TEST_true(create_cert_key(sigidx, certfilename, privkeyfilename)))
9600         goto end;
9601
9602     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9603                                        TLS_client_method(),
9604                                        TLS1_3_VERSION,
9605                                        TLS1_3_VERSION,
9606                                        &sctx, &cctx, certfilename, privkeyfilename))
9607             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9608                                              NULL, NULL)))
9609         goto end;
9610
9611     /* Enable RPK for server cert */
9612     if (rpkidx) {
9613         if (!TEST_true(SSL_set1_server_cert_type(serverssl, cert_type_rpk, sizeof(cert_type_rpk)))
9614                 || !TEST_true(SSL_set1_server_cert_type(clientssl, cert_type_rpk, sizeof(cert_type_rpk))))
9615             goto end;
9616     }
9617
9618     /* This is necessary to pass minimal setup w/o other groups configured */
9619     if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup"))
9620             || !TEST_true(SSL_set1_groups_list(clientssl, "xorgroup")))
9621         goto end;
9622
9623     /*
9624      * If this connection gets established, it must have been completed
9625      * via the tls-provider-implemented "hmacsig" algorithm, testing
9626      * both sign and verify functions during handshake.
9627      */
9628     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9629         goto end;
9630
9631     /* If using RPK, make sure we got one */
9632     if (rpkidx && !TEST_long_eq(SSL_get_verify_result(clientssl), X509_V_ERR_RPK_UNTRUSTED))
9633         goto end;
9634
9635     testresult = 1;
9636
9637  end:
9638     SSL_free(serverssl);
9639     SSL_free(clientssl);
9640     SSL_CTX_free(sctx);
9641     SSL_CTX_free(cctx);
9642     OSSL_PROVIDER_unload(tlsprov);
9643     OSSL_PROVIDER_unload(defaultprov);
9644
9645     return testresult;
9646 }
9647 #endif
9648
9649 #ifndef OPENSSL_NO_TLS1_2
9650 static int test_ssl_dup(void)
9651 {
9652     SSL_CTX *cctx = NULL, *sctx = NULL;
9653     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
9654     int testresult = 0;
9655     BIO *rbio = NULL, *wbio = NULL;
9656
9657     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9658                                        TLS_client_method(),
9659                                        0,
9660                                        0,
9661                                        &sctx, &cctx, cert, privkey)))
9662         goto end;
9663
9664     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9665                                              NULL, NULL)))
9666         goto end;
9667
9668     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
9669             || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
9670         goto end;
9671
9672     client2ssl = SSL_dup(clientssl);
9673     rbio = SSL_get_rbio(clientssl);
9674     if (!TEST_ptr(rbio)
9675             || !TEST_true(BIO_up_ref(rbio)))
9676         goto end;
9677     SSL_set0_rbio(client2ssl, rbio);
9678     rbio = NULL;
9679
9680     wbio = SSL_get_wbio(clientssl);
9681     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
9682         goto end;
9683     SSL_set0_wbio(client2ssl, wbio);
9684     rbio = NULL;
9685
9686     if (!TEST_ptr(client2ssl)
9687                /* Handshake not started so pointers should be different */
9688             || !TEST_ptr_ne(clientssl, client2ssl))
9689         goto end;
9690
9691     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
9692             || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
9693         goto end;
9694
9695     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
9696         goto end;
9697
9698     SSL_free(clientssl);
9699     clientssl = SSL_dup(client2ssl);
9700     if (!TEST_ptr(clientssl)
9701                /* Handshake has finished so pointers should be the same */
9702             || !TEST_ptr_eq(clientssl, client2ssl))
9703         goto end;
9704
9705     testresult = 1;
9706
9707  end:
9708     SSL_free(serverssl);
9709     SSL_free(clientssl);
9710     SSL_free(client2ssl);
9711     SSL_CTX_free(sctx);
9712     SSL_CTX_free(cctx);
9713
9714     return testresult;
9715 }
9716
9717 # ifndef OPENSSL_NO_DH
9718
9719 static EVP_PKEY *tmp_dh_params = NULL;
9720
9721 /* Helper function for the test_set_tmp_dh() tests */
9722 static EVP_PKEY *get_tmp_dh_params(void)
9723 {
9724     if (tmp_dh_params == NULL) {
9725         BIGNUM *p = NULL;
9726         OSSL_PARAM_BLD *tmpl = NULL;
9727         EVP_PKEY_CTX *pctx = NULL;
9728         OSSL_PARAM *params = NULL;
9729         EVP_PKEY *dhpkey = NULL;
9730
9731         p = BN_get_rfc3526_prime_2048(NULL);
9732         if (!TEST_ptr(p))
9733             goto end;
9734
9735         pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL);
9736         if (!TEST_ptr(pctx)
9737                 || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx), 1))
9738             goto end;
9739
9740         tmpl = OSSL_PARAM_BLD_new();
9741         if (!TEST_ptr(tmpl)
9742                 || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl,
9743                                                         OSSL_PKEY_PARAM_FFC_P,
9744                                                         p))
9745                 || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl,
9746                                                         OSSL_PKEY_PARAM_FFC_G,
9747                                                         2)))
9748             goto end;
9749
9750         params = OSSL_PARAM_BLD_to_param(tmpl);
9751         if (!TEST_ptr(params)
9752                 || !TEST_int_eq(EVP_PKEY_fromdata(pctx, &dhpkey,
9753                                                   EVP_PKEY_KEY_PARAMETERS,
9754                                                   params), 1))
9755             goto end;
9756
9757         tmp_dh_params = dhpkey;
9758     end:
9759         BN_free(p);
9760         EVP_PKEY_CTX_free(pctx);
9761         OSSL_PARAM_BLD_free(tmpl);
9762         OSSL_PARAM_free(params);
9763     }
9764
9765     if (tmp_dh_params != NULL && !EVP_PKEY_up_ref(tmp_dh_params))
9766         return NULL;
9767
9768     return tmp_dh_params;
9769 }
9770
9771 #  ifndef OPENSSL_NO_DEPRECATED_3_0
9772 /* Callback used by test_set_tmp_dh() */
9773 static DH *tmp_dh_callback(SSL *s, int is_export, int keylen)
9774 {
9775     EVP_PKEY *dhpkey = get_tmp_dh_params();
9776     DH *ret = NULL;
9777
9778     if (!TEST_ptr(dhpkey))
9779         return NULL;
9780
9781     /*
9782      * libssl does not free the returned DH, so we free it now knowing that even
9783      * after we free dhpkey, there will still be a reference to the owning
9784      * EVP_PKEY in tmp_dh_params, and so the DH object will live for the length
9785      * of time we need it for.
9786      */
9787     ret = EVP_PKEY_get1_DH(dhpkey);
9788     DH_free(ret);
9789
9790     EVP_PKEY_free(dhpkey);
9791
9792     return ret;
9793 }
9794 #  endif
9795
9796 /*
9797  * Test the various methods for setting temporary DH parameters
9798  *
9799  * Test  0: Default (no auto) setting
9800  * Test  1: Explicit SSL_CTX auto off
9801  * Test  2: Explicit SSL auto off
9802  * Test  3: Explicit SSL_CTX auto on
9803  * Test  4: Explicit SSL auto on
9804  * Test  5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY
9805  * Test  6: Explicit SSL auto off, custom DH params via EVP_PKEY
9806  *
9807  * The following are testing deprecated APIs, so we only run them if available
9808  * Test  7: Explicit SSL_CTX auto off, custom DH params via DH
9809  * Test  8: Explicit SSL auto off, custom DH params via DH
9810  * Test  9: Explicit SSL_CTX auto off, custom DH params via callback
9811  * Test 10: Explicit SSL auto off, custom DH params via callback
9812  */
9813 static int test_set_tmp_dh(int idx)
9814 {
9815     SSL_CTX *cctx = NULL, *sctx = NULL;
9816     SSL *clientssl = NULL, *serverssl = NULL;
9817     int testresult = 0;
9818     int dhauto = (idx == 3 || idx == 4) ? 1 : 0;
9819     int expected = (idx <= 2) ? 0 : 1;
9820     EVP_PKEY *dhpkey = NULL;
9821 #  ifndef OPENSSL_NO_DEPRECATED_3_0
9822     DH *dh = NULL;
9823 #  else
9824
9825     if (idx >= 7)
9826         return 1;
9827 #  endif
9828
9829     if (idx >= 5 && idx <= 8) {
9830         dhpkey = get_tmp_dh_params();
9831         if (!TEST_ptr(dhpkey))
9832             goto end;
9833     }
9834 #  ifndef OPENSSL_NO_DEPRECATED_3_0
9835     if (idx == 7 || idx == 8) {
9836         dh = EVP_PKEY_get1_DH(dhpkey);
9837         if (!TEST_ptr(dh))
9838             goto end;
9839     }
9840 #  endif
9841
9842     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9843                                        TLS_client_method(),
9844                                        0,
9845                                        0,
9846                                        &sctx, &cctx, cert, privkey)))
9847         goto end;
9848
9849     if ((idx & 1) == 1) {
9850         if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto)))
9851             goto end;
9852     }
9853
9854     if (idx == 5) {
9855         if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey)))
9856             goto end;
9857         dhpkey = NULL;
9858     }
9859 #  ifndef OPENSSL_NO_DEPRECATED_3_0
9860     else if (idx == 7) {
9861         if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh)))
9862             goto end;
9863     } else if (idx == 9) {
9864         SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback);
9865     }
9866 #  endif
9867
9868     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9869                                       NULL, NULL)))
9870         goto end;
9871
9872     if ((idx & 1) == 0 && idx != 0) {
9873         if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto)))
9874             goto end;
9875     }
9876     if (idx == 6) {
9877         if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey)))
9878             goto end;
9879         dhpkey = NULL;
9880     }
9881 #  ifndef OPENSSL_NO_DEPRECATED_3_0
9882     else if (idx == 8) {
9883         if (!TEST_true(SSL_set_tmp_dh(serverssl, dh)))
9884             goto end;
9885     } else if (idx == 10) {
9886         SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback);
9887     }
9888 #  endif
9889
9890     if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
9891             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
9892             || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA")))
9893         goto end;
9894
9895     /*
9896      * If autoon then we should succeed. Otherwise we expect failure because
9897      * there are no parameters
9898      */
9899     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
9900                                            SSL_ERROR_NONE), expected))
9901         goto end;
9902
9903     testresult = 1;
9904
9905  end:
9906 #  ifndef OPENSSL_NO_DEPRECATED_3_0
9907     DH_free(dh);
9908 #  endif
9909     SSL_free(serverssl);
9910     SSL_free(clientssl);
9911     SSL_CTX_free(sctx);
9912     SSL_CTX_free(cctx);
9913     EVP_PKEY_free(dhpkey);
9914
9915     return testresult;
9916 }
9917
9918 /*
9919  * Test the auto DH keys are appropriately sized
9920  */
9921 static int test_dh_auto(int idx)
9922 {
9923     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method());
9924     SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9925     SSL *clientssl = NULL, *serverssl = NULL;
9926     int testresult = 0;
9927     EVP_PKEY *tmpkey = NULL;
9928     char *thiscert = NULL, *thiskey = NULL;
9929     size_t expdhsize = 0;
9930     const char *ciphersuite = "DHE-RSA-AES128-SHA";
9931
9932     if (!TEST_ptr(sctx) || !TEST_ptr(cctx))
9933         goto end;
9934
9935     switch (idx) {
9936     case 0:
9937         /* The FIPS provider doesn't support this DH size - so we ignore it */
9938         if (is_fips) {
9939             testresult = 1;
9940             goto end;
9941         }
9942         thiscert = cert1024;
9943         thiskey = privkey1024;
9944         expdhsize = 1024;
9945         SSL_CTX_set_security_level(sctx, 1);
9946         SSL_CTX_set_security_level(cctx, 1);
9947         break;
9948     case 1:
9949         /* 2048 bit prime */
9950         thiscert = cert;
9951         thiskey = privkey;
9952         expdhsize = 2048;
9953         break;
9954     case 2:
9955         thiscert = cert3072;
9956         thiskey = privkey3072;
9957         expdhsize = 3072;
9958         break;
9959     case 3:
9960         thiscert = cert4096;
9961         thiskey = privkey4096;
9962         expdhsize = 4096;
9963         break;
9964     case 4:
9965         thiscert = cert8192;
9966         thiskey = privkey8192;
9967         expdhsize = 8192;
9968         break;
9969     /* No certificate cases */
9970     case 5:
9971         /* The FIPS provider doesn't support this DH size - so we ignore it */
9972         if (is_fips) {
9973             testresult = 1;
9974             goto end;
9975         }
9976         ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0";
9977         expdhsize = 1024;
9978         break;
9979     case 6:
9980         ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0";
9981         expdhsize = 3072;
9982         break;
9983     default:
9984         TEST_error("Invalid text index");
9985         goto end;
9986     }
9987
9988     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL,
9989                                        NULL,
9990                                        0,
9991                                        0,
9992                                        &sctx, &cctx, thiscert, thiskey)))
9993         goto end;
9994
9995     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9996                                       NULL, NULL)))
9997         goto end;
9998
9999     if (!TEST_true(SSL_set_dh_auto(serverssl, 1))
10000             || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10001             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10002             || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite))
10003             || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite)))
10004         goto end;
10005
10006     /*
10007      * Send the server's first flight. At this point the server has created the
10008      * temporary DH key but hasn't finished using it yet. Once used it is
10009      * removed, so we cannot test it.
10010      */
10011     if (!TEST_int_le(SSL_connect(clientssl), 0)
10012             || !TEST_int_le(SSL_accept(serverssl), 0))
10013         goto end;
10014
10015     if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0))
10016         goto end;
10017     if (!TEST_size_t_eq(EVP_PKEY_get_bits(tmpkey), expdhsize))
10018         goto end;
10019
10020     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10021         goto end;
10022
10023     testresult = 1;
10024
10025  end:
10026     SSL_free(serverssl);
10027     SSL_free(clientssl);
10028     SSL_CTX_free(sctx);
10029     SSL_CTX_free(cctx);
10030     EVP_PKEY_free(tmpkey);
10031
10032     return testresult;
10033
10034 }
10035 # endif /* OPENSSL_NO_DH */
10036 #endif /* OPENSSL_NO_TLS1_2 */
10037
10038 #ifndef OSSL_NO_USABLE_TLS1_3
10039 /*
10040  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
10041  * that it works even without a certificate configured for the original
10042  * SSL_CTX
10043  */
10044 static int test_sni_tls13(void)
10045 {
10046     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
10047     SSL *clientssl = NULL, *serverssl = NULL;
10048     int testresult = 0;
10049
10050     /* Reset callback counter */
10051     snicb = 0;
10052
10053     /* Create an initial SSL_CTX with no certificate configured */
10054     sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10055     if (!TEST_ptr(sctx))
10056         goto end;
10057     /* Require TLSv1.3 as a minimum */
10058     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10059                                        TLS_client_method(), TLS1_3_VERSION, 0,
10060                                        &sctx2, &cctx, cert, privkey)))
10061         goto end;
10062
10063     /* Set up SNI */
10064     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
10065             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
10066         goto end;
10067
10068     /*
10069      * Connection should still succeed because the final SSL_CTX has the right
10070      * certificates configured.
10071      */
10072     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10073                                       &clientssl, NULL, NULL))
10074             || !TEST_true(create_ssl_connection(serverssl, clientssl,
10075                                                 SSL_ERROR_NONE)))
10076         goto end;
10077
10078     /* We should have had the SNI callback called exactly once */
10079     if (!TEST_int_eq(snicb, 1))
10080         goto end;
10081
10082     testresult = 1;
10083
10084 end:
10085     SSL_free(serverssl);
10086     SSL_free(clientssl);
10087     SSL_CTX_free(sctx2);
10088     SSL_CTX_free(sctx);
10089     SSL_CTX_free(cctx);
10090     return testresult;
10091 }
10092
10093 /*
10094  * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week
10095  * 0 = TLSv1.2
10096  * 1 = TLSv1.3
10097  */
10098 static int test_ticket_lifetime(int idx)
10099 {
10100     SSL_CTX *cctx = NULL, *sctx = NULL;
10101     SSL *clientssl = NULL, *serverssl = NULL;
10102     int testresult = 0;
10103     int version = TLS1_3_VERSION;
10104
10105 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
10106 #define TWO_WEEK_SEC (2 * ONE_WEEK_SEC)
10107
10108     if (idx == 0) {
10109 #ifdef OPENSSL_NO_TLS1_2
10110         return TEST_skip("TLS 1.2 is disabled.");
10111 #else
10112         version = TLS1_2_VERSION;
10113 #endif
10114     }
10115
10116     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10117                                        TLS_client_method(), version, version,
10118                                        &sctx, &cctx, cert, privkey)))
10119         goto end;
10120
10121     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10122                                       &clientssl, NULL, NULL)))
10123         goto end;
10124
10125     /*
10126      * Set the timeout to be more than 1 week
10127      * make sure the returned value is the default
10128      */
10129     if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC),
10130                       SSL_get_default_timeout(serverssl)))
10131         goto end;
10132
10133     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10134         goto end;
10135
10136     if (idx == 0) {
10137         /* TLSv1.2 uses the set value */
10138         if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC))
10139             goto end;
10140     } else {
10141         /* TLSv1.3 uses the limited value */
10142         if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC))
10143             goto end;
10144     }
10145     testresult = 1;
10146
10147 end:
10148     SSL_free(serverssl);
10149     SSL_free(clientssl);
10150     SSL_CTX_free(sctx);
10151     SSL_CTX_free(cctx);
10152     return testresult;
10153 }
10154 #endif
10155 /*
10156  * Test that setting an ALPN does not violate RFC
10157  */
10158 static int test_set_alpn(void)
10159 {
10160     SSL_CTX *ctx = NULL;
10161     SSL *ssl = NULL;
10162     int testresult = 0;
10163
10164     unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
10165     unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
10166     unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
10167     unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00};
10168     unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'};
10169     unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'};
10170
10171     /* Create an initial SSL_CTX with no certificate configured */
10172     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10173     if (!TEST_ptr(ctx))
10174         goto end;
10175
10176     /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
10177     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
10178         goto end;
10179     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
10180         goto end;
10181     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
10182         goto end;
10183     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
10184         goto end;
10185     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
10186         goto end;
10187     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
10188         goto end;
10189     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
10190         goto end;
10191     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
10192         goto end;
10193     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
10194         goto end;
10195
10196     ssl = SSL_new(ctx);
10197     if (!TEST_ptr(ssl))
10198         goto end;
10199
10200     if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
10201         goto end;
10202     if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
10203         goto end;
10204     if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
10205         goto end;
10206     if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
10207         goto end;
10208     if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
10209         goto end;
10210     if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
10211         goto end;
10212     if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
10213         goto end;
10214     if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
10215         goto end;
10216     if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
10217         goto end;
10218
10219     testresult = 1;
10220
10221 end:
10222     SSL_free(ssl);
10223     SSL_CTX_free(ctx);
10224     return testresult;
10225 }
10226
10227 /*
10228  * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store.
10229  */
10230 static int test_set_verify_cert_store_ssl_ctx(void)
10231 {
10232    SSL_CTX *ctx = NULL;
10233    int testresult = 0;
10234    X509_STORE *store = NULL, *new_store = NULL,
10235               *cstore = NULL, *new_cstore = NULL;
10236
10237    /* Create an initial SSL_CTX. */
10238    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10239    if (!TEST_ptr(ctx))
10240        goto end;
10241
10242    /* Retrieve verify store pointer. */
10243    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
10244        goto end;
10245
10246    /* Retrieve chain store pointer. */
10247    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
10248        goto end;
10249
10250    /* We haven't set any yet, so this should be NULL. */
10251    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10252        goto end;
10253
10254    /* Create stores. We use separate stores so pointers are different. */
10255    new_store = X509_STORE_new();
10256    if (!TEST_ptr(new_store))
10257        goto end;
10258
10259    new_cstore = X509_STORE_new();
10260    if (!TEST_ptr(new_cstore))
10261        goto end;
10262
10263    /* Set stores. */
10264    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store)))
10265        goto end;
10266
10267    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore)))
10268        goto end;
10269
10270    /* Should be able to retrieve the same pointer. */
10271    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
10272        goto end;
10273
10274    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
10275        goto end;
10276
10277    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
10278        goto end;
10279
10280    /* Should be able to unset again. */
10281    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL)))
10282        goto end;
10283
10284    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL)))
10285        goto end;
10286
10287    /* Should now be NULL. */
10288    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
10289        goto end;
10290
10291    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
10292        goto end;
10293
10294    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10295        goto end;
10296
10297    testresult = 1;
10298
10299 end:
10300    X509_STORE_free(new_store);
10301    X509_STORE_free(new_cstore);
10302    SSL_CTX_free(ctx);
10303    return testresult;
10304 }
10305
10306 /*
10307  * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store.
10308  */
10309 static int test_set_verify_cert_store_ssl(void)
10310 {
10311    SSL_CTX *ctx = NULL;
10312    SSL *ssl = NULL;
10313    int testresult = 0;
10314    X509_STORE *store = NULL, *new_store = NULL,
10315               *cstore = NULL, *new_cstore = NULL;
10316
10317    /* Create an initial SSL_CTX. */
10318    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10319    if (!TEST_ptr(ctx))
10320        goto end;
10321
10322    /* Create an SSL object. */
10323    ssl = SSL_new(ctx);
10324    if (!TEST_ptr(ssl))
10325        goto end;
10326
10327    /* Retrieve verify store pointer. */
10328    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10329        goto end;
10330
10331    /* Retrieve chain store pointer. */
10332    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10333        goto end;
10334
10335    /* We haven't set any yet, so this should be NULL. */
10336    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10337        goto end;
10338
10339    /* Create stores. We use separate stores so pointers are different. */
10340    new_store = X509_STORE_new();
10341    if (!TEST_ptr(new_store))
10342        goto end;
10343
10344    new_cstore = X509_STORE_new();
10345    if (!TEST_ptr(new_cstore))
10346        goto end;
10347
10348    /* Set stores. */
10349    if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store)))
10350        goto end;
10351
10352    if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore)))
10353        goto end;
10354
10355    /* Should be able to retrieve the same pointer. */
10356    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10357        goto end;
10358
10359    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10360        goto end;
10361
10362    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
10363        goto end;
10364
10365    /* Should be able to unset again. */
10366    if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL)))
10367        goto end;
10368
10369    if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL)))
10370        goto end;
10371
10372    /* Should now be NULL. */
10373    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10374        goto end;
10375
10376    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10377        goto end;
10378
10379    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10380        goto end;
10381
10382    testresult = 1;
10383
10384 end:
10385    X509_STORE_free(new_store);
10386    X509_STORE_free(new_cstore);
10387    SSL_free(ssl);
10388    SSL_CTX_free(ctx);
10389    return testresult;
10390 }
10391
10392
10393 static int test_inherit_verify_param(void)
10394 {
10395     int testresult = 0;
10396
10397     SSL_CTX *ctx = NULL;
10398     X509_VERIFY_PARAM *cp = NULL;
10399     SSL *ssl = NULL;
10400     X509_VERIFY_PARAM *sp = NULL;
10401     int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
10402
10403     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10404     if (!TEST_ptr(ctx))
10405         goto end;
10406
10407     cp = SSL_CTX_get0_param(ctx);
10408     if (!TEST_ptr(cp))
10409         goto end;
10410     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
10411         goto end;
10412
10413     X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
10414
10415     ssl = SSL_new(ctx);
10416     if (!TEST_ptr(ssl))
10417         goto end;
10418
10419     sp = SSL_get0_param(ssl);
10420     if (!TEST_ptr(sp))
10421         goto end;
10422     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
10423         goto end;
10424
10425     testresult = 1;
10426
10427  end:
10428     SSL_free(ssl);
10429     SSL_CTX_free(ctx);
10430
10431     return testresult;
10432 }
10433
10434 static int test_load_dhfile(void)
10435 {
10436 #ifndef OPENSSL_NO_DH
10437     int testresult = 0;
10438
10439     SSL_CTX *ctx = NULL;
10440     SSL_CONF_CTX *cctx = NULL;
10441
10442     if (dhfile == NULL)
10443         return 1;
10444
10445     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()))
10446         || !TEST_ptr(cctx = SSL_CONF_CTX_new()))
10447         goto end;
10448
10449     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
10450     SSL_CONF_CTX_set_flags(cctx,
10451                            SSL_CONF_FLAG_CERTIFICATE
10452                            | SSL_CONF_FLAG_SERVER
10453                            | SSL_CONF_FLAG_FILE);
10454
10455     if (!TEST_int_eq(SSL_CONF_cmd(cctx, "DHParameters", dhfile), 2))
10456         goto end;
10457
10458     testresult = 1;
10459 end:
10460     SSL_CONF_CTX_free(cctx);
10461     SSL_CTX_free(ctx);
10462
10463     return testresult;
10464 #else
10465     return TEST_skip("DH not supported by this build");
10466 #endif
10467 }
10468
10469 #ifndef OSSL_NO_USABLE_TLS1_3
10470 /* Test that read_ahead works across a key change */
10471 static int test_read_ahead_key_change(void)
10472 {
10473     SSL_CTX *cctx = NULL, *sctx = NULL;
10474     SSL *clientssl = NULL, *serverssl = NULL;
10475     int testresult = 0;
10476     char *msg = "Hello World";
10477     size_t written, readbytes;
10478     char buf[80];
10479     int i;
10480
10481     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10482                                        TLS_client_method(), TLS1_3_VERSION, 0,
10483                                        &sctx, &cctx, cert, privkey)))
10484         goto end;
10485
10486     SSL_CTX_set_read_ahead(sctx, 1);
10487
10488     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10489                                       &clientssl, NULL, NULL)))
10490         goto end;
10491
10492     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10493         goto end;
10494
10495     /* Write some data, send a key update, write more data */
10496     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
10497         || !TEST_size_t_eq(written, strlen(msg)))
10498         goto end;
10499
10500     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
10501         goto end;
10502
10503     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
10504         || !TEST_size_t_eq(written, strlen(msg)))
10505         goto end;
10506
10507     /*
10508      * Since read_ahead is on the first read below should read the record with
10509      * the first app data, the second record with the key update message, and
10510      * the third record with the app data all in one go. We should be able to
10511      * still process the read_ahead data correctly even though it crosses
10512      * epochs
10513      */
10514     for (i = 0; i < 2; i++) {
10515         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
10516                                     &readbytes)))
10517             goto end;
10518
10519         buf[readbytes] = '\0';
10520         if (!TEST_str_eq(buf, msg))
10521             goto end;
10522     }
10523
10524     testresult = 1;
10525
10526 end:
10527     SSL_free(serverssl);
10528     SSL_free(clientssl);
10529     SSL_CTX_free(sctx);
10530     SSL_CTX_free(cctx);
10531     return testresult;
10532 }
10533
10534 static size_t record_pad_cb(SSL *s, int type, size_t len, void *arg)
10535 {
10536     int *called = arg;
10537
10538     switch ((*called)++) {
10539     case 0:
10540         /* Add some padding to first record */
10541         return 512;
10542     case 1:
10543         /* Maximally pad the second record */
10544         return SSL3_RT_MAX_PLAIN_LENGTH - len;
10545     case 2:
10546         /*
10547          * Exceeding the maximum padding should be fine. It should just pad to
10548          * the maximum anyway
10549          */
10550         return SSL3_RT_MAX_PLAIN_LENGTH + 1 - len;
10551     case 3:
10552         /*
10553          * Very large padding should also be ok. Should just pad to the maximum
10554          * allowed
10555          */
10556         return SIZE_MAX;
10557     default:
10558         return 0;
10559     }
10560 }
10561
10562 /*
10563  * Test that setting record padding in TLSv1.3 works as expected
10564  * Test 0: Record padding callback on the SSL_CTX
10565  * Test 1: Record padding callback on the SSL
10566  * Test 2: Record block padding on the SSL_CTX
10567  * Test 3: Record block padding on the SSL
10568  */
10569 static int test_tls13_record_padding(int idx)
10570 {
10571     SSL_CTX *cctx = NULL, *sctx = NULL;
10572     SSL *clientssl = NULL, *serverssl = NULL;
10573     int testresult = 0;
10574     char *msg = "Hello World";
10575     size_t written, readbytes;
10576     char buf[80];
10577     int i;
10578     int called = 0;
10579
10580     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10581                                        TLS_client_method(), TLS1_3_VERSION, 0,
10582                                        &sctx, &cctx, cert, privkey)))
10583         goto end;
10584
10585     if (idx == 0) {
10586         SSL_CTX_set_record_padding_callback(cctx, record_pad_cb);
10587         SSL_CTX_set_record_padding_callback_arg(cctx, &called);
10588         if (!TEST_ptr_eq(SSL_CTX_get_record_padding_callback_arg(cctx), &called))
10589             goto end;
10590     } else if (idx == 2) {
10591         /* Exceeding the max plain length should fail */
10592         if (!TEST_false(SSL_CTX_set_block_padding(cctx,
10593                                                   SSL3_RT_MAX_PLAIN_LENGTH + 1)))
10594             goto end;
10595         if (!TEST_true(SSL_CTX_set_block_padding(cctx, 512)))
10596             goto end;
10597     }
10598
10599     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10600                                       &clientssl, NULL, NULL)))
10601         goto end;
10602
10603     if (idx == 1) {
10604         SSL_set_record_padding_callback(clientssl, record_pad_cb);
10605         SSL_set_record_padding_callback_arg(clientssl, &called);
10606         if (!TEST_ptr_eq(SSL_get_record_padding_callback_arg(clientssl), &called))
10607             goto end;
10608     } else if (idx == 3) {
10609         /* Exceeding the max plain length should fail */
10610         if (!TEST_false(SSL_set_block_padding(clientssl,
10611                                               SSL3_RT_MAX_PLAIN_LENGTH + 1)))
10612             goto end;
10613         if (!TEST_true(SSL_set_block_padding(clientssl, 512)))
10614             goto end;
10615     }
10616
10617     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10618         goto end;
10619
10620     called = 0;
10621     /*
10622      * Write some data, then check we can read it. Do this four times to check
10623      * we can continue to write and read padded data after the initial record
10624      * padding has been added. We don't actually check that the padding has
10625      * been applied to the record - just that we can continue to communicate
10626      * normally and that the callback has been called (if appropriate).
10627      */
10628     for (i = 0; i < 4; i++) {
10629         if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
10630             || !TEST_size_t_eq(written, strlen(msg)))
10631             goto end;
10632
10633         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
10634                                     &readbytes))
10635                 || !TEST_size_t_eq(written, readbytes))
10636             goto end;
10637
10638         buf[readbytes] = '\0';
10639         if (!TEST_str_eq(buf, msg))
10640             goto end;
10641     }
10642
10643     if ((idx == 0 || idx == 1) && !TEST_int_eq(called, 4))
10644         goto end;
10645
10646     testresult = 1;
10647 end:
10648     SSL_free(serverssl);
10649     SSL_free(clientssl);
10650     SSL_CTX_free(sctx);
10651     SSL_CTX_free(cctx);
10652     return testresult;
10653 }
10654 #endif /* OSSL_NO_USABLE_TLS1_3 */
10655
10656 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
10657 /*
10658  * Test TLSv1.2 with a pipeline capable cipher. TLSv1.3 and DTLS do not
10659  * support this yet. The only pipeline capable cipher that we have is in the
10660  * dasync engine (providers don't support this yet), so we have to use
10661  * deprecated APIs for this test.
10662  *
10663  * Test 0: Client has pipelining enabled, server does not
10664  * Test 1: Server has pipelining enabled, client does not
10665  * Test 2: Client has pipelining enabled, server does not: not enough data to
10666  *         fill all the pipelines
10667  * Test 3: Client has pipelining enabled, server does not: not enough data to
10668  *         fill all the pipelines by more than a full pipeline's worth
10669  * Test 4: Client has pipelining enabled, server does not: more data than all
10670  *         the available pipelines can take
10671  * Test 5: Client has pipelining enabled, server does not: Maximum size pipeline
10672  */
10673 static int test_pipelining(int idx)
10674 {
10675     SSL_CTX *cctx = NULL, *sctx = NULL;
10676     SSL *clientssl = NULL, *serverssl = NULL, *peera, *peerb;
10677     int testresult = 0, numreads;
10678     /* A 55 byte message */
10679     unsigned char *msg = (unsigned char *)
10680         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123";
10681     size_t written, readbytes, offset, msglen, fragsize = 10, numpipes = 5;
10682     size_t expectedreads;
10683     unsigned char *buf = NULL;
10684     ENGINE *e;
10685
10686     if (!TEST_ptr(e = ENGINE_by_id("dasync")))
10687         return 0;
10688
10689     if (!TEST_true(ENGINE_init(e))) {
10690         ENGINE_free(e);
10691         return 0;
10692     }
10693
10694     if (!TEST_true(ENGINE_register_ciphers(e)))
10695         goto end;
10696
10697     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10698                                        TLS_client_method(), 0,
10699                                        TLS1_2_VERSION, &sctx, &cctx, cert,
10700                                        privkey)))
10701         goto end;
10702
10703     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10704                                       &clientssl, NULL, NULL)))
10705         goto end;
10706
10707     if (!TEST_true(SSL_set_cipher_list(clientssl, "AES128-SHA")))
10708         goto end;
10709
10710     /* peera is always configured for pipelining, while peerb is not. */
10711     if (idx == 1) {
10712         peera = serverssl;
10713         peerb = clientssl;
10714
10715     } else {
10716         peera = clientssl;
10717         peerb = serverssl;
10718     }
10719
10720     if (idx == 5) {
10721         numpipes = 2;
10722         /* Maximum allowed fragment size */
10723         fragsize = SSL3_RT_MAX_PLAIN_LENGTH;
10724         msglen = fragsize * numpipes;
10725         msg = OPENSSL_malloc(msglen);
10726         if (!TEST_ptr(msg))
10727             goto end;
10728         if (!TEST_int_gt(RAND_bytes_ex(libctx, msg, msglen, 0), 0))
10729             goto end;
10730     } else if (idx == 4) {
10731         msglen = 55;
10732     } else {
10733         msglen = 50;
10734     }
10735     if (idx == 2)
10736         msglen -= 2; /* Send 2 less bytes */
10737     else if (idx == 3)
10738         msglen -= 12; /* Send 12 less bytes */
10739
10740     buf = OPENSSL_malloc(msglen);
10741     if (!TEST_ptr(buf))
10742         goto end;
10743
10744     if (idx == 5) {
10745         /*
10746          * Test that setting a split send fragment longer than the maximum
10747          * allowed fails
10748          */
10749         if (!TEST_false(SSL_set_split_send_fragment(peera, fragsize + 1)))
10750             goto end;
10751     }
10752
10753     /*
10754      * In the normal case. We have 5 pipelines with 10 bytes per pipeline
10755      * (50 bytes in total). This is a ridiculously small number of bytes -
10756      * but sufficient for our purposes
10757      */
10758     if (!TEST_true(SSL_set_max_pipelines(peera, numpipes))
10759             || !TEST_true(SSL_set_split_send_fragment(peera, fragsize)))
10760         goto end;
10761
10762     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10763         goto end;
10764
10765     /* Write some data from peera to peerb */
10766     if (!TEST_true(SSL_write_ex(peera, msg, msglen, &written))
10767         || !TEST_size_t_eq(written, msglen))
10768         goto end;
10769
10770     /*
10771      * If the pipelining code worked, then we expect all |numpipes| pipelines to
10772      * have been used - except in test 3 where only |numpipes - 1| pipelines
10773      * will be used. This will result in |numpipes| records (|numpipes - 1| for
10774      * test 3) having been sent to peerb. Since peerb is not using read_ahead we
10775      * expect this to be read in |numpipes| or |numpipes - 1| separate
10776      * SSL_read_ex calls. In the case of test 4, there is then one additional
10777      * read for left over data that couldn't fit in the previous pipelines
10778      */
10779     for (offset = 0, numreads = 0;
10780          offset < msglen;
10781          offset += readbytes, numreads++) {
10782         if (!TEST_true(SSL_read_ex(peerb, buf + offset,
10783                                    msglen - offset, &readbytes)))
10784             goto end;
10785     }
10786
10787     expectedreads = idx == 4 ? numpipes + 1
10788                              : (idx == 3 ? numpipes - 1 : numpipes);
10789     if (!TEST_mem_eq(msg, msglen, buf, offset)
10790             || !TEST_int_eq(numreads, expectedreads))
10791         goto end;
10792
10793     /*
10794      * Write some data from peerb to peera. We do this in up to |numpipes + 1|
10795      * chunks to exercise the read pipelining code on peera.
10796      */
10797     for (offset = 0; offset < msglen; offset += fragsize) {
10798         size_t sendlen = msglen - offset;
10799
10800         if (sendlen > fragsize)
10801             sendlen = fragsize;
10802         if (!TEST_true(SSL_write_ex(peerb, msg + offset, sendlen, &written))
10803                 || !TEST_size_t_eq(written, sendlen))
10804             goto end;
10805     }
10806
10807     /*
10808      * The data was written in |numpipes|, |numpipes - 1| or |numpipes + 1|
10809      * separate chunks (depending on which test we are running). If the
10810      * pipelining is working then we expect peera to read up to numpipes chunks
10811      * and process them in parallel, giving back the complete result in a single
10812      * call to SSL_read_ex
10813      */
10814     if (!TEST_true(SSL_read_ex(peera, buf, msglen, &readbytes))
10815             || !TEST_size_t_le(readbytes, msglen))
10816         goto end;
10817
10818     if (idx == 4) {
10819         size_t readbytes2;
10820
10821         if (!TEST_true(SSL_read_ex(peera, buf + readbytes,
10822                                    msglen - readbytes, &readbytes2)))
10823             goto end;
10824         readbytes += readbytes2;
10825         if (!TEST_size_t_le(readbytes, msglen))
10826             goto end;
10827     }
10828
10829     if (!TEST_mem_eq(msg, msglen, buf, readbytes))
10830         goto end;
10831
10832     testresult = 1;
10833 end:
10834     SSL_free(serverssl);
10835     SSL_free(clientssl);
10836     SSL_CTX_free(sctx);
10837     SSL_CTX_free(cctx);
10838     ENGINE_unregister_ciphers(e);
10839     ENGINE_finish(e);
10840     ENGINE_free(e);
10841     OPENSSL_free(buf);
10842     if (idx == 5)
10843         OPENSSL_free(msg);
10844     return testresult;
10845 }
10846 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */
10847
10848 static int check_version_string(SSL *s, int version)
10849 {
10850     const char *verstr = NULL;
10851
10852     switch (version) {
10853     case SSL3_VERSION:
10854         verstr = "SSLv3";
10855         break;
10856     case TLS1_VERSION:
10857         verstr = "TLSv1";
10858         break;
10859     case TLS1_1_VERSION:
10860         verstr = "TLSv1.1";
10861         break;
10862     case TLS1_2_VERSION:
10863         verstr = "TLSv1.2";
10864         break;
10865     case TLS1_3_VERSION:
10866         verstr = "TLSv1.3";
10867         break;
10868     case DTLS1_VERSION:
10869         verstr = "DTLSv1";
10870         break;
10871     case DTLS1_2_VERSION:
10872         verstr = "DTLSv1.2";
10873     }
10874
10875     return TEST_str_eq(verstr, SSL_get_version(s));
10876 }
10877
10878 /*
10879  * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and
10880  * SSL_is_dtls return the expected results for a (D)TLS connection. Compare with
10881  * test_version() in quicapitest.c which does the same thing for QUIC
10882  * connections.
10883  */
10884 static int test_version(int idx)
10885 {
10886     SSL_CTX *cctx = NULL, *sctx = NULL;
10887     SSL *clientssl = NULL, *serverssl = NULL;
10888     int testresult = 0, version;
10889     const SSL_METHOD *servmeth = TLS_server_method();
10890     const SSL_METHOD *clientmeth = TLS_client_method();
10891
10892     switch (idx) {
10893 #if !defined(OPENSSL_NO_SSL3)
10894     case 0:
10895         version = SSL3_VERSION;
10896         break;
10897 #endif
10898 #if !defined(OPENSSL_NO_TLS1)
10899     case 1:
10900         version = TLS1_VERSION;
10901         break;
10902 #endif
10903 #if !defined(OPENSSL_NO_TLS1_2)
10904     case 2:
10905         version = TLS1_2_VERSION;
10906         break;
10907 #endif
10908 #if !defined(OSSL_NO_USABLE_TLS1_3)
10909     case 3:
10910         version = TLS1_3_VERSION;
10911         break;
10912 #endif
10913 #if !defined(OPENSSL_NO_DTLS1)
10914     case 4:
10915         version = DTLS1_VERSION;
10916         break;
10917 #endif
10918 #if !defined(OPENSSL_NO_DTLS1_2)
10919     case 5:
10920         version = DTLS1_2_VERSION;
10921         break;
10922 #endif
10923     /*
10924      * NB we do not support QUIC in this test. That is covered by quicapitest.c
10925      * We also don't support DTLS1_BAD_VER since we have no server support for
10926      * that.
10927      */
10928     default:
10929         TEST_skip("Unsupported protocol version");
10930         return 1;
10931     }
10932
10933     if (is_fips
10934             && (version == SSL3_VERSION
10935                 || version == TLS1_VERSION
10936                 || version == DTLS1_VERSION)) {
10937         TEST_skip("Protocol version not supported with FIPS");
10938         return 1;
10939     }
10940
10941 #if !defined(OPENSSL_NO_DTLS)
10942     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
10943         servmeth = DTLS_server_method();
10944         clientmeth = DTLS_client_method();
10945     }
10946 #endif
10947
10948     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, version,
10949                                        version, &sctx, &cctx, cert, privkey)))
10950         goto end;
10951
10952     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
10953             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
10954                                                 "DEFAULT:@SECLEVEL=0")))
10955         goto end;
10956
10957     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10958                                       &clientssl, NULL, NULL)))
10959         goto end;
10960
10961     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10962         goto end;
10963
10964     if (!TEST_int_eq(SSL_version(serverssl), version)
10965             || !TEST_int_eq(SSL_version(clientssl), version)
10966             || !TEST_true(check_version_string(serverssl, version))
10967             || !TEST_true(check_version_string(clientssl, version)))
10968         goto end;
10969
10970     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
10971         if (!TEST_true(SSL_is_dtls(serverssl))
10972                 || !TEST_true(SSL_is_dtls(clientssl))
10973                 || !TEST_false(SSL_is_tls(serverssl))
10974                 || !TEST_false(SSL_is_tls(clientssl))
10975                 || !TEST_false(SSL_is_quic(serverssl))
10976                 || !TEST_false(SSL_is_quic(clientssl)))
10977         goto end;
10978     } else {
10979         if (!TEST_true(SSL_is_tls(serverssl))
10980                 || !TEST_true(SSL_is_tls(clientssl))
10981                 || !TEST_false(SSL_is_dtls(serverssl))
10982                 || !TEST_false(SSL_is_dtls(clientssl))
10983                 || !TEST_false(SSL_is_quic(serverssl))
10984                 || !TEST_false(SSL_is_quic(clientssl)))
10985         goto end;
10986     }
10987
10988     testresult = 1;
10989 end:
10990     SSL_free(serverssl);
10991     SSL_free(clientssl);
10992     SSL_CTX_free(sctx);
10993     SSL_CTX_free(cctx);
10994     return testresult;
10995 }
10996
10997 /*
10998  * Test that the SSL_rstate_string*() APIs return sane results
10999  */
11000 static int test_rstate_string(void)
11001 {
11002     SSL_CTX *cctx = NULL, *sctx = NULL;
11003     SSL *clientssl = NULL, *serverssl = NULL;
11004     int testresult = 0, version;
11005     const SSL_METHOD *servmeth = TLS_server_method();
11006     const SSL_METHOD *clientmeth = TLS_client_method();
11007     size_t written, readbytes;
11008     unsigned char buf[2];
11009     unsigned char dummyheader[SSL3_RT_HEADER_LENGTH] = {
11010         SSL3_RT_APPLICATION_DATA,
11011         TLS1_2_VERSION_MAJOR,
11012         0, /* To be filled in later */
11013         0,
11014         1
11015     };
11016
11017     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, 0,
11018                                        0, &sctx, &cctx, cert, privkey)))
11019         goto end;
11020
11021     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11022                                       &clientssl, NULL, NULL)))
11023         goto end;
11024
11025     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11026             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11027         goto end;
11028
11029     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11030         goto end;
11031
11032     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11033             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11034         goto end;
11035
11036     /* Fill in the correct version for the record header */
11037     version = SSL_version(serverssl);
11038     if (version == TLS1_3_VERSION)
11039         version = TLS1_2_VERSION;
11040     dummyheader[2] = version & 0xff;
11041
11042     /*
11043      * Send a dummy header. If we continued to read the body as well this
11044      * would fail with a bad record mac, but we're not going to go that far.
11045      */
11046     if (!TEST_true(BIO_write_ex(SSL_get_rbio(serverssl), dummyheader,
11047                                 sizeof(dummyheader), &written))
11048             || !TEST_size_t_eq(written, SSL3_RT_HEADER_LENGTH))
11049         goto end;
11050
11051     if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)))
11052         goto end;
11053
11054     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RB")
11055             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read body"))
11056         goto end;
11057
11058     testresult = 1;
11059 end:
11060     SSL_free(serverssl);
11061     SSL_free(clientssl);
11062     SSL_CTX_free(sctx);
11063     SSL_CTX_free(cctx);
11064     return testresult;
11065 }
11066
11067 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config dhfile\n")
11068
11069 int setup_tests(void)
11070 {
11071     char *modulename;
11072     char *configfile;
11073
11074     libctx = OSSL_LIB_CTX_new();
11075     if (!TEST_ptr(libctx))
11076         return 0;
11077
11078     defctxnull = OSSL_PROVIDER_load(NULL, "null");
11079
11080     /*
11081      * Verify that the default and fips providers in the default libctx are not
11082      * available
11083      */
11084     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
11085             || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
11086         return 0;
11087
11088     if (!test_skip_common_options()) {
11089         TEST_error("Error parsing test options\n");
11090         return 0;
11091     }
11092
11093     if (!TEST_ptr(certsdir = test_get_argument(0))
11094             || !TEST_ptr(srpvfile = test_get_argument(1))
11095             || !TEST_ptr(tmpfilename = test_get_argument(2))
11096             || !TEST_ptr(modulename = test_get_argument(3))
11097             || !TEST_ptr(configfile = test_get_argument(4))
11098             || !TEST_ptr(dhfile = test_get_argument(5)))
11099         return 0;
11100
11101     if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
11102         return 0;
11103
11104     /* Check we have the expected provider available */
11105     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
11106         return 0;
11107
11108     /* Check the default provider is not available */
11109     if (strcmp(modulename, "default") != 0
11110             && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
11111         return 0;
11112
11113     if (strcmp(modulename, "fips") == 0) {
11114         OSSL_PROVIDER *prov = NULL;
11115         OSSL_PARAM params[2];
11116
11117         is_fips = 1;
11118
11119         prov = OSSL_PROVIDER_load(libctx, "fips");
11120         if (prov != NULL) {
11121             /* Query the fips provider to check if the check ems option is enabled */
11122             params[0] =
11123                 OSSL_PARAM_construct_int(OSSL_PROV_PARAM_TLS1_PRF_EMS_CHECK,
11124                                          &fips_ems_check);
11125             params[1] = OSSL_PARAM_construct_end();
11126             OSSL_PROVIDER_get_params(prov, params);
11127             OSSL_PROVIDER_unload(prov);
11128         }
11129     }
11130
11131     /*
11132      * We add, but don't load the test "tls-provider". We'll load it when we
11133      * need it.
11134      */
11135     if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider",
11136                                              tls_provider_init)))
11137         return 0;
11138
11139
11140     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
11141 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
11142         TEST_error("not supported in this build");
11143         return 0;
11144 #else
11145         int i, mcount, rcount, fcount;
11146
11147         for (i = 0; i < 4; i++)
11148             test_export_key_mat(i);
11149         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
11150         test_printf_stdout("malloc %d realloc %d free %d\n",
11151                 mcount, rcount, fcount);
11152         return 1;
11153 #endif
11154     }
11155
11156     cert = test_mk_file_path(certsdir, "servercert.pem");
11157     if (cert == NULL)
11158         goto err;
11159
11160     privkey = test_mk_file_path(certsdir, "serverkey.pem");
11161     if (privkey == NULL)
11162         goto err;
11163
11164     cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
11165     if (cert2 == NULL)
11166         goto err;
11167
11168     privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
11169     if (privkey2 == NULL)
11170         goto err;
11171
11172     cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem");
11173     if (cert1024 == NULL)
11174         goto err;
11175
11176     privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem");
11177     if (privkey1024 == NULL)
11178         goto err;
11179
11180     cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem");
11181     if (cert3072 == NULL)
11182         goto err;
11183
11184     privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem");
11185     if (privkey3072 == NULL)
11186         goto err;
11187
11188     cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem");
11189     if (cert4096 == NULL)
11190         goto err;
11191
11192     privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem");
11193     if (privkey4096 == NULL)
11194         goto err;
11195
11196     cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem");
11197     if (cert8192 == NULL)
11198         goto err;
11199
11200     privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem");
11201     if (privkey8192 == NULL)
11202         goto err;
11203
11204     if (fips_ems_check) {
11205 #ifndef OPENSSL_NO_TLS1_2
11206         ADD_TEST(test_no_ems);
11207 #endif
11208         return 1;
11209     }
11210 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
11211 # if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
11212     ADD_ALL_TESTS(test_ktls, NUM_KTLS_TEST_CIPHERS * 4);
11213     ADD_ALL_TESTS(test_ktls_sendfile, NUM_KTLS_TEST_CIPHERS * 2);
11214 # endif
11215 #endif
11216     ADD_TEST(test_large_message_tls);
11217     ADD_TEST(test_large_message_tls_read_ahead);
11218 #ifndef OPENSSL_NO_DTLS
11219     ADD_TEST(test_large_message_dtls);
11220 #endif
11221     ADD_ALL_TESTS(test_large_app_data, 28);
11222     ADD_TEST(test_cleanse_plaintext);
11223 #ifndef OPENSSL_NO_OCSP
11224     ADD_TEST(test_tlsext_status_type);
11225 #endif
11226     ADD_TEST(test_session_with_only_int_cache);
11227     ADD_TEST(test_session_with_only_ext_cache);
11228     ADD_TEST(test_session_with_both_cache);
11229     ADD_TEST(test_session_wo_ca_names);
11230 #ifndef OSSL_NO_USABLE_TLS1_3
11231     ADD_ALL_TESTS(test_stateful_tickets, 3);
11232     ADD_ALL_TESTS(test_stateless_tickets, 3);
11233     ADD_TEST(test_psk_tickets);
11234     ADD_ALL_TESTS(test_extra_tickets, 6);
11235 #endif
11236     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
11237     ADD_TEST(test_ssl_bio_pop_next_bio);
11238     ADD_TEST(test_ssl_bio_pop_ssl_bio);
11239     ADD_TEST(test_ssl_bio_change_rbio);
11240     ADD_TEST(test_ssl_bio_change_wbio);
11241 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
11242     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
11243     ADD_TEST(test_keylog);
11244 #endif
11245 #ifndef OSSL_NO_USABLE_TLS1_3
11246     ADD_TEST(test_keylog_no_master_key);
11247 #endif
11248     ADD_TEST(test_client_cert_verify_cb);
11249     ADD_TEST(test_ssl_build_cert_chain);
11250     ADD_TEST(test_ssl_ctx_build_cert_chain);
11251 #ifndef OPENSSL_NO_TLS1_2
11252     ADD_TEST(test_client_hello_cb);
11253     ADD_TEST(test_no_ems);
11254     ADD_TEST(test_ccs_change_cipher);
11255 #endif
11256 #ifndef OSSL_NO_USABLE_TLS1_3
11257     ADD_ALL_TESTS(test_early_data_read_write, 6);
11258     /*
11259      * We don't do replay tests for external PSK. Replay protection isn't used
11260      * in that scenario.
11261      */
11262     ADD_ALL_TESTS(test_early_data_replay, 2);
11263     ADD_ALL_TESTS(test_early_data_skip, OSSL_NELEM(ciphersuites) * 3);
11264     ADD_ALL_TESTS(test_early_data_skip_hrr, OSSL_NELEM(ciphersuites) * 3);
11265     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, OSSL_NELEM(ciphersuites) * 3);
11266     ADD_ALL_TESTS(test_early_data_skip_abort, OSSL_NELEM(ciphersuites) * 3);
11267     ADD_ALL_TESTS(test_early_data_not_sent, 3);
11268     ADD_ALL_TESTS(test_early_data_psk, 8);
11269     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 5);
11270     ADD_ALL_TESTS(test_early_data_not_expected, 3);
11271 # ifndef OPENSSL_NO_TLS1_2
11272     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
11273 # endif
11274 #endif
11275 #ifndef OSSL_NO_USABLE_TLS1_3
11276     ADD_ALL_TESTS(test_set_ciphersuite, 10);
11277     ADD_TEST(test_ciphersuite_change);
11278     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
11279 # ifdef OPENSSL_NO_PSK
11280     ADD_ALL_TESTS(test_tls13_psk, 1);
11281 # else
11282     ADD_ALL_TESTS(test_tls13_psk, 4);
11283 # endif  /* OPENSSL_NO_PSK */
11284 # ifndef OPENSSL_NO_TLS1_2
11285     /* Test with both TLSv1.3 and 1.2 versions */
11286     ADD_ALL_TESTS(test_key_exchange, 14);
11287 #  if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH)
11288     ADD_ALL_TESTS(test_negotiated_group,
11289                   4 * (OSSL_NELEM(ecdhe_kexch_groups)
11290                        + OSSL_NELEM(ffdhe_kexch_groups)));
11291 #  endif
11292 # else
11293     /* Test with only TLSv1.3 versions */
11294     ADD_ALL_TESTS(test_key_exchange, 12);
11295 # endif
11296     ADD_ALL_TESTS(test_custom_exts, 6);
11297     ADD_TEST(test_stateless);
11298     ADD_TEST(test_pha_key_update);
11299 #else
11300     ADD_ALL_TESTS(test_custom_exts, 3);
11301 #endif
11302     ADD_ALL_TESTS(test_export_key_mat, 6);
11303 #ifndef OSSL_NO_USABLE_TLS1_3
11304     ADD_ALL_TESTS(test_export_key_mat_early, 3);
11305     ADD_TEST(test_key_update);
11306     ADD_ALL_TESTS(test_key_update_peer_in_write, 2);
11307     ADD_ALL_TESTS(test_key_update_peer_in_read, 2);
11308     ADD_ALL_TESTS(test_key_update_local_in_write, 2);
11309     ADD_ALL_TESTS(test_key_update_local_in_read, 2);
11310 #endif
11311     ADD_ALL_TESTS(test_ssl_clear, 2);
11312     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
11313 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
11314     ADD_ALL_TESTS(test_srp, 6);
11315 #endif
11316 #if !defined(OPENSSL_NO_COMP_ALG)
11317     /* Add compression case */
11318     ADD_ALL_TESTS(test_info_callback, 8);
11319 #else
11320     ADD_ALL_TESTS(test_info_callback, 6);
11321 #endif
11322     ADD_ALL_TESTS(test_ssl_pending, 2);
11323     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
11324     ADD_ALL_TESTS(test_ticket_callbacks, 20);
11325     ADD_ALL_TESTS(test_shutdown, 7);
11326     ADD_TEST(test_async_shutdown);
11327     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
11328     ADD_ALL_TESTS(test_cert_cb, 6);
11329     ADD_ALL_TESTS(test_client_cert_cb, 2);
11330     ADD_ALL_TESTS(test_ca_names, 3);
11331 #ifndef OPENSSL_NO_TLS1_2
11332     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
11333 #endif
11334     ADD_ALL_TESTS(test_servername, 10);
11335 #if !defined(OPENSSL_NO_EC) \
11336     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
11337     ADD_ALL_TESTS(test_sigalgs_available, 6);
11338 #endif
11339 #ifndef OPENSSL_NO_TLS1_3
11340     ADD_ALL_TESTS(test_pluggable_group, 2);
11341     ADD_ALL_TESTS(test_pluggable_signature, 4);
11342 #endif
11343 #ifndef OPENSSL_NO_TLS1_2
11344     ADD_TEST(test_ssl_dup);
11345 # ifndef OPENSSL_NO_DH
11346     ADD_ALL_TESTS(test_set_tmp_dh, 11);
11347     ADD_ALL_TESTS(test_dh_auto, 7);
11348 # endif
11349 #endif
11350 #ifndef OSSL_NO_USABLE_TLS1_3
11351     ADD_TEST(test_sni_tls13);
11352     ADD_ALL_TESTS(test_ticket_lifetime, 2);
11353 #endif
11354     ADD_TEST(test_inherit_verify_param);
11355     ADD_TEST(test_set_alpn);
11356     ADD_TEST(test_set_verify_cert_store_ssl_ctx);
11357     ADD_TEST(test_set_verify_cert_store_ssl);
11358     ADD_ALL_TESTS(test_session_timeout, 1);
11359     ADD_TEST(test_load_dhfile);
11360 #ifndef OSSL_NO_USABLE_TLS1_3
11361     ADD_TEST(test_read_ahead_key_change);
11362     ADD_ALL_TESTS(test_tls13_record_padding, 4);
11363 #endif
11364 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
11365     ADD_ALL_TESTS(test_serverinfo_custom, 4);
11366 #endif
11367 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
11368     ADD_ALL_TESTS(test_pipelining, 6);
11369 #endif
11370     ADD_ALL_TESTS(test_version, 6);
11371     ADD_TEST(test_rstate_string);
11372     return 1;
11373
11374  err:
11375     OPENSSL_free(cert);
11376     OPENSSL_free(privkey);
11377     OPENSSL_free(cert2);
11378     OPENSSL_free(privkey2);
11379     return 0;
11380 }
11381
11382 void cleanup_tests(void)
11383 {
11384 # if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH)
11385     EVP_PKEY_free(tmp_dh_params);
11386 #endif
11387     OPENSSL_free(cert);
11388     OPENSSL_free(privkey);
11389     OPENSSL_free(cert2);
11390     OPENSSL_free(privkey2);
11391     OPENSSL_free(cert1024);
11392     OPENSSL_free(privkey1024);
11393     OPENSSL_free(cert3072);
11394     OPENSSL_free(privkey3072);
11395     OPENSSL_free(cert4096);
11396     OPENSSL_free(privkey4096);
11397     OPENSSL_free(cert8192);
11398     OPENSSL_free(privkey8192);
11399     bio_s_mempacket_test_free();
11400     bio_s_always_retry_free();
11401     OSSL_PROVIDER_unload(defctxnull);
11402     OSSL_LIB_CTX_free(libctx);
11403 }