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