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