xref: /freebsd/crypto/openssl/test/sslapitest.c (revision 10a428653ee7216475f1ddce3fb4cbf1200319f8)
1 /*
2  * Copyright 2016-2026 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 /*
11  * We need access to the deprecated low level HMAC APIs for legacy purposes
12  * when the deprecated calls are not hidden
13  */
14 #ifndef OPENSSL_NO_DEPRECATED_3_0
15 #define OPENSSL_SUPPRESS_DEPRECATED
16 #endif
17 
18 #include <stdio.h>
19 #include <string.h>
20 
21 #include <openssl/opensslconf.h>
22 #include <openssl/bio.h>
23 #include <openssl/crypto.h>
24 #include <openssl/ssl.h>
25 #include <openssl/ocsp.h>
26 #include <openssl/srp.h>
27 #include <openssl/txt_db.h>
28 #include <openssl/aes.h>
29 #include <openssl/rand.h>
30 #include <openssl/core_names.h>
31 #include <openssl/core_dispatch.h>
32 #include <openssl/provider.h>
33 #include <openssl/param_build.h>
34 #include <openssl/x509v3.h>
35 #include <openssl/dh.h>
36 #include <openssl/engine.h>
37 
38 #include "helpers/ssltestlib.h"
39 #include "testutil.h"
40 #include "testutil/output.h"
41 #include "internal/nelem.h"
42 #include "internal/tlsgroups.h"
43 #include "internal/ktls.h"
44 #include "internal/ssl_unwrap.h"
45 #include "../ssl/ssl_local.h"
46 #include "../ssl/record/methods/recmethod_local.h"
47 #include "filterprov.h"
48 
49 #undef OSSL_NO_USABLE_TLS1_3
50 #if defined(OPENSSL_NO_TLS1_3) \
51     || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH))
52 /*
53  * If we don't have ec or dh then there are no built-in groups that are usable
54  * with TLSv1.3
55  */
56 #define OSSL_NO_USABLE_TLS1_3
57 #endif
58 
59 /* Defined in tls-provider.c */
60 int tls_provider_init(const OSSL_CORE_HANDLE *handle,
61     const OSSL_DISPATCH *in,
62     const OSSL_DISPATCH **out,
63     void **provctx);
64 
65 static OSSL_LIB_CTX *libctx = NULL;
66 static OSSL_PROVIDER *defctxnull = NULL;
67 
68 #ifndef OSSL_NO_USABLE_TLS1_3
69 
70 static SSL_SESSION *clientpsk = NULL;
71 static SSL_SESSION *serverpsk = NULL;
72 static const char *pskid = "Identity";
73 static const char *srvid;
74 
75 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
76     size_t *idlen, SSL_SESSION **sess);
77 static int find_session_cb(SSL *ssl, const unsigned char *identity,
78     size_t identity_len, SSL_SESSION **sess);
79 
80 static int use_session_cb_cnt = 0;
81 static int find_session_cb_cnt = 0;
82 static int end_of_early_data = 0;
83 #endif
84 
85 static char *certsdir = NULL;
86 static char *cert = NULL;
87 static char *privkey = NULL;
88 static char *cert2 = NULL;
89 static char *privkey2 = NULL;
90 static char *cert1024 = NULL;
91 static char *privkey1024 = NULL;
92 static char *cert3072 = NULL;
93 static char *privkey3072 = NULL;
94 static char *cert4096 = NULL;
95 static char *privkey4096 = NULL;
96 static char *cert8192 = NULL;
97 static char *privkey8192 = NULL;
98 static char *srpvfile = NULL;
99 static char *tmpfilename = NULL;
100 static char *dhfile = NULL;
101 static char *datadir = NULL;
102 
103 static int is_fips = 0;
104 static int fips_ems_check = 0;
105 
106 #define LOG_BUFFER_SIZE 2048
107 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = { 0 };
108 static size_t server_log_buffer_index = 0;
109 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = { 0 };
110 static size_t client_log_buffer_index = 0;
111 static int error_writing_log = 0;
112 
113 #ifndef OPENSSL_NO_OCSP
114 static const unsigned char orespder[] = "Dummy OCSP Response";
115 static int ocsp_server_called = 0;
116 static int ocsp_client_called = 0;
117 
118 static int cdummyarg = 1;
119 static X509 *ocspcert = NULL;
120 #endif
121 
122 #define CLIENT_VERSION_LEN 2
123 
124 /* The ssltrace test assumes some options are switched on/off */
125 #if !defined(OPENSSL_NO_SSL_TRACE)                                \
126     && defined(OPENSSL_NO_BROTLI) && defined(OPENSSL_NO_ZSTD)     \
127     && !defined(OPENSSL_NO_ECX) && !defined(OPENSSL_NO_DH)        \
128     && !defined(OPENSSL_NO_ML_DSA) && !defined(OPENSSL_NO_ML_KEM) \
129     && !defined(OPENSSL_NO_TLS1_3)
130 #define DO_SSL_TRACE_TEST
131 #endif
132 
133 /*
134  * This structure is used to validate that the correct number of log messages
135  * of various types are emitted when emitting secret logs.
136  */
137 struct sslapitest_log_counts {
138     unsigned int rsa_key_exchange_count;
139     unsigned int master_secret_count;
140     unsigned int client_early_secret_count;
141     unsigned int client_handshake_secret_count;
142     unsigned int server_handshake_secret_count;
143     unsigned int client_application_secret_count;
144     unsigned int server_application_secret_count;
145     unsigned int early_exporter_secret_count;
146     unsigned int exporter_secret_count;
147 };
148 
hostname_cb(SSL * s,int * al,void * arg)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 || strcmp(hostname, "altgoodhost") == 0))
154         return SSL_TLSEXT_ERR_OK;
155 
156     return SSL_TLSEXT_ERR_NOACK;
157 }
158 
client_keylog_callback(const SSL * ssl,const char * line)159 static void client_keylog_callback(const SSL *ssl, const char *line)
160 {
161     int line_length = strlen(line);
162 
163     /* If the log doesn't fit, error out. */
164     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
165         TEST_info("Client log too full");
166         error_writing_log = 1;
167         return;
168     }
169 
170     strcat(client_log_buffer, line);
171     client_log_buffer_index += line_length;
172     client_log_buffer[client_log_buffer_index++] = '\n';
173 }
174 
server_keylog_callback(const SSL * ssl,const char * line)175 static void server_keylog_callback(const SSL *ssl, const char *line)
176 {
177     int line_length = strlen(line);
178 
179     /* If the log doesn't fit, error out. */
180     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
181         TEST_info("Server log too full");
182         error_writing_log = 1;
183         return;
184     }
185 
186     strcat(server_log_buffer, line);
187     server_log_buffer_index += line_length;
188     server_log_buffer[server_log_buffer_index++] = '\n';
189 }
190 
compare_hex_encoded_buffer(const char * hex_encoded,size_t hex_length,const uint8_t * raw,size_t raw_length)191 static int compare_hex_encoded_buffer(const char *hex_encoded,
192     size_t hex_length,
193     const uint8_t *raw,
194     size_t raw_length)
195 {
196     size_t i, j;
197     char hexed[3];
198 
199     if (!TEST_size_t_eq(raw_length * 2, hex_length))
200         return 1;
201 
202     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
203         BIO_snprintf(hexed, sizeof(hexed), "%02x", raw[i]);
204         if (!TEST_int_eq(hexed[0], hex_encoded[j])
205             || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
206             return 1;
207     }
208 
209     return 0;
210 }
211 
test_keylog_output(char * buffer,const SSL * ssl,const SSL_SESSION * session,struct sslapitest_log_counts * expected)212 static int test_keylog_output(char *buffer, const SSL *ssl,
213     const SSL_SESSION *session,
214     struct sslapitest_log_counts *expected)
215 {
216     char *token = NULL;
217     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = { 0 };
218     size_t client_random_size = SSL3_RANDOM_SIZE;
219     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = { 0 };
220     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
221     unsigned int rsa_key_exchange_count = 0;
222     unsigned int master_secret_count = 0;
223     unsigned int client_early_secret_count = 0;
224     unsigned int client_handshake_secret_count = 0;
225     unsigned int server_handshake_secret_count = 0;
226     unsigned int client_application_secret_count = 0;
227     unsigned int server_application_secret_count = 0;
228     unsigned int early_exporter_secret_count = 0;
229     unsigned int exporter_secret_count = 0;
230 
231     for (token = strtok(buffer, " \n"); token != NULL;
232         token = strtok(NULL, " \n")) {
233         if (strcmp(token, "RSA") == 0) {
234             /*
235              * Premaster secret. Tokens should be: 16 ASCII bytes of
236              * hex-encoded encrypted secret, then the hex-encoded pre-master
237              * secret.
238              */
239             if (!TEST_ptr(token = strtok(NULL, " \n")))
240                 return 0;
241             if (!TEST_size_t_eq(strlen(token), 16))
242                 return 0;
243             if (!TEST_ptr(token = strtok(NULL, " \n")))
244                 return 0;
245             /*
246              * We can't sensibly check the log because the premaster secret is
247              * transient, and OpenSSL doesn't keep hold of it once the master
248              * secret is generated.
249              */
250             rsa_key_exchange_count++;
251         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
252             /*
253              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
254              * client random, then the hex-encoded master secret.
255              */
256             client_random_size = SSL_get_client_random(ssl,
257                 actual_client_random,
258                 SSL3_RANDOM_SIZE);
259             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
260                 return 0;
261 
262             if (!TEST_ptr(token = strtok(NULL, " \n")))
263                 return 0;
264             if (!TEST_size_t_eq(strlen(token), 64))
265                 return 0;
266             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
267                     actual_client_random,
268                     client_random_size)))
269                 return 0;
270 
271             if (!TEST_ptr(token = strtok(NULL, " \n")))
272                 return 0;
273             master_key_size = SSL_SESSION_get_master_key(session,
274                 actual_master_key,
275                 master_key_size);
276             if (!TEST_size_t_ne(master_key_size, 0))
277                 return 0;
278             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
279                     actual_master_key,
280                     master_key_size)))
281                 return 0;
282             master_secret_count++;
283         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
284             || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
285             || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
286             || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
287             || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
288             || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
289             || strcmp(token, "EXPORTER_SECRET") == 0) {
290             /*
291              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
292              * client random, and then the hex-encoded secret. In this case,
293              * we treat all of these secrets identically and then just
294              * distinguish between them when counting what we saw.
295              */
296             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
297                 client_early_secret_count++;
298             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
299                 client_handshake_secret_count++;
300             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
301                 server_handshake_secret_count++;
302             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
303                 client_application_secret_count++;
304             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
305                 server_application_secret_count++;
306             else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
307                 early_exporter_secret_count++;
308             else if (strcmp(token, "EXPORTER_SECRET") == 0)
309                 exporter_secret_count++;
310 
311             client_random_size = SSL_get_client_random(ssl,
312                 actual_client_random,
313                 SSL3_RANDOM_SIZE);
314             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
315                 return 0;
316 
317             if (!TEST_ptr(token = strtok(NULL, " \n")))
318                 return 0;
319             if (!TEST_size_t_eq(strlen(token), 64))
320                 return 0;
321             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
322                     actual_client_random,
323                     client_random_size)))
324                 return 0;
325 
326             if (!TEST_ptr(token = strtok(NULL, " \n")))
327                 return 0;
328         } else {
329             TEST_info("Unexpected token %s\n", token);
330             return 0;
331         }
332     }
333 
334     /* Got what we expected? */
335     if (!TEST_size_t_eq(rsa_key_exchange_count,
336             expected->rsa_key_exchange_count)
337         || !TEST_size_t_eq(master_secret_count,
338             expected->master_secret_count)
339         || !TEST_size_t_eq(client_early_secret_count,
340             expected->client_early_secret_count)
341         || !TEST_size_t_eq(client_handshake_secret_count,
342             expected->client_handshake_secret_count)
343         || !TEST_size_t_eq(server_handshake_secret_count,
344             expected->server_handshake_secret_count)
345         || !TEST_size_t_eq(client_application_secret_count,
346             expected->client_application_secret_count)
347         || !TEST_size_t_eq(server_application_secret_count,
348             expected->server_application_secret_count)
349         || !TEST_size_t_eq(early_exporter_secret_count,
350             expected->early_exporter_secret_count)
351         || !TEST_size_t_eq(exporter_secret_count,
352             expected->exporter_secret_count))
353         return 0;
354     return 1;
355 }
356 
357 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
test_keylog(void)358 static int test_keylog(void)
359 {
360     SSL_CTX *cctx = NULL, *sctx = NULL;
361     SSL *clientssl = NULL, *serverssl = NULL;
362     int testresult = 0;
363     struct sslapitest_log_counts expected;
364 
365     /* Clean up logging space */
366     memset(&expected, 0, sizeof(expected));
367     memset(client_log_buffer, 0, sizeof(client_log_buffer));
368     memset(server_log_buffer, 0, sizeof(server_log_buffer));
369     client_log_buffer_index = 0;
370     server_log_buffer_index = 0;
371     error_writing_log = 0;
372 
373     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
374             TLS_client_method(),
375             TLS1_VERSION, 0,
376             &sctx, &cctx, cert, privkey)))
377         return 0;
378 
379     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
380     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
381     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
382 
383     /* We also want to ensure that we use RSA-based key exchange. */
384     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
385         goto end;
386 
387     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
388         || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
389         goto end;
390     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
391     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
392             == client_keylog_callback))
393         goto end;
394     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
395     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
396             == server_keylog_callback))
397         goto end;
398 
399     /* Now do a handshake and check that the logs have been written to. */
400     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
401             &clientssl, NULL, NULL))
402         || !TEST_true(create_ssl_connection(serverssl, clientssl,
403             SSL_ERROR_NONE))
404         || !TEST_false(error_writing_log)
405         || !TEST_int_gt(client_log_buffer_index, 0)
406         || !TEST_int_gt(server_log_buffer_index, 0))
407         goto end;
408 
409     /*
410      * Now we want to test that our output data was vaguely sensible. We
411      * do that by using strtok and confirming that we have more or less the
412      * data we expect. For both client and server, we expect to see one master
413      * secret. The client should also see an RSA key exchange.
414      */
415     expected.rsa_key_exchange_count = 1;
416     expected.master_secret_count = 1;
417     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
418             SSL_get_session(clientssl), &expected)))
419         goto end;
420 
421     expected.rsa_key_exchange_count = 0;
422     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
423             SSL_get_session(serverssl), &expected)))
424         goto end;
425 
426     testresult = 1;
427 
428 end:
429     SSL_free(serverssl);
430     SSL_free(clientssl);
431     SSL_CTX_free(sctx);
432     SSL_CTX_free(cctx);
433 
434     return testresult;
435 }
436 #endif
437 
438 #ifndef OSSL_NO_USABLE_TLS1_3
test_keylog_no_master_key(void)439 static int test_keylog_no_master_key(void)
440 {
441     SSL_CTX *cctx = NULL, *sctx = NULL;
442     SSL *clientssl = NULL, *serverssl = NULL;
443     SSL_SESSION *sess = NULL;
444     int testresult = 0;
445     struct sslapitest_log_counts expected;
446     unsigned char buf[1];
447     size_t readbytes, written;
448 
449     /* Clean up logging space */
450     memset(&expected, 0, sizeof(expected));
451     memset(client_log_buffer, 0, sizeof(client_log_buffer));
452     memset(server_log_buffer, 0, sizeof(server_log_buffer));
453     client_log_buffer_index = 0;
454     server_log_buffer_index = 0;
455     error_writing_log = 0;
456 
457     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
458             TLS_client_method(), TLS1_VERSION, 0,
459             &sctx, &cctx, cert, privkey))
460         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
461             SSL3_RT_MAX_PLAIN_LENGTH)))
462         return 0;
463 
464     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
465         || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
466         goto end;
467 
468     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
469     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
470             == client_keylog_callback))
471         goto end;
472 
473     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
474     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
475             == server_keylog_callback))
476         goto end;
477 
478     /* Now do a handshake and check that the logs have been written to. */
479     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
480             &clientssl, NULL, NULL))
481         || !TEST_true(create_ssl_connection(serverssl, clientssl,
482             SSL_ERROR_NONE))
483         || !TEST_false(error_writing_log))
484         goto end;
485 
486     /*
487      * Now we want to test that our output data was vaguely sensible. For this
488      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
489      * TLSv1.3, but we do expect both client and server to emit keys.
490      */
491     expected.client_handshake_secret_count = 1;
492     expected.server_handshake_secret_count = 1;
493     expected.client_application_secret_count = 1;
494     expected.server_application_secret_count = 1;
495     expected.exporter_secret_count = 1;
496     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
497             SSL_get_session(clientssl), &expected))
498         || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
499             SSL_get_session(serverssl),
500             &expected)))
501         goto end;
502 
503     /* Terminate old session and resume with early data. */
504     sess = SSL_get1_session(clientssl);
505     SSL_shutdown(clientssl);
506     SSL_shutdown(serverssl);
507     SSL_free(serverssl);
508     SSL_free(clientssl);
509     serverssl = clientssl = NULL;
510 
511     /* Reset key log */
512     memset(client_log_buffer, 0, sizeof(client_log_buffer));
513     memset(server_log_buffer, 0, sizeof(server_log_buffer));
514     client_log_buffer_index = 0;
515     server_log_buffer_index = 0;
516 
517     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
518             &clientssl, NULL, NULL))
519         || !TEST_true(SSL_set_session(clientssl, sess))
520         /* Here writing 0 length early data is enough. */
521         || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
522         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
523                             &readbytes),
524             SSL_READ_EARLY_DATA_ERROR)
525         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
526             SSL_EARLY_DATA_ACCEPTED)
527         || !TEST_true(create_ssl_connection(serverssl, clientssl,
528             SSL_ERROR_NONE))
529         || !TEST_true(SSL_session_reused(clientssl)))
530         goto end;
531 
532     /* In addition to the previous entries, expect early secrets. */
533     expected.client_early_secret_count = 1;
534     expected.early_exporter_secret_count = 1;
535     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
536             SSL_get_session(clientssl), &expected))
537         || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
538             SSL_get_session(serverssl),
539             &expected)))
540         goto end;
541 
542     testresult = 1;
543 
544 end:
545     SSL_SESSION_free(sess);
546     SSL_free(serverssl);
547     SSL_free(clientssl);
548     SSL_CTX_free(sctx);
549     SSL_CTX_free(cctx);
550 
551     return testresult;
552 }
553 #endif
554 
verify_retry_cb(X509_STORE_CTX * ctx,void * arg)555 static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg)
556 {
557     int res = X509_verify_cert(ctx);
558     int idx = SSL_get_ex_data_X509_STORE_CTX_idx();
559     SSL *ssl;
560 
561     /* this should not happen but check anyway */
562     if (idx < 0
563         || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL)
564         return 0;
565 
566     if (res == 0 && X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
567         /* indicate SSL_ERROR_WANT_RETRY_VERIFY */
568         return SSL_set_retry_verify(ssl);
569 
570     return res;
571 }
572 
test_client_cert_verify_cb(void)573 static int test_client_cert_verify_cb(void)
574 {
575     /* server key, cert, chain, and root */
576     char *skey = test_mk_file_path(certsdir, "leaf.key");
577     char *leaf = test_mk_file_path(certsdir, "leaf.pem");
578     char *int2 = test_mk_file_path(certsdir, "subinterCA.pem");
579     char *int1 = test_mk_file_path(certsdir, "interCA.pem");
580     char *root = test_mk_file_path(certsdir, "rootCA.pem");
581     X509 *crt1 = NULL, *crt2 = NULL;
582     STACK_OF(X509) *server_chain;
583     SSL_CTX *cctx = NULL, *sctx = NULL;
584     SSL *clientssl = NULL, *serverssl = NULL;
585     int testresult = 0;
586 
587     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
588             TLS_client_method(), TLS1_VERSION, 0,
589             &sctx, &cctx, NULL, NULL)))
590         goto end;
591     if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(sctx, leaf), 1)
592         || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, skey,
593                             SSL_FILETYPE_PEM),
594             1)
595         || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
596         goto end;
597     if (!TEST_true(SSL_CTX_load_verify_locations(cctx, root, NULL)))
598         goto end;
599     SSL_CTX_set_verify(cctx, SSL_VERIFY_PEER, NULL);
600     SSL_CTX_set_cert_verify_callback(cctx, verify_retry_cb, NULL);
601     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
602             &clientssl, NULL, NULL)))
603         goto end;
604 
605     /* attempt SSL_connect() with incomplete server chain */
606     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
607             SSL_ERROR_WANT_RETRY_VERIFY)))
608         goto end;
609 
610     /* application provides intermediate certs needed to verify server cert */
611     if (!TEST_ptr((crt1 = load_cert_pem(int1, libctx)))
612         || !TEST_ptr((crt2 = load_cert_pem(int2, libctx)))
613         || !TEST_ptr((server_chain = SSL_get_peer_cert_chain(clientssl))))
614         goto end;
615     /* add certs in reverse order to demonstrate real chain building */
616     if (!TEST_true(sk_X509_push(server_chain, crt1)))
617         goto end;
618     crt1 = NULL;
619     if (!TEST_true(sk_X509_push(server_chain, crt2)))
620         goto end;
621     crt2 = NULL;
622 
623     /* continue SSL_connect(), must now succeed with completed server chain */
624     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
625             SSL_ERROR_NONE)))
626         goto end;
627 
628     testresult = 1;
629 
630 end:
631     X509_free(crt1);
632     X509_free(crt2);
633     if (clientssl != NULL) {
634         SSL_shutdown(clientssl);
635         SSL_free(clientssl);
636     }
637     if (serverssl != NULL) {
638         SSL_shutdown(serverssl);
639         SSL_free(serverssl);
640     }
641     SSL_CTX_free(sctx);
642     SSL_CTX_free(cctx);
643 
644     OPENSSL_free(skey);
645     OPENSSL_free(leaf);
646     OPENSSL_free(int2);
647     OPENSSL_free(int1);
648     OPENSSL_free(root);
649 
650     return testresult;
651 }
652 
test_ssl_build_cert_chain(void)653 static int test_ssl_build_cert_chain(void)
654 {
655     int ret = 0;
656     SSL_CTX *ssl_ctx = NULL;
657     SSL *ssl = NULL;
658     char *skey = test_mk_file_path(certsdir, "leaf.key");
659     char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
660 
661     if (!TEST_ptr(ssl_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
662         goto end;
663     if (!TEST_ptr(ssl = SSL_new(ssl_ctx)))
664         goto end;
665     /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
666     if (!TEST_int_eq(SSL_use_certificate_chain_file(ssl, leaf_chain), 1)
667         || !TEST_int_eq(SSL_use_PrivateKey_file(ssl, skey, SSL_FILETYPE_PEM), 1)
668         || !TEST_int_eq(SSL_check_private_key(ssl), 1))
669         goto end;
670     if (!TEST_true(SSL_build_cert_chain(ssl, SSL_BUILD_CHAIN_FLAG_NO_ROOT | SSL_BUILD_CHAIN_FLAG_CHECK)))
671         goto end;
672     ret = 1;
673 end:
674     SSL_free(ssl);
675     SSL_CTX_free(ssl_ctx);
676     OPENSSL_free(leaf_chain);
677     OPENSSL_free(skey);
678     return ret;
679 }
680 
get_password_cb(char * buf,int size,int rw_flag,void * userdata)681 static int get_password_cb(char *buf, int size, int rw_flag, void *userdata)
682 {
683     static const char pass[] = "testpass";
684 
685     if (!TEST_int_eq(size, PEM_BUFSIZE))
686         return -1;
687 
688     memcpy(buf, pass, sizeof(pass) - 1);
689     return sizeof(pass) - 1;
690 }
691 
test_ssl_ctx_build_cert_chain(void)692 static int test_ssl_ctx_build_cert_chain(void)
693 {
694     int ret = 0;
695     SSL_CTX *ctx = NULL;
696     char *skey = test_mk_file_path(certsdir, "leaf-encrypted.key");
697     char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
698 
699     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
700         goto end;
701     SSL_CTX_set_default_passwd_cb(ctx, get_password_cb);
702     /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
703     if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(ctx, leaf_chain), 1)
704         || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(ctx, skey,
705                             SSL_FILETYPE_PEM),
706             1)
707         || !TEST_int_eq(SSL_CTX_check_private_key(ctx), 1))
708         goto end;
709     if (!TEST_true(SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT | SSL_BUILD_CHAIN_FLAG_CHECK)))
710         goto end;
711     ret = 1;
712 end:
713     SSL_CTX_free(ctx);
714     OPENSSL_free(leaf_chain);
715     OPENSSL_free(skey);
716     return ret;
717 }
718 
719 #ifndef OPENSSL_NO_TLS1_2
full_client_hello_callback(SSL * s,int * al,void * arg)720 static int full_client_hello_callback(SSL *s, int *al, void *arg)
721 {
722     int *ctr = arg;
723     const unsigned char *p;
724     int *exts;
725 #ifdef OPENSSL_NO_EC
726     const unsigned char expected_ciphers[] = { 0x00, 0x9d };
727 #else
728     const unsigned char expected_ciphers[] = { 0x00, 0x9d, 0xc0,
729         0x2c };
730 #endif
731     const int expected_extensions[] = {
732         65281,
733 #ifndef OPENSSL_NO_EC
734         11, 10,
735 #endif
736         35, 22, 23, 13
737     };
738     size_t len;
739 
740     /* Make sure we can defer processing and get called back. */
741     if ((*ctr)++ == 0)
742         return SSL_CLIENT_HELLO_RETRY;
743 
744     len = SSL_client_hello_get0_ciphers(s, &p);
745     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
746         || !TEST_size_t_eq(
747             SSL_client_hello_get0_compression_methods(s, &p), 1)
748         || !TEST_int_eq(*p, 0))
749         return SSL_CLIENT_HELLO_ERROR;
750     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
751         return SSL_CLIENT_HELLO_ERROR;
752     if (len != OSSL_NELEM(expected_extensions) || memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
753         printf("ClientHello callback expected extensions mismatch\n");
754         OPENSSL_free(exts);
755         return SSL_CLIENT_HELLO_ERROR;
756     }
757     OPENSSL_free(exts);
758     return SSL_CLIENT_HELLO_SUCCESS;
759 }
760 
test_client_hello_cb(void)761 static int test_client_hello_cb(void)
762 {
763     SSL_CTX *cctx = NULL, *sctx = NULL;
764     SSL *clientssl = NULL, *serverssl = NULL;
765     int testctr = 0, testresult = 0;
766 
767     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
768             TLS_client_method(), TLS1_VERSION, 0,
769             &sctx, &cctx, cert, privkey)))
770         goto end;
771     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
772 
773     /* The gimpy cipher list we configure can't do TLS 1.3. */
774     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
775     /* Avoid problems where the default seclevel has been changed */
776     SSL_CTX_set_security_level(cctx, 2);
777     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
778             "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
779         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
780             &clientssl, NULL, NULL))
781         || !TEST_false(create_ssl_connection(serverssl, clientssl,
782             SSL_ERROR_WANT_CLIENT_HELLO_CB))
783         /*
784          * Passing a -1 literal is a hack since
785          * the real value was lost.
786          * */
787         || !TEST_int_eq(SSL_get_error(serverssl, -1),
788             SSL_ERROR_WANT_CLIENT_HELLO_CB)
789         || !TEST_true(create_ssl_connection(serverssl, clientssl,
790             SSL_ERROR_NONE)))
791         goto end;
792 
793     testresult = 1;
794 
795 end:
796     SSL_free(serverssl);
797     SSL_free(clientssl);
798     SSL_CTX_free(sctx);
799     SSL_CTX_free(cctx);
800 
801     return testresult;
802 }
803 
test_no_ems(void)804 static int test_no_ems(void)
805 {
806     SSL_CTX *cctx = NULL, *sctx = NULL;
807     SSL *clientssl = NULL, *serverssl = NULL;
808     int testresult = 0, status;
809 
810     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
811             TLS1_VERSION, TLS1_2_VERSION,
812             &sctx, &cctx, cert, privkey)) {
813         printf("Unable to create SSL_CTX pair\n");
814         goto end;
815     }
816 
817     SSL_CTX_set_options(sctx, SSL_OP_NO_EXTENDED_MASTER_SECRET);
818 
819     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
820         printf("Unable to create SSL objects\n");
821         goto end;
822     }
823 
824     status = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
825     if (fips_ems_check) {
826         if (status == 1) {
827             printf("When FIPS uses the EMS check a connection that doesn't use EMS should fail\n");
828             goto end;
829         }
830     } else {
831         if (!status) {
832             printf("Creating SSL connection failed\n");
833             goto end;
834         }
835         if (SSL_get_extms_support(serverssl)) {
836             printf("Server reports Extended Master Secret support\n");
837             goto end;
838         }
839         if (SSL_get_extms_support(clientssl)) {
840             printf("Client reports Extended Master Secret support\n");
841             goto end;
842         }
843     }
844     testresult = 1;
845 
846 end:
847     SSL_free(serverssl);
848     SSL_free(clientssl);
849     SSL_CTX_free(sctx);
850     SSL_CTX_free(cctx);
851 
852     return testresult;
853 }
854 
855 /*
856  * Very focused test to exercise a single case in the server-side state
857  * machine, when the ChangeCipherState message needs to actually change
858  * from one cipher to a different cipher (i.e., not changing from null
859  * encryption to real encryption).
860  */
test_ccs_change_cipher(void)861 static int test_ccs_change_cipher(void)
862 {
863     SSL_CTX *cctx = NULL, *sctx = NULL;
864     SSL *clientssl = NULL, *serverssl = NULL;
865     SSL_SESSION *sess = NULL, *sesspre, *sesspost;
866     int testresult = 0;
867     int i;
868     unsigned char buf;
869     size_t readbytes;
870 
871     /*
872      * Create a connection so we can resume and potentially (but not) use
873      * a different cipher in the second connection.
874      */
875     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
876             TLS_client_method(),
877             TLS1_VERSION, TLS1_2_VERSION,
878             &sctx, &cctx, cert, privkey))
879         || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
880         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
881             NULL, NULL))
882         || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
883         || !TEST_true(create_ssl_connection(serverssl, clientssl,
884             SSL_ERROR_NONE))
885         || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
886         || !TEST_ptr(sess = SSL_get1_session(clientssl)))
887         goto end;
888 
889     shutdown_ssl_connection(serverssl, clientssl);
890     serverssl = clientssl = NULL;
891 
892     /* Resume, preferring a different cipher. Our server will force the
893      * same cipher to be used as the initial handshake. */
894     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
895             NULL, NULL))
896         || !TEST_true(SSL_set_session(clientssl, sess))
897         || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
898         || !TEST_true(create_ssl_connection(serverssl, clientssl,
899             SSL_ERROR_NONE))
900         || !TEST_true(SSL_session_reused(clientssl))
901         || !TEST_true(SSL_session_reused(serverssl))
902         || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
903         || !TEST_ptr_eq(sesspre, sesspost)
904         || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
905             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
906         goto end;
907     shutdown_ssl_connection(serverssl, clientssl);
908     serverssl = clientssl = NULL;
909 
910     /*
911      * Now create a fresh connection and try to renegotiate a different
912      * cipher on it.
913      */
914     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
915             NULL, NULL))
916         || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
917         || !TEST_true(create_ssl_connection(serverssl, clientssl,
918             SSL_ERROR_NONE))
919         || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
920         || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
921         || !TEST_true(SSL_renegotiate(clientssl))
922         || !TEST_true(SSL_renegotiate_pending(clientssl)))
923         goto end;
924     /* Actually drive the renegotiation. */
925     for (i = 0; i < 3; i++) {
926         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
927             if (!TEST_ulong_eq(readbytes, 0))
928                 goto end;
929         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
930                        SSL_ERROR_WANT_READ)) {
931             goto end;
932         }
933         if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
934             if (!TEST_ulong_eq(readbytes, 0))
935                 goto end;
936         } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
937                        SSL_ERROR_WANT_READ)) {
938             goto end;
939         }
940     }
941     /* sesspre and sesspost should be different since the cipher changed. */
942     if (!TEST_false(SSL_renegotiate_pending(clientssl))
943         || !TEST_false(SSL_session_reused(clientssl))
944         || !TEST_false(SSL_session_reused(serverssl))
945         || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
946         || !TEST_ptr_ne(sesspre, sesspost)
947         || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
948             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
949         goto end;
950 
951     shutdown_ssl_connection(serverssl, clientssl);
952     serverssl = clientssl = NULL;
953 
954     testresult = 1;
955 
956 end:
957     SSL_free(serverssl);
958     SSL_free(clientssl);
959     SSL_CTX_free(sctx);
960     SSL_CTX_free(cctx);
961     SSL_SESSION_free(sess);
962 
963     return testresult;
964 }
965 #endif
966 
execute_test_large_message(const SSL_METHOD * smeth,const SSL_METHOD * cmeth,int min_version,int max_version,int read_ahead)967 static int execute_test_large_message(const SSL_METHOD *smeth,
968     const SSL_METHOD *cmeth,
969     int min_version, int max_version,
970     int read_ahead)
971 {
972     SSL_CTX *cctx = NULL, *sctx = NULL;
973     SSL *clientssl = NULL, *serverssl = NULL;
974     int testresult = 0;
975 
976     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
977             max_version, &sctx, &cctx, cert,
978             privkey)))
979         goto end;
980 
981 #ifdef OPENSSL_NO_DTLS1_2
982     if (smeth == DTLS_server_method()) {
983         /*
984          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
985          * level 0
986          */
987         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
988             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
989                 "DEFAULT:@SECLEVEL=0")))
990             goto end;
991     }
992 #endif
993 
994     if (read_ahead) {
995         /*
996          * Test that read_ahead works correctly when dealing with large
997          * records
998          */
999         SSL_CTX_set_read_ahead(cctx, 1);
1000     }
1001 
1002     if (!ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
1003         goto end;
1004 
1005     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1006             NULL, NULL))
1007         || !TEST_true(create_ssl_connection(serverssl, clientssl,
1008             SSL_ERROR_NONE)))
1009         goto end;
1010 
1011     /*
1012      * Calling SSL_clear() first is not required but this tests that SSL_clear()
1013      * doesn't leak.
1014      */
1015     if (!TEST_true(SSL_clear(serverssl)))
1016         goto end;
1017 
1018     testresult = 1;
1019 end:
1020     SSL_free(serverssl);
1021     SSL_free(clientssl);
1022     SSL_CTX_free(sctx);
1023     SSL_CTX_free(cctx);
1024 
1025     return testresult;
1026 }
1027 
1028 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_KTLS) && !(defined(OSSL_NO_USABLE_TLS1_3) && defined(OPENSSL_NO_TLS1_2))
1029 /* sock must be connected */
ktls_chk_platform(int sock)1030 static int ktls_chk_platform(int sock)
1031 {
1032     if (!ktls_enable(sock))
1033         return 0;
1034     return 1;
1035 }
1036 
ping_pong_query(SSL * clientssl,SSL * serverssl)1037 static int ping_pong_query(SSL *clientssl, SSL *serverssl)
1038 {
1039     static char count = 1;
1040     unsigned char cbuf[16000] = { 0 };
1041     unsigned char sbuf[16000];
1042     size_t err = 0;
1043     char crec_wseq_before[SEQ_NUM_SIZE];
1044     char crec_wseq_after[SEQ_NUM_SIZE];
1045     char crec_rseq_before[SEQ_NUM_SIZE];
1046     char crec_rseq_after[SEQ_NUM_SIZE];
1047     char srec_wseq_before[SEQ_NUM_SIZE];
1048     char srec_wseq_after[SEQ_NUM_SIZE];
1049     char srec_rseq_before[SEQ_NUM_SIZE];
1050     char srec_rseq_after[SEQ_NUM_SIZE];
1051     SSL_CONNECTION *clientsc, *serversc;
1052 
1053     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1054         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1055         goto end;
1056 
1057     cbuf[0] = count++;
1058     memcpy(crec_wseq_before, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1059     memcpy(srec_wseq_before, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1060     memcpy(crec_rseq_before, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1061     memcpy(srec_rseq_before, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1062 
1063     if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf)))
1064         goto end;
1065 
1066     while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) {
1067         if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) {
1068             goto end;
1069         }
1070     }
1071 
1072     if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf)))
1073         goto end;
1074 
1075     while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) {
1076         if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) {
1077             goto end;
1078         }
1079     }
1080 
1081     memcpy(crec_wseq_after, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1082     memcpy(srec_wseq_after, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1083     memcpy(crec_rseq_after, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1084     memcpy(srec_rseq_after, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1085 
1086     /* verify the payload */
1087     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1088         goto end;
1089 
1090     /*
1091      * If ktls is used then kernel sequences are used instead of
1092      * OpenSSL sequences
1093      */
1094     if (!BIO_get_ktls_send(clientsc->wbio)) {
1095         if (!TEST_mem_ne(crec_wseq_before, SEQ_NUM_SIZE,
1096                 crec_wseq_after, SEQ_NUM_SIZE))
1097             goto end;
1098     } else {
1099         if (!TEST_mem_eq(crec_wseq_before, SEQ_NUM_SIZE,
1100                 crec_wseq_after, SEQ_NUM_SIZE))
1101             goto end;
1102     }
1103 
1104     if (!BIO_get_ktls_send(serversc->wbio)) {
1105         if (!TEST_mem_ne(srec_wseq_before, SEQ_NUM_SIZE,
1106                 srec_wseq_after, SEQ_NUM_SIZE))
1107             goto end;
1108     } else {
1109         if (!TEST_mem_eq(srec_wseq_before, SEQ_NUM_SIZE,
1110                 srec_wseq_after, SEQ_NUM_SIZE))
1111             goto end;
1112     }
1113 
1114     if (!BIO_get_ktls_recv(clientsc->wbio)) {
1115         if (!TEST_mem_ne(crec_rseq_before, SEQ_NUM_SIZE,
1116                 crec_rseq_after, SEQ_NUM_SIZE))
1117             goto end;
1118     } else {
1119         if (!TEST_mem_eq(crec_rseq_before, SEQ_NUM_SIZE,
1120                 crec_rseq_after, SEQ_NUM_SIZE))
1121             goto end;
1122     }
1123 
1124     if (!BIO_get_ktls_recv(serversc->wbio)) {
1125         if (!TEST_mem_ne(srec_rseq_before, SEQ_NUM_SIZE,
1126                 srec_rseq_after, SEQ_NUM_SIZE))
1127             goto end;
1128     } else {
1129         if (!TEST_mem_eq(srec_rseq_before, SEQ_NUM_SIZE,
1130                 srec_rseq_after, SEQ_NUM_SIZE))
1131             goto end;
1132     }
1133 
1134     return 1;
1135 end:
1136     return 0;
1137 }
1138 
execute_test_ktls(int cis_ktls,int sis_ktls,int tls_version,const char * cipher)1139 static int execute_test_ktls(int cis_ktls, int sis_ktls,
1140     int tls_version, const char *cipher)
1141 {
1142     SSL_CTX *cctx = NULL, *sctx = NULL;
1143     SSL *clientssl = NULL, *serverssl = NULL;
1144     int ktls_used = 0, testresult = 0;
1145     int cfd = -1, sfd = -1;
1146     int rx_supported;
1147     SSL_CONNECTION *clientsc, *serversc;
1148     unsigned char *buf = NULL;
1149     const size_t bufsz = SSL3_RT_MAX_PLAIN_LENGTH + 16;
1150     int ret;
1151     size_t offset = 0, i;
1152 
1153     if (!TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1154         goto end;
1155 
1156     /* Skip this test if the platform does not support ktls */
1157     if (!ktls_chk_platform(cfd)) {
1158         testresult = TEST_skip("Kernel does not support KTLS");
1159         goto end;
1160     }
1161 
1162     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1163         testresult = TEST_skip("CHACHA is not supported in FIPS");
1164         goto end;
1165     }
1166 
1167     /* Create a session based on SHA-256 */
1168     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1169             TLS_client_method(),
1170             tls_version, tls_version,
1171             &sctx, &cctx, cert, privkey)))
1172         goto end;
1173 
1174     if (tls_version == TLS1_3_VERSION) {
1175         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1176             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1177             goto end;
1178     } else {
1179         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1180             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1181             goto end;
1182     }
1183 
1184     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1185             &clientssl, sfd, cfd)))
1186         goto end;
1187 
1188     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1189         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1190         goto end;
1191 
1192     if (cis_ktls) {
1193         if (!TEST_true(SSL_set_options(clientssl, SSL_OP_ENABLE_KTLS)))
1194             goto end;
1195     }
1196 
1197     if (sis_ktls) {
1198         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1199             goto end;
1200     }
1201 
1202     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1203         goto end;
1204 
1205     /*
1206      * The running kernel may not support a given cipher suite
1207      * or direction, so just check that KTLS isn't used when it
1208      * isn't enabled.
1209      */
1210     if (!cis_ktls) {
1211         if (!TEST_false(BIO_get_ktls_send(clientsc->wbio)))
1212             goto end;
1213     } else {
1214         if (BIO_get_ktls_send(clientsc->wbio))
1215             ktls_used = 1;
1216     }
1217 
1218     if (!sis_ktls) {
1219         if (!TEST_false(BIO_get_ktls_send(serversc->wbio)))
1220             goto end;
1221     } else {
1222         if (BIO_get_ktls_send(serversc->wbio))
1223             ktls_used = 1;
1224     }
1225 
1226 #if defined(OPENSSL_NO_KTLS_RX)
1227     rx_supported = 0;
1228 #else
1229     rx_supported = 1;
1230 #endif
1231     if (!cis_ktls || !rx_supported) {
1232         if (!TEST_false(BIO_get_ktls_recv(clientsc->rbio)))
1233             goto end;
1234     } else {
1235         if (BIO_get_ktls_send(clientsc->rbio))
1236             ktls_used = 1;
1237     }
1238 
1239     if (!sis_ktls || !rx_supported) {
1240         if (!TEST_false(BIO_get_ktls_recv(serversc->rbio)))
1241             goto end;
1242     } else {
1243         if (BIO_get_ktls_send(serversc->rbio))
1244             ktls_used = 1;
1245     }
1246 
1247     if ((cis_ktls || sis_ktls) && !ktls_used) {
1248         testresult = TEST_skip("KTLS not supported for %s cipher %s",
1249             tls_version == TLS1_3_VERSION ? "TLS 1.3" : "TLS 1.2", cipher);
1250         goto end;
1251     }
1252 
1253     if (!TEST_true(ping_pong_query(clientssl, serverssl)))
1254         goto end;
1255 
1256     buf = OPENSSL_zalloc(bufsz);
1257     if (!TEST_ptr(buf))
1258         goto end;
1259 
1260     /*
1261      * Write some data that exceeds the maximum record length. KTLS may choose
1262      * to coalesce this data into a single buffer when we read it again.
1263      */
1264     while ((ret = SSL_write(clientssl, buf, bufsz)) != (int)bufsz) {
1265         if (!TEST_true(SSL_get_error(clientssl, ret) == SSL_ERROR_WANT_WRITE))
1266             goto end;
1267     }
1268 
1269     /* Now check that we can read all the data we wrote */
1270     do {
1271         ret = SSL_read(serverssl, buf + offset, bufsz - offset);
1272         if (ret <= 0) {
1273             if (!TEST_true(SSL_get_error(serverssl, ret) == SSL_ERROR_WANT_READ))
1274                 goto end;
1275         } else {
1276             offset += ret;
1277         }
1278     } while (offset < bufsz);
1279 
1280     if (!TEST_true(offset == bufsz))
1281         goto end;
1282     for (i = 0; i < bufsz; i++)
1283         if (!TEST_true(buf[i] == 0))
1284             goto end;
1285 
1286     testresult = 1;
1287 end:
1288     OPENSSL_free(buf);
1289     if (clientssl) {
1290         SSL_shutdown(clientssl);
1291         SSL_free(clientssl);
1292     }
1293     if (serverssl) {
1294         SSL_shutdown(serverssl);
1295         SSL_free(serverssl);
1296     }
1297     SSL_CTX_free(sctx);
1298     SSL_CTX_free(cctx);
1299     serverssl = clientssl = NULL;
1300     if (cfd != -1)
1301         close(cfd);
1302     if (sfd != -1)
1303         close(sfd);
1304     return testresult;
1305 }
1306 
1307 #define SENDFILE_SZ (16 * 4096)
1308 #define SENDFILE_CHUNK (4 * 4096)
1309 #define min(a, b) ((a) > (b) ? (b) : (a))
1310 
execute_test_ktls_sendfile(int tls_version,const char * cipher,int zerocopy)1311 static int execute_test_ktls_sendfile(int tls_version, const char *cipher,
1312     int zerocopy)
1313 {
1314     SSL_CTX *cctx = NULL, *sctx = NULL;
1315     SSL *clientssl = NULL, *serverssl = NULL;
1316     unsigned char *buf, *buf_dst;
1317     BIO *out = NULL, *in = NULL;
1318     int cfd = -1, sfd = -1, ffd, err;
1319     ssize_t chunk_size = 0;
1320     off_t chunk_off = 0;
1321     int testresult = 0;
1322     FILE *ffdp;
1323     SSL_CONNECTION *serversc;
1324 
1325     buf = OPENSSL_zalloc(SENDFILE_SZ);
1326     buf_dst = OPENSSL_zalloc(SENDFILE_SZ);
1327     if (!TEST_ptr(buf) || !TEST_ptr(buf_dst)
1328         || !TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1329         goto end;
1330 
1331     /* Skip this test if the platform does not support ktls */
1332     if (!ktls_chk_platform(sfd)) {
1333         testresult = TEST_skip("Kernel does not support KTLS");
1334         goto end;
1335     }
1336 
1337     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1338         testresult = TEST_skip("CHACHA is not supported in FIPS");
1339         goto end;
1340     }
1341 
1342     /* Create a session based on SHA-256 */
1343     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1344             TLS_client_method(),
1345             tls_version, tls_version,
1346             &sctx, &cctx, cert, privkey)))
1347         goto end;
1348 
1349     if (tls_version == TLS1_3_VERSION) {
1350         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1351             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1352             goto end;
1353     } else {
1354         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1355             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1356             goto end;
1357     }
1358 
1359     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1360             &clientssl, sfd, cfd)))
1361         goto end;
1362 
1363     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1364         goto end;
1365 
1366     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1367         goto end;
1368 
1369     if (zerocopy) {
1370         if (!TEST_true(SSL_set_options(serverssl,
1371                 SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE)))
1372             goto end;
1373     }
1374 
1375     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1376             SSL_ERROR_NONE)))
1377         goto end;
1378 
1379     if (!BIO_get_ktls_send(serversc->wbio)) {
1380         testresult = TEST_skip("Failed to enable KTLS for %s cipher %s",
1381             tls_version == TLS1_3_VERSION ? "TLS 1.3" : "TLS 1.2", cipher);
1382         goto end;
1383     }
1384 
1385     if (!TEST_int_gt(RAND_bytes_ex(libctx, buf, SENDFILE_SZ, 0), 0))
1386         goto end;
1387 
1388     out = BIO_new_file(tmpfilename, "wb");
1389     if (!TEST_ptr(out))
1390         goto end;
1391 
1392     if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ)
1393         goto end;
1394 
1395     BIO_free(out);
1396     out = NULL;
1397     in = BIO_new_file(tmpfilename, "rb");
1398     BIO_get_fp(in, &ffdp);
1399     ffd = fileno(ffdp);
1400 
1401     while (chunk_off < SENDFILE_SZ) {
1402         chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off);
1403         while ((err = SSL_sendfile(serverssl,
1404                     ffd,
1405                     chunk_off,
1406                     chunk_size,
1407                     0))
1408             != chunk_size) {
1409             if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE)
1410                 goto end;
1411         }
1412         while ((err = SSL_read(clientssl,
1413                     buf_dst + chunk_off,
1414                     chunk_size))
1415             != chunk_size) {
1416             if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ)
1417                 goto end;
1418         }
1419 
1420         /* verify the payload */
1421         if (!TEST_mem_eq(buf_dst + chunk_off,
1422                 chunk_size,
1423                 buf + chunk_off,
1424                 chunk_size))
1425             goto end;
1426 
1427         chunk_off += chunk_size;
1428     }
1429 
1430     testresult = 1;
1431 end:
1432     if (clientssl) {
1433         SSL_shutdown(clientssl);
1434         SSL_free(clientssl);
1435     }
1436     if (serverssl) {
1437         SSL_shutdown(serverssl);
1438         SSL_free(serverssl);
1439     }
1440     SSL_CTX_free(sctx);
1441     SSL_CTX_free(cctx);
1442     serverssl = clientssl = NULL;
1443     BIO_free(out);
1444     BIO_free(in);
1445     if (cfd != -1)
1446         close(cfd);
1447     if (sfd != -1)
1448         close(sfd);
1449     OPENSSL_free(buf);
1450     OPENSSL_free(buf_dst);
1451     return testresult;
1452 }
1453 
1454 static struct ktls_test_cipher {
1455     int tls_version;
1456     const char *cipher;
1457 } ktls_test_ciphers[] = {
1458 #if !defined(OPENSSL_NO_TLS1_2)
1459 #ifdef OPENSSL_KTLS_AES_GCM_128
1460     { TLS1_2_VERSION, "AES128-GCM-SHA256" },
1461 #endif
1462 #ifdef OPENSSL_KTLS_AES_CCM_128
1463     { TLS1_2_VERSION, "AES128-CCM" },
1464 #endif
1465 #ifdef OPENSSL_KTLS_AES_GCM_256
1466     { TLS1_2_VERSION, "AES256-GCM-SHA384" },
1467 #endif
1468 #ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1469 #ifndef OPENSSL_NO_EC
1470     { TLS1_2_VERSION, "ECDHE-RSA-CHACHA20-POLY1305" },
1471 #endif
1472 #endif
1473 #endif
1474 #if !defined(OSSL_NO_USABLE_TLS1_3)
1475 #ifdef OPENSSL_KTLS_AES_GCM_128
1476     { TLS1_3_VERSION, "TLS_AES_128_GCM_SHA256" },
1477 #endif
1478 #ifdef OPENSSL_KTLS_AES_CCM_128
1479     { TLS1_3_VERSION, "TLS_AES_128_CCM_SHA256" },
1480 #endif
1481 #ifdef OPENSSL_KTLS_AES_GCM_256
1482     { TLS1_3_VERSION, "TLS_AES_256_GCM_SHA384" },
1483 #endif
1484 #ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1485     { TLS1_3_VERSION, "TLS_CHACHA20_POLY1305_SHA256" },
1486 #endif
1487 #endif
1488 };
1489 
1490 #define NUM_KTLS_TEST_CIPHERS OSSL_NELEM(ktls_test_ciphers)
1491 
test_ktls(int test)1492 static int test_ktls(int test)
1493 {
1494     struct ktls_test_cipher *cipher;
1495     int cis_ktls, sis_ktls;
1496 
1497     OPENSSL_assert(test / 4 < (int)NUM_KTLS_TEST_CIPHERS);
1498     cipher = &ktls_test_ciphers[test / 4];
1499 
1500     cis_ktls = (test & 1) != 0;
1501     sis_ktls = (test & 2) != 0;
1502 
1503     return execute_test_ktls(cis_ktls, sis_ktls, cipher->tls_version,
1504         cipher->cipher);
1505 }
1506 
test_ktls_sendfile(int test)1507 static int test_ktls_sendfile(int test)
1508 {
1509     struct ktls_test_cipher *cipher;
1510     int tst = test >> 1;
1511 
1512     OPENSSL_assert(tst < (int)NUM_KTLS_TEST_CIPHERS);
1513     cipher = &ktls_test_ciphers[tst];
1514 
1515     return execute_test_ktls_sendfile(cipher->tls_version, cipher->cipher,
1516         test & 1);
1517 }
1518 #endif
1519 
test_large_message_tls(void)1520 static int test_large_message_tls(void)
1521 {
1522     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1523         TLS1_VERSION, 0, 0);
1524 }
1525 
test_large_message_tls_read_ahead(void)1526 static int test_large_message_tls_read_ahead(void)
1527 {
1528     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1529         TLS1_VERSION, 0, 1);
1530 }
1531 
1532 #ifndef OPENSSL_NO_DTLS
test_large_message_dtls(void)1533 static int test_large_message_dtls(void)
1534 {
1535 #ifdef OPENSSL_NO_DTLS1_2
1536     /* Not supported in the FIPS provider */
1537     if (is_fips)
1538         return 1;
1539 #endif
1540     /*
1541      * read_ahead is not relevant to DTLS because DTLS always acts as if
1542      * read_ahead is set.
1543      */
1544     return execute_test_large_message(DTLS_server_method(),
1545         DTLS_client_method(),
1546         DTLS1_VERSION, 0, 0);
1547 }
1548 #endif
1549 
1550 /*
1551  * Test we can successfully send the maximum amount of application data. We
1552  * test each protocol version individually, each with and without EtM enabled.
1553  * TLSv1.3 doesn't use EtM so technically it is redundant to test both but it is
1554  * simpler this way. We also test all combinations with and without the
1555  * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS option which affects the size of the
1556  * underlying buffer.
1557  */
test_large_app_data(int tst)1558 static int test_large_app_data(int tst)
1559 {
1560     SSL_CTX *cctx = NULL, *sctx = NULL;
1561     SSL *clientssl = NULL, *serverssl = NULL;
1562     int testresult = 0, prot;
1563     unsigned char *msg, *buf = NULL;
1564     size_t written, readbytes;
1565     const SSL_METHOD *smeth = TLS_server_method();
1566     const SSL_METHOD *cmeth = TLS_client_method();
1567 
1568     switch (tst >> 2) {
1569     case 0:
1570 #ifndef OSSL_NO_USABLE_TLS1_3
1571         prot = TLS1_3_VERSION;
1572         break;
1573 #else
1574         return TEST_skip("TLS 1.3 not supported");
1575 #endif
1576 
1577     case 1:
1578 #ifndef OPENSSL_NO_TLS1_2
1579         prot = TLS1_2_VERSION;
1580         break;
1581 #else
1582         return TEST_skip("TLS 1.2 not supported");
1583 #endif
1584 
1585     case 2:
1586 #ifndef OPENSSL_NO_TLS1_1
1587         prot = TLS1_1_VERSION;
1588         break;
1589 #else
1590         return TEST_skip("TLS 1.1 not supported");
1591 #endif
1592 
1593     case 3:
1594 #ifndef OPENSSL_NO_TLS1
1595         prot = TLS1_VERSION;
1596         break;
1597 #else
1598         return TEST_skip("TLS 1 not supported");
1599 #endif
1600 
1601     case 4:
1602 #ifndef OPENSSL_NO_SSL3
1603         prot = SSL3_VERSION;
1604         break;
1605 #else
1606         return TEST_skip("SSL 3 not supported");
1607 #endif
1608 
1609     case 5:
1610 #ifndef OPENSSL_NO_DTLS1_2
1611         prot = DTLS1_2_VERSION;
1612         smeth = DTLS_server_method();
1613         cmeth = DTLS_client_method();
1614         break;
1615 #else
1616         return TEST_skip("DTLS 1.2 not supported");
1617 #endif
1618 
1619     case 6:
1620 #ifndef OPENSSL_NO_DTLS1
1621         if (is_fips)
1622             return TEST_skip("DTLS 1 not supported by FIPS provider");
1623         prot = DTLS1_VERSION;
1624         smeth = DTLS_server_method();
1625         cmeth = DTLS_client_method();
1626         break;
1627 #else
1628         return TEST_skip("DTLS 1 not supported");
1629 #endif
1630 
1631     default:
1632         /* Shouldn't happen */
1633         return 0;
1634     }
1635 
1636     if (is_fips && prot < TLS1_2_VERSION)
1637         return TEST_skip("TLS versions < 1.2 not supported by FIPS provider");
1638 
1639     /* Maximal sized message of zeros */
1640     msg = OPENSSL_zalloc(SSL3_RT_MAX_PLAIN_LENGTH);
1641     if (!TEST_ptr(msg))
1642         goto end;
1643 
1644     buf = OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH + 1);
1645     if (!TEST_ptr(buf))
1646         goto end;
1647     /* Set whole buffer to all bits set */
1648     memset(buf, 0xff, SSL3_RT_MAX_PLAIN_LENGTH + 1);
1649 
1650     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, prot, prot,
1651             &sctx, &cctx, cert, privkey)))
1652         goto end;
1653 
1654     if (prot < TLS1_2_VERSION || prot == DTLS1_VERSION) {
1655         /* Older protocol versions need SECLEVEL=0 due to SHA1 usage */
1656         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0"))
1657             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
1658                 "DEFAULT:@SECLEVEL=0")))
1659             goto end;
1660     }
1661 
1662     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1663             &clientssl, NULL, NULL)))
1664         goto end;
1665 
1666     if ((tst & 1) != 0) {
1667         /* Setting this option gives us a minimally sized underlying buffer */
1668         if (!TEST_true(SSL_set_options(serverssl,
1669                 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
1670             || !TEST_true(SSL_set_options(clientssl,
1671                 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)))
1672             goto end;
1673     }
1674 
1675     if ((tst & 2) != 0) {
1676         /*
1677          * Setting this option means the MAC is added before encryption
1678          * giving us a larger record for the encryption process
1679          */
1680         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC))
1681             || !TEST_true(SSL_set_options(clientssl,
1682                 SSL_OP_NO_ENCRYPT_THEN_MAC)))
1683             goto end;
1684     }
1685 
1686     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1687         goto end;
1688 
1689     if (!TEST_true(SSL_write_ex(clientssl, msg, SSL3_RT_MAX_PLAIN_LENGTH,
1690             &written))
1691         || !TEST_size_t_eq(written, SSL3_RT_MAX_PLAIN_LENGTH))
1692         goto end;
1693 
1694     /* We provide a buffer slightly larger than what we are actually expecting */
1695     if (!TEST_true(SSL_read_ex(serverssl, buf, SSL3_RT_MAX_PLAIN_LENGTH + 1,
1696             &readbytes)))
1697         goto end;
1698 
1699     if (!TEST_mem_eq(msg, written, buf, readbytes))
1700         goto end;
1701 
1702     testresult = 1;
1703 end:
1704     OPENSSL_free(msg);
1705     OPENSSL_free(buf);
1706     SSL_free(serverssl);
1707     SSL_free(clientssl);
1708     SSL_CTX_free(sctx);
1709     SSL_CTX_free(cctx);
1710     return testresult;
1711 }
1712 
1713 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) \
1714     || !defined(OPENSSL_NO_DTLS)
execute_cleanse_plaintext(const SSL_METHOD * smeth,const SSL_METHOD * cmeth,int min_version,int max_version)1715 static int execute_cleanse_plaintext(const SSL_METHOD *smeth,
1716     const SSL_METHOD *cmeth,
1717     int min_version, int max_version)
1718 {
1719     size_t i;
1720     SSL_CTX *cctx = NULL, *sctx = NULL;
1721     SSL *clientssl = NULL, *serverssl = NULL;
1722     int testresult = 0;
1723     const unsigned char *zbuf;
1724     SSL_CONNECTION *serversc;
1725     TLS_RECORD *rr;
1726 
1727     static unsigned char cbuf[16000];
1728     static unsigned char sbuf[16000];
1729 
1730     if (!TEST_true(create_ssl_ctx_pair(libctx,
1731             smeth, cmeth,
1732             min_version, max_version,
1733             &sctx, &cctx, cert,
1734             privkey)))
1735         goto end;
1736 
1737 #ifdef OPENSSL_NO_DTLS1_2
1738     if (smeth == DTLS_server_method()) {
1739         /* Not supported in the FIPS provider */
1740         if (is_fips) {
1741             testresult = 1;
1742             goto end;
1743         };
1744         /*
1745          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
1746          * level 0
1747          */
1748         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
1749             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1750                 "DEFAULT:@SECLEVEL=0")))
1751             goto end;
1752     }
1753 #endif
1754 
1755     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1756             NULL, NULL)))
1757         goto end;
1758 
1759     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_CLEANSE_PLAINTEXT)))
1760         goto end;
1761 
1762     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1763             SSL_ERROR_NONE)))
1764         goto end;
1765 
1766     for (i = 0; i < sizeof(cbuf); i++) {
1767         cbuf[i] = i & 0xff;
1768     }
1769 
1770     if (!TEST_int_eq(SSL_write(clientssl, cbuf, sizeof(cbuf)), sizeof(cbuf)))
1771         goto end;
1772 
1773     if (!TEST_int_eq(SSL_peek(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1774         goto end;
1775 
1776     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1777         goto end;
1778 
1779     /*
1780      * Since we called SSL_peek(), we know the data in the record
1781      * layer is a plaintext record. We can gather the pointer to check
1782      * for zeroization after SSL_read().
1783      */
1784     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1785         goto end;
1786     rr = serversc->rlayer.tlsrecs;
1787 
1788     zbuf = &rr->data[rr->off];
1789     if (!TEST_int_eq(rr->length, sizeof(cbuf)))
1790         goto end;
1791 
1792     /*
1793      * After SSL_peek() the plaintext must still be stored in the
1794      * record.
1795      */
1796     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1797         goto end;
1798 
1799     memset(sbuf, 0, sizeof(sbuf));
1800     if (!TEST_int_eq(SSL_read(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1801         goto end;
1802 
1803     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(cbuf)))
1804         goto end;
1805 
1806     /* Check if rbuf is cleansed */
1807     memset(cbuf, 0, sizeof(cbuf));
1808     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1809         goto end;
1810 
1811     testresult = 1;
1812 end:
1813     SSL_free(serverssl);
1814     SSL_free(clientssl);
1815     SSL_CTX_free(sctx);
1816     SSL_CTX_free(cctx);
1817 
1818     return testresult;
1819 }
1820 #endif /*                                                                \
1821         * !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) \
1822         * || !defined(OPENSSL_NO_DTLS)                                   \
1823         */
1824 
test_cleanse_plaintext(void)1825 static int test_cleanse_plaintext(void)
1826 {
1827 #if !defined(OPENSSL_NO_TLS1_2)
1828     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1829             TLS_client_method(),
1830             TLS1_2_VERSION,
1831             TLS1_2_VERSION)))
1832         return 0;
1833 
1834 #endif
1835 
1836 #if !defined(OSSL_NO_USABLE_TLS1_3)
1837     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1838             TLS_client_method(),
1839             TLS1_3_VERSION,
1840             TLS1_3_VERSION)))
1841         return 0;
1842 #endif
1843 
1844 #if !defined(OPENSSL_NO_DTLS)
1845 
1846     if (!TEST_true(execute_cleanse_plaintext(DTLS_server_method(),
1847             DTLS_client_method(),
1848             DTLS1_VERSION,
1849             0)))
1850         return 0;
1851 #endif
1852     return 1;
1853 }
1854 
1855 #ifndef OPENSSL_NO_OCSP
ocsp_server_cb(SSL * s,void * arg)1856 static int ocsp_server_cb(SSL *s, void *arg)
1857 {
1858     int *argi = (int *)arg;
1859     unsigned char *copy = NULL;
1860     STACK_OF(OCSP_RESPID) *ids = NULL;
1861     OCSP_RESPID *id = NULL;
1862 
1863     if (*argi == 2) {
1864         /* In this test we are expecting exactly 1 OCSP_RESPID */
1865         SSL_get_tlsext_status_ids(s, &ids);
1866         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
1867             return SSL_TLSEXT_ERR_ALERT_FATAL;
1868 
1869         id = sk_OCSP_RESPID_value(ids, 0);
1870         if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL))
1871             return SSL_TLSEXT_ERR_ALERT_FATAL;
1872     } else if (*argi != 1) {
1873         return SSL_TLSEXT_ERR_ALERT_FATAL;
1874     }
1875 
1876     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
1877         return SSL_TLSEXT_ERR_ALERT_FATAL;
1878 
1879     if (!TEST_true(SSL_set_tlsext_status_ocsp_resp(s, copy,
1880             sizeof(orespder)))) {
1881         OPENSSL_free(copy);
1882         return SSL_TLSEXT_ERR_ALERT_FATAL;
1883     }
1884     ocsp_server_called = 1;
1885     return SSL_TLSEXT_ERR_OK;
1886 }
1887 
ocsp_client_cb(SSL * s,void * arg)1888 static int ocsp_client_cb(SSL *s, void *arg)
1889 {
1890     int *argi = (int *)arg;
1891     const unsigned char *respderin;
1892     size_t len;
1893 
1894     if (*argi != 1 && *argi != 2)
1895         return 0;
1896 
1897     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
1898     if (!TEST_mem_eq(orespder, len, respderin, len))
1899         return 0;
1900 
1901     ocsp_client_called = 1;
1902     return 1;
1903 }
1904 
test_tlsext_status_type(void)1905 static int test_tlsext_status_type(void)
1906 {
1907     SSL_CTX *cctx = NULL, *sctx = NULL;
1908     SSL *clientssl = NULL, *serverssl = NULL;
1909     int testresult = 0;
1910     STACK_OF(OCSP_RESPID) *ids = NULL;
1911     OCSP_RESPID *id = NULL;
1912     BIO *certbio = NULL;
1913 
1914     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
1915             TLS1_VERSION, 0,
1916             &sctx, &cctx, cert, privkey))
1917         return 0;
1918 
1919     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
1920         goto end;
1921 
1922     /* First just do various checks getting and setting tlsext_status_type */
1923 
1924     clientssl = SSL_new(cctx);
1925     if (!TEST_ptr(clientssl))
1926         goto end;
1927     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
1928         || !TEST_true(SSL_set_tlsext_status_type(clientssl,
1929             TLSEXT_STATUSTYPE_ocsp))
1930         || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
1931             TLSEXT_STATUSTYPE_ocsp))
1932         goto end;
1933 
1934     SSL_free(clientssl);
1935     clientssl = NULL;
1936 
1937     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
1938         || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
1939         goto end;
1940 
1941     clientssl = SSL_new(cctx);
1942     if (!TEST_ptr(clientssl))
1943         goto end;
1944     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
1945         goto end;
1946     SSL_free(clientssl);
1947     clientssl = NULL;
1948 
1949     /*
1950      * Now actually do a handshake and check OCSP information is exchanged and
1951      * the callbacks get called
1952      */
1953     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
1954     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
1955     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
1956     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
1957     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1958             &clientssl, NULL, NULL))
1959         || !TEST_true(create_ssl_connection(serverssl, clientssl,
1960             SSL_ERROR_NONE))
1961         || !TEST_true(ocsp_client_called)
1962         || !TEST_true(ocsp_server_called))
1963         goto end;
1964     SSL_free(serverssl);
1965     SSL_free(clientssl);
1966     serverssl = NULL;
1967     clientssl = NULL;
1968 
1969     /* Try again but this time force the server side callback to fail */
1970     ocsp_client_called = 0;
1971     ocsp_server_called = 0;
1972     cdummyarg = 0;
1973     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1974             &clientssl, NULL, NULL))
1975         /* This should fail because the callback will fail */
1976         || !TEST_false(create_ssl_connection(serverssl, clientssl,
1977             SSL_ERROR_NONE))
1978         || !TEST_false(ocsp_client_called)
1979         || !TEST_false(ocsp_server_called))
1980         goto end;
1981     SSL_free(serverssl);
1982     SSL_free(clientssl);
1983     serverssl = NULL;
1984     clientssl = NULL;
1985 
1986     /*
1987      * This time we'll get the client to send an OCSP_RESPID that it will
1988      * accept.
1989      */
1990     ocsp_client_called = 0;
1991     ocsp_server_called = 0;
1992     cdummyarg = 2;
1993     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1994             &clientssl, NULL, NULL)))
1995         goto end;
1996 
1997     /*
1998      * We'll just use any old cert for this test - it doesn't have to be an OCSP
1999      * specific one. We'll use the server cert.
2000      */
2001     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
2002         || !TEST_ptr(id = OCSP_RESPID_new())
2003         || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
2004         || !TEST_ptr(ocspcert = X509_new_ex(libctx, NULL))
2005         || !TEST_ptr(PEM_read_bio_X509(certbio, &ocspcert, NULL, NULL))
2006         || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL))
2007         || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
2008         goto end;
2009     id = NULL;
2010     SSL_set_tlsext_status_ids(clientssl, ids);
2011     /* Control has been transferred */
2012     ids = NULL;
2013 
2014     BIO_free(certbio);
2015     certbio = NULL;
2016 
2017     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2018             SSL_ERROR_NONE))
2019         || !TEST_true(ocsp_client_called)
2020         || !TEST_true(ocsp_server_called))
2021         goto end;
2022 
2023     testresult = 1;
2024 
2025 end:
2026     SSL_free(serverssl);
2027     SSL_free(clientssl);
2028     SSL_CTX_free(sctx);
2029     SSL_CTX_free(cctx);
2030     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
2031     OCSP_RESPID_free(id);
2032     BIO_free(certbio);
2033     X509_free(ocspcert);
2034     ocspcert = NULL;
2035 
2036     return testresult;
2037 }
2038 #endif
2039 
2040 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
2041 static int new_called, remove_called, get_called;
2042 
new_session_cb(SSL * ssl,SSL_SESSION * sess)2043 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
2044 {
2045     new_called++;
2046     /*
2047      * sess has been up-refed for us, but we don't actually need it so free it
2048      * immediately.
2049      */
2050     SSL_SESSION_free(sess);
2051     return 1;
2052 }
2053 
remove_session_cb(SSL_CTX * ctx,SSL_SESSION * sess)2054 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
2055 {
2056     remove_called++;
2057 }
2058 
2059 static SSL_SESSION *get_sess_val = NULL;
2060 
get_session_cb(SSL * ssl,const unsigned char * id,int len,int * copy)2061 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
2062     int *copy)
2063 {
2064     get_called++;
2065     *copy = 1;
2066     return get_sess_val;
2067 }
2068 
execute_test_session(int maxprot,int use_int_cache,int use_ext_cache,long s_options)2069 static int execute_test_session(int maxprot, int use_int_cache,
2070     int use_ext_cache, long s_options)
2071 {
2072     SSL_CTX *sctx = NULL, *cctx = NULL;
2073     SSL *serverssl1 = NULL, *clientssl1 = NULL;
2074     SSL *serverssl2 = NULL, *clientssl2 = NULL;
2075 #ifndef OPENSSL_NO_TLS1_1
2076     SSL *serverssl3 = NULL, *clientssl3 = NULL;
2077 #endif
2078     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
2079     int testresult = 0, numnewsesstick = 1;
2080 
2081     new_called = remove_called = 0;
2082 
2083     /* TLSv1.3 sends 2 NewSessionTickets */
2084     if (maxprot == TLS1_3_VERSION)
2085         numnewsesstick = 2;
2086 
2087     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2088             TLS_client_method(), TLS1_VERSION, 0,
2089             &sctx, &cctx, cert, privkey)))
2090         return 0;
2091 
2092     /*
2093      * Only allow the max protocol version so we can force a connection failure
2094      * later
2095      */
2096     SSL_CTX_set_min_proto_version(cctx, maxprot);
2097     SSL_CTX_set_max_proto_version(cctx, maxprot);
2098 
2099     /* Set up session cache */
2100     if (use_ext_cache) {
2101         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2102         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
2103     }
2104     if (use_int_cache) {
2105         /* Also covers instance where both are set */
2106         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
2107     } else {
2108         SSL_CTX_set_session_cache_mode(cctx,
2109             SSL_SESS_CACHE_CLIENT
2110                 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2111     }
2112 
2113     if (s_options) {
2114         SSL_CTX_set_options(sctx, s_options);
2115     }
2116 
2117     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2118             NULL, NULL))
2119         || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2120             SSL_ERROR_NONE))
2121         || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
2122         goto end;
2123 
2124     /* Should fail because it should already be in the cache */
2125     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
2126         goto end;
2127     if (use_ext_cache
2128         && (!TEST_int_eq(new_called, numnewsesstick)
2129 
2130             || !TEST_int_eq(remove_called, 0)))
2131         goto end;
2132 
2133     new_called = remove_called = 0;
2134     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2135             &clientssl2, NULL, NULL))
2136         || !TEST_true(SSL_set_session(clientssl2, sess1))
2137         || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2138             SSL_ERROR_NONE))
2139         || !TEST_true(SSL_session_reused(clientssl2)))
2140         goto end;
2141 
2142     if (maxprot == TLS1_3_VERSION) {
2143         /*
2144          * In TLSv1.3 we should have created a new session even though we have
2145          * resumed. Since we attempted a resume we should also have removed the
2146          * old ticket from the cache so that we try to only use tickets once.
2147          */
2148         if (use_ext_cache
2149             && (!TEST_int_eq(new_called, 1)
2150                 || !TEST_int_eq(remove_called, 1)))
2151             goto end;
2152     } else {
2153         /*
2154          * In TLSv1.2 we expect to have resumed so no sessions added or
2155          * removed.
2156          */
2157         if (use_ext_cache
2158             && (!TEST_int_eq(new_called, 0)
2159                 || !TEST_int_eq(remove_called, 0)))
2160             goto end;
2161     }
2162 
2163     SSL_SESSION_free(sess1);
2164     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
2165         goto end;
2166     shutdown_ssl_connection(serverssl2, clientssl2);
2167     serverssl2 = clientssl2 = NULL;
2168 
2169     new_called = remove_called = 0;
2170     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2171             &clientssl2, NULL, NULL))
2172         || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2173             SSL_ERROR_NONE)))
2174         goto end;
2175 
2176     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
2177         goto end;
2178 
2179     if (use_ext_cache
2180         && (!TEST_int_eq(new_called, numnewsesstick)
2181             || !TEST_int_eq(remove_called, 0)))
2182         goto end;
2183 
2184     new_called = remove_called = 0;
2185     /*
2186      * This should clear sess2 from the cache because it is a "bad" session.
2187      * See SSL_set_session() documentation.
2188      */
2189     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
2190         goto end;
2191     if (use_ext_cache
2192         && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2193         goto end;
2194     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
2195         goto end;
2196 
2197     if (use_int_cache) {
2198         /* Should succeeded because it should not already be in the cache */
2199         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
2200             || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
2201             goto end;
2202     }
2203 
2204     new_called = remove_called = 0;
2205     /* This shouldn't be in the cache so should fail */
2206     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
2207         goto end;
2208 
2209     if (use_ext_cache
2210         && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2211         goto end;
2212 
2213 #if !defined(OPENSSL_NO_TLS1_1)
2214     new_called = remove_called = 0;
2215     /* Force a connection failure */
2216     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
2217     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
2218             &clientssl3, NULL, NULL))
2219         || !TEST_true(SSL_set_session(clientssl3, sess1))
2220         /* This should fail because of the mismatched protocol versions */
2221         || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
2222             SSL_ERROR_NONE)))
2223         goto end;
2224 
2225     /* We should have automatically removed the session from the cache */
2226     if (use_ext_cache
2227         && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2228         goto end;
2229 
2230     /* Should succeed because it should not already be in the cache */
2231     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
2232         goto end;
2233 #endif
2234 
2235     /* Now do some tests for server side caching */
2236     if (use_ext_cache) {
2237         SSL_CTX_sess_set_new_cb(cctx, NULL);
2238         SSL_CTX_sess_set_remove_cb(cctx, NULL);
2239         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2240         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
2241         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
2242         get_sess_val = NULL;
2243     }
2244 
2245     SSL_CTX_set_session_cache_mode(cctx, 0);
2246     /* Internal caching is the default on the server side */
2247     if (!use_int_cache)
2248         SSL_CTX_set_session_cache_mode(sctx,
2249             SSL_SESS_CACHE_SERVER
2250                 | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2251 
2252     SSL_free(serverssl1);
2253     SSL_free(clientssl1);
2254     serverssl1 = clientssl1 = NULL;
2255     SSL_free(serverssl2);
2256     SSL_free(clientssl2);
2257     serverssl2 = clientssl2 = NULL;
2258     SSL_SESSION_free(sess1);
2259     sess1 = NULL;
2260     SSL_SESSION_free(sess2);
2261     sess2 = NULL;
2262 
2263     SSL_CTX_set_max_proto_version(sctx, maxprot);
2264     if (maxprot == TLS1_2_VERSION)
2265         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
2266     new_called = remove_called = get_called = 0;
2267     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2268             NULL, NULL))
2269         || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2270             SSL_ERROR_NONE))
2271         || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
2272         || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
2273         goto end;
2274 
2275     if (use_int_cache) {
2276         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
2277             /*
2278              * In TLSv1.3 it should not have been added to the internal cache,
2279              * except in the case where we also have an external cache (in that
2280              * case it gets added to the cache in order to generate remove
2281              * events after timeout).
2282              */
2283             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
2284                 goto end;
2285         } else {
2286             /* Should fail because it should already be in the cache */
2287             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
2288                 goto end;
2289         }
2290     }
2291 
2292     if (use_ext_cache) {
2293         SSL_SESSION *tmp = sess2;
2294 
2295         if (!TEST_int_eq(new_called, numnewsesstick)
2296             || !TEST_int_eq(remove_called, 0)
2297             || !TEST_int_eq(get_called, 0))
2298             goto end;
2299         /*
2300          * Delete the session from the internal cache to force a lookup from
2301          * the external cache. We take a copy first because
2302          * SSL_CTX_remove_session() also marks the session as non-resumable.
2303          */
2304         if (use_int_cache && maxprot != TLS1_3_VERSION) {
2305             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
2306                 || !TEST_true(sess2->owner != NULL)
2307                 || !TEST_true(tmp->owner == NULL)
2308                 || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
2309                 goto end;
2310             SSL_SESSION_free(sess2);
2311         }
2312         sess2 = tmp;
2313     }
2314 
2315     new_called = remove_called = get_called = 0;
2316     get_sess_val = sess2;
2317     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2318             &clientssl2, NULL, NULL))
2319         || !TEST_true(SSL_set_session(clientssl2, sess1))
2320         || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2321             SSL_ERROR_NONE))
2322         || !TEST_true(SSL_session_reused(clientssl2)))
2323         goto end;
2324 
2325     if (use_ext_cache) {
2326         if (!TEST_int_eq(remove_called, 0))
2327             goto end;
2328 
2329         if (maxprot == TLS1_3_VERSION) {
2330             if (!TEST_int_eq(new_called, 1)
2331                 || !TEST_int_eq(get_called, 0))
2332                 goto end;
2333         } else {
2334             if (!TEST_int_eq(new_called, 0)
2335                 || !TEST_int_eq(get_called, 1))
2336                 goto end;
2337         }
2338     }
2339     /*
2340      * Make a small cache, force out all other sessions but
2341      * sess2, try to add sess1, which should succeed. Then
2342      * make sure it's there by checking the owners. Despite
2343      * the timeouts, sess1 should have kicked out sess2
2344      */
2345 
2346     /* Make sess1 expire before sess2 */
2347     if (!TEST_time_t_gt(SSL_SESSION_set_time_ex(sess1, 1000), 0)
2348         || !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0)
2349         || !TEST_time_t_gt(SSL_SESSION_set_time_ex(sess2, 2000), 0)
2350         || !TEST_long_gt(SSL_SESSION_set_timeout(sess2, 2000), 0))
2351         goto end;
2352 
2353     if (!TEST_long_ne(SSL_CTX_sess_set_cache_size(sctx, 1), 0))
2354         goto end;
2355 
2356     /* Don't care about results - cache should only be sess2 at end */
2357     SSL_CTX_add_session(sctx, sess1);
2358     SSL_CTX_add_session(sctx, sess2);
2359 
2360     /* Now add sess1, and make sure it remains, despite timeout */
2361     if (!TEST_true(SSL_CTX_add_session(sctx, sess1))
2362         || !TEST_ptr(sess1->owner)
2363         || !TEST_ptr_null(sess2->owner))
2364         goto end;
2365 
2366     testresult = 1;
2367 
2368 end:
2369     SSL_free(serverssl1);
2370     SSL_free(clientssl1);
2371     SSL_free(serverssl2);
2372     SSL_free(clientssl2);
2373 #ifndef OPENSSL_NO_TLS1_1
2374     SSL_free(serverssl3);
2375     SSL_free(clientssl3);
2376 #endif
2377     SSL_SESSION_free(sess1);
2378     SSL_SESSION_free(sess2);
2379     SSL_CTX_free(sctx);
2380     SSL_CTX_free(cctx);
2381 
2382     return testresult;
2383 }
2384 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
2385 
test_session_with_only_int_cache(void)2386 static int test_session_with_only_int_cache(void)
2387 {
2388 #ifndef OSSL_NO_USABLE_TLS1_3
2389     if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0))
2390         return 0;
2391 #endif
2392 
2393 #ifndef OPENSSL_NO_TLS1_2
2394     return execute_test_session(TLS1_2_VERSION, 1, 0, 0);
2395 #else
2396     return 1;
2397 #endif
2398 }
2399 
test_session_with_only_ext_cache(void)2400 static int test_session_with_only_ext_cache(void)
2401 {
2402 #ifndef OSSL_NO_USABLE_TLS1_3
2403     if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0))
2404         return 0;
2405 #endif
2406 
2407 #ifndef OPENSSL_NO_TLS1_2
2408     return execute_test_session(TLS1_2_VERSION, 0, 1, 0);
2409 #else
2410     return 1;
2411 #endif
2412 }
2413 
test_session_with_both_cache(void)2414 static int test_session_with_both_cache(void)
2415 {
2416 #ifndef OSSL_NO_USABLE_TLS1_3
2417     if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0))
2418         return 0;
2419 #endif
2420 
2421 #ifndef OPENSSL_NO_TLS1_2
2422     return execute_test_session(TLS1_2_VERSION, 1, 1, 0);
2423 #else
2424     return 1;
2425 #endif
2426 }
2427 
test_session_wo_ca_names(void)2428 static int test_session_wo_ca_names(void)
2429 {
2430 #ifndef OSSL_NO_USABLE_TLS1_3
2431     if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES))
2432         return 0;
2433 #endif
2434 
2435 #ifndef OPENSSL_NO_TLS1_2
2436     return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
2437 #else
2438     return 1;
2439 #endif
2440 }
2441 
2442 #ifndef OSSL_NO_USABLE_TLS1_3
2443 static SSL_SESSION *sesscache[6];
2444 static int do_cache;
2445 
new_cachesession_cb(SSL * ssl,SSL_SESSION * sess)2446 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
2447 {
2448     if (do_cache) {
2449         sesscache[new_called] = sess;
2450     } else {
2451         /* We don't need the reference to the session, so free it */
2452         SSL_SESSION_free(sess);
2453     }
2454     new_called++;
2455 
2456     return 1;
2457 }
2458 
post_handshake_verify(SSL * sssl,SSL * cssl)2459 static int post_handshake_verify(SSL *sssl, SSL *cssl)
2460 {
2461     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
2462     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
2463         return 0;
2464 
2465     /* Start handshake on the server and client */
2466     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
2467         || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
2468         || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
2469         || !TEST_true(create_ssl_connection(sssl, cssl,
2470             SSL_ERROR_NONE)))
2471         return 0;
2472 
2473     return 1;
2474 }
2475 
setup_ticket_test(int stateful,int idx,SSL_CTX ** sctx,SSL_CTX ** cctx)2476 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
2477     SSL_CTX **cctx)
2478 {
2479     int sess_id_ctx = 1;
2480 
2481     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2482             TLS_client_method(), TLS1_VERSION, 0,
2483             sctx, cctx, cert, privkey))
2484         || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
2485         || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
2486             (void *)&sess_id_ctx,
2487             sizeof(sess_id_ctx))))
2488         return 0;
2489 
2490     if (stateful)
2491         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
2492 
2493     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2494     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
2495 
2496     return 1;
2497 }
2498 
check_resumption(int idx,SSL_CTX * sctx,SSL_CTX * cctx,int succ)2499 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
2500 {
2501     SSL *serverssl = NULL, *clientssl = NULL;
2502     int i;
2503 
2504     /* Test that we can resume with all the tickets we got given */
2505     for (i = 0; i < idx * 2; i++) {
2506         new_called = 0;
2507         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2508                 &clientssl, NULL, NULL))
2509             || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
2510             goto end;
2511 
2512         SSL_set_post_handshake_auth(clientssl, 1);
2513 
2514         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2515                 SSL_ERROR_NONE)))
2516             goto end;
2517 
2518         /*
2519          * Following a successful resumption we only get 1 ticket. After a
2520          * failed one we should get idx tickets.
2521          */
2522         if (succ) {
2523             if (!TEST_true(SSL_session_reused(clientssl))
2524                 || !TEST_int_eq(new_called, 1))
2525                 goto end;
2526         } else {
2527             if (!TEST_false(SSL_session_reused(clientssl))
2528                 || !TEST_int_eq(new_called, idx))
2529                 goto end;
2530         }
2531 
2532         new_called = 0;
2533         /* After a post-handshake authentication we should get 1 new ticket */
2534         if (succ
2535             && (!post_handshake_verify(serverssl, clientssl)
2536                 || !TEST_int_eq(new_called, 1)))
2537             goto end;
2538 
2539         SSL_shutdown(clientssl);
2540         SSL_shutdown(serverssl);
2541         SSL_free(serverssl);
2542         SSL_free(clientssl);
2543         serverssl = clientssl = NULL;
2544         SSL_SESSION_free(sesscache[i]);
2545         sesscache[i] = NULL;
2546     }
2547 
2548     return 1;
2549 
2550 end:
2551     SSL_free(clientssl);
2552     SSL_free(serverssl);
2553     return 0;
2554 }
2555 
test_tickets(int stateful,int idx)2556 static int test_tickets(int stateful, int idx)
2557 {
2558     SSL_CTX *sctx = NULL, *cctx = NULL;
2559     SSL *serverssl = NULL, *clientssl = NULL;
2560     int testresult = 0;
2561     size_t j;
2562 
2563     /* idx is the test number, but also the number of tickets we want */
2564 
2565     new_called = 0;
2566     do_cache = 1;
2567 
2568     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2569         goto end;
2570 
2571     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2572             &clientssl, NULL, NULL)))
2573         goto end;
2574 
2575     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2576             SSL_ERROR_NONE))
2577         /* Check we got the number of tickets we were expecting */
2578         || !TEST_int_eq(idx, new_called))
2579         goto end;
2580 
2581     SSL_shutdown(clientssl);
2582     SSL_shutdown(serverssl);
2583     SSL_free(serverssl);
2584     SSL_free(clientssl);
2585     SSL_CTX_free(sctx);
2586     SSL_CTX_free(cctx);
2587     clientssl = serverssl = NULL;
2588     sctx = cctx = NULL;
2589 
2590     /*
2591      * Now we try to resume with the tickets we previously created. The
2592      * resumption attempt is expected to fail (because we're now using a new
2593      * SSL_CTX). We should see idx number of tickets issued again.
2594      */
2595 
2596     /* Stop caching sessions - just count them */
2597     do_cache = 0;
2598 
2599     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2600         goto end;
2601 
2602     if (!check_resumption(idx, sctx, cctx, 0))
2603         goto end;
2604 
2605     /* Start again with caching sessions */
2606     new_called = 0;
2607     do_cache = 1;
2608     SSL_CTX_free(sctx);
2609     SSL_CTX_free(cctx);
2610     sctx = cctx = NULL;
2611 
2612     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2613         goto end;
2614 
2615     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2616             &clientssl, NULL, NULL)))
2617         goto end;
2618 
2619     SSL_set_post_handshake_auth(clientssl, 1);
2620 
2621     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2622             SSL_ERROR_NONE))
2623         /* Check we got the number of tickets we were expecting */
2624         || !TEST_int_eq(idx, new_called))
2625         goto end;
2626 
2627     /* After a post-handshake authentication we should get new tickets issued */
2628     if (!post_handshake_verify(serverssl, clientssl)
2629         || !TEST_int_eq(idx * 2, new_called))
2630         goto end;
2631 
2632     SSL_shutdown(clientssl);
2633     SSL_shutdown(serverssl);
2634     SSL_free(serverssl);
2635     SSL_free(clientssl);
2636     serverssl = clientssl = NULL;
2637 
2638     /* Stop caching sessions - just count them */
2639     do_cache = 0;
2640 
2641     /*
2642      * Check we can resume with all the tickets we created. This time around the
2643      * resumptions should all be successful.
2644      */
2645     if (!check_resumption(idx, sctx, cctx, 1))
2646         goto end;
2647 
2648     testresult = 1;
2649 
2650 end:
2651     SSL_free(serverssl);
2652     SSL_free(clientssl);
2653     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2654         SSL_SESSION_free(sesscache[j]);
2655         sesscache[j] = NULL;
2656     }
2657     SSL_CTX_free(sctx);
2658     SSL_CTX_free(cctx);
2659 
2660     return testresult;
2661 }
2662 
test_stateless_tickets(int idx)2663 static int test_stateless_tickets(int idx)
2664 {
2665     return test_tickets(0, idx);
2666 }
2667 
test_stateful_tickets(int idx)2668 static int test_stateful_tickets(int idx)
2669 {
2670     return test_tickets(1, idx);
2671 }
2672 
test_psk_tickets(void)2673 static int test_psk_tickets(void)
2674 {
2675     SSL_CTX *sctx = NULL, *cctx = NULL;
2676     SSL *serverssl = NULL, *clientssl = NULL;
2677     int testresult = 0;
2678     int sess_id_ctx = 1;
2679 
2680     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2681             TLS_client_method(), TLS1_VERSION, 0,
2682             &sctx, &cctx, NULL, NULL))
2683         || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2684             (void *)&sess_id_ctx,
2685             sizeof(sess_id_ctx))))
2686         goto end;
2687 
2688     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2689     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2690     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2691     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2692     use_session_cb_cnt = 0;
2693     find_session_cb_cnt = 0;
2694     srvid = pskid;
2695     new_called = 0;
2696 
2697     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2698             NULL, NULL)))
2699         goto end;
2700     clientpsk = serverpsk = create_a_psk(clientssl, SHA384_DIGEST_LENGTH);
2701     if (!TEST_ptr(clientpsk) || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
2702         goto end;
2703 
2704     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2705             SSL_ERROR_NONE))
2706         || !TEST_int_eq(1, find_session_cb_cnt)
2707         || !TEST_int_eq(1, use_session_cb_cnt)
2708         /* We should always get 1 ticket when using external PSK */
2709         || !TEST_int_eq(1, new_called))
2710         goto end;
2711 
2712     testresult = 1;
2713 
2714 end:
2715     SSL_free(serverssl);
2716     SSL_free(clientssl);
2717     SSL_CTX_free(sctx);
2718     SSL_CTX_free(cctx);
2719     SSL_SESSION_free(clientpsk);
2720     SSL_SESSION_free(serverpsk);
2721     clientpsk = serverpsk = NULL;
2722 
2723     return testresult;
2724 }
2725 
test_extra_tickets(int idx)2726 static int test_extra_tickets(int idx)
2727 {
2728     SSL_CTX *sctx = NULL, *cctx = NULL;
2729     SSL *serverssl = NULL, *clientssl = NULL;
2730     BIO *bretry = BIO_new(bio_s_always_retry());
2731     BIO *tmp = NULL;
2732     int testresult = 0;
2733     int stateful = 0;
2734     size_t nbytes;
2735     unsigned char c, buf[1];
2736 
2737     new_called = 0;
2738     do_cache = 1;
2739 
2740     if (idx >= 3) {
2741         idx -= 3;
2742         stateful = 1;
2743     }
2744 
2745     if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2746         goto end;
2747     SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2748     /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2749     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2750 
2751     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2752             &clientssl, NULL, NULL)))
2753         goto end;
2754 
2755     /*
2756      * Note that we have new_session_cb on both sctx and cctx, so new_called is
2757      * incremented by both client and server.
2758      */
2759     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2760             SSL_ERROR_NONE))
2761         /* Check we got the number of tickets we were expecting */
2762         || !TEST_int_eq(idx * 2, new_called)
2763         || !TEST_true(SSL_new_session_ticket(serverssl))
2764         || !TEST_true(SSL_new_session_ticket(serverssl))
2765         || !TEST_int_eq(idx * 2, new_called))
2766         goto end;
2767 
2768     /* Now try a (real) write to actually send the tickets */
2769     c = '1';
2770     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2771         || !TEST_size_t_eq(1, nbytes)
2772         || !TEST_int_eq(idx * 2 + 2, new_called)
2773         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2774         || !TEST_int_eq(idx * 2 + 4, new_called)
2775         || !TEST_int_eq(sizeof(buf), nbytes)
2776         || !TEST_int_eq(c, buf[0])
2777         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2778         goto end;
2779 
2780     /* Try with only requesting one new ticket, too */
2781     c = '2';
2782     new_called = 0;
2783     if (!TEST_true(SSL_new_session_ticket(serverssl))
2784         || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2785         || !TEST_size_t_eq(sizeof(c), nbytes)
2786         || !TEST_int_eq(1, new_called)
2787         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2788         || !TEST_int_eq(2, new_called)
2789         || !TEST_size_t_eq(sizeof(buf), nbytes)
2790         || !TEST_int_eq(c, buf[0]))
2791         goto end;
2792 
2793     /* Do it again but use dummy writes to drive the ticket generation */
2794     c = '3';
2795     new_called = 0;
2796     if (!TEST_true(SSL_new_session_ticket(serverssl))
2797         || !TEST_true(SSL_new_session_ticket(serverssl))
2798         || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2799         || !TEST_size_t_eq(0, nbytes)
2800         || !TEST_int_eq(2, new_called)
2801         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2802         || !TEST_int_eq(4, new_called))
2803         goto end;
2804 
2805     /* Once more, but with SSL_do_handshake() to drive the ticket generation */
2806     c = '4';
2807     new_called = 0;
2808     if (!TEST_true(SSL_new_session_ticket(serverssl))
2809         || !TEST_true(SSL_new_session_ticket(serverssl))
2810         || !TEST_true(SSL_do_handshake(serverssl))
2811         || !TEST_int_eq(2, new_called)
2812         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2813         || !TEST_int_eq(4, new_called))
2814         goto end;
2815 
2816     /*
2817      * Use the always-retry BIO to exercise the logic that forces ticket
2818      * generation to wait until a record boundary.
2819      */
2820     c = '5';
2821     new_called = 0;
2822     tmp = SSL_get_wbio(serverssl);
2823     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2824         tmp = NULL;
2825         goto end;
2826     }
2827     SSL_set0_wbio(serverssl, bretry);
2828     bretry = NULL;
2829     if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2830         || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2831         || !TEST_size_t_eq(nbytes, 0))
2832         goto end;
2833     /* Restore a BIO that will let the write succeed */
2834     SSL_set0_wbio(serverssl, tmp);
2835     tmp = NULL;
2836     /*
2837      * These calls should just queue the request and not send anything
2838      * even if we explicitly try to hit the state machine.
2839      */
2840     if (!TEST_true(SSL_new_session_ticket(serverssl))
2841         || !TEST_true(SSL_new_session_ticket(serverssl))
2842         || !TEST_int_eq(0, new_called)
2843         || !TEST_true(SSL_do_handshake(serverssl))
2844         || !TEST_int_eq(0, new_called))
2845         goto end;
2846     /* Re-do the write; still no tickets sent */
2847     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2848         || !TEST_size_t_eq(1, nbytes)
2849         || !TEST_int_eq(0, new_called)
2850         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2851         || !TEST_int_eq(0, new_called)
2852         || !TEST_int_eq(sizeof(buf), nbytes)
2853         || !TEST_int_eq(c, buf[0])
2854         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2855         goto end;
2856     /* Even trying to hit the state machine now will still not send tickets */
2857     if (!TEST_true(SSL_do_handshake(serverssl))
2858         || !TEST_int_eq(0, new_called))
2859         goto end;
2860     /* Now the *next* write should send the tickets */
2861     c = '6';
2862     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2863         || !TEST_size_t_eq(1, nbytes)
2864         || !TEST_int_eq(2, new_called)
2865         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2866         || !TEST_int_eq(4, new_called)
2867         || !TEST_int_eq(sizeof(buf), nbytes)
2868         || !TEST_int_eq(c, buf[0])
2869         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2870         goto end;
2871 
2872     SSL_shutdown(clientssl);
2873     SSL_shutdown(serverssl);
2874     testresult = 1;
2875 
2876 end:
2877     BIO_free(bretry);
2878     BIO_free(tmp);
2879     SSL_free(serverssl);
2880     SSL_free(clientssl);
2881     SSL_CTX_free(sctx);
2882     SSL_CTX_free(cctx);
2883     clientssl = serverssl = NULL;
2884     sctx = cctx = NULL;
2885     return testresult;
2886 }
2887 #endif
2888 
2889 #define USE_NULL 0
2890 #define USE_BIO_1 1
2891 #define USE_BIO_2 2
2892 #define USE_DEFAULT 3
2893 
2894 #define CONNTYPE_CONNECTION_SUCCESS 0
2895 #define CONNTYPE_CONNECTION_FAIL 1
2896 #define CONNTYPE_NO_CONNECTION 2
2897 
2898 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS (3 * 3 * 3 * 3)
2899 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS (2 * 2)
2900 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2901 #define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS (2 * 2)
2902 #else
2903 #define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS 0
2904 #endif
2905 
2906 #define TOTAL_SSL_SET_BIO_TESTS           \
2907     TOTAL_NO_CONN_SSL_SET_BIO_TESTS       \
2908     +TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2909         + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2910 
setupbio(BIO ** res,BIO * bio1,BIO * bio2,int type)2911 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2912 {
2913     switch (type) {
2914     case USE_NULL:
2915         *res = NULL;
2916         break;
2917     case USE_BIO_1:
2918         *res = bio1;
2919         break;
2920     case USE_BIO_2:
2921         *res = bio2;
2922         break;
2923     }
2924 }
2925 
2926 /*
2927  * Tests calls to SSL_set_bio() under various conditions.
2928  *
2929  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2930  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2931  * then do more tests where we create a successful connection first using our
2932  * standard connection setup functions, and then call SSL_set_bio() with
2933  * various combinations of valid BIOs or NULL. We then repeat these tests
2934  * following a failed connection. In this last case we are looking to check that
2935  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2936  */
test_ssl_set_bio(int idx)2937 static int test_ssl_set_bio(int idx)
2938 {
2939     SSL_CTX *sctx = NULL, *cctx = NULL;
2940     BIO *bio1 = NULL;
2941     BIO *bio2 = NULL;
2942     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2943     SSL *serverssl = NULL, *clientssl = NULL;
2944     int initrbio, initwbio, newrbio, newwbio, conntype;
2945     int testresult = 0;
2946 
2947     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2948         initrbio = idx % 3;
2949         idx /= 3;
2950         initwbio = idx % 3;
2951         idx /= 3;
2952         newrbio = idx % 3;
2953         idx /= 3;
2954         newwbio = idx % 3;
2955         conntype = CONNTYPE_NO_CONNECTION;
2956     } else {
2957         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2958         initrbio = initwbio = USE_DEFAULT;
2959         newrbio = idx % 2;
2960         idx /= 2;
2961         newwbio = idx % 2;
2962         idx /= 2;
2963         conntype = idx % 2;
2964     }
2965 
2966     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2967             TLS_client_method(), TLS1_VERSION, 0,
2968             &sctx, &cctx, cert, privkey)))
2969         goto end;
2970 
2971     if (conntype == CONNTYPE_CONNECTION_FAIL) {
2972         /*
2973          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2974          * because we reduced the number of tests in the definition of
2975          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2976          * mismatched protocol versions we will force a connection failure.
2977          */
2978         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2979         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2980     }
2981 
2982     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2983             NULL, NULL)))
2984         goto end;
2985 
2986     if (initrbio == USE_BIO_1
2987         || initwbio == USE_BIO_1
2988         || newrbio == USE_BIO_1
2989         || newwbio == USE_BIO_1) {
2990         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2991             goto end;
2992     }
2993 
2994     if (initrbio == USE_BIO_2
2995         || initwbio == USE_BIO_2
2996         || newrbio == USE_BIO_2
2997         || newwbio == USE_BIO_2) {
2998         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
2999             goto end;
3000     }
3001 
3002     if (initrbio != USE_DEFAULT) {
3003         setupbio(&irbio, bio1, bio2, initrbio);
3004         setupbio(&iwbio, bio1, bio2, initwbio);
3005         SSL_set_bio(clientssl, irbio, iwbio);
3006 
3007         /*
3008          * We want to maintain our own refs to these BIO, so do an up ref for
3009          * each BIO that will have ownership transferred in the SSL_set_bio()
3010          * call
3011          */
3012         if (irbio != NULL && !BIO_up_ref(irbio))
3013             goto end;
3014         if (iwbio != NULL && iwbio != irbio && !BIO_up_ref(iwbio)) {
3015             BIO_free(irbio);
3016             goto end;
3017         }
3018     }
3019 
3020     if (conntype != CONNTYPE_NO_CONNECTION
3021         && !TEST_true(create_ssl_connection(serverssl, clientssl,
3022                           SSL_ERROR_NONE)
3023             == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
3024         goto end;
3025 
3026     setupbio(&nrbio, bio1, bio2, newrbio);
3027     setupbio(&nwbio, bio1, bio2, newwbio);
3028 
3029     /*
3030      * We will (maybe) transfer ownership again so do more up refs.
3031      * SSL_set_bio() has some really complicated ownership rules where BIOs have
3032      * already been set!
3033      */
3034     if (nrbio != NULL
3035         && nrbio != irbio
3036         && (nwbio != iwbio || nrbio != nwbio))
3037         if (!TEST_true(BIO_up_ref(nrbio)))
3038             goto end;
3039     if (nwbio != NULL
3040         && nwbio != nrbio
3041         && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
3042         if (!TEST_true(BIO_up_ref(nwbio))) {
3043             if (nrbio != irbio
3044                 && (nwbio != iwbio || nrbio != nwbio))
3045                 BIO_free(nrbio);
3046             goto end;
3047         }
3048 
3049     SSL_set_bio(clientssl, nrbio, nwbio);
3050 
3051     testresult = 1;
3052 
3053 end:
3054     BIO_free(bio1);
3055     BIO_free(bio2);
3056 
3057     /*
3058      * This test is checking that the ref counting for SSL_set_bio is correct.
3059      * If we get here and we did too many frees then we will fail in the above
3060      * functions.
3061      */
3062     SSL_free(serverssl);
3063     SSL_free(clientssl);
3064     SSL_CTX_free(sctx);
3065     SSL_CTX_free(cctx);
3066     return testresult;
3067 }
3068 
3069 typedef enum { NO_BIO_CHANGE,
3070     CHANGE_RBIO,
3071     CHANGE_WBIO } bio_change_t;
3072 
execute_test_ssl_bio(int pop_ssl,bio_change_t change_bio)3073 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
3074 {
3075     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
3076     SSL_CTX *ctx;
3077     SSL *ssl = NULL;
3078     int testresult = 0;
3079 
3080     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
3081         || !TEST_ptr(ssl = SSL_new(ctx))
3082         || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
3083         || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
3084         goto end;
3085 
3086     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
3087 
3088     /*
3089      * If anything goes wrong here then we could leak memory.
3090      */
3091     BIO_push(sslbio, membio1);
3092 
3093     /* Verify changing the rbio/wbio directly does not cause leaks */
3094     if (change_bio != NO_BIO_CHANGE) {
3095         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
3096             ssl = NULL;
3097             goto end;
3098         }
3099         if (change_bio == CHANGE_RBIO)
3100             SSL_set0_rbio(ssl, membio2);
3101         else
3102             SSL_set0_wbio(ssl, membio2);
3103     }
3104     ssl = NULL;
3105 
3106     if (pop_ssl)
3107         BIO_pop(sslbio);
3108     else
3109         BIO_pop(membio1);
3110 
3111     testresult = 1;
3112 end:
3113     BIO_free(membio1);
3114     BIO_free(sslbio);
3115     SSL_free(ssl);
3116     SSL_CTX_free(ctx);
3117 
3118     return testresult;
3119 }
3120 
test_ssl_bio_pop_next_bio(void)3121 static int test_ssl_bio_pop_next_bio(void)
3122 {
3123     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
3124 }
3125 
test_ssl_bio_pop_ssl_bio(void)3126 static int test_ssl_bio_pop_ssl_bio(void)
3127 {
3128     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
3129 }
3130 
test_ssl_bio_change_rbio(void)3131 static int test_ssl_bio_change_rbio(void)
3132 {
3133     return execute_test_ssl_bio(0, CHANGE_RBIO);
3134 }
3135 
test_ssl_bio_change_wbio(void)3136 static int test_ssl_bio_change_wbio(void)
3137 {
3138     return execute_test_ssl_bio(0, CHANGE_WBIO);
3139 }
3140 
3141 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
3142 typedef struct {
3143     /* The list of sig algs */
3144     const int *list;
3145     /* The length of the list */
3146     size_t listlen;
3147     /* A sigalgs list in string format */
3148     const char *liststr;
3149     /* Whether setting the list should succeed */
3150     int valid;
3151     /* Whether creating a connection with the list should succeed */
3152     int connsuccess;
3153 } sigalgs_list;
3154 
3155 static const int validlist1[] = { NID_sha256, EVP_PKEY_RSA };
3156 #ifndef OPENSSL_NO_EC
3157 static const int validlist2[] = { NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC };
3158 static const int validlist3[] = { NID_sha512, EVP_PKEY_EC };
3159 #endif
3160 static const int invalidlist1[] = { NID_undef, EVP_PKEY_RSA };
3161 static const int invalidlist2[] = { NID_sha256, NID_undef };
3162 static const int invalidlist3[] = { NID_sha256, EVP_PKEY_RSA, NID_sha256 };
3163 static const int invalidlist4[] = { NID_sha256 };
3164 static const sigalgs_list testsigalgs[] = {
3165     { validlist1, OSSL_NELEM(validlist1), NULL, 1, 1 },
3166 #ifndef OPENSSL_NO_EC
3167     { validlist2, OSSL_NELEM(validlist2), NULL, 1, 1 },
3168     { validlist3, OSSL_NELEM(validlist3), NULL, 1, 0 },
3169 #endif
3170     { NULL, 0, "RSA+SHA256", 1, 1 },
3171     { NULL, 0, "RSA+SHA256:?Invalid", 1, 1 },
3172 #ifndef OPENSSL_NO_EC
3173     { NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1 },
3174     { NULL, 0, "ECDSA+SHA512", 1, 0 },
3175 #endif
3176     { invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0 },
3177     { invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0 },
3178     { invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0 },
3179     { invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0 },
3180     { NULL, 0, "RSA", 0, 0 },
3181     { NULL, 0, "SHA256", 0, 0 },
3182     { NULL, 0, "RSA+SHA256:SHA256", 0, 0 },
3183     { NULL, 0, "Invalid", 0, 0 }
3184 };
3185 
test_set_sigalgs(int idx)3186 static int test_set_sigalgs(int idx)
3187 {
3188     SSL_CTX *cctx = NULL, *sctx = NULL;
3189     SSL *clientssl = NULL, *serverssl = NULL;
3190     int testresult = 0;
3191     const sigalgs_list *curr;
3192     int testctx;
3193 
3194     /* Should never happen */
3195     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
3196         return 0;
3197 
3198     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
3199     curr = testctx ? &testsigalgs[idx]
3200                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
3201 
3202     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3203             TLS_client_method(), TLS1_VERSION, 0,
3204             &sctx, &cctx, cert, privkey)))
3205         return 0;
3206 
3207     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
3208 
3209     if (testctx) {
3210         int ret;
3211 
3212         if (curr->list != NULL)
3213             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
3214         else
3215             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
3216 
3217         if (!ret) {
3218             if (curr->valid)
3219                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
3220             else
3221                 testresult = 1;
3222             goto end;
3223         }
3224         if (!curr->valid) {
3225             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
3226             goto end;
3227         }
3228     }
3229 
3230     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3231             &clientssl, NULL, NULL)))
3232         goto end;
3233 
3234     if (!testctx) {
3235         int ret;
3236 
3237         if (curr->list != NULL)
3238             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
3239         else
3240             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
3241         if (!ret) {
3242             if (curr->valid)
3243                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
3244             else
3245                 testresult = 1;
3246             goto end;
3247         }
3248         if (!curr->valid)
3249             goto end;
3250     }
3251 
3252     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
3253                          SSL_ERROR_NONE),
3254             curr->connsuccess))
3255         goto end;
3256 
3257     testresult = 1;
3258 
3259 end:
3260     SSL_free(serverssl);
3261     SSL_free(clientssl);
3262     SSL_CTX_free(sctx);
3263     SSL_CTX_free(cctx);
3264 
3265     return testresult;
3266 }
3267 #endif
3268 
3269 #ifndef OSSL_NO_USABLE_TLS1_3
3270 static int psk_client_cb_cnt = 0;
3271 static int psk_server_cb_cnt = 0;
3272 
use_session_cb(SSL * ssl,const EVP_MD * md,const unsigned char ** id,size_t * idlen,SSL_SESSION ** sess)3273 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
3274     size_t *idlen, SSL_SESSION **sess)
3275 {
3276     switch (++use_session_cb_cnt) {
3277     case 1:
3278         /* The first call should always have a NULL md */
3279         if (md != NULL)
3280             return 0;
3281         break;
3282 
3283     case 2:
3284         /* The second call should always have an md */
3285         if (md == NULL)
3286             return 0;
3287         break;
3288 
3289     default:
3290         /* We should only be called a maximum of twice */
3291         return 0;
3292     }
3293 
3294     if (clientpsk != NULL && !SSL_SESSION_up_ref(clientpsk))
3295         return 0;
3296 
3297     *sess = clientpsk;
3298     *id = (const unsigned char *)pskid;
3299     *idlen = strlen(pskid);
3300 
3301     return 1;
3302 }
3303 
3304 #ifndef OPENSSL_NO_PSK
psk_client_cb(SSL * ssl,const char * hint,char * id,unsigned int max_id_len,unsigned char * psk,unsigned int max_psk_len)3305 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
3306     unsigned int max_id_len,
3307     unsigned char *psk,
3308     unsigned int max_psk_len)
3309 {
3310     unsigned int psklen = 0;
3311 
3312     psk_client_cb_cnt++;
3313 
3314     if (strlen(pskid) + 1 > max_id_len)
3315         return 0;
3316 
3317     /* We should only ever be called a maximum of twice per connection */
3318     if (psk_client_cb_cnt > 2)
3319         return 0;
3320 
3321     if (clientpsk == NULL)
3322         return 0;
3323 
3324     /* We'll reuse the PSK we set up for TLSv1.3 */
3325     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
3326         return 0;
3327     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
3328     strncpy(id, pskid, max_id_len);
3329 
3330     return psklen;
3331 }
3332 #endif /* OPENSSL_NO_PSK */
3333 
find_session_cb(SSL * ssl,const unsigned char * identity,size_t identity_len,SSL_SESSION ** sess)3334 static int find_session_cb(SSL *ssl, const unsigned char *identity,
3335     size_t identity_len, SSL_SESSION **sess)
3336 {
3337     find_session_cb_cnt++;
3338 
3339     /* We should only ever be called a maximum of twice per connection */
3340     if (find_session_cb_cnt > 2)
3341         return 0;
3342 
3343     if (serverpsk == NULL)
3344         return 0;
3345 
3346     /* Identity should match that set by the client */
3347     if (strlen(srvid) != identity_len
3348         || strncmp(srvid, (const char *)identity, identity_len) != 0) {
3349         /* No PSK found, continue but without a PSK */
3350         *sess = NULL;
3351         return 1;
3352     }
3353 
3354     if (!SSL_SESSION_up_ref(serverpsk))
3355         return 0;
3356 
3357     *sess = serverpsk;
3358 
3359     return 1;
3360 }
3361 
3362 #ifndef OPENSSL_NO_PSK
psk_server_cb(SSL * ssl,const char * identity,unsigned char * psk,unsigned int max_psk_len)3363 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
3364     unsigned char *psk, unsigned int max_psk_len)
3365 {
3366     unsigned int psklen = 0;
3367 
3368     psk_server_cb_cnt++;
3369 
3370     /* We should only ever be called a maximum of twice per connection */
3371     if (find_session_cb_cnt > 2)
3372         return 0;
3373 
3374     if (serverpsk == NULL)
3375         return 0;
3376 
3377     /* Identity should match that set by the client */
3378     if (strcmp(srvid, identity) != 0) {
3379         return 0;
3380     }
3381 
3382     /* We'll reuse the PSK we set up for TLSv1.3 */
3383     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
3384         return 0;
3385     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
3386 
3387     return psklen;
3388 }
3389 #endif /* OPENSSL_NO_PSK */
3390 
3391 #define MSG1 "Hello"
3392 #define MSG2 "World."
3393 #define MSG3 "This"
3394 #define MSG4 "is"
3395 #define MSG5 "a"
3396 #define MSG6 "test"
3397 #define MSG7 "message."
3398 
3399 static int artificial_ticket_time = 0;
3400 
sub_session_time(SSL_SESSION * sess)3401 static int sub_session_time(SSL_SESSION *sess)
3402 {
3403     OSSL_TIME tick_time;
3404 
3405     tick_time = ossl_time_from_time_t(SSL_SESSION_get_time_ex(sess));
3406     tick_time = ossl_time_subtract(tick_time, ossl_seconds2time(10));
3407 
3408     return SSL_SESSION_set_time_ex(sess, ossl_time_to_time_t(tick_time)) != 0;
3409 }
3410 
ed_gen_cb(SSL * s,void * arg)3411 static int ed_gen_cb(SSL *s, void *arg)
3412 {
3413     SSL_SESSION *sess = SSL_get0_session(s);
3414 
3415     if (sess == NULL)
3416         return 0;
3417 
3418     /*
3419      * Artificially give the ticket some age. Just do it for the number of
3420      * tickets we've been told to do.
3421      */
3422     if (artificial_ticket_time == 0)
3423         return 1;
3424     artificial_ticket_time--;
3425 
3426     return sub_session_time(sess);
3427 }
3428 
3429 /*
3430  * Helper method to setup objects for early data test. Caller frees objects on
3431  * error.
3432  */
setupearly_data_test(SSL_CTX ** cctx,SSL_CTX ** sctx,SSL ** clientssl,SSL ** serverssl,SSL_SESSION ** sess,int idx,size_t mdsize)3433 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
3434     SSL **serverssl, SSL_SESSION **sess, int idx,
3435     size_t mdsize)
3436 {
3437     int artificial = (artificial_ticket_time > 0);
3438 
3439     if (*sctx == NULL
3440         && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3441             TLS_client_method(),
3442             TLS1_VERSION, 0,
3443             sctx, cctx, cert, privkey)))
3444         return 0;
3445 
3446     if (artificial)
3447         SSL_CTX_set_session_ticket_cb(*sctx, ed_gen_cb, NULL, NULL);
3448 
3449     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
3450         return 0;
3451 
3452     if (idx == 1) {
3453         /* When idx == 1 we repeat the tests with read_ahead set */
3454         SSL_CTX_set_read_ahead(*cctx, 1);
3455         SSL_CTX_set_read_ahead(*sctx, 1);
3456     } else if (idx == 2) {
3457         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
3458         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
3459         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
3460         use_session_cb_cnt = 0;
3461         find_session_cb_cnt = 0;
3462         srvid = pskid;
3463     }
3464 
3465     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
3466             NULL, NULL)))
3467         return 0;
3468 
3469     /*
3470      * For one of the run throughs (doesn't matter which one), we'll try sending
3471      * some SNI data in the initial ClientHello. This will be ignored (because
3472      * there is no SNI cb set up by the server), so it should not impact
3473      * early_data.
3474      */
3475     if (idx == 1
3476         && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
3477         return 0;
3478 
3479     if (idx == 2) {
3480         clientpsk = create_a_psk(*clientssl, mdsize);
3481         if (!TEST_ptr(clientpsk)
3482             /*
3483              * We just choose an arbitrary value for max_early_data which
3484              * should be big enough for testing purposes.
3485              */
3486             || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
3487                 0x100))
3488             || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3489             SSL_SESSION_free(clientpsk);
3490             clientpsk = NULL;
3491             return 0;
3492         }
3493         serverpsk = clientpsk;
3494 
3495         if (sess != NULL) {
3496             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3497                 SSL_SESSION_free(clientpsk);
3498                 SSL_SESSION_free(serverpsk);
3499                 clientpsk = serverpsk = NULL;
3500                 return 0;
3501             }
3502             *sess = clientpsk;
3503         }
3504         return 1;
3505     }
3506 
3507     if (sess == NULL)
3508         return 1;
3509 
3510     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
3511             SSL_ERROR_NONE)))
3512         return 0;
3513 
3514     *sess = SSL_get1_session(*clientssl);
3515     SSL_shutdown(*clientssl);
3516     SSL_shutdown(*serverssl);
3517     SSL_free(*serverssl);
3518     SSL_free(*clientssl);
3519     *serverssl = *clientssl = NULL;
3520 
3521     /*
3522      * Artificially give the ticket some age to match the artificial age we
3523      * gave it on the server side
3524      */
3525     if (artificial
3526         && !TEST_true(sub_session_time(*sess)))
3527         return 0;
3528 
3529     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
3530             clientssl, NULL, NULL))
3531         || !TEST_true(SSL_set_session(*clientssl, *sess)))
3532         return 0;
3533 
3534     return 1;
3535 }
3536 
check_early_data_timeout(OSSL_TIME timer)3537 static int check_early_data_timeout(OSSL_TIME timer)
3538 {
3539     int res = 0;
3540 
3541     /*
3542      * Early data is time sensitive. We have an approx 8 second allowance
3543      * between writing the early data and reading it. If we exceed that time
3544      * then this test will fail. This can sometimes (rarely) occur in normal CI
3545      * operation. We can try and detect this and just ignore the result of this
3546      * test if it has taken too long. We assume anything over 7 seconds is too
3547      * long
3548      */
3549     timer = ossl_time_subtract(ossl_time_now(), timer);
3550     if (ossl_time_compare(timer, ossl_seconds2time(7)) >= 0)
3551         res = TEST_skip("Test took too long, ignoring result");
3552 
3553     return res;
3554 }
3555 
test_early_data_read_write(int idx)3556 static int test_early_data_read_write(int idx)
3557 {
3558     SSL_CTX *cctx = NULL, *sctx = NULL;
3559     SSL *clientssl = NULL, *serverssl = NULL;
3560     int testresult = 0;
3561     SSL_SESSION *sess = NULL;
3562     unsigned char buf[20], data[1024];
3563     size_t readbytes, written, eoedlen, rawread, rawwritten;
3564     BIO *rbio;
3565     OSSL_TIME timer;
3566 
3567     /* Artificially give the next 2 tickets some age for non PSK sessions */
3568     if (idx != 2)
3569         artificial_ticket_time = 2;
3570     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3571             &serverssl, &sess, idx,
3572             SHA384_DIGEST_LENGTH))) {
3573         artificial_ticket_time = 0;
3574         goto end;
3575     }
3576     artificial_ticket_time = 0;
3577 
3578     /* Write and read some early data */
3579     timer = ossl_time_now();
3580     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3581             &written))
3582         || !TEST_size_t_eq(written, strlen(MSG1)))
3583         goto end;
3584 
3585     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3586                          &readbytes),
3587             SSL_READ_EARLY_DATA_SUCCESS)) {
3588         testresult = check_early_data_timeout(timer);
3589         goto end;
3590     }
3591 
3592     if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
3593         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3594             SSL_EARLY_DATA_ACCEPTED))
3595         goto end;
3596 
3597     /*
3598      * Server should be able to write data, and client should be able to
3599      * read it.
3600      */
3601     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
3602             &written))
3603         || !TEST_size_t_eq(written, strlen(MSG2))
3604         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3605         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3606         goto end;
3607 
3608     /* Even after reading normal data, client should be able write early data */
3609     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
3610             &written))
3611         || !TEST_size_t_eq(written, strlen(MSG3)))
3612         goto end;
3613 
3614     /* Server should still be able read early data after writing data */
3615     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3616                          &readbytes),
3617             SSL_READ_EARLY_DATA_SUCCESS)
3618         || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
3619         goto end;
3620 
3621     /* Write more data from server and read it from client */
3622     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
3623             &written))
3624         || !TEST_size_t_eq(written, strlen(MSG4))
3625         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3626         || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
3627         goto end;
3628 
3629     /*
3630      * If client writes normal data it should mean writing early data is no
3631      * longer possible.
3632      */
3633     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3634         || !TEST_size_t_eq(written, strlen(MSG5))
3635         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3636             SSL_EARLY_DATA_ACCEPTED))
3637         goto end;
3638 
3639     /*
3640      * At this point the client has written EndOfEarlyData, ClientFinished and
3641      * normal (fully protected) data. We are going to cause a delay between the
3642      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
3643      * in the read BIO, and then just put back the EndOfEarlyData message.
3644      */
3645     rbio = SSL_get_rbio(serverssl);
3646     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
3647         || !TEST_size_t_lt(rawread, sizeof(data))
3648         || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
3649         goto end;
3650 
3651     /* Record length is in the 4th and 5th bytes of the record header */
3652     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
3653     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
3654         || !TEST_size_t_eq(rawwritten, eoedlen))
3655         goto end;
3656 
3657     /* Server should be told that there is no more early data */
3658     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3659                          &readbytes),
3660             SSL_READ_EARLY_DATA_FINISH)
3661         || !TEST_size_t_eq(readbytes, 0))
3662         goto end;
3663 
3664     /*
3665      * Server has not finished init yet, so should still be able to write early
3666      * data.
3667      */
3668     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
3669             &written))
3670         || !TEST_size_t_eq(written, strlen(MSG6)))
3671         goto end;
3672 
3673     /* Push the ClientFinished and the normal data back into the server rbio */
3674     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
3675             &rawwritten))
3676         || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
3677         goto end;
3678 
3679     /* Server should be able to read normal data */
3680     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3681         || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3682         goto end;
3683 
3684     /* Client and server should not be able to write/read early data now */
3685     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3686             &written)))
3687         goto end;
3688     ERR_clear_error();
3689     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3690                          &readbytes),
3691             SSL_READ_EARLY_DATA_ERROR))
3692         goto end;
3693     ERR_clear_error();
3694 
3695     /* Client should be able to read the data sent by the server */
3696     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3697         || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
3698         goto end;
3699 
3700     /*
3701      * Make sure we process the two NewSessionTickets. These arrive
3702      * post-handshake. We attempt reads which we do not expect to return any
3703      * data.
3704      */
3705     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3706         || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3707             &readbytes)))
3708         goto end;
3709 
3710     /* Server should be able to write normal data */
3711     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3712         || !TEST_size_t_eq(written, strlen(MSG7))
3713         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3714         || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3715         goto end;
3716 
3717     SSL_SESSION_free(sess);
3718     sess = SSL_get1_session(clientssl);
3719     use_session_cb_cnt = 0;
3720     find_session_cb_cnt = 0;
3721 
3722     SSL_shutdown(clientssl);
3723     SSL_shutdown(serverssl);
3724     SSL_free(serverssl);
3725     SSL_free(clientssl);
3726     serverssl = clientssl = NULL;
3727     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3728             &clientssl, NULL, NULL))
3729         || !TEST_true(SSL_set_session(clientssl, sess)))
3730         goto end;
3731 
3732     /* Write and read some early data */
3733     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3734             &written))
3735         || !TEST_size_t_eq(written, strlen(MSG1))
3736         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3737                             &readbytes),
3738             SSL_READ_EARLY_DATA_SUCCESS)
3739         || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3740         goto end;
3741 
3742     if (!TEST_int_gt(SSL_connect(clientssl), 0)
3743         || !TEST_int_gt(SSL_accept(serverssl), 0))
3744         goto end;
3745 
3746     /* Client and server should not be able to write/read early data now */
3747     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3748             &written)))
3749         goto end;
3750     ERR_clear_error();
3751     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3752                          &readbytes),
3753             SSL_READ_EARLY_DATA_ERROR))
3754         goto end;
3755     ERR_clear_error();
3756 
3757     /* Client and server should be able to write/read normal data */
3758     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3759         || !TEST_size_t_eq(written, strlen(MSG5))
3760         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3761         || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3762         goto end;
3763 
3764     testresult = 1;
3765 
3766 end:
3767     SSL_SESSION_free(sess);
3768     SSL_SESSION_free(clientpsk);
3769     SSL_SESSION_free(serverpsk);
3770     clientpsk = serverpsk = NULL;
3771     SSL_free(serverssl);
3772     SSL_free(clientssl);
3773     SSL_CTX_free(sctx);
3774     SSL_CTX_free(cctx);
3775     return testresult;
3776 }
3777 
3778 static int allow_ed_cb_called = 0;
3779 
allow_early_data_cb(SSL * s,void * arg)3780 static int allow_early_data_cb(SSL *s, void *arg)
3781 {
3782     int *usecb = (int *)arg;
3783 
3784     allow_ed_cb_called++;
3785 
3786     if (*usecb == 1)
3787         return 0;
3788 
3789     return 1;
3790 }
3791 
3792 /*
3793  * idx == 0: Standard early_data setup
3794  * idx == 1: early_data setup using read_ahead
3795  * usecb == 0: Don't use a custom early data callback
3796  * usecb == 1: Use a custom early data callback and reject the early data
3797  * usecb == 2: Use a custom early data callback and accept the early data
3798  * confopt == 0: Configure anti-replay directly
3799  * confopt == 1: Configure anti-replay using SSL_CONF
3800  */
test_early_data_replay_int(int idx,int usecb,int confopt)3801 static int test_early_data_replay_int(int idx, int usecb, int confopt)
3802 {
3803     SSL_CTX *cctx = NULL, *sctx = NULL;
3804     SSL *clientssl = NULL, *serverssl = NULL;
3805     int testresult = 0;
3806     SSL_SESSION *sess = NULL;
3807     size_t readbytes, written;
3808     unsigned char buf[20];
3809     OSSL_TIME timer;
3810 
3811     allow_ed_cb_called = 0;
3812 
3813     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3814             TLS_client_method(), TLS1_VERSION, 0,
3815             &sctx, &cctx, cert, privkey)))
3816         return 0;
3817 
3818     if (usecb > 0) {
3819         if (confopt == 0) {
3820             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3821         } else {
3822             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3823 
3824             if (!TEST_ptr(confctx))
3825                 goto end;
3826             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_SERVER);
3827             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3828             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3829                     2)) {
3830                 SSL_CONF_CTX_free(confctx);
3831                 goto end;
3832             }
3833             SSL_CONF_CTX_free(confctx);
3834         }
3835         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3836     }
3837 
3838     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3839             &serverssl, &sess, idx,
3840             SHA384_DIGEST_LENGTH)))
3841         goto end;
3842 
3843     /*
3844      * The server is configured to accept early data. Create a connection to
3845      * "use up" the ticket
3846      */
3847     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3848         || !TEST_true(SSL_session_reused(clientssl)))
3849         goto end;
3850 
3851     SSL_shutdown(clientssl);
3852     SSL_shutdown(serverssl);
3853     SSL_free(serverssl);
3854     SSL_free(clientssl);
3855     serverssl = clientssl = NULL;
3856 
3857     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3858             &clientssl, NULL, NULL))
3859         || !TEST_true(SSL_set_session(clientssl, sess)))
3860         goto end;
3861 
3862     /* Write and read some early data */
3863     timer = ossl_time_now();
3864     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3865             &written))
3866         || !TEST_size_t_eq(written, strlen(MSG1)))
3867         goto end;
3868 
3869     if (usecb <= 1) {
3870         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3871                              &readbytes),
3872                 SSL_READ_EARLY_DATA_FINISH)
3873             /*
3874              * The ticket was reused, so the we should have rejected the
3875              * early data
3876              */
3877             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3878                 SSL_EARLY_DATA_REJECTED))
3879             goto end;
3880     } else {
3881         /* In this case the callback decides to accept the early data */
3882         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3883                              &readbytes),
3884                 SSL_READ_EARLY_DATA_SUCCESS)) {
3885             testresult = check_early_data_timeout(timer);
3886             goto end;
3887         }
3888         if (!TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3889             /*
3890              * Server will have sent its flight so client can now send
3891              * end of early data and complete its half of the handshake
3892              */
3893             || !TEST_int_gt(SSL_connect(clientssl), 0)
3894             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3895                                 &readbytes),
3896                 SSL_READ_EARLY_DATA_FINISH)
3897             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3898                 SSL_EARLY_DATA_ACCEPTED))
3899             goto end;
3900     }
3901 
3902     /* Complete the connection */
3903     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3904         || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3905         || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3906         goto end;
3907 
3908     testresult = 1;
3909 
3910 end:
3911     SSL_SESSION_free(sess);
3912     SSL_SESSION_free(clientpsk);
3913     SSL_SESSION_free(serverpsk);
3914     clientpsk = serverpsk = NULL;
3915     SSL_free(serverssl);
3916     SSL_free(clientssl);
3917     SSL_CTX_free(sctx);
3918     SSL_CTX_free(cctx);
3919     return testresult;
3920 }
3921 
test_early_data_replay(int idx)3922 static int test_early_data_replay(int idx)
3923 {
3924     int ret = 1, usecb, confopt;
3925 
3926     for (usecb = 0; usecb < 3; usecb++) {
3927         for (confopt = 0; confopt < 2; confopt++)
3928             ret &= test_early_data_replay_int(idx, usecb, confopt);
3929     }
3930 
3931     return ret;
3932 }
3933 
3934 static const char *ciphersuites[] = {
3935     "TLS_AES_128_CCM_8_SHA256",
3936     "TLS_AES_128_GCM_SHA256",
3937     "TLS_AES_256_GCM_SHA384",
3938     "TLS_AES_128_CCM_SHA256",
3939 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3940     "TLS_CHACHA20_POLY1305_SHA256",
3941 #else
3942     NULL,
3943 #endif
3944 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
3945     "TLS_SHA256_SHA256",
3946     "TLS_SHA384_SHA384"
3947 #endif
3948 };
3949 
3950 /*
3951  * Helper function to test that a server attempting to read early data can
3952  * handle a connection from a client where the early data should be skipped.
3953  * testtype: 0 == No HRR
3954  * testtype: 1 == HRR
3955  * testtype: 2 == HRR, invalid early_data sent after HRR
3956  * testtype: 3 == recv_max_early_data set to 0
3957  */
early_data_skip_helper(int testtype,int cipher,int idx)3958 static int early_data_skip_helper(int testtype, int cipher, int idx)
3959 {
3960     SSL_CTX *cctx = NULL, *sctx = NULL;
3961     SSL *clientssl = NULL, *serverssl = NULL;
3962     int testresult = 0;
3963     SSL_SESSION *sess = NULL;
3964     unsigned char buf[20];
3965     size_t readbytes, written;
3966 
3967     if (is_fips && cipher >= 4)
3968         return 1;
3969 
3970     if (ciphersuites[cipher] == NULL)
3971         return TEST_skip("Cipher not supported");
3972 
3973     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3974             TLS_client_method(),
3975             TLS1_VERSION, 0,
3976             &sctx, &cctx, cert, privkey)))
3977         goto end;
3978 
3979     if (cipher == 0 || cipher == 5 || cipher == 6) {
3980         SSL_CTX_set_security_level(sctx, 0);
3981         SSL_CTX_set_security_level(cctx, 0);
3982     }
3983 
3984     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, ciphersuites[cipher]))
3985         || !TEST_true(SSL_CTX_set_ciphersuites(cctx, ciphersuites[cipher])))
3986         goto end;
3987 
3988     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3989             &serverssl, &sess, idx,
3990             (cipher == 2 || cipher == 6)
3991                 ? SHA384_DIGEST_LENGTH
3992                 : SHA256_DIGEST_LENGTH)))
3993         goto end;
3994 
3995     if (testtype == 1 || testtype == 2) {
3996         /* Force an HRR to occur */
3997 #if defined(OPENSSL_NO_EC)
3998         if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
3999             goto end;
4000 #else
4001         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
4002             goto end;
4003 #endif
4004     } else if (idx == 2) {
4005         /*
4006          * We force early_data rejection by ensuring the PSK identity is
4007          * unrecognised
4008          */
4009         srvid = "Dummy Identity";
4010     } else {
4011         /*
4012          * Deliberately corrupt the creation time. We take 20 seconds off the
4013          * time. It could be any value as long as it is not within tolerance.
4014          * This should mean the ticket is rejected.
4015          */
4016         if (!TEST_true(SSL_SESSION_set_time_ex(sess, time(NULL) - 20)))
4017             goto end;
4018     }
4019 
4020     if (testtype == 3
4021         && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
4022         goto end;
4023 
4024     /* Write some early data */
4025     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4026             &written))
4027         || !TEST_size_t_eq(written, strlen(MSG1)))
4028         goto end;
4029 
4030     /* Server should reject the early data */
4031     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4032                          &readbytes),
4033             SSL_READ_EARLY_DATA_FINISH)
4034         || !TEST_size_t_eq(readbytes, 0)
4035         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4036             SSL_EARLY_DATA_REJECTED))
4037         goto end;
4038 
4039     switch (testtype) {
4040     case 0:
4041         /* Nothing to do */
4042         break;
4043 
4044     case 1:
4045         /*
4046          * Finish off the handshake. We perform the same writes and reads as
4047          * further down but we expect them to fail due to the incomplete
4048          * handshake.
4049          */
4050         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4051             || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
4052                 &readbytes)))
4053             goto end;
4054         break;
4055 
4056     case 2: {
4057         BIO *wbio = SSL_get_wbio(clientssl);
4058         /* A record that will appear as bad early_data */
4059         const unsigned char bad_early_data[] = {
4060             0x17, 0x03, 0x03, 0x00, 0x01, 0x00
4061         };
4062 
4063         /*
4064          * We force the client to attempt a write. This will fail because
4065          * we're still in the handshake. It will cause the second
4066          * ClientHello to be sent.
4067          */
4068         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
4069                 &written)))
4070             goto end;
4071 
4072         /*
4073          * Inject some early_data after the second ClientHello. This should
4074          * cause the server to fail
4075          */
4076         if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
4077                 sizeof(bad_early_data), &written)))
4078             goto end;
4079     }
4080         /* FALLTHROUGH */
4081 
4082     case 3:
4083         /*
4084          * This client has sent more early_data than we are willing to skip
4085          * (case 3) or sent invalid early_data (case 2) so the connection should
4086          * abort.
4087          */
4088         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4089             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
4090             goto end;
4091 
4092         /* Connection has failed - nothing more to do */
4093         testresult = 1;
4094         goto end;
4095 
4096     default:
4097         TEST_error("Invalid test type");
4098         goto end;
4099     }
4100 
4101     ERR_clear_error();
4102     /*
4103      * Should be able to send normal data despite rejection of early data. The
4104      * early_data should be skipped.
4105      */
4106     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4107         || !TEST_size_t_eq(written, strlen(MSG2))
4108         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4109             SSL_EARLY_DATA_REJECTED)
4110         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4111         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4112         goto end;
4113 
4114     /*
4115      * Failure to decrypt early data records should not leave spurious errors
4116      * on the error stack
4117      */
4118     if (!TEST_long_eq(ERR_peek_error(), 0))
4119         goto end;
4120 
4121     testresult = 1;
4122 
4123 end:
4124     SSL_SESSION_free(clientpsk);
4125     SSL_SESSION_free(serverpsk);
4126     clientpsk = serverpsk = NULL;
4127     SSL_SESSION_free(sess);
4128     SSL_free(serverssl);
4129     SSL_free(clientssl);
4130     SSL_CTX_free(sctx);
4131     SSL_CTX_free(cctx);
4132     return testresult;
4133 }
4134 
4135 /*
4136  * Test that a server attempting to read early data can handle a connection
4137  * from a client where the early data is not acceptable.
4138  */
test_early_data_skip(int idx)4139 static int test_early_data_skip(int idx)
4140 {
4141     return early_data_skip_helper(0,
4142         idx % OSSL_NELEM(ciphersuites),
4143         idx / OSSL_NELEM(ciphersuites));
4144 }
4145 
4146 /*
4147  * Test that a server attempting to read early data can handle a connection
4148  * from a client where an HRR occurs.
4149  */
test_early_data_skip_hrr(int idx)4150 static int test_early_data_skip_hrr(int idx)
4151 {
4152     return early_data_skip_helper(1,
4153         idx % OSSL_NELEM(ciphersuites),
4154         idx / OSSL_NELEM(ciphersuites));
4155 }
4156 
4157 /*
4158  * Test that a server attempting to read early data can handle a connection
4159  * from a client where an HRR occurs and correctly fails if early_data is sent
4160  * after the HRR
4161  */
test_early_data_skip_hrr_fail(int idx)4162 static int test_early_data_skip_hrr_fail(int idx)
4163 {
4164     return early_data_skip_helper(2,
4165         idx % OSSL_NELEM(ciphersuites),
4166         idx / OSSL_NELEM(ciphersuites));
4167 }
4168 
4169 /*
4170  * Test that a server attempting to read early data will abort if it tries to
4171  * skip over too much.
4172  */
test_early_data_skip_abort(int idx)4173 static int test_early_data_skip_abort(int idx)
4174 {
4175     return early_data_skip_helper(3,
4176         idx % OSSL_NELEM(ciphersuites),
4177         idx / OSSL_NELEM(ciphersuites));
4178 }
4179 
4180 /*
4181  * Test that a server attempting to read early data can handle a connection
4182  * from a client that doesn't send any.
4183  */
test_early_data_not_sent(int idx)4184 static int test_early_data_not_sent(int idx)
4185 {
4186     SSL_CTX *cctx = NULL, *sctx = NULL;
4187     SSL *clientssl = NULL, *serverssl = NULL;
4188     int testresult = 0;
4189     SSL_SESSION *sess = NULL;
4190     unsigned char buf[20];
4191     size_t readbytes, written;
4192 
4193     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4194             &serverssl, &sess, idx,
4195             SHA384_DIGEST_LENGTH)))
4196         goto end;
4197 
4198     /* Write some data - should block due to handshake with server */
4199     SSL_set_connect_state(clientssl);
4200     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4201         goto end;
4202 
4203     /* Server should detect that early data has not been sent */
4204     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4205                          &readbytes),
4206             SSL_READ_EARLY_DATA_FINISH)
4207         || !TEST_size_t_eq(readbytes, 0)
4208         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4209             SSL_EARLY_DATA_NOT_SENT)
4210         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4211             SSL_EARLY_DATA_NOT_SENT))
4212         goto end;
4213 
4214     /* Continue writing the message we started earlier */
4215     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4216         || !TEST_size_t_eq(written, strlen(MSG1))
4217         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4218         || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4219         || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
4220         || !TEST_size_t_eq(written, strlen(MSG2)))
4221         goto end;
4222 
4223     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4224         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4225         goto end;
4226 
4227     testresult = 1;
4228 
4229 end:
4230     SSL_SESSION_free(sess);
4231     SSL_SESSION_free(clientpsk);
4232     SSL_SESSION_free(serverpsk);
4233     clientpsk = serverpsk = NULL;
4234     SSL_free(serverssl);
4235     SSL_free(clientssl);
4236     SSL_CTX_free(sctx);
4237     SSL_CTX_free(cctx);
4238     return testresult;
4239 }
4240 
4241 static const char *servalpn;
4242 
alpn_select_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)4243 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
4244     unsigned char *outlen, const unsigned char *in,
4245     unsigned int inlen, void *arg)
4246 {
4247     unsigned int protlen = 0;
4248     const unsigned char *prot;
4249 
4250     for (prot = in; prot < in + inlen; prot += protlen) {
4251         protlen = *prot++;
4252         if (in + inlen < prot + protlen)
4253             return SSL_TLSEXT_ERR_NOACK;
4254 
4255         if (protlen == strlen(servalpn)
4256             && memcmp(prot, servalpn, protlen) == 0) {
4257             *out = prot;
4258             *outlen = protlen;
4259             return SSL_TLSEXT_ERR_OK;
4260         }
4261     }
4262 
4263     return SSL_TLSEXT_ERR_NOACK;
4264 }
4265 
4266 /* Test that a PSK can be used to send early_data */
test_early_data_psk(int idx)4267 static int test_early_data_psk(int idx)
4268 {
4269     SSL_CTX *cctx = NULL, *sctx = NULL;
4270     SSL *clientssl = NULL, *serverssl = NULL;
4271     int testresult = 0;
4272     SSL_SESSION *sess = NULL;
4273     unsigned char alpnlist[] = {
4274         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
4275         'l', 'p', 'n'
4276     };
4277 #define GOODALPNLEN 9
4278 #define BADALPNLEN 8
4279 #define GOODALPN (alpnlist)
4280 #define BADALPN (alpnlist + GOODALPNLEN)
4281     int err = 0;
4282     unsigned char buf[20];
4283     size_t readbytes, written;
4284     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
4285     int edstatus = SSL_EARLY_DATA_ACCEPTED;
4286 
4287     /* We always set this up with a final parameter of "2" for PSK */
4288     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4289             &serverssl, &sess, 2,
4290             SHA384_DIGEST_LENGTH)))
4291         goto end;
4292 
4293     servalpn = "goodalpn";
4294 
4295     /*
4296      * Note: There is no test for inconsistent SNI with late client detection.
4297      * This is because servers do not acknowledge SNI even if they are using
4298      * it in a resumption handshake - so it is not actually possible for a
4299      * client to detect a problem.
4300      */
4301     switch (idx) {
4302     case 0:
4303         /* Set inconsistent SNI (early client detection) */
4304         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
4305         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4306             || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
4307             goto end;
4308         break;
4309 
4310     case 1:
4311         /* Set inconsistent ALPN (early client detection) */
4312         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
4313         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
4314         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
4315                 GOODALPNLEN))
4316             || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
4317                 BADALPNLEN)))
4318             goto end;
4319         break;
4320 
4321     case 2:
4322         /*
4323          * Set invalid protocol version. Technically this affects PSKs without
4324          * early_data too, but we test it here because it is similar to the
4325          * SNI/ALPN consistency tests.
4326          */
4327         err = SSL_R_BAD_PSK;
4328         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
4329             goto end;
4330         break;
4331 
4332     case 3:
4333         /*
4334          * Set inconsistent SNI (server side). In this case the connection
4335          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
4336          * is associated with each handshake - not the session. Therefore it
4337          * should not matter that we used a different server name last time.
4338          */
4339         SSL_SESSION_free(serverpsk);
4340         serverpsk = SSL_SESSION_dup(clientpsk);
4341         if (!TEST_ptr(serverpsk)
4342             || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
4343             goto end;
4344         /* Fall through */
4345     case 4:
4346         /* Set consistent SNI */
4347         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4348             || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
4349             || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
4350                 hostname_cb)))
4351             goto end;
4352         break;
4353 
4354     case 5:
4355         /*
4356          * Set inconsistent ALPN (server detected). In this case the connection
4357          * will succeed but reject early_data.
4358          */
4359         servalpn = "badalpn";
4360         edstatus = SSL_EARLY_DATA_REJECTED;
4361         readearlyres = SSL_READ_EARLY_DATA_FINISH;
4362         /* Fall through */
4363     case 6:
4364         /*
4365          * Set consistent ALPN.
4366          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
4367          * accepts a list of protos (each one length prefixed).
4368          * SSL_set1_alpn_selected accepts a single protocol (not length
4369          * prefixed)
4370          */
4371         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
4372                 GOODALPNLEN - 1))
4373             || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
4374                 GOODALPNLEN)))
4375             goto end;
4376 
4377         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4378         break;
4379 
4380     case 7:
4381         /* Set inconsistent ALPN (late client detection) */
4382         SSL_SESSION_free(serverpsk);
4383         serverpsk = SSL_SESSION_dup(clientpsk);
4384         if (!TEST_ptr(serverpsk)
4385             || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
4386                 BADALPN + 1,
4387                 BADALPNLEN - 1))
4388             || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
4389                 GOODALPN + 1,
4390                 GOODALPNLEN - 1))
4391             || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
4392                 sizeof(alpnlist))))
4393             goto end;
4394         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4395         edstatus = SSL_EARLY_DATA_ACCEPTED;
4396         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
4397         /* SSL_connect() call should fail */
4398         connectres = -1;
4399         break;
4400 
4401     default:
4402         TEST_error("Bad test index");
4403         goto end;
4404     }
4405 
4406     SSL_set_connect_state(clientssl);
4407     if (err != 0) {
4408         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4409                 &written))
4410             || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
4411             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
4412             goto end;
4413     } else {
4414         OSSL_TIME timer = ossl_time_now();
4415 
4416         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4417                 &written)))
4418             goto end;
4419 
4420         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4421                              &readbytes),
4422                 readearlyres)) {
4423             testresult = check_early_data_timeout(timer);
4424             goto end;
4425         }
4426 
4427         if ((readearlyres == SSL_READ_EARLY_DATA_SUCCESS
4428                 && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
4429             || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
4430             || !TEST_int_eq(SSL_connect(clientssl), connectres))
4431             goto end;
4432     }
4433 
4434     testresult = 1;
4435 
4436 end:
4437     SSL_SESSION_free(sess);
4438     SSL_SESSION_free(clientpsk);
4439     SSL_SESSION_free(serverpsk);
4440     clientpsk = serverpsk = NULL;
4441     SSL_free(serverssl);
4442     SSL_free(clientssl);
4443     SSL_CTX_free(sctx);
4444     SSL_CTX_free(cctx);
4445     return testresult;
4446 }
4447 
4448 /*
4449  * Test TLSv1.3 PSK can be used to send early_data with all 7 ciphersuites
4450  * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
4451  * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
4452  * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4453  * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
4454  * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
4455  * idx == 5: Test with TLS1_3_RFC_SHA256_SHA256
4456  * idx == 6: Test with TLS1_3_RFC_SHA384_SHA384
4457  */
test_early_data_psk_with_all_ciphers(int idx)4458 static int test_early_data_psk_with_all_ciphers(int idx)
4459 {
4460     SSL_CTX *cctx = NULL, *sctx = NULL;
4461     SSL *clientssl = NULL, *serverssl = NULL;
4462     int testresult = 0;
4463     SSL_SESSION *sess = NULL;
4464     unsigned char buf[20];
4465     size_t readbytes, written;
4466     const SSL_CIPHER *cipher;
4467     OSSL_TIME timer;
4468     const char *cipher_str[] = {
4469         TLS1_3_RFC_AES_128_GCM_SHA256,
4470         TLS1_3_RFC_AES_256_GCM_SHA384,
4471 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4472         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4473 #else
4474         NULL,
4475 #endif
4476         TLS1_3_RFC_AES_128_CCM_SHA256,
4477         TLS1_3_RFC_AES_128_CCM_8_SHA256,
4478 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4479         TLS1_3_RFC_SHA256_SHA256,
4480         TLS1_3_RFC_SHA384_SHA384
4481 #else
4482         NULL,
4483         NULL
4484 #endif
4485     };
4486     const unsigned char *cipher_bytes[] = {
4487         TLS13_AES_128_GCM_SHA256_BYTES,
4488         TLS13_AES_256_GCM_SHA384_BYTES,
4489 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4490         TLS13_CHACHA20_POLY1305_SHA256_BYTES,
4491 #else
4492         NULL,
4493 #endif
4494         TLS13_AES_128_CCM_SHA256_BYTES,
4495         TLS13_AES_128_CCM_8_SHA256_BYTES,
4496 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4497         TLS13_SHA256_SHA256_BYTES,
4498         TLS13_SHA384_SHA384_BYTES
4499 #else
4500         NULL,
4501         NULL
4502 #endif
4503     };
4504 
4505     if (cipher_str[idx] == NULL)
4506         return 1;
4507     /*
4508      * Skip ChaCha20Poly1305 and TLS_SHA{256,384}_SHA{256,384} ciphers
4509      * as currently FIPS module does not support them.
4510      */
4511     if ((idx == 2 || idx == 5 || idx == 6) && is_fips == 1)
4512         return 1;
4513 
4514     /* We always set this up with a final parameter of "2" for PSK */
4515     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4516             &serverssl, &sess, 2,
4517             SHA384_DIGEST_LENGTH)))
4518         goto end;
4519 
4520     if (idx == 4 || idx == 5 || idx == 6) {
4521         /*
4522          * CCM8 ciphers are considered low security due to their short tag.
4523          * Integrity-only cipher do not provide any confidentiality.
4524          */
4525         SSL_set_security_level(clientssl, 0);
4526         SSL_set_security_level(serverssl, 0);
4527     }
4528 
4529     if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
4530         || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
4531         goto end;
4532 
4533     /*
4534      * 'setupearly_data_test' creates only one instance of SSL_SESSION
4535      * and assigns to both client and server with incremented reference
4536      * and the same instance is updated in 'sess'.
4537      * So updating ciphersuite in 'sess' which will get reflected in
4538      * PSK handshake using psk use sess and find sess cb.
4539      */
4540     cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
4541     if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
4542         goto end;
4543 
4544     SSL_set_connect_state(clientssl);
4545     timer = ossl_time_now();
4546     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4547             &written)))
4548         goto end;
4549 
4550     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4551                          &readbytes),
4552             SSL_READ_EARLY_DATA_SUCCESS)) {
4553         testresult = check_early_data_timeout(timer);
4554         goto end;
4555     }
4556 
4557     if (!TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4558         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4559             SSL_EARLY_DATA_ACCEPTED)
4560         || !TEST_int_eq(SSL_connect(clientssl), 1)
4561         || !TEST_int_eq(SSL_accept(serverssl), 1))
4562         goto end;
4563 
4564     /* Send some normal data from client to server */
4565     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4566         || !TEST_size_t_eq(written, strlen(MSG2)))
4567         goto end;
4568 
4569     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4570         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4571         goto end;
4572 
4573     testresult = 1;
4574 end:
4575     SSL_SESSION_free(sess);
4576     SSL_SESSION_free(clientpsk);
4577     SSL_SESSION_free(serverpsk);
4578     clientpsk = serverpsk = NULL;
4579     if (clientssl != NULL)
4580         SSL_shutdown(clientssl);
4581     if (serverssl != NULL)
4582         SSL_shutdown(serverssl);
4583     SSL_free(serverssl);
4584     SSL_free(clientssl);
4585     SSL_CTX_free(sctx);
4586     SSL_CTX_free(cctx);
4587     return testresult;
4588 }
4589 
4590 /*
4591  * Test that a server that doesn't try to read early data can handle a
4592  * client sending some.
4593  */
test_early_data_not_expected(int idx)4594 static int test_early_data_not_expected(int idx)
4595 {
4596     SSL_CTX *cctx = NULL, *sctx = NULL;
4597     SSL *clientssl = NULL, *serverssl = NULL;
4598     int testresult = 0;
4599     SSL_SESSION *sess = NULL;
4600     unsigned char buf[20];
4601     size_t readbytes, written;
4602 
4603     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4604             &serverssl, &sess, idx,
4605             SHA384_DIGEST_LENGTH)))
4606         goto end;
4607 
4608     /* Write some early data */
4609     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4610             &written)))
4611         goto end;
4612 
4613     /*
4614      * Server should skip over early data and then block waiting for client to
4615      * continue handshake
4616      */
4617     if (!TEST_int_le(SSL_accept(serverssl), 0)
4618         || !TEST_int_gt(SSL_connect(clientssl), 0)
4619         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4620             SSL_EARLY_DATA_REJECTED)
4621         || !TEST_int_gt(SSL_accept(serverssl), 0)
4622         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4623             SSL_EARLY_DATA_REJECTED))
4624         goto end;
4625 
4626     /* Send some normal data from client to server */
4627     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4628         || !TEST_size_t_eq(written, strlen(MSG2)))
4629         goto end;
4630 
4631     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4632         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4633         goto end;
4634 
4635     testresult = 1;
4636 
4637 end:
4638     SSL_SESSION_free(sess);
4639     SSL_SESSION_free(clientpsk);
4640     SSL_SESSION_free(serverpsk);
4641     clientpsk = serverpsk = NULL;
4642     SSL_free(serverssl);
4643     SSL_free(clientssl);
4644     SSL_CTX_free(sctx);
4645     SSL_CTX_free(cctx);
4646     return testresult;
4647 }
4648 
4649 #ifndef OPENSSL_NO_TLS1_2
4650 /*
4651  * Test that a server attempting to read early data can handle a connection
4652  * from a TLSv1.2 client.
4653  */
test_early_data_tls1_2(int idx)4654 static int test_early_data_tls1_2(int idx)
4655 {
4656     SSL_CTX *cctx = NULL, *sctx = NULL;
4657     SSL *clientssl = NULL, *serverssl = NULL;
4658     int testresult = 0;
4659     unsigned char buf[20];
4660     size_t readbytes, written;
4661 
4662     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4663             &serverssl, NULL, idx,
4664             SHA384_DIGEST_LENGTH)))
4665         goto end;
4666 
4667     /* Write some data - should block due to handshake with server */
4668     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
4669     SSL_set_connect_state(clientssl);
4670     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4671         goto end;
4672 
4673     /*
4674      * Server should do TLSv1.2 handshake. First it will block waiting for more
4675      * messages from client after ServerDone. Then SSL_read_early_data should
4676      * finish and detect that early data has not been sent
4677      */
4678     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4679                          &readbytes),
4680             SSL_READ_EARLY_DATA_ERROR))
4681         goto end;
4682 
4683     /*
4684      * Continue writing the message we started earlier. Will still block waiting
4685      * for the CCS/Finished from server
4686      */
4687     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4688         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4689                             &readbytes),
4690             SSL_READ_EARLY_DATA_FINISH)
4691         || !TEST_size_t_eq(readbytes, 0)
4692         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4693             SSL_EARLY_DATA_NOT_SENT))
4694         goto end;
4695 
4696     /* Continue writing the message we started earlier */
4697     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4698         || !TEST_size_t_eq(written, strlen(MSG1))
4699         || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4700             SSL_EARLY_DATA_NOT_SENT)
4701         || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4702         || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4703         || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
4704         || !TEST_size_t_eq(written, strlen(MSG2))
4705         || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
4706         || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4707         goto end;
4708 
4709     testresult = 1;
4710 
4711 end:
4712     SSL_SESSION_free(clientpsk);
4713     SSL_SESSION_free(serverpsk);
4714     clientpsk = serverpsk = NULL;
4715     SSL_free(serverssl);
4716     SSL_free(clientssl);
4717     SSL_CTX_free(sctx);
4718     SSL_CTX_free(cctx);
4719 
4720     return testresult;
4721 }
4722 #endif /* OPENSSL_NO_TLS1_2 */
4723 
4724 /*
4725  * Test configuring the TLSv1.3 ciphersuites
4726  *
4727  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
4728  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
4729  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
4730  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
4731  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4732  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4733  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
4734  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
4735  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
4736  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
4737  */
test_set_ciphersuite(int idx)4738 static int test_set_ciphersuite(int idx)
4739 {
4740     SSL_CTX *cctx = NULL, *sctx = NULL;
4741     SSL *clientssl = NULL, *serverssl = NULL;
4742     int testresult = 0;
4743 
4744     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4745             TLS_client_method(), TLS1_VERSION, 0,
4746             &sctx, &cctx, cert, privkey))
4747         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4748             "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
4749         goto end;
4750 
4751     if (idx >= 4 && idx <= 7) {
4752         /* SSL_CTX explicit cipher list */
4753         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
4754             goto end;
4755     }
4756 
4757     if (idx == 0 || idx == 4) {
4758         /* Default ciphersuite */
4759         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4760                 "TLS_AES_128_GCM_SHA256")))
4761             goto end;
4762     } else if (idx == 1 || idx == 5) {
4763         /* Non default ciphersuite */
4764         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4765                 "TLS_AES_128_CCM_SHA256")))
4766             goto end;
4767     }
4768 
4769     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4770             &clientssl, NULL, NULL)))
4771         goto end;
4772 
4773     if (idx == 8 || idx == 9) {
4774         /* SSL explicit cipher list */
4775         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
4776             goto end;
4777     }
4778 
4779     if (idx == 2 || idx == 6 || idx == 8) {
4780         /* Default ciphersuite */
4781         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4782                 "TLS_AES_128_GCM_SHA256")))
4783             goto end;
4784     } else if (idx == 3 || idx == 7 || idx == 9) {
4785         /* Non default ciphersuite */
4786         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4787                 "TLS_AES_128_CCM_SHA256")))
4788             goto end;
4789     }
4790 
4791     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4792         goto end;
4793 
4794     testresult = 1;
4795 
4796 end:
4797     SSL_free(serverssl);
4798     SSL_free(clientssl);
4799     SSL_CTX_free(sctx);
4800     SSL_CTX_free(cctx);
4801 
4802     return testresult;
4803 }
4804 
test_ciphersuite_change(void)4805 static int test_ciphersuite_change(void)
4806 {
4807     SSL_CTX *cctx = NULL, *sctx = NULL;
4808     SSL *clientssl = NULL, *serverssl = NULL;
4809     SSL_SESSION *clntsess = NULL;
4810     int testresult = 0;
4811     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
4812 
4813     /* Create a session based on SHA-256 */
4814     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4815             TLS_client_method(), TLS1_VERSION, 0,
4816             &sctx, &cctx, cert, privkey))
4817         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4818             "TLS_AES_128_GCM_SHA256:"
4819             "TLS_AES_256_GCM_SHA384:"
4820             "TLS_AES_128_CCM_SHA256"))
4821         || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4822             "TLS_AES_128_GCM_SHA256")))
4823         goto end;
4824 
4825     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4826             NULL, NULL))
4827         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4828             SSL_ERROR_NONE)))
4829         goto end;
4830 
4831     clntsess = SSL_get1_session(clientssl);
4832     /* Save for later */
4833     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
4834     SSL_shutdown(clientssl);
4835     SSL_shutdown(serverssl);
4836     SSL_free(serverssl);
4837     SSL_free(clientssl);
4838     serverssl = clientssl = NULL;
4839 
4840     /* Check we can resume a session with a different SHA-256 ciphersuite */
4841     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4842             "TLS_AES_128_CCM_SHA256"))
4843         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4844             &clientssl, NULL, NULL))
4845         || !TEST_true(SSL_set_session(clientssl, clntsess))
4846         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4847             SSL_ERROR_NONE))
4848         || !TEST_true(SSL_session_reused(clientssl)))
4849         goto end;
4850 
4851     SSL_SESSION_free(clntsess);
4852     clntsess = SSL_get1_session(clientssl);
4853     SSL_shutdown(clientssl);
4854     SSL_shutdown(serverssl);
4855     SSL_free(serverssl);
4856     SSL_free(clientssl);
4857     serverssl = clientssl = NULL;
4858 
4859     /*
4860      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
4861      * succeeds but does not resume.
4862      */
4863     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4864         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4865             NULL, NULL))
4866         || !TEST_true(SSL_set_session(clientssl, clntsess))
4867         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4868             SSL_ERROR_SSL))
4869         || !TEST_false(SSL_session_reused(clientssl)))
4870         goto end;
4871 
4872     SSL_SESSION_free(clntsess);
4873     clntsess = NULL;
4874     SSL_shutdown(clientssl);
4875     SSL_shutdown(serverssl);
4876     SSL_free(serverssl);
4877     SSL_free(clientssl);
4878     serverssl = clientssl = NULL;
4879 
4880     /* Create a session based on SHA384 */
4881     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4882         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4883             &clientssl, NULL, NULL))
4884         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4885             SSL_ERROR_NONE)))
4886         goto end;
4887 
4888     clntsess = SSL_get1_session(clientssl);
4889     SSL_shutdown(clientssl);
4890     SSL_shutdown(serverssl);
4891     SSL_free(serverssl);
4892     SSL_free(clientssl);
4893     serverssl = clientssl = NULL;
4894 
4895     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4896             "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
4897         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4898             "TLS_AES_256_GCM_SHA384"))
4899         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4900             NULL, NULL))
4901         || !TEST_true(SSL_set_session(clientssl, clntsess))
4902         /*
4903          * We use SSL_ERROR_WANT_READ below so that we can pause the
4904          * connection after the initial ClientHello has been sent to
4905          * enable us to make some session changes.
4906          */
4907         || !TEST_false(create_ssl_connection(serverssl, clientssl,
4908             SSL_ERROR_WANT_READ)))
4909         goto end;
4910 
4911     /* Trick the client into thinking this session is for a different digest */
4912     clntsess->cipher = aes_128_gcm_sha256;
4913     clntsess->cipher_id = clntsess->cipher->id;
4914 
4915     /*
4916      * Continue the previously started connection. Server has selected a SHA-384
4917      * ciphersuite, but client thinks the session is for SHA-256, so it should
4918      * bail out.
4919      */
4920     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4921             SSL_ERROR_SSL))
4922         || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4923             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4924         goto end;
4925 
4926     testresult = 1;
4927 
4928 end:
4929     SSL_SESSION_free(clntsess);
4930     SSL_free(serverssl);
4931     SSL_free(clientssl);
4932     SSL_CTX_free(sctx);
4933     SSL_CTX_free(cctx);
4934 
4935     return testresult;
4936 }
4937 
4938 /*
4939  * Test TLSv1.3 Key exchange
4940  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4941  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4942  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4943  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4944  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4945  * Test 5 = Test NID_X448 with TLSv1.3 client and server
4946  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4947  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4948  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4949  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4950  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4951  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4952  * Test 12 = Test all ML-KEM with TLSv1.3 client and server
4953  * Test 13 = Test MLKEM512
4954  * Test 14 = Test MLKEM768
4955  * Test 15 = Test MLKEM1024
4956  * Test 16 = Test X25519MLKEM768
4957  * Test 17 = Test SecP256r1MLKEM768
4958  * Test 18 = Test SecP384r1MLKEM1024
4959  * Test 19 = Test all ML-KEM with TLSv1.2 client and server
4960  * Test 20 = Test all FFDHE with TLSv1.2 client and server
4961  * Test 21 = Test all ECDHE with TLSv1.2 client and server
4962  */
4963 #ifndef OPENSSL_NO_EC
4964 static int ecdhe_kexch_groups[] = { NID_X9_62_prime256v1, NID_secp384r1,
4965     NID_secp521r1,
4966 #ifndef OPENSSL_NO_ECX
4967     NID_X25519, NID_X448
4968 #endif
4969 };
4970 #endif
4971 #ifndef OPENSSL_NO_DH
4972 static int ffdhe_kexch_groups[] = { NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4973     NID_ffdhe6144, NID_ffdhe8192 };
4974 #endif
test_key_exchange(int idx)4975 static int test_key_exchange(int idx)
4976 {
4977     SSL_CTX *sctx = NULL, *cctx = NULL;
4978     SSL *serverssl = NULL, *clientssl = NULL;
4979     int testresult = 0;
4980     int kexch_alg = NID_undef;
4981     int *kexch_groups = &kexch_alg;
4982     int kexch_groups_size = 1;
4983     int max_version = TLS1_3_VERSION;
4984     char *kexch_name0 = NULL;
4985     const char *kexch_names = NULL;
4986     int shared_group0;
4987 
4988     switch (idx) {
4989 #ifndef OPENSSL_NO_EC
4990 #ifndef OPENSSL_NO_TLS1_2
4991     case 21:
4992         max_version = TLS1_2_VERSION;
4993 #endif
4994         /* Fall through */
4995     case 0:
4996         kexch_groups = ecdhe_kexch_groups;
4997         kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
4998         kexch_name0 = "secp256r1";
4999         break;
5000     case 1:
5001         kexch_alg = NID_X9_62_prime256v1;
5002         kexch_name0 = "secp256r1";
5003         break;
5004     case 2:
5005         kexch_alg = NID_secp384r1;
5006         kexch_name0 = "secp384r1";
5007         break;
5008     case 3:
5009         kexch_alg = NID_secp521r1;
5010         kexch_name0 = "secp521r1";
5011         break;
5012 #ifndef OPENSSL_NO_ECX
5013     case 4:
5014         if (is_fips)
5015             return TEST_skip("X25519 might not be supported by fips provider.");
5016         kexch_alg = NID_X25519;
5017         kexch_name0 = "x25519";
5018         break;
5019     case 5:
5020         if (is_fips)
5021             return TEST_skip("X448 might not be supported by fips provider.");
5022         kexch_alg = NID_X448;
5023         kexch_name0 = "x448";
5024         break;
5025 #endif
5026 #endif
5027 #ifndef OPENSSL_NO_DH
5028 #ifndef OPENSSL_NO_TLS1_2
5029     case 20:
5030         max_version = TLS1_2_VERSION;
5031         kexch_name0 = "ffdhe2048";
5032 #endif
5033         /* Fall through */
5034     case 6:
5035         kexch_groups = ffdhe_kexch_groups;
5036         kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
5037         kexch_name0 = "ffdhe2048";
5038         break;
5039     case 7:
5040         kexch_alg = NID_ffdhe2048;
5041         kexch_name0 = "ffdhe2048";
5042         break;
5043     case 8:
5044         kexch_alg = NID_ffdhe3072;
5045         kexch_name0 = "ffdhe3072";
5046         break;
5047     case 9:
5048         kexch_alg = NID_ffdhe4096;
5049         kexch_name0 = "ffdhe4096";
5050         break;
5051     case 10:
5052         kexch_alg = NID_ffdhe6144;
5053         kexch_name0 = "ffdhe6144";
5054         break;
5055     case 11:
5056         kexch_alg = NID_ffdhe8192;
5057         kexch_name0 = "ffdhe8192";
5058         break;
5059 #endif
5060 #ifndef OPENSSL_NO_ML_KEM
5061 #if !defined(OPENSSL_NO_TLS1_2)
5062     case 19:
5063         max_version = TLS1_2_VERSION;
5064 #if !defined(OPENSSL_NO_EC)
5065         /* Set at least one EC group so the handshake completes */
5066         kexch_names = "MLKEM512:MLKEM768:MLKEM1024:secp256r1";
5067 #elif !defined(OPENSSL_NO_DH)
5068         kexch_names = "MLKEM512:MLKEM768:MLKEM1024";
5069 #else
5070         /* With neither EC nor DH TLS 1.2 can't happen */
5071         return 1;
5072 #endif
5073 #endif
5074         /* Fall through */
5075     case 12:
5076         kexch_groups = NULL;
5077         if (kexch_names == NULL)
5078             kexch_names = "MLKEM512:MLKEM768:MLKEM1024";
5079         kexch_name0 = "MLKEM512";
5080         break;
5081     case 13:
5082         kexch_groups = NULL;
5083         kexch_name0 = "MLKEM512";
5084         kexch_names = kexch_name0;
5085         break;
5086     case 14:
5087         kexch_groups = NULL;
5088         kexch_name0 = "MLKEM768";
5089         kexch_names = kexch_name0;
5090         break;
5091     case 15:
5092         kexch_groups = NULL;
5093         kexch_name0 = "MLKEM1024";
5094         kexch_names = kexch_name0;
5095         break;
5096 #ifndef OPENSSL_NO_EC
5097 #ifndef OPENSSL_NO_ECX
5098     case 16:
5099         kexch_groups = NULL;
5100         kexch_name0 = "X25519MLKEM768";
5101         kexch_names = kexch_name0;
5102         break;
5103 #endif
5104     case 17:
5105         kexch_groups = NULL;
5106         kexch_name0 = "SecP256r1MLKEM768";
5107         kexch_names = kexch_name0;
5108         break;
5109     case 18:
5110         kexch_groups = NULL;
5111         kexch_name0 = "SecP384r1MLKEM1024";
5112         kexch_names = kexch_name0;
5113         break;
5114 #endif
5115 #endif
5116     default:
5117         /* We're skipping this test */
5118         return 1;
5119     }
5120 
5121     if (is_fips && fips_provider_version_lt(libctx, 3, 5, 0)
5122         && idx >= 12 && idx <= 19)
5123         return TEST_skip("ML-KEM not supported in this version of fips provider");
5124 
5125     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5126             TLS_client_method(), TLS1_VERSION,
5127             max_version, &sctx, &cctx, cert,
5128             privkey)))
5129         goto end;
5130 
5131     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
5132             TLS1_3_RFC_AES_128_GCM_SHA256)))
5133         goto end;
5134 
5135     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5136             TLS1_3_RFC_AES_128_GCM_SHA256)))
5137         goto end;
5138 
5139     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5140             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5141         || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5142         goto end;
5143 
5144     /*
5145      * Must include an EC ciphersuite so that we send supported groups in
5146      * TLSv1.2
5147      */
5148 #ifndef OPENSSL_NO_TLS1_2
5149     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5150             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5151         goto end;
5152 #endif
5153 
5154     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5155             NULL, NULL)))
5156         goto end;
5157 
5158     if (kexch_groups != NULL) {
5159         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
5160             || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
5161             goto end;
5162     } else {
5163         if (!TEST_true(SSL_set1_groups_list(serverssl, kexch_names))
5164             || !TEST_true(SSL_set1_groups_list(clientssl, kexch_names)))
5165             goto end;
5166     }
5167 
5168     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5169         goto end;
5170 
5171     /*
5172      * If the handshake succeeds the negotiated kexch alg should be the first
5173      * one in configured, except in the case of "all" FFDHE and "all" ML-KEM
5174      * groups (idx == 19, 20), which are TLSv1.3 only so we expect no shared
5175      * group to exist.
5176      */
5177     shared_group0 = SSL_get_shared_group(serverssl, 0);
5178     switch (idx) {
5179     case 19:
5180 #if !defined(OPENSSL_NO_EC)
5181         /* MLKEM + TLS 1.2 and no DH => "secp526r1" */
5182         if (!TEST_int_eq(shared_group0, NID_X9_62_prime256v1))
5183             goto end;
5184         break;
5185 #endif
5186         /* Fall through */
5187     case 20:
5188         if (!TEST_int_eq(shared_group0, 0))
5189             goto end;
5190         break;
5191     default:
5192         if (kexch_groups != NULL
5193             && !TEST_int_eq(shared_group0, kexch_groups[0]))
5194             goto end;
5195         if (!TEST_str_eq(SSL_group_to_name(serverssl, shared_group0),
5196                 kexch_name0))
5197             goto end;
5198         if (!TEST_str_eq(SSL_get0_group_name(serverssl), kexch_name0)
5199             || !TEST_str_eq(SSL_get0_group_name(clientssl), kexch_name0))
5200             goto end;
5201         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), shared_group0))
5202             goto end;
5203         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), shared_group0))
5204             goto end;
5205         break;
5206     }
5207 
5208     testresult = 1;
5209 end:
5210     SSL_free(serverssl);
5211     SSL_free(clientssl);
5212     SSL_CTX_free(sctx);
5213     SSL_CTX_free(cctx);
5214     return testresult;
5215 }
5216 
5217 #if !defined(OPENSSL_NO_TLS1_2) \
5218     && !defined(OPENSSL_NO_EC)  \
5219     && !defined(OPENSSL_NO_DH)
set_ssl_groups(SSL * serverssl,SSL * clientssl,int clientmulti,int isecdhe,int idx)5220 static int set_ssl_groups(SSL *serverssl, SSL *clientssl, int clientmulti,
5221     int isecdhe, int idx)
5222 {
5223     int kexch_alg;
5224     int *kexch_groups = &kexch_alg;
5225     int numec, numff;
5226 
5227     numec = OSSL_NELEM(ecdhe_kexch_groups);
5228     numff = OSSL_NELEM(ffdhe_kexch_groups);
5229     if (isecdhe)
5230         kexch_alg = ecdhe_kexch_groups[idx];
5231     else
5232         kexch_alg = ffdhe_kexch_groups[idx];
5233 
5234     if (clientmulti) {
5235         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, 1)))
5236             return 0;
5237         if (isecdhe) {
5238             if (!TEST_true(SSL_set1_groups(clientssl, ecdhe_kexch_groups,
5239                     numec)))
5240                 return 0;
5241         } else {
5242             if (!TEST_true(SSL_set1_groups(clientssl, ffdhe_kexch_groups,
5243                     numff)))
5244                 return 0;
5245         }
5246     } else {
5247         if (!TEST_true(SSL_set1_groups(clientssl, kexch_groups, 1)))
5248             return 0;
5249         if (isecdhe) {
5250             if (!TEST_true(SSL_set1_groups(serverssl, ecdhe_kexch_groups,
5251                     numec)))
5252                 return 0;
5253         } else {
5254             if (!TEST_true(SSL_set1_groups(serverssl, ffdhe_kexch_groups,
5255                     numff)))
5256                 return 0;
5257         }
5258     }
5259     return 1;
5260 }
5261 
5262 /*-
5263  * Test the SSL_get_negotiated_group() API across a battery of scenarios.
5264  * Run through both the ECDHE and FFDHE group lists used in the previous
5265  * test, for both TLS 1.2 and TLS 1.3, negotiating each group in turn,
5266  * confirming the expected result; then perform a resumption handshake
5267  * while offering the same group list, and another resumption handshake
5268  * offering a different group list.  The returned value should be the
5269  * negotiated group for the initial handshake; for TLS 1.3 resumption
5270  * handshakes the returned value will be negotiated on the resumption
5271  * handshake itself, but for TLS 1.2 resumption handshakes the value will
5272  * be cached in the session from the original handshake, regardless of what
5273  * was offered in the resumption ClientHello.
5274  *
5275  * Using E for the number of EC groups and F for the number of FF groups:
5276  * E tests of ECDHE with TLS 1.3, server only has one group
5277  * F tests of FFDHE with TLS 1.3, server only has one group
5278  * E tests of ECDHE with TLS 1.2, server only has one group
5279  * F tests of FFDHE with TLS 1.2, server only has one group
5280  * E tests of ECDHE with TLS 1.3, client sends only one group
5281  * F tests of FFDHE with TLS 1.3, client sends only one group
5282  * E tests of ECDHE with TLS 1.2, client sends only one group
5283  * F tests of FFDHE with TLS 1.2, client sends only one group
5284  */
test_negotiated_group(int idx)5285 static int test_negotiated_group(int idx)
5286 {
5287     int clientmulti, istls13, isecdhe, numec, numff, numgroups;
5288     int expectednid;
5289     SSL_CTX *sctx = NULL, *cctx = NULL;
5290     SSL *serverssl = NULL, *clientssl = NULL;
5291     SSL_SESSION *origsess = NULL;
5292     int testresult = 0;
5293     int kexch_alg;
5294     int max_version = TLS1_3_VERSION;
5295 
5296     numec = OSSL_NELEM(ecdhe_kexch_groups);
5297     numff = OSSL_NELEM(ffdhe_kexch_groups);
5298     numgroups = numec + numff;
5299     clientmulti = (idx < 2 * numgroups);
5300     idx = idx % (2 * numgroups);
5301     istls13 = (idx < numgroups);
5302     idx = idx % numgroups;
5303     isecdhe = (idx < numec);
5304     if (!isecdhe)
5305         idx -= numec;
5306     /* Now 'idx' is an index into ecdhe_kexch_groups or ffdhe_kexch_groups */
5307     if (isecdhe)
5308         kexch_alg = ecdhe_kexch_groups[idx];
5309     else
5310         kexch_alg = ffdhe_kexch_groups[idx];
5311     /* We expect nothing for the unimplemented TLS 1.2 FFDHE named groups */
5312     if (!istls13 && !isecdhe)
5313         expectednid = NID_undef;
5314     else
5315         expectednid = kexch_alg;
5316 
5317     if (is_fips && (kexch_alg == NID_X25519 || kexch_alg == NID_X448))
5318         return TEST_skip("X25519 and X448 might not be available in fips provider.");
5319 
5320     if (!istls13)
5321         max_version = TLS1_2_VERSION;
5322 
5323     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5324             TLS_client_method(), TLS1_VERSION,
5325             max_version, &sctx, &cctx, cert,
5326             privkey)))
5327         goto end;
5328 
5329     /*
5330      * Force (EC)DHE ciphers for TLS 1.2.
5331      * Be sure to enable auto tmp DH so that FFDHE can succeed.
5332      */
5333     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5334             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5335         || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5336         goto end;
5337     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5338             TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":" TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5339         goto end;
5340 
5341     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5342             NULL, NULL)))
5343         goto end;
5344 
5345     if (!TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe,
5346             idx)))
5347         goto end;
5348 
5349     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5350         goto end;
5351 
5352     /* Initial handshake; always the configured one */
5353     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5354         || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5355         goto end;
5356 
5357     if (!TEST_ptr((origsess = SSL_get1_session(clientssl))))
5358         goto end;
5359 
5360     SSL_shutdown(clientssl);
5361     SSL_shutdown(serverssl);
5362     SSL_free(serverssl);
5363     SSL_free(clientssl);
5364     serverssl = clientssl = NULL;
5365 
5366     /* First resumption attempt; use the same config as initial handshake */
5367     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5368             NULL, NULL))
5369         || !TEST_true(SSL_set_session(clientssl, origsess))
5370         || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5371             isecdhe, idx)))
5372         goto end;
5373 
5374     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5375         || !TEST_true(SSL_session_reused(clientssl)))
5376         goto end;
5377 
5378     /* Still had better agree, since nothing changed... */
5379     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5380         || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5381         goto end;
5382 
5383     SSL_shutdown(clientssl);
5384     SSL_shutdown(serverssl);
5385     SSL_free(serverssl);
5386     SSL_free(clientssl);
5387     serverssl = clientssl = NULL;
5388 
5389     /*-
5390      * Second resumption attempt
5391      * The party that picks one group changes it, which we effectuate by
5392      * changing 'idx' and updating what we expect.
5393      */
5394     if (idx == 0)
5395         idx = 1;
5396     else
5397         idx--;
5398     if (istls13) {
5399         if (isecdhe)
5400             expectednid = ecdhe_kexch_groups[idx];
5401         else
5402             expectednid = ffdhe_kexch_groups[idx];
5403         /* Verify that we are changing what we expect. */
5404         if (!TEST_int_ne(expectednid, kexch_alg))
5405             goto end;
5406     } else {
5407         /* TLS 1.2 only supports named groups for ECDHE. */
5408         if (isecdhe)
5409             expectednid = kexch_alg;
5410         else
5411             expectednid = 0;
5412     }
5413     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5414             NULL, NULL))
5415         || !TEST_true(SSL_set_session(clientssl, origsess))
5416         || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5417             isecdhe, idx)))
5418         goto end;
5419 
5420     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5421         || !TEST_true(SSL_session_reused(clientssl)))
5422         goto end;
5423 
5424     /* Check that we get what we expected */
5425     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5426         || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5427         goto end;
5428 
5429     testresult = 1;
5430 end:
5431     SSL_free(serverssl);
5432     SSL_free(clientssl);
5433     SSL_CTX_free(sctx);
5434     SSL_CTX_free(cctx);
5435     SSL_SESSION_free(origsess);
5436     return testresult;
5437 }
5438 #endif /* !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) */
5439 
5440 /*
5441  * Test TLSv1.3 Cipher Suite
5442  * Test 0 = Set TLS1.3 cipher on context
5443  * Test 1 = Set TLS1.3 cipher on SSL
5444  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
5445  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
5446  */
test_tls13_ciphersuite(int idx)5447 static int test_tls13_ciphersuite(int idx)
5448 {
5449     SSL_CTX *sctx = NULL, *cctx = NULL;
5450     SSL *serverssl = NULL, *clientssl = NULL;
5451     static const struct {
5452         const char *ciphername;
5453         int fipscapable;
5454         int low_security;
5455     } t13_ciphers[] = {
5456         { TLS1_3_RFC_AES_128_GCM_SHA256, 1, 0 },
5457         { TLS1_3_RFC_AES_256_GCM_SHA384, 1, 0 },
5458         { TLS1_3_RFC_AES_128_CCM_SHA256, 1, 0 },
5459 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5460         { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5461         { TLS1_3_RFC_AES_256_GCM_SHA384
5462             ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
5463             0, 0 },
5464 #endif
5465         /* CCM8 ciphers are considered low security due to their short tag */
5466         { TLS1_3_RFC_AES_128_CCM_8_SHA256
5467             ":" TLS1_3_RFC_AES_128_CCM_SHA256,
5468             1, 1 },
5469 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
5470         /* Integrity-only cipher do not provide any confidentiality */
5471         { TLS1_3_RFC_SHA256_SHA256, 0, 1 },
5472         { TLS1_3_RFC_SHA384_SHA384, 0, 1 }
5473 #endif
5474     };
5475     const char *t13_cipher = NULL;
5476     const char *t12_cipher = NULL;
5477     const char *negotiated_scipher;
5478     const char *negotiated_ccipher;
5479     int set_at_ctx = 0;
5480     int set_at_ssl = 0;
5481     int testresult = 0;
5482     int max_ver;
5483     size_t i;
5484 
5485     switch (idx) {
5486     case 0:
5487         set_at_ctx = 1;
5488         break;
5489     case 1:
5490         set_at_ssl = 1;
5491         break;
5492     case 2:
5493         set_at_ctx = 1;
5494         t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5495         break;
5496     case 3:
5497         set_at_ssl = 1;
5498         t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5499         break;
5500     }
5501 
5502     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
5503 #ifdef OPENSSL_NO_TLS1_2
5504         if (max_ver == TLS1_2_VERSION)
5505             continue;
5506 #endif
5507         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
5508             if (is_fips && !t13_ciphers[i].fipscapable)
5509                 continue;
5510             t13_cipher = t13_ciphers[i].ciphername;
5511             if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5512                     TLS_client_method(),
5513                     TLS1_VERSION, max_ver,
5514                     &sctx, &cctx, cert, privkey)))
5515                 goto end;
5516 
5517             if (t13_ciphers[i].low_security) {
5518                 SSL_CTX_set_security_level(sctx, 0);
5519                 SSL_CTX_set_security_level(cctx, 0);
5520             }
5521 
5522             if (set_at_ctx) {
5523                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
5524                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
5525                     goto end;
5526                 if (t12_cipher != NULL) {
5527                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
5528                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
5529                             t12_cipher)))
5530                         goto end;
5531                 }
5532             }
5533 
5534             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5535                     &clientssl, NULL, NULL)))
5536                 goto end;
5537 
5538             if (set_at_ssl) {
5539                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
5540                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
5541                     goto end;
5542                 if (t12_cipher != NULL) {
5543                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
5544                         || !TEST_true(SSL_set_cipher_list(clientssl,
5545                             t12_cipher)))
5546                         goto end;
5547                 }
5548             }
5549 
5550             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5551                     SSL_ERROR_NONE)))
5552                 goto end;
5553 
5554             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5555                 serverssl));
5556             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5557                 clientssl));
5558             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
5559                 goto end;
5560 
5561             /*
5562              * TEST_strn_eq is used below because t13_cipher can contain
5563              * multiple ciphersuites
5564              */
5565             if (max_ver == TLS1_3_VERSION
5566                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
5567                     strlen(negotiated_scipher)))
5568                 goto end;
5569 
5570 #ifndef OPENSSL_NO_TLS1_2
5571             /* Below validation is not done when t12_cipher is NULL */
5572             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
5573                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
5574                 goto end;
5575 #endif
5576 
5577             SSL_free(serverssl);
5578             serverssl = NULL;
5579             SSL_free(clientssl);
5580             clientssl = NULL;
5581             SSL_CTX_free(sctx);
5582             sctx = NULL;
5583             SSL_CTX_free(cctx);
5584             cctx = NULL;
5585         }
5586     }
5587 
5588     testresult = 1;
5589 end:
5590     SSL_free(serverssl);
5591     SSL_free(clientssl);
5592     SSL_CTX_free(sctx);
5593     SSL_CTX_free(cctx);
5594     return testresult;
5595 }
5596 
5597 /*
5598  * Test TLSv1.3 PSKs
5599  * Test 0 = Test new style callbacks
5600  * Test 1 = Test both new and old style callbacks
5601  * Test 2 = Test old style callbacks
5602  * Test 3 = Test old style callbacks with no certificate
5603  */
test_tls13_psk(int idx)5604 static int test_tls13_psk(int idx)
5605 {
5606     SSL_CTX *sctx = NULL, *cctx = NULL;
5607     SSL *serverssl = NULL, *clientssl = NULL;
5608     const SSL_CIPHER *cipher = NULL;
5609     const unsigned char key[] = {
5610         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
5611         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5612         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
5613         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
5614     };
5615     int testresult = 0;
5616 
5617     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5618             TLS_client_method(), TLS1_VERSION, 0,
5619             &sctx, &cctx, idx == 3 ? NULL : cert,
5620             idx == 3 ? NULL : privkey)))
5621         goto end;
5622 
5623     if (idx != 3) {
5624         /*
5625          * We use a ciphersuite with SHA256 to ease testing old style PSK
5626          * callbacks which will always default to SHA256. This should not be
5627          * necessary if we have no cert/priv key. In that case the server should
5628          * prefer SHA256 automatically.
5629          */
5630         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5631                 "TLS_AES_128_GCM_SHA256")))
5632             goto end;
5633     } else {
5634         /*
5635          * As noted above the server should prefer SHA256 automatically. However
5636          * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
5637          * code works even if we are testing with only the FIPS provider loaded.
5638          */
5639         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5640                 "TLS_AES_256_GCM_SHA384:"
5641                 "TLS_AES_128_GCM_SHA256")))
5642             goto end;
5643     }
5644 
5645     /*
5646      * Test 0: New style callbacks only
5647      * Test 1: New and old style callbacks (only the new ones should be used)
5648      * Test 2: Old style callbacks only
5649      */
5650     if (idx == 0 || idx == 1) {
5651         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
5652         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
5653     }
5654 #ifndef OPENSSL_NO_PSK
5655     if (idx >= 1) {
5656         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
5657         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
5658     }
5659 #endif
5660     srvid = pskid;
5661     use_session_cb_cnt = 0;
5662     find_session_cb_cnt = 0;
5663     psk_client_cb_cnt = 0;
5664     psk_server_cb_cnt = 0;
5665 
5666     if (idx != 3) {
5667         /*
5668          * Check we can create a connection if callback decides not to send a
5669          * PSK
5670          */
5671         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5672                 NULL, NULL))
5673             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5674                 SSL_ERROR_NONE))
5675             || !TEST_false(SSL_session_reused(clientssl))
5676             || !TEST_false(SSL_session_reused(serverssl)))
5677             goto end;
5678 
5679         if (idx == 0 || idx == 1) {
5680             if (!TEST_true(use_session_cb_cnt == 1)
5681                 || !TEST_true(find_session_cb_cnt == 0)
5682                 /*
5683                  * If no old style callback then below should be 0
5684                  * otherwise 1
5685                  */
5686                 || !TEST_true(psk_client_cb_cnt == idx)
5687                 || !TEST_true(psk_server_cb_cnt == 0))
5688                 goto end;
5689         } else {
5690             if (!TEST_true(use_session_cb_cnt == 0)
5691                 || !TEST_true(find_session_cb_cnt == 0)
5692                 || !TEST_true(psk_client_cb_cnt == 1)
5693                 || !TEST_true(psk_server_cb_cnt == 0))
5694                 goto end;
5695         }
5696 
5697         shutdown_ssl_connection(serverssl, clientssl);
5698         serverssl = clientssl = NULL;
5699         use_session_cb_cnt = psk_client_cb_cnt = 0;
5700     }
5701 
5702     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5703             NULL, NULL)))
5704         goto end;
5705 
5706     /* Create the PSK */
5707     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
5708     clientpsk = SSL_SESSION_new();
5709     if (!TEST_ptr(clientpsk)
5710         || !TEST_ptr(cipher)
5711         || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
5712             sizeof(key)))
5713         || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
5714         || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
5715             TLS1_3_VERSION))
5716         || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
5717         goto end;
5718     serverpsk = clientpsk;
5719 
5720     /* Check we can create a connection and the PSK is used */
5721     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5722         || !TEST_true(SSL_session_reused(clientssl))
5723         || !TEST_true(SSL_session_reused(serverssl)))
5724         goto end;
5725 
5726     if (idx == 0 || idx == 1) {
5727         if (!TEST_true(use_session_cb_cnt == 1)
5728             || !TEST_true(find_session_cb_cnt == 1)
5729             || !TEST_true(psk_client_cb_cnt == 0)
5730             || !TEST_true(psk_server_cb_cnt == 0))
5731             goto end;
5732     } else {
5733         if (!TEST_true(use_session_cb_cnt == 0)
5734             || !TEST_true(find_session_cb_cnt == 0)
5735             || !TEST_true(psk_client_cb_cnt == 1)
5736             || !TEST_true(psk_server_cb_cnt == 1))
5737             goto end;
5738     }
5739 
5740     shutdown_ssl_connection(serverssl, clientssl);
5741     serverssl = clientssl = NULL;
5742     use_session_cb_cnt = find_session_cb_cnt = 0;
5743     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5744 
5745     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5746             NULL, NULL)))
5747         goto end;
5748 
5749     /* Force an HRR */
5750 #if defined(OPENSSL_NO_EC)
5751     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
5752         goto end;
5753 #else
5754     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
5755         goto end;
5756 #endif
5757 
5758     /*
5759      * Check we can create a connection, the PSK is used and the callbacks are
5760      * called twice.
5761      */
5762     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5763         || !TEST_true(SSL_session_reused(clientssl))
5764         || !TEST_true(SSL_session_reused(serverssl)))
5765         goto end;
5766 
5767     if (idx == 0 || idx == 1) {
5768         if (!TEST_true(use_session_cb_cnt == 2)
5769             || !TEST_true(find_session_cb_cnt == 2)
5770             || !TEST_true(psk_client_cb_cnt == 0)
5771             || !TEST_true(psk_server_cb_cnt == 0))
5772             goto end;
5773     } else {
5774         if (!TEST_true(use_session_cb_cnt == 0)
5775             || !TEST_true(find_session_cb_cnt == 0)
5776             || !TEST_true(psk_client_cb_cnt == 2)
5777             || !TEST_true(psk_server_cb_cnt == 2))
5778             goto end;
5779     }
5780 
5781     shutdown_ssl_connection(serverssl, clientssl);
5782     serverssl = clientssl = NULL;
5783     use_session_cb_cnt = find_session_cb_cnt = 0;
5784     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5785 
5786     if (idx != 3) {
5787         /*
5788          * Check that if the server rejects the PSK we can still connect, but with
5789          * a full handshake
5790          */
5791         srvid = "Dummy Identity";
5792         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5793                 NULL, NULL))
5794             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5795                 SSL_ERROR_NONE))
5796             || !TEST_false(SSL_session_reused(clientssl))
5797             || !TEST_false(SSL_session_reused(serverssl)))
5798             goto end;
5799 
5800         if (idx == 0 || idx == 1) {
5801             if (!TEST_true(use_session_cb_cnt == 1)
5802                 || !TEST_true(find_session_cb_cnt == 1)
5803                 || !TEST_true(psk_client_cb_cnt == 0)
5804                 /*
5805                  * If no old style callback then below should be 0
5806                  * otherwise 1
5807                  */
5808                 || !TEST_true(psk_server_cb_cnt == idx))
5809                 goto end;
5810         } else {
5811             if (!TEST_true(use_session_cb_cnt == 0)
5812                 || !TEST_true(find_session_cb_cnt == 0)
5813                 || !TEST_true(psk_client_cb_cnt == 1)
5814                 || !TEST_true(psk_server_cb_cnt == 1))
5815                 goto end;
5816         }
5817 
5818         shutdown_ssl_connection(serverssl, clientssl);
5819         serverssl = clientssl = NULL;
5820     }
5821     testresult = 1;
5822 
5823 end:
5824     SSL_SESSION_free(clientpsk);
5825     SSL_SESSION_free(serverpsk);
5826     clientpsk = serverpsk = NULL;
5827     SSL_free(serverssl);
5828     SSL_free(clientssl);
5829     SSL_CTX_free(sctx);
5830     SSL_CTX_free(cctx);
5831     return testresult;
5832 }
5833 
5834 #ifndef OSSL_NO_USABLE_TLS1_3
5835 /*
5836  * Test TLS1.3 connection establishment succeeds with various configurations of
5837  * the options `SSL_OP_ALLOW_NO_DHE_KEX` and `SSL_OP_PREFER_NO_DHE_KEX`.
5838  * The verification of whether the right KEX mode is chosen is not covered by
5839  * this test but by `test_tls13kexmodes`.
5840  *
5841  * Tests (idx & 1): Server has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5842  * Tests (idx & 2): Server has `SSL_OP_PREFER_NO_DHE_KEX` set.
5843  * Tests (idx & 4): Client has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5844  */
test_tls13_no_dhe_kex(const int idx)5845 static int test_tls13_no_dhe_kex(const int idx)
5846 {
5847     SSL_CTX *sctx = NULL, *cctx = NULL;
5848     SSL *serverssl = NULL, *clientssl = NULL;
5849     int testresult = 0;
5850     size_t j;
5851     SSL_SESSION *saved_session;
5852 
5853     int server_allow_no_dhe = (idx & 1) != 0;
5854     int server_prefer_no_dhe = (idx & 2) != 0;
5855     int client_allow_no_dhe = (idx & 4) != 0;
5856 
5857     uint64_t server_options = 0
5858         | (server_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0)
5859         | (server_prefer_no_dhe ? SSL_OP_PREFER_NO_DHE_KEX : 0);
5860 
5861     uint64_t client_options = 0
5862         | (client_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0);
5863 
5864     new_called = 0;
5865     do_cache = 1;
5866 
5867     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5868             TLS_client_method(), TLS1_3_VERSION, 0,
5869             &sctx, &cctx, cert, privkey)))
5870         goto end;
5871 
5872     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5873 
5874     SSL_CTX_set_options(sctx, server_options);
5875     SSL_CTX_set_options(cctx, client_options);
5876 
5877     SSL_CTX_sess_set_new_cb(cctx, new_cachesession_cb);
5878 
5879     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5880             &clientssl, NULL, NULL)))
5881         goto end;
5882 
5883     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5884             SSL_ERROR_NONE))
5885         /* Check we got the number of tickets we were expecting */
5886         || !TEST_int_eq(2, new_called))
5887         goto end;
5888 
5889     /* We'll reuse the last ticket. */
5890     saved_session = sesscache[new_called - 1];
5891 
5892     SSL_shutdown(clientssl);
5893     SSL_shutdown(serverssl);
5894     SSL_free(serverssl);
5895     SSL_free(clientssl);
5896     SSL_CTX_free(cctx);
5897     clientssl = serverssl = NULL;
5898     cctx = NULL;
5899 
5900     /*
5901      * Now we resume with the last ticket we created.
5902      */
5903 
5904     /* The server context already exists, so we only create the client. */
5905     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5906             TLS_client_method(), TLS1_3_VERSION, 0,
5907             NULL, &cctx, cert, privkey)))
5908         goto end;
5909 
5910     SSL_CTX_set_options(cctx, client_options);
5911 
5912     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5913             &clientssl, NULL, NULL))
5914         || !TEST_true(SSL_set_session(clientssl, saved_session)))
5915         goto end;
5916 
5917     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5918             SSL_ERROR_NONE)))
5919         goto end;
5920 
5921     /*
5922      * Make sure, the session was resumed.
5923      */
5924     if (!TEST_true(SSL_session_reused(clientssl)))
5925         goto end;
5926 
5927     SSL_shutdown(clientssl);
5928     SSL_shutdown(serverssl);
5929 
5930     testresult = 1;
5931 
5932 end:
5933     SSL_free(serverssl);
5934     SSL_free(clientssl);
5935     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
5936         SSL_SESSION_free(sesscache[j]);
5937         sesscache[j] = NULL;
5938     }
5939     SSL_CTX_free(sctx);
5940     SSL_CTX_free(cctx);
5941 
5942     return testresult;
5943 }
5944 #endif /* OSSL_NO_USABLE_TLS1_3 */
5945 
5946 static unsigned char cookie_magic_value[] = "cookie magic";
5947 
generate_cookie_callback(SSL * ssl,unsigned char * cookie,unsigned int * cookie_len)5948 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
5949     unsigned int *cookie_len)
5950 {
5951     /*
5952      * Not suitable as a real cookie generation function but good enough for
5953      * testing!
5954      */
5955     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
5956     *cookie_len = sizeof(cookie_magic_value) - 1;
5957 
5958     return 1;
5959 }
5960 
verify_cookie_callback(SSL * ssl,const unsigned char * cookie,unsigned int cookie_len)5961 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
5962     unsigned int cookie_len)
5963 {
5964     if (cookie_len == sizeof(cookie_magic_value) - 1
5965         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
5966         return 1;
5967 
5968     return 0;
5969 }
5970 
generate_stateless_cookie_callback(SSL * ssl,unsigned char * cookie,size_t * cookie_len)5971 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
5972     size_t *cookie_len)
5973 {
5974     unsigned int temp;
5975     int res = generate_cookie_callback(ssl, cookie, &temp);
5976     *cookie_len = temp;
5977     return res;
5978 }
5979 
verify_stateless_cookie_callback(SSL * ssl,const unsigned char * cookie,size_t cookie_len)5980 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
5981     size_t cookie_len)
5982 {
5983     return verify_cookie_callback(ssl, cookie, cookie_len);
5984 }
5985 
test_stateless(void)5986 static int test_stateless(void)
5987 {
5988     SSL_CTX *sctx = NULL, *cctx = NULL;
5989     SSL *serverssl = NULL, *clientssl = NULL;
5990     int testresult = 0;
5991 
5992     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5993             TLS_client_method(), TLS1_VERSION, 0,
5994             &sctx, &cctx, cert, privkey)))
5995         goto end;
5996 
5997     /* The arrival of CCS messages can confuse the test */
5998     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5999 
6000     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6001             NULL, NULL))
6002         /* Send the first ClientHello */
6003         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6004             SSL_ERROR_WANT_READ))
6005         /*
6006          * This should fail with a -1 return because we have no callbacks
6007          * set up
6008          */
6009         || !TEST_int_eq(SSL_stateless(serverssl), -1))
6010         goto end;
6011 
6012     /* Fatal error so abandon the connection from this client */
6013     SSL_free(clientssl);
6014     clientssl = NULL;
6015 
6016     /* Set up the cookie generation and verification callbacks */
6017     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
6018     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
6019 
6020     /*
6021      * Create a new connection from the client (we can reuse the server SSL
6022      * object).
6023      */
6024     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6025             NULL, NULL))
6026         /* Send the first ClientHello */
6027         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6028             SSL_ERROR_WANT_READ))
6029         /* This should fail because there is no cookie */
6030         || !TEST_int_eq(SSL_stateless(serverssl), 0))
6031         goto end;
6032 
6033     /* Abandon the connection from this client */
6034     SSL_free(clientssl);
6035     clientssl = NULL;
6036 
6037     /*
6038      * Now create a connection from a new client but with the same server SSL
6039      * object
6040      */
6041     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6042             NULL, NULL))
6043         /* Send the first ClientHello */
6044         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6045             SSL_ERROR_WANT_READ))
6046         /* This should fail because there is no cookie */
6047         || !TEST_int_eq(SSL_stateless(serverssl), 0)
6048         /* Send the second ClientHello */
6049         || !TEST_false(create_ssl_connection(serverssl, clientssl,
6050             SSL_ERROR_WANT_READ))
6051         /* This should succeed because a cookie is now present */
6052         || !TEST_int_eq(SSL_stateless(serverssl), 1)
6053         /* Complete the connection */
6054         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6055             SSL_ERROR_NONE)))
6056         goto end;
6057 
6058     shutdown_ssl_connection(serverssl, clientssl);
6059     serverssl = clientssl = NULL;
6060     testresult = 1;
6061 
6062 end:
6063     SSL_free(serverssl);
6064     SSL_free(clientssl);
6065     SSL_CTX_free(sctx);
6066     SSL_CTX_free(cctx);
6067     return testresult;
6068 }
6069 #endif /* OSSL_NO_USABLE_TLS1_3 */
6070 
6071 static int clntaddoldcb = 0;
6072 static int clntparseoldcb = 0;
6073 static int srvaddoldcb = 0;
6074 static int srvparseoldcb = 0;
6075 static int clntaddnewcb = 0;
6076 static int clntparsenewcb = 0;
6077 static int srvaddnewcb = 0;
6078 static int srvparsenewcb = 0;
6079 static int snicb = 0;
6080 
6081 #define TEST_EXT_TYPE1 0xff00
6082 
old_add_cb(SSL * s,unsigned int ext_type,const unsigned char ** out,size_t * outlen,int * al,void * add_arg)6083 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
6084     size_t *outlen, int *al, void *add_arg)
6085 {
6086     int *server = (int *)add_arg;
6087     unsigned char *data;
6088 
6089     if (SSL_is_server(s))
6090         srvaddoldcb++;
6091     else
6092         clntaddoldcb++;
6093 
6094     if (*server != SSL_is_server(s)
6095         || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
6096         return -1;
6097 
6098     *data = 1;
6099     *out = data;
6100     *outlen = sizeof(char);
6101     return 1;
6102 }
6103 
old_free_cb(SSL * s,unsigned int ext_type,const unsigned char * out,void * add_arg)6104 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
6105     void *add_arg)
6106 {
6107     OPENSSL_free((unsigned char *)out);
6108 }
6109 
old_parse_cb(SSL * s,unsigned int ext_type,const unsigned char * in,size_t inlen,int * al,void * parse_arg)6110 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
6111     size_t inlen, int *al, void *parse_arg)
6112 {
6113     int *server = (int *)parse_arg;
6114 
6115     if (SSL_is_server(s))
6116         srvparseoldcb++;
6117     else
6118         clntparseoldcb++;
6119 
6120     if (*server != SSL_is_server(s)
6121         || inlen != sizeof(char)
6122         || *in != 1)
6123         return -1;
6124 
6125     return 1;
6126 }
6127 
new_add_cb(SSL * s,unsigned int ext_type,unsigned int context,const unsigned char ** out,size_t * outlen,X509 * x,size_t chainidx,int * al,void * add_arg)6128 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
6129     const unsigned char **out, size_t *outlen, X509 *x,
6130     size_t chainidx, int *al, void *add_arg)
6131 {
6132     int *server = (int *)add_arg;
6133     unsigned char *data;
6134 
6135     if (SSL_is_server(s))
6136         srvaddnewcb++;
6137     else
6138         clntaddnewcb++;
6139 
6140     if (*server != SSL_is_server(s)
6141         || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
6142         return -1;
6143 
6144     *data = 1;
6145     *out = data;
6146     *outlen = sizeof(*data);
6147     return 1;
6148 }
6149 
new_free_cb(SSL * s,unsigned int ext_type,unsigned int context,const unsigned char * out,void * add_arg)6150 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
6151     const unsigned char *out, void *add_arg)
6152 {
6153     OPENSSL_free((unsigned char *)out);
6154 }
6155 
new_parse_cb(SSL * s,unsigned int ext_type,unsigned int context,const unsigned char * in,size_t inlen,X509 * x,size_t chainidx,int * al,void * parse_arg)6156 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
6157     const unsigned char *in, size_t inlen, X509 *x,
6158     size_t chainidx, int *al, void *parse_arg)
6159 {
6160     int *server = (int *)parse_arg;
6161 
6162     if (SSL_is_server(s))
6163         srvparsenewcb++;
6164     else
6165         clntparsenewcb++;
6166 
6167     if (*server != SSL_is_server(s)
6168         || inlen != sizeof(char) || *in != 1)
6169         return -1;
6170 
6171     return 1;
6172 }
6173 
sni_cb(SSL * s,int * al,void * arg)6174 static int sni_cb(SSL *s, int *al, void *arg)
6175 {
6176     SSL_CTX *ctx = (SSL_CTX *)arg;
6177 
6178     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
6179         *al = SSL_AD_INTERNAL_ERROR;
6180         return SSL_TLSEXT_ERR_ALERT_FATAL;
6181     }
6182     snicb++;
6183     return SSL_TLSEXT_ERR_OK;
6184 }
6185 
verify_cb(int preverify_ok,X509_STORE_CTX * x509_ctx)6186 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
6187 {
6188     return 1;
6189 }
6190 
6191 /*
6192  * Custom call back tests.
6193  * Test 0: Old style callbacks in TLSv1.2
6194  * Test 1: New style callbacks in TLSv1.2
6195  * Test 2: New style callbacks in TLSv1.2 with SNI
6196  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
6197  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
6198  * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
6199  */
test_custom_exts(int tst)6200 static int test_custom_exts(int tst)
6201 {
6202     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6203     SSL *clientssl = NULL, *serverssl = NULL;
6204     int testresult = 0;
6205     static int server = 1;
6206     static int client = 0;
6207     SSL_SESSION *sess = NULL;
6208     unsigned int context;
6209 
6210 #if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6211     /* Skip tests for TLSv1.2 and below in this case */
6212     if (tst < 3)
6213         return 1;
6214 #endif
6215 
6216     /* Reset callback counters */
6217     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
6218     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
6219     snicb = 0;
6220 
6221     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6222             TLS_client_method(), TLS1_VERSION, 0,
6223             &sctx, &cctx, cert, privkey)))
6224         goto end;
6225 
6226     if (tst == 2
6227         && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
6228             TLS1_VERSION, 0,
6229             &sctx2, NULL, cert, privkey)))
6230         goto end;
6231 
6232     if (tst < 3) {
6233         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
6234         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
6235         if (sctx2 != NULL)
6236             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
6237     }
6238 
6239     if (tst == 5) {
6240         context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
6241             | SSL_EXT_TLS1_3_CERTIFICATE;
6242         SSL_CTX_set_verify(sctx,
6243             SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
6244             verify_cb);
6245         if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
6246                              SSL_FILETYPE_PEM),
6247                 1)
6248             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
6249                                 SSL_FILETYPE_PEM),
6250                 1)
6251             || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
6252             goto end;
6253     } else if (tst == 4) {
6254         context = SSL_EXT_CLIENT_HELLO
6255             | SSL_EXT_TLS1_2_SERVER_HELLO
6256             | SSL_EXT_TLS1_3_SERVER_HELLO
6257             | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
6258             | SSL_EXT_TLS1_3_CERTIFICATE
6259             | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
6260     } else {
6261         context = SSL_EXT_CLIENT_HELLO
6262             | SSL_EXT_TLS1_2_SERVER_HELLO
6263             | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
6264     }
6265 
6266     /* Create a client side custom extension */
6267     if (tst == 0) {
6268         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6269                 old_add_cb, old_free_cb,
6270                 &client, old_parse_cb,
6271                 &client)))
6272             goto end;
6273     } else {
6274         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
6275                 new_add_cb, new_free_cb,
6276                 &client, new_parse_cb, &client)))
6277             goto end;
6278     }
6279 
6280     /* Should not be able to add duplicates */
6281     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6282             old_add_cb, old_free_cb,
6283             &client, old_parse_cb,
6284             &client))
6285         || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
6286             context, new_add_cb,
6287             new_free_cb, &client,
6288             new_parse_cb, &client)))
6289         goto end;
6290 
6291     /* Create a server side custom extension */
6292     if (tst == 0) {
6293         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6294                 old_add_cb, old_free_cb,
6295                 &server, old_parse_cb,
6296                 &server)))
6297             goto end;
6298     } else {
6299         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
6300                 new_add_cb, new_free_cb,
6301                 &server, new_parse_cb, &server)))
6302             goto end;
6303         if (sctx2 != NULL
6304             && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
6305                 context, new_add_cb,
6306                 new_free_cb, &server,
6307                 new_parse_cb, &server)))
6308             goto end;
6309     }
6310 
6311     /* Should not be able to add duplicates */
6312     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6313             old_add_cb, old_free_cb,
6314             &server, old_parse_cb,
6315             &server))
6316         || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
6317             context, new_add_cb,
6318             new_free_cb, &server,
6319             new_parse_cb, &server)))
6320         goto end;
6321 
6322     if (tst == 2) {
6323         /* Set up SNI */
6324         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
6325             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
6326             goto end;
6327     }
6328 
6329     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6330             &clientssl, NULL, NULL))
6331         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6332             SSL_ERROR_NONE)))
6333         goto end;
6334 
6335     if (tst == 0) {
6336         if (clntaddoldcb != 1
6337             || clntparseoldcb != 1
6338             || srvaddoldcb != 1
6339             || srvparseoldcb != 1)
6340             goto end;
6341     } else if (tst == 1 || tst == 2 || tst == 3) {
6342         if (clntaddnewcb != 1
6343             || clntparsenewcb != 1
6344             || srvaddnewcb != 1
6345             || srvparsenewcb != 1
6346             || (tst != 2 && snicb != 0)
6347             || (tst == 2 && snicb != 1))
6348             goto end;
6349     } else if (tst == 5) {
6350         if (clntaddnewcb != 1
6351             || clntparsenewcb != 1
6352             || srvaddnewcb != 1
6353             || srvparsenewcb != 1)
6354             goto end;
6355     } else {
6356         /* In this case there 2 NewSessionTicket messages created */
6357         if (clntaddnewcb != 1
6358             || clntparsenewcb != 5
6359             || srvaddnewcb != 5
6360             || srvparsenewcb != 1)
6361             goto end;
6362     }
6363 
6364     sess = SSL_get1_session(clientssl);
6365     SSL_shutdown(clientssl);
6366     SSL_shutdown(serverssl);
6367     SSL_free(serverssl);
6368     SSL_free(clientssl);
6369     serverssl = clientssl = NULL;
6370 
6371     if (tst == 3 || tst == 5) {
6372         /* We don't bother with the resumption aspects for these tests */
6373         testresult = 1;
6374         goto end;
6375     }
6376 
6377     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6378             NULL, NULL))
6379         || !TEST_true(SSL_set_session(clientssl, sess))
6380         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6381             SSL_ERROR_NONE)))
6382         goto end;
6383 
6384     /*
6385      * For a resumed session we expect to add the ClientHello extension. For the
6386      * old style callbacks we ignore it on the server side because they set
6387      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
6388      * them.
6389      */
6390     if (tst == 0) {
6391         if (clntaddoldcb != 2
6392             || clntparseoldcb != 1
6393             || srvaddoldcb != 1
6394             || srvparseoldcb != 1)
6395             goto end;
6396     } else if (tst == 1 || tst == 2 || tst == 3) {
6397         if (clntaddnewcb != 2
6398             || clntparsenewcb != 2
6399             || srvaddnewcb != 2
6400             || srvparsenewcb != 2)
6401             goto end;
6402     } else {
6403         /*
6404          * No Certificate message extensions in the resumption handshake,
6405          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
6406          */
6407         if (clntaddnewcb != 2
6408             || clntparsenewcb != 8
6409             || srvaddnewcb != 8
6410             || srvparsenewcb != 2)
6411             goto end;
6412     }
6413 
6414     testresult = 1;
6415 
6416 end:
6417     SSL_SESSION_free(sess);
6418     SSL_free(serverssl);
6419     SSL_free(clientssl);
6420     SSL_CTX_free(sctx2);
6421     SSL_CTX_free(sctx);
6422     SSL_CTX_free(cctx);
6423     return testresult;
6424 }
6425 
6426 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6427 
6428 #define SYNTHV1CONTEXT (SSL_EXT_TLS1_2_AND_BELOW_ONLY \
6429     | SSL_EXT_CLIENT_HELLO                            \
6430     | SSL_EXT_TLS1_2_SERVER_HELLO                     \
6431     | SSL_EXT_IGNORE_ON_RESUMPTION)
6432 
6433 #define TLS13CONTEXT (SSL_EXT_TLS1_3_CERTIFICATE \
6434     | SSL_EXT_TLS1_2_SERVER_HELLO                \
6435     | SSL_EXT_CLIENT_HELLO)
6436 
6437 #define SERVERINFO_CUSTOM                                 \
6438     0x00, (char)TLSEXT_TYPE_signed_certificate_timestamp, \
6439         0x00, 0x03,                                       \
6440         0x04, 0x05, 0x06
6441 
6442 static const unsigned char serverinfo_custom_tls13[] = {
6443     0x00, 0x00, (TLS13CONTEXT >> 8) & 0xff, TLS13CONTEXT & 0xff,
6444     SERVERINFO_CUSTOM
6445 };
6446 static const unsigned char serverinfo_custom_v2[] = {
6447     0x00, 0x00, (SYNTHV1CONTEXT >> 8) & 0xff, SYNTHV1CONTEXT & 0xff,
6448     SERVERINFO_CUSTOM
6449 };
6450 static const unsigned char serverinfo_custom_v1[] = {
6451     SERVERINFO_CUSTOM
6452 };
6453 static const size_t serverinfo_custom_tls13_len = sizeof(serverinfo_custom_tls13);
6454 static const size_t serverinfo_custom_v2_len = sizeof(serverinfo_custom_v2);
6455 static const size_t serverinfo_custom_v1_len = sizeof(serverinfo_custom_v1);
6456 
serverinfo_custom_parse_cb(SSL * s,unsigned int ext_type,unsigned int context,const unsigned char * in,size_t inlen,X509 * x,size_t chainidx,int * al,void * parse_arg)6457 static int serverinfo_custom_parse_cb(SSL *s, unsigned int ext_type,
6458     unsigned int context,
6459     const unsigned char *in,
6460     size_t inlen, X509 *x,
6461     size_t chainidx, int *al,
6462     void *parse_arg)
6463 {
6464     const size_t len = serverinfo_custom_v1_len;
6465     const unsigned char *si = &serverinfo_custom_v1[len - 3];
6466     int *p_cb_result = (int *)parse_arg;
6467     *p_cb_result = TEST_mem_eq(in, inlen, si, 3);
6468     return 1;
6469 }
6470 
test_serverinfo_custom(const int idx)6471 static int test_serverinfo_custom(const int idx)
6472 {
6473     SSL_CTX *sctx = NULL, *cctx = NULL;
6474     SSL *clientssl = NULL, *serverssl = NULL;
6475     int testresult = 0;
6476     int cb_result = 0;
6477 
6478     /*
6479      * Following variables are set in the switch statement
6480      *  according to the test iteration.
6481      * Default values do not make much sense: test would fail with them.
6482      */
6483     int serverinfo_version = 0;
6484     int protocol_version = 0;
6485     unsigned int extension_context = 0;
6486     const unsigned char *si = NULL;
6487     size_t si_len = 0;
6488 
6489     const int call_use_serverinfo_ex = idx > 0;
6490     switch (idx) {
6491     case 0: /* FALLTHROUGH */
6492     case 1:
6493         serverinfo_version = SSL_SERVERINFOV1;
6494         protocol_version = TLS1_2_VERSION;
6495         extension_context = SYNTHV1CONTEXT;
6496         si = serverinfo_custom_v1;
6497         si_len = serverinfo_custom_v1_len;
6498         break;
6499     case 2:
6500         serverinfo_version = SSL_SERVERINFOV2;
6501         protocol_version = TLS1_2_VERSION;
6502         extension_context = SYNTHV1CONTEXT;
6503         si = serverinfo_custom_v2;
6504         si_len = serverinfo_custom_v2_len;
6505         break;
6506     case 3:
6507         serverinfo_version = SSL_SERVERINFOV2;
6508         protocol_version = TLS1_3_VERSION;
6509         extension_context = TLS13CONTEXT;
6510         si = serverinfo_custom_tls13;
6511         si_len = serverinfo_custom_tls13_len;
6512         break;
6513     }
6514 
6515     if (!TEST_true(create_ssl_ctx_pair(libctx,
6516             TLS_method(),
6517             TLS_method(),
6518             protocol_version,
6519             protocol_version,
6520             &sctx, &cctx, cert, privkey)))
6521         goto end;
6522 
6523     if (call_use_serverinfo_ex) {
6524         if (!TEST_true(SSL_CTX_use_serverinfo_ex(sctx, serverinfo_version,
6525                 si, si_len)))
6526             goto end;
6527     } else {
6528         if (!TEST_true(SSL_CTX_use_serverinfo(sctx, si, si_len)))
6529             goto end;
6530     }
6531 
6532     if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TLSEXT_TYPE_signed_certificate_timestamp,
6533             extension_context,
6534             NULL, NULL, NULL,
6535             serverinfo_custom_parse_cb,
6536             &cb_result))
6537         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6538             NULL, NULL))
6539         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6540             SSL_ERROR_NONE))
6541         || !TEST_int_eq(SSL_do_handshake(clientssl), 1))
6542         goto end;
6543 
6544     if (!TEST_true(cb_result))
6545         goto end;
6546 
6547     testresult = 1;
6548 
6549 end:
6550     SSL_free(serverssl);
6551     SSL_free(clientssl);
6552     SSL_CTX_free(sctx);
6553     SSL_CTX_free(cctx);
6554 
6555     return testresult;
6556 }
6557 #endif
6558 
6559 /*
6560  * Test that SSL_export_keying_material() produces expected results. There are
6561  * no test vectors so all we do is test that both sides of the communication
6562  * produce the same results for different protocol versions.
6563  */
6564 #define SMALL_LABEL_LEN 10
6565 #define LONG_LABEL_LEN 249
test_export_key_mat(int tst)6566 static int test_export_key_mat(int tst)
6567 {
6568     int testresult = 0;
6569     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6570     SSL *clientssl = NULL, *serverssl = NULL;
6571     const char label[LONG_LABEL_LEN + 1] = "test label";
6572     const unsigned char context[] = "context";
6573     const unsigned char *emptycontext = NULL;
6574     unsigned char longcontext[1280];
6575     int test_longcontext = fips_provider_version_ge(libctx, 3, 3, 0);
6576     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80], ckeymat4[80];
6577     unsigned char skeymat1[80], skeymat2[80], skeymat3[80], skeymat4[80];
6578     size_t labellen;
6579     const int protocols[] = {
6580         TLS1_VERSION,
6581         TLS1_1_VERSION,
6582         TLS1_2_VERSION,
6583         TLS1_3_VERSION,
6584         TLS1_3_VERSION,
6585         TLS1_3_VERSION
6586     };
6587 
6588 #ifdef OPENSSL_NO_TLS1
6589     if (tst == 0)
6590         return 1;
6591 #endif
6592 #ifdef OPENSSL_NO_TLS1_1
6593     if (tst == 1)
6594         return 1;
6595 #endif
6596     if (is_fips && (tst == 0 || tst == 1))
6597         return 1;
6598 #ifdef OPENSSL_NO_TLS1_2
6599     if (tst == 2)
6600         return 1;
6601 #endif
6602 #ifdef OSSL_NO_USABLE_TLS1_3
6603     if (tst >= 3)
6604         return 1;
6605 #endif
6606     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6607             TLS_client_method(), TLS1_VERSION, 0,
6608             &sctx, &cctx, cert, privkey)))
6609         goto end;
6610 
6611     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
6612     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
6613     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
6614     if ((protocols[tst] < TLS1_2_VERSION) && (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0") || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
6615         goto end;
6616 
6617     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6618             NULL)))
6619         goto end;
6620 
6621     /*
6622      * Premature call of SSL_export_keying_material should just fail.
6623      */
6624     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6625                          sizeof(ckeymat1), label,
6626                          SMALL_LABEL_LEN + 1, context,
6627                          sizeof(context) - 1, 1),
6628             0))
6629         goto end;
6630 
6631     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6632             SSL_ERROR_NONE)))
6633         goto end;
6634 
6635     if (tst == 5) {
6636         /*
6637          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
6638          * go over that.
6639          */
6640         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6641                              sizeof(ckeymat1), label,
6642                              LONG_LABEL_LEN + 1, context,
6643                              sizeof(context) - 1, 1),
6644                 0))
6645             goto end;
6646 
6647         testresult = 1;
6648         goto end;
6649     } else if (tst == 4) {
6650         labellen = LONG_LABEL_LEN;
6651     } else {
6652         labellen = SMALL_LABEL_LEN;
6653     }
6654 
6655     memset(longcontext, 1, sizeof(longcontext));
6656 
6657     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
6658                          sizeof(ckeymat1), label,
6659                          labellen, context,
6660                          sizeof(context) - 1, 1),
6661             1)
6662         || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
6663                             sizeof(ckeymat2), label,
6664                             labellen,
6665                             emptycontext,
6666                             0, 1),
6667             1)
6668         || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
6669                             sizeof(ckeymat3), label,
6670                             labellen,
6671                             NULL, 0, 0),
6672             1)
6673         || (test_longcontext
6674             && !TEST_int_eq(SSL_export_keying_material(clientssl,
6675                                 ckeymat4,
6676                                 sizeof(ckeymat4), label,
6677                                 labellen,
6678                                 longcontext,
6679                                 sizeof(longcontext), 1),
6680                 1))
6681         || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
6682                             sizeof(skeymat1), label,
6683                             labellen,
6684                             context,
6685                             sizeof(context) - 1, 1),
6686             1)
6687         || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
6688                             sizeof(skeymat2), label,
6689                             labellen,
6690                             emptycontext,
6691                             0, 1),
6692             1)
6693         || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
6694                             sizeof(skeymat3), label,
6695                             labellen,
6696                             NULL, 0, 0),
6697             1)
6698         || (test_longcontext
6699             && !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat4,
6700                                 sizeof(skeymat4), label,
6701                                 labellen,
6702                                 longcontext,
6703                                 sizeof(longcontext), 1),
6704                 1))
6705         /*
6706          * Check that both sides created the same key material with the
6707          * same context.
6708          */
6709         || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6710             sizeof(skeymat1))
6711         /*
6712          * Check that both sides created the same key material with an
6713          * empty context.
6714          */
6715         || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6716             sizeof(skeymat2))
6717         /*
6718          * Check that both sides created the same key material without a
6719          * context.
6720          */
6721         || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
6722             sizeof(skeymat3))
6723         /*
6724          * Check that both sides created the same key material with a
6725          * long context.
6726          */
6727         || (test_longcontext
6728             && !TEST_mem_eq(ckeymat4, sizeof(ckeymat4), skeymat4,
6729                 sizeof(skeymat4)))
6730         /* Different contexts should produce different results */
6731         || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6732             sizeof(ckeymat2)))
6733         goto end;
6734 
6735     /*
6736      * Check that an empty context and no context produce different results in
6737      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
6738      */
6739     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3, sizeof(ckeymat3)))
6740         || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3, sizeof(ckeymat3))))
6741         goto end;
6742 
6743     testresult = 1;
6744 
6745 end:
6746     SSL_free(serverssl);
6747     SSL_free(clientssl);
6748     SSL_CTX_free(sctx2);
6749     SSL_CTX_free(sctx);
6750     SSL_CTX_free(cctx);
6751 
6752     return testresult;
6753 }
6754 
6755 #ifndef OSSL_NO_USABLE_TLS1_3
6756 /*
6757  * Test that SSL_export_keying_material_early() produces expected
6758  * results. There are no test vectors so all we do is test that both
6759  * sides of the communication produce the same results for different
6760  * protocol versions.
6761  */
test_export_key_mat_early(int idx)6762 static int test_export_key_mat_early(int idx)
6763 {
6764     static const char label[] = "test label";
6765     static const unsigned char context[] = "context";
6766     int testresult = 0;
6767     SSL_CTX *cctx = NULL, *sctx = NULL;
6768     SSL *clientssl = NULL, *serverssl = NULL;
6769     SSL_SESSION *sess = NULL;
6770     const unsigned char *emptycontext = NULL;
6771     unsigned char ckeymat1[80], ckeymat2[80];
6772     unsigned char skeymat1[80], skeymat2[80];
6773     unsigned char buf[1];
6774     size_t readbytes, written;
6775 
6776     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
6777             &sess, idx, SHA384_DIGEST_LENGTH)))
6778         goto end;
6779 
6780     /* Here writing 0 length early data is enough. */
6781     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
6782         || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
6783                             &readbytes),
6784             SSL_READ_EARLY_DATA_ERROR)
6785         || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6786             SSL_EARLY_DATA_ACCEPTED))
6787         goto end;
6788 
6789     if (!TEST_int_eq(SSL_export_keying_material_early(
6790                          clientssl, ckeymat1, sizeof(ckeymat1), label,
6791                          sizeof(label) - 1, context, sizeof(context) - 1),
6792             1)
6793         || !TEST_int_eq(SSL_export_keying_material_early(
6794                             clientssl, ckeymat2, sizeof(ckeymat2), label,
6795                             sizeof(label) - 1, emptycontext, 0),
6796             1)
6797         || !TEST_int_eq(SSL_export_keying_material_early(
6798                             serverssl, skeymat1, sizeof(skeymat1), label,
6799                             sizeof(label) - 1, context, sizeof(context) - 1),
6800             1)
6801         || !TEST_int_eq(SSL_export_keying_material_early(
6802                             serverssl, skeymat2, sizeof(skeymat2), label,
6803                             sizeof(label) - 1, emptycontext, 0),
6804             1)
6805         /*
6806          * Check that both sides created the same key material with the
6807          * same context.
6808          */
6809         || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6810             sizeof(skeymat1))
6811         /*
6812          * Check that both sides created the same key material with an
6813          * empty context.
6814          */
6815         || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6816             sizeof(skeymat2))
6817         /* Different contexts should produce different results */
6818         || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6819             sizeof(ckeymat2)))
6820         goto end;
6821 
6822     testresult = 1;
6823 
6824 end:
6825     SSL_SESSION_free(sess);
6826     SSL_SESSION_free(clientpsk);
6827     SSL_SESSION_free(serverpsk);
6828     clientpsk = serverpsk = NULL;
6829     SSL_free(serverssl);
6830     SSL_free(clientssl);
6831     SSL_CTX_free(sctx);
6832     SSL_CTX_free(cctx);
6833 
6834     return testresult;
6835 }
6836 
6837 #define NUM_KEY_UPDATE_MESSAGES 40
6838 /*
6839  * Test KeyUpdate.
6840  */
test_key_update(void)6841 static int test_key_update(void)
6842 {
6843     SSL_CTX *cctx = NULL, *sctx = NULL;
6844     SSL *clientssl = NULL, *serverssl = NULL;
6845     int testresult = 0, i, j;
6846     char buf[20];
6847     static char *mess = "A test message";
6848 
6849     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6850             TLS_client_method(),
6851             TLS1_3_VERSION,
6852             0,
6853             &sctx, &cctx, cert, privkey))
6854         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6855             NULL, NULL))
6856         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6857             SSL_ERROR_NONE)))
6858         goto end;
6859 
6860     for (j = 0; j < 2; j++) {
6861         /* Send lots of KeyUpdate messages */
6862         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
6863             if (!TEST_true(SSL_key_update(clientssl,
6864                     (j == 0)
6865                         ? SSL_KEY_UPDATE_NOT_REQUESTED
6866                         : SSL_KEY_UPDATE_REQUESTED))
6867                 || !TEST_true(SSL_do_handshake(clientssl)))
6868                 goto end;
6869         }
6870 
6871         /* Check that sending and receiving app data is ok */
6872         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
6873             || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
6874                 strlen(mess)))
6875             goto end;
6876 
6877         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
6878             || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
6879                 strlen(mess)))
6880             goto end;
6881     }
6882 
6883     testresult = 1;
6884 
6885 end:
6886     SSL_free(serverssl);
6887     SSL_free(clientssl);
6888     SSL_CTX_free(sctx);
6889     SSL_CTX_free(cctx);
6890 
6891     return testresult;
6892 }
6893 
6894 /*
6895  * Test we can handle a KeyUpdate (update requested) message while
6896  * write data is pending in peer.
6897  * Test 0: Client sends KeyUpdate while Server is writing
6898  * Test 1: Server sends KeyUpdate while Client is writing
6899  */
test_key_update_peer_in_write(int tst)6900 static int test_key_update_peer_in_write(int tst)
6901 {
6902     SSL_CTX *cctx = NULL, *sctx = NULL;
6903     SSL *clientssl = NULL, *serverssl = NULL;
6904     int testresult = 0;
6905     char buf[20];
6906     static char *mess = "A test message";
6907     BIO *bretry = BIO_new(bio_s_always_retry());
6908     BIO *tmp = NULL;
6909     SSL *peerupdate = NULL, *peerwrite = NULL;
6910 
6911     if (!TEST_ptr(bretry)
6912         || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6913             TLS_client_method(),
6914             TLS1_3_VERSION,
6915             0,
6916             &sctx, &cctx, cert, privkey))
6917         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6918             NULL, NULL))
6919         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6920             SSL_ERROR_NONE)))
6921         goto end;
6922 
6923     peerupdate = tst == 0 ? clientssl : serverssl;
6924     peerwrite = tst == 0 ? serverssl : clientssl;
6925 
6926     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
6927         || !TEST_int_eq(SSL_do_handshake(peerupdate), 1))
6928         goto end;
6929 
6930     /* Swap the writing endpoint's write BIO to force a retry */
6931     tmp = SSL_get_wbio(peerwrite);
6932     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6933         tmp = NULL;
6934         goto end;
6935     }
6936     SSL_set0_wbio(peerwrite, bretry);
6937     bretry = NULL;
6938 
6939     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
6940     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
6941         || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE)
6942         || !TEST_true(SSL_want_write(peerwrite))
6943         || !TEST_true(SSL_net_write_desired(peerwrite)))
6944         goto end;
6945 
6946     /* Reinstate the original writing endpoint's write BIO */
6947     SSL_set0_wbio(peerwrite, tmp);
6948     tmp = NULL;
6949 
6950     /* Now read some data - we will read the key update */
6951     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
6952         || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ)
6953         || !TEST_true(SSL_want_read(peerwrite))
6954         || !TEST_true(SSL_net_read_desired(peerwrite)))
6955         goto end;
6956 
6957     /*
6958      * Complete the write we started previously and read it from the other
6959      * endpoint
6960      */
6961     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6962         || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6963         goto end;
6964 
6965     /* Write more data to ensure we send the KeyUpdate message back */
6966     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6967         || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6968         goto end;
6969 
6970     if (!TEST_false(SSL_net_read_desired(peerwrite))
6971         || !TEST_false(SSL_net_write_desired(peerwrite))
6972         || !TEST_int_eq(SSL_want(peerwrite), SSL_NOTHING))
6973         goto end;
6974 
6975     testresult = 1;
6976 
6977 end:
6978     SSL_free(serverssl);
6979     SSL_free(clientssl);
6980     SSL_CTX_free(sctx);
6981     SSL_CTX_free(cctx);
6982     BIO_free(bretry);
6983     BIO_free(tmp);
6984 
6985     return testresult;
6986 }
6987 
6988 /*
6989  * Test we can handle a KeyUpdate (update requested) message while
6990  * peer read data is pending after peer accepted keyupdate(the msg header
6991  * had been read 5 bytes).
6992  * Test 0: Client sends KeyUpdate while Server is reading
6993  * Test 1: Server sends KeyUpdate while Client is reading
6994  */
test_key_update_peer_in_read(int tst)6995 static int test_key_update_peer_in_read(int tst)
6996 {
6997     SSL_CTX *cctx = NULL, *sctx = NULL;
6998     SSL *clientssl = NULL, *serverssl = NULL;
6999     int testresult = 0;
7000     char prbuf[515], lwbuf[515] = { 0 };
7001     static char *mess = "A test message";
7002     BIO *lbio = NULL, *pbio = NULL;
7003     SSL *local = NULL, *peer = NULL;
7004 
7005     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7006             TLS_client_method(),
7007             TLS1_3_VERSION,
7008             0,
7009             &sctx, &cctx, cert, privkey))
7010         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7011             NULL, NULL))
7012         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7013             SSL_ERROR_NONE)))
7014         goto end;
7015 
7016     local = tst == 0 ? clientssl : serverssl;
7017     peer = tst == 0 ? serverssl : clientssl;
7018 
7019     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
7020         goto end;
7021 
7022     SSL_set_bio(local, lbio, lbio);
7023     SSL_set_bio(peer, pbio, pbio);
7024 
7025     /*
7026      * we first write keyupdate msg then appdata in local
7027      * write data in local will fail with SSL_ERROR_WANT_WRITE,because
7028      * lwbuf app data msg size + key updata msg size > 512(the size of
7029      * the bio pair buffer)
7030      */
7031     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7032         || !TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), -1)
7033         || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
7034         goto end;
7035 
7036     /*
7037      * first read keyupdate msg in peer in peer
7038      * then read appdata that we know will fail with SSL_ERROR_WANT_READ
7039      */
7040     if (!TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), -1)
7041         || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_READ))
7042         goto end;
7043 
7044     /* Now write some data in peer - we will write the key update */
7045     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)))
7046         goto end;
7047 
7048     /*
7049      * write data in local previously that we will complete
7050      * read data in peer previously that we will complete
7051      */
7052     if (!TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), sizeof(lwbuf))
7053         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), sizeof(prbuf)))
7054         goto end;
7055 
7056     /* check that sending and receiving appdata ok */
7057     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7058         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
7059         goto end;
7060 
7061     testresult = 1;
7062 
7063 end:
7064     SSL_free(serverssl);
7065     SSL_free(clientssl);
7066     SSL_CTX_free(sctx);
7067     SSL_CTX_free(cctx);
7068 
7069     return testresult;
7070 }
7071 
7072 /*
7073  * Test we can't send a KeyUpdate (update requested) message while
7074  * local write data is pending.
7075  * Test 0: Client sends KeyUpdate while Client is writing
7076  * Test 1: Server sends KeyUpdate while Server is writing
7077  */
test_key_update_local_in_write(int tst)7078 static int test_key_update_local_in_write(int tst)
7079 {
7080     SSL_CTX *cctx = NULL, *sctx = NULL;
7081     SSL *clientssl = NULL, *serverssl = NULL;
7082     int testresult = 0;
7083     char buf[20];
7084     static char *mess = "A test message";
7085     BIO *bretry = BIO_new(bio_s_always_retry());
7086     BIO *tmp = NULL;
7087     SSL *local = NULL, *peer = NULL;
7088 
7089     if (!TEST_ptr(bretry)
7090         || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7091             TLS_client_method(),
7092             TLS1_3_VERSION,
7093             0,
7094             &sctx, &cctx, cert, privkey))
7095         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7096             NULL, NULL))
7097         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7098             SSL_ERROR_NONE)))
7099         goto end;
7100 
7101     local = tst == 0 ? clientssl : serverssl;
7102     peer = tst == 0 ? serverssl : clientssl;
7103 
7104     /* Swap the writing endpoint's write BIO to force a retry */
7105     tmp = SSL_get_wbio(local);
7106     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
7107         tmp = NULL;
7108         goto end;
7109     }
7110     SSL_set0_wbio(local, bretry);
7111     bretry = NULL;
7112 
7113     /* write data in local will fail with SSL_ERROR_WANT_WRITE */
7114     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), -1)
7115         || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
7116         goto end;
7117 
7118     /* Reinstate the original writing endpoint's write BIO */
7119     SSL_set0_wbio(local, tmp);
7120     tmp = NULL;
7121 
7122     /* SSL_key_update will fail, because writing in local*/
7123     if (!TEST_false(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7124         || !TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_BAD_WRITE_RETRY))
7125         goto end;
7126 
7127     ERR_clear_error();
7128     /* write data in local previously that we will complete */
7129     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)))
7130         goto end;
7131 
7132     /* SSL_key_update will succeed because there is no pending write data */
7133     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7134         || !TEST_int_eq(SSL_do_handshake(local), 1))
7135         goto end;
7136 
7137     /*
7138      * we write some appdata in local
7139      * read data in peer - we will read the keyupdate msg
7140      */
7141     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7142         || !TEST_int_eq(SSL_read(peer, buf, sizeof(buf)), strlen(mess)))
7143         goto end;
7144 
7145     /* Write more peer more data to ensure we send the keyupdate message back */
7146     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7147         || !TEST_int_eq(SSL_read(local, buf, sizeof(buf)), strlen(mess)))
7148         goto end;
7149 
7150     testresult = 1;
7151 
7152 end:
7153     SSL_free(serverssl);
7154     SSL_free(clientssl);
7155     SSL_CTX_free(sctx);
7156     SSL_CTX_free(cctx);
7157     BIO_free(bretry);
7158     BIO_free(tmp);
7159 
7160     return testresult;
7161 }
7162 
7163 /*
7164  * Test we can handle a KeyUpdate (update requested) message while
7165  * local read data is pending(the msg header had been read 5 bytes).
7166  * Test 0: Client sends KeyUpdate while Client is reading
7167  * Test 1: Server sends KeyUpdate while Server is reading
7168  */
test_key_update_local_in_read(int tst)7169 static int test_key_update_local_in_read(int tst)
7170 {
7171     SSL_CTX *cctx = NULL, *sctx = NULL;
7172     SSL *clientssl = NULL, *serverssl = NULL;
7173     int testresult = 0;
7174     char lrbuf[515], pwbuf[515] = { 0 }, prbuf[20];
7175     static char *mess = "A test message";
7176     BIO *lbio = NULL, *pbio = NULL;
7177     SSL *local = NULL, *peer = NULL;
7178 
7179     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7180             TLS_client_method(),
7181             TLS1_3_VERSION,
7182             0,
7183             &sctx, &cctx, cert, privkey))
7184         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7185             NULL, NULL))
7186         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7187             SSL_ERROR_NONE)))
7188         goto end;
7189 
7190     local = tst == 0 ? clientssl : serverssl;
7191     peer = tst == 0 ? serverssl : clientssl;
7192 
7193     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
7194         goto end;
7195 
7196     SSL_set_bio(local, lbio, lbio);
7197     SSL_set_bio(peer, pbio, pbio);
7198 
7199     /* write app data in peer will fail with SSL_ERROR_WANT_WRITE */
7200     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), -1)
7201         || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_WRITE))
7202         goto end;
7203 
7204     /* read appdata in local will fail with SSL_ERROR_WANT_READ */
7205     if (!TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), -1)
7206         || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_READ))
7207         goto end;
7208 
7209     /* SSL_do_handshake will send keyupdate msg */
7210     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7211         || !TEST_int_eq(SSL_do_handshake(local), 1))
7212         goto end;
7213 
7214     /*
7215      * write data in peer previously that we will complete
7216      * read data in local previously that we will complete
7217      */
7218     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), sizeof(pwbuf))
7219         || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), sizeof(lrbuf)))
7220         goto end;
7221 
7222     /*
7223      * write data in local
7224      * read data in peer - we will read the key update
7225      */
7226     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7227         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
7228         goto end;
7229 
7230     /* Write more peer data to ensure we send the keyupdate message back */
7231     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7232         || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), strlen(mess)))
7233         goto end;
7234 
7235     testresult = 1;
7236 
7237 end:
7238     SSL_free(serverssl);
7239     SSL_free(clientssl);
7240     SSL_CTX_free(sctx);
7241     SSL_CTX_free(cctx);
7242 
7243     return testresult;
7244 }
7245 #endif /* OSSL_NO_USABLE_TLS1_3 */
7246 
7247 /*
7248  * Test clearing a connection via SSL_clear(), or resetting it via
7249  * SSL_set_connect_state()/SSL_set_accept_state()
7250  * Test 0: SSL_set_connect_state, TLSv1.3
7251  * Test 1: SSL_set_connect_state, TLSv1.2
7252  * Test 2: SSL_set_accept_state, TLSv1.3
7253  * Test 3: SSL_set_accept_state, TLSv1.2
7254  * Test 4: SSL_clear (client), TLSv1.3
7255  * Test 5: SSL_clear (client), TLSv1.2
7256  * Test 6: SSL_clear (server), TLSv1.3
7257  * Test 7: SSL_clear (server), TLSv1.2
7258  */
test_ssl_clear(int idx)7259 static int test_ssl_clear(int idx)
7260 {
7261     SSL_CTX *cctx = NULL, *sctx = NULL;
7262     SSL *clientssl = NULL, *serverssl = NULL;
7263     SSL *writer, *reader;
7264     int testresult = 0;
7265     int tls12test, servertest, cleartest;
7266     size_t written, readbytes;
7267     const char *msg = "Hello World";
7268     unsigned char buf[5];
7269 
7270     tls12test = idx & 1;
7271     idx >>= 1;
7272     servertest = idx & 1;
7273     idx >>= 1;
7274     cleartest = idx & 1;
7275 
7276 #ifdef OPENSSL_NO_TLS1_2
7277     if (tls12test == 1)
7278         return TEST_skip("No TLSv1.2 in this build");
7279 #endif
7280 
7281     /* Create an initial connection */
7282     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7283             TLS_client_method(), TLS1_VERSION, 0,
7284             &sctx, &cctx, cert, privkey))
7285         || (tls12test
7286             && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
7287                 TLS1_2_VERSION)))
7288         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
7289             &clientssl, NULL, NULL))
7290         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7291             SSL_ERROR_NONE)))
7292         goto end;
7293 
7294     if (servertest) {
7295         writer = clientssl;
7296         reader = serverssl;
7297     } else {
7298         writer = serverssl;
7299         reader = clientssl;
7300     }
7301 
7302     /* Write some data */
7303     if (!TEST_true(SSL_write_ex(writer, msg, strlen(msg), &written))
7304         || written != strlen(msg))
7305         goto end;
7306 
7307     /*
7308      * Read a partial record. The remaining buffered data should be cleared by
7309      * the subsequent clear/reset
7310      */
7311     if (!TEST_true(SSL_read_ex(reader, buf, sizeof(buf), &readbytes))
7312         || readbytes != sizeof(buf))
7313         goto end;
7314 
7315     SSL_shutdown(clientssl);
7316     SSL_shutdown(serverssl);
7317 
7318     /* Reset/clear one SSL object in order to reuse it. We free the other one */
7319     if (servertest) {
7320         if (cleartest) {
7321             if (!TEST_true(SSL_clear(serverssl)))
7322                 goto end;
7323         } else {
7324             SSL_set_accept_state(serverssl);
7325         }
7326         SSL_free(clientssl);
7327         clientssl = NULL;
7328     } else {
7329         if (cleartest) {
7330             if (!TEST_true(SSL_clear(clientssl)))
7331                 goto end;
7332         } else {
7333             SSL_set_connect_state(clientssl);
7334         }
7335         SSL_free(serverssl);
7336         serverssl = NULL;
7337     }
7338 
7339     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7340             NULL, NULL))
7341         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7342             SSL_ERROR_NONE))
7343         || !TEST_true(servertest || SSL_session_reused(clientssl)))
7344         goto end;
7345 
7346     SSL_shutdown(clientssl);
7347     SSL_shutdown(serverssl);
7348 
7349     testresult = 1;
7350 
7351 end:
7352     SSL_free(serverssl);
7353     SSL_free(clientssl);
7354     SSL_CTX_free(sctx);
7355     SSL_CTX_free(cctx);
7356 
7357     return testresult;
7358 }
7359 
7360 /* Parse CH and retrieve any MFL extension value if present */
get_MFL_from_client_hello(BIO * bio,int * mfl_codemfl_code)7361 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
7362 {
7363     long len;
7364     unsigned char *data;
7365     PACKET pkt, pkt2, pkt3;
7366     unsigned int MFL_code = 0, type = 0;
7367 
7368     if (!TEST_uint_gt(len = BIO_get_mem_data(bio, (char **)&data), 0))
7369         goto end;
7370 
7371     memset(&pkt, 0, sizeof(pkt));
7372     memset(&pkt2, 0, sizeof(pkt2));
7373     memset(&pkt3, 0, sizeof(pkt3));
7374 
7375     if (!TEST_long_gt(len, 0)
7376         || !TEST_true(PACKET_buf_init(&pkt, data, len))
7377         /* Skip the record header */
7378         || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
7379         /* Skip the handshake message header */
7380         || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
7381         /* Skip client version and random */
7382         || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN + SSL3_RANDOM_SIZE))
7383         /* Skip session id */
7384         || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7385         /* Skip ciphers */
7386         || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
7387         /* Skip compression */
7388         || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7389         /* Extensions len */
7390         || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
7391         goto end;
7392 
7393     /* Loop through all extensions */
7394     while (PACKET_remaining(&pkt2)) {
7395         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
7396             || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
7397             goto end;
7398 
7399         if (type == TLSEXT_TYPE_max_fragment_length) {
7400             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
7401                 || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
7402                 goto end;
7403 
7404             *mfl_codemfl_code = MFL_code;
7405             return 1;
7406         }
7407     }
7408 
7409 end:
7410     return 0;
7411 }
7412 
7413 /* Maximum-Fragment-Length TLS extension mode to test */
7414 static const unsigned char max_fragment_len_test[] = {
7415     TLSEXT_max_fragment_length_512,
7416     TLSEXT_max_fragment_length_1024,
7417     TLSEXT_max_fragment_length_2048,
7418     TLSEXT_max_fragment_length_4096
7419 };
7420 
test_max_fragment_len_ext(int idx_tst)7421 static int test_max_fragment_len_ext(int idx_tst)
7422 {
7423     SSL_CTX *ctx = NULL;
7424     SSL *con = NULL;
7425     int testresult = 0, MFL_mode = 0;
7426     BIO *rbio, *wbio;
7427 
7428     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(),
7429             TLS1_VERSION, 0, NULL, &ctx, NULL,
7430             NULL)))
7431         return 0;
7432 
7433     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
7434             ctx, max_fragment_len_test[idx_tst])))
7435         goto end;
7436 
7437     con = SSL_new(ctx);
7438     if (!TEST_ptr(con))
7439         goto end;
7440 
7441     rbio = BIO_new(BIO_s_mem());
7442     wbio = BIO_new(BIO_s_mem());
7443     if (!TEST_ptr(rbio) || !TEST_ptr(wbio)) {
7444         BIO_free(rbio);
7445         BIO_free(wbio);
7446         goto end;
7447     }
7448 
7449     SSL_set_bio(con, rbio, wbio);
7450 
7451     if (!TEST_int_le(SSL_connect(con), 0)) {
7452         /* This shouldn't succeed because we don't have a server! */
7453         goto end;
7454     }
7455 
7456     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
7457         /* no MFL in client hello */
7458         goto end;
7459     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
7460         goto end;
7461 
7462     testresult = 1;
7463 
7464 end:
7465     SSL_free(con);
7466     SSL_CTX_free(ctx);
7467 
7468     return testresult;
7469 }
7470 
7471 #ifndef OSSL_NO_USABLE_TLS1_3
test_pha_key_update(void)7472 static int test_pha_key_update(void)
7473 {
7474     SSL_CTX *cctx = NULL, *sctx = NULL;
7475     SSL *clientssl = NULL, *serverssl = NULL;
7476     int testresult = 0;
7477 
7478     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7479             TLS_client_method(), TLS1_VERSION, 0,
7480             &sctx, &cctx, cert, privkey)))
7481         return 0;
7482 
7483     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
7484         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
7485         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
7486         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
7487         goto end;
7488 
7489     SSL_CTX_set_post_handshake_auth(cctx, 1);
7490 
7491     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7492             NULL, NULL)))
7493         goto end;
7494 
7495     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7496             SSL_ERROR_NONE)))
7497         goto end;
7498 
7499     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
7500     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
7501         goto end;
7502 
7503     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
7504         goto end;
7505 
7506     /* Start handshake on the server */
7507     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
7508         goto end;
7509 
7510     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
7511     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7512             SSL_ERROR_NONE)))
7513         goto end;
7514 
7515     SSL_shutdown(clientssl);
7516     SSL_shutdown(serverssl);
7517 
7518     testresult = 1;
7519 
7520 end:
7521     SSL_free(serverssl);
7522     SSL_free(clientssl);
7523     SSL_CTX_free(sctx);
7524     SSL_CTX_free(cctx);
7525     return testresult;
7526 }
7527 #endif
7528 
7529 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7530 
7531 static SRP_VBASE *vbase = NULL;
7532 
ssl_srp_cb(SSL * s,int * ad,void * arg)7533 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
7534 {
7535     int ret = SSL3_AL_FATAL;
7536     char *username;
7537     SRP_user_pwd *user = NULL;
7538 
7539     username = SSL_get_srp_username(s);
7540     if (username == NULL) {
7541         *ad = SSL_AD_INTERNAL_ERROR;
7542         goto err;
7543     }
7544 
7545     user = SRP_VBASE_get1_by_user(vbase, username);
7546     if (user == NULL) {
7547         *ad = SSL_AD_INTERNAL_ERROR;
7548         goto err;
7549     }
7550 
7551     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
7552             user->info)
7553         <= 0) {
7554         *ad = SSL_AD_INTERNAL_ERROR;
7555         goto err;
7556     }
7557 
7558     ret = 0;
7559 
7560 err:
7561     SRP_user_pwd_free(user);
7562     return ret;
7563 }
7564 
create_new_vfile(char * userid,char * password,const char * filename)7565 static int create_new_vfile(char *userid, char *password, const char *filename)
7566 {
7567     char *gNid = NULL;
7568     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
7569     TXT_DB *db = NULL;
7570     int ret = 0;
7571     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
7572     size_t i;
7573 
7574     if (!TEST_ptr(dummy) || !TEST_ptr(row))
7575         goto end;
7576 
7577     gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
7578         &row[DB_srpverifier], NULL, NULL, libctx, NULL);
7579     if (!TEST_ptr(gNid))
7580         goto end;
7581 
7582     /*
7583      * The only way to create an empty TXT_DB is to provide a BIO with no data
7584      * in it!
7585      */
7586     db = TXT_DB_read(dummy, DB_NUMBER);
7587     if (!TEST_ptr(db))
7588         goto end;
7589 
7590     out = BIO_new_file(filename, "w");
7591     if (!TEST_ptr(out))
7592         goto end;
7593 
7594     row[DB_srpid] = OPENSSL_strdup(userid);
7595     row[DB_srptype] = OPENSSL_strdup("V");
7596     row[DB_srpgN] = OPENSSL_strdup(gNid);
7597 
7598     if (!TEST_ptr(row[DB_srpid])
7599         || !TEST_ptr(row[DB_srptype])
7600         || !TEST_ptr(row[DB_srpgN])
7601         || !TEST_true(TXT_DB_insert(db, row)))
7602         goto end;
7603 
7604     row = NULL;
7605 
7606     if (TXT_DB_write(out, db) <= 0)
7607         goto end;
7608 
7609     ret = 1;
7610 end:
7611     if (row != NULL) {
7612         for (i = 0; i < DB_NUMBER; i++)
7613             OPENSSL_free(row[i]);
7614     }
7615     OPENSSL_free(row);
7616     BIO_free(dummy);
7617     BIO_free(out);
7618     TXT_DB_free(db);
7619 
7620     return ret;
7621 }
7622 
create_new_vbase(char * userid,char * password)7623 static int create_new_vbase(char *userid, char *password)
7624 {
7625     BIGNUM *verifier = NULL, *salt = NULL;
7626     const SRP_gN *lgN = NULL;
7627     SRP_user_pwd *user_pwd = NULL;
7628     int ret = 0;
7629 
7630     lgN = SRP_get_default_gN(NULL);
7631     if (!TEST_ptr(lgN))
7632         goto end;
7633 
7634     if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
7635             lgN->N, lgN->g, libctx, NULL)))
7636         goto end;
7637 
7638     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
7639     if (!TEST_ptr(user_pwd))
7640         goto end;
7641 
7642     user_pwd->N = lgN->N;
7643     user_pwd->g = lgN->g;
7644     user_pwd->id = OPENSSL_strdup(userid);
7645     if (!TEST_ptr(user_pwd->id))
7646         goto end;
7647 
7648     user_pwd->v = verifier;
7649     user_pwd->s = salt;
7650     verifier = salt = NULL;
7651 
7652     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
7653         goto end;
7654     user_pwd = NULL;
7655 
7656     ret = 1;
7657 end:
7658     SRP_user_pwd_free(user_pwd);
7659     BN_free(salt);
7660     BN_free(verifier);
7661 
7662     return ret;
7663 }
7664 
7665 /*
7666  * SRP tests
7667  *
7668  * Test 0: Simple successful SRP connection, new vbase
7669  * Test 1: Connection failure due to bad password, new vbase
7670  * Test 2: Simple successful SRP connection, vbase loaded from existing file
7671  * Test 3: Connection failure due to bad password, vbase loaded from existing
7672  *         file
7673  * Test 4: Simple successful SRP connection, vbase loaded from new file
7674  * Test 5: Connection failure due to bad password, vbase loaded from new file
7675  */
test_srp(int tst)7676 static int test_srp(int tst)
7677 {
7678     char *userid = "test", *password = "password", *tstsrpfile;
7679     SSL_CTX *cctx = NULL, *sctx = NULL;
7680     SSL *clientssl = NULL, *serverssl = NULL;
7681     int ret, testresult = 0;
7682 
7683     vbase = SRP_VBASE_new(NULL);
7684     if (!TEST_ptr(vbase))
7685         goto end;
7686 
7687     if (tst == 0 || tst == 1) {
7688         if (!TEST_true(create_new_vbase(userid, password)))
7689             goto end;
7690     } else {
7691         if (tst == 4 || tst == 5) {
7692             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
7693                 goto end;
7694             tstsrpfile = tmpfilename;
7695         } else {
7696             tstsrpfile = srpvfile;
7697         }
7698         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
7699             goto end;
7700     }
7701 
7702     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7703             TLS_client_method(), TLS1_VERSION, 0,
7704             &sctx, &cctx, cert, privkey)))
7705         goto end;
7706 
7707     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
7708         || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
7709         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
7710         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
7711         || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
7712         goto end;
7713 
7714     if (tst % 2 == 1) {
7715         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
7716             goto end;
7717     } else {
7718         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
7719             goto end;
7720     }
7721 
7722     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7723             NULL, NULL)))
7724         goto end;
7725 
7726     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
7727     if (ret) {
7728         if (!TEST_true(tst % 2 == 0))
7729             goto end;
7730     } else {
7731         if (!TEST_true(tst % 2 == 1))
7732             goto end;
7733     }
7734 
7735     testresult = 1;
7736 
7737 end:
7738     SRP_VBASE_free(vbase);
7739     vbase = NULL;
7740     SSL_free(serverssl);
7741     SSL_free(clientssl);
7742     SSL_CTX_free(sctx);
7743     SSL_CTX_free(cctx);
7744 
7745     return testresult;
7746 }
7747 #endif
7748 
7749 static int info_cb_failed = 0;
7750 static int info_cb_offset = 0;
7751 static int info_cb_this_state = -1;
7752 
7753 static struct info_cb_states_st {
7754     int where;
7755     const char *statestr;
7756 } info_cb_states[][60] = {
7757     {
7758         /* TLSv1.2 server followed by resumption */
7759         { SSL_CB_HANDSHAKE_START, NULL },
7760         { SSL_CB_LOOP, "PINIT" },
7761         { SSL_CB_LOOP, "PINIT" },
7762         { SSL_CB_LOOP, "TRCH" },
7763         { SSL_CB_LOOP, "TWSH" },
7764         { SSL_CB_LOOP, "TWSC" },
7765         { SSL_CB_LOOP, "TWSKE" },
7766         { SSL_CB_LOOP, "TWSD" },
7767         { SSL_CB_EXIT, NULL },
7768         { SSL_CB_LOOP, "TWSD" },
7769         { SSL_CB_LOOP, "TRCKE" },
7770         { SSL_CB_LOOP, "TRCCS" },
7771         { SSL_CB_LOOP, "TRFIN" },
7772         { SSL_CB_LOOP, "TWST" },
7773         { SSL_CB_LOOP, "TWCCS" },
7774         { SSL_CB_LOOP, "TWFIN" },
7775         { SSL_CB_HANDSHAKE_DONE, NULL },
7776         { SSL_CB_EXIT, NULL },
7777         { SSL_CB_ALERT, NULL },
7778         { SSL_CB_HANDSHAKE_START, NULL },
7779         { SSL_CB_LOOP, "PINIT" },
7780         { SSL_CB_LOOP, "PINIT" },
7781         { SSL_CB_LOOP, "TRCH" },
7782         { SSL_CB_LOOP, "TWSH" },
7783         { SSL_CB_LOOP, "TWCCS" },
7784         { SSL_CB_LOOP, "TWFIN" },
7785         { SSL_CB_EXIT, NULL },
7786         { SSL_CB_LOOP, "TWFIN" },
7787         { SSL_CB_LOOP, "TRCCS" },
7788         { SSL_CB_LOOP, "TRFIN" },
7789         { SSL_CB_HANDSHAKE_DONE, NULL },
7790         { SSL_CB_EXIT, NULL },
7791         { 0, NULL },
7792     },
7793     {
7794         /* TLSv1.2 client followed by resumption */
7795         { SSL_CB_HANDSHAKE_START, NULL },
7796         { SSL_CB_LOOP, "PINIT" },
7797         { SSL_CB_LOOP, "TWCH" },
7798         { SSL_CB_EXIT, NULL },
7799         { SSL_CB_LOOP, "TWCH" },
7800         { SSL_CB_LOOP, "TRSH" },
7801         { SSL_CB_LOOP, "TRSC" },
7802         { SSL_CB_LOOP, "TRSKE" },
7803         { SSL_CB_LOOP, "TRSD" },
7804         { SSL_CB_LOOP, "TWCKE" },
7805         { SSL_CB_LOOP, "TWCCS" },
7806         { SSL_CB_LOOP, "TWFIN" },
7807         { SSL_CB_EXIT, NULL },
7808         { SSL_CB_LOOP, "TWFIN" },
7809         { SSL_CB_LOOP, "TRST" },
7810         { SSL_CB_LOOP, "TRCCS" },
7811         { SSL_CB_LOOP, "TRFIN" },
7812         { SSL_CB_HANDSHAKE_DONE, NULL },
7813         { SSL_CB_EXIT, NULL },
7814         { SSL_CB_ALERT, NULL },
7815         { SSL_CB_HANDSHAKE_START, NULL },
7816         { SSL_CB_LOOP, "PINIT" },
7817         { SSL_CB_LOOP, "TWCH" },
7818         { SSL_CB_EXIT, NULL },
7819         { SSL_CB_LOOP, "TWCH" },
7820         { SSL_CB_LOOP, "TRSH" },
7821         { SSL_CB_LOOP, "TRCCS" },
7822         { SSL_CB_LOOP, "TRFIN" },
7823         { SSL_CB_LOOP, "TWCCS" },
7824         { SSL_CB_LOOP, "TWFIN" },
7825         { SSL_CB_HANDSHAKE_DONE, NULL },
7826         { SSL_CB_EXIT, NULL },
7827         { 0, NULL },
7828     },
7829     {
7830         /* TLSv1.3 server followed by resumption */
7831         { SSL_CB_HANDSHAKE_START, NULL },
7832         { SSL_CB_LOOP, "PINIT" },
7833         { SSL_CB_LOOP, "PINIT" },
7834         { SSL_CB_LOOP, "TRCH" },
7835         { SSL_CB_LOOP, "TWSH" },
7836         { SSL_CB_LOOP, "TWCCS" },
7837         { SSL_CB_LOOP, "TWEE" },
7838         { SSL_CB_LOOP, "TWSC" },
7839         { SSL_CB_LOOP, "TWSCV" },
7840         { SSL_CB_LOOP, "TWFIN" },
7841         { SSL_CB_LOOP, "TED" },
7842         { SSL_CB_EXIT, NULL },
7843         { SSL_CB_LOOP, "TED" },
7844         { SSL_CB_LOOP, "TRFIN" },
7845         { SSL_CB_HANDSHAKE_DONE, NULL },
7846         { SSL_CB_LOOP, "TWST" },
7847         { SSL_CB_LOOP, "TWST" },
7848         { SSL_CB_EXIT, NULL },
7849         { SSL_CB_ALERT, NULL },
7850         { SSL_CB_HANDSHAKE_START, NULL },
7851         { SSL_CB_LOOP, "PINIT" },
7852         { SSL_CB_LOOP, "PINIT" },
7853         { SSL_CB_LOOP, "TRCH" },
7854         { SSL_CB_LOOP, "TWSH" },
7855         { SSL_CB_LOOP, "TWCCS" },
7856         { SSL_CB_LOOP, "TWEE" },
7857         { SSL_CB_LOOP, "TWFIN" },
7858         { SSL_CB_LOOP, "TED" },
7859         { SSL_CB_EXIT, NULL },
7860         { SSL_CB_LOOP, "TED" },
7861         { SSL_CB_LOOP, "TRFIN" },
7862         { SSL_CB_HANDSHAKE_DONE, NULL },
7863         { SSL_CB_LOOP, "TWST" },
7864         { SSL_CB_EXIT, NULL },
7865         { 0, NULL },
7866     },
7867     {
7868         /* TLSv1.3 client followed by resumption */
7869         { SSL_CB_HANDSHAKE_START, NULL },
7870         { SSL_CB_LOOP, "PINIT" },
7871         { SSL_CB_LOOP, "TWCH" },
7872         { SSL_CB_EXIT, NULL },
7873         { SSL_CB_LOOP, "TWCH" },
7874         { SSL_CB_LOOP, "TRSH" },
7875         { SSL_CB_LOOP, "TREE" },
7876         { SSL_CB_LOOP, "TRSC" },
7877         { SSL_CB_LOOP, "TRSCV" },
7878         { SSL_CB_LOOP, "TRFIN" },
7879         { SSL_CB_LOOP, "TWCCS" },
7880         { SSL_CB_LOOP, "TWFIN" },
7881         { SSL_CB_HANDSHAKE_DONE, NULL },
7882         { SSL_CB_EXIT, NULL },
7883         { SSL_CB_LOOP, "SSLOK" },
7884         { SSL_CB_LOOP, "SSLOK" },
7885         { SSL_CB_LOOP, "TRST" },
7886         { SSL_CB_EXIT, NULL },
7887         { SSL_CB_LOOP, "SSLOK" },
7888         { SSL_CB_LOOP, "SSLOK" },
7889         { SSL_CB_LOOP, "TRST" },
7890         { SSL_CB_EXIT, NULL },
7891         { SSL_CB_ALERT, NULL },
7892         { SSL_CB_HANDSHAKE_START, NULL },
7893         { SSL_CB_LOOP, "PINIT" },
7894         { SSL_CB_LOOP, "TWCH" },
7895         { SSL_CB_EXIT, NULL },
7896         { SSL_CB_LOOP, "TWCH" },
7897         { SSL_CB_LOOP, "TRSH" },
7898         { SSL_CB_LOOP, "TREE" },
7899         { SSL_CB_LOOP, "TRFIN" },
7900         { SSL_CB_LOOP, "TWCCS" },
7901         { SSL_CB_LOOP, "TWFIN" },
7902         { SSL_CB_HANDSHAKE_DONE, NULL },
7903         { SSL_CB_EXIT, NULL },
7904         { SSL_CB_LOOP, "SSLOK" },
7905         { SSL_CB_LOOP, "SSLOK" },
7906         { SSL_CB_LOOP, "TRST" },
7907         { SSL_CB_EXIT, NULL },
7908         { 0, NULL },
7909     },
7910     {
7911         /* TLSv1.3 server, early_data */
7912         { SSL_CB_HANDSHAKE_START, NULL },
7913         { SSL_CB_LOOP, "PINIT" },
7914         { SSL_CB_LOOP, "PINIT" },
7915         { SSL_CB_LOOP, "TRCH" },
7916         { SSL_CB_LOOP, "TWSH" },
7917         { SSL_CB_LOOP, "TWCCS" },
7918         { SSL_CB_LOOP, "TWEE" },
7919         { SSL_CB_LOOP, "TWFIN" },
7920         { SSL_CB_HANDSHAKE_DONE, NULL },
7921         { SSL_CB_EXIT, NULL },
7922         { SSL_CB_HANDSHAKE_START, NULL },
7923         { SSL_CB_LOOP, "TED" },
7924         { SSL_CB_LOOP, "TED" },
7925         { SSL_CB_LOOP, "TWEOED" },
7926         { SSL_CB_LOOP, "TRFIN" },
7927         { SSL_CB_HANDSHAKE_DONE, NULL },
7928         { SSL_CB_LOOP, "TWST" },
7929         { SSL_CB_EXIT, NULL },
7930         { 0, NULL },
7931     },
7932     {
7933         /* TLSv1.3 client, early_data */
7934         { SSL_CB_HANDSHAKE_START, NULL },
7935         { SSL_CB_LOOP, "PINIT" },
7936         { SSL_CB_LOOP, "TWCH" },
7937         { SSL_CB_LOOP, "TWCCS" },
7938         { SSL_CB_HANDSHAKE_DONE, NULL },
7939         { SSL_CB_EXIT, NULL },
7940         { SSL_CB_HANDSHAKE_START, NULL },
7941         { SSL_CB_LOOP, "TED" },
7942         { SSL_CB_LOOP, "TED" },
7943         { SSL_CB_LOOP, "TRSH" },
7944         { SSL_CB_LOOP, "TREE" },
7945         { SSL_CB_LOOP, "TRFIN" },
7946         { SSL_CB_LOOP, "TPEDE" },
7947         { SSL_CB_LOOP, "TWEOED" },
7948         { SSL_CB_LOOP, "TWFIN" },
7949         { SSL_CB_HANDSHAKE_DONE, NULL },
7950         { SSL_CB_EXIT, NULL },
7951         { SSL_CB_LOOP, "SSLOK" },
7952         { SSL_CB_LOOP, "SSLOK" },
7953         { SSL_CB_LOOP, "TRST" },
7954         { SSL_CB_EXIT, NULL },
7955         { 0, NULL },
7956     },
7957     {
7958         /* TLSv1.3 server, certificate compression, followed by resumption */
7959         { SSL_CB_HANDSHAKE_START, NULL },
7960         { SSL_CB_LOOP, "PINIT" },
7961         { SSL_CB_LOOP, "PINIT" },
7962         { SSL_CB_LOOP, "TRCH" },
7963         { SSL_CB_LOOP, "TWSH" },
7964         { SSL_CB_LOOP, "TWCCS" },
7965         { SSL_CB_LOOP, "TWEE" },
7966         { SSL_CB_LOOP, "TWSCC" },
7967         { SSL_CB_LOOP, "TWSCV" },
7968         { SSL_CB_LOOP, "TWFIN" },
7969         { SSL_CB_LOOP, "TED" },
7970         { SSL_CB_EXIT, NULL },
7971         { SSL_CB_LOOP, "TED" },
7972         { SSL_CB_LOOP, "TRFIN" },
7973         { SSL_CB_HANDSHAKE_DONE, NULL },
7974         { SSL_CB_LOOP, "TWST" },
7975         { SSL_CB_LOOP, "TWST" },
7976         { SSL_CB_EXIT, NULL },
7977         { SSL_CB_ALERT, NULL },
7978         { SSL_CB_HANDSHAKE_START, NULL },
7979         { SSL_CB_LOOP, "PINIT" },
7980         { SSL_CB_LOOP, "PINIT" },
7981         { SSL_CB_LOOP, "TRCH" },
7982         { SSL_CB_LOOP, "TWSH" },
7983         { SSL_CB_LOOP, "TWCCS" },
7984         { SSL_CB_LOOP, "TWEE" },
7985         { SSL_CB_LOOP, "TWFIN" },
7986         { SSL_CB_LOOP, "TED" },
7987         { SSL_CB_EXIT, NULL },
7988         { SSL_CB_LOOP, "TED" },
7989         { SSL_CB_LOOP, "TRFIN" },
7990         { SSL_CB_HANDSHAKE_DONE, NULL },
7991         { SSL_CB_LOOP, "TWST" },
7992         { SSL_CB_EXIT, NULL },
7993         { 0, NULL },
7994     },
7995     {
7996         /* TLSv1.3 client, certificate compression, followed by resumption */
7997         { SSL_CB_HANDSHAKE_START, NULL },
7998         { SSL_CB_LOOP, "PINIT" },
7999         { SSL_CB_LOOP, "TWCH" },
8000         { SSL_CB_EXIT, NULL },
8001         { SSL_CB_LOOP, "TWCH" },
8002         { SSL_CB_LOOP, "TRSH" },
8003         { SSL_CB_LOOP, "TREE" },
8004         { SSL_CB_LOOP, "TRSCC" },
8005         { SSL_CB_LOOP, "TRSCV" },
8006         { SSL_CB_LOOP, "TRFIN" },
8007         { SSL_CB_LOOP, "TWCCS" },
8008         { SSL_CB_LOOP, "TWFIN" },
8009         { SSL_CB_HANDSHAKE_DONE, NULL },
8010         { SSL_CB_EXIT, NULL },
8011         { SSL_CB_LOOP, "SSLOK" },
8012         { SSL_CB_LOOP, "SSLOK" },
8013         { SSL_CB_LOOP, "TRST" },
8014         { SSL_CB_EXIT, NULL },
8015         { SSL_CB_LOOP, "SSLOK" },
8016         { SSL_CB_LOOP, "SSLOK" },
8017         { SSL_CB_LOOP, "TRST" },
8018         { SSL_CB_EXIT, NULL },
8019         { SSL_CB_ALERT, NULL },
8020         { SSL_CB_HANDSHAKE_START, NULL },
8021         { SSL_CB_LOOP, "PINIT" },
8022         { SSL_CB_LOOP, "TWCH" },
8023         { SSL_CB_EXIT, NULL },
8024         { SSL_CB_LOOP, "TWCH" },
8025         { SSL_CB_LOOP, "TRSH" },
8026         { SSL_CB_LOOP, "TREE" },
8027         { SSL_CB_LOOP, "TRFIN" },
8028         { SSL_CB_LOOP, "TWCCS" },
8029         { SSL_CB_LOOP, "TWFIN" },
8030         { SSL_CB_HANDSHAKE_DONE, NULL },
8031         { SSL_CB_EXIT, NULL },
8032         { SSL_CB_LOOP, "SSLOK" },
8033         { SSL_CB_LOOP, "SSLOK" },
8034         { SSL_CB_LOOP, "TRST" },
8035         { SSL_CB_EXIT, NULL },
8036         { 0, NULL },
8037     },
8038     {
8039         { 0, NULL },
8040     }
8041 };
8042 
sslapi_info_callback(const SSL * s,int where,int ret)8043 static void sslapi_info_callback(const SSL *s, int where, int ret)
8044 {
8045     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
8046 
8047     /* We do not ever expect a connection to fail in this test */
8048     if (!TEST_false(ret == 0)) {
8049         info_cb_failed = 1;
8050         return;
8051     }
8052 
8053     /*
8054      * Do some sanity checks. We never expect these things to happen in this
8055      * test
8056      */
8057     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
8058         || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
8059         || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
8060         info_cb_failed = 1;
8061         return;
8062     }
8063 
8064     /* Now check we're in the right state */
8065     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
8066         info_cb_failed = 1;
8067         return;
8068     }
8069     if ((where & SSL_CB_LOOP) != 0
8070         && !TEST_int_eq(strcmp(SSL_state_string(s),
8071                             state[info_cb_this_state].statestr),
8072             0)) {
8073         info_cb_failed = 1;
8074         return;
8075     }
8076 
8077     /*
8078      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
8079      */
8080     if ((where & SSL_CB_HANDSHAKE_DONE)
8081         && SSL_in_init((SSL *)s) != 0) {
8082         info_cb_failed = 1;
8083         return;
8084     }
8085 }
8086 
8087 /*
8088  * Test the info callback gets called when we expect it to.
8089  *
8090  * Test 0: TLSv1.2, server
8091  * Test 1: TLSv1.2, client
8092  * Test 2: TLSv1.3, server
8093  * Test 3: TLSv1.3, client
8094  * Test 4: TLSv1.3, server, early_data
8095  * Test 5: TLSv1.3, client, early_data
8096  * Test 6: TLSv1.3, server, compressed certificate
8097  * Test 7: TLSv1.3, client, compressed certificate
8098  */
test_info_callback(int tst)8099 static int test_info_callback(int tst)
8100 {
8101     SSL_CTX *cctx = NULL, *sctx = NULL;
8102     SSL *clientssl = NULL, *serverssl = NULL;
8103     SSL_SESSION *clntsess = NULL;
8104     int testresult = 0;
8105     int tlsvers;
8106 
8107     if (tst < 2) {
8108 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
8109 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH))
8110         tlsvers = TLS1_2_VERSION;
8111 #else
8112         return 1;
8113 #endif
8114     } else {
8115 #ifndef OSSL_NO_USABLE_TLS1_3
8116         tlsvers = TLS1_3_VERSION;
8117 #else
8118         return 1;
8119 #endif
8120     }
8121 
8122     /* Reset globals */
8123     info_cb_failed = 0;
8124     info_cb_this_state = -1;
8125     info_cb_offset = tst;
8126 
8127 #ifndef OSSL_NO_USABLE_TLS1_3
8128     if (tst >= 4 && tst < 6) {
8129         SSL_SESSION *sess = NULL;
8130         size_t written, readbytes;
8131         unsigned char buf[80];
8132         OSSL_TIME timer;
8133 
8134         /* early_data tests */
8135         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
8136                 &serverssl, &sess, 0,
8137                 SHA384_DIGEST_LENGTH)))
8138             goto end;
8139 
8140         /* We don't actually need this reference */
8141         SSL_SESSION_free(sess);
8142 
8143         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
8144             sslapi_info_callback);
8145 
8146         /* Write and read some early data and then complete the connection */
8147         timer = ossl_time_now();
8148         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
8149                 &written))
8150             || !TEST_size_t_eq(written, strlen(MSG1)))
8151             goto end;
8152 
8153         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf,
8154                              sizeof(buf), &readbytes),
8155                 SSL_READ_EARLY_DATA_SUCCESS)) {
8156             testresult = check_early_data_timeout(timer);
8157             goto end;
8158         }
8159 
8160         if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
8161             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
8162                 SSL_EARLY_DATA_ACCEPTED)
8163             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8164                 SSL_ERROR_NONE))
8165             || !TEST_false(info_cb_failed))
8166             goto end;
8167 
8168         testresult = 1;
8169         goto end;
8170     }
8171 #endif
8172 
8173     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8174             TLS_client_method(),
8175             tlsvers, tlsvers, &sctx, &cctx, cert,
8176             privkey)))
8177         goto end;
8178 
8179     if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
8180         goto end;
8181 
8182     /*
8183      * For even numbered tests we check the server callbacks. For odd numbers we
8184      * check the client.
8185      */
8186     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
8187         sslapi_info_callback);
8188     if (tst >= 6) {
8189         if (!SSL_CTX_compress_certs(sctx, 0))
8190             goto end;
8191     }
8192 
8193     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
8194             &clientssl, NULL, NULL))
8195         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8196             SSL_ERROR_NONE))
8197         || !TEST_false(info_cb_failed))
8198         goto end;
8199 
8200     clntsess = SSL_get1_session(clientssl);
8201     SSL_shutdown(clientssl);
8202     SSL_shutdown(serverssl);
8203     SSL_free(serverssl);
8204     SSL_free(clientssl);
8205     serverssl = clientssl = NULL;
8206 
8207     /* Now do a resumption */
8208     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8209             NULL))
8210         || !TEST_true(SSL_set_session(clientssl, clntsess))
8211         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8212             SSL_ERROR_NONE))
8213         || !TEST_true(SSL_session_reused(clientssl))
8214         || !TEST_false(info_cb_failed))
8215         goto end;
8216 
8217     testresult = 1;
8218 
8219 end:
8220     SSL_free(serverssl);
8221     SSL_free(clientssl);
8222     SSL_SESSION_free(clntsess);
8223     SSL_CTX_free(sctx);
8224     SSL_CTX_free(cctx);
8225     return testresult;
8226 }
8227 
test_ssl_pending(int tst)8228 static int test_ssl_pending(int tst)
8229 {
8230     SSL_CTX *cctx = NULL, *sctx = NULL;
8231     SSL *clientssl = NULL, *serverssl = NULL;
8232     int testresult = 0;
8233     char msg[] = "A test message";
8234     char buf[5];
8235     size_t written, readbytes;
8236 
8237     if (tst == 0) {
8238         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8239                 TLS_client_method(),
8240                 TLS1_VERSION, 0,
8241                 &sctx, &cctx, cert, privkey)))
8242             goto end;
8243     } else {
8244 #ifndef OPENSSL_NO_DTLS
8245         if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
8246                 DTLS_client_method(),
8247                 DTLS1_VERSION, 0,
8248                 &sctx, &cctx, cert, privkey)))
8249             goto end;
8250 
8251 #ifdef OPENSSL_NO_DTLS1_2
8252         /* Not supported in the FIPS provider */
8253         if (is_fips) {
8254             testresult = 1;
8255             goto end;
8256         };
8257         /*
8258          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
8259          * level 0
8260          */
8261         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
8262             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
8263                 "DEFAULT:@SECLEVEL=0")))
8264             goto end;
8265 #endif
8266 #else
8267         return 1;
8268 #endif
8269     }
8270 
8271     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8272             NULL, NULL))
8273         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8274             SSL_ERROR_NONE)))
8275         goto end;
8276 
8277     if (!TEST_int_eq(SSL_pending(clientssl), 0)
8278         || !TEST_false(SSL_has_pending(clientssl))
8279         || !TEST_int_eq(SSL_pending(serverssl), 0)
8280         || !TEST_false(SSL_has_pending(serverssl))
8281         || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8282         || !TEST_size_t_eq(written, sizeof(msg))
8283         || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
8284         || !TEST_size_t_eq(readbytes, sizeof(buf))
8285         || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
8286         || !TEST_true(SSL_has_pending(clientssl)))
8287         goto end;
8288 
8289     testresult = 1;
8290 
8291 end:
8292     SSL_free(serverssl);
8293     SSL_free(clientssl);
8294     SSL_CTX_free(sctx);
8295     SSL_CTX_free(cctx);
8296 
8297     return testresult;
8298 }
8299 
8300 static struct {
8301     unsigned int maxprot;
8302     const char *clntciphers;
8303     const char *clnttls13ciphers;
8304     const char *srvrciphers;
8305     const char *srvrtls13ciphers;
8306     const char *shared;
8307     const char *fipsshared;
8308 } shared_ciphers_data[] = {
8309 /*
8310  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
8311  * TLSv1.3 is enabled but TLSv1.2 is disabled.
8312  */
8313 #if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
8314     { TLS1_2_VERSION,
8315         "AES128-SHA:AES256-SHA",
8316         NULL,
8317         "AES256-SHA:DHE-RSA-AES128-SHA",
8318         NULL,
8319         "AES256-SHA",
8320         "AES256-SHA" },
8321 #if !defined(OPENSSL_NO_CHACHA)      \
8322     && !defined(OPENSSL_NO_POLY1305) \
8323     && !defined(OPENSSL_NO_EC)
8324     { TLS1_2_VERSION,
8325         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8326         NULL,
8327         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8328         NULL,
8329         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8330         "AES128-SHA" },
8331 #endif
8332     { TLS1_2_VERSION,
8333         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
8334         NULL,
8335         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
8336         NULL,
8337         "AES128-SHA:AES256-SHA",
8338         "AES128-SHA:AES256-SHA" },
8339     { TLS1_2_VERSION,
8340         "AES128-SHA:AES256-SHA",
8341         NULL,
8342         "AES128-SHA:DHE-RSA-AES128-SHA",
8343         NULL,
8344         "AES128-SHA",
8345         "AES128-SHA" },
8346     { TLS1_2_VERSION,
8347         "AES256-SHA",
8348         NULL,
8349         "AES128-SHA",
8350         NULL,
8351         "",
8352         "" },
8353 #endif
8354 /*
8355  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
8356  * enabled.
8357  */
8358 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
8359     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
8360     { TLS1_3_VERSION,
8361         "AES128-SHA:AES256-SHA",
8362         NULL,
8363         "AES256-SHA:AES128-SHA256",
8364         NULL,
8365         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
8366         "TLS_AES_128_GCM_SHA256:AES256-SHA",
8367         "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA" },
8368 #endif
8369 #ifndef OSSL_NO_USABLE_TLS1_3
8370     { TLS1_3_VERSION,
8371         "AES128-SHA",
8372         "TLS_AES_256_GCM_SHA384",
8373         "AES256-SHA",
8374         "TLS_AES_256_GCM_SHA384",
8375         "TLS_AES_256_GCM_SHA384",
8376         "TLS_AES_256_GCM_SHA384" },
8377     { TLS1_3_VERSION,
8378         "AES128-SHA",
8379         "TLS_AES_128_GCM_SHA256",
8380         "AES256-SHA",
8381         "TLS_AES_256_GCM_SHA384",
8382         "",
8383         "" },
8384 #endif
8385 };
8386 
int_test_ssl_get_shared_ciphers(int tst,int clnt)8387 static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
8388 {
8389     SSL_CTX *cctx = NULL, *sctx = NULL;
8390     SSL *clientssl = NULL, *serverssl = NULL;
8391     int testresult = 0;
8392     char buf[1024];
8393     OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
8394     const char *expbuf = is_fips ? shared_ciphers_data[tst].fipsshared
8395                                  : shared_ciphers_data[tst].shared;
8396     int handshakeok = strcmp(expbuf, "") != 0;
8397 
8398     if (!TEST_ptr(tmplibctx))
8399         goto end;
8400 
8401     /*
8402      * Regardless of whether we're testing with the FIPS provider loaded into
8403      * libctx, we want one peer to always use the full set of ciphersuites
8404      * available. Therefore we use a separate libctx with the default provider
8405      * loaded into it. We run the same tests twice - once with the client side
8406      * having the full set of ciphersuites and once with the server side.
8407      */
8408     if (clnt) {
8409         cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
8410         if (!TEST_ptr(cctx))
8411             goto end;
8412     } else {
8413         sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
8414         if (!TEST_ptr(sctx))
8415             goto end;
8416     }
8417 
8418     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8419             TLS_client_method(),
8420             TLS1_VERSION,
8421             shared_ciphers_data[tst].maxprot,
8422             &sctx, &cctx, cert, privkey)))
8423         goto end;
8424 
8425     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
8426             shared_ciphers_data[tst].clntciphers))
8427         || (shared_ciphers_data[tst].clnttls13ciphers != NULL
8428             && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
8429                 shared_ciphers_data[tst].clnttls13ciphers)))
8430         || !TEST_true(SSL_CTX_set_cipher_list(sctx,
8431             shared_ciphers_data[tst].srvrciphers))
8432         || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
8433             && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
8434                 shared_ciphers_data[tst].srvrtls13ciphers))))
8435         goto end;
8436 
8437     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8438             NULL)))
8439         goto end;
8440 
8441     if (handshakeok) {
8442         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8443                 SSL_ERROR_NONE)))
8444             goto end;
8445     } else {
8446         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
8447                 SSL_ERROR_NONE)))
8448             goto end;
8449     }
8450 
8451     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
8452         || !TEST_int_eq(strcmp(buf, expbuf), 0)) {
8453         TEST_info("Shared ciphers are: %s\n", buf);
8454         goto end;
8455     }
8456 
8457     testresult = 1;
8458 
8459 end:
8460     SSL_free(serverssl);
8461     SSL_free(clientssl);
8462     SSL_CTX_free(sctx);
8463     SSL_CTX_free(cctx);
8464     OSSL_LIB_CTX_free(tmplibctx);
8465 
8466     return testresult;
8467 }
8468 
test_ssl_get_shared_ciphers(int tst)8469 static int test_ssl_get_shared_ciphers(int tst)
8470 {
8471     return int_test_ssl_get_shared_ciphers(tst, 0)
8472         && int_test_ssl_get_shared_ciphers(tst, 1);
8473 }
8474 
8475 static const char *appdata = "Hello World";
8476 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
8477 static int tick_key_renew = 0;
8478 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8479 
gen_tick_cb(SSL * s,void * arg)8480 static int gen_tick_cb(SSL *s, void *arg)
8481 {
8482     gen_tick_called = 1;
8483 
8484     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
8485         strlen(appdata));
8486 }
8487 
dec_tick_cb(SSL * s,SSL_SESSION * ss,const unsigned char * keyname,size_t keyname_length,SSL_TICKET_STATUS status,void * arg)8488 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
8489     const unsigned char *keyname,
8490     size_t keyname_length,
8491     SSL_TICKET_STATUS status,
8492     void *arg)
8493 {
8494     void *tickdata;
8495     size_t tickdlen;
8496 
8497     dec_tick_called = 1;
8498 
8499     if (status == SSL_TICKET_EMPTY)
8500         return SSL_TICKET_RETURN_IGNORE_RENEW;
8501 
8502     if (!TEST_true(status == SSL_TICKET_SUCCESS
8503             || status == SSL_TICKET_SUCCESS_RENEW))
8504         return SSL_TICKET_RETURN_ABORT;
8505 
8506     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
8507             &tickdlen))
8508         || !TEST_size_t_eq(tickdlen, strlen(appdata))
8509         || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
8510         return SSL_TICKET_RETURN_ABORT;
8511 
8512     if (tick_key_cb_called) {
8513         /* Don't change what the ticket key callback wanted to do */
8514         switch (status) {
8515         case SSL_TICKET_NO_DECRYPT:
8516             return SSL_TICKET_RETURN_IGNORE_RENEW;
8517 
8518         case SSL_TICKET_SUCCESS:
8519             return SSL_TICKET_RETURN_USE;
8520 
8521         case SSL_TICKET_SUCCESS_RENEW:
8522             return SSL_TICKET_RETURN_USE_RENEW;
8523 
8524         default:
8525             return SSL_TICKET_RETURN_ABORT;
8526         }
8527     }
8528     return tick_dec_ret;
8529 }
8530 
8531 #ifndef OPENSSL_NO_DEPRECATED_3_0
tick_key_cb(SSL * s,unsigned char key_name[16],unsigned char iv[EVP_MAX_IV_LENGTH],EVP_CIPHER_CTX * ctx,HMAC_CTX * hctx,int enc)8532 static int tick_key_cb(SSL *s, unsigned char key_name[16],
8533     unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
8534     HMAC_CTX *hctx, int enc)
8535 {
8536     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8537     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
8538     EVP_CIPHER *aes128cbc;
8539     EVP_MD *sha256;
8540     int ret;
8541 
8542     tick_key_cb_called = 1;
8543 
8544     if (tick_key_renew == -1)
8545         return 0;
8546 
8547     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8548     if (!TEST_ptr(aes128cbc))
8549         return 0;
8550     sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
8551     if (!TEST_ptr(sha256)) {
8552         EVP_CIPHER_free(aes128cbc);
8553         return 0;
8554     }
8555 
8556     memset(iv, 0, AES_BLOCK_SIZE);
8557     memset(key_name, 0, 16);
8558     if (aes128cbc == NULL
8559         || sha256 == NULL
8560         || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8561         || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
8562             NULL))
8563         ret = -1;
8564     else
8565         ret = tick_key_renew ? 2 : 1;
8566 
8567     EVP_CIPHER_free(aes128cbc);
8568     EVP_MD_free(sha256);
8569 
8570     return ret;
8571 }
8572 #endif
8573 
tick_key_evp_cb(SSL * s,unsigned char key_name[16],unsigned char iv[EVP_MAX_IV_LENGTH],EVP_CIPHER_CTX * ctx,EVP_MAC_CTX * hctx,int enc)8574 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
8575     unsigned char iv[EVP_MAX_IV_LENGTH],
8576     EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
8577 {
8578     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8579     unsigned char tick_hmac_key[16] = "0123456789abcdef";
8580     OSSL_PARAM params[2];
8581     EVP_CIPHER *aes128cbc;
8582     int ret;
8583 
8584     tick_key_cb_called = 1;
8585 
8586     if (tick_key_renew == -1)
8587         return 0;
8588 
8589     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8590     if (!TEST_ptr(aes128cbc))
8591         return 0;
8592 
8593     memset(iv, 0, AES_BLOCK_SIZE);
8594     memset(key_name, 0, 16);
8595     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
8596         "SHA256", 0);
8597     params[1] = OSSL_PARAM_construct_end();
8598     if (aes128cbc == NULL
8599         || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8600         || !EVP_MAC_init(hctx, tick_hmac_key, sizeof(tick_hmac_key),
8601             params))
8602         ret = -1;
8603     else
8604         ret = tick_key_renew ? 2 : 1;
8605 
8606     EVP_CIPHER_free(aes128cbc);
8607 
8608     return ret;
8609 }
8610 
8611 /*
8612  * Test the various ticket callbacks
8613  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
8614  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
8615  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
8616  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
8617  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
8618  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
8619  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
8620  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
8621  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
8622  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
8623  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
8624  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
8625  * Test 12: TLSv1.2, old ticket key callback, no ticket
8626  * Test 13: TLSv1.3, old ticket key callback, no ticket
8627  * Test 14: TLSv1.2, ticket key callback, ticket, no renewal
8628  * Test 15: TLSv1.3, ticket key callback, ticket, no renewal
8629  * Test 16: TLSv1.2, ticket key callback, ticket, renewal
8630  * Test 17: TLSv1.3, ticket key callback, ticket, renewal
8631  * Test 18: TLSv1.2, ticket key callback, no ticket
8632  * Test 19: TLSv1.3, ticket key callback, no ticket
8633  */
test_ticket_callbacks(int tst)8634 static int test_ticket_callbacks(int tst)
8635 {
8636     SSL_CTX *cctx = NULL, *sctx = NULL;
8637     SSL *clientssl = NULL, *serverssl = NULL;
8638     SSL_SESSION *clntsess = NULL;
8639     int testresult = 0;
8640 
8641 #ifdef OPENSSL_NO_TLS1_2
8642     if (tst % 2 == 0)
8643         return 1;
8644 #endif
8645 #ifdef OSSL_NO_USABLE_TLS1_3
8646     if (tst % 2 == 1)
8647         return 1;
8648 #endif
8649 #ifdef OPENSSL_NO_DEPRECATED_3_0
8650     if (tst >= 8 && tst <= 13)
8651         return 1;
8652 #endif
8653 
8654     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
8655 
8656     /* Which tests the ticket key callback should request renewal for */
8657 
8658     if (tst == 10 || tst == 11 || tst == 16 || tst == 17)
8659         tick_key_renew = 1;
8660     else if (tst == 12 || tst == 13 || tst == 18 || tst == 19)
8661         tick_key_renew = -1; /* abort sending the ticket/0-length ticket */
8662     else
8663         tick_key_renew = 0;
8664 
8665     /* Which tests the decrypt ticket callback should request renewal for */
8666     switch (tst) {
8667     case 0:
8668     case 1:
8669         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
8670         break;
8671 
8672     case 2:
8673     case 3:
8674         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
8675         break;
8676 
8677     case 4:
8678     case 5:
8679         tick_dec_ret = SSL_TICKET_RETURN_USE;
8680         break;
8681 
8682     case 6:
8683     case 7:
8684         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
8685         break;
8686 
8687     default:
8688         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8689     }
8690 
8691     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8692             TLS_client_method(),
8693             TLS1_VERSION,
8694             ((tst % 2) == 0) ? TLS1_2_VERSION
8695                              : TLS1_3_VERSION,
8696             &sctx, &cctx, cert, privkey)))
8697         goto end;
8698 
8699     /*
8700      * We only want sessions to resume from tickets - not the session cache. So
8701      * switch the cache off.
8702      */
8703     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
8704         goto end;
8705 
8706     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
8707             NULL)))
8708         goto end;
8709 
8710     if (tst >= 14) {
8711         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
8712             goto end;
8713 #ifndef OPENSSL_NO_DEPRECATED_3_0
8714     } else if (tst >= 8) {
8715         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
8716             goto end;
8717 #endif
8718     }
8719 
8720     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8721             NULL, NULL))
8722         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8723             SSL_ERROR_NONE)))
8724         goto end;
8725 
8726     /*
8727      * The decrypt ticket key callback in TLSv1.2 should be called even though
8728      * we have no ticket yet, because it gets called with a status of
8729      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
8730      * actually send any ticket data). This does not happen in TLSv1.3 because
8731      * it is not valid to send empty ticket data in TLSv1.3.
8732      */
8733     if (!TEST_int_eq(gen_tick_called, 1)
8734         || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
8735         goto end;
8736 
8737     gen_tick_called = dec_tick_called = 0;
8738 
8739     clntsess = SSL_get1_session(clientssl);
8740     SSL_shutdown(clientssl);
8741     SSL_shutdown(serverssl);
8742     SSL_free(serverssl);
8743     SSL_free(clientssl);
8744     serverssl = clientssl = NULL;
8745 
8746     /* Now do a resumption */
8747     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8748             NULL))
8749         || !TEST_true(SSL_set_session(clientssl, clntsess))
8750         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8751             SSL_ERROR_NONE)))
8752         goto end;
8753 
8754     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
8755         || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8756         || tick_key_renew == -1) {
8757         if (!TEST_false(SSL_session_reused(clientssl)))
8758             goto end;
8759     } else {
8760         if (!TEST_true(SSL_session_reused(clientssl)))
8761             goto end;
8762     }
8763 
8764     if (!TEST_int_eq(gen_tick_called,
8765             (tick_key_renew
8766                 || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8767                 || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
8768                 ? 1
8769                 : 0)
8770         /* There is no ticket to decrypt in tests 13 and 19 */
8771         || !TEST_int_eq(dec_tick_called, (tst == 13 || tst == 19) ? 0 : 1))
8772         goto end;
8773 
8774     testresult = 1;
8775 
8776 end:
8777     SSL_SESSION_free(clntsess);
8778     SSL_free(serverssl);
8779     SSL_free(clientssl);
8780     SSL_CTX_free(sctx);
8781     SSL_CTX_free(cctx);
8782 
8783     return testresult;
8784 }
8785 
8786 /*
8787  * Test incorrect shutdown.
8788  * Test 0: client does not shutdown properly,
8789  *         server does not set SSL_OP_IGNORE_UNEXPECTED_EOF,
8790  *         server should get SSL_ERROR_SSL
8791  * Test 1: client does not shutdown properly,
8792  *         server sets SSL_OP_IGNORE_UNEXPECTED_EOF,
8793  *         server should get SSL_ERROR_ZERO_RETURN
8794  */
test_incorrect_shutdown(int tst)8795 static int test_incorrect_shutdown(int tst)
8796 {
8797     SSL_CTX *cctx = NULL, *sctx = NULL;
8798     SSL *clientssl = NULL, *serverssl = NULL;
8799     int testresult = 0;
8800     char buf[80];
8801     BIO *c2s;
8802 
8803     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8804             TLS_client_method(), 0, 0,
8805             &sctx, &cctx, cert, privkey)))
8806         goto end;
8807 
8808     if (tst == 1)
8809         SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
8810 
8811     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8812             NULL, NULL)))
8813         goto end;
8814 
8815     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8816             SSL_ERROR_NONE)))
8817         goto end;
8818 
8819     c2s = SSL_get_rbio(serverssl);
8820     BIO_set_mem_eof_return(c2s, 0);
8821 
8822     if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf))))
8823         goto end;
8824 
8825     if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
8826         goto end;
8827     if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN))
8828         goto end;
8829 
8830     testresult = 1;
8831 
8832 end:
8833     SSL_free(serverssl);
8834     SSL_free(clientssl);
8835     SSL_CTX_free(sctx);
8836     SSL_CTX_free(cctx);
8837 
8838     return testresult;
8839 }
8840 
8841 /*
8842  * Test bi-directional shutdown.
8843  * Test 0: TLSv1.2
8844  * Test 1: TLSv1.2, server continues to read/write after client shutdown
8845  * Test 2: TLSv1.3, no pending NewSessionTicket messages
8846  * Test 3: TLSv1.3, pending NewSessionTicket messages
8847  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
8848  *                  sends key update, client reads it
8849  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
8850  *                  sends CertificateRequest, client reads and ignores it
8851  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
8852  *                  doesn't read it
8853  */
test_shutdown(int tst)8854 static int test_shutdown(int tst)
8855 {
8856     SSL_CTX *cctx = NULL, *sctx = NULL;
8857     SSL *clientssl = NULL, *serverssl = NULL;
8858     int testresult = 0;
8859     char msg[] = "A test message";
8860     char buf[80];
8861     size_t written, readbytes;
8862     SSL_SESSION *sess;
8863 
8864 #ifdef OPENSSL_NO_TLS1_2
8865     if (tst <= 1)
8866         return 1;
8867 #endif
8868 #ifdef OSSL_NO_USABLE_TLS1_3
8869     if (tst >= 2)
8870         return 1;
8871 #endif
8872 
8873     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8874             TLS_client_method(),
8875             TLS1_VERSION,
8876             (tst <= 1) ? TLS1_2_VERSION
8877                        : TLS1_3_VERSION,
8878             &sctx, &cctx, cert, privkey)))
8879         goto end;
8880 
8881     if (tst == 5)
8882         SSL_CTX_set_post_handshake_auth(cctx, 1);
8883 
8884     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8885             NULL, NULL)))
8886         goto end;
8887 
8888     if (tst == 3) {
8889         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
8890                 SSL_ERROR_NONE, 1, 0))
8891             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8892             || !TEST_false(SSL_SESSION_is_resumable(sess)))
8893             goto end;
8894     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8895                    SSL_ERROR_NONE))
8896         || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8897         || !TEST_true(SSL_SESSION_is_resumable(sess))) {
8898         goto end;
8899     }
8900 
8901     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8902         goto end;
8903 
8904     if (tst >= 4) {
8905         /*
8906          * Reading on the server after the client has sent close_notify should
8907          * fail and provide SSL_ERROR_ZERO_RETURN
8908          */
8909         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
8910             || !TEST_int_eq(SSL_get_error(serverssl, 0),
8911                 SSL_ERROR_ZERO_RETURN)
8912             || !TEST_int_eq(SSL_get_shutdown(serverssl),
8913                 SSL_RECEIVED_SHUTDOWN)
8914             /*
8915              * Even though we're shutdown on receive we should still be
8916              * able to write.
8917              */
8918             || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8919             goto end;
8920         if (tst == 4
8921             && !TEST_true(SSL_key_update(serverssl,
8922                 SSL_KEY_UPDATE_REQUESTED)))
8923             goto end;
8924         if (tst == 5) {
8925             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
8926             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
8927                 goto end;
8928         }
8929         if ((tst == 4 || tst == 5)
8930             && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8931             goto end;
8932         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8933             goto end;
8934         if (tst == 4 || tst == 5) {
8935             /* Should still be able to read data from server */
8936             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8937                     &readbytes))
8938                 || !TEST_size_t_eq(readbytes, sizeof(msg))
8939                 || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
8940                 || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8941                     &readbytes))
8942                 || !TEST_size_t_eq(readbytes, sizeof(msg))
8943                 || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
8944                 goto end;
8945         }
8946     }
8947 
8948     /* Writing on the client after sending close_notify shouldn't be possible */
8949     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
8950         goto end;
8951 
8952     if (tst < 4) {
8953         /*
8954          * For these tests the client has sent close_notify but it has not yet
8955          * been received by the server. The server has not sent close_notify
8956          * yet.
8957          */
8958         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
8959             /*
8960              * Writing on the server after sending close_notify shouldn't
8961              * be possible.
8962              */
8963             || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8964             || !TEST_int_eq(SSL_shutdown(clientssl), 1)
8965             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8966             || !TEST_true(SSL_SESSION_is_resumable(sess))
8967             || !TEST_int_eq(SSL_shutdown(serverssl), 1))
8968             goto end;
8969     } else if (tst == 4 || tst == 5) {
8970         /*
8971          * In this test the client has sent close_notify and it has been
8972          * received by the server which has responded with a close_notify. The
8973          * client needs to read the close_notify sent by the server.
8974          */
8975         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
8976             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8977             || !TEST_true(SSL_SESSION_is_resumable(sess)))
8978             goto end;
8979     } else {
8980         /*
8981          * tst == 6
8982          *
8983          * The client has sent close_notify and is expecting a close_notify
8984          * back, but instead there is application data first. The shutdown
8985          * should fail with a fatal error.
8986          */
8987         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
8988             || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
8989             goto end;
8990     }
8991 
8992     testresult = 1;
8993 
8994 end:
8995     SSL_free(serverssl);
8996     SSL_free(clientssl);
8997     SSL_CTX_free(sctx);
8998     SSL_CTX_free(cctx);
8999 
9000     return testresult;
9001 }
9002 
9003 /*
9004  * Test that sending close_notify alerts works correctly in the case of a
9005  * retryable write failure.
9006  */
test_async_shutdown(void)9007 static int test_async_shutdown(void)
9008 {
9009     SSL_CTX *cctx = NULL, *sctx = NULL;
9010     SSL *clientssl = NULL, *serverssl = NULL;
9011     int testresult = 0;
9012     BIO *bretry = BIO_new(bio_s_always_retry()), *tmp = NULL;
9013 
9014     if (!TEST_ptr(bretry))
9015         goto end;
9016 
9017     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9018             TLS_client_method(),
9019             0, 0,
9020             &sctx, &cctx, cert, privkey)))
9021         goto end;
9022 
9023     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9024             NULL)))
9025         goto end;
9026 
9027     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9028         goto end;
9029 
9030     /* Close write side of clientssl */
9031     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
9032         goto end;
9033 
9034     tmp = SSL_get_wbio(serverssl);
9035     if (!TEST_true(BIO_up_ref(tmp))) {
9036         tmp = NULL;
9037         goto end;
9038     }
9039     SSL_set0_wbio(serverssl, bretry);
9040     bretry = NULL;
9041 
9042     /* First server shutdown should fail because of a retrable write failure */
9043     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
9044         || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
9045         goto end;
9046 
9047     /* Second server shutdown should fail for the same reason */
9048     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
9049         || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
9050         goto end;
9051 
9052     SSL_set0_wbio(serverssl, tmp);
9053     tmp = NULL;
9054 
9055     /* Third server shutdown should send close_notify */
9056     if (!TEST_int_eq(SSL_shutdown(serverssl), 0))
9057         goto end;
9058 
9059     /* Fourth server shutdown should read close_notify from client and finish */
9060     if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
9061         goto end;
9062 
9063     /* Client should also successfully fully shutdown */
9064     if (!TEST_int_eq(SSL_shutdown(clientssl), 1))
9065         goto end;
9066 
9067     testresult = 1;
9068 end:
9069     SSL_free(serverssl);
9070     SSL_free(clientssl);
9071     SSL_CTX_free(sctx);
9072     SSL_CTX_free(cctx);
9073     BIO_free(bretry);
9074     BIO_free(tmp);
9075 
9076     return testresult;
9077 }
9078 
9079 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
9080 static int cert_cb_cnt;
9081 
load_chain(const char * file,EVP_PKEY ** pkey,X509 ** x509,STACK_OF (X509)* chain)9082 static int load_chain(const char *file, EVP_PKEY **pkey, X509 **x509,
9083     STACK_OF(X509) *chain)
9084 {
9085     char *path = test_mk_file_path(certsdir, file);
9086     BIO *in = NULL;
9087     X509 *x = NULL;
9088     int ok = 0;
9089 
9090     if (path == NULL)
9091         return 0;
9092     if ((in = BIO_new(BIO_s_file())) == NULL
9093         || BIO_read_filename(in, path) <= 0)
9094         goto out;
9095     if (pkey == NULL) {
9096         if ((x = X509_new_ex(libctx, NULL)) == NULL
9097             || PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
9098             goto out;
9099         if (chain == NULL)
9100             *x509 = x;
9101         else if (!sk_X509_push(chain, x))
9102             goto out;
9103     } else if (PEM_read_bio_PrivateKey_ex(in, pkey, NULL, NULL,
9104                    libctx, NULL)
9105         == NULL) {
9106         goto out;
9107     }
9108 
9109     x = NULL;
9110     ok = 1;
9111 out:
9112     X509_free(x);
9113     BIO_free(in);
9114     OPENSSL_free(path);
9115     return ok;
9116 }
9117 
cert_cb(SSL * s,void * arg)9118 static int cert_cb(SSL *s, void *arg)
9119 {
9120     SSL_CTX *ctx = (SSL_CTX *)arg;
9121     EVP_PKEY *pkey = NULL;
9122     X509 *x509 = NULL, *x = NULL;
9123     STACK_OF(X509) *chain = NULL;
9124     int ret = 0;
9125 
9126     if (cert_cb_cnt == 0) {
9127         /* Suspend the handshake */
9128         cert_cb_cnt++;
9129         return -1;
9130     } else if (cert_cb_cnt == 1) {
9131         /*
9132          * Update the SSL_CTX, set the certificate and private key and then
9133          * continue the handshake normally.
9134          */
9135         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
9136             return 0;
9137 
9138         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
9139             || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
9140                 SSL_FILETYPE_PEM))
9141             || !TEST_true(SSL_check_private_key(s)))
9142             return 0;
9143         cert_cb_cnt++;
9144         return 1;
9145     } else if (cert_cb_cnt == 3) {
9146         int rv;
9147 
9148         chain = sk_X509_new_null();
9149         if (!TEST_ptr(chain)
9150             || !TEST_true(load_chain("ca-cert.pem", NULL, NULL, chain))
9151             || !TEST_true(load_chain("root-cert.pem", NULL, NULL, chain))
9152             || !TEST_true(load_chain("p256-ee-rsa-ca-cert.pem", NULL,
9153                 &x509, NULL))
9154             || !TEST_true(load_chain("p256-ee-rsa-ca-key.pem", &pkey,
9155                 NULL, NULL)))
9156             goto out;
9157         rv = SSL_check_chain(s, x509, pkey, chain);
9158         /*
9159          * If the cert doesn't show as valid here (e.g., because we don't
9160          * have any shared sigalgs), then we will not set it, and there will
9161          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
9162          * will cause tls_choose_sigalgs() to fail the connection.
9163          */
9164         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
9165             == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
9166             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
9167                 goto out;
9168         }
9169 
9170         ret = 1;
9171     }
9172 
9173     /* Abort the handshake */
9174 out:
9175     EVP_PKEY_free(pkey);
9176     X509_free(x509);
9177     X509_free(x);
9178     OSSL_STACK_OF_X509_free(chain);
9179     return ret;
9180 }
9181 
9182 /*
9183  * Test the certificate callback.
9184  * Test 0: Callback fails
9185  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
9186  * Test 2: Success - SSL_set_SSL_CTX() in the callback
9187  * Test 3: Success - Call SSL_check_chain from the callback
9188  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
9189  *                   chain
9190  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
9191  */
test_cert_cb_int(int prot,int tst)9192 static int test_cert_cb_int(int prot, int tst)
9193 {
9194     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
9195     SSL *clientssl = NULL, *serverssl = NULL;
9196     int testresult = 0, ret;
9197 
9198 #ifdef OPENSSL_NO_EC
9199     /* We use an EC cert in these tests, so we skip in a no-ec build */
9200     if (tst >= 3)
9201         return 1;
9202 #endif
9203 
9204     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9205             TLS_client_method(),
9206             prot,
9207             prot,
9208             &sctx, &cctx, NULL, NULL)))
9209         goto end;
9210 
9211     if (tst == 0)
9212         cert_cb_cnt = -1;
9213     else if (tst >= 3)
9214         cert_cb_cnt = 3;
9215     else
9216         cert_cb_cnt = 0;
9217 
9218     if (tst == 2) {
9219         snictx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9220         if (!TEST_ptr(snictx))
9221             goto end;
9222     }
9223 
9224     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
9225 
9226     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9227             NULL, NULL)))
9228         goto end;
9229 
9230     if (tst == 4) {
9231         /*
9232          * We cause SSL_check_chain() to fail by specifying sig_algs that
9233          * the chain doesn't meet (the root uses an RSA cert)
9234          */
9235         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
9236                 "ecdsa_secp256r1_sha256")))
9237             goto end;
9238     } else if (tst == 5) {
9239         /*
9240          * We cause SSL_check_chain() to fail by specifying sig_algs that
9241          * the ee cert doesn't meet (the ee uses an ECDSA cert)
9242          */
9243         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
9244                 "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
9245             goto end;
9246     }
9247 
9248     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
9249     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
9250         || (tst > 0
9251             && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
9252         goto end;
9253     }
9254 
9255     testresult = 1;
9256 
9257 end:
9258     SSL_free(serverssl);
9259     SSL_free(clientssl);
9260     SSL_CTX_free(sctx);
9261     SSL_CTX_free(cctx);
9262     SSL_CTX_free(snictx);
9263 
9264     return testresult;
9265 }
9266 #endif
9267 
test_cert_cb(int tst)9268 static int test_cert_cb(int tst)
9269 {
9270     int testresult = 1;
9271 
9272 #ifndef OPENSSL_NO_TLS1_2
9273     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
9274 #endif
9275 #ifndef OSSL_NO_USABLE_TLS1_3
9276     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
9277 #endif
9278 
9279     return testresult;
9280 }
9281 
client_cert_cb(SSL * ssl,X509 ** x509,EVP_PKEY ** pkey)9282 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
9283 {
9284     X509 *xcert;
9285     EVP_PKEY *privpkey;
9286     BIO *in = NULL;
9287     BIO *priv_in = NULL;
9288 
9289     /* Check that SSL_get0_peer_certificate() returns something sensible */
9290     if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
9291         return 0;
9292 
9293     in = BIO_new_file(cert, "r");
9294     if (!TEST_ptr(in))
9295         return 0;
9296 
9297     if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL))
9298         || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
9299         || !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
9300         || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
9301                          NULL, NULL,
9302                          libctx, NULL)))
9303         goto err;
9304 
9305     *x509 = xcert;
9306     *pkey = privpkey;
9307 
9308     BIO_free(in);
9309     BIO_free(priv_in);
9310     return 1;
9311 err:
9312     X509_free(xcert);
9313     BIO_free(in);
9314     BIO_free(priv_in);
9315     return 0;
9316 }
9317 
test_client_cert_cb(int tst)9318 static int test_client_cert_cb(int tst)
9319 {
9320     SSL_CTX *cctx = NULL, *sctx = NULL;
9321     SSL *clientssl = NULL, *serverssl = NULL;
9322     int testresult = 0;
9323 
9324 #ifdef OPENSSL_NO_TLS1_2
9325     if (tst == 0)
9326         return 1;
9327 #endif
9328 #ifdef OSSL_NO_USABLE_TLS1_3
9329     if (tst == 1)
9330         return 1;
9331 #endif
9332 
9333     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9334             TLS_client_method(),
9335             TLS1_VERSION,
9336             tst == 0 ? TLS1_2_VERSION
9337                      : TLS1_3_VERSION,
9338             &sctx, &cctx, cert, privkey)))
9339         goto end;
9340 
9341     /*
9342      * Test that setting a client_cert_cb results in a client certificate being
9343      * sent.
9344      */
9345     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
9346     SSL_CTX_set_verify(sctx,
9347         SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
9348         verify_cb);
9349 
9350     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9351             NULL, NULL))
9352         || !TEST_true(create_ssl_connection(serverssl, clientssl,
9353             SSL_ERROR_NONE)))
9354         goto end;
9355 
9356     testresult = 1;
9357 
9358 end:
9359     SSL_free(serverssl);
9360     SSL_free(clientssl);
9361     SSL_CTX_free(sctx);
9362     SSL_CTX_free(cctx);
9363 
9364     return testresult;
9365 }
9366 
9367 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
9368 /*
9369  * Test setting certificate authorities on both client and server.
9370  *
9371  * Test 0: SSL_CTX_set0_CA_list() only
9372  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
9373  * Test 2: Only SSL_CTX_set_client_CA_list()
9374  */
test_ca_names_int(int prot,int tst)9375 static int test_ca_names_int(int prot, int tst)
9376 {
9377     SSL_CTX *cctx = NULL, *sctx = NULL;
9378     SSL *clientssl = NULL, *serverssl = NULL;
9379     int testresult = 0;
9380     size_t i;
9381     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
9382     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
9383     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
9384     const STACK_OF(X509_NAME) *sktmp = NULL;
9385 
9386     for (i = 0; i < OSSL_NELEM(name); i++) {
9387         name[i] = X509_NAME_new();
9388         if (!TEST_ptr(name[i])
9389             || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
9390                 MBSTRING_ASC,
9391                 (unsigned char *)
9392                     strnames[i],
9393                 -1, -1, 0)))
9394             goto end;
9395     }
9396 
9397     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9398             TLS_client_method(),
9399             TLS1_VERSION,
9400             prot,
9401             &sctx, &cctx, cert, privkey)))
9402         goto end;
9403 
9404     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
9405 
9406     if (tst == 0 || tst == 1) {
9407         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9408             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
9409             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
9410             || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9411             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
9412             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
9413             goto end;
9414 
9415         SSL_CTX_set0_CA_list(sctx, sk1);
9416         SSL_CTX_set0_CA_list(cctx, sk2);
9417         sk1 = sk2 = NULL;
9418     }
9419     if (tst == 1 || tst == 2) {
9420         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9421             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
9422             || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
9423             || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9424             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
9425             || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
9426             goto end;
9427 
9428         SSL_CTX_set_client_CA_list(sctx, sk1);
9429         SSL_CTX_set_client_CA_list(cctx, sk2);
9430         sk1 = sk2 = NULL;
9431     }
9432 
9433     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9434             NULL, NULL))
9435         || !TEST_true(create_ssl_connection(serverssl, clientssl,
9436             SSL_ERROR_NONE)))
9437         goto end;
9438 
9439     /*
9440      * We only expect certificate authorities to have been sent to the server
9441      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
9442      */
9443     sktmp = SSL_get0_peer_CA_list(serverssl);
9444     if (prot == TLS1_3_VERSION
9445         && (tst == 0 || tst == 1)) {
9446         if (!TEST_ptr(sktmp)
9447             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9448             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9449                                 name[0]),
9450                 0)
9451             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9452                                 name[1]),
9453                 0))
9454             goto end;
9455     } else if (!TEST_ptr_null(sktmp)) {
9456         goto end;
9457     }
9458 
9459     /*
9460      * In all tests we expect certificate authorities to have been sent to the
9461      * client. However, SSL_set_client_CA_list() should override
9462      * SSL_set0_CA_list()
9463      */
9464     sktmp = SSL_get0_peer_CA_list(clientssl);
9465     if (!TEST_ptr(sktmp)
9466         || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9467         || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9468                             name[tst == 0 ? 0 : 2]),
9469             0)
9470         || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9471                             name[tst == 0 ? 1 : 3]),
9472             0))
9473         goto end;
9474 
9475     testresult = 1;
9476 
9477 end:
9478     SSL_free(serverssl);
9479     SSL_free(clientssl);
9480     SSL_CTX_free(sctx);
9481     SSL_CTX_free(cctx);
9482     for (i = 0; i < OSSL_NELEM(name); i++)
9483         X509_NAME_free(name[i]);
9484     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
9485     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
9486 
9487     return testresult;
9488 }
9489 #endif
9490 
test_ca_names(int tst)9491 static int test_ca_names(int tst)
9492 {
9493     int testresult = 1;
9494 
9495 #ifndef OPENSSL_NO_TLS1_2
9496     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
9497 #endif
9498 #ifndef OSSL_NO_USABLE_TLS1_3
9499     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
9500 #endif
9501 
9502     return testresult;
9503 }
9504 
9505 #ifndef OPENSSL_NO_TLS1_2
9506 static const char *multiblock_cipherlist_data[] = {
9507     "AES128-SHA",
9508     "AES128-SHA256",
9509     "AES256-SHA",
9510     "AES256-SHA256",
9511 };
9512 
9513 /* Reduce the fragment size - so the multiblock test buffer can be small */
9514 #define MULTIBLOCK_FRAGSIZE 512
9515 
test_multiblock_write(int test_index)9516 static int test_multiblock_write(int test_index)
9517 {
9518     static const char *fetchable_ciphers[] = {
9519         "AES-128-CBC-HMAC-SHA1",
9520         "AES-128-CBC-HMAC-SHA256",
9521         "AES-256-CBC-HMAC-SHA1",
9522         "AES-256-CBC-HMAC-SHA256"
9523     };
9524     const char *cipherlist = multiblock_cipherlist_data[test_index];
9525     const SSL_METHOD *smeth = TLS_server_method();
9526     const SSL_METHOD *cmeth = TLS_client_method();
9527     int min_version = TLS1_VERSION;
9528     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
9529     SSL_CTX *cctx = NULL, *sctx = NULL;
9530     SSL *clientssl = NULL, *serverssl = NULL;
9531     int testresult = 0;
9532 
9533     /*
9534      * Choose a buffer large enough to perform a multi-block operation
9535      * i.e: write_len >= 4 * frag_size
9536      * 9 * is chosen so that multiple multiblocks are used + some leftover.
9537      */
9538     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
9539     unsigned char buf[sizeof(msg)], *p = buf;
9540     size_t readbytes, written, len;
9541     EVP_CIPHER *ciph = NULL;
9542 
9543     /*
9544      * Check if the cipher exists before attempting to use it since it only has
9545      * a hardware specific implementation.
9546      */
9547     ciph = EVP_CIPHER_fetch(libctx, fetchable_ciphers[test_index], "");
9548     if (ciph == NULL) {
9549         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
9550         return 1;
9551     }
9552     EVP_CIPHER_free(ciph);
9553 
9554     /* Set up a buffer with some data that will be sent to the client */
9555     RAND_bytes(msg, sizeof(msg));
9556 
9557     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
9558             max_version, &sctx, &cctx, cert,
9559             privkey)))
9560         goto end;
9561 
9562     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
9563         goto end;
9564 
9565     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9566             NULL, NULL)))
9567         goto end;
9568 
9569     /* settings to force it to use AES-CBC-HMAC_SHA */
9570     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
9571     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
9572         goto end;
9573 
9574     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9575         goto end;
9576 
9577     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
9578         || !TEST_size_t_eq(written, sizeof(msg)))
9579         goto end;
9580 
9581     len = written;
9582     while (len > 0) {
9583         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
9584             goto end;
9585         p += readbytes;
9586         len -= readbytes;
9587     }
9588     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
9589         goto end;
9590 
9591     testresult = 1;
9592 end:
9593     SSL_free(serverssl);
9594     SSL_free(clientssl);
9595     SSL_CTX_free(sctx);
9596     SSL_CTX_free(cctx);
9597 
9598     return testresult;
9599 }
9600 #endif /* OPENSSL_NO_TLS1_2 */
9601 
test_session_timeout(int test)9602 static int test_session_timeout(int test)
9603 {
9604     /*
9605      * Test session ordering and timeout
9606      * Can't explicitly test performance of the new code,
9607      * but can test to see if the ordering of the sessions
9608      * are correct, and they are removed as expected
9609      */
9610     SSL_SESSION *early = NULL;
9611     SSL_SESSION *middle = NULL;
9612     SSL_SESSION *late = NULL;
9613     SSL_CTX *ctx;
9614     int testresult = 0;
9615     time_t now = time(NULL);
9616 #define TIMEOUT 10
9617 
9618     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
9619         || !TEST_ptr(early = SSL_SESSION_new())
9620         || !TEST_ptr(middle = SSL_SESSION_new())
9621         || !TEST_ptr(late = SSL_SESSION_new()))
9622         goto end;
9623 
9624     /* assign unique session ids */
9625     early->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9626     memset(early->session_id, 1, SSL3_SSL_SESSION_ID_LENGTH);
9627     middle->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9628     memset(middle->session_id, 2, SSL3_SSL_SESSION_ID_LENGTH);
9629     late->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9630     memset(late->session_id, 3, SSL3_SSL_SESSION_ID_LENGTH);
9631 
9632     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9633         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9634         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9635         goto end;
9636 
9637     /* Make sure they are all added */
9638     if (!TEST_ptr(early->prev)
9639         || !TEST_ptr(middle->prev)
9640         || !TEST_ptr(late->prev))
9641         goto end;
9642 
9643     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now - 10), 0)
9644         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(middle, now), 0)
9645         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(late, now + 10), 0))
9646         goto end;
9647 
9648     if (!TEST_int_ne(SSL_SESSION_set_timeout(early, TIMEOUT), 0)
9649         || !TEST_int_ne(SSL_SESSION_set_timeout(middle, TIMEOUT), 0)
9650         || !TEST_int_ne(SSL_SESSION_set_timeout(late, TIMEOUT), 0))
9651         goto end;
9652 
9653     /* Make sure they are all still there */
9654     if (!TEST_ptr(early->prev)
9655         || !TEST_ptr(middle->prev)
9656         || !TEST_ptr(late->prev))
9657         goto end;
9658 
9659     /* Make sure they are in the expected order */
9660     if (!TEST_ptr_eq(late->next, middle)
9661         || !TEST_ptr_eq(middle->next, early)
9662         || !TEST_ptr_eq(early->prev, middle)
9663         || !TEST_ptr_eq(middle->prev, late))
9664         goto end;
9665 
9666     /* This should remove "early" */
9667     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT - 1);
9668     if (!TEST_ptr_null(early->prev)
9669         || !TEST_ptr(middle->prev)
9670         || !TEST_ptr(late->prev))
9671         goto end;
9672 
9673     /* This should remove "middle" */
9674     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 1);
9675     if (!TEST_ptr_null(early->prev)
9676         || !TEST_ptr_null(middle->prev)
9677         || !TEST_ptr(late->prev))
9678         goto end;
9679 
9680     /* This should remove "late" */
9681     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 11);
9682     if (!TEST_ptr_null(early->prev)
9683         || !TEST_ptr_null(middle->prev)
9684         || !TEST_ptr_null(late->prev))
9685         goto end;
9686 
9687     /* Add them back in again */
9688     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9689         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9690         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9691         goto end;
9692 
9693     /* Make sure they are all added */
9694     if (!TEST_ptr(early->prev)
9695         || !TEST_ptr(middle->prev)
9696         || !TEST_ptr(late->prev))
9697         goto end;
9698 
9699     /* This should remove all of them */
9700     SSL_CTX_flush_sessions_ex(ctx, 0);
9701     if (!TEST_ptr_null(early->prev)
9702         || !TEST_ptr_null(middle->prev)
9703         || !TEST_ptr_null(late->prev))
9704         goto end;
9705 
9706     (void)SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_UPDATE_TIME | SSL_CTX_get_session_cache_mode(ctx));
9707 
9708     /* make sure |now| is NOT  equal to the current time */
9709     now -= 10;
9710     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now), 0)
9711         || !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9712         || !TEST_time_t_ne(SSL_SESSION_get_time_ex(early), now))
9713         goto end;
9714 
9715     testresult = 1;
9716 end:
9717     SSL_CTX_free(ctx);
9718     SSL_SESSION_free(early);
9719     SSL_SESSION_free(middle);
9720     SSL_SESSION_free(late);
9721     return testresult;
9722 }
9723 
9724 /*
9725  * Test that a session cache overflow works as expected
9726  * Test 0: TLSv1.3, timeout on new session later than old session
9727  * Test 1: TLSv1.2, timeout on new session later than old session
9728  * Test 2: TLSv1.3, timeout on new session earlier than old session
9729  * Test 3: TLSv1.2, timeout on new session earlier than old session
9730  */
9731 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
test_session_cache_overflow(int idx)9732 static int test_session_cache_overflow(int idx)
9733 {
9734     SSL_CTX *sctx = NULL, *cctx = NULL;
9735     SSL *serverssl = NULL, *clientssl = NULL;
9736     int testresult = 0;
9737     SSL_SESSION *sess = NULL;
9738     int references;
9739 
9740 #ifdef OSSL_NO_USABLE_TLS1_3
9741     /* If no TLSv1.3 available then do nothing in this case */
9742     if (idx % 2 == 0)
9743         return TEST_skip("No TLSv1.3 available");
9744 #endif
9745 #ifdef OPENSSL_NO_TLS1_2
9746     /* If no TLSv1.2 available then do nothing in this case */
9747     if (idx % 2 == 1)
9748         return TEST_skip("No TLSv1.2 available");
9749 #endif
9750 
9751     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9752             TLS_client_method(), TLS1_VERSION,
9753             (idx % 2 == 0) ? TLS1_3_VERSION
9754                            : TLS1_2_VERSION,
9755             &sctx, &cctx, cert, privkey))
9756         || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET)))
9757         goto end;
9758 
9759     SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
9760     get_sess_val = NULL;
9761 
9762     SSL_CTX_sess_set_cache_size(sctx, 1);
9763 
9764     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9765             NULL, NULL)))
9766         goto end;
9767 
9768     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9769         goto end;
9770 
9771     if (idx > 1) {
9772         sess = SSL_get_session(serverssl);
9773         if (!TEST_ptr(sess))
9774             goto end;
9775 
9776         /*
9777          * Cause this session to have a longer timeout than the next session to
9778          * be added.
9779          */
9780         if (!TEST_true(SSL_SESSION_set_timeout(sess, LONG_MAX))) {
9781             sess = NULL;
9782             goto end;
9783         }
9784         sess = NULL;
9785     }
9786 
9787     SSL_shutdown(serverssl);
9788     SSL_shutdown(clientssl);
9789     SSL_free(serverssl);
9790     SSL_free(clientssl);
9791     serverssl = clientssl = NULL;
9792 
9793     /*
9794      * Session cache size is 1 and we already populated the cache with a session
9795      * so the next connection should cause an overflow.
9796      */
9797 
9798     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9799             NULL, NULL)))
9800         goto end;
9801 
9802     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9803         goto end;
9804 
9805     /*
9806      * The session we just negotiated may have been already removed from the
9807      * internal cache - but we will return it anyway from our external cache.
9808      */
9809     get_sess_val = SSL_get_session(serverssl);
9810     if (!TEST_ptr(get_sess_val))
9811         goto end;
9812     /*
9813      * Normally the session is also stored in the cache, thus we have more than
9814      * one reference, but due to an out-of-memory error it can happen that this
9815      * is the only reference, and in that case the SSL_free(serverssl) below
9816      * would free the get_sess_val, causing a use-after-free error.
9817      */
9818     if (!TEST_true(CRYPTO_GET_REF(&get_sess_val->references, &references))
9819         || !TEST_int_ge(references, 2))
9820         goto end;
9821     sess = SSL_get1_session(clientssl);
9822     if (!TEST_ptr(sess))
9823         goto end;
9824 
9825     SSL_shutdown(serverssl);
9826     SSL_shutdown(clientssl);
9827     SSL_free(serverssl);
9828     SSL_free(clientssl);
9829     serverssl = clientssl = NULL;
9830 
9831     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9832             NULL, NULL)))
9833         goto end;
9834 
9835     if (!TEST_true(SSL_set_session(clientssl, sess)))
9836         goto end;
9837 
9838     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9839         goto end;
9840 
9841     testresult = 1;
9842 
9843 end:
9844     SSL_free(serverssl);
9845     SSL_free(clientssl);
9846     SSL_CTX_free(sctx);
9847     SSL_CTX_free(cctx);
9848     SSL_SESSION_free(sess);
9849 
9850     return testresult;
9851 }
9852 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
9853 
9854 /*
9855  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
9856  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
9857  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
9858  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
9859  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
9860  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
9861  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
9862  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
9863  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
9864  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
9865  */
test_servername(int tst)9866 static int test_servername(int tst)
9867 {
9868     SSL_CTX *cctx = NULL, *sctx = NULL;
9869     SSL *clientssl = NULL, *serverssl = NULL;
9870     int testresult = 0;
9871     SSL_SESSION *sess = NULL;
9872     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
9873 
9874 #ifdef OPENSSL_NO_TLS1_2
9875     if (tst <= 4)
9876         return 1;
9877 #endif
9878 #ifdef OSSL_NO_USABLE_TLS1_3
9879     if (tst >= 5)
9880         return 1;
9881 #endif
9882 
9883     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9884             TLS_client_method(),
9885             TLS1_VERSION,
9886             (tst <= 4) ? TLS1_2_VERSION
9887                        : TLS1_3_VERSION,
9888             &sctx, &cctx, cert, privkey))
9889         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9890             NULL, NULL)))
9891         goto end;
9892 
9893     if (tst != 1 && tst != 6) {
9894         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
9895                 hostname_cb)))
9896             goto end;
9897     }
9898 
9899     if (tst != 3 && tst != 8) {
9900         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9901             goto end;
9902         sexpectedhost = cexpectedhost = "goodhost";
9903     }
9904 
9905     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9906         goto end;
9907 
9908     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
9909             cexpectedhost)
9910         || !TEST_str_eq(SSL_get_servername(serverssl,
9911                             TLSEXT_NAMETYPE_host_name),
9912             sexpectedhost))
9913         goto end;
9914 
9915     /* Now repeat with a resumption handshake */
9916 
9917     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
9918         || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
9919         || !TEST_true(SSL_SESSION_is_resumable(sess))
9920         || !TEST_int_eq(SSL_shutdown(serverssl), 0))
9921         goto end;
9922 
9923     SSL_free(clientssl);
9924     SSL_free(serverssl);
9925     clientssl = serverssl = NULL;
9926 
9927     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9928             NULL)))
9929         goto end;
9930 
9931     if (!TEST_true(SSL_set_session(clientssl, sess)))
9932         goto end;
9933 
9934     sexpectedhost = cexpectedhost = "goodhost";
9935     if (tst == 2 || tst == 7) {
9936         /* Set an inconsistent hostname */
9937         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
9938             goto end;
9939         /*
9940          * In TLSv1.2 we expect the hostname from the original handshake, in
9941          * TLSv1.3 we expect the hostname from this handshake
9942          */
9943         if (tst == 7)
9944             sexpectedhost = cexpectedhost = "altgoodhost";
9945 
9946         if (!TEST_str_eq(SSL_get_servername(clientssl,
9947                              TLSEXT_NAMETYPE_host_name),
9948                 "altgoodhost"))
9949             goto end;
9950     } else if (tst == 4 || tst == 9) {
9951         /*
9952          * A TLSv1.3 session does not associate a session with a servername,
9953          * but a TLSv1.2 session does.
9954          */
9955         if (tst == 9)
9956             sexpectedhost = cexpectedhost = NULL;
9957 
9958         if (!TEST_str_eq(SSL_get_servername(clientssl,
9959                              TLSEXT_NAMETYPE_host_name),
9960                 cexpectedhost))
9961             goto end;
9962     } else {
9963         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9964             goto end;
9965         /*
9966          * In a TLSv1.2 resumption where the hostname was not acknowledged
9967          * we expect the hostname on the server to be empty. On the client we
9968          * return what was requested in this case.
9969          *
9970          * Similarly if the client didn't set a hostname on an original TLSv1.2
9971          * session but is now, the server hostname will be empty, but the client
9972          * is as we set it.
9973          */
9974         if (tst == 1 || tst == 3)
9975             sexpectedhost = NULL;
9976 
9977         if (!TEST_str_eq(SSL_get_servername(clientssl,
9978                              TLSEXT_NAMETYPE_host_name),
9979                 "goodhost"))
9980             goto end;
9981     }
9982 
9983     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9984         goto end;
9985 
9986     if (!TEST_true(SSL_session_reused(clientssl))
9987         || !TEST_true(SSL_session_reused(serverssl))
9988         || !TEST_str_eq(SSL_get_servername(clientssl,
9989                             TLSEXT_NAMETYPE_host_name),
9990             cexpectedhost)
9991         || !TEST_str_eq(SSL_get_servername(serverssl,
9992                             TLSEXT_NAMETYPE_host_name),
9993             sexpectedhost))
9994         goto end;
9995 
9996     testresult = 1;
9997 
9998 end:
9999     SSL_SESSION_free(sess);
10000     SSL_free(serverssl);
10001     SSL_free(clientssl);
10002     SSL_CTX_free(sctx);
10003     SSL_CTX_free(cctx);
10004 
10005     return testresult;
10006 }
10007 
test_unknown_sigalgs_groups(void)10008 static int test_unknown_sigalgs_groups(void)
10009 {
10010     int ret = 0;
10011     SSL_CTX *ctx = NULL;
10012 
10013     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
10014         goto end;
10015 
10016     if (!TEST_int_gt(SSL_CTX_set1_sigalgs_list(ctx,
10017                          "RSA+SHA256:?nonexistent:?RSA+SHA512"),
10018             0))
10019         goto end;
10020     if (!TEST_size_t_eq(ctx->cert->conf_sigalgslen, 2)
10021         || !TEST_int_eq(ctx->cert->conf_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
10022         || !TEST_int_eq(ctx->cert->conf_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
10023         goto end;
10024 
10025     if (!TEST_int_gt(SSL_CTX_set1_client_sigalgs_list(ctx,
10026                          "RSA+SHA256:?nonexistent:?RSA+SHA512"),
10027             0))
10028         goto end;
10029     if (!TEST_size_t_eq(ctx->cert->client_sigalgslen, 2)
10030         || !TEST_int_eq(ctx->cert->client_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
10031         || !TEST_int_eq(ctx->cert->client_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
10032         goto end;
10033 
10034     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
10035                          "nonexistent"),
10036             0))
10037         goto end;
10038 
10039     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx,
10040                          "?nonexistent1:?nonexistent2:?nonexistent3"),
10041             0))
10042         goto end;
10043 
10044 #ifndef OPENSSL_NO_EC
10045     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
10046                          "P-256:nonexistent"),
10047             0))
10048         goto end;
10049 
10050     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx,
10051                          "P-384:?nonexistent:?P-521"),
10052             0))
10053         goto end;
10054     if (!TEST_size_t_eq(ctx->ext.supportedgroups_len, 2)
10055         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp384r1)
10056         || !TEST_int_eq(ctx->ext.supportedgroups[1], OSSL_TLS_GROUP_ID_secp521r1))
10057         goto end;
10058 #endif
10059 
10060     ret = 1;
10061 end:
10062     SSL_CTX_free(ctx);
10063     return ret;
10064 }
10065 
10066 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM)
test_configuration_of_groups(void)10067 static int test_configuration_of_groups(void)
10068 {
10069     int ret = 0;
10070     SSL_CTX *ctx = NULL;
10071     size_t groups_len;
10072 
10073     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
10074         goto end;
10075     groups_len = ctx->ext.supportedgroups_len;
10076 
10077     if (!TEST_size_t_gt(groups_len, 0)
10078         || !TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT"), 0)
10079         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len))
10080         goto end;
10081 
10082     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT:-?P-256"), 0)
10083 #if !defined(OPENSSL_NO_EC)
10084         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len - 1)
10085 #else
10086         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len)
10087 #endif
10088     )
10089         goto end;
10090 
10091 #if !defined(OPENSSL_NO_EC)
10092     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "?P-256:?P-521:-?P-256"), 0)
10093         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, 1)
10094         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp521r1))
10095         goto end;
10096 #endif
10097 
10098     ret = 1;
10099 
10100 end:
10101     SSL_CTX_free(ctx);
10102     return ret;
10103 }
10104 #endif
10105 
10106 #if !defined(OPENSSL_NO_EC) \
10107     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
10108 /*
10109  * Test that if signature algorithms are not available, then we do not offer or
10110  * accept them.
10111  * Test 0: Two RSA sig algs available: both RSA sig algs shared
10112  * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared
10113  * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared
10114  * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared
10115  * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared
10116  * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared
10117  */
test_sigalgs_available(int idx)10118 static int test_sigalgs_available(int idx)
10119 {
10120     SSL_CTX *cctx = NULL, *sctx = NULL;
10121     SSL *clientssl = NULL, *serverssl = NULL;
10122     int testresult = 0;
10123     OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
10124     OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx;
10125     OSSL_PROVIDER *filterprov = NULL;
10126     int sig, hash, numshared, numshared_expected, hash_expected, sig_expected;
10127     const char *sigalg_name, *signame_expected;
10128 
10129     if (!TEST_ptr(tmpctx))
10130         goto end;
10131 
10132     if (idx != 0 && idx != 3) {
10133         if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter",
10134                 filter_provider_init)))
10135             goto end;
10136 
10137         filterprov = OSSL_PROVIDER_load(tmpctx, "filter");
10138         if (!TEST_ptr(filterprov))
10139             goto end;
10140 
10141         if (idx < 3) {
10142             /*
10143              * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered
10144              * or accepted for the peer that uses this libctx. Note that libssl
10145              * *requires* SHA2-256 to be available so we cannot disable that. We
10146              * also need SHA1 for our certificate.
10147              */
10148             if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST,
10149                     "SHA2-256:SHA1")))
10150                 goto end;
10151         } else {
10152             if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE,
10153                     "ECDSA"))
10154 #ifdef OPENSSL_NO_ECX
10155                 || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT, "EC"))
10156 #else
10157                 || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
10158                     "EC:X25519:X448"))
10159 #endif
10160             )
10161                 goto end;
10162         }
10163 
10164         if (idx == 1 || idx == 4)
10165             clientctx = tmpctx;
10166         else
10167             serverctx = tmpctx;
10168     }
10169 
10170     cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method());
10171     sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method());
10172     if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
10173         goto end;
10174 
10175     /* Avoid MLKEM groups that depend on possibly filtered-out digests */
10176     if (!TEST_true(SSL_CTX_set1_groups_list(cctx,
10177             "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072"))
10178         || !TEST_true(SSL_CTX_set1_groups_list(sctx,
10179             "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072")))
10180         goto end;
10181 
10182     if (idx != 5) {
10183         /* RSA first server key */
10184         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10185                 TLS_client_method(),
10186                 TLS1_VERSION,
10187                 0,
10188                 &sctx, &cctx, cert, privkey)))
10189             goto end;
10190     } else {
10191         /* ECDSA P-256 first server key */
10192         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10193                 TLS_client_method(),
10194                 TLS1_VERSION,
10195                 0,
10196                 &sctx, &cctx, cert2, privkey2)))
10197             goto end;
10198     }
10199 
10200     /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */
10201     if (idx < 4) {
10202         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
10203                 "ECDHE-RSA-AES128-GCM-SHA256")))
10204             goto end;
10205     } else {
10206         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
10207                 "ECDHE-ECDSA-AES128-GCM-SHA256")))
10208             goto end;
10209     }
10210 
10211     if (idx < 3) {
10212         if (!SSL_CTX_set1_sigalgs_list(cctx,
10213                 "rsa_pss_rsae_sha384"
10214                 ":rsa_pss_rsae_sha256")
10215             || !SSL_CTX_set1_sigalgs_list(sctx,
10216                 "rsa_pss_rsae_sha384"
10217                 ":rsa_pss_rsae_sha256"))
10218             goto end;
10219     } else {
10220         if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")
10221             || !SSL_CTX_set1_sigalgs_list(sctx,
10222                 "rsa_pss_rsae_sha256:ECDSA+SHA256"))
10223             goto end;
10224     }
10225 
10226     /* ECDSA P-256 second server key, unless already first */
10227     if (idx != 5
10228         && (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2,
10229                              SSL_FILETYPE_PEM),
10230                 1)
10231             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
10232                                 privkey2,
10233                                 SSL_FILETYPE_PEM),
10234                 1)
10235             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)))
10236         goto end;
10237 
10238     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10239             NULL, NULL)))
10240         goto end;
10241 
10242     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10243         goto end;
10244 
10245     /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */
10246     numshared = SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash,
10247         NULL, NULL, NULL);
10248     numshared_expected = 1;
10249     hash_expected = NID_sha256;
10250     sig_expected = NID_rsassaPss;
10251     signame_expected = "rsa_pss_rsae_sha256";
10252     switch (idx) {
10253     case 0:
10254         hash_expected = NID_sha384;
10255         signame_expected = "rsa_pss_rsae_sha384";
10256         /* FALLTHROUGH */
10257     case 3:
10258         numshared_expected = 2;
10259         break;
10260     case 4:
10261     case 5:
10262         sig_expected = EVP_PKEY_EC;
10263         signame_expected = "ecdsa_secp256r1_sha256";
10264         break;
10265     }
10266     if (!TEST_int_eq(numshared, numshared_expected)
10267         || !TEST_int_eq(hash, hash_expected)
10268         || !TEST_int_eq(sig, sig_expected)
10269         || !TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name))
10270         || !TEST_ptr(sigalg_name)
10271         || !TEST_str_eq(sigalg_name, signame_expected))
10272         goto end;
10273 
10274     testresult = filter_provider_check_clean_finish();
10275 
10276 end:
10277     SSL_free(serverssl);
10278     SSL_free(clientssl);
10279     SSL_CTX_free(sctx);
10280     SSL_CTX_free(cctx);
10281     OSSL_PROVIDER_unload(filterprov);
10282     OSSL_LIB_CTX_free(tmpctx);
10283 
10284     return testresult;
10285 }
10286 #endif /*                                                                     \
10287         * !defined(OPENSSL_NO_EC)                                             \
10288         * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)) \
10289         */
10290 
10291 #ifndef OPENSSL_NO_TLS1_3
10292 /* This test can run in TLSv1.3 even if ec and dh are disabled */
test_pluggable_group(int idx)10293 static int test_pluggable_group(int idx)
10294 {
10295     SSL_CTX *cctx = NULL, *sctx = NULL;
10296     SSL *clientssl = NULL, *serverssl = NULL;
10297     int testresult = 0;
10298     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
10299     /* Check that we are not impacted by a provider without any groups */
10300     OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy");
10301     const char *group_name = idx == 0 ? "xorkemgroup" : "xorgroup";
10302 
10303     if (!TEST_ptr(tlsprov))
10304         goto end;
10305 
10306     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10307             TLS_client_method(),
10308             TLS1_3_VERSION,
10309             TLS1_3_VERSION,
10310             &sctx, &cctx, cert, privkey))
10311         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10312             NULL, NULL)))
10313         goto end;
10314 
10315     /* ensure GROUPLIST_INCREMENT (=40) logic triggers: */
10316     if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup:xorkemgroup:dummy1:dummy2:dummy3:dummy4:dummy5:dummy6:dummy7:dummy8:dummy9:dummy10:dummy11:dummy12:dummy13:dummy14:dummy15:dummy16:dummy17:dummy18:dummy19:dummy20:dummy21:dummy22:dummy23:dummy24:dummy25:dummy26:dummy27:dummy28:dummy29:dummy30:dummy31:dummy32:dummy33:dummy34:dummy35:dummy36:dummy37:dummy38:dummy39:dummy40:dummy41:dummy42:dummy43"))
10317         /* removing a single algorithm from the list makes the test pass */
10318         || !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
10319         goto end;
10320 
10321     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10322         goto end;
10323 
10324     if (!TEST_str_eq(group_name,
10325             SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
10326         goto end;
10327 
10328     if (!TEST_str_eq(group_name, SSL_get0_group_name(serverssl))
10329         || !TEST_str_eq(group_name, SSL_get0_group_name(clientssl)))
10330         goto end;
10331 
10332     testresult = 1;
10333 
10334 end:
10335     SSL_free(serverssl);
10336     SSL_free(clientssl);
10337     SSL_CTX_free(sctx);
10338     SSL_CTX_free(cctx);
10339     OSSL_PROVIDER_unload(tlsprov);
10340     OSSL_PROVIDER_unload(legacyprov);
10341 
10342     return testresult;
10343 }
10344 
10345 /*
10346  * This function triggers encode, decode and sign functions
10347  * of the artificial "xorhmacsig" algorithm implemented in tls-provider
10348  * creating private key and certificate files for use in TLS testing.
10349  */
create_cert_key(int idx,char * certfilename,char * privkeyfilename)10350 static int create_cert_key(int idx, char *certfilename, char *privkeyfilename)
10351 {
10352     EVP_PKEY_CTX *evpctx = EVP_PKEY_CTX_new_from_name(libctx,
10353         (idx == 0) ? "xorhmacsig" : "xorhmacsha2sig", NULL);
10354     EVP_PKEY *pkey = NULL;
10355     X509 *x509 = X509_new();
10356     X509_NAME *name = NULL;
10357     BIO *keybio = NULL, *certbio = NULL;
10358     int ret = 1;
10359 
10360     if (!TEST_ptr(evpctx)
10361         || !TEST_int_gt(EVP_PKEY_keygen_init(evpctx), 0)
10362         || !TEST_true(EVP_PKEY_generate(evpctx, &pkey))
10363         || !TEST_ptr(pkey)
10364         || !TEST_ptr(x509)
10365         || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(x509), 1))
10366         || !TEST_true(X509_gmtime_adj(X509_getm_notBefore(x509), 0))
10367         || !TEST_true(X509_gmtime_adj(X509_getm_notAfter(x509), 31536000L))
10368         || !TEST_true(X509_set_pubkey(x509, pkey))
10369         || !TEST_ptr(name = X509_get_subject_name(x509))
10370         || !TEST_true(X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
10371             (unsigned char *)"CH", -1, -1, 0))
10372         || !TEST_true(X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
10373             (unsigned char *)"test.org", -1, -1, 0))
10374         || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
10375             (unsigned char *)"localhost", -1, -1, 0))
10376         || !TEST_true(X509_set_issuer_name(x509, name))
10377         || !TEST_true(X509_sign(x509, pkey, EVP_sha1()))
10378         || !TEST_ptr(keybio = BIO_new_file(privkeyfilename, "wb"))
10379         || !TEST_true(PEM_write_bio_PrivateKey(keybio, pkey, NULL, NULL, 0, NULL, NULL))
10380         || !TEST_ptr(certbio = BIO_new_file(certfilename, "wb"))
10381         || !TEST_true(PEM_write_bio_X509(certbio, x509)))
10382         ret = 0;
10383 
10384     EVP_PKEY_free(pkey);
10385     X509_free(x509);
10386     EVP_PKEY_CTX_free(evpctx);
10387     BIO_free(keybio);
10388     BIO_free(certbio);
10389     return ret;
10390 }
10391 
10392 /*
10393  * Test that signature algorithms loaded via the provider interface can
10394  * correctly establish a TLS (1.3) connection.
10395  * Test 0: Signature algorithm with built-in hashing functionality: "xorhmacsig"
10396  * Test 1: Signature algorithm using external SHA2 hashing: "xorhmacsha2sig"
10397  * Test 2: Signature algorithm with built-in hashing configured via SSL_CONF_cmd
10398  * Test 3: Test 0 using RPK
10399  * Test 4: Test 1 using RPK
10400  * Test 5: Test 2 using RPK
10401  */
test_pluggable_signature(int idx)10402 static int test_pluggable_signature(int idx)
10403 {
10404     static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
10405     SSL_CTX *cctx = NULL, *sctx = NULL;
10406     SSL *clientssl = NULL, *serverssl = NULL;
10407     int testresult = 0;
10408     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
10409     OSSL_PROVIDER *defaultprov = OSSL_PROVIDER_load(libctx, "default");
10410     char *certfilename = "tls-prov-cert.pem";
10411     char *privkeyfilename = "tls-prov-key.pem";
10412     const char *sigalg_name = NULL, *expected_sigalg_name;
10413     int sigidx = idx % 3;
10414     int rpkidx = idx / 3;
10415     int do_conf_cmd = 0;
10416 
10417     if (sigidx == 2) {
10418         sigidx = 0;
10419         do_conf_cmd = 1;
10420     }
10421 
10422     /* See create_cert_key() above */
10423     expected_sigalg_name = (sigidx == 0) ? "xorhmacsig" : "xorhmacsha2sig";
10424 
10425     /* create key and certificate for the different algorithm types */
10426     if (!TEST_ptr(tlsprov)
10427         || !TEST_true(create_cert_key(sigidx, certfilename, privkeyfilename)))
10428         goto end;
10429 
10430     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10431             TLS_client_method(),
10432             TLS1_3_VERSION,
10433             TLS1_3_VERSION,
10434             &sctx, &cctx, NULL, NULL)))
10435         goto end;
10436 
10437     if (do_conf_cmd) {
10438         SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
10439 
10440         if (!TEST_ptr(confctx))
10441             goto end;
10442         SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE | SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CERTIFICATE | SSL_CONF_FLAG_REQUIRE_PRIVATE | SSL_CONF_FLAG_SHOW_ERRORS);
10443         SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
10444         if (!TEST_int_gt(SSL_CONF_cmd(confctx, "Certificate", certfilename), 0)
10445             || !TEST_int_gt(SSL_CONF_cmd(confctx, "PrivateKey", privkeyfilename), 0)
10446             || !TEST_true(SSL_CONF_CTX_finish(confctx))) {
10447             SSL_CONF_CTX_free(confctx);
10448             goto end;
10449         }
10450         SSL_CONF_CTX_free(confctx);
10451     } else {
10452         if (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, certfilename,
10453                              SSL_FILETYPE_PEM),
10454                 1)
10455             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
10456                                 privkeyfilename,
10457                                 SSL_FILETYPE_PEM),
10458                 1))
10459             goto end;
10460     }
10461     if (!TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
10462         goto end;
10463 
10464     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10465             NULL, NULL)))
10466         goto end;
10467 
10468     /* Enable RPK for server cert */
10469     if (rpkidx) {
10470         if (!TEST_true(SSL_set1_server_cert_type(serverssl, cert_type_rpk, sizeof(cert_type_rpk)))
10471             || !TEST_true(SSL_set1_server_cert_type(clientssl, cert_type_rpk, sizeof(cert_type_rpk))))
10472             goto end;
10473     }
10474 
10475     /* This is necessary to pass minimal setup w/o other groups configured */
10476     if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup"))
10477         || !TEST_true(SSL_set1_groups_list(clientssl, "xorgroup")))
10478         goto end;
10479 
10480     /*
10481      * If this connection gets established, it must have been completed
10482      * via the tls-provider-implemented "hmacsig" algorithm, testing
10483      * both sign and verify functions during handshake.
10484      */
10485     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10486         goto end;
10487 
10488     /* If using RPK, make sure we got one */
10489     if (rpkidx && !TEST_long_eq(SSL_get_verify_result(clientssl), X509_V_ERR_RPK_UNTRUSTED))
10490         goto end;
10491 
10492     if (!TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name))
10493         || !TEST_str_eq(sigalg_name, expected_sigalg_name)
10494         || !TEST_ptr(sigalg_name))
10495         goto end;
10496 
10497     testresult = 1;
10498 
10499 end:
10500     SSL_free(serverssl);
10501     SSL_free(clientssl);
10502     SSL_CTX_free(sctx);
10503     SSL_CTX_free(cctx);
10504     OSSL_PROVIDER_unload(tlsprov);
10505     OSSL_PROVIDER_unload(defaultprov);
10506 
10507     return testresult;
10508 }
10509 #endif
10510 
10511 #ifndef OPENSSL_NO_TLS1_2
test_ssl_dup(void)10512 static int test_ssl_dup(void)
10513 {
10514     SSL_CTX *cctx = NULL, *sctx = NULL;
10515     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
10516     int testresult = 0;
10517     BIO *rbio = NULL, *wbio = NULL;
10518 
10519     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10520             TLS_client_method(),
10521             0,
10522             0,
10523             &sctx, &cctx, cert, privkey)))
10524         goto end;
10525 
10526     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10527             NULL, NULL)))
10528         goto end;
10529 
10530     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10531         || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
10532         goto end;
10533 
10534     client2ssl = SSL_dup(clientssl);
10535     rbio = SSL_get_rbio(clientssl);
10536     if (!TEST_ptr(rbio)
10537         || !TEST_true(BIO_up_ref(rbio)))
10538         goto end;
10539     SSL_set0_rbio(client2ssl, rbio);
10540     rbio = NULL;
10541 
10542     wbio = SSL_get_wbio(clientssl);
10543     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
10544         goto end;
10545     SSL_set0_wbio(client2ssl, wbio);
10546     rbio = NULL;
10547 
10548     if (!TEST_ptr(client2ssl)
10549         /* Handshake not started so pointers should be different */
10550         || !TEST_ptr_ne(clientssl, client2ssl))
10551         goto end;
10552 
10553     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
10554         || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
10555         goto end;
10556 
10557     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
10558         goto end;
10559 
10560     SSL_free(clientssl);
10561     clientssl = SSL_dup(client2ssl);
10562     if (!TEST_ptr(clientssl)
10563         /* Handshake has finished so pointers should be the same */
10564         || !TEST_ptr_eq(clientssl, client2ssl))
10565         goto end;
10566 
10567     testresult = 1;
10568 
10569 end:
10570     SSL_free(serverssl);
10571     SSL_free(clientssl);
10572     SSL_free(client2ssl);
10573     SSL_CTX_free(sctx);
10574     SSL_CTX_free(cctx);
10575 
10576     return testresult;
10577 }
10578 
secret_cb(SSL * s,void * secretin,int * secret_len,STACK_OF (SSL_CIPHER)* peer_ciphers,const SSL_CIPHER ** cipher,void * arg)10579 static int secret_cb(SSL *s, void *secretin, int *secret_len,
10580     STACK_OF(SSL_CIPHER) *peer_ciphers,
10581     const SSL_CIPHER **cipher, void *arg)
10582 {
10583     int i;
10584     unsigned char *secret = secretin;
10585 
10586     /* Just use a fixed master secret */
10587     for (i = 0; i < *secret_len; i++)
10588         secret[i] = 0xff;
10589 
10590     /* We don't set a preferred cipher */
10591 
10592     return 1;
10593 }
10594 
10595 /*
10596  * Test the session_secret_cb which is designed for use with EAP-FAST
10597  */
test_session_secret_cb(void)10598 static int test_session_secret_cb(void)
10599 {
10600     SSL_CTX *cctx = NULL, *sctx = NULL;
10601     SSL *clientssl = NULL, *serverssl = NULL;
10602     SSL_SESSION *secret_sess = NULL;
10603     int testresult = 0;
10604 
10605     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10606             TLS_client_method(),
10607             0,
10608             0,
10609             &sctx, &cctx, cert, privkey)))
10610         goto end;
10611 
10612     /* Create an initial connection and save the session */
10613     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10614             NULL, NULL)))
10615         goto end;
10616 
10617     /* session_secret_cb does not support TLSv1.3 */
10618     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10619         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION)))
10620         goto end;
10621 
10622     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10623         goto end;
10624 
10625     if (!TEST_ptr(secret_sess = SSL_get1_session(clientssl)))
10626         goto end;
10627 
10628     shutdown_ssl_connection(serverssl, clientssl);
10629     serverssl = clientssl = NULL;
10630 
10631     /* Resume the earlier session */
10632     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10633             NULL, NULL)))
10634         goto end;
10635 
10636     /*
10637      * No session ids for EAP-FAST - otherwise the state machine gets very
10638      * confused.
10639      */
10640     if (!TEST_true(SSL_SESSION_set1_id(secret_sess, NULL, 0)))
10641         goto end;
10642 
10643     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10644         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10645         || !TEST_true(SSL_set_session_secret_cb(serverssl, secret_cb,
10646             NULL))
10647         || !TEST_true(SSL_set_session_secret_cb(clientssl, secret_cb,
10648             NULL))
10649         || !TEST_true(SSL_set_session(clientssl, secret_sess)))
10650         goto end;
10651 
10652     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10653         goto end;
10654 
10655     testresult = 1;
10656 
10657 end:
10658     SSL_SESSION_free(secret_sess);
10659     SSL_free(serverssl);
10660     SSL_free(clientssl);
10661     SSL_CTX_free(sctx);
10662     SSL_CTX_free(cctx);
10663 
10664     return testresult;
10665 }
10666 
10667 #ifndef OPENSSL_NO_DH
10668 
10669 static EVP_PKEY *tmp_dh_params = NULL;
10670 
10671 /* Helper function for the test_set_tmp_dh() tests */
get_tmp_dh_params(void)10672 static EVP_PKEY *get_tmp_dh_params(void)
10673 {
10674     if (tmp_dh_params == NULL) {
10675         BIGNUM *p = NULL;
10676         OSSL_PARAM_BLD *tmpl = NULL;
10677         EVP_PKEY_CTX *pctx = NULL;
10678         OSSL_PARAM *params = NULL;
10679         EVP_PKEY *dhpkey = NULL;
10680 
10681         p = BN_get_rfc3526_prime_2048(NULL);
10682         if (!TEST_ptr(p))
10683             goto end;
10684 
10685         pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL);
10686         if (!TEST_ptr(pctx)
10687             || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx), 1))
10688             goto end;
10689 
10690         tmpl = OSSL_PARAM_BLD_new();
10691         if (!TEST_ptr(tmpl)
10692             || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl,
10693                 OSSL_PKEY_PARAM_FFC_P,
10694                 p))
10695             || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl,
10696                 OSSL_PKEY_PARAM_FFC_G,
10697                 2)))
10698             goto end;
10699 
10700         params = OSSL_PARAM_BLD_to_param(tmpl);
10701         if (!TEST_ptr(params)
10702             || !TEST_int_eq(EVP_PKEY_fromdata(pctx, &dhpkey,
10703                                 EVP_PKEY_KEY_PARAMETERS,
10704                                 params),
10705                 1))
10706             goto end;
10707 
10708         tmp_dh_params = dhpkey;
10709     end:
10710         BN_free(p);
10711         EVP_PKEY_CTX_free(pctx);
10712         OSSL_PARAM_BLD_free(tmpl);
10713         OSSL_PARAM_free(params);
10714     }
10715 
10716     if (tmp_dh_params != NULL && !EVP_PKEY_up_ref(tmp_dh_params))
10717         return NULL;
10718 
10719     return tmp_dh_params;
10720 }
10721 
10722 #ifndef OPENSSL_NO_DEPRECATED_3_0
10723 /* Callback used by test_set_tmp_dh() */
tmp_dh_callback(SSL * s,int is_export,int keylen)10724 static DH *tmp_dh_callback(SSL *s, int is_export, int keylen)
10725 {
10726     EVP_PKEY *dhpkey = get_tmp_dh_params();
10727     DH *ret = NULL;
10728 
10729     if (!TEST_ptr(dhpkey))
10730         return NULL;
10731 
10732     /*
10733      * libssl does not free the returned DH, so we free it now knowing that even
10734      * after we free dhpkey, there will still be a reference to the owning
10735      * EVP_PKEY in tmp_dh_params, and so the DH object will live for the length
10736      * of time we need it for.
10737      */
10738     ret = EVP_PKEY_get1_DH(dhpkey);
10739     DH_free(ret);
10740 
10741     EVP_PKEY_free(dhpkey);
10742 
10743     return ret;
10744 }
10745 #endif
10746 
10747 /*
10748  * Test the various methods for setting temporary DH parameters
10749  *
10750  * Test  0: Default (no auto) setting
10751  * Test  1: Explicit SSL_CTX auto off
10752  * Test  2: Explicit SSL auto off
10753  * Test  3: Explicit SSL_CTX auto on
10754  * Test  4: Explicit SSL auto on
10755  * Test  5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY
10756  * Test  6: Explicit SSL auto off, custom DH params via EVP_PKEY
10757  *
10758  * The following are testing deprecated APIs, so we only run them if available
10759  * Test  7: Explicit SSL_CTX auto off, custom DH params via DH
10760  * Test  8: Explicit SSL auto off, custom DH params via DH
10761  * Test  9: Explicit SSL_CTX auto off, custom DH params via callback
10762  * Test 10: Explicit SSL auto off, custom DH params via callback
10763  */
test_set_tmp_dh(int idx)10764 static int test_set_tmp_dh(int idx)
10765 {
10766     SSL_CTX *cctx = NULL, *sctx = NULL;
10767     SSL *clientssl = NULL, *serverssl = NULL;
10768     int testresult = 0;
10769     int dhauto = (idx == 3 || idx == 4) ? 1 : 0;
10770     int expected = (idx <= 2) ? 0 : 1;
10771     EVP_PKEY *dhpkey = NULL;
10772 #ifndef OPENSSL_NO_DEPRECATED_3_0
10773     DH *dh = NULL;
10774 #else
10775 
10776     if (idx >= 7)
10777         return 1;
10778 #endif
10779 
10780     if (idx >= 5 && idx <= 8) {
10781         dhpkey = get_tmp_dh_params();
10782         if (!TEST_ptr(dhpkey))
10783             goto end;
10784     }
10785 #ifndef OPENSSL_NO_DEPRECATED_3_0
10786     if (idx == 7 || idx == 8) {
10787         dh = EVP_PKEY_get1_DH(dhpkey);
10788         if (!TEST_ptr(dh))
10789             goto end;
10790     }
10791 #endif
10792 
10793     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10794             TLS_client_method(),
10795             0,
10796             0,
10797             &sctx, &cctx, cert, privkey)))
10798         goto end;
10799 
10800     if ((idx & 1) == 1) {
10801         if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto)))
10802             goto end;
10803     }
10804 
10805     if (idx == 5) {
10806         if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey)))
10807             goto end;
10808         dhpkey = NULL;
10809     }
10810 #ifndef OPENSSL_NO_DEPRECATED_3_0
10811     else if (idx == 7) {
10812         if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh)))
10813             goto end;
10814     } else if (idx == 9) {
10815         SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback);
10816     }
10817 #endif
10818 
10819     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10820             NULL, NULL)))
10821         goto end;
10822 
10823     if ((idx & 1) == 0 && idx != 0) {
10824         if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto)))
10825             goto end;
10826     }
10827     if (idx == 6) {
10828         if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey)))
10829             goto end;
10830         dhpkey = NULL;
10831     }
10832 #ifndef OPENSSL_NO_DEPRECATED_3_0
10833     else if (idx == 8) {
10834         if (!TEST_true(SSL_set_tmp_dh(serverssl, dh)))
10835             goto end;
10836     } else if (idx == 10) {
10837         SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback);
10838     }
10839 #endif
10840 
10841     if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10842         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10843         || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA")))
10844         goto end;
10845 
10846     /*
10847      * If autoon then we should succeed. Otherwise we expect failure because
10848      * there are no parameters
10849      */
10850     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
10851                          SSL_ERROR_NONE),
10852             expected))
10853         goto end;
10854 
10855     testresult = 1;
10856 
10857 end:
10858 #ifndef OPENSSL_NO_DEPRECATED_3_0
10859     DH_free(dh);
10860 #endif
10861     SSL_free(serverssl);
10862     SSL_free(clientssl);
10863     SSL_CTX_free(sctx);
10864     SSL_CTX_free(cctx);
10865     EVP_PKEY_free(dhpkey);
10866 
10867     return testresult;
10868 }
10869 
10870 /*
10871  * Test the auto DH keys are appropriately sized
10872  */
test_dh_auto(int idx)10873 static int test_dh_auto(int idx)
10874 {
10875     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method());
10876     SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10877     SSL *clientssl = NULL, *serverssl = NULL;
10878     int testresult = 0;
10879     EVP_PKEY *tmpkey = NULL;
10880     char *thiscert = NULL, *thiskey = NULL;
10881     size_t expdhsize = 0;
10882     const char *ciphersuite = "DHE-RSA-AES128-SHA";
10883 
10884     if (!TEST_ptr(sctx) || !TEST_ptr(cctx))
10885         goto end;
10886 
10887     switch (idx) {
10888     case 0:
10889         /* The FIPS provider doesn't support this DH size - so we ignore it */
10890         if (is_fips) {
10891             testresult = 1;
10892             goto end;
10893         }
10894         thiscert = cert1024;
10895         thiskey = privkey1024;
10896         expdhsize = 1024;
10897         SSL_CTX_set_security_level(sctx, 1);
10898         SSL_CTX_set_security_level(cctx, 1);
10899         break;
10900     case 1:
10901         /* 2048 bit prime */
10902         thiscert = cert;
10903         thiskey = privkey;
10904         expdhsize = 2048;
10905         break;
10906     case 2:
10907         thiscert = cert3072;
10908         thiskey = privkey3072;
10909         expdhsize = 3072;
10910         break;
10911     case 3:
10912         thiscert = cert4096;
10913         thiskey = privkey4096;
10914         expdhsize = 4096;
10915         break;
10916     case 4:
10917         thiscert = cert8192;
10918         thiskey = privkey8192;
10919         expdhsize = 8192;
10920         break;
10921     /* No certificate cases */
10922     case 5:
10923         /* The FIPS provider doesn't support this DH size - so we ignore it */
10924         if (is_fips) {
10925             testresult = 1;
10926             goto end;
10927         }
10928         ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0";
10929         expdhsize = 1024;
10930         break;
10931     case 6:
10932         ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0";
10933         expdhsize = 3072;
10934         break;
10935     default:
10936         TEST_error("Invalid text index");
10937         goto end;
10938     }
10939 
10940     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL,
10941             NULL,
10942             0,
10943             0,
10944             &sctx, &cctx, thiscert, thiskey)))
10945         goto end;
10946 
10947     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10948             NULL, NULL)))
10949         goto end;
10950 
10951     if (!TEST_true(SSL_set_dh_auto(serverssl, 1))
10952         || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10953         || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10954         || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite))
10955         || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite)))
10956         goto end;
10957 
10958     /*
10959      * Send the server's first flight. At this point the server has created the
10960      * temporary DH key but hasn't finished using it yet. Once used it is
10961      * removed, so we cannot test it.
10962      */
10963     if (!TEST_int_le(SSL_connect(clientssl), 0)
10964         || !TEST_int_le(SSL_accept(serverssl), 0))
10965         goto end;
10966 
10967     if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0))
10968         goto end;
10969     if (!TEST_size_t_eq(EVP_PKEY_get_bits(tmpkey), expdhsize))
10970         goto end;
10971 
10972     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10973         goto end;
10974 
10975     testresult = 1;
10976 
10977 end:
10978     SSL_free(serverssl);
10979     SSL_free(clientssl);
10980     SSL_CTX_free(sctx);
10981     SSL_CTX_free(cctx);
10982     EVP_PKEY_free(tmpkey);
10983 
10984     return testresult;
10985 }
10986 #endif /* OPENSSL_NO_DH */
10987 #endif /* OPENSSL_NO_TLS1_2 */
10988 
10989 #ifndef OSSL_NO_USABLE_TLS1_3
10990 /*
10991  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
10992  * that it works even without a certificate configured for the original
10993  * SSL_CTX
10994  */
test_sni_tls13(void)10995 static int test_sni_tls13(void)
10996 {
10997     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
10998     SSL *clientssl = NULL, *serverssl = NULL;
10999     int testresult = 0;
11000 
11001     /* Reset callback counter */
11002     snicb = 0;
11003 
11004     /* Create an initial SSL_CTX with no certificate configured */
11005     sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11006     if (!TEST_ptr(sctx))
11007         goto end;
11008     /* Require TLSv1.3 as a minimum */
11009     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11010             TLS_client_method(), TLS1_3_VERSION, 0,
11011             &sctx2, &cctx, cert, privkey)))
11012         goto end;
11013 
11014     /* Set up SNI */
11015     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
11016         || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
11017         goto end;
11018 
11019     /*
11020      * Connection should still succeed because the final SSL_CTX has the right
11021      * certificates configured.
11022      */
11023     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11024             &clientssl, NULL, NULL))
11025         || !TEST_true(create_ssl_connection(serverssl, clientssl,
11026             SSL_ERROR_NONE)))
11027         goto end;
11028 
11029     /* We should have had the SNI callback called exactly once */
11030     if (!TEST_int_eq(snicb, 1))
11031         goto end;
11032 
11033     testresult = 1;
11034 
11035 end:
11036     SSL_free(serverssl);
11037     SSL_free(clientssl);
11038     SSL_CTX_free(sctx2);
11039     SSL_CTX_free(sctx);
11040     SSL_CTX_free(cctx);
11041     return testresult;
11042 }
11043 
11044 /*
11045  * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week
11046  * 0 = TLSv1.2
11047  * 1 = TLSv1.3
11048  */
test_ticket_lifetime(int idx)11049 static int test_ticket_lifetime(int idx)
11050 {
11051     SSL_CTX *cctx = NULL, *sctx = NULL;
11052     SSL *clientssl = NULL, *serverssl = NULL;
11053     int testresult = 0;
11054     int version = TLS1_3_VERSION;
11055 
11056 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
11057 #define TWO_WEEK_SEC (2 * ONE_WEEK_SEC)
11058 
11059     if (idx == 0) {
11060 #ifdef OPENSSL_NO_TLS1_2
11061         return TEST_skip("TLS 1.2 is disabled.");
11062 #else
11063         version = TLS1_2_VERSION;
11064 #endif
11065     }
11066 
11067     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11068             TLS_client_method(), version, version,
11069             &sctx, &cctx, cert, privkey)))
11070         goto end;
11071 
11072     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11073             &clientssl, NULL, NULL)))
11074         goto end;
11075 
11076     /*
11077      * Set the timeout to be more than 1 week
11078      * make sure the returned value is the default
11079      */
11080     if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC),
11081             SSL_get_default_timeout(serverssl)))
11082         goto end;
11083 
11084     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11085         goto end;
11086 
11087     if (idx == 0) {
11088         /* TLSv1.2 uses the set value */
11089         if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC))
11090             goto end;
11091     } else {
11092         /* TLSv1.3 uses the limited value */
11093         if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC))
11094             goto end;
11095     }
11096     testresult = 1;
11097 
11098 end:
11099     SSL_free(serverssl);
11100     SSL_free(clientssl);
11101     SSL_CTX_free(sctx);
11102     SSL_CTX_free(cctx);
11103     return testresult;
11104 }
11105 #endif
11106 /*
11107  * Test that setting an ALPN does not violate RFC
11108  */
test_set_alpn(void)11109 static int test_set_alpn(void)
11110 {
11111     SSL_CTX *ctx = NULL;
11112     SSL *ssl = NULL;
11113     int testresult = 0;
11114 
11115     unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
11116     unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
11117     unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
11118     unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00 };
11119     unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd' };
11120     unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd' };
11121 
11122     /* Create an initial SSL_CTX with no certificate configured */
11123     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11124     if (!TEST_ptr(ctx))
11125         goto end;
11126 
11127     /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
11128     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
11129         goto end;
11130     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
11131         goto end;
11132     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
11133         goto end;
11134     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
11135         goto end;
11136     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
11137         goto end;
11138     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
11139         goto end;
11140     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
11141         goto end;
11142     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
11143         goto end;
11144     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
11145         goto end;
11146 
11147     ssl = SSL_new(ctx);
11148     if (!TEST_ptr(ssl))
11149         goto end;
11150 
11151     if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
11152         goto end;
11153     if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
11154         goto end;
11155     if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
11156         goto end;
11157     if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
11158         goto end;
11159     if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
11160         goto end;
11161     if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
11162         goto end;
11163     if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
11164         goto end;
11165     if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
11166         goto end;
11167     if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
11168         goto end;
11169 
11170     testresult = 1;
11171 
11172 end:
11173     SSL_free(ssl);
11174     SSL_CTX_free(ctx);
11175     return testresult;
11176 }
11177 
11178 /*
11179  * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store.
11180  */
test_set_verify_cert_store_ssl_ctx(void)11181 static int test_set_verify_cert_store_ssl_ctx(void)
11182 {
11183     SSL_CTX *ctx = NULL;
11184     int testresult = 0;
11185     X509_STORE *store = NULL, *new_store = NULL,
11186                *cstore = NULL, *new_cstore = NULL;
11187 
11188     /* Create an initial SSL_CTX. */
11189     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11190     if (!TEST_ptr(ctx))
11191         goto end;
11192 
11193     /* Retrieve verify store pointer. */
11194     if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11195         goto end;
11196 
11197     /* Retrieve chain store pointer. */
11198     if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11199         goto end;
11200 
11201     /* We haven't set any yet, so this should be NULL. */
11202     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11203         goto end;
11204 
11205     /* Create stores. We use separate stores so pointers are different. */
11206     new_store = X509_STORE_new();
11207     if (!TEST_ptr(new_store))
11208         goto end;
11209 
11210     new_cstore = X509_STORE_new();
11211     if (!TEST_ptr(new_cstore))
11212         goto end;
11213 
11214     /* Set stores. */
11215     if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store)))
11216         goto end;
11217 
11218     if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore)))
11219         goto end;
11220 
11221     /* Should be able to retrieve the same pointer. */
11222     if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11223         goto end;
11224 
11225     if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11226         goto end;
11227 
11228     if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
11229         goto end;
11230 
11231     /* Should be able to unset again. */
11232     if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL)))
11233         goto end;
11234 
11235     if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL)))
11236         goto end;
11237 
11238     /* Should now be NULL. */
11239     if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11240         goto end;
11241 
11242     if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11243         goto end;
11244 
11245     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11246         goto end;
11247 
11248     testresult = 1;
11249 
11250 end:
11251     X509_STORE_free(new_store);
11252     X509_STORE_free(new_cstore);
11253     SSL_CTX_free(ctx);
11254     return testresult;
11255 }
11256 
11257 /*
11258  * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store.
11259  */
test_set_verify_cert_store_ssl(void)11260 static int test_set_verify_cert_store_ssl(void)
11261 {
11262     SSL_CTX *ctx = NULL;
11263     SSL *ssl = NULL;
11264     int testresult = 0;
11265     X509_STORE *store = NULL, *new_store = NULL,
11266                *cstore = NULL, *new_cstore = NULL;
11267 
11268     /* Create an initial SSL_CTX. */
11269     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11270     if (!TEST_ptr(ctx))
11271         goto end;
11272 
11273     /* Create an SSL object. */
11274     ssl = SSL_new(ctx);
11275     if (!TEST_ptr(ssl))
11276         goto end;
11277 
11278     /* Retrieve verify store pointer. */
11279     if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11280         goto end;
11281 
11282     /* Retrieve chain store pointer. */
11283     if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11284         goto end;
11285 
11286     /* We haven't set any yet, so this should be NULL. */
11287     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11288         goto end;
11289 
11290     /* Create stores. We use separate stores so pointers are different. */
11291     new_store = X509_STORE_new();
11292     if (!TEST_ptr(new_store))
11293         goto end;
11294 
11295     new_cstore = X509_STORE_new();
11296     if (!TEST_ptr(new_cstore))
11297         goto end;
11298 
11299     /* Set stores. */
11300     if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store)))
11301         goto end;
11302 
11303     if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore)))
11304         goto end;
11305 
11306     /* Should be able to retrieve the same pointer. */
11307     if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11308         goto end;
11309 
11310     if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11311         goto end;
11312 
11313     if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
11314         goto end;
11315 
11316     /* Should be able to unset again. */
11317     if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL)))
11318         goto end;
11319 
11320     if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL)))
11321         goto end;
11322 
11323     /* Should now be NULL. */
11324     if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11325         goto end;
11326 
11327     if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11328         goto end;
11329 
11330     if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11331         goto end;
11332 
11333     testresult = 1;
11334 
11335 end:
11336     X509_STORE_free(new_store);
11337     X509_STORE_free(new_cstore);
11338     SSL_free(ssl);
11339     SSL_CTX_free(ctx);
11340     return testresult;
11341 }
11342 
test_inherit_verify_param(void)11343 static int test_inherit_verify_param(void)
11344 {
11345     int testresult = 0;
11346 
11347     SSL_CTX *ctx = NULL;
11348     X509_VERIFY_PARAM *cp = NULL;
11349     SSL *ssl = NULL;
11350     X509_VERIFY_PARAM *sp = NULL;
11351     int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
11352 
11353     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11354     if (!TEST_ptr(ctx))
11355         goto end;
11356 
11357     cp = SSL_CTX_get0_param(ctx);
11358     if (!TEST_ptr(cp))
11359         goto end;
11360     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
11361         goto end;
11362 
11363     X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
11364 
11365     ssl = SSL_new(ctx);
11366     if (!TEST_ptr(ssl))
11367         goto end;
11368 
11369     sp = SSL_get0_param(ssl);
11370     if (!TEST_ptr(sp))
11371         goto end;
11372     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
11373         goto end;
11374 
11375     testresult = 1;
11376 
11377 end:
11378     SSL_free(ssl);
11379     SSL_CTX_free(ctx);
11380 
11381     return testresult;
11382 }
11383 
test_load_dhfile(void)11384 static int test_load_dhfile(void)
11385 {
11386 #ifndef OPENSSL_NO_DH
11387     int testresult = 0;
11388 
11389     SSL_CTX *ctx = NULL;
11390     SSL_CONF_CTX *cctx = NULL;
11391 
11392     if (dhfile == NULL)
11393         return 1;
11394 
11395     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()))
11396         || !TEST_ptr(cctx = SSL_CONF_CTX_new()))
11397         goto end;
11398 
11399     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
11400     SSL_CONF_CTX_set_flags(cctx,
11401         SSL_CONF_FLAG_CERTIFICATE
11402             | SSL_CONF_FLAG_SERVER
11403             | SSL_CONF_FLAG_FILE);
11404 
11405     if (!TEST_int_eq(SSL_CONF_cmd(cctx, "DHParameters", dhfile), 2))
11406         goto end;
11407 
11408     testresult = 1;
11409 end:
11410     SSL_CONF_CTX_free(cctx);
11411     SSL_CTX_free(ctx);
11412 
11413     return testresult;
11414 #else
11415     return TEST_skip("DH not supported by this build");
11416 #endif
11417 }
11418 
11419 #ifndef OSSL_NO_USABLE_TLS1_3
11420 /* Test that read_ahead works across a key change */
test_read_ahead_key_change(void)11421 static int test_read_ahead_key_change(void)
11422 {
11423     SSL_CTX *cctx = NULL, *sctx = NULL;
11424     SSL *clientssl = NULL, *serverssl = NULL;
11425     int testresult = 0;
11426     char *msg = "Hello World";
11427     size_t written, readbytes;
11428     char buf[80];
11429     int i;
11430 
11431     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11432             TLS_client_method(), TLS1_3_VERSION, 0,
11433             &sctx, &cctx, cert, privkey)))
11434         goto end;
11435 
11436     SSL_CTX_set_read_ahead(sctx, 1);
11437 
11438     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11439             &clientssl, NULL, NULL)))
11440         goto end;
11441 
11442     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11443         goto end;
11444 
11445     /* Write some data, send a key update, write more data */
11446     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11447         || !TEST_size_t_eq(written, strlen(msg)))
11448         goto end;
11449 
11450     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
11451         goto end;
11452 
11453     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11454         || !TEST_size_t_eq(written, strlen(msg)))
11455         goto end;
11456 
11457     /*
11458      * Since read_ahead is on the first read below should read the record with
11459      * the first app data, the second record with the key update message, and
11460      * the third record with the app data all in one go. We should be able to
11461      * still process the read_ahead data correctly even though it crosses
11462      * epochs
11463      */
11464     for (i = 0; i < 2; i++) {
11465         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11466                 &readbytes)))
11467             goto end;
11468 
11469         buf[readbytes] = '\0';
11470         if (!TEST_str_eq(buf, msg))
11471             goto end;
11472     }
11473 
11474     testresult = 1;
11475 
11476 end:
11477     SSL_free(serverssl);
11478     SSL_free(clientssl);
11479     SSL_CTX_free(sctx);
11480     SSL_CTX_free(cctx);
11481     return testresult;
11482 }
11483 
record_pad_cb(SSL * s,int type,size_t len,void * arg)11484 static size_t record_pad_cb(SSL *s, int type, size_t len, void *arg)
11485 {
11486     int *called = arg;
11487 
11488     switch ((*called)++) {
11489     case 0:
11490         /* Add some padding to first record */
11491         return 512;
11492     case 1:
11493         /* Maximally pad the second record */
11494         return SSL3_RT_MAX_PLAIN_LENGTH - len;
11495     case 2:
11496         /*
11497          * Exceeding the maximum padding should be fine. It should just pad to
11498          * the maximum anyway
11499          */
11500         return SSL3_RT_MAX_PLAIN_LENGTH + 1 - len;
11501     case 3:
11502         /*
11503          * Very large padding should also be ok. Should just pad to the maximum
11504          * allowed
11505          */
11506         return SIZE_MAX;
11507     default:
11508         return 0;
11509     }
11510 }
11511 
11512 /*
11513  * Test that setting record padding in TLSv1.3 works as expected
11514  * Test 0: Record padding callback on the SSL_CTX
11515  * Test 1: Record padding callback on the SSL
11516  * Test 2: Record block padding on the SSL_CTX
11517  * Test 3: Record block padding on the SSL
11518  * Test 4: Extended record block padding on the SSL_CTX
11519  * Test 5: Extended record block padding on the SSL
11520  */
test_tls13_record_padding(int idx)11521 static int test_tls13_record_padding(int idx)
11522 {
11523     SSL_CTX *cctx = NULL, *sctx = NULL;
11524     SSL *clientssl = NULL, *serverssl = NULL;
11525     int testresult = 0;
11526     char *msg = "Hello World";
11527     size_t written, readbytes;
11528     char buf[80];
11529     int i;
11530     int called = 0;
11531 
11532     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11533             TLS_client_method(), TLS1_3_VERSION, 0,
11534             &sctx, &cctx, cert, privkey)))
11535         goto end;
11536 
11537     if (idx == 0) {
11538         SSL_CTX_set_record_padding_callback(cctx, record_pad_cb);
11539         SSL_CTX_set_record_padding_callback_arg(cctx, &called);
11540         if (!TEST_ptr_eq(SSL_CTX_get_record_padding_callback_arg(cctx), &called))
11541             goto end;
11542     } else if (idx == 2) {
11543         /* Exceeding the max plain length should fail */
11544         if (!TEST_false(SSL_CTX_set_block_padding(cctx,
11545                 SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11546             goto end;
11547         if (!TEST_true(SSL_CTX_set_block_padding(cctx, 512)))
11548             goto end;
11549     } else if (idx == 4) {
11550         /* pad only handshake/alert messages */
11551         if (!TEST_true(SSL_CTX_set_block_padding_ex(cctx, 0, 512)))
11552             goto end;
11553     }
11554 
11555     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11556             &clientssl, NULL, NULL)))
11557         goto end;
11558 
11559     if (idx == 1) {
11560         SSL_set_record_padding_callback(clientssl, record_pad_cb);
11561         SSL_set_record_padding_callback_arg(clientssl, &called);
11562         if (!TEST_ptr_eq(SSL_get_record_padding_callback_arg(clientssl), &called))
11563             goto end;
11564     } else if (idx == 3) {
11565         /* Exceeding the max plain length should fail */
11566         if (!TEST_false(SSL_set_block_padding(clientssl,
11567                 SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11568             goto end;
11569         if (!TEST_true(SSL_set_block_padding(clientssl, 512)))
11570             goto end;
11571     } else if (idx == 5) {
11572         /* Exceeding the max plain length should fail */
11573         if (!TEST_false(SSL_set_block_padding_ex(clientssl, 0,
11574                 SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11575             goto end;
11576         /* pad server and client handshake only */
11577         if (!TEST_true(SSL_set_block_padding_ex(clientssl, 0, 512)))
11578             goto end;
11579         if (!TEST_true(SSL_set_block_padding_ex(serverssl, 0, 512)))
11580             goto end;
11581     }
11582 
11583     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11584         goto end;
11585 
11586     called = 0;
11587     /*
11588      * Write some data, then check we can read it. Do this four times to check
11589      * we can continue to write and read padded data after the initial record
11590      * padding has been added. We don't actually check that the padding has
11591      * been applied to the record - just that we can continue to communicate
11592      * normally and that the callback has been called (if appropriate).
11593      */
11594     for (i = 0; i < 4; i++) {
11595         if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11596             || !TEST_size_t_eq(written, strlen(msg)))
11597             goto end;
11598 
11599         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11600                 &readbytes))
11601             || !TEST_size_t_eq(written, readbytes))
11602             goto end;
11603 
11604         buf[readbytes] = '\0';
11605         if (!TEST_str_eq(buf, msg))
11606             goto end;
11607     }
11608 
11609     if ((idx == 0 || idx == 1) && !TEST_int_eq(called, 4))
11610         goto end;
11611 
11612     testresult = 1;
11613 end:
11614     SSL_free(serverssl);
11615     SSL_free(clientssl);
11616     SSL_CTX_free(sctx);
11617     SSL_CTX_free(cctx);
11618     return testresult;
11619 }
11620 #endif /* OSSL_NO_USABLE_TLS1_3 */
11621 
11622 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
11623 /*
11624  * Test TLSv1.2 with a pipeline capable cipher. TLSv1.3 and DTLS do not
11625  * support this yet. The only pipeline capable cipher that we have is in the
11626  * dasync engine (providers don't support this yet), so we have to use
11627  * deprecated APIs for this test.
11628  *
11629  * Test 0: Client has pipelining enabled, server does not
11630  * Test 1: Server has pipelining enabled, client does not
11631  * Test 2: Client has pipelining enabled, server does not: not enough data to
11632  *         fill all the pipelines
11633  * Test 3: Client has pipelining enabled, server does not: not enough data to
11634  *         fill all the pipelines by more than a full pipeline's worth
11635  * Test 4: Client has pipelining enabled, server does not: more data than all
11636  *         the available pipelines can take
11637  * Test 5: Client has pipelining enabled, server does not: Maximum size pipeline
11638  * Test 6: Repeat of test 0, but the engine is loaded late (after the SSL_CTX
11639  *         is created)
11640  */
test_pipelining(int idx)11641 static int test_pipelining(int idx)
11642 {
11643     SSL_CTX *cctx = NULL, *sctx = NULL;
11644     SSL *clientssl = NULL, *serverssl = NULL, *peera, *peerb;
11645     int testresult = 0, numreads;
11646     /* A 55 byte message */
11647     unsigned char *msg = (unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123";
11648     size_t written, readbytes, offset, msglen, fragsize = 10, numpipes = 5;
11649     size_t expectedreads;
11650     unsigned char *buf = NULL;
11651     ENGINE *e = NULL;
11652 
11653     if (idx != 6) {
11654         e = load_dasync();
11655         if (e == NULL)
11656             return 0;
11657     }
11658 
11659     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11660             TLS_client_method(), 0,
11661             TLS1_2_VERSION, &sctx, &cctx, cert,
11662             privkey)))
11663         goto end;
11664 
11665     if (idx == 6) {
11666         e = load_dasync();
11667         if (e == NULL)
11668             goto end;
11669         /* Now act like test 0 */
11670         idx = 0;
11671     }
11672 
11673     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11674             &clientssl, NULL, NULL)))
11675         goto end;
11676 
11677     if (!TEST_true(SSL_set_cipher_list(clientssl, "AES128-SHA")))
11678         goto end;
11679 
11680     /* peera is always configured for pipelining, while peerb is not. */
11681     if (idx == 1) {
11682         peera = serverssl;
11683         peerb = clientssl;
11684 
11685     } else {
11686         peera = clientssl;
11687         peerb = serverssl;
11688     }
11689 
11690     if (idx == 5) {
11691         numpipes = 2;
11692         /* Maximum allowed fragment size */
11693         fragsize = SSL3_RT_MAX_PLAIN_LENGTH;
11694         msglen = fragsize * numpipes;
11695         msg = OPENSSL_malloc(msglen);
11696         if (!TEST_ptr(msg))
11697             goto end;
11698         if (!TEST_int_gt(RAND_bytes_ex(libctx, msg, msglen, 0), 0))
11699             goto end;
11700     } else if (idx == 4) {
11701         msglen = 55;
11702     } else {
11703         msglen = 50;
11704     }
11705     if (idx == 2)
11706         msglen -= 2; /* Send 2 less bytes */
11707     else if (idx == 3)
11708         msglen -= 12; /* Send 12 less bytes */
11709 
11710     buf = OPENSSL_malloc(msglen);
11711     if (!TEST_ptr(buf))
11712         goto end;
11713 
11714     if (idx == 5) {
11715         /*
11716          * Test that setting a split send fragment longer than the maximum
11717          * allowed fails
11718          */
11719         if (!TEST_false(SSL_set_split_send_fragment(peera, fragsize + 1)))
11720             goto end;
11721     }
11722 
11723     /*
11724      * In the normal case. We have 5 pipelines with 10 bytes per pipeline
11725      * (50 bytes in total). This is a ridiculously small number of bytes -
11726      * but sufficient for our purposes
11727      */
11728     if (!TEST_true(SSL_set_max_pipelines(peera, numpipes))
11729         || !TEST_true(SSL_set_split_send_fragment(peera, fragsize)))
11730         goto end;
11731 
11732     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11733         goto end;
11734 
11735     /* Write some data from peera to peerb */
11736     if (!TEST_true(SSL_write_ex(peera, msg, msglen, &written))
11737         || !TEST_size_t_eq(written, msglen))
11738         goto end;
11739 
11740     /*
11741      * If the pipelining code worked, then we expect all |numpipes| pipelines to
11742      * have been used - except in test 3 where only |numpipes - 1| pipelines
11743      * will be used. This will result in |numpipes| records (|numpipes - 1| for
11744      * test 3) having been sent to peerb. Since peerb is not using read_ahead we
11745      * expect this to be read in |numpipes| or |numpipes - 1| separate
11746      * SSL_read_ex calls. In the case of test 4, there is then one additional
11747      * read for left over data that couldn't fit in the previous pipelines
11748      */
11749     for (offset = 0, numreads = 0;
11750         offset < msglen;
11751         offset += readbytes, numreads++) {
11752         if (!TEST_true(SSL_read_ex(peerb, buf + offset,
11753                 msglen - offset, &readbytes)))
11754             goto end;
11755     }
11756 
11757     expectedreads = idx == 4 ? numpipes + 1
11758                              : (idx == 3 ? numpipes - 1 : numpipes);
11759     if (!TEST_mem_eq(msg, msglen, buf, offset)
11760         || !TEST_int_eq(numreads, expectedreads))
11761         goto end;
11762 
11763     /*
11764      * Write some data from peerb to peera. We do this in up to |numpipes + 1|
11765      * chunks to exercise the read pipelining code on peera.
11766      */
11767     for (offset = 0; offset < msglen; offset += fragsize) {
11768         size_t sendlen = msglen - offset;
11769 
11770         if (sendlen > fragsize)
11771             sendlen = fragsize;
11772         if (!TEST_true(SSL_write_ex(peerb, msg + offset, sendlen, &written))
11773             || !TEST_size_t_eq(written, sendlen))
11774             goto end;
11775     }
11776 
11777     /*
11778      * The data was written in |numpipes|, |numpipes - 1| or |numpipes + 1|
11779      * separate chunks (depending on which test we are running). If the
11780      * pipelining is working then we expect peera to read up to numpipes chunks
11781      * and process them in parallel, giving back the complete result in a single
11782      * call to SSL_read_ex
11783      */
11784     if (!TEST_true(SSL_read_ex(peera, buf, msglen, &readbytes))
11785         || !TEST_size_t_le(readbytes, msglen))
11786         goto end;
11787 
11788     if (idx == 4) {
11789         size_t readbytes2;
11790 
11791         if (!TEST_true(SSL_read_ex(peera, buf + readbytes,
11792                 msglen - readbytes, &readbytes2)))
11793             goto end;
11794         readbytes += readbytes2;
11795         if (!TEST_size_t_le(readbytes, msglen))
11796             goto end;
11797     }
11798 
11799     if (!TEST_mem_eq(msg, msglen, buf, readbytes))
11800         goto end;
11801 
11802     testresult = 1;
11803 end:
11804     SSL_free(serverssl);
11805     SSL_free(clientssl);
11806     SSL_CTX_free(sctx);
11807     SSL_CTX_free(cctx);
11808     if (e != NULL) {
11809         ENGINE_unregister_ciphers(e);
11810         ENGINE_finish(e);
11811         ENGINE_free(e);
11812     }
11813     OPENSSL_free(buf);
11814     if (fragsize == SSL3_RT_MAX_PLAIN_LENGTH)
11815         OPENSSL_free(msg);
11816     return testresult;
11817 }
11818 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */
11819 
check_version_string(SSL * s,int version)11820 static int check_version_string(SSL *s, int version)
11821 {
11822     const char *verstr = NULL;
11823 
11824     switch (version) {
11825     case SSL3_VERSION:
11826         verstr = "SSLv3";
11827         break;
11828     case TLS1_VERSION:
11829         verstr = "TLSv1";
11830         break;
11831     case TLS1_1_VERSION:
11832         verstr = "TLSv1.1";
11833         break;
11834     case TLS1_2_VERSION:
11835         verstr = "TLSv1.2";
11836         break;
11837     case TLS1_3_VERSION:
11838         verstr = "TLSv1.3";
11839         break;
11840     case DTLS1_VERSION:
11841         verstr = "DTLSv1";
11842         break;
11843     case DTLS1_2_VERSION:
11844         verstr = "DTLSv1.2";
11845     }
11846 
11847     return TEST_str_eq(verstr, SSL_get_version(s));
11848 }
11849 
11850 /*
11851  * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and
11852  * SSL_is_dtls return the expected results for a (D)TLS connection. Compare with
11853  * test_version() in quicapitest.c which does the same thing for QUIC
11854  * connections.
11855  */
test_version(int idx)11856 static int test_version(int idx)
11857 {
11858     SSL_CTX *cctx = NULL, *sctx = NULL;
11859     SSL *clientssl = NULL, *serverssl = NULL;
11860     int testresult = 0, version;
11861     const SSL_METHOD *servmeth = TLS_server_method();
11862     const SSL_METHOD *clientmeth = TLS_client_method();
11863 
11864     switch (idx) {
11865 #if !defined(OPENSSL_NO_SSL3)
11866     case 0:
11867         version = SSL3_VERSION;
11868         break;
11869 #endif
11870 #if !defined(OPENSSL_NO_TLS1)
11871     case 1:
11872         version = TLS1_VERSION;
11873         break;
11874 #endif
11875 #if !defined(OPENSSL_NO_TLS1_2)
11876     case 2:
11877         version = TLS1_2_VERSION;
11878         break;
11879 #endif
11880 #if !defined(OSSL_NO_USABLE_TLS1_3)
11881     case 3:
11882         version = TLS1_3_VERSION;
11883         break;
11884 #endif
11885 #if !defined(OPENSSL_NO_DTLS1)
11886     case 4:
11887         version = DTLS1_VERSION;
11888         break;
11889 #endif
11890 #if !defined(OPENSSL_NO_DTLS1_2)
11891     case 5:
11892         version = DTLS1_2_VERSION;
11893         break;
11894 #endif
11895     /*
11896      * NB we do not support QUIC in this test. That is covered by quicapitest.c
11897      * We also don't support DTLS1_BAD_VER since we have no server support for
11898      * that.
11899      */
11900     default:
11901         TEST_skip("Unsupported protocol version");
11902         return 1;
11903     }
11904 
11905     if (is_fips
11906         && (version == SSL3_VERSION
11907             || version == TLS1_VERSION
11908             || version == DTLS1_VERSION)) {
11909         TEST_skip("Protocol version not supported with FIPS");
11910         return 1;
11911     }
11912 
11913 #if !defined(OPENSSL_NO_DTLS)
11914     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11915         servmeth = DTLS_server_method();
11916         clientmeth = DTLS_client_method();
11917     }
11918 #endif
11919 
11920     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, version,
11921             version, &sctx, &cctx, cert, privkey)))
11922         goto end;
11923 
11924     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
11925         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
11926             "DEFAULT:@SECLEVEL=0")))
11927         goto end;
11928 
11929     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11930             &clientssl, NULL, NULL)))
11931         goto end;
11932 
11933     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11934         goto end;
11935 
11936     if (!TEST_int_eq(SSL_version(serverssl), version)
11937         || !TEST_int_eq(SSL_version(clientssl), version)
11938         || !TEST_true(check_version_string(serverssl, version))
11939         || !TEST_true(check_version_string(clientssl, version)))
11940         goto end;
11941 
11942     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11943         if (!TEST_true(SSL_is_dtls(serverssl))
11944             || !TEST_true(SSL_is_dtls(clientssl))
11945             || !TEST_false(SSL_is_tls(serverssl))
11946             || !TEST_false(SSL_is_tls(clientssl))
11947             || !TEST_false(SSL_is_quic(serverssl))
11948             || !TEST_false(SSL_is_quic(clientssl)))
11949             goto end;
11950     } else {
11951         if (!TEST_true(SSL_is_tls(serverssl))
11952             || !TEST_true(SSL_is_tls(clientssl))
11953             || !TEST_false(SSL_is_dtls(serverssl))
11954             || !TEST_false(SSL_is_dtls(clientssl))
11955             || !TEST_false(SSL_is_quic(serverssl))
11956             || !TEST_false(SSL_is_quic(clientssl)))
11957             goto end;
11958     }
11959 
11960     testresult = 1;
11961 end:
11962     SSL_free(serverssl);
11963     SSL_free(clientssl);
11964     SSL_CTX_free(sctx);
11965     SSL_CTX_free(cctx);
11966     return testresult;
11967 }
11968 
11969 /*
11970  * Test that the SSL_rstate_string*() APIs return sane results
11971  */
test_rstate_string(void)11972 static int test_rstate_string(void)
11973 {
11974     SSL_CTX *cctx = NULL, *sctx = NULL;
11975     SSL *clientssl = NULL, *serverssl = NULL;
11976     int testresult = 0, version;
11977     const SSL_METHOD *servmeth = TLS_server_method();
11978     const SSL_METHOD *clientmeth = TLS_client_method();
11979     size_t written, readbytes;
11980     unsigned char buf[2];
11981     unsigned char dummyheader[SSL3_RT_HEADER_LENGTH] = {
11982         SSL3_RT_APPLICATION_DATA,
11983         TLS1_2_VERSION_MAJOR,
11984         0, /* To be filled in later */
11985         0,
11986         1
11987     };
11988 
11989     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, 0,
11990             0, &sctx, &cctx, cert, privkey)))
11991         goto end;
11992 
11993     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11994             &clientssl, NULL, NULL)))
11995         goto end;
11996 
11997     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11998         || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11999         goto end;
12000 
12001     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12002         goto end;
12003 
12004     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
12005         || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
12006         goto end;
12007 
12008     /* Fill in the correct version for the record header */
12009     version = SSL_version(serverssl);
12010     if (version == TLS1_3_VERSION)
12011         version = TLS1_2_VERSION;
12012     dummyheader[2] = version & 0xff;
12013 
12014     /*
12015      * Send a dummy header. If we continued to read the body as well this
12016      * would fail with a bad record mac, but we're not going to go that far.
12017      */
12018     if (!TEST_true(BIO_write_ex(SSL_get_rbio(serverssl), dummyheader,
12019             sizeof(dummyheader), &written))
12020         || !TEST_size_t_eq(written, SSL3_RT_HEADER_LENGTH))
12021         goto end;
12022 
12023     if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)))
12024         goto end;
12025 
12026     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RB")
12027         || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read body"))
12028         goto end;
12029 
12030     testresult = 1;
12031 end:
12032     SSL_free(serverssl);
12033     SSL_free(clientssl);
12034     SSL_CTX_free(sctx);
12035     SSL_CTX_free(cctx);
12036     return testresult;
12037 }
12038 
12039 /*
12040  * Force a write retry during handshaking. We test various combinations of
12041  * scenarios. We test a large certificate message which will fill the buffering
12042  * BIO used in the handshake. We try with client auth on and off. Finally we
12043  * also try a BIO that indicates retry via a 0 return. BIO_write() is documented
12044  * to indicate retry via -1 - but sometimes BIOs don't do that.
12045  *
12046  * Test 0: Standard certificate message
12047  * Test 1: Large certificate message
12048  * Test 2: Standard cert, verify peer
12049  * Test 3: Large cert, verify peer
12050  * Test 4: Standard cert, BIO returns 0 on retry
12051  * Test 5: Large cert, BIO returns 0 on retry
12052  * Test 6: Standard cert, verify peer, BIO returns 0 on retry
12053  * Test 7: Large cert, verify peer, BIO returns 0 on retry
12054  * Test 8-15: Repeat of above with TLSv1.2
12055  */
test_handshake_retry(int idx)12056 static int test_handshake_retry(int idx)
12057 {
12058     SSL_CTX *cctx = NULL, *sctx = NULL;
12059     SSL *clientssl = NULL, *serverssl = NULL;
12060     int testresult = 0;
12061     BIO *tmp = NULL, *bretry = BIO_new(bio_s_always_retry());
12062     int maxversion = 0;
12063 
12064     if (!TEST_ptr(bretry))
12065         goto end;
12066 
12067 #ifndef OPENSSL_NO_TLS1_2
12068     if ((idx & 8) == 8)
12069         maxversion = TLS1_2_VERSION;
12070 #else
12071     if ((idx & 8) == 8)
12072         return TEST_skip("No TLSv1.2");
12073 #endif
12074 
12075     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12076             TLS_client_method(), 0, maxversion,
12077             &sctx, &cctx, cert, privkey)))
12078         goto end;
12079 
12080     /*
12081      * Add a large amount of data to fill the buffering BIO used by the SSL
12082      * object
12083      */
12084     if ((idx & 1) == 1 && !ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
12085         goto end;
12086 
12087     /*
12088      * We don't actually configure a client cert, but neither do we fail if one
12089      * isn't present.
12090      */
12091     if ((idx & 2) == 2)
12092         SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
12093 
12094     if ((idx & 4) == 4)
12095         set_always_retry_err_val(0);
12096 
12097     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
12098             &clientssl, NULL, NULL)))
12099         goto end;
12100 
12101     tmp = SSL_get_wbio(serverssl);
12102     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
12103         tmp = NULL;
12104         goto end;
12105     }
12106     SSL_set0_wbio(serverssl, bretry);
12107     bretry = NULL;
12108 
12109     if (!TEST_int_eq(SSL_connect(clientssl), -1))
12110         goto end;
12111 
12112     if (!TEST_int_eq(SSL_accept(serverssl), -1)
12113         || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
12114         goto end;
12115 
12116     /* Restore a BIO that will let the write succeed */
12117     SSL_set0_wbio(serverssl, tmp);
12118     tmp = NULL;
12119 
12120     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12121         goto end;
12122 
12123     testresult = 1;
12124 end:
12125     SSL_free(serverssl);
12126     SSL_free(clientssl);
12127     SSL_CTX_free(sctx);
12128     SSL_CTX_free(cctx);
12129     BIO_free(bretry);
12130     BIO_free(tmp);
12131     set_always_retry_err_val(-1);
12132     return testresult;
12133 }
12134 
12135 /*
12136  * Test that receiving retries when writing application data works as expected
12137  */
test_data_retry(void)12138 static int test_data_retry(void)
12139 {
12140     SSL_CTX *cctx = NULL, *sctx = NULL;
12141     SSL *clientssl = NULL, *serverssl = NULL;
12142     int testresult = 0;
12143     unsigned char inbuf[1200], outbuf[1200];
12144     size_t i;
12145     BIO *tmp = NULL;
12146     BIO *bretry = BIO_new(bio_s_maybe_retry());
12147     size_t written, readbytes, totread = 0;
12148 
12149     if (!TEST_ptr(bretry))
12150         goto end;
12151 
12152     for (i = 0; i < sizeof(inbuf); i++)
12153         inbuf[i] = (unsigned char)(0xff & i);
12154     memset(outbuf, 0, sizeof(outbuf));
12155 
12156     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12157             TLS_client_method(), 0, 0, &sctx, &cctx,
12158             cert, privkey)))
12159         goto end;
12160 
12161     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12162             NULL)))
12163         goto end;
12164 
12165     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12166         goto end;
12167 
12168     /* Smallest possible max send fragment is 512 */
12169     if (!TEST_true(SSL_set_max_send_fragment(clientssl, 512)))
12170         goto end;
12171 
12172     tmp = SSL_get_wbio(clientssl);
12173     if (!TEST_ptr(tmp))
12174         goto end;
12175     if (!TEST_true(BIO_up_ref(tmp)))
12176         goto end;
12177     BIO_push(bretry, tmp);
12178     tmp = NULL;
12179     SSL_set0_wbio(clientssl, bretry);
12180     if (!BIO_up_ref(bretry)) {
12181         bretry = NULL;
12182         goto end;
12183     }
12184 
12185     for (i = 0; i < 3; i++) {
12186         /* We expect this call to make no progress and indicate retry */
12187         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12188             goto end;
12189         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
12190             goto end;
12191 
12192         /* Allow one write to progress, but the next one to signal retry */
12193         if (!TEST_true(BIO_ctrl(bretry, MAYBE_RETRY_CTRL_SET_RETRY_AFTER_CNT, 1,
12194                 NULL)))
12195             goto end;
12196 
12197         if (i == 2)
12198             break;
12199 
12200         /*
12201          * This call will hopefully make progress but will still indicate retry
12202          * because there is more data than will fit into a single record.
12203          */
12204         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12205             goto end;
12206         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
12207             goto end;
12208     }
12209 
12210     /* The final call should write the last chunk of data and succeed */
12211     if (!TEST_true(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12212         goto end;
12213     /* Read all the data available */
12214     while (SSL_read_ex(serverssl, outbuf + totread, sizeof(outbuf) - totread,
12215         &readbytes))
12216         totread += readbytes;
12217     if (!TEST_mem_eq(inbuf, sizeof(inbuf), outbuf, totread))
12218         goto end;
12219 
12220     testresult = 1;
12221 end:
12222     SSL_free(serverssl);
12223     SSL_free(clientssl);
12224     SSL_CTX_free(sctx);
12225     SSL_CTX_free(cctx);
12226     BIO_free_all(bretry);
12227     BIO_free(tmp);
12228     return testresult;
12229 }
12230 
12231 struct resume_servername_cb_data {
12232     int i;
12233     SSL_CTX *cctx;
12234     SSL_CTX *sctx;
12235     SSL_SESSION *sess;
12236     int recurse;
12237 };
12238 
12239 /*
12240  * Servername callback. We use it here to run another complete handshake using
12241  * the same session - and mark the session as not_resuamble at the end
12242  */
resume_servername_cb(SSL * s,int * ad,void * arg)12243 static int resume_servername_cb(SSL *s, int *ad, void *arg)
12244 {
12245     struct resume_servername_cb_data *cbdata = arg;
12246     SSL *serverssl = NULL, *clientssl = NULL;
12247     int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
12248 
12249     if (cbdata->recurse)
12250         return SSL_TLSEXT_ERR_ALERT_FATAL;
12251 
12252     if ((cbdata->i % 3) != 1)
12253         return SSL_TLSEXT_ERR_OK;
12254 
12255     cbdata->recurse = 1;
12256 
12257     if (!TEST_true(create_ssl_objects(cbdata->sctx, cbdata->cctx, &serverssl,
12258             &clientssl, NULL, NULL))
12259         || !TEST_true(SSL_set_session(clientssl, cbdata->sess)))
12260         goto end;
12261 
12262     ERR_set_mark();
12263     /*
12264      * We expect this to fail - because the servername cb will fail. This will
12265      * mark the session as not_resumable.
12266      */
12267     if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) {
12268         ERR_clear_last_mark();
12269         goto end;
12270     }
12271     ERR_pop_to_mark();
12272 
12273     ret = SSL_TLSEXT_ERR_OK;
12274 end:
12275     SSL_free(serverssl);
12276     SSL_free(clientssl);
12277     cbdata->recurse = 0;
12278     return ret;
12279 }
12280 /*
12281  * Test multiple resumptions and cache size handling
12282  * Test 0: TLSv1.3 (max_early_data set)
12283  * Test 1: TLSv1.3 (SSL_OP_NO_TICKET set)
12284  * Test 2: TLSv1.3 (max_early_data and SSL_OP_NO_TICKET set)
12285  * Test 3: TLSv1.3 (SSL_OP_NO_TICKET, simultaneous resumes)
12286  * Test 4: TLSv1.2
12287  */
test_multi_resume(int idx)12288 static int test_multi_resume(int idx)
12289 {
12290     SSL_CTX *sctx = NULL, *cctx = NULL;
12291     SSL *serverssl = NULL, *clientssl = NULL;
12292     SSL_SESSION *sess = NULL;
12293     int max_version = TLS1_3_VERSION;
12294     int i, testresult = 0;
12295     struct resume_servername_cb_data cbdata;
12296 
12297 #if defined(OPENSSL_NO_TLS1_2)
12298     if (idx == 4)
12299         return TEST_skip("TLSv1.2 is disabled in this build");
12300 #else
12301     if (idx == 4)
12302         max_version = TLS1_2_VERSION;
12303 #endif
12304 #if defined(OSSL_NO_USABLE_TLS1_3)
12305     if (idx != 4)
12306         return TEST_skip("No usable TLSv1.3 in this build");
12307 #endif
12308 
12309     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12310             TLS_client_method(), TLS1_VERSION,
12311             max_version, &sctx, &cctx, cert,
12312             privkey)))
12313         goto end;
12314 
12315     /*
12316      * TLSv1.3 only uses a session cache if either max_early_data > 0 (used for
12317      * replay protection), or if SSL_OP_NO_TICKET is in use
12318      */
12319     if (idx == 0 || idx == 2) {
12320         if (!TEST_true(SSL_CTX_set_max_early_data(sctx, 1024)))
12321             goto end;
12322     }
12323     if (idx == 1 || idx == 2 || idx == 3)
12324         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
12325 
12326     SSL_CTX_sess_set_cache_size(sctx, 5);
12327 
12328     if (idx == 3) {
12329         SSL_CTX_set_tlsext_servername_callback(sctx, resume_servername_cb);
12330         SSL_CTX_set_tlsext_servername_arg(sctx, &cbdata);
12331         cbdata.cctx = cctx;
12332         cbdata.sctx = sctx;
12333         cbdata.recurse = 0;
12334     }
12335 
12336     for (i = 0; i < 30; i++) {
12337         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
12338                 NULL, NULL))
12339             || !TEST_true(SSL_set_session(clientssl, sess)))
12340             goto end;
12341 
12342         /*
12343          * Check simultaneous resumes. We pause the connection part way through
12344          * the handshake by (mis)using the servername_cb. The pause occurs after
12345          * session resumption has already occurred, but before any session
12346          * tickets have been issued. While paused we run another complete
12347          * handshake resuming the same session.
12348          */
12349         if (idx == 3) {
12350             cbdata.i = i;
12351             cbdata.sess = sess;
12352         }
12353 
12354         /*
12355          * Recreate a bug where dynamically changing the max_early_data value
12356          * can cause sessions in the session cache which cannot be deleted.
12357          */
12358         if ((idx == 0 || idx == 2) && (i % 3) == 2)
12359             SSL_set_max_early_data(serverssl, 0);
12360 
12361         if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12362             goto end;
12363 
12364         if (sess == NULL || (idx == 0 && (i % 3) == 2)) {
12365             if (!TEST_false(SSL_session_reused(clientssl)))
12366                 goto end;
12367         } else {
12368             if (!TEST_true(SSL_session_reused(clientssl)))
12369                 goto end;
12370         }
12371         SSL_SESSION_free(sess);
12372 
12373         /* Do a full handshake, followed by two resumptions */
12374         if ((i % 3) == 2) {
12375             sess = NULL;
12376         } else {
12377             if (!TEST_ptr((sess = SSL_get1_session(clientssl))))
12378                 goto end;
12379         }
12380 
12381         SSL_shutdown(clientssl);
12382         SSL_shutdown(serverssl);
12383         SSL_free(serverssl);
12384         SSL_free(clientssl);
12385         serverssl = clientssl = NULL;
12386     }
12387 
12388     /* We should never exceed the session cache size limit */
12389     if (!TEST_long_le(SSL_CTX_sess_number(sctx), 5))
12390         goto end;
12391 
12392     testresult = 1;
12393 end:
12394     SSL_free(serverssl);
12395     SSL_free(clientssl);
12396     SSL_CTX_free(sctx);
12397     SSL_CTX_free(cctx);
12398     SSL_SESSION_free(sess);
12399     return testresult;
12400 }
12401 
12402 static struct next_proto_st {
12403     int serverlen;
12404     unsigned char server[40];
12405     int clientlen;
12406     unsigned char client[40];
12407     int expected_ret;
12408     size_t selectedlen;
12409     unsigned char selected[40];
12410 } next_proto_tests[] = {
12411     { 4, { 3, 'a', 'b', 'c' },
12412         4, { 3, 'a', 'b', 'c' },
12413         OPENSSL_NPN_NEGOTIATED,
12414         3, { 'a', 'b', 'c' } },
12415     { 7, { 3, 'a', 'b', 'c', 2, 'a', 'b' },
12416         4, { 3, 'a', 'b', 'c' },
12417         OPENSSL_NPN_NEGOTIATED,
12418         3, { 'a', 'b', 'c' } },
12419     { 7, {
12420              2,
12421              'a',
12422              'b',
12423              3,
12424              'a',
12425              'b',
12426              'c',
12427          },
12428         4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } },
12429     { 4, { 3, 'a', 'b', 'c' }, 7, {
12430                                       3,
12431                                       'a',
12432                                       'b',
12433                                       'c',
12434                                       2,
12435                                       'a',
12436                                       'b',
12437                                   },
12438         OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } },
12439     { 4, { 3, 'a', 'b', 'c' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 7, { 2, 'b', 'c', 3, 'a', 'b', 'c' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 10, { 2, 'b', 'c', 3, 'a', 'b', 'c', 2, 'a', 'b' }, 7, { 2, 'a', 'b', 3, 'a', 'b', 'c' }, OPENSSL_NPN_NEGOTIATED, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'b', 'c', 'd' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 0, { 0 }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { -1, { 0 }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 0, { 0 }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }, { 4, { 3, 'a', 'b', 'c' }, -1, { 0 }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }, { 3, { 3, 'a', 'b', 'c' }, 4, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 3, { 'a', 'b', 'c' } }, { 4, { 3, 'a', 'b', 'c' }, 3, { 3, 'a', 'b', 'c' }, OPENSSL_NPN_NO_OVERLAP, 0, { 0 } }
12440 };
12441 
test_select_next_proto(int idx)12442 static int test_select_next_proto(int idx)
12443 {
12444     struct next_proto_st *np = &next_proto_tests[idx];
12445     int ret = 0;
12446     unsigned char *out, *client, *server;
12447     unsigned char outlen;
12448     unsigned int clientlen, serverlen;
12449 
12450     if (np->clientlen == -1) {
12451         client = NULL;
12452         clientlen = 0;
12453     } else {
12454         client = np->client;
12455         clientlen = (unsigned int)np->clientlen;
12456     }
12457     if (np->serverlen == -1) {
12458         server = NULL;
12459         serverlen = 0;
12460     } else {
12461         server = np->server;
12462         serverlen = (unsigned int)np->serverlen;
12463     }
12464 
12465     if (!TEST_int_eq(SSL_select_next_proto(&out, &outlen, server, serverlen,
12466                          client, clientlen),
12467             np->expected_ret))
12468         goto err;
12469 
12470     if (np->selectedlen == 0) {
12471         if (!TEST_ptr_null(out) || !TEST_uchar_eq(outlen, 0))
12472             goto err;
12473     } else {
12474         if (!TEST_mem_eq(out, outlen, np->selected, np->selectedlen))
12475             goto err;
12476     }
12477 
12478     ret = 1;
12479 err:
12480     return ret;
12481 }
12482 
12483 static const unsigned char fooprot[] = { 3, 'f', 'o', 'o' };
12484 static const unsigned char barprot[] = { 3, 'b', 'a', 'r' };
12485 
12486 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
npn_advert_cb(SSL * ssl,const unsigned char ** out,unsigned int * outlen,void * arg)12487 static int npn_advert_cb(SSL *ssl, const unsigned char **out,
12488     unsigned int *outlen, void *arg)
12489 {
12490     int *idx = (int *)arg;
12491 
12492     switch (*idx) {
12493     default:
12494     case 0:
12495         *out = fooprot;
12496         *outlen = sizeof(fooprot);
12497         return SSL_TLSEXT_ERR_OK;
12498 
12499     case 1:
12500         *out = NULL;
12501         *outlen = 0;
12502         return SSL_TLSEXT_ERR_OK;
12503 
12504     case 2:
12505         return SSL_TLSEXT_ERR_NOACK;
12506     }
12507 }
12508 
npn_select_cb(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)12509 static int npn_select_cb(SSL *s, unsigned char **out, unsigned char *outlen,
12510     const unsigned char *in, unsigned int inlen, void *arg)
12511 {
12512     int *idx = (int *)arg;
12513 
12514     switch (*idx) {
12515     case 0:
12516     case 1:
12517         *out = (unsigned char *)(fooprot + 1);
12518         *outlen = *fooprot;
12519         return SSL_TLSEXT_ERR_OK;
12520 
12521     case 3:
12522         *out = (unsigned char *)(barprot + 1);
12523         *outlen = *barprot;
12524         return SSL_TLSEXT_ERR_OK;
12525 
12526     case 4:
12527         *outlen = 0;
12528         return SSL_TLSEXT_ERR_OK;
12529 
12530     default:
12531     case 2:
12532         return SSL_TLSEXT_ERR_ALERT_FATAL;
12533     }
12534 }
12535 
12536 /*
12537  * Test the NPN callbacks
12538  * Test 0: advert = foo, select = foo
12539  * Test 1: advert = <empty>, select = foo
12540  * Test 2: no advert
12541  * Test 3: advert = foo, select = bar
12542  * Test 4: advert = foo, select = <empty> (should fail)
12543  */
test_npn(int idx)12544 static int test_npn(int idx)
12545 {
12546     SSL_CTX *sctx = NULL, *cctx = NULL;
12547     SSL *serverssl = NULL, *clientssl = NULL;
12548     int testresult = 0;
12549 
12550     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12551             TLS_client_method(), 0, TLS1_2_VERSION,
12552             &sctx, &cctx, cert, privkey)))
12553         goto end;
12554 
12555     SSL_CTX_set_next_protos_advertised_cb(sctx, npn_advert_cb, &idx);
12556     SSL_CTX_set_next_proto_select_cb(cctx, npn_select_cb, &idx);
12557 
12558     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12559             NULL)))
12560         goto end;
12561 
12562     if (idx == 4) {
12563         /* We don't allow empty selection of NPN, so this should fail */
12564         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12565                 SSL_ERROR_NONE)))
12566             goto end;
12567     } else {
12568         const unsigned char *prot;
12569         unsigned int protlen;
12570 
12571         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12572                 SSL_ERROR_NONE)))
12573             goto end;
12574 
12575         SSL_get0_next_proto_negotiated(serverssl, &prot, &protlen);
12576         switch (idx) {
12577         case 0:
12578         case 1:
12579             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12580                 goto end;
12581             break;
12582         case 2:
12583             if (!TEST_uint_eq(protlen, 0))
12584                 goto end;
12585             break;
12586         case 3:
12587             if (!TEST_mem_eq(prot, protlen, barprot + 1, *barprot))
12588                 goto end;
12589             break;
12590         default:
12591             TEST_error("Should not get here");
12592             goto end;
12593         }
12594     }
12595 
12596     testresult = 1;
12597 end:
12598     SSL_free(serverssl);
12599     SSL_free(clientssl);
12600     SSL_CTX_free(sctx);
12601     SSL_CTX_free(cctx);
12602 
12603     return testresult;
12604 }
12605 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) */
12606 
alpn_select_cb2(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)12607 static int alpn_select_cb2(SSL *ssl, const unsigned char **out,
12608     unsigned char *outlen, const unsigned char *in,
12609     unsigned int inlen, void *arg)
12610 {
12611     int *idx = (int *)arg;
12612 
12613     switch (*idx) {
12614     case 0:
12615         *out = (unsigned char *)(fooprot + 1);
12616         *outlen = *fooprot;
12617         return SSL_TLSEXT_ERR_OK;
12618 
12619     case 2:
12620         *out = (unsigned char *)(barprot + 1);
12621         *outlen = *barprot;
12622         return SSL_TLSEXT_ERR_OK;
12623 
12624     case 3:
12625         *outlen = 0;
12626         return SSL_TLSEXT_ERR_OK;
12627 
12628     default:
12629     case 1:
12630         return SSL_TLSEXT_ERR_ALERT_FATAL;
12631     }
12632     return 0;
12633 }
12634 
12635 /*
12636  * Test the ALPN callbacks
12637  * Test 0: client = foo, select = foo
12638  * Test 1: client = <empty>, select = none
12639  * Test 2: client = foo, select = bar (should fail)
12640  * Test 3: client = foo, select = <empty> (should fail)
12641  */
test_alpn(int idx)12642 static int test_alpn(int idx)
12643 {
12644     SSL_CTX *sctx = NULL, *cctx = NULL;
12645     SSL *serverssl = NULL, *clientssl = NULL;
12646     int testresult = 0;
12647     const unsigned char *prots = fooprot;
12648     unsigned int protslen = sizeof(fooprot);
12649 
12650     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12651             TLS_client_method(), 0, 0,
12652             &sctx, &cctx, cert, privkey)))
12653         goto end;
12654 
12655     SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb2, &idx);
12656 
12657     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12658             NULL)))
12659         goto end;
12660 
12661     if (idx == 1) {
12662         prots = NULL;
12663         protslen = 0;
12664     }
12665 
12666     /* SSL_set_alpn_protos returns 0 for success! */
12667     if (!TEST_false(SSL_set_alpn_protos(clientssl, prots, protslen)))
12668         goto end;
12669 
12670     if (idx == 2 || idx == 3) {
12671         /* We don't allow empty selection of NPN, so this should fail */
12672         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12673                 SSL_ERROR_NONE)))
12674             goto end;
12675     } else {
12676         const unsigned char *prot;
12677         unsigned int protlen;
12678 
12679         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12680                 SSL_ERROR_NONE)))
12681             goto end;
12682 
12683         SSL_get0_alpn_selected(clientssl, &prot, &protlen);
12684         switch (idx) {
12685         case 0:
12686             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12687                 goto end;
12688             break;
12689         case 1:
12690             if (!TEST_uint_eq(protlen, 0))
12691                 goto end;
12692             break;
12693         default:
12694             TEST_error("Should not get here");
12695             goto end;
12696         }
12697     }
12698 
12699     testresult = 1;
12700 end:
12701     SSL_free(serverssl);
12702     SSL_free(clientssl);
12703     SSL_CTX_free(sctx);
12704     SSL_CTX_free(cctx);
12705 
12706     return testresult;
12707 }
12708 
12709 #if !defined(OSSL_NO_USABLE_TLS1_3)
12710 struct quic_tls_test_data {
12711     struct quic_tls_test_data *peer;
12712     uint32_t renc_level;
12713     uint32_t wenc_level;
12714     unsigned char rcd_data[4][2048];
12715     size_t rcd_data_len[4];
12716     unsigned char rsecret[3][48];
12717     size_t rsecret_len[3];
12718     unsigned char wsecret[3][48];
12719     size_t wsecret_len[3];
12720     unsigned char params[3];
12721     size_t params_len;
12722     int alert;
12723     int err;
12724     int forcefail;
12725     int sm_count;
12726 };
12727 
12728 static int clientquicdata = 0xff, serverquicdata = 0xfe;
12729 
check_app_data(SSL * s)12730 static int check_app_data(SSL *s)
12731 {
12732     int *data, *comparedata;
12733 
12734     /* Check app data works */
12735     data = (int *)SSL_get_app_data(s);
12736     comparedata = SSL_is_server(s) ? &serverquicdata : &clientquicdata;
12737 
12738     if (!TEST_true(comparedata == data))
12739         return 0;
12740 
12741     return 1;
12742 }
12743 
crypto_send_cb(SSL * s,const unsigned char * buf,size_t buf_len,size_t * consumed,void * arg)12744 static int crypto_send_cb(SSL *s, const unsigned char *buf, size_t buf_len,
12745     size_t *consumed, void *arg)
12746 {
12747     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12748     struct quic_tls_test_data *peer = data->peer;
12749     size_t max_len = sizeof(peer->rcd_data[data->wenc_level])
12750         - peer->rcd_data_len[data->wenc_level];
12751 
12752     if (!check_app_data(s)) {
12753         data->err = 1;
12754         return 0;
12755     }
12756 
12757     if (buf_len > max_len)
12758         buf_len = max_len;
12759 
12760     if (buf_len == 0) {
12761         *consumed = 0;
12762         return 1;
12763     }
12764 
12765     memcpy(peer->rcd_data[data->wenc_level]
12766             + peer->rcd_data_len[data->wenc_level],
12767         buf, buf_len);
12768     peer->rcd_data_len[data->wenc_level] += buf_len;
12769 
12770     *consumed = buf_len;
12771     return 1;
12772 }
crypto_recv_rcd_cb(SSL * s,const unsigned char ** buf,size_t * bytes_read,void * arg)12773 static int crypto_recv_rcd_cb(SSL *s, const unsigned char **buf,
12774     size_t *bytes_read, void *arg)
12775 {
12776     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12777 
12778     if (!check_app_data(s)) {
12779         data->err = 1;
12780         return 0;
12781     }
12782 
12783     *bytes_read = data->rcd_data_len[data->renc_level];
12784     *buf = data->rcd_data[data->renc_level];
12785     return 1;
12786 }
12787 
crypto_release_rcd_cb(SSL * s,size_t bytes_read,void * arg)12788 static int crypto_release_rcd_cb(SSL *s, size_t bytes_read, void *arg)
12789 {
12790     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12791 
12792     if (!check_app_data(s)) {
12793         data->err = 1;
12794         return 0;
12795     }
12796 
12797     /* See if we need to force a failure in this callback */
12798     if (data->forcefail) {
12799         data->forcefail = 0;
12800         data->err = 1;
12801         return 0;
12802     }
12803 
12804     if (!TEST_size_t_eq(bytes_read, data->rcd_data_len[data->renc_level])
12805         || !TEST_size_t_gt(bytes_read, 0)) {
12806         data->err = 1;
12807         return 0;
12808     }
12809     data->rcd_data_len[data->renc_level] = 0;
12810 
12811     return 1;
12812 }
12813 
12814 struct secret_yield_entry {
12815     uint8_t recorded;
12816     int prot_level;
12817     int direction;
12818     int sm_generation;
12819     SSL *ssl;
12820 };
12821 
12822 static struct secret_yield_entry secret_history[16];
12823 static int secret_history_idx = 0;
12824 /*
12825  * Note, this enum needs to match the direction values passed
12826  * to yield_secret_cb
12827  */
12828 typedef enum {
12829     LAST_DIR_READ = 0,
12830     LAST_DIR_WRITE = 1,
12831     LAST_DIR_UNSET = 2
12832 } last_dir_history_state;
12833 
check_secret_history(SSL * s)12834 static int check_secret_history(SSL *s)
12835 {
12836     int i;
12837     int ret = 0;
12838     last_dir_history_state last_state = LAST_DIR_UNSET;
12839     int last_prot_level = 0;
12840     int last_generation = 0;
12841 
12842     TEST_info("Checking history for %p\n", (void *)s);
12843     for (i = 0; secret_history[i].recorded == 1; i++) {
12844         if (secret_history[i].ssl != s)
12845             continue;
12846         TEST_info("Got %s(%d) secret for level %d, last level %d, last state %d, gen %d\n",
12847             secret_history[i].direction == 1 ? "Write" : "Read", secret_history[i].direction,
12848             secret_history[i].prot_level, last_prot_level, last_state,
12849             secret_history[i].sm_generation);
12850 
12851         if (last_state == LAST_DIR_UNSET) {
12852             last_prot_level = secret_history[i].prot_level;
12853             last_state = secret_history[i].direction;
12854             last_generation = secret_history[i].sm_generation;
12855             continue;
12856         }
12857 
12858         switch (secret_history[i].direction) {
12859         case 1:
12860             /*
12861              * write case
12862              * NOTE: There is an odd corner case here.  It may occur that
12863              * in a single iteration of the state machine, the read key is yielded
12864              * prior to the write key for the same level.  This is undesirable
12865              * for quic, but it is ok, as the general implementation of every 3rd
12866              * party quic stack while preferring write keys before read, allows
12867              * for read before write if both keys are yielded in the same call
12868              * to SSL_do_handshake, as the tls adaptation code for that quic stack
12869              * can then cache keys until both are available, so we allow read before
12870              * write here iff they occur in the same iteration of SSL_do_handshake
12871              * as represented by the recorded sm_generation value.
12872              */
12873             if (last_prot_level == secret_history[i].prot_level
12874                 && last_state == LAST_DIR_READ) {
12875                 if (last_generation == secret_history[i].sm_generation) {
12876                     TEST_info("Read before write key in same SSL state machine iteration is ok");
12877                 } else {
12878                     TEST_error("Got read key before write key");
12879                     goto end;
12880                 }
12881             }
12882             /* FALLTHROUGH */
12883         case 0:
12884             /*
12885              * Read case
12886              */
12887             break;
12888         default:
12889             TEST_error("Unknown direction");
12890             goto end;
12891         }
12892         last_prot_level = secret_history[i].prot_level;
12893         last_state = secret_history[i].direction;
12894         last_generation = secret_history[i].sm_generation;
12895     }
12896 
12897     ret = 1;
12898 end:
12899     return ret;
12900 }
12901 
yield_secret_cb(SSL * s,uint32_t prot_level,int direction,const unsigned char * secret,size_t secret_len,void * arg)12902 static int yield_secret_cb(SSL *s, uint32_t prot_level, int direction,
12903     const unsigned char *secret, size_t secret_len,
12904     void *arg)
12905 {
12906     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12907 
12908     if (!check_app_data(s))
12909         goto err;
12910 
12911     if (prot_level < OSSL_RECORD_PROTECTION_LEVEL_EARLY
12912         || prot_level > OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
12913         goto err;
12914 
12915     switch (direction) {
12916     case 0: /* read */
12917         if (!TEST_size_t_le(secret_len, sizeof(data->rsecret)))
12918             goto err;
12919         data->renc_level = prot_level;
12920         memcpy(data->rsecret[prot_level - 1], secret, secret_len);
12921         data->rsecret_len[prot_level - 1] = secret_len;
12922         break;
12923 
12924     case 1: /* write */
12925         if (!TEST_size_t_le(secret_len, sizeof(data->wsecret)))
12926             goto err;
12927         data->wenc_level = prot_level;
12928         memcpy(data->wsecret[prot_level - 1], secret, secret_len);
12929         data->wsecret_len[prot_level - 1] = secret_len;
12930         break;
12931 
12932     default:
12933         goto err;
12934     }
12935 
12936     secret_history[secret_history_idx].direction = direction;
12937     secret_history[secret_history_idx].prot_level = (int)prot_level;
12938     secret_history[secret_history_idx].recorded = 1;
12939     secret_history[secret_history_idx].ssl = s;
12940     secret_history[secret_history_idx].sm_generation = data->sm_count;
12941     secret_history_idx++;
12942     return 1;
12943 err:
12944     data->err = 1;
12945     return 0;
12946 }
12947 
yield_secret_cb_fail(SSL * s,uint32_t prot_level,int direction,const unsigned char * secret,size_t secret_len,void * arg)12948 static int yield_secret_cb_fail(SSL *s, uint32_t prot_level, int direction,
12949     const unsigned char *secret, size_t secret_len,
12950     void *arg)
12951 {
12952     (void)s;
12953     (void)prot_level;
12954     (void)direction;
12955     (void)secret;
12956     (void)secret_len;
12957     (void)arg;
12958     /*
12959      * This callback is to test double free in quic tls
12960      */
12961     return 0;
12962 }
12963 
got_transport_params_cb(SSL * s,const unsigned char * params,size_t params_len,void * arg)12964 static int got_transport_params_cb(SSL *s, const unsigned char *params,
12965     size_t params_len,
12966     void *arg)
12967 {
12968     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12969 
12970     if (!check_app_data(s)) {
12971         data->err = 1;
12972         return 0;
12973     }
12974 
12975     if (!TEST_size_t_le(params_len, sizeof(data->params))) {
12976         data->err = 1;
12977         return 0;
12978     }
12979 
12980     memcpy(data->params, params, params_len);
12981     data->params_len = params_len;
12982 
12983     return 1;
12984 }
12985 
alert_cb(SSL * s,unsigned char alert_code,void * arg)12986 static int alert_cb(SSL *s, unsigned char alert_code, void *arg)
12987 {
12988     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12989 
12990     if (!check_app_data(s)) {
12991         data->err = 1;
12992         return 0;
12993     }
12994 
12995     data->alert = 1;
12996     return 1;
12997 }
12998 
12999 /*
13000  * Test the QUIC TLS API
13001  * Test 0: Normal run
13002  * Test 1: Force a failure
13003  * Test 3: Use a CCM based ciphersuite
13004  * Test 4: fail yield_secret_cb to see double free
13005  * Test 5: Normal run with SNI
13006  */
test_quic_tls(int idx)13007 static int test_quic_tls(int idx)
13008 {
13009     SSL_CTX *sctx = NULL, *sctx2 = NULL, *cctx = NULL;
13010     SSL *serverssl = NULL, *clientssl = NULL;
13011     int testresult = 0;
13012     OSSL_DISPATCH qtdis[] = {
13013         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb },
13014         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD,
13015             (void (*)(void))crypto_recv_rcd_cb },
13016         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD,
13017             (void (*)(void))crypto_release_rcd_cb },
13018         { OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET,
13019             (void (*)(void))yield_secret_cb },
13020         { OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS,
13021             (void (*)(void))got_transport_params_cb },
13022         { OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb },
13023         { 0, NULL }
13024     };
13025     struct quic_tls_test_data sdata, cdata;
13026     const unsigned char cparams[] = {
13027         0xff, 0x01, 0x00
13028     };
13029     const unsigned char sparams[] = {
13030         0xfe, 0x01, 0x00
13031     };
13032     int i;
13033 
13034     if (idx == 4)
13035         qtdis[3].function = (void (*)(void))yield_secret_cb_fail;
13036 
13037     snicb = 0;
13038     memset(secret_history, 0, sizeof(secret_history));
13039     secret_history_idx = 0;
13040     memset(&sdata, 0, sizeof(sdata));
13041     memset(&cdata, 0, sizeof(cdata));
13042     sdata.peer = &cdata;
13043     cdata.peer = &sdata;
13044     if (idx == 1)
13045         sdata.forcefail = 1;
13046 
13047     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13048             TLS_client_method(), TLS1_3_VERSION, 0,
13049             &sctx, &cctx, cert, privkey)))
13050         goto end;
13051 
13052     if (idx == 5) {
13053         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
13054                 TLS1_3_VERSION, 0,
13055                 &sctx2, NULL, cert, privkey)))
13056             goto end;
13057 
13058         /* Set up SNI */
13059         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
13060             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
13061             goto end;
13062     }
13063 
13064     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13065             NULL)))
13066         goto end;
13067 
13068     /* Reset the BIOs we set in create_ssl_objects. We should not need them */
13069     SSL_set_bio(serverssl, NULL, NULL);
13070     SSL_set_bio(clientssl, NULL, NULL);
13071 
13072     if (idx == 2) {
13073         if (!TEST_true(SSL_set_ciphersuites(serverssl, "TLS_AES_128_CCM_SHA256"))
13074             || !TEST_true(SSL_set_ciphersuites(clientssl, "TLS_AES_128_CCM_SHA256")))
13075             goto end;
13076     }
13077 
13078     if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata))
13079         || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata)))
13080         goto end;
13081 
13082     if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata))
13083         || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata))
13084         || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams,
13085             sizeof(cparams)))
13086         || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams,
13087             sizeof(sparams))))
13088         goto end;
13089 
13090     if (idx != 1 && idx != 4) {
13091         if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
13092                 &cdata.sm_count, &sdata.sm_count)))
13093             goto end;
13094     } else {
13095         /* We expect this connection to fail */
13096         if (!TEST_false(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
13097                 &cdata.sm_count, &sdata.sm_count)))
13098             goto end;
13099         testresult = 1;
13100         sdata.err = 0;
13101         goto end;
13102     }
13103 
13104     /* We should have had the SNI callback called exactly once */
13105     if (idx == 5) {
13106         if (!TEST_int_eq(snicb, 1))
13107             goto end;
13108     }
13109 
13110     /* Check no problems during the handshake */
13111     if (!TEST_false(sdata.alert)
13112         || !TEST_false(cdata.alert)
13113         || !TEST_false(sdata.err)
13114         || !TEST_false(cdata.err))
13115         goto end;
13116 
13117     /* Check the secrets all match */
13118     for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1;
13119         i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION;
13120         i++) {
13121         if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i],
13122                 cdata.rsecret[i], cdata.rsecret_len[i]))
13123             goto end;
13124     }
13125 
13126     /*
13127      * Check that our secret history yields write secrets before read secrets
13128      */
13129     if (!TEST_int_eq(check_secret_history(serverssl), 1))
13130         goto end;
13131     if (!TEST_int_eq(check_secret_history(clientssl), 1))
13132         goto end;
13133 
13134     /* Check the transport params */
13135     if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams))
13136         || !TEST_mem_eq(cdata.params, cdata.params_len, sparams,
13137             sizeof(sparams)))
13138         goto end;
13139 
13140     /* Check the encryption levels are what we expect them to be */
13141     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13142         || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13143         || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13144         || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION))
13145         goto end;
13146 
13147     testresult = 1;
13148 end:
13149     SSL_free(serverssl);
13150     SSL_free(clientssl);
13151     SSL_CTX_free(sctx2);
13152     SSL_CTX_free(sctx);
13153     SSL_CTX_free(cctx);
13154 
13155     /* Check that we didn't suddenly hit an unexpected failure during cleanup */
13156     if (!TEST_false(sdata.err) || !TEST_false(cdata.err))
13157         testresult = 0;
13158 
13159     return testresult;
13160 }
13161 
assert_no_end_of_early_data(int write_p,int version,int content_type,const void * buf,size_t msglen,SSL * ssl,void * arg)13162 static void assert_no_end_of_early_data(int write_p, int version, int content_type,
13163     const void *buf, size_t msglen, SSL *ssl, void *arg)
13164 {
13165     const unsigned char *msg = buf;
13166 
13167     if (content_type == SSL3_RT_HANDSHAKE && msg[0] == SSL3_MT_END_OF_EARLY_DATA)
13168         end_of_early_data = 1;
13169 }
13170 
test_quic_tls_early_data(void)13171 static int test_quic_tls_early_data(void)
13172 {
13173     SSL_CTX *sctx = NULL, *cctx = NULL;
13174     SSL *serverssl = NULL, *clientssl = NULL;
13175     int testresult = 0;
13176     SSL_SESSION *sess = NULL;
13177     const OSSL_DISPATCH qtdis[] = {
13178         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb },
13179         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD,
13180             (void (*)(void))crypto_recv_rcd_cb },
13181         { OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD,
13182             (void (*)(void))crypto_release_rcd_cb },
13183         { OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET,
13184             (void (*)(void))yield_secret_cb },
13185         { OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS,
13186             (void (*)(void))got_transport_params_cb },
13187         { OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb },
13188         { 0, NULL }
13189     };
13190     struct quic_tls_test_data sdata, cdata;
13191     const unsigned char cparams[] = {
13192         0xff, 0x01, 0x00
13193     };
13194     const unsigned char sparams[] = {
13195         0xfe, 0x01, 0x00
13196     };
13197     int i;
13198 
13199     memset(secret_history, 0, sizeof(secret_history));
13200     secret_history_idx = 0;
13201     memset(&sdata, 0, sizeof(sdata));
13202     memset(&cdata, 0, sizeof(cdata));
13203     sdata.peer = &cdata;
13204     cdata.peer = &sdata;
13205     end_of_early_data = 0;
13206 
13207     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13208             TLS_client_method(), TLS1_3_VERSION, 0,
13209             &sctx, &cctx, cert, privkey)))
13210         goto end;
13211 
13212     SSL_CTX_set_max_early_data(sctx, 0xffffffff);
13213     SSL_CTX_set_max_early_data(cctx, 0xffffffff);
13214 
13215     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13216             NULL)))
13217         goto end;
13218 
13219     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13220         goto end;
13221 
13222     sess = SSL_get1_session(clientssl);
13223     SSL_shutdown(clientssl);
13224     SSL_shutdown(serverssl);
13225     SSL_free(serverssl);
13226     SSL_free(clientssl);
13227     serverssl = clientssl = NULL;
13228 
13229     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
13230             &clientssl, NULL, NULL))
13231         || !TEST_true(SSL_set_session(clientssl, sess)))
13232         goto end;
13233 
13234     /* Reset the BIOs we set in create_ssl_objects. We should not need them */
13235     SSL_set_bio(serverssl, NULL, NULL);
13236     SSL_set_bio(clientssl, NULL, NULL);
13237 
13238     if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata))
13239         || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata)))
13240         goto end;
13241 
13242     if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata))
13243         || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata))
13244         || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams,
13245             sizeof(cparams)))
13246         || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams,
13247             sizeof(sparams))))
13248         goto end;
13249 
13250     /*
13251      * Reset our secret history so we get the record of the second connection
13252      */
13253     memset(secret_history, 0, sizeof(secret_history));
13254     secret_history_idx = 0;
13255 
13256     SSL_set_quic_tls_early_data_enabled(serverssl, 1);
13257     SSL_set_quic_tls_early_data_enabled(clientssl, 1);
13258 
13259     SSL_set_msg_callback(serverssl, assert_no_end_of_early_data);
13260     SSL_set_msg_callback(clientssl, assert_no_end_of_early_data);
13261 
13262     if (!TEST_int_eq(SSL_connect(clientssl), -1)
13263         || !TEST_int_eq(SSL_accept(serverssl), -1)
13264         || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED)
13265         || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_READ)
13266         || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_READ))
13267         goto end;
13268 
13269     /* Check the encryption levels are what we expect them to be */
13270     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE)
13271         || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13272         || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
13273         || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_EARLY))
13274         goto end;
13275 
13276     sdata.sm_count = 0;
13277     cdata.sm_count = 0;
13278     if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
13279             &cdata.sm_count, &sdata.sm_count)))
13280         goto end;
13281 
13282     /* Check no problems during the handshake */
13283     if (!TEST_false(sdata.alert)
13284         || !TEST_false(cdata.alert)
13285         || !TEST_false(sdata.err)
13286         || !TEST_false(cdata.err))
13287         goto end;
13288 
13289     /* Check the secrets all match */
13290     for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1;
13291         i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION;
13292         i++) {
13293         if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i],
13294                 cdata.rsecret[i], cdata.rsecret_len[i]))
13295             goto end;
13296     }
13297 
13298     if (!TEST_int_eq(check_secret_history(serverssl), 1))
13299         goto end;
13300     if (!TEST_int_eq(check_secret_history(clientssl), 1))
13301         goto end;
13302 
13303     /* Check the transport params */
13304     if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams))
13305         || !TEST_mem_eq(cdata.params, cdata.params_len, sparams,
13306             sizeof(sparams)))
13307         goto end;
13308 
13309     /* Check the encryption levels are what we expect them to be */
13310     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13311         || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13312         || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13313         || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION))
13314         goto end;
13315 
13316     /* Check there is no EndOfEearlyData in handshake */
13317     if (!TEST_int_eq(end_of_early_data, 0))
13318         goto end;
13319 
13320     testresult = 1;
13321 end:
13322     SSL_SESSION_free(sess);
13323     SSL_SESSION_free(clientpsk);
13324     SSL_SESSION_free(serverpsk);
13325     clientpsk = serverpsk = NULL;
13326     SSL_free(serverssl);
13327     SSL_free(clientssl);
13328     SSL_CTX_free(sctx);
13329     SSL_CTX_free(cctx);
13330 
13331     return testresult;
13332 }
13333 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) */
13334 
test_no_renegotiation(int idx)13335 static int test_no_renegotiation(int idx)
13336 {
13337     SSL_CTX *sctx = NULL, *cctx = NULL;
13338     SSL *serverssl = NULL, *clientssl = NULL;
13339     int testresult = 0, ret;
13340     int max_proto;
13341     const SSL_METHOD *sm, *cm;
13342     unsigned char buf[5];
13343 
13344     if (idx == 0) {
13345 #ifndef OPENSSL_NO_TLS1_2
13346         max_proto = TLS1_2_VERSION;
13347         sm = TLS_server_method();
13348         cm = TLS_client_method();
13349 #else
13350         return TEST_skip("TLSv1.2 is disabled in this build");
13351 #endif
13352     } else {
13353 #ifndef OPENSSL_NO_DTLS1_2
13354         max_proto = DTLS1_2_VERSION;
13355         sm = DTLS_server_method();
13356         cm = DTLS_client_method();
13357 #else
13358         return TEST_skip("DTLSv1.2 is disabled in this build");
13359 #endif
13360     }
13361     if (!TEST_true(create_ssl_ctx_pair(libctx, sm, cm, 0, max_proto,
13362             &sctx, &cctx, cert, privkey)))
13363         goto end;
13364 
13365     SSL_CTX_set_options(sctx, SSL_OP_NO_RENEGOTIATION);
13366 
13367     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13368             NULL)))
13369         goto end;
13370 
13371     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13372         goto end;
13373 
13374     if (!TEST_true(SSL_renegotiate(clientssl))
13375         || !TEST_int_le(ret = SSL_connect(clientssl), 0)
13376         || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_WANT_READ))
13377         goto end;
13378 
13379     /*
13380      * We've not sent any application data, so we expect this to fail. It should
13381      * also read the renegotiation attempt, and send back a no_renegotiation
13382      * warning alert because we have renegotiation disabled.
13383      */
13384     if (!TEST_int_le(ret = SSL_read(serverssl, buf, sizeof(buf)), 0))
13385         goto end;
13386     if (!TEST_int_eq(SSL_get_error(serverssl, ret), SSL_ERROR_WANT_READ))
13387         goto end;
13388 
13389     /*
13390      * The client should now see the no_renegotiation warning and fail the
13391      * connection
13392      */
13393     if (!TEST_int_le(ret = SSL_connect(clientssl), 0)
13394         || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_SSL)
13395         || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_NO_RENEGOTIATION))
13396         goto end;
13397 
13398     testresult = 1;
13399 end:
13400     SSL_free(serverssl);
13401     SSL_free(clientssl);
13402     SSL_CTX_free(sctx);
13403     SSL_CTX_free(cctx);
13404 
13405     return testresult;
13406 }
13407 
13408 #if defined(DO_SSL_TRACE_TEST)
13409 /*
13410  * Tests that the SSL_trace() msg_callback works as expected with a PQ Groups.
13411  */
test_ssl_trace(void)13412 static int test_ssl_trace(void)
13413 {
13414     SSL_CTX *sctx = NULL, *cctx = NULL;
13415     SSL *serverssl = NULL, *clientssl = NULL;
13416     int testresult = 0;
13417     BIO *bio = NULL;
13418     char *reffile = NULL;
13419     char *grouplist = "MLKEM512:MLKEM768:MLKEM1024:X25519MLKEM768:SecP256r1MLKEM768"
13420                       ":SecP384r1MLKEM1024:secp521r1:secp384r1:secp256r1";
13421 
13422     if (!fips_provider_version_ge(libctx, 3, 5, 0))
13423         return TEST_skip("FIPS provider does not support MLKEM algorithms");
13424 
13425     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13426             TLS_client_method(),
13427             TLS1_3_VERSION, TLS1_3_VERSION,
13428             &sctx, &cctx, cert, privkey))
13429         || !TEST_ptr(bio = BIO_new(BIO_s_mem()))
13430         || !TEST_true(SSL_CTX_set1_groups_list(sctx, grouplist))
13431         || !TEST_true(SSL_CTX_set1_groups_list(cctx, grouplist))
13432         || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
13433             "TLS_AES_128_GCM_SHA256"))
13434         || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
13435             "TLS_AES_128_GCM_SHA256"))
13436 #ifdef SSL_OP_LEGACY_EC_POINT_FORMATS
13437         || !TEST_true(SSL_CTX_set_options(cctx, SSL_OP_LEGACY_EC_POINT_FORMATS))
13438         || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_LEGACY_EC_POINT_FORMATS))
13439 #endif
13440         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
13441             NULL, NULL)))
13442         goto err;
13443 
13444     SSL_set_msg_callback(clientssl, SSL_trace);
13445     SSL_set_msg_callback_arg(clientssl, bio);
13446 
13447     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13448         goto err;
13449 
13450     /* Skip the comparison of the trace when the fips provider is used. */
13451     if (is_fips) {
13452         /* Check whether there was something written. */
13453         if (!TEST_int_gt(BIO_pending(bio), 0))
13454             goto err;
13455     } else {
13456 
13457 #ifdef OPENSSL_NO_ZLIB
13458         reffile = test_mk_file_path(datadir, "ssltraceref.txt");
13459 #else
13460         reffile = test_mk_file_path(datadir, "ssltraceref-zlib.txt");
13461 #endif
13462         if (!TEST_true(compare_with_reference_file(bio, reffile)))
13463             goto err;
13464     }
13465 
13466     testresult = 1;
13467 err:
13468     BIO_free(bio);
13469     SSL_free(serverssl);
13470     SSL_free(clientssl);
13471     SSL_CTX_free(sctx);
13472     SSL_CTX_free(cctx);
13473     OPENSSL_free(reffile);
13474 
13475     return testresult;
13476 }
13477 #endif
13478 
13479 /*
13480  * Test that SSL_CTX_set1_groups() when called with a list where the first
13481  * entry is unsupported, will send a key_share that uses the next usable entry.
13482  */
test_ssl_set_groups_unsupported_keyshare(int idx)13483 static int test_ssl_set_groups_unsupported_keyshare(int idx)
13484 {
13485 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
13486     int testresult = 0;
13487     SSL_CTX *sctx = NULL, *cctx = NULL;
13488     SSL *serverssl = NULL, *clientssl = NULL;
13489     int client_groups[] = {
13490         NID_brainpoolP256r1tls13,
13491         NID_sect163k1,
13492         NID_secp384r1,
13493         NID_ffdhe2048,
13494     };
13495 
13496     switch (idx) {
13497     case 1:
13498         client_groups[0] = NID_id_tc26_gost_3410_2012_512_paramSetC;
13499         if (sizeof(unsigned long) == 4) {
13500             return TEST_skip("SSL_CTX_set1_groups() is broken on 32-bit systems with TLS"
13501                              " group IDs > 0x20, see https://github.com/openssl/openssl/issues/29196");
13502         }
13503         break;
13504     }
13505 
13506     if (!TEST_true(create_ssl_ctx_pair(libctx,
13507             TLS_server_method(),
13508             TLS_client_method(),
13509             0, 0,
13510             &sctx,
13511             &cctx,
13512             cert,
13513             privkey)))
13514         goto end;
13515 
13516     if (!TEST_true(SSL_CTX_set1_groups(cctx,
13517             client_groups,
13518             OSSL_NELEM(client_groups))))
13519         goto end;
13520 
13521     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13522             NULL)))
13523         goto end;
13524 
13525     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13526         goto end;
13527 
13528     testresult = 1;
13529 end:
13530     SSL_free(serverssl);
13531     SSL_free(clientssl);
13532     SSL_CTX_free(sctx);
13533     SSL_CTX_free(cctx);
13534 
13535     return testresult;
13536 #else /* !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH) */
13537     return TEST_skip("No EC and DH support.");
13538 #endif /* !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH) */
13539 }
13540 
13541 /*
13542  * Test that if we attempt to send HTTP to a TLS server that we get the expected
13543  * failure reason code.
13544  */
test_http_verbs(int idx)13545 static int test_http_verbs(int idx)
13546 {
13547     SSL_CTX *sctx = NULL;
13548     SSL *serverssl = NULL;
13549     int testresult = 0;
13550     const char *verbs[] = { "GET", "POST", "HEAD" };
13551     const char *http_trailer = " / HTTP/1.0\r\n\r\n";
13552     BIO *b = BIO_new(BIO_s_mem());
13553 
13554     if (!TEST_true((unsigned int)idx < OSSL_NELEM(verbs)))
13555         goto end;
13556 
13557     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13558             NULL, 0, 0, &sctx, NULL, cert, privkey)))
13559         goto end;
13560 
13561     serverssl = SSL_new(sctx);
13562     if (!TEST_ptr(serverssl))
13563         goto end;
13564 
13565     if (!TEST_int_gt(BIO_write(b, verbs[idx], (int)strlen(verbs[idx])), 0))
13566         goto end;
13567     if (!TEST_int_gt(BIO_write(b, http_trailer, (int)strlen(http_trailer)), 0))
13568         goto end;
13569     SSL_set_bio(serverssl, b, b);
13570     b = NULL;
13571 
13572     ERR_clear_error();
13573     if (!TEST_int_le(SSL_accept(serverssl), 0))
13574         goto end;
13575     if (!TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_HTTP_REQUEST))
13576         goto end;
13577 
13578     testresult = 1;
13579 end:
13580     SSL_free(serverssl);
13581     SSL_CTX_free(sctx);
13582     BIO_free(b);
13583 
13584     return testresult;
13585 }
13586 
13587 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config dhfile\n")
13588 
setup_tests(void)13589 int setup_tests(void)
13590 {
13591     char *modulename;
13592     char *configfile;
13593 
13594     libctx = OSSL_LIB_CTX_new();
13595     if (!TEST_ptr(libctx))
13596         return 0;
13597 
13598     defctxnull = OSSL_PROVIDER_load(NULL, "null");
13599 
13600     /*
13601      * Verify that the default and fips providers in the default libctx are not
13602      * available
13603      */
13604     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
13605         || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
13606         return 0;
13607 
13608     if (!test_skip_common_options()) {
13609         TEST_error("Error parsing test options\n");
13610         return 0;
13611     }
13612 
13613     if (!TEST_ptr(certsdir = test_get_argument(0))
13614         || !TEST_ptr(srpvfile = test_get_argument(1))
13615         || !TEST_ptr(tmpfilename = test_get_argument(2))
13616         || !TEST_ptr(modulename = test_get_argument(3))
13617         || !TEST_ptr(configfile = test_get_argument(4))
13618         || !TEST_ptr(dhfile = test_get_argument(5)))
13619         return 0;
13620 
13621     datadir = test_get_argument(6);
13622 
13623     if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
13624         return 0;
13625 
13626     /* Check we have the expected provider available */
13627     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
13628         return 0;
13629 
13630     /* Check the default provider is not available */
13631     if (strcmp(modulename, "default") != 0
13632         && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
13633         return 0;
13634 
13635     if (strcmp(modulename, "fips") == 0) {
13636         OSSL_PROVIDER *prov = NULL;
13637         OSSL_PARAM params[2];
13638 
13639         is_fips = 1;
13640 
13641         prov = OSSL_PROVIDER_load(libctx, "fips");
13642         if (prov != NULL) {
13643             /* Query the fips provider to check if the check ems option is enabled */
13644             params[0] = OSSL_PARAM_construct_int(OSSL_PROV_PARAM_TLS1_PRF_EMS_CHECK,
13645                 &fips_ems_check);
13646             params[1] = OSSL_PARAM_construct_end();
13647             OSSL_PROVIDER_get_params(prov, params);
13648             OSSL_PROVIDER_unload(prov);
13649         }
13650     }
13651 
13652     /*
13653      * We add, but don't load the test "tls-provider". We'll load it when we
13654      * need it.
13655      */
13656     if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider",
13657             tls_provider_init)))
13658         return 0;
13659 
13660     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
13661 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
13662         TEST_error("not supported in this build");
13663         return 0;
13664 #else
13665         int i, mcount, rcount, fcount;
13666 
13667         for (i = 0; i < 4; i++)
13668             test_export_key_mat(i);
13669         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
13670         test_printf_stdout("malloc %d realloc %d free %d\n",
13671             mcount, rcount, fcount);
13672         return 1;
13673 #endif
13674     }
13675 
13676     cert = test_mk_file_path(certsdir, "servercert.pem");
13677     if (cert == NULL)
13678         goto err;
13679 
13680     privkey = test_mk_file_path(certsdir, "serverkey.pem");
13681     if (privkey == NULL)
13682         goto err;
13683 
13684     cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
13685     if (cert2 == NULL)
13686         goto err;
13687 
13688     privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
13689     if (privkey2 == NULL)
13690         goto err;
13691 
13692     cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem");
13693     if (cert1024 == NULL)
13694         goto err;
13695 
13696     privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem");
13697     if (privkey1024 == NULL)
13698         goto err;
13699 
13700     cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem");
13701     if (cert3072 == NULL)
13702         goto err;
13703 
13704     privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem");
13705     if (privkey3072 == NULL)
13706         goto err;
13707 
13708     cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem");
13709     if (cert4096 == NULL)
13710         goto err;
13711 
13712     privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem");
13713     if (privkey4096 == NULL)
13714         goto err;
13715 
13716     cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem");
13717     if (cert8192 == NULL)
13718         goto err;
13719 
13720     privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem");
13721     if (privkey8192 == NULL)
13722         goto err;
13723 
13724     if (fips_ems_check) {
13725 #ifndef OPENSSL_NO_TLS1_2
13726         ADD_TEST(test_no_ems);
13727 #endif
13728         return 1;
13729     }
13730 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
13731 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
13732     ADD_ALL_TESTS(test_ktls, NUM_KTLS_TEST_CIPHERS * 4);
13733     ADD_ALL_TESTS(test_ktls_sendfile, NUM_KTLS_TEST_CIPHERS * 2);
13734 #endif
13735 #endif
13736     ADD_TEST(test_large_message_tls);
13737     ADD_TEST(test_large_message_tls_read_ahead);
13738 #ifndef OPENSSL_NO_DTLS
13739     ADD_TEST(test_large_message_dtls);
13740 #endif
13741     ADD_ALL_TESTS(test_large_app_data, 28);
13742     ADD_TEST(test_cleanse_plaintext);
13743 #ifndef OPENSSL_NO_OCSP
13744     ADD_TEST(test_tlsext_status_type);
13745 #endif
13746     ADD_TEST(test_session_with_only_int_cache);
13747     ADD_TEST(test_session_with_only_ext_cache);
13748     ADD_TEST(test_session_with_both_cache);
13749     ADD_TEST(test_session_wo_ca_names);
13750 #ifndef OSSL_NO_USABLE_TLS1_3
13751     ADD_ALL_TESTS(test_stateful_tickets, 3);
13752     ADD_ALL_TESTS(test_stateless_tickets, 3);
13753     ADD_TEST(test_psk_tickets);
13754     ADD_ALL_TESTS(test_extra_tickets, 6);
13755 #endif
13756     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
13757     ADD_TEST(test_ssl_bio_pop_next_bio);
13758     ADD_TEST(test_ssl_bio_pop_ssl_bio);
13759     ADD_TEST(test_ssl_bio_change_rbio);
13760     ADD_TEST(test_ssl_bio_change_wbio);
13761 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
13762     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
13763     ADD_TEST(test_keylog);
13764 #endif
13765 #ifndef OSSL_NO_USABLE_TLS1_3
13766     ADD_TEST(test_keylog_no_master_key);
13767 #endif
13768     ADD_TEST(test_client_cert_verify_cb);
13769     ADD_TEST(test_ssl_build_cert_chain);
13770     ADD_TEST(test_ssl_ctx_build_cert_chain);
13771 #ifndef OPENSSL_NO_TLS1_2
13772     ADD_TEST(test_client_hello_cb);
13773     ADD_TEST(test_no_ems);
13774     ADD_TEST(test_ccs_change_cipher);
13775 #endif
13776 #ifndef OSSL_NO_USABLE_TLS1_3
13777     ADD_ALL_TESTS(test_early_data_read_write, 6);
13778     /*
13779      * We don't do replay tests for external PSK. Replay protection isn't used
13780      * in that scenario.
13781      */
13782     ADD_ALL_TESTS(test_early_data_replay, 2);
13783     ADD_ALL_TESTS(test_early_data_skip, OSSL_NELEM(ciphersuites) * 3);
13784     ADD_ALL_TESTS(test_early_data_skip_hrr, OSSL_NELEM(ciphersuites) * 3);
13785     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, OSSL_NELEM(ciphersuites) * 3);
13786     ADD_ALL_TESTS(test_early_data_skip_abort, OSSL_NELEM(ciphersuites) * 3);
13787     ADD_ALL_TESTS(test_early_data_not_sent, 3);
13788     ADD_ALL_TESTS(test_early_data_psk, 8);
13789     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 7);
13790     ADD_ALL_TESTS(test_early_data_not_expected, 3);
13791 #ifndef OPENSSL_NO_TLS1_2
13792     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
13793 #endif
13794 #endif
13795 #ifndef OSSL_NO_USABLE_TLS1_3
13796     ADD_ALL_TESTS(test_set_ciphersuite, 10);
13797     ADD_TEST(test_ciphersuite_change);
13798     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
13799 #ifdef OPENSSL_NO_PSK
13800     ADD_ALL_TESTS(test_tls13_psk, 1);
13801 #else
13802     ADD_ALL_TESTS(test_tls13_psk, 4);
13803 #endif /* OPENSSL_NO_PSK */
13804 #ifndef OSSL_NO_USABLE_TLS1_3
13805     ADD_ALL_TESTS(test_tls13_no_dhe_kex, 8);
13806 #endif /* OSSL_NO_USABLE_TLS1_3 */
13807 #ifndef OPENSSL_NO_TLS1_2
13808     /* Test with both TLSv1.3 and 1.2 versions */
13809     ADD_ALL_TESTS(test_key_exchange, 21);
13810 #if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH)
13811     ADD_ALL_TESTS(test_negotiated_group,
13812         4 * (OSSL_NELEM(ecdhe_kexch_groups) + OSSL_NELEM(ffdhe_kexch_groups)));
13813 #endif
13814 #else
13815     /* Test with only TLSv1.3 versions */
13816     ADD_ALL_TESTS(test_key_exchange, 18);
13817 #endif
13818     ADD_ALL_TESTS(test_custom_exts, 6);
13819     ADD_TEST(test_stateless);
13820     ADD_TEST(test_pha_key_update);
13821 #else
13822     ADD_ALL_TESTS(test_custom_exts, 3);
13823 #endif
13824     ADD_ALL_TESTS(test_export_key_mat, 6);
13825 #ifndef OSSL_NO_USABLE_TLS1_3
13826     ADD_ALL_TESTS(test_export_key_mat_early, 3);
13827     ADD_TEST(test_key_update);
13828     ADD_ALL_TESTS(test_key_update_peer_in_write, 2);
13829     ADD_ALL_TESTS(test_key_update_peer_in_read, 2);
13830     ADD_ALL_TESTS(test_key_update_local_in_write, 2);
13831     ADD_ALL_TESTS(test_key_update_local_in_read, 2);
13832 #endif
13833     ADD_ALL_TESTS(test_ssl_clear, 8);
13834     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
13835 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
13836     ADD_ALL_TESTS(test_srp, 6);
13837 #endif
13838 #if !defined(OPENSSL_NO_COMP_ALG)
13839     /* Add compression case */
13840     ADD_ALL_TESTS(test_info_callback, 8);
13841 #else
13842     ADD_ALL_TESTS(test_info_callback, 6);
13843 #endif
13844     ADD_ALL_TESTS(test_ssl_pending, 2);
13845     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
13846     ADD_ALL_TESTS(test_ticket_callbacks, 20);
13847     ADD_ALL_TESTS(test_shutdown, 7);
13848     ADD_TEST(test_async_shutdown);
13849     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
13850     ADD_ALL_TESTS(test_cert_cb, 6);
13851     ADD_ALL_TESTS(test_client_cert_cb, 2);
13852     ADD_ALL_TESTS(test_ca_names, 3);
13853 #ifndef OPENSSL_NO_TLS1_2
13854     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
13855 #endif
13856     ADD_ALL_TESTS(test_servername, 10);
13857     ADD_TEST(test_unknown_sigalgs_groups);
13858 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM)
13859     ADD_TEST(test_configuration_of_groups);
13860 #endif
13861 #if !defined(OPENSSL_NO_EC) \
13862     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
13863     ADD_ALL_TESTS(test_sigalgs_available, 6);
13864 #endif
13865 #ifndef OPENSSL_NO_TLS1_3
13866     ADD_ALL_TESTS(test_pluggable_group, 2);
13867     ADD_ALL_TESTS(test_pluggable_signature, 6);
13868 #endif
13869 #ifndef OPENSSL_NO_TLS1_2
13870     ADD_TEST(test_ssl_dup);
13871     ADD_TEST(test_session_secret_cb);
13872 #ifndef OPENSSL_NO_DH
13873     ADD_ALL_TESTS(test_set_tmp_dh, 11);
13874     ADD_ALL_TESTS(test_dh_auto, 7);
13875 #endif
13876 #endif
13877 #ifndef OSSL_NO_USABLE_TLS1_3
13878     ADD_TEST(test_sni_tls13);
13879     ADD_ALL_TESTS(test_ticket_lifetime, 2);
13880 #endif
13881     ADD_TEST(test_inherit_verify_param);
13882     ADD_TEST(test_set_alpn);
13883     ADD_TEST(test_set_verify_cert_store_ssl_ctx);
13884     ADD_TEST(test_set_verify_cert_store_ssl);
13885     ADD_ALL_TESTS(test_session_timeout, 1);
13886 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
13887     ADD_ALL_TESTS(test_session_cache_overflow, 4);
13888 #endif
13889     ADD_TEST(test_load_dhfile);
13890 #ifndef OSSL_NO_USABLE_TLS1_3
13891     ADD_TEST(test_read_ahead_key_change);
13892     ADD_ALL_TESTS(test_tls13_record_padding, 6);
13893 #endif
13894 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
13895     ADD_ALL_TESTS(test_serverinfo_custom, 4);
13896 #endif
13897 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
13898     ADD_ALL_TESTS(test_pipelining, 7);
13899 #endif
13900     ADD_ALL_TESTS(test_version, 6);
13901     ADD_TEST(test_rstate_string);
13902     ADD_ALL_TESTS(test_handshake_retry, 16);
13903     ADD_TEST(test_data_retry);
13904     ADD_ALL_TESTS(test_multi_resume, 5);
13905     ADD_ALL_TESTS(test_select_next_proto, OSSL_NELEM(next_proto_tests));
13906 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
13907     ADD_ALL_TESTS(test_npn, 5);
13908 #endif
13909     ADD_ALL_TESTS(test_alpn, 4);
13910 #if !defined(OSSL_NO_USABLE_TLS1_3)
13911     ADD_ALL_TESTS(test_quic_tls, 6);
13912     ADD_TEST(test_quic_tls_early_data);
13913 #endif
13914     ADD_ALL_TESTS(test_no_renegotiation, 2);
13915 #if defined(DO_SSL_TRACE_TEST)
13916     if (datadir != NULL)
13917         ADD_TEST(test_ssl_trace);
13918 #endif
13919     ADD_ALL_TESTS(test_ssl_set_groups_unsupported_keyshare, 2);
13920     ADD_ALL_TESTS(test_http_verbs, 3);
13921     return 1;
13922 
13923 err:
13924     OPENSSL_free(cert);
13925     OPENSSL_free(privkey);
13926     OPENSSL_free(cert2);
13927     OPENSSL_free(privkey2);
13928     return 0;
13929 }
13930 
cleanup_tests(void)13931 void cleanup_tests(void)
13932 {
13933 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH)
13934     EVP_PKEY_free(tmp_dh_params);
13935 #endif
13936     OPENSSL_free(cert);
13937     OPENSSL_free(privkey);
13938     OPENSSL_free(cert2);
13939     OPENSSL_free(privkey2);
13940     OPENSSL_free(cert1024);
13941     OPENSSL_free(privkey1024);
13942     OPENSSL_free(cert3072);
13943     OPENSSL_free(privkey3072);
13944     OPENSSL_free(cert4096);
13945     OPENSSL_free(privkey4096);
13946     OPENSSL_free(cert8192);
13947     OPENSSL_free(privkey8192);
13948     bio_s_mempacket_test_free();
13949     bio_s_always_retry_free();
13950     bio_s_maybe_retry_free();
13951     OSSL_PROVIDER_unload(defctxnull);
13952     OSSL_LIB_CTX_free(libctx);
13953 }
13954