xref: /freebsd/crypto/openssl/test/sslapitest.c (revision 046c625e9382e17da953767b881aaa782fa73af8)
1 /*
2  * Copyright 2016-2025 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 
149 
hostname_cb(SSL * s,int * al,void * arg)150 static int hostname_cb(SSL *s, int *al, void *arg)
151 {
152     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
153 
154     if (hostname != NULL && (strcmp(hostname, "goodhost") == 0
155                              || strcmp(hostname, "altgoodhost") == 0))
156         return  SSL_TLSEXT_ERR_OK;
157 
158     return SSL_TLSEXT_ERR_NOACK;
159 }
160 
client_keylog_callback(const SSL * ssl,const char * line)161 static void client_keylog_callback(const SSL *ssl, const char *line)
162 {
163     int line_length = strlen(line);
164 
165     /* If the log doesn't fit, error out. */
166     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
167         TEST_info("Client log too full");
168         error_writing_log = 1;
169         return;
170     }
171 
172     strcat(client_log_buffer, line);
173     client_log_buffer_index += line_length;
174     client_log_buffer[client_log_buffer_index++] = '\n';
175 }
176 
server_keylog_callback(const SSL * ssl,const char * line)177 static void server_keylog_callback(const SSL *ssl, const char *line)
178 {
179     int line_length = strlen(line);
180 
181     /* If the log doesn't fit, error out. */
182     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
183         TEST_info("Server log too full");
184         error_writing_log = 1;
185         return;
186     }
187 
188     strcat(server_log_buffer, line);
189     server_log_buffer_index += line_length;
190     server_log_buffer[server_log_buffer_index++] = '\n';
191 }
192 
compare_hex_encoded_buffer(const char * hex_encoded,size_t hex_length,const uint8_t * raw,size_t raw_length)193 static int compare_hex_encoded_buffer(const char *hex_encoded,
194                                       size_t hex_length,
195                                       const uint8_t *raw,
196                                       size_t raw_length)
197 {
198     size_t i, j;
199     char hexed[3];
200 
201     if (!TEST_size_t_eq(raw_length * 2, hex_length))
202         return 1;
203 
204     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
205         BIO_snprintf(hexed, sizeof(hexed), "%02x", raw[i]);
206         if (!TEST_int_eq(hexed[0], hex_encoded[j])
207                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
208             return 1;
209     }
210 
211     return 0;
212 }
213 
test_keylog_output(char * buffer,const SSL * ssl,const SSL_SESSION * session,struct sslapitest_log_counts * expected)214 static int test_keylog_output(char *buffer, const SSL *ssl,
215                               const SSL_SESSION *session,
216                               struct sslapitest_log_counts *expected)
217 {
218     char *token = NULL;
219     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
220     size_t client_random_size = SSL3_RANDOM_SIZE;
221     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
222     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
223     unsigned int rsa_key_exchange_count = 0;
224     unsigned int master_secret_count = 0;
225     unsigned int client_early_secret_count = 0;
226     unsigned int client_handshake_secret_count = 0;
227     unsigned int server_handshake_secret_count = 0;
228     unsigned int client_application_secret_count = 0;
229     unsigned int server_application_secret_count = 0;
230     unsigned int early_exporter_secret_count = 0;
231     unsigned int exporter_secret_count = 0;
232 
233     for (token = strtok(buffer, " \n"); token != NULL;
234          token = strtok(NULL, " \n")) {
235         if (strcmp(token, "RSA") == 0) {
236             /*
237              * Premaster secret. Tokens should be: 16 ASCII bytes of
238              * hex-encoded encrypted secret, then the hex-encoded pre-master
239              * secret.
240              */
241             if (!TEST_ptr(token = strtok(NULL, " \n")))
242                 return 0;
243             if (!TEST_size_t_eq(strlen(token), 16))
244                 return 0;
245             if (!TEST_ptr(token = strtok(NULL, " \n")))
246                 return 0;
247             /*
248              * We can't sensibly check the log because the premaster secret is
249              * transient, and OpenSSL doesn't keep hold of it once the master
250              * secret is generated.
251              */
252             rsa_key_exchange_count++;
253         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
254             /*
255              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
256              * client random, then the hex-encoded master secret.
257              */
258             client_random_size = SSL_get_client_random(ssl,
259                                                        actual_client_random,
260                                                        SSL3_RANDOM_SIZE);
261             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
262                 return 0;
263 
264             if (!TEST_ptr(token = strtok(NULL, " \n")))
265                 return 0;
266             if (!TEST_size_t_eq(strlen(token), 64))
267                 return 0;
268             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
269                                                        actual_client_random,
270                                                        client_random_size)))
271                 return 0;
272 
273             if (!TEST_ptr(token = strtok(NULL, " \n")))
274                 return 0;
275             master_key_size = SSL_SESSION_get_master_key(session,
276                                                          actual_master_key,
277                                                          master_key_size);
278             if (!TEST_size_t_ne(master_key_size, 0))
279                 return 0;
280             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
281                                                        actual_master_key,
282                                                        master_key_size)))
283                 return 0;
284             master_secret_count++;
285         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
286                     || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
287                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
288                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
289                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
290                     || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
291                     || strcmp(token, "EXPORTER_SECRET") == 0) {
292             /*
293              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
294              * client random, and then the hex-encoded secret. In this case,
295              * we treat all of these secrets identically and then just
296              * distinguish between them when counting what we saw.
297              */
298             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
299                 client_early_secret_count++;
300             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
301                 client_handshake_secret_count++;
302             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
303                 server_handshake_secret_count++;
304             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
305                 client_application_secret_count++;
306             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
307                 server_application_secret_count++;
308             else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
309                 early_exporter_secret_count++;
310             else if (strcmp(token, "EXPORTER_SECRET") == 0)
311                 exporter_secret_count++;
312 
313             client_random_size = SSL_get_client_random(ssl,
314                                                        actual_client_random,
315                                                        SSL3_RANDOM_SIZE);
316             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
317                 return 0;
318 
319             if (!TEST_ptr(token = strtok(NULL, " \n")))
320                 return 0;
321             if (!TEST_size_t_eq(strlen(token), 64))
322                 return 0;
323             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
324                                                        actual_client_random,
325                                                        client_random_size)))
326                 return 0;
327 
328             if (!TEST_ptr(token = strtok(NULL, " \n")))
329                 return 0;
330         } else {
331             TEST_info("Unexpected token %s\n", token);
332             return 0;
333         }
334     }
335 
336     /* Got what we expected? */
337     if (!TEST_size_t_eq(rsa_key_exchange_count,
338                         expected->rsa_key_exchange_count)
339             || !TEST_size_t_eq(master_secret_count,
340                                expected->master_secret_count)
341             || !TEST_size_t_eq(client_early_secret_count,
342                                expected->client_early_secret_count)
343             || !TEST_size_t_eq(client_handshake_secret_count,
344                                expected->client_handshake_secret_count)
345             || !TEST_size_t_eq(server_handshake_secret_count,
346                                expected->server_handshake_secret_count)
347             || !TEST_size_t_eq(client_application_secret_count,
348                                expected->client_application_secret_count)
349             || !TEST_size_t_eq(server_application_secret_count,
350                                expected->server_application_secret_count)
351             || !TEST_size_t_eq(early_exporter_secret_count,
352                                expected->early_exporter_secret_count)
353             || !TEST_size_t_eq(exporter_secret_count,
354                                expected->exporter_secret_count))
355         return 0;
356     return 1;
357 }
358 
359 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
test_keylog(void)360 static int test_keylog(void)
361 {
362     SSL_CTX *cctx = NULL, *sctx = NULL;
363     SSL *clientssl = NULL, *serverssl = NULL;
364     int testresult = 0;
365     struct sslapitest_log_counts expected;
366 
367     /* Clean up logging space */
368     memset(&expected, 0, sizeof(expected));
369     memset(client_log_buffer, 0, sizeof(client_log_buffer));
370     memset(server_log_buffer, 0, sizeof(server_log_buffer));
371     client_log_buffer_index = 0;
372     server_log_buffer_index = 0;
373     error_writing_log = 0;
374 
375     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
376                                        TLS_client_method(),
377                                        TLS1_VERSION, 0,
378                                        &sctx, &cctx, cert, privkey)))
379         return 0;
380 
381     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
382     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
383     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
384 
385     /* We also want to ensure that we use RSA-based key exchange. */
386     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
387         goto end;
388 
389     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
390             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
391         goto end;
392     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
393     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
394                    == client_keylog_callback))
395         goto end;
396     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
397     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
398                    == server_keylog_callback))
399         goto end;
400 
401     /* Now do a handshake and check that the logs have been written to. */
402     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
403                                       &clientssl, NULL, NULL))
404             || !TEST_true(create_ssl_connection(serverssl, clientssl,
405                                                 SSL_ERROR_NONE))
406             || !TEST_false(error_writing_log)
407             || !TEST_int_gt(client_log_buffer_index, 0)
408             || !TEST_int_gt(server_log_buffer_index, 0))
409         goto end;
410 
411     /*
412      * Now we want to test that our output data was vaguely sensible. We
413      * do that by using strtok and confirming that we have more or less the
414      * data we expect. For both client and server, we expect to see one master
415      * secret. The client should also see an RSA key exchange.
416      */
417     expected.rsa_key_exchange_count = 1;
418     expected.master_secret_count = 1;
419     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
420                                       SSL_get_session(clientssl), &expected)))
421         goto end;
422 
423     expected.rsa_key_exchange_count = 0;
424     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
425                                       SSL_get_session(serverssl), &expected)))
426         goto end;
427 
428     testresult = 1;
429 
430 end:
431     SSL_free(serverssl);
432     SSL_free(clientssl);
433     SSL_CTX_free(sctx);
434     SSL_CTX_free(cctx);
435 
436     return testresult;
437 }
438 #endif
439 
440 #ifndef OSSL_NO_USABLE_TLS1_3
test_keylog_no_master_key(void)441 static int test_keylog_no_master_key(void)
442 {
443     SSL_CTX *cctx = NULL, *sctx = NULL;
444     SSL *clientssl = NULL, *serverssl = NULL;
445     SSL_SESSION *sess = NULL;
446     int testresult = 0;
447     struct sslapitest_log_counts expected;
448     unsigned char buf[1];
449     size_t readbytes, written;
450 
451     /* Clean up logging space */
452     memset(&expected, 0, sizeof(expected));
453     memset(client_log_buffer, 0, sizeof(client_log_buffer));
454     memset(server_log_buffer, 0, sizeof(server_log_buffer));
455     client_log_buffer_index = 0;
456     server_log_buffer_index = 0;
457     error_writing_log = 0;
458 
459     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
460                                        TLS_client_method(), TLS1_VERSION, 0,
461                                        &sctx, &cctx, cert, privkey))
462         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
463                                                  SSL3_RT_MAX_PLAIN_LENGTH)))
464         return 0;
465 
466     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
467             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
468         goto end;
469 
470     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
471     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
472                    == client_keylog_callback))
473         goto end;
474 
475     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
476     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
477                    == server_keylog_callback))
478         goto end;
479 
480     /* Now do a handshake and check that the logs have been written to. */
481     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
482                                       &clientssl, NULL, NULL))
483             || !TEST_true(create_ssl_connection(serverssl, clientssl,
484                                                 SSL_ERROR_NONE))
485             || !TEST_false(error_writing_log))
486         goto end;
487 
488     /*
489      * Now we want to test that our output data was vaguely sensible. For this
490      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
491      * TLSv1.3, but we do expect both client and server to emit keys.
492      */
493     expected.client_handshake_secret_count = 1;
494     expected.server_handshake_secret_count = 1;
495     expected.client_application_secret_count = 1;
496     expected.server_application_secret_count = 1;
497     expected.exporter_secret_count = 1;
498     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
499                                       SSL_get_session(clientssl), &expected))
500             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
501                                              SSL_get_session(serverssl),
502                                              &expected)))
503         goto end;
504 
505     /* Terminate old session and resume with early data. */
506     sess = SSL_get1_session(clientssl);
507     SSL_shutdown(clientssl);
508     SSL_shutdown(serverssl);
509     SSL_free(serverssl);
510     SSL_free(clientssl);
511     serverssl = clientssl = NULL;
512 
513     /* Reset key log */
514     memset(client_log_buffer, 0, sizeof(client_log_buffer));
515     memset(server_log_buffer, 0, sizeof(server_log_buffer));
516     client_log_buffer_index = 0;
517     server_log_buffer_index = 0;
518 
519     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
520                                       &clientssl, NULL, NULL))
521             || !TEST_true(SSL_set_session(clientssl, sess))
522             /* Here writing 0 length early data is enough. */
523             || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
524             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
525                                                 &readbytes),
526                             SSL_READ_EARLY_DATA_ERROR)
527             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
528                             SSL_EARLY_DATA_ACCEPTED)
529             || !TEST_true(create_ssl_connection(serverssl, clientssl,
530                           SSL_ERROR_NONE))
531             || !TEST_true(SSL_session_reused(clientssl)))
532         goto end;
533 
534     /* In addition to the previous entries, expect early secrets. */
535     expected.client_early_secret_count = 1;
536     expected.early_exporter_secret_count = 1;
537     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
538                                       SSL_get_session(clientssl), &expected))
539             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
540                                              SSL_get_session(serverssl),
541                                              &expected)))
542         goto end;
543 
544     testresult = 1;
545 
546 end:
547     SSL_SESSION_free(sess);
548     SSL_free(serverssl);
549     SSL_free(clientssl);
550     SSL_CTX_free(sctx);
551     SSL_CTX_free(cctx);
552 
553     return testresult;
554 }
555 #endif
556 
verify_retry_cb(X509_STORE_CTX * ctx,void * arg)557 static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg)
558 {
559     int res = X509_verify_cert(ctx);
560     int idx = SSL_get_ex_data_X509_STORE_CTX_idx();
561     SSL *ssl;
562 
563     /* this should not happen but check anyway */
564     if (idx < 0
565         || (ssl = X509_STORE_CTX_get_ex_data(ctx, idx)) == NULL)
566         return 0;
567 
568     if (res == 0 && X509_STORE_CTX_get_error(ctx) ==
569         X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)
570         /* indicate SSL_ERROR_WANT_RETRY_VERIFY */
571         return SSL_set_retry_verify(ssl);
572 
573     return res;
574 }
575 
test_client_cert_verify_cb(void)576 static int test_client_cert_verify_cb(void)
577 {
578     /* server key, cert, chain, and root */
579     char *skey = test_mk_file_path(certsdir, "leaf.key");
580     char *leaf = test_mk_file_path(certsdir, "leaf.pem");
581     char *int2 = test_mk_file_path(certsdir, "subinterCA.pem");
582     char *int1 = test_mk_file_path(certsdir, "interCA.pem");
583     char *root = test_mk_file_path(certsdir, "rootCA.pem");
584     X509 *crt1 = NULL, *crt2 = NULL;
585     STACK_OF(X509) *server_chain;
586     SSL_CTX *cctx = NULL, *sctx = NULL;
587     SSL *clientssl = NULL, *serverssl = NULL;
588     int testresult = 0;
589 
590     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
591                                        TLS_client_method(), TLS1_VERSION, 0,
592                                        &sctx, &cctx, NULL, NULL)))
593         goto end;
594     if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(sctx, leaf), 1)
595             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx, skey,
596                                                         SSL_FILETYPE_PEM), 1)
597             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
598         goto end;
599     if (!TEST_true(SSL_CTX_load_verify_locations(cctx, root, NULL)))
600         goto end;
601     SSL_CTX_set_verify(cctx, SSL_VERIFY_PEER, NULL);
602     SSL_CTX_set_cert_verify_callback(cctx, verify_retry_cb, NULL);
603     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
604                                       &clientssl, NULL, NULL)))
605         goto end;
606 
607     /* attempt SSL_connect() with incomplete server chain */
608     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
609                                           SSL_ERROR_WANT_RETRY_VERIFY)))
610         goto end;
611 
612     /* application provides intermediate certs needed to verify server cert */
613     if (!TEST_ptr((crt1 = load_cert_pem(int1, libctx)))
614         || !TEST_ptr((crt2 = load_cert_pem(int2, libctx)))
615         || !TEST_ptr((server_chain = SSL_get_peer_cert_chain(clientssl))))
616         goto end;
617     /* add certs in reverse order to demonstrate real chain building */
618     if (!TEST_true(sk_X509_push(server_chain, crt1)))
619         goto end;
620     crt1 = NULL;
621     if (!TEST_true(sk_X509_push(server_chain, crt2)))
622         goto end;
623     crt2 = NULL;
624 
625     /* continue SSL_connect(), must now succeed with completed server chain */
626     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
627                                          SSL_ERROR_NONE)))
628         goto end;
629 
630     testresult = 1;
631 
632 end:
633     X509_free(crt1);
634     X509_free(crt2);
635     if (clientssl != NULL) {
636         SSL_shutdown(clientssl);
637         SSL_free(clientssl);
638     }
639     if (serverssl != NULL) {
640         SSL_shutdown(serverssl);
641         SSL_free(serverssl);
642     }
643     SSL_CTX_free(sctx);
644     SSL_CTX_free(cctx);
645 
646     OPENSSL_free(skey);
647     OPENSSL_free(leaf);
648     OPENSSL_free(int2);
649     OPENSSL_free(int1);
650     OPENSSL_free(root);
651 
652     return testresult;
653 }
654 
test_ssl_build_cert_chain(void)655 static int test_ssl_build_cert_chain(void)
656 {
657     int ret = 0;
658     SSL_CTX *ssl_ctx = NULL;
659     SSL *ssl = NULL;
660     char *skey = test_mk_file_path(certsdir, "leaf.key");
661     char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
662 
663     if (!TEST_ptr(ssl_ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
664         goto end;
665     if (!TEST_ptr(ssl = SSL_new(ssl_ctx)))
666         goto end;
667     /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
668     if (!TEST_int_eq(SSL_use_certificate_chain_file(ssl, leaf_chain), 1)
669         || !TEST_int_eq(SSL_use_PrivateKey_file(ssl, skey, SSL_FILETYPE_PEM), 1)
670         || !TEST_int_eq(SSL_check_private_key(ssl), 1))
671         goto end;
672     if (!TEST_true(SSL_build_cert_chain(ssl, SSL_BUILD_CHAIN_FLAG_NO_ROOT
673                                              | SSL_BUILD_CHAIN_FLAG_CHECK)))
674         goto end;
675     ret = 1;
676 end:
677     SSL_free(ssl);
678     SSL_CTX_free(ssl_ctx);
679     OPENSSL_free(leaf_chain);
680     OPENSSL_free(skey);
681     return ret;
682 }
683 
get_password_cb(char * buf,int size,int rw_flag,void * userdata)684 static int get_password_cb(char *buf, int size, int rw_flag, void *userdata)
685 {
686     static const char pass[] = "testpass";
687 
688     if (!TEST_int_eq(size, PEM_BUFSIZE))
689         return -1;
690 
691     memcpy(buf, pass, sizeof(pass) - 1);
692     return sizeof(pass) - 1;
693 }
694 
test_ssl_ctx_build_cert_chain(void)695 static int test_ssl_ctx_build_cert_chain(void)
696 {
697     int ret = 0;
698     SSL_CTX *ctx = NULL;
699     char *skey = test_mk_file_path(certsdir, "leaf-encrypted.key");
700     char *leaf_chain = test_mk_file_path(certsdir, "leaf-chain.pem");
701 
702     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
703         goto end;
704     SSL_CTX_set_default_passwd_cb(ctx, get_password_cb);
705     /* leaf_chain contains leaf + subinterCA + interCA + rootCA */
706     if (!TEST_int_eq(SSL_CTX_use_certificate_chain_file(ctx, leaf_chain), 1)
707         || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(ctx, skey,
708                                                     SSL_FILETYPE_PEM), 1)
709         || !TEST_int_eq(SSL_CTX_check_private_key(ctx), 1))
710         goto end;
711     if (!TEST_true(SSL_CTX_build_cert_chain(ctx, SSL_BUILD_CHAIN_FLAG_NO_ROOT
712                                                 | SSL_BUILD_CHAIN_FLAG_CHECK)))
713         goto end;
714     ret = 1;
715 end:
716     SSL_CTX_free(ctx);
717     OPENSSL_free(leaf_chain);
718     OPENSSL_free(skey);
719     return ret;
720 }
721 
722 #ifndef OPENSSL_NO_TLS1_2
full_client_hello_callback(SSL * s,int * al,void * arg)723 static int full_client_hello_callback(SSL *s, int *al, void *arg)
724 {
725     int *ctr = arg;
726     const unsigned char *p;
727     int *exts;
728 #ifdef OPENSSL_NO_EC
729     const unsigned char expected_ciphers[] = {0x00, 0x9d};
730 #else
731     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
732                                               0x2c};
733 #endif
734     const int expected_extensions[] = {
735                                        65281,
736 #ifndef OPENSSL_NO_EC
737                                        11, 10,
738 #endif
739                                        35, 22, 23, 13};
740     size_t len;
741 
742     /* Make sure we can defer processing and get called back. */
743     if ((*ctr)++ == 0)
744         return SSL_CLIENT_HELLO_RETRY;
745 
746     len = SSL_client_hello_get0_ciphers(s, &p);
747     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
748             || !TEST_size_t_eq(
749                        SSL_client_hello_get0_compression_methods(s, &p), 1)
750             || !TEST_int_eq(*p, 0))
751         return SSL_CLIENT_HELLO_ERROR;
752     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
753         return SSL_CLIENT_HELLO_ERROR;
754     if (len != OSSL_NELEM(expected_extensions) ||
755         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
756         printf("ClientHello callback expected extensions mismatch\n");
757         OPENSSL_free(exts);
758         return SSL_CLIENT_HELLO_ERROR;
759     }
760     OPENSSL_free(exts);
761     return SSL_CLIENT_HELLO_SUCCESS;
762 }
763 
test_client_hello_cb(void)764 static int test_client_hello_cb(void)
765 {
766     SSL_CTX *cctx = NULL, *sctx = NULL;
767     SSL *clientssl = NULL, *serverssl = NULL;
768     int testctr = 0, testresult = 0;
769 
770     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
771                                        TLS_client_method(), TLS1_VERSION, 0,
772                                        &sctx, &cctx, cert, privkey)))
773         goto end;
774     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
775 
776     /* The gimpy cipher list we configure can't do TLS 1.3. */
777     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
778     /* Avoid problems where the default seclevel has been changed */
779     SSL_CTX_set_security_level(cctx, 2);
780     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
781                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
782             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
783                                              &clientssl, NULL, NULL))
784             || !TEST_false(create_ssl_connection(serverssl, clientssl,
785                         SSL_ERROR_WANT_CLIENT_HELLO_CB))
786                 /*
787                  * Passing a -1 literal is a hack since
788                  * the real value was lost.
789                  * */
790             || !TEST_int_eq(SSL_get_error(serverssl, -1),
791                             SSL_ERROR_WANT_CLIENT_HELLO_CB)
792             || !TEST_true(create_ssl_connection(serverssl, clientssl,
793                                                 SSL_ERROR_NONE)))
794         goto end;
795 
796     testresult = 1;
797 
798 end:
799     SSL_free(serverssl);
800     SSL_free(clientssl);
801     SSL_CTX_free(sctx);
802     SSL_CTX_free(cctx);
803 
804     return testresult;
805 }
806 
test_no_ems(void)807 static int test_no_ems(void)
808 {
809     SSL_CTX *cctx = NULL, *sctx = NULL;
810     SSL *clientssl = NULL, *serverssl = NULL;
811     int testresult = 0, status;
812 
813     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
814                              TLS1_VERSION, TLS1_2_VERSION,
815                              &sctx, &cctx, cert, privkey)) {
816         printf("Unable to create SSL_CTX pair\n");
817         goto end;
818     }
819 
820     SSL_CTX_set_options(sctx, SSL_OP_NO_EXTENDED_MASTER_SECRET);
821 
822     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
823         printf("Unable to create SSL objects\n");
824         goto end;
825     }
826 
827     status = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
828     if (fips_ems_check) {
829         if (status == 1) {
830             printf("When FIPS uses the EMS check a connection that doesn't use EMS should fail\n");
831             goto end;
832         }
833     } else {
834         if (!status) {
835             printf("Creating SSL connection failed\n");
836             goto end;
837         }
838         if (SSL_get_extms_support(serverssl)) {
839             printf("Server reports Extended Master Secret support\n");
840             goto end;
841         }
842         if (SSL_get_extms_support(clientssl)) {
843             printf("Client reports Extended Master Secret support\n");
844             goto end;
845         }
846     }
847     testresult = 1;
848 
849 end:
850     SSL_free(serverssl);
851     SSL_free(clientssl);
852     SSL_CTX_free(sctx);
853     SSL_CTX_free(cctx);
854 
855     return testresult;
856 }
857 
858 /*
859  * Very focused test to exercise a single case in the server-side state
860  * machine, when the ChangeCipherState message needs to actually change
861  * from one cipher to a different cipher (i.e., not changing from null
862  * encryption to real encryption).
863  */
test_ccs_change_cipher(void)864 static int test_ccs_change_cipher(void)
865 {
866     SSL_CTX *cctx = NULL, *sctx = NULL;
867     SSL *clientssl = NULL, *serverssl = NULL;
868     SSL_SESSION *sess = NULL, *sesspre, *sesspost;
869     int testresult = 0;
870     int i;
871     unsigned char buf;
872     size_t readbytes;
873 
874     /*
875      * Create a connection so we can resume and potentially (but not) use
876      * a different cipher in the second connection.
877      */
878     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
879                                        TLS_client_method(),
880                                        TLS1_VERSION, TLS1_2_VERSION,
881                                        &sctx, &cctx, cert, privkey))
882             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
883             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
884                           NULL, NULL))
885             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
886             || !TEST_true(create_ssl_connection(serverssl, clientssl,
887                                                 SSL_ERROR_NONE))
888             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
889             || !TEST_ptr(sess = SSL_get1_session(clientssl)))
890         goto end;
891 
892     shutdown_ssl_connection(serverssl, clientssl);
893     serverssl = clientssl = NULL;
894 
895     /* Resume, preferring a different cipher. Our server will force the
896      * same cipher to be used as the initial handshake. */
897     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
898                           NULL, NULL))
899             || !TEST_true(SSL_set_session(clientssl, sess))
900             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
901             || !TEST_true(create_ssl_connection(serverssl, clientssl,
902                                                 SSL_ERROR_NONE))
903             || !TEST_true(SSL_session_reused(clientssl))
904             || !TEST_true(SSL_session_reused(serverssl))
905             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
906             || !TEST_ptr_eq(sesspre, sesspost)
907             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
908                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
909         goto end;
910     shutdown_ssl_connection(serverssl, clientssl);
911     serverssl = clientssl = NULL;
912 
913     /*
914      * Now create a fresh connection and try to renegotiate a different
915      * cipher on it.
916      */
917     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
918                                       NULL, NULL))
919             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
920             || !TEST_true(create_ssl_connection(serverssl, clientssl,
921                                                 SSL_ERROR_NONE))
922             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
923             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
924             || !TEST_true(SSL_renegotiate(clientssl))
925             || !TEST_true(SSL_renegotiate_pending(clientssl)))
926         goto end;
927     /* Actually drive the renegotiation. */
928     for (i = 0; i < 3; i++) {
929         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
930             if (!TEST_ulong_eq(readbytes, 0))
931                 goto end;
932         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
933                                 SSL_ERROR_WANT_READ)) {
934             goto end;
935         }
936         if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
937             if (!TEST_ulong_eq(readbytes, 0))
938                 goto end;
939         } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
940                                 SSL_ERROR_WANT_READ)) {
941             goto end;
942         }
943     }
944     /* sesspre and sesspost should be different since the cipher changed. */
945     if (!TEST_false(SSL_renegotiate_pending(clientssl))
946             || !TEST_false(SSL_session_reused(clientssl))
947             || !TEST_false(SSL_session_reused(serverssl))
948             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
949             || !TEST_ptr_ne(sesspre, sesspost)
950             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
951                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
952         goto end;
953 
954     shutdown_ssl_connection(serverssl, clientssl);
955     serverssl = clientssl = NULL;
956 
957     testresult = 1;
958 
959 end:
960     SSL_free(serverssl);
961     SSL_free(clientssl);
962     SSL_CTX_free(sctx);
963     SSL_CTX_free(cctx);
964     SSL_SESSION_free(sess);
965 
966     return testresult;
967 }
968 #endif
969 
execute_test_large_message(const SSL_METHOD * smeth,const SSL_METHOD * cmeth,int min_version,int max_version,int read_ahead)970 static int execute_test_large_message(const SSL_METHOD *smeth,
971                                       const SSL_METHOD *cmeth,
972                                       int min_version, int max_version,
973                                       int read_ahead)
974 {
975     SSL_CTX *cctx = NULL, *sctx = NULL;
976     SSL *clientssl = NULL, *serverssl = NULL;
977     int testresult = 0;
978 
979     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
980                                        max_version, &sctx, &cctx, cert,
981                                        privkey)))
982         goto end;
983 
984 #ifdef OPENSSL_NO_DTLS1_2
985     if (smeth == DTLS_server_method()) {
986         /*
987          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
988          * level 0
989          */
990         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
991                 || !TEST_true(SSL_CTX_set_cipher_list(cctx,
992                                                     "DEFAULT:@SECLEVEL=0")))
993             goto end;
994     }
995 #endif
996 
997     if (read_ahead) {
998         /*
999          * Test that read_ahead works correctly when dealing with large
1000          * records
1001          */
1002         SSL_CTX_set_read_ahead(cctx, 1);
1003     }
1004 
1005     if (!ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
1006         goto end;
1007 
1008     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1009                                       NULL, NULL))
1010             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1011                                                 SSL_ERROR_NONE)))
1012         goto end;
1013 
1014     /*
1015      * Calling SSL_clear() first is not required but this tests that SSL_clear()
1016      * doesn't leak.
1017      */
1018     if (!TEST_true(SSL_clear(serverssl)))
1019         goto end;
1020 
1021     testresult = 1;
1022  end:
1023     SSL_free(serverssl);
1024     SSL_free(clientssl);
1025     SSL_CTX_free(sctx);
1026     SSL_CTX_free(cctx);
1027 
1028     return testresult;
1029 }
1030 
1031 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_KTLS) && \
1032     !(defined(OSSL_NO_USABLE_TLS1_3) && defined(OPENSSL_NO_TLS1_2))
1033 /* sock must be connected */
ktls_chk_platform(int sock)1034 static int ktls_chk_platform(int sock)
1035 {
1036     if (!ktls_enable(sock))
1037         return 0;
1038     return 1;
1039 }
1040 
ping_pong_query(SSL * clientssl,SSL * serverssl)1041 static int ping_pong_query(SSL *clientssl, SSL *serverssl)
1042 {
1043     static char count = 1;
1044     unsigned char cbuf[16000] = {0};
1045     unsigned char sbuf[16000];
1046     size_t err = 0;
1047     char crec_wseq_before[SEQ_NUM_SIZE];
1048     char crec_wseq_after[SEQ_NUM_SIZE];
1049     char crec_rseq_before[SEQ_NUM_SIZE];
1050     char crec_rseq_after[SEQ_NUM_SIZE];
1051     char srec_wseq_before[SEQ_NUM_SIZE];
1052     char srec_wseq_after[SEQ_NUM_SIZE];
1053     char srec_rseq_before[SEQ_NUM_SIZE];
1054     char srec_rseq_after[SEQ_NUM_SIZE];
1055     SSL_CONNECTION *clientsc, *serversc;
1056 
1057     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1058         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1059         goto end;
1060 
1061     cbuf[0] = count++;
1062     memcpy(crec_wseq_before, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1063     memcpy(srec_wseq_before, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1064     memcpy(crec_rseq_before, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1065     memcpy(srec_rseq_before, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1066 
1067     if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf)))
1068         goto end;
1069 
1070     while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) {
1071         if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) {
1072             goto end;
1073         }
1074     }
1075 
1076     if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf)))
1077         goto end;
1078 
1079     while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) {
1080         if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) {
1081             goto end;
1082         }
1083     }
1084 
1085     memcpy(crec_wseq_after, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1086     memcpy(srec_wseq_after, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1087     memcpy(crec_rseq_after, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1088     memcpy(srec_rseq_after, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1089 
1090     /* verify the payload */
1091     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1092         goto end;
1093 
1094     /*
1095      * If ktls is used then kernel sequences are used instead of
1096      * OpenSSL sequences
1097      */
1098     if (!BIO_get_ktls_send(clientsc->wbio)) {
1099         if (!TEST_mem_ne(crec_wseq_before, SEQ_NUM_SIZE,
1100                          crec_wseq_after, SEQ_NUM_SIZE))
1101             goto end;
1102     } else {
1103         if (!TEST_mem_eq(crec_wseq_before, SEQ_NUM_SIZE,
1104                          crec_wseq_after, SEQ_NUM_SIZE))
1105             goto end;
1106     }
1107 
1108     if (!BIO_get_ktls_send(serversc->wbio)) {
1109         if (!TEST_mem_ne(srec_wseq_before, SEQ_NUM_SIZE,
1110                          srec_wseq_after, SEQ_NUM_SIZE))
1111             goto end;
1112     } else {
1113         if (!TEST_mem_eq(srec_wseq_before, SEQ_NUM_SIZE,
1114                          srec_wseq_after, SEQ_NUM_SIZE))
1115             goto end;
1116     }
1117 
1118     if (!BIO_get_ktls_recv(clientsc->wbio)) {
1119         if (!TEST_mem_ne(crec_rseq_before, SEQ_NUM_SIZE,
1120                          crec_rseq_after, SEQ_NUM_SIZE))
1121             goto end;
1122     } else {
1123         if (!TEST_mem_eq(crec_rseq_before, SEQ_NUM_SIZE,
1124                          crec_rseq_after, SEQ_NUM_SIZE))
1125             goto end;
1126     }
1127 
1128     if (!BIO_get_ktls_recv(serversc->wbio)) {
1129         if (!TEST_mem_ne(srec_rseq_before, SEQ_NUM_SIZE,
1130                          srec_rseq_after, SEQ_NUM_SIZE))
1131             goto end;
1132     } else {
1133         if (!TEST_mem_eq(srec_rseq_before, SEQ_NUM_SIZE,
1134                          srec_rseq_after, SEQ_NUM_SIZE))
1135             goto end;
1136     }
1137 
1138     return 1;
1139 end:
1140     return 0;
1141 }
1142 
execute_test_ktls(int cis_ktls,int sis_ktls,int tls_version,const char * cipher)1143 static int execute_test_ktls(int cis_ktls, int sis_ktls,
1144                              int tls_version, const char *cipher)
1145 {
1146     SSL_CTX *cctx = NULL, *sctx = NULL;
1147     SSL *clientssl = NULL, *serverssl = NULL;
1148     int ktls_used = 0, testresult = 0;
1149     int cfd = -1, sfd = -1;
1150     int rx_supported;
1151     SSL_CONNECTION *clientsc, *serversc;
1152     unsigned char *buf = NULL;
1153     const size_t bufsz = SSL3_RT_MAX_PLAIN_LENGTH + 16;
1154     int ret;
1155     size_t offset = 0, i;
1156 
1157     if (!TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1158         goto end;
1159 
1160     /* Skip this test if the platform does not support ktls */
1161     if (!ktls_chk_platform(cfd)) {
1162         testresult = TEST_skip("Kernel does not support KTLS");
1163         goto end;
1164     }
1165 
1166     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1167         testresult = TEST_skip("CHACHA is not supported in FIPS");
1168         goto end;
1169     }
1170 
1171     /* Create a session based on SHA-256 */
1172     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1173                                        TLS_client_method(),
1174                                        tls_version, tls_version,
1175                                        &sctx, &cctx, cert, privkey)))
1176         goto end;
1177 
1178     if (tls_version == TLS1_3_VERSION) {
1179         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1180             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1181             goto end;
1182     } else {
1183         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1184             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1185             goto end;
1186     }
1187 
1188     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1189                                        &clientssl, sfd, cfd)))
1190         goto end;
1191 
1192     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1193         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1194         goto end;
1195 
1196     if (cis_ktls) {
1197         if (!TEST_true(SSL_set_options(clientssl, SSL_OP_ENABLE_KTLS)))
1198             goto end;
1199     }
1200 
1201     if (sis_ktls) {
1202         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1203             goto end;
1204     }
1205 
1206     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1207         goto end;
1208 
1209     /*
1210      * The running kernel may not support a given cipher suite
1211      * or direction, so just check that KTLS isn't used when it
1212      * isn't enabled.
1213      */
1214     if (!cis_ktls) {
1215         if (!TEST_false(BIO_get_ktls_send(clientsc->wbio)))
1216             goto end;
1217     } else {
1218         if (BIO_get_ktls_send(clientsc->wbio))
1219             ktls_used = 1;
1220     }
1221 
1222     if (!sis_ktls) {
1223         if (!TEST_false(BIO_get_ktls_send(serversc->wbio)))
1224             goto end;
1225     } else {
1226         if (BIO_get_ktls_send(serversc->wbio))
1227             ktls_used = 1;
1228     }
1229 
1230 #if defined(OPENSSL_NO_KTLS_RX)
1231     rx_supported = 0;
1232 #else
1233     rx_supported = 1;
1234 #endif
1235     if (!cis_ktls || !rx_supported) {
1236         if (!TEST_false(BIO_get_ktls_recv(clientsc->rbio)))
1237             goto end;
1238     } else {
1239         if (BIO_get_ktls_send(clientsc->rbio))
1240             ktls_used = 1;
1241     }
1242 
1243     if (!sis_ktls || !rx_supported) {
1244         if (!TEST_false(BIO_get_ktls_recv(serversc->rbio)))
1245             goto end;
1246     } else {
1247         if (BIO_get_ktls_send(serversc->rbio))
1248             ktls_used = 1;
1249     }
1250 
1251     if ((cis_ktls || sis_ktls) && !ktls_used) {
1252         testresult = TEST_skip("KTLS not supported for %s cipher %s",
1253                                tls_version == TLS1_3_VERSION ? "TLS 1.3" :
1254                                "TLS 1.2", cipher);
1255         goto end;
1256     }
1257 
1258     if (!TEST_true(ping_pong_query(clientssl, serverssl)))
1259         goto end;
1260 
1261     buf = OPENSSL_zalloc(bufsz);
1262     if (!TEST_ptr(buf))
1263         goto end;
1264 
1265     /*
1266      * Write some data that exceeds the maximum record length. KTLS may choose
1267      * to coalesce this data into a single buffer when we read it again.
1268      */
1269     while ((ret = SSL_write(clientssl, buf, bufsz)) != (int)bufsz) {
1270         if (!TEST_true(SSL_get_error(clientssl, ret) == SSL_ERROR_WANT_WRITE))
1271             goto end;
1272     }
1273 
1274     /* Now check that we can read all the data we wrote */
1275     do {
1276         ret = SSL_read(serverssl, buf + offset, bufsz - offset);
1277         if (ret <= 0) {
1278             if (!TEST_true(SSL_get_error(serverssl, ret) == SSL_ERROR_WANT_READ))
1279                 goto end;
1280         } else {
1281             offset += ret;
1282         }
1283     } while (offset < bufsz);
1284 
1285     if (!TEST_true(offset == bufsz))
1286         goto end;
1287     for (i = 0; i < bufsz; i++)
1288         if (!TEST_true(buf[i] == 0))
1289             goto end;
1290 
1291     testresult = 1;
1292 end:
1293     OPENSSL_free(buf);
1294     if (clientssl) {
1295         SSL_shutdown(clientssl);
1296         SSL_free(clientssl);
1297     }
1298     if (serverssl) {
1299         SSL_shutdown(serverssl);
1300         SSL_free(serverssl);
1301     }
1302     SSL_CTX_free(sctx);
1303     SSL_CTX_free(cctx);
1304     serverssl = clientssl = NULL;
1305     if (cfd != -1)
1306         close(cfd);
1307     if (sfd != -1)
1308         close(sfd);
1309     return testresult;
1310 }
1311 
1312 #define SENDFILE_SZ                     (16 * 4096)
1313 #define SENDFILE_CHUNK                  (4 * 4096)
1314 #define min(a,b)                        ((a) > (b) ? (b) : (a))
1315 
execute_test_ktls_sendfile(int tls_version,const char * cipher,int zerocopy)1316 static int execute_test_ktls_sendfile(int tls_version, const char *cipher,
1317                                       int zerocopy)
1318 {
1319     SSL_CTX *cctx = NULL, *sctx = NULL;
1320     SSL *clientssl = NULL, *serverssl = NULL;
1321     unsigned char *buf, *buf_dst;
1322     BIO *out = NULL, *in = NULL;
1323     int cfd = -1, sfd = -1, ffd, err;
1324     ssize_t chunk_size = 0;
1325     off_t chunk_off = 0;
1326     int testresult = 0;
1327     FILE *ffdp;
1328     SSL_CONNECTION *serversc;
1329 
1330     buf = OPENSSL_zalloc(SENDFILE_SZ);
1331     buf_dst = OPENSSL_zalloc(SENDFILE_SZ);
1332     if (!TEST_ptr(buf) || !TEST_ptr(buf_dst)
1333         || !TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1334         goto end;
1335 
1336     /* Skip this test if the platform does not support ktls */
1337     if (!ktls_chk_platform(sfd)) {
1338         testresult = TEST_skip("Kernel does not support KTLS");
1339         goto end;
1340     }
1341 
1342     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1343         testresult = TEST_skip("CHACHA is not supported in FIPS");
1344         goto end;
1345     }
1346 
1347     /* Create a session based on SHA-256 */
1348     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1349                                        TLS_client_method(),
1350                                        tls_version, tls_version,
1351                                        &sctx, &cctx, cert, privkey)))
1352         goto end;
1353 
1354     if (tls_version == TLS1_3_VERSION) {
1355         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1356             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1357             goto end;
1358     } else {
1359         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1360             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1361             goto end;
1362     }
1363 
1364     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1365                                        &clientssl, sfd, cfd)))
1366         goto end;
1367 
1368     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1369         goto end;
1370 
1371     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1372         goto end;
1373 
1374     if (zerocopy) {
1375         if (!TEST_true(SSL_set_options(serverssl,
1376                                        SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE)))
1377             goto end;
1378     }
1379 
1380     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1381                                          SSL_ERROR_NONE)))
1382         goto end;
1383 
1384     if (!BIO_get_ktls_send(serversc->wbio)) {
1385         testresult = TEST_skip("Failed to enable KTLS for %s cipher %s",
1386                                tls_version == TLS1_3_VERSION ? "TLS 1.3" :
1387                                "TLS 1.2", cipher);
1388         goto end;
1389     }
1390 
1391     if (!TEST_int_gt(RAND_bytes_ex(libctx, buf, SENDFILE_SZ, 0), 0))
1392         goto end;
1393 
1394     out = BIO_new_file(tmpfilename, "wb");
1395     if (!TEST_ptr(out))
1396         goto end;
1397 
1398     if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ)
1399         goto end;
1400 
1401     BIO_free(out);
1402     out = NULL;
1403     in = BIO_new_file(tmpfilename, "rb");
1404     BIO_get_fp(in, &ffdp);
1405     ffd = fileno(ffdp);
1406 
1407     while (chunk_off < SENDFILE_SZ) {
1408         chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off);
1409         while ((err = SSL_sendfile(serverssl,
1410                                    ffd,
1411                                    chunk_off,
1412                                    chunk_size,
1413                                    0)) != chunk_size) {
1414             if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE)
1415                 goto end;
1416         }
1417         while ((err = SSL_read(clientssl,
1418                                buf_dst + chunk_off,
1419                                chunk_size)) != chunk_size) {
1420             if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ)
1421                 goto end;
1422         }
1423 
1424         /* verify the payload */
1425         if (!TEST_mem_eq(buf_dst + chunk_off,
1426                          chunk_size,
1427                          buf + chunk_off,
1428                          chunk_size))
1429             goto end;
1430 
1431         chunk_off += chunk_size;
1432     }
1433 
1434     testresult = 1;
1435 end:
1436     if (clientssl) {
1437         SSL_shutdown(clientssl);
1438         SSL_free(clientssl);
1439     }
1440     if (serverssl) {
1441         SSL_shutdown(serverssl);
1442         SSL_free(serverssl);
1443     }
1444     SSL_CTX_free(sctx);
1445     SSL_CTX_free(cctx);
1446     serverssl = clientssl = NULL;
1447     BIO_free(out);
1448     BIO_free(in);
1449     if (cfd != -1)
1450         close(cfd);
1451     if (sfd != -1)
1452         close(sfd);
1453     OPENSSL_free(buf);
1454     OPENSSL_free(buf_dst);
1455     return testresult;
1456 }
1457 
1458 static struct ktls_test_cipher {
1459     int tls_version;
1460     const char *cipher;
1461 } ktls_test_ciphers[] = {
1462 # if !defined(OPENSSL_NO_TLS1_2)
1463 #  ifdef OPENSSL_KTLS_AES_GCM_128
1464     { TLS1_2_VERSION, "AES128-GCM-SHA256" },
1465 #  endif
1466 #  ifdef OPENSSL_KTLS_AES_CCM_128
1467     { TLS1_2_VERSION, "AES128-CCM"},
1468 #  endif
1469 #  ifdef OPENSSL_KTLS_AES_GCM_256
1470     { TLS1_2_VERSION, "AES256-GCM-SHA384"},
1471 #  endif
1472 #  ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1473 #    ifndef OPENSSL_NO_EC
1474     { TLS1_2_VERSION, "ECDHE-RSA-CHACHA20-POLY1305"},
1475 #    endif
1476 #  endif
1477 # endif
1478 # if !defined(OSSL_NO_USABLE_TLS1_3)
1479 #  ifdef OPENSSL_KTLS_AES_GCM_128
1480     { TLS1_3_VERSION, "TLS_AES_128_GCM_SHA256" },
1481 #  endif
1482 #  ifdef OPENSSL_KTLS_AES_CCM_128
1483     { TLS1_3_VERSION, "TLS_AES_128_CCM_SHA256" },
1484 #  endif
1485 #  ifdef OPENSSL_KTLS_AES_GCM_256
1486     { TLS1_3_VERSION, "TLS_AES_256_GCM_SHA384" },
1487 #  endif
1488 #  ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1489     { TLS1_3_VERSION, "TLS_CHACHA20_POLY1305_SHA256" },
1490 #  endif
1491 # endif
1492 };
1493 
1494 #define NUM_KTLS_TEST_CIPHERS OSSL_NELEM(ktls_test_ciphers)
1495 
test_ktls(int test)1496 static int test_ktls(int test)
1497 {
1498     struct ktls_test_cipher *cipher;
1499     int cis_ktls, sis_ktls;
1500 
1501     OPENSSL_assert(test / 4 < (int)NUM_KTLS_TEST_CIPHERS);
1502     cipher = &ktls_test_ciphers[test / 4];
1503 
1504     cis_ktls = (test & 1) != 0;
1505     sis_ktls = (test & 2) != 0;
1506 
1507     return execute_test_ktls(cis_ktls, sis_ktls, cipher->tls_version,
1508                              cipher->cipher);
1509 }
1510 
test_ktls_sendfile(int test)1511 static int test_ktls_sendfile(int test)
1512 {
1513     struct ktls_test_cipher *cipher;
1514     int tst = test >> 1;
1515 
1516     OPENSSL_assert(tst < (int)NUM_KTLS_TEST_CIPHERS);
1517     cipher = &ktls_test_ciphers[tst];
1518 
1519     return execute_test_ktls_sendfile(cipher->tls_version, cipher->cipher,
1520                                       test & 1);
1521 }
1522 #endif
1523 
test_large_message_tls(void)1524 static int test_large_message_tls(void)
1525 {
1526     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1527                                       TLS1_VERSION, 0, 0);
1528 }
1529 
test_large_message_tls_read_ahead(void)1530 static int test_large_message_tls_read_ahead(void)
1531 {
1532     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1533                                       TLS1_VERSION, 0, 1);
1534 }
1535 
1536 #ifndef OPENSSL_NO_DTLS
test_large_message_dtls(void)1537 static int test_large_message_dtls(void)
1538 {
1539 # ifdef OPENSSL_NO_DTLS1_2
1540     /* Not supported in the FIPS provider */
1541     if (is_fips)
1542         return 1;
1543 # endif
1544     /*
1545      * read_ahead is not relevant to DTLS because DTLS always acts as if
1546      * read_ahead is set.
1547      */
1548     return execute_test_large_message(DTLS_server_method(),
1549                                       DTLS_client_method(),
1550                                       DTLS1_VERSION, 0, 0);
1551 }
1552 #endif
1553 
1554 /*
1555  * Test we can successfully send the maximum amount of application data. We
1556  * test each protocol version individually, each with and without EtM enabled.
1557  * TLSv1.3 doesn't use EtM so technically it is redundant to test both but it is
1558  * simpler this way. We also test all combinations with and without the
1559  * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS option which affects the size of the
1560  * underlying buffer.
1561  */
test_large_app_data(int tst)1562 static int test_large_app_data(int tst)
1563 {
1564     SSL_CTX *cctx = NULL, *sctx = NULL;
1565     SSL *clientssl = NULL, *serverssl = NULL;
1566     int testresult = 0, prot;
1567     unsigned char *msg, *buf = NULL;
1568     size_t written, readbytes;
1569     const SSL_METHOD *smeth = TLS_server_method();
1570     const SSL_METHOD *cmeth = TLS_client_method();
1571 
1572     switch (tst >> 2) {
1573     case 0:
1574 #ifndef OSSL_NO_USABLE_TLS1_3
1575         prot = TLS1_3_VERSION;
1576         break;
1577 #else
1578         return TEST_skip("TLS 1.3 not supported");
1579 #endif
1580 
1581     case 1:
1582 #ifndef OPENSSL_NO_TLS1_2
1583         prot = TLS1_2_VERSION;
1584         break;
1585 #else
1586         return TEST_skip("TLS 1.2 not supported");
1587 #endif
1588 
1589     case 2:
1590 #ifndef OPENSSL_NO_TLS1_1
1591         prot = TLS1_1_VERSION;
1592         break;
1593 #else
1594         return TEST_skip("TLS 1.1 not supported");
1595 #endif
1596 
1597     case 3:
1598 #ifndef OPENSSL_NO_TLS1
1599         prot = TLS1_VERSION;
1600         break;
1601 #else
1602         return TEST_skip("TLS 1 not supported");
1603 #endif
1604 
1605     case 4:
1606 #ifndef OPENSSL_NO_SSL3
1607         prot = SSL3_VERSION;
1608         break;
1609 #else
1610         return TEST_skip("SSL 3 not supported");
1611 #endif
1612 
1613     case 5:
1614 #ifndef OPENSSL_NO_DTLS1_2
1615         prot = DTLS1_2_VERSION;
1616         smeth = DTLS_server_method();
1617         cmeth = DTLS_client_method();
1618         break;
1619 #else
1620         return TEST_skip("DTLS 1.2 not supported");
1621 #endif
1622 
1623     case 6:
1624 #ifndef OPENSSL_NO_DTLS1
1625         if (is_fips)
1626             return TEST_skip("DTLS 1 not supported by FIPS provider");
1627         prot = DTLS1_VERSION;
1628         smeth = DTLS_server_method();
1629         cmeth = DTLS_client_method();
1630         break;
1631 #else
1632         return TEST_skip("DTLS 1 not supported");
1633 #endif
1634 
1635     default:
1636         /* Shouldn't happen */
1637         return 0;
1638     }
1639 
1640     if (is_fips && prot < TLS1_2_VERSION)
1641         return TEST_skip("TLS versions < 1.2 not supported by FIPS provider");
1642 
1643     /* Maximal sized message of zeros */
1644     msg = OPENSSL_zalloc(SSL3_RT_MAX_PLAIN_LENGTH);
1645     if (!TEST_ptr(msg))
1646         goto end;
1647 
1648     buf = OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH + 1);
1649     if (!TEST_ptr(buf))
1650         goto end;
1651     /* Set whole buffer to all bits set */
1652     memset(buf, 0xff, SSL3_RT_MAX_PLAIN_LENGTH + 1);
1653 
1654     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, prot, prot,
1655                                        &sctx, &cctx, cert, privkey)))
1656         goto end;
1657 
1658     if (prot < TLS1_2_VERSION || prot == DTLS1_VERSION) {
1659         /* Older protocol versions need SECLEVEL=0 due to SHA1 usage */
1660         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0"))
1661                 || !TEST_true(SSL_CTX_set_cipher_list(sctx,
1662                                                       "DEFAULT:@SECLEVEL=0")))
1663         goto end;
1664     }
1665 
1666     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1667                                       &clientssl, NULL, NULL)))
1668         goto end;
1669 
1670     if ((tst & 1) != 0) {
1671         /* Setting this option gives us a minimally sized underlying buffer */
1672         if (!TEST_true(SSL_set_options(serverssl,
1673                                        SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
1674                 || !TEST_true(SSL_set_options(clientssl,
1675                                               SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)))
1676             goto end;
1677     }
1678 
1679     if ((tst & 2) != 0) {
1680         /*
1681          * Setting this option means the MAC is added before encryption
1682          * giving us a larger record for the encryption process
1683          */
1684         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC))
1685                 || !TEST_true(SSL_set_options(clientssl,
1686                                               SSL_OP_NO_ENCRYPT_THEN_MAC)))
1687             goto end;
1688     }
1689 
1690     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1691         goto end;
1692 
1693     if (!TEST_true(SSL_write_ex(clientssl, msg, SSL3_RT_MAX_PLAIN_LENGTH,
1694                                 &written))
1695             || !TEST_size_t_eq(written, SSL3_RT_MAX_PLAIN_LENGTH))
1696         goto end;
1697 
1698     /* We provide a buffer slightly larger than what we are actually expecting */
1699     if (!TEST_true(SSL_read_ex(serverssl, buf, SSL3_RT_MAX_PLAIN_LENGTH + 1,
1700                                &readbytes)))
1701         goto end;
1702 
1703     if (!TEST_mem_eq(msg, written, buf, readbytes))
1704         goto end;
1705 
1706     testresult = 1;
1707 end:
1708     OPENSSL_free(msg);
1709     OPENSSL_free(buf);
1710     SSL_free(serverssl);
1711     SSL_free(clientssl);
1712     SSL_CTX_free(sctx);
1713     SSL_CTX_free(cctx);
1714     return testresult;
1715 }
1716 
1717 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) \
1718     || !defined(OPENSSL_NO_DTLS)
execute_cleanse_plaintext(const SSL_METHOD * smeth,const SSL_METHOD * cmeth,int min_version,int max_version)1719 static int execute_cleanse_plaintext(const SSL_METHOD *smeth,
1720                                      const SSL_METHOD *cmeth,
1721                                      int min_version, int max_version)
1722 {
1723     size_t i;
1724     SSL_CTX *cctx = NULL, *sctx = NULL;
1725     SSL *clientssl = NULL, *serverssl = NULL;
1726     int testresult = 0;
1727     const unsigned char *zbuf;
1728     SSL_CONNECTION *serversc;
1729     TLS_RECORD *rr;
1730 
1731     static unsigned char cbuf[16000];
1732     static unsigned char sbuf[16000];
1733 
1734     if (!TEST_true(create_ssl_ctx_pair(libctx,
1735                                        smeth, cmeth,
1736                                        min_version, max_version,
1737                                        &sctx, &cctx, cert,
1738                                        privkey)))
1739         goto end;
1740 
1741 # ifdef OPENSSL_NO_DTLS1_2
1742     if (smeth == DTLS_server_method()) {
1743         /* Not supported in the FIPS provider */
1744         if (is_fips) {
1745             testresult = 1;
1746             goto end;
1747         };
1748         /*
1749          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
1750          * level 0
1751          */
1752         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
1753                 || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1754                                                     "DEFAULT:@SECLEVEL=0")))
1755             goto end;
1756     }
1757 # endif
1758 
1759     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1760                                       NULL, NULL)))
1761         goto end;
1762 
1763     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_CLEANSE_PLAINTEXT)))
1764         goto end;
1765 
1766     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1767                                          SSL_ERROR_NONE)))
1768         goto end;
1769 
1770     for (i = 0; i < sizeof(cbuf); i++) {
1771         cbuf[i] = i & 0xff;
1772     }
1773 
1774     if (!TEST_int_eq(SSL_write(clientssl, cbuf, sizeof(cbuf)), sizeof(cbuf)))
1775         goto end;
1776 
1777     if (!TEST_int_eq(SSL_peek(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1778         goto end;
1779 
1780     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1781         goto end;
1782 
1783     /*
1784      * Since we called SSL_peek(), we know the data in the record
1785      * layer is a plaintext record. We can gather the pointer to check
1786      * for zeroization after SSL_read().
1787      */
1788     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1789         goto end;
1790     rr = serversc->rlayer.tlsrecs;
1791 
1792     zbuf = &rr->data[rr->off];
1793     if (!TEST_int_eq(rr->length, sizeof(cbuf)))
1794         goto end;
1795 
1796     /*
1797      * After SSL_peek() the plaintext must still be stored in the
1798      * record.
1799      */
1800     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1801         goto end;
1802 
1803     memset(sbuf, 0, sizeof(sbuf));
1804     if (!TEST_int_eq(SSL_read(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1805         goto end;
1806 
1807     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(cbuf)))
1808         goto end;
1809 
1810     /* Check if rbuf is cleansed */
1811     memset(cbuf, 0, sizeof(cbuf));
1812     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1813         goto end;
1814 
1815     testresult = 1;
1816  end:
1817     SSL_free(serverssl);
1818     SSL_free(clientssl);
1819     SSL_CTX_free(sctx);
1820     SSL_CTX_free(cctx);
1821 
1822     return testresult;
1823 }
1824 #endif /*
1825         * !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
1826         * || !defined(OPENSSL_NO_DTLS)
1827         */
1828 
test_cleanse_plaintext(void)1829 static int test_cleanse_plaintext(void)
1830 {
1831 #if !defined(OPENSSL_NO_TLS1_2)
1832     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1833                                              TLS_client_method(),
1834                                              TLS1_2_VERSION,
1835                                              TLS1_2_VERSION)))
1836         return 0;
1837 
1838 #endif
1839 
1840 #if !defined(OSSL_NO_USABLE_TLS1_3)
1841     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1842                                              TLS_client_method(),
1843                                              TLS1_3_VERSION,
1844                                              TLS1_3_VERSION)))
1845         return 0;
1846 #endif
1847 
1848 #if !defined(OPENSSL_NO_DTLS)
1849 
1850     if (!TEST_true(execute_cleanse_plaintext(DTLS_server_method(),
1851                                              DTLS_client_method(),
1852                                              DTLS1_VERSION,
1853                                              0)))
1854         return 0;
1855 #endif
1856     return 1;
1857 }
1858 
1859 #ifndef OPENSSL_NO_OCSP
ocsp_server_cb(SSL * s,void * arg)1860 static int ocsp_server_cb(SSL *s, void *arg)
1861 {
1862     int *argi = (int *)arg;
1863     unsigned char *copy = NULL;
1864     STACK_OF(OCSP_RESPID) *ids = NULL;
1865     OCSP_RESPID *id = NULL;
1866 
1867     if (*argi == 2) {
1868         /* In this test we are expecting exactly 1 OCSP_RESPID */
1869         SSL_get_tlsext_status_ids(s, &ids);
1870         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
1871             return SSL_TLSEXT_ERR_ALERT_FATAL;
1872 
1873         id = sk_OCSP_RESPID_value(ids, 0);
1874         if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL))
1875             return SSL_TLSEXT_ERR_ALERT_FATAL;
1876     } else if (*argi != 1) {
1877         return SSL_TLSEXT_ERR_ALERT_FATAL;
1878     }
1879 
1880     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
1881         return SSL_TLSEXT_ERR_ALERT_FATAL;
1882 
1883     if (!TEST_true(SSL_set_tlsext_status_ocsp_resp(s, copy,
1884                                                    sizeof(orespder)))) {
1885         OPENSSL_free(copy);
1886         return SSL_TLSEXT_ERR_ALERT_FATAL;
1887     }
1888     ocsp_server_called = 1;
1889     return SSL_TLSEXT_ERR_OK;
1890 }
1891 
ocsp_client_cb(SSL * s,void * arg)1892 static int ocsp_client_cb(SSL *s, void *arg)
1893 {
1894     int *argi = (int *)arg;
1895     const unsigned char *respderin;
1896     size_t len;
1897 
1898     if (*argi != 1 && *argi != 2)
1899         return 0;
1900 
1901     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
1902     if (!TEST_mem_eq(orespder, len, respderin, len))
1903         return 0;
1904 
1905     ocsp_client_called = 1;
1906     return 1;
1907 }
1908 
test_tlsext_status_type(void)1909 static int test_tlsext_status_type(void)
1910 {
1911     SSL_CTX *cctx = NULL, *sctx = NULL;
1912     SSL *clientssl = NULL, *serverssl = NULL;
1913     int testresult = 0;
1914     STACK_OF(OCSP_RESPID) *ids = NULL;
1915     OCSP_RESPID *id = NULL;
1916     BIO *certbio = NULL;
1917 
1918     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
1919                              TLS1_VERSION, 0,
1920                              &sctx, &cctx, cert, privkey))
1921         return 0;
1922 
1923     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
1924         goto end;
1925 
1926     /* First just do various checks getting and setting tlsext_status_type */
1927 
1928     clientssl = SSL_new(cctx);
1929     if (!TEST_ptr(clientssl))
1930         goto end;
1931     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
1932             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
1933                                                       TLSEXT_STATUSTYPE_ocsp))
1934             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
1935                             TLSEXT_STATUSTYPE_ocsp))
1936         goto end;
1937 
1938     SSL_free(clientssl);
1939     clientssl = NULL;
1940 
1941     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
1942      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
1943         goto end;
1944 
1945     clientssl = SSL_new(cctx);
1946     if (!TEST_ptr(clientssl))
1947         goto end;
1948     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
1949         goto end;
1950     SSL_free(clientssl);
1951     clientssl = NULL;
1952 
1953     /*
1954      * Now actually do a handshake and check OCSP information is exchanged and
1955      * the callbacks get called
1956      */
1957     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
1958     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
1959     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
1960     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
1961     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1962                                       &clientssl, NULL, NULL))
1963             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1964                                                 SSL_ERROR_NONE))
1965             || !TEST_true(ocsp_client_called)
1966             || !TEST_true(ocsp_server_called))
1967         goto end;
1968     SSL_free(serverssl);
1969     SSL_free(clientssl);
1970     serverssl = NULL;
1971     clientssl = NULL;
1972 
1973     /* Try again but this time force the server side callback to fail */
1974     ocsp_client_called = 0;
1975     ocsp_server_called = 0;
1976     cdummyarg = 0;
1977     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1978                                       &clientssl, NULL, NULL))
1979                 /* This should fail because the callback will fail */
1980             || !TEST_false(create_ssl_connection(serverssl, clientssl,
1981                                                  SSL_ERROR_NONE))
1982             || !TEST_false(ocsp_client_called)
1983             || !TEST_false(ocsp_server_called))
1984         goto end;
1985     SSL_free(serverssl);
1986     SSL_free(clientssl);
1987     serverssl = NULL;
1988     clientssl = NULL;
1989 
1990     /*
1991      * This time we'll get the client to send an OCSP_RESPID that it will
1992      * accept.
1993      */
1994     ocsp_client_called = 0;
1995     ocsp_server_called = 0;
1996     cdummyarg = 2;
1997     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1998                                       &clientssl, NULL, NULL)))
1999         goto end;
2000 
2001     /*
2002      * We'll just use any old cert for this test - it doesn't have to be an OCSP
2003      * specific one. We'll use the server cert.
2004      */
2005     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
2006             || !TEST_ptr(id = OCSP_RESPID_new())
2007             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
2008             || !TEST_ptr(ocspcert = X509_new_ex(libctx, NULL))
2009             || !TEST_ptr(PEM_read_bio_X509(certbio, &ocspcert, NULL, NULL))
2010             || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL))
2011             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
2012         goto end;
2013     id = NULL;
2014     SSL_set_tlsext_status_ids(clientssl, ids);
2015     /* Control has been transferred */
2016     ids = NULL;
2017 
2018     BIO_free(certbio);
2019     certbio = NULL;
2020 
2021     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2022                                          SSL_ERROR_NONE))
2023             || !TEST_true(ocsp_client_called)
2024             || !TEST_true(ocsp_server_called))
2025         goto end;
2026 
2027     testresult = 1;
2028 
2029  end:
2030     SSL_free(serverssl);
2031     SSL_free(clientssl);
2032     SSL_CTX_free(sctx);
2033     SSL_CTX_free(cctx);
2034     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
2035     OCSP_RESPID_free(id);
2036     BIO_free(certbio);
2037     X509_free(ocspcert);
2038     ocspcert = NULL;
2039 
2040     return testresult;
2041 }
2042 #endif
2043 
2044 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
2045 static int new_called, remove_called, get_called;
2046 
new_session_cb(SSL * ssl,SSL_SESSION * sess)2047 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
2048 {
2049     new_called++;
2050     /*
2051      * sess has been up-refed for us, but we don't actually need it so free it
2052      * immediately.
2053      */
2054     SSL_SESSION_free(sess);
2055     return 1;
2056 }
2057 
remove_session_cb(SSL_CTX * ctx,SSL_SESSION * sess)2058 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
2059 {
2060     remove_called++;
2061 }
2062 
2063 static SSL_SESSION *get_sess_val = NULL;
2064 
get_session_cb(SSL * ssl,const unsigned char * id,int len,int * copy)2065 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
2066                                    int *copy)
2067 {
2068     get_called++;
2069     *copy = 1;
2070     return get_sess_val;
2071 }
2072 
execute_test_session(int maxprot,int use_int_cache,int use_ext_cache,long s_options)2073 static int execute_test_session(int maxprot, int use_int_cache,
2074                                 int use_ext_cache, long s_options)
2075 {
2076     SSL_CTX *sctx = NULL, *cctx = NULL;
2077     SSL *serverssl1 = NULL, *clientssl1 = NULL;
2078     SSL *serverssl2 = NULL, *clientssl2 = NULL;
2079 # ifndef OPENSSL_NO_TLS1_1
2080     SSL *serverssl3 = NULL, *clientssl3 = NULL;
2081 # endif
2082     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
2083     int testresult = 0, numnewsesstick = 1;
2084 
2085     new_called = remove_called = 0;
2086 
2087     /* TLSv1.3 sends 2 NewSessionTickets */
2088     if (maxprot == TLS1_3_VERSION)
2089         numnewsesstick = 2;
2090 
2091     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2092                                        TLS_client_method(), TLS1_VERSION, 0,
2093                                        &sctx, &cctx, cert, privkey)))
2094         return 0;
2095 
2096     /*
2097      * Only allow the max protocol version so we can force a connection failure
2098      * later
2099      */
2100     SSL_CTX_set_min_proto_version(cctx, maxprot);
2101     SSL_CTX_set_max_proto_version(cctx, maxprot);
2102 
2103     /* Set up session cache */
2104     if (use_ext_cache) {
2105         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2106         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
2107     }
2108     if (use_int_cache) {
2109         /* Also covers instance where both are set */
2110         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
2111     } else {
2112         SSL_CTX_set_session_cache_mode(cctx,
2113                                        SSL_SESS_CACHE_CLIENT
2114                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2115     }
2116 
2117     if (s_options) {
2118         SSL_CTX_set_options(sctx, s_options);
2119     }
2120 
2121     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2122                                       NULL, NULL))
2123             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2124                                                 SSL_ERROR_NONE))
2125             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
2126         goto end;
2127 
2128     /* Should fail because it should already be in the cache */
2129     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
2130         goto end;
2131     if (use_ext_cache
2132             && (!TEST_int_eq(new_called, numnewsesstick)
2133 
2134                 || !TEST_int_eq(remove_called, 0)))
2135         goto end;
2136 
2137     new_called = remove_called = 0;
2138     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2139                                       &clientssl2, NULL, NULL))
2140             || !TEST_true(SSL_set_session(clientssl2, sess1))
2141             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2142                                                 SSL_ERROR_NONE))
2143             || !TEST_true(SSL_session_reused(clientssl2)))
2144         goto end;
2145 
2146     if (maxprot == TLS1_3_VERSION) {
2147         /*
2148          * In TLSv1.3 we should have created a new session even though we have
2149          * resumed. Since we attempted a resume we should also have removed the
2150          * old ticket from the cache so that we try to only use tickets once.
2151          */
2152         if (use_ext_cache
2153                 && (!TEST_int_eq(new_called, 1)
2154                     || !TEST_int_eq(remove_called, 1)))
2155             goto end;
2156     } else {
2157         /*
2158          * In TLSv1.2 we expect to have resumed so no sessions added or
2159          * removed.
2160          */
2161         if (use_ext_cache
2162                 && (!TEST_int_eq(new_called, 0)
2163                     || !TEST_int_eq(remove_called, 0)))
2164             goto end;
2165     }
2166 
2167     SSL_SESSION_free(sess1);
2168     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
2169         goto end;
2170     shutdown_ssl_connection(serverssl2, clientssl2);
2171     serverssl2 = clientssl2 = NULL;
2172 
2173     new_called = remove_called = 0;
2174     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2175                                       &clientssl2, NULL, NULL))
2176             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2177                                                 SSL_ERROR_NONE)))
2178         goto end;
2179 
2180     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
2181         goto end;
2182 
2183     if (use_ext_cache
2184             && (!TEST_int_eq(new_called, numnewsesstick)
2185                 || !TEST_int_eq(remove_called, 0)))
2186         goto end;
2187 
2188     new_called = remove_called = 0;
2189     /*
2190      * This should clear sess2 from the cache because it is a "bad" session.
2191      * See SSL_set_session() documentation.
2192      */
2193     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
2194         goto end;
2195     if (use_ext_cache
2196             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2197         goto end;
2198     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
2199         goto end;
2200 
2201     if (use_int_cache) {
2202         /* Should succeeded because it should not already be in the cache */
2203         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
2204                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
2205             goto end;
2206     }
2207 
2208     new_called = remove_called = 0;
2209     /* This shouldn't be in the cache so should fail */
2210     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
2211         goto end;
2212 
2213     if (use_ext_cache
2214             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2215         goto end;
2216 
2217 # if !defined(OPENSSL_NO_TLS1_1)
2218     new_called = remove_called = 0;
2219     /* Force a connection failure */
2220     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
2221     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
2222                                       &clientssl3, NULL, NULL))
2223             || !TEST_true(SSL_set_session(clientssl3, sess1))
2224             /* This should fail because of the mismatched protocol versions */
2225             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
2226                                                  SSL_ERROR_NONE)))
2227         goto end;
2228 
2229     /* We should have automatically removed the session from the cache */
2230     if (use_ext_cache
2231             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2232         goto end;
2233 
2234     /* Should succeed because it should not already be in the cache */
2235     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
2236         goto end;
2237 # endif
2238 
2239     /* Now do some tests for server side caching */
2240     if (use_ext_cache) {
2241         SSL_CTX_sess_set_new_cb(cctx, NULL);
2242         SSL_CTX_sess_set_remove_cb(cctx, NULL);
2243         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2244         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
2245         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
2246         get_sess_val = NULL;
2247     }
2248 
2249     SSL_CTX_set_session_cache_mode(cctx, 0);
2250     /* Internal caching is the default on the server side */
2251     if (!use_int_cache)
2252         SSL_CTX_set_session_cache_mode(sctx,
2253                                        SSL_SESS_CACHE_SERVER
2254                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2255 
2256     SSL_free(serverssl1);
2257     SSL_free(clientssl1);
2258     serverssl1 = clientssl1 = NULL;
2259     SSL_free(serverssl2);
2260     SSL_free(clientssl2);
2261     serverssl2 = clientssl2 = NULL;
2262     SSL_SESSION_free(sess1);
2263     sess1 = NULL;
2264     SSL_SESSION_free(sess2);
2265     sess2 = NULL;
2266 
2267     SSL_CTX_set_max_proto_version(sctx, maxprot);
2268     if (maxprot == TLS1_2_VERSION)
2269         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
2270     new_called = remove_called = get_called = 0;
2271     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2272                                       NULL, NULL))
2273             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2274                                                 SSL_ERROR_NONE))
2275             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
2276             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
2277         goto end;
2278 
2279     if (use_int_cache) {
2280         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
2281             /*
2282              * In TLSv1.3 it should not have been added to the internal cache,
2283              * except in the case where we also have an external cache (in that
2284              * case it gets added to the cache in order to generate remove
2285              * events after timeout).
2286              */
2287             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
2288                 goto end;
2289         } else {
2290             /* Should fail because it should already be in the cache */
2291             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
2292                 goto end;
2293         }
2294     }
2295 
2296     if (use_ext_cache) {
2297         SSL_SESSION *tmp = sess2;
2298 
2299         if (!TEST_int_eq(new_called, numnewsesstick)
2300                 || !TEST_int_eq(remove_called, 0)
2301                 || !TEST_int_eq(get_called, 0))
2302             goto end;
2303         /*
2304          * Delete the session from the internal cache to force a lookup from
2305          * the external cache. We take a copy first because
2306          * SSL_CTX_remove_session() also marks the session as non-resumable.
2307          */
2308         if (use_int_cache && maxprot != TLS1_3_VERSION) {
2309             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
2310                 || !TEST_true(sess2->owner != NULL)
2311                 || !TEST_true(tmp->owner == NULL)
2312                 || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
2313                 goto end;
2314             SSL_SESSION_free(sess2);
2315         }
2316         sess2 = tmp;
2317     }
2318 
2319     new_called = remove_called = get_called = 0;
2320     get_sess_val = sess2;
2321     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2322                                       &clientssl2, NULL, NULL))
2323             || !TEST_true(SSL_set_session(clientssl2, sess1))
2324             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2325                                                 SSL_ERROR_NONE))
2326             || !TEST_true(SSL_session_reused(clientssl2)))
2327         goto end;
2328 
2329     if (use_ext_cache) {
2330         if (!TEST_int_eq(remove_called, 0))
2331             goto end;
2332 
2333         if (maxprot == TLS1_3_VERSION) {
2334             if (!TEST_int_eq(new_called, 1)
2335                     || !TEST_int_eq(get_called, 0))
2336                 goto end;
2337         } else {
2338             if (!TEST_int_eq(new_called, 0)
2339                     || !TEST_int_eq(get_called, 1))
2340                 goto end;
2341         }
2342     }
2343     /*
2344      * Make a small cache, force out all other sessions but
2345      * sess2, try to add sess1, which should succeed. Then
2346      * make sure it's there by checking the owners. Despite
2347      * the timeouts, sess1 should have kicked out sess2
2348      */
2349 
2350     /* Make sess1 expire before sess2 */
2351     if (!TEST_time_t_gt(SSL_SESSION_set_time_ex(sess1, 1000), 0)
2352             || !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0)
2353             || !TEST_time_t_gt(SSL_SESSION_set_time_ex(sess2, 2000), 0)
2354             || !TEST_long_gt(SSL_SESSION_set_timeout(sess2, 2000), 0))
2355         goto end;
2356 
2357     if (!TEST_long_ne(SSL_CTX_sess_set_cache_size(sctx, 1), 0))
2358         goto end;
2359 
2360     /* Don't care about results - cache should only be sess2 at end */
2361     SSL_CTX_add_session(sctx, sess1);
2362     SSL_CTX_add_session(sctx, sess2);
2363 
2364     /* Now add sess1, and make sure it remains, despite timeout */
2365     if (!TEST_true(SSL_CTX_add_session(sctx, sess1))
2366             || !TEST_ptr(sess1->owner)
2367             || !TEST_ptr_null(sess2->owner))
2368         goto end;
2369 
2370     testresult = 1;
2371 
2372  end:
2373     SSL_free(serverssl1);
2374     SSL_free(clientssl1);
2375     SSL_free(serverssl2);
2376     SSL_free(clientssl2);
2377 # ifndef OPENSSL_NO_TLS1_1
2378     SSL_free(serverssl3);
2379     SSL_free(clientssl3);
2380 # endif
2381     SSL_SESSION_free(sess1);
2382     SSL_SESSION_free(sess2);
2383     SSL_CTX_free(sctx);
2384     SSL_CTX_free(cctx);
2385 
2386     return testresult;
2387 }
2388 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
2389 
test_session_with_only_int_cache(void)2390 static int test_session_with_only_int_cache(void)
2391 {
2392 #ifndef OSSL_NO_USABLE_TLS1_3
2393     if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0))
2394         return 0;
2395 #endif
2396 
2397 #ifndef OPENSSL_NO_TLS1_2
2398     return execute_test_session(TLS1_2_VERSION, 1, 0, 0);
2399 #else
2400     return 1;
2401 #endif
2402 }
2403 
test_session_with_only_ext_cache(void)2404 static int test_session_with_only_ext_cache(void)
2405 {
2406 #ifndef OSSL_NO_USABLE_TLS1_3
2407     if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0))
2408         return 0;
2409 #endif
2410 
2411 #ifndef OPENSSL_NO_TLS1_2
2412     return execute_test_session(TLS1_2_VERSION, 0, 1, 0);
2413 #else
2414     return 1;
2415 #endif
2416 }
2417 
test_session_with_both_cache(void)2418 static int test_session_with_both_cache(void)
2419 {
2420 #ifndef OSSL_NO_USABLE_TLS1_3
2421     if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0))
2422         return 0;
2423 #endif
2424 
2425 #ifndef OPENSSL_NO_TLS1_2
2426     return execute_test_session(TLS1_2_VERSION, 1, 1, 0);
2427 #else
2428     return 1;
2429 #endif
2430 }
2431 
test_session_wo_ca_names(void)2432 static int test_session_wo_ca_names(void)
2433 {
2434 #ifndef OSSL_NO_USABLE_TLS1_3
2435     if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES))
2436         return 0;
2437 #endif
2438 
2439 #ifndef OPENSSL_NO_TLS1_2
2440     return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
2441 #else
2442     return 1;
2443 #endif
2444 }
2445 
2446 #ifndef OSSL_NO_USABLE_TLS1_3
2447 static SSL_SESSION *sesscache[6];
2448 static int do_cache;
2449 
new_cachesession_cb(SSL * ssl,SSL_SESSION * sess)2450 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
2451 {
2452     if (do_cache) {
2453         sesscache[new_called] = sess;
2454     } else {
2455         /* We don't need the reference to the session, so free it */
2456         SSL_SESSION_free(sess);
2457     }
2458     new_called++;
2459 
2460     return 1;
2461 }
2462 
post_handshake_verify(SSL * sssl,SSL * cssl)2463 static int post_handshake_verify(SSL *sssl, SSL *cssl)
2464 {
2465     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
2466     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
2467         return 0;
2468 
2469     /* Start handshake on the server and client */
2470     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
2471             || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
2472             || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
2473             || !TEST_true(create_ssl_connection(sssl, cssl,
2474                                                 SSL_ERROR_NONE)))
2475         return 0;
2476 
2477     return 1;
2478 }
2479 
setup_ticket_test(int stateful,int idx,SSL_CTX ** sctx,SSL_CTX ** cctx)2480 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
2481                              SSL_CTX **cctx)
2482 {
2483     int sess_id_ctx = 1;
2484 
2485     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2486                                        TLS_client_method(), TLS1_VERSION, 0,
2487                                        sctx, cctx, cert, privkey))
2488             || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
2489             || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
2490                                                          (void *)&sess_id_ctx,
2491                                                          sizeof(sess_id_ctx))))
2492         return 0;
2493 
2494     if (stateful)
2495         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
2496 
2497     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT
2498                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2499     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
2500 
2501     return 1;
2502 }
2503 
check_resumption(int idx,SSL_CTX * sctx,SSL_CTX * cctx,int succ)2504 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
2505 {
2506     SSL *serverssl = NULL, *clientssl = NULL;
2507     int i;
2508 
2509     /* Test that we can resume with all the tickets we got given */
2510     for (i = 0; i < idx * 2; i++) {
2511         new_called = 0;
2512         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2513                                               &clientssl, NULL, NULL))
2514                 || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
2515             goto end;
2516 
2517         SSL_set_post_handshake_auth(clientssl, 1);
2518 
2519         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2520                                                     SSL_ERROR_NONE)))
2521             goto end;
2522 
2523         /*
2524          * Following a successful resumption we only get 1 ticket. After a
2525          * failed one we should get idx tickets.
2526          */
2527         if (succ) {
2528             if (!TEST_true(SSL_session_reused(clientssl))
2529                     || !TEST_int_eq(new_called, 1))
2530                 goto end;
2531         } else {
2532             if (!TEST_false(SSL_session_reused(clientssl))
2533                     || !TEST_int_eq(new_called, idx))
2534                 goto end;
2535         }
2536 
2537         new_called = 0;
2538         /* After a post-handshake authentication we should get 1 new ticket */
2539         if (succ
2540                 && (!post_handshake_verify(serverssl, clientssl)
2541                     || !TEST_int_eq(new_called, 1)))
2542             goto end;
2543 
2544         SSL_shutdown(clientssl);
2545         SSL_shutdown(serverssl);
2546         SSL_free(serverssl);
2547         SSL_free(clientssl);
2548         serverssl = clientssl = NULL;
2549         SSL_SESSION_free(sesscache[i]);
2550         sesscache[i] = NULL;
2551     }
2552 
2553     return 1;
2554 
2555  end:
2556     SSL_free(clientssl);
2557     SSL_free(serverssl);
2558     return 0;
2559 }
2560 
test_tickets(int stateful,int idx)2561 static int test_tickets(int stateful, int idx)
2562 {
2563     SSL_CTX *sctx = NULL, *cctx = NULL;
2564     SSL *serverssl = NULL, *clientssl = NULL;
2565     int testresult = 0;
2566     size_t j;
2567 
2568     /* idx is the test number, but also the number of tickets we want */
2569 
2570     new_called = 0;
2571     do_cache = 1;
2572 
2573     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2574         goto end;
2575 
2576     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2577                                           &clientssl, NULL, NULL)))
2578         goto end;
2579 
2580     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2581                                                 SSL_ERROR_NONE))
2582                /* Check we got the number of tickets we were expecting */
2583             || !TEST_int_eq(idx, new_called))
2584         goto end;
2585 
2586     SSL_shutdown(clientssl);
2587     SSL_shutdown(serverssl);
2588     SSL_free(serverssl);
2589     SSL_free(clientssl);
2590     SSL_CTX_free(sctx);
2591     SSL_CTX_free(cctx);
2592     clientssl = serverssl = NULL;
2593     sctx = cctx = NULL;
2594 
2595     /*
2596      * Now we try to resume with the tickets we previously created. The
2597      * resumption attempt is expected to fail (because we're now using a new
2598      * SSL_CTX). We should see idx number of tickets issued again.
2599      */
2600 
2601     /* Stop caching sessions - just count them */
2602     do_cache = 0;
2603 
2604     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2605         goto end;
2606 
2607     if (!check_resumption(idx, sctx, cctx, 0))
2608         goto end;
2609 
2610     /* Start again with caching sessions */
2611     new_called = 0;
2612     do_cache = 1;
2613     SSL_CTX_free(sctx);
2614     SSL_CTX_free(cctx);
2615     sctx = cctx = NULL;
2616 
2617     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2618         goto end;
2619 
2620     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2621                                           &clientssl, NULL, NULL)))
2622         goto end;
2623 
2624     SSL_set_post_handshake_auth(clientssl, 1);
2625 
2626     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2627                                                 SSL_ERROR_NONE))
2628                /* Check we got the number of tickets we were expecting */
2629             || !TEST_int_eq(idx, new_called))
2630         goto end;
2631 
2632     /* After a post-handshake authentication we should get new tickets issued */
2633     if (!post_handshake_verify(serverssl, clientssl)
2634             || !TEST_int_eq(idx * 2, new_called))
2635         goto end;
2636 
2637     SSL_shutdown(clientssl);
2638     SSL_shutdown(serverssl);
2639     SSL_free(serverssl);
2640     SSL_free(clientssl);
2641     serverssl = clientssl = NULL;
2642 
2643     /* Stop caching sessions - just count them */
2644     do_cache = 0;
2645 
2646     /*
2647      * Check we can resume with all the tickets we created. This time around the
2648      * resumptions should all be successful.
2649      */
2650     if (!check_resumption(idx, sctx, cctx, 1))
2651         goto end;
2652 
2653     testresult = 1;
2654 
2655  end:
2656     SSL_free(serverssl);
2657     SSL_free(clientssl);
2658     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2659         SSL_SESSION_free(sesscache[j]);
2660         sesscache[j] = NULL;
2661     }
2662     SSL_CTX_free(sctx);
2663     SSL_CTX_free(cctx);
2664 
2665     return testresult;
2666 }
2667 
test_stateless_tickets(int idx)2668 static int test_stateless_tickets(int idx)
2669 {
2670     return test_tickets(0, idx);
2671 }
2672 
test_stateful_tickets(int idx)2673 static int test_stateful_tickets(int idx)
2674 {
2675     return test_tickets(1, idx);
2676 }
2677 
test_psk_tickets(void)2678 static int test_psk_tickets(void)
2679 {
2680     SSL_CTX *sctx = NULL, *cctx = NULL;
2681     SSL *serverssl = NULL, *clientssl = NULL;
2682     int testresult = 0;
2683     int sess_id_ctx = 1;
2684 
2685     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2686                                        TLS_client_method(), TLS1_VERSION, 0,
2687                                        &sctx, &cctx, NULL, NULL))
2688             || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2689                                                          (void *)&sess_id_ctx,
2690                                                          sizeof(sess_id_ctx))))
2691         goto end;
2692 
2693     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
2694                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2695     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2696     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2697     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2698     use_session_cb_cnt = 0;
2699     find_session_cb_cnt = 0;
2700     srvid = pskid;
2701     new_called = 0;
2702 
2703     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2704                                       NULL, NULL)))
2705         goto end;
2706     clientpsk = serverpsk = create_a_psk(clientssl, SHA384_DIGEST_LENGTH);
2707     if (!TEST_ptr(clientpsk) || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
2708         goto end;
2709 
2710     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2711                                                 SSL_ERROR_NONE))
2712             || !TEST_int_eq(1, find_session_cb_cnt)
2713             || !TEST_int_eq(1, use_session_cb_cnt)
2714                /* We should always get 1 ticket when using external PSK */
2715             || !TEST_int_eq(1, new_called))
2716         goto end;
2717 
2718     testresult = 1;
2719 
2720  end:
2721     SSL_free(serverssl);
2722     SSL_free(clientssl);
2723     SSL_CTX_free(sctx);
2724     SSL_CTX_free(cctx);
2725     SSL_SESSION_free(clientpsk);
2726     SSL_SESSION_free(serverpsk);
2727     clientpsk = serverpsk = NULL;
2728 
2729     return testresult;
2730 }
2731 
test_extra_tickets(int idx)2732 static int test_extra_tickets(int idx)
2733 {
2734     SSL_CTX *sctx = NULL, *cctx = NULL;
2735     SSL *serverssl = NULL, *clientssl = NULL;
2736     BIO *bretry = BIO_new(bio_s_always_retry());
2737     BIO *tmp = NULL;
2738     int testresult = 0;
2739     int stateful = 0;
2740     size_t nbytes;
2741     unsigned char c, buf[1];
2742 
2743     new_called = 0;
2744     do_cache = 1;
2745 
2746     if (idx >= 3) {
2747         idx -= 3;
2748         stateful = 1;
2749     }
2750 
2751     if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2752         goto end;
2753     SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2754     /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2755     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2756 
2757     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2758                                           &clientssl, NULL, NULL)))
2759         goto end;
2760 
2761     /*
2762      * Note that we have new_session_cb on both sctx and cctx, so new_called is
2763      * incremented by both client and server.
2764      */
2765     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2766                                                 SSL_ERROR_NONE))
2767                /* Check we got the number of tickets we were expecting */
2768             || !TEST_int_eq(idx * 2, new_called)
2769             || !TEST_true(SSL_new_session_ticket(serverssl))
2770             || !TEST_true(SSL_new_session_ticket(serverssl))
2771             || !TEST_int_eq(idx * 2, new_called))
2772         goto end;
2773 
2774     /* Now try a (real) write to actually send the tickets */
2775     c = '1';
2776     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2777             || !TEST_size_t_eq(1, nbytes)
2778             || !TEST_int_eq(idx * 2 + 2, new_called)
2779             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2780             || !TEST_int_eq(idx * 2 + 4, new_called)
2781             || !TEST_int_eq(sizeof(buf), nbytes)
2782             || !TEST_int_eq(c, buf[0])
2783             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2784         goto end;
2785 
2786     /* Try with only requesting one new ticket, too */
2787     c = '2';
2788     new_called = 0;
2789     if (!TEST_true(SSL_new_session_ticket(serverssl))
2790             || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2791             || !TEST_size_t_eq(sizeof(c), nbytes)
2792             || !TEST_int_eq(1, new_called)
2793             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2794             || !TEST_int_eq(2, new_called)
2795             || !TEST_size_t_eq(sizeof(buf), nbytes)
2796             || !TEST_int_eq(c, buf[0]))
2797         goto end;
2798 
2799     /* Do it again but use dummy writes to drive the ticket generation */
2800     c = '3';
2801     new_called = 0;
2802     if (!TEST_true(SSL_new_session_ticket(serverssl))
2803             || !TEST_true(SSL_new_session_ticket(serverssl))
2804             || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2805             || !TEST_size_t_eq(0, nbytes)
2806             || !TEST_int_eq(2, new_called)
2807             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2808             || !TEST_int_eq(4, new_called))
2809         goto end;
2810 
2811     /* Once more, but with SSL_do_handshake() to drive the ticket generation */
2812     c = '4';
2813     new_called = 0;
2814     if (!TEST_true(SSL_new_session_ticket(serverssl))
2815             || !TEST_true(SSL_new_session_ticket(serverssl))
2816             || !TEST_true(SSL_do_handshake(serverssl))
2817             || !TEST_int_eq(2, new_called)
2818             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2819             || !TEST_int_eq(4, new_called))
2820         goto end;
2821 
2822     /*
2823      * Use the always-retry BIO to exercise the logic that forces ticket
2824      * generation to wait until a record boundary.
2825      */
2826     c = '5';
2827     new_called = 0;
2828     tmp = SSL_get_wbio(serverssl);
2829     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2830         tmp = NULL;
2831         goto end;
2832     }
2833     SSL_set0_wbio(serverssl, bretry);
2834     bretry = NULL;
2835     if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2836             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2837             || !TEST_size_t_eq(nbytes, 0))
2838         goto end;
2839     /* Restore a BIO that will let the write succeed */
2840     SSL_set0_wbio(serverssl, tmp);
2841     tmp = NULL;
2842     /*
2843      * These calls should just queue the request and not send anything
2844      * even if we explicitly try to hit the state machine.
2845      */
2846     if (!TEST_true(SSL_new_session_ticket(serverssl))
2847             || !TEST_true(SSL_new_session_ticket(serverssl))
2848             || !TEST_int_eq(0, new_called)
2849             || !TEST_true(SSL_do_handshake(serverssl))
2850             || !TEST_int_eq(0, new_called))
2851         goto end;
2852     /* Re-do the write; still no tickets sent */
2853     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2854             || !TEST_size_t_eq(1, nbytes)
2855             || !TEST_int_eq(0, new_called)
2856             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2857             || !TEST_int_eq(0, new_called)
2858             || !TEST_int_eq(sizeof(buf), nbytes)
2859             || !TEST_int_eq(c, buf[0])
2860             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2861         goto end;
2862     /* Even trying to hit the state machine now will still not send tickets */
2863     if (!TEST_true(SSL_do_handshake(serverssl))
2864             || !TEST_int_eq(0, new_called))
2865         goto end;
2866     /* Now the *next* write should send the tickets */
2867     c = '6';
2868     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2869             || !TEST_size_t_eq(1, nbytes)
2870             || !TEST_int_eq(2, new_called)
2871             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2872             || !TEST_int_eq(4, new_called)
2873             || !TEST_int_eq(sizeof(buf), nbytes)
2874             || !TEST_int_eq(c, buf[0])
2875             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2876         goto end;
2877 
2878     SSL_shutdown(clientssl);
2879     SSL_shutdown(serverssl);
2880     testresult = 1;
2881 
2882  end:
2883     BIO_free(bretry);
2884     BIO_free(tmp);
2885     SSL_free(serverssl);
2886     SSL_free(clientssl);
2887     SSL_CTX_free(sctx);
2888     SSL_CTX_free(cctx);
2889     clientssl = serverssl = NULL;
2890     sctx = cctx = NULL;
2891     return testresult;
2892 }
2893 #endif
2894 
2895 #define USE_NULL            0
2896 #define USE_BIO_1           1
2897 #define USE_BIO_2           2
2898 #define USE_DEFAULT         3
2899 
2900 #define CONNTYPE_CONNECTION_SUCCESS  0
2901 #define CONNTYPE_CONNECTION_FAIL     1
2902 #define CONNTYPE_NO_CONNECTION       2
2903 
2904 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
2905 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
2906 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2907 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
2908 #else
2909 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
2910 #endif
2911 
2912 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
2913                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2914                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2915 
setupbio(BIO ** res,BIO * bio1,BIO * bio2,int type)2916 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2917 {
2918     switch (type) {
2919     case USE_NULL:
2920         *res = NULL;
2921         break;
2922     case USE_BIO_1:
2923         *res = bio1;
2924         break;
2925     case USE_BIO_2:
2926         *res = bio2;
2927         break;
2928     }
2929 }
2930 
2931 
2932 /*
2933  * Tests calls to SSL_set_bio() under various conditions.
2934  *
2935  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2936  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2937  * then do more tests where we create a successful connection first using our
2938  * standard connection setup functions, and then call SSL_set_bio() with
2939  * various combinations of valid BIOs or NULL. We then repeat these tests
2940  * following a failed connection. In this last case we are looking to check that
2941  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2942  */
test_ssl_set_bio(int idx)2943 static int test_ssl_set_bio(int idx)
2944 {
2945     SSL_CTX *sctx = NULL, *cctx = NULL;
2946     BIO *bio1 = NULL;
2947     BIO *bio2 = NULL;
2948     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2949     SSL *serverssl = NULL, *clientssl = NULL;
2950     int initrbio, initwbio, newrbio, newwbio, conntype;
2951     int testresult = 0;
2952 
2953     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2954         initrbio = idx % 3;
2955         idx /= 3;
2956         initwbio = idx % 3;
2957         idx /= 3;
2958         newrbio = idx % 3;
2959         idx /= 3;
2960         newwbio = idx % 3;
2961         conntype = CONNTYPE_NO_CONNECTION;
2962     } else {
2963         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2964         initrbio = initwbio = USE_DEFAULT;
2965         newrbio = idx % 2;
2966         idx /= 2;
2967         newwbio = idx % 2;
2968         idx /= 2;
2969         conntype = idx % 2;
2970     }
2971 
2972     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2973                                        TLS_client_method(), TLS1_VERSION, 0,
2974                                        &sctx, &cctx, cert, privkey)))
2975         goto end;
2976 
2977     if (conntype == CONNTYPE_CONNECTION_FAIL) {
2978         /*
2979          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2980          * because we reduced the number of tests in the definition of
2981          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2982          * mismatched protocol versions we will force a connection failure.
2983          */
2984         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2985         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2986     }
2987 
2988     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2989                                       NULL, NULL)))
2990         goto end;
2991 
2992     if (initrbio == USE_BIO_1
2993             || initwbio == USE_BIO_1
2994             || newrbio == USE_BIO_1
2995             || newwbio == USE_BIO_1) {
2996         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2997             goto end;
2998     }
2999 
3000     if (initrbio == USE_BIO_2
3001             || initwbio == USE_BIO_2
3002             || newrbio == USE_BIO_2
3003             || newwbio == USE_BIO_2) {
3004         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
3005             goto end;
3006     }
3007 
3008     if (initrbio != USE_DEFAULT) {
3009         setupbio(&irbio, bio1, bio2, initrbio);
3010         setupbio(&iwbio, bio1, bio2, initwbio);
3011         SSL_set_bio(clientssl, irbio, iwbio);
3012 
3013         /*
3014          * We want to maintain our own refs to these BIO, so do an up ref for
3015          * each BIO that will have ownership transferred in the SSL_set_bio()
3016          * call
3017          */
3018         if (irbio != NULL && !BIO_up_ref(irbio))
3019             goto end;
3020         if (iwbio != NULL && iwbio != irbio && !BIO_up_ref(iwbio)) {
3021             BIO_free(irbio);
3022             goto end;
3023         }
3024     }
3025 
3026     if (conntype != CONNTYPE_NO_CONNECTION
3027             && !TEST_true(create_ssl_connection(serverssl, clientssl,
3028                                                 SSL_ERROR_NONE)
3029                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
3030         goto end;
3031 
3032     setupbio(&nrbio, bio1, bio2, newrbio);
3033     setupbio(&nwbio, bio1, bio2, newwbio);
3034 
3035     /*
3036      * We will (maybe) transfer ownership again so do more up refs.
3037      * SSL_set_bio() has some really complicated ownership rules where BIOs have
3038      * already been set!
3039      */
3040     if (nrbio != NULL
3041             && nrbio != irbio
3042             && (nwbio != iwbio || nrbio != nwbio))
3043         if (!TEST_true(BIO_up_ref(nrbio)))
3044             goto end;
3045     if (nwbio != NULL
3046             && nwbio != nrbio
3047             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
3048         if (!TEST_true(BIO_up_ref(nwbio))) {
3049             if (nrbio != irbio
3050                     && (nwbio != iwbio || nrbio != nwbio))
3051                 BIO_free(nrbio);
3052             goto end;
3053         }
3054 
3055     SSL_set_bio(clientssl, nrbio, nwbio);
3056 
3057     testresult = 1;
3058 
3059  end:
3060     BIO_free(bio1);
3061     BIO_free(bio2);
3062 
3063     /*
3064      * This test is checking that the ref counting for SSL_set_bio is correct.
3065      * If we get here and we did too many frees then we will fail in the above
3066      * functions.
3067      */
3068     SSL_free(serverssl);
3069     SSL_free(clientssl);
3070     SSL_CTX_free(sctx);
3071     SSL_CTX_free(cctx);
3072     return testresult;
3073 }
3074 
3075 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
3076 
execute_test_ssl_bio(int pop_ssl,bio_change_t change_bio)3077 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
3078 {
3079     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
3080     SSL_CTX *ctx;
3081     SSL *ssl = NULL;
3082     int testresult = 0;
3083 
3084     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
3085             || !TEST_ptr(ssl = SSL_new(ctx))
3086             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
3087             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
3088         goto end;
3089 
3090     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
3091 
3092     /*
3093      * If anything goes wrong here then we could leak memory.
3094      */
3095     BIO_push(sslbio, membio1);
3096 
3097     /* Verify changing the rbio/wbio directly does not cause leaks */
3098     if (change_bio != NO_BIO_CHANGE) {
3099         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
3100             ssl = NULL;
3101             goto end;
3102         }
3103         if (change_bio == CHANGE_RBIO)
3104             SSL_set0_rbio(ssl, membio2);
3105         else
3106             SSL_set0_wbio(ssl, membio2);
3107     }
3108     ssl = NULL;
3109 
3110     if (pop_ssl)
3111         BIO_pop(sslbio);
3112     else
3113         BIO_pop(membio1);
3114 
3115     testresult = 1;
3116  end:
3117     BIO_free(membio1);
3118     BIO_free(sslbio);
3119     SSL_free(ssl);
3120     SSL_CTX_free(ctx);
3121 
3122     return testresult;
3123 }
3124 
test_ssl_bio_pop_next_bio(void)3125 static int test_ssl_bio_pop_next_bio(void)
3126 {
3127     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
3128 }
3129 
test_ssl_bio_pop_ssl_bio(void)3130 static int test_ssl_bio_pop_ssl_bio(void)
3131 {
3132     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
3133 }
3134 
test_ssl_bio_change_rbio(void)3135 static int test_ssl_bio_change_rbio(void)
3136 {
3137     return execute_test_ssl_bio(0, CHANGE_RBIO);
3138 }
3139 
test_ssl_bio_change_wbio(void)3140 static int test_ssl_bio_change_wbio(void)
3141 {
3142     return execute_test_ssl_bio(0, CHANGE_WBIO);
3143 }
3144 
3145 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
3146 typedef struct {
3147     /* The list of sig algs */
3148     const int *list;
3149     /* The length of the list */
3150     size_t listlen;
3151     /* A sigalgs list in string format */
3152     const char *liststr;
3153     /* Whether setting the list should succeed */
3154     int valid;
3155     /* Whether creating a connection with the list should succeed */
3156     int connsuccess;
3157 } sigalgs_list;
3158 
3159 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
3160 # ifndef OPENSSL_NO_EC
3161 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
3162 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
3163 # endif
3164 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
3165 static const int invalidlist2[] = {NID_sha256, NID_undef};
3166 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
3167 static const int invalidlist4[] = {NID_sha256};
3168 static const sigalgs_list testsigalgs[] = {
3169     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
3170 # ifndef OPENSSL_NO_EC
3171     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
3172     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
3173 # endif
3174     {NULL, 0, "RSA+SHA256", 1, 1},
3175     {NULL, 0, "RSA+SHA256:?Invalid", 1, 1},
3176 # ifndef OPENSSL_NO_EC
3177     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
3178     {NULL, 0, "ECDSA+SHA512", 1, 0},
3179 # endif
3180     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
3181     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
3182     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
3183     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
3184     {NULL, 0, "RSA", 0, 0},
3185     {NULL, 0, "SHA256", 0, 0},
3186     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
3187     {NULL, 0, "Invalid", 0, 0}
3188 };
3189 
test_set_sigalgs(int idx)3190 static int test_set_sigalgs(int idx)
3191 {
3192     SSL_CTX *cctx = NULL, *sctx = NULL;
3193     SSL *clientssl = NULL, *serverssl = NULL;
3194     int testresult = 0;
3195     const sigalgs_list *curr;
3196     int testctx;
3197 
3198     /* Should never happen */
3199     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
3200         return 0;
3201 
3202     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
3203     curr = testctx ? &testsigalgs[idx]
3204                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
3205 
3206     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3207                                        TLS_client_method(), TLS1_VERSION, 0,
3208                                        &sctx, &cctx, cert, privkey)))
3209         return 0;
3210 
3211     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
3212 
3213     if (testctx) {
3214         int ret;
3215 
3216         if (curr->list != NULL)
3217             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
3218         else
3219             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
3220 
3221         if (!ret) {
3222             if (curr->valid)
3223                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
3224             else
3225                 testresult = 1;
3226             goto end;
3227         }
3228         if (!curr->valid) {
3229             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
3230             goto end;
3231         }
3232     }
3233 
3234     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3235                                       &clientssl, NULL, NULL)))
3236         goto end;
3237 
3238     if (!testctx) {
3239         int ret;
3240 
3241         if (curr->list != NULL)
3242             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
3243         else
3244             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
3245         if (!ret) {
3246             if (curr->valid)
3247                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
3248             else
3249                 testresult = 1;
3250             goto end;
3251         }
3252         if (!curr->valid)
3253             goto end;
3254     }
3255 
3256     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
3257                                            SSL_ERROR_NONE),
3258                 curr->connsuccess))
3259         goto end;
3260 
3261     testresult = 1;
3262 
3263  end:
3264     SSL_free(serverssl);
3265     SSL_free(clientssl);
3266     SSL_CTX_free(sctx);
3267     SSL_CTX_free(cctx);
3268 
3269     return testresult;
3270 }
3271 #endif
3272 
3273 #ifndef OSSL_NO_USABLE_TLS1_3
3274 static int psk_client_cb_cnt = 0;
3275 static int psk_server_cb_cnt = 0;
3276 
use_session_cb(SSL * ssl,const EVP_MD * md,const unsigned char ** id,size_t * idlen,SSL_SESSION ** sess)3277 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
3278                           size_t *idlen, SSL_SESSION **sess)
3279 {
3280     switch (++use_session_cb_cnt) {
3281     case 1:
3282         /* The first call should always have a NULL md */
3283         if (md != NULL)
3284             return 0;
3285         break;
3286 
3287     case 2:
3288         /* The second call should always have an md */
3289         if (md == NULL)
3290             return 0;
3291         break;
3292 
3293     default:
3294         /* We should only be called a maximum of twice */
3295         return 0;
3296     }
3297 
3298     if (clientpsk != NULL && !SSL_SESSION_up_ref(clientpsk))
3299         return 0;
3300 
3301     *sess = clientpsk;
3302     *id = (const unsigned char *)pskid;
3303     *idlen = strlen(pskid);
3304 
3305     return 1;
3306 }
3307 
3308 #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)3309 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
3310                                   unsigned int max_id_len,
3311                                   unsigned char *psk,
3312                                   unsigned int max_psk_len)
3313 {
3314     unsigned int psklen = 0;
3315 
3316     psk_client_cb_cnt++;
3317 
3318     if (strlen(pskid) + 1 > max_id_len)
3319         return 0;
3320 
3321     /* We should only ever be called a maximum of twice per connection */
3322     if (psk_client_cb_cnt > 2)
3323         return 0;
3324 
3325     if (clientpsk == NULL)
3326         return 0;
3327 
3328     /* We'll reuse the PSK we set up for TLSv1.3 */
3329     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
3330         return 0;
3331     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
3332     strncpy(id, pskid, max_id_len);
3333 
3334     return psklen;
3335 }
3336 #endif /* OPENSSL_NO_PSK */
3337 
find_session_cb(SSL * ssl,const unsigned char * identity,size_t identity_len,SSL_SESSION ** sess)3338 static int find_session_cb(SSL *ssl, const unsigned char *identity,
3339                            size_t identity_len, SSL_SESSION **sess)
3340 {
3341     find_session_cb_cnt++;
3342 
3343     /* We should only ever be called a maximum of twice per connection */
3344     if (find_session_cb_cnt > 2)
3345         return 0;
3346 
3347     if (serverpsk == NULL)
3348         return 0;
3349 
3350     /* Identity should match that set by the client */
3351     if (strlen(srvid) != identity_len
3352             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
3353         /* No PSK found, continue but without a PSK */
3354         *sess = NULL;
3355         return 1;
3356     }
3357 
3358     if (!SSL_SESSION_up_ref(serverpsk))
3359         return 0;
3360 
3361     *sess = serverpsk;
3362 
3363     return 1;
3364 }
3365 
3366 #ifndef OPENSSL_NO_PSK
psk_server_cb(SSL * ssl,const char * identity,unsigned char * psk,unsigned int max_psk_len)3367 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
3368                                   unsigned char *psk, unsigned int max_psk_len)
3369 {
3370     unsigned int psklen = 0;
3371 
3372     psk_server_cb_cnt++;
3373 
3374     /* We should only ever be called a maximum of twice per connection */
3375     if (find_session_cb_cnt > 2)
3376         return 0;
3377 
3378     if (serverpsk == NULL)
3379         return 0;
3380 
3381     /* Identity should match that set by the client */
3382     if (strcmp(srvid, identity) != 0) {
3383         return 0;
3384     }
3385 
3386     /* We'll reuse the PSK we set up for TLSv1.3 */
3387     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
3388         return 0;
3389     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
3390 
3391     return psklen;
3392 }
3393 #endif /* OPENSSL_NO_PSK */
3394 
3395 #define MSG1    "Hello"
3396 #define MSG2    "World."
3397 #define MSG3    "This"
3398 #define MSG4    "is"
3399 #define MSG5    "a"
3400 #define MSG6    "test"
3401 #define MSG7    "message."
3402 
3403 static int artificial_ticket_time = 0;
3404 
sub_session_time(SSL_SESSION * sess)3405 static int sub_session_time(SSL_SESSION *sess)
3406 {
3407     OSSL_TIME tick_time;
3408 
3409     tick_time = ossl_time_from_time_t(SSL_SESSION_get_time_ex(sess));
3410     tick_time = ossl_time_subtract(tick_time, ossl_seconds2time(10));
3411 
3412     return SSL_SESSION_set_time_ex(sess, ossl_time_to_time_t(tick_time)) != 0;
3413 }
3414 
ed_gen_cb(SSL * s,void * arg)3415 static int ed_gen_cb(SSL *s, void *arg)
3416 {
3417     SSL_SESSION *sess = SSL_get0_session(s);
3418 
3419     if (sess == NULL)
3420         return 0;
3421 
3422     /*
3423      * Artificially give the ticket some age. Just do it for the number of
3424      * tickets we've been told to do.
3425      */
3426     if (artificial_ticket_time == 0)
3427         return 1;
3428     artificial_ticket_time--;
3429 
3430     return sub_session_time(sess);
3431 }
3432 
3433 /*
3434  * Helper method to setup objects for early data test. Caller frees objects on
3435  * error.
3436  */
setupearly_data_test(SSL_CTX ** cctx,SSL_CTX ** sctx,SSL ** clientssl,SSL ** serverssl,SSL_SESSION ** sess,int idx,size_t mdsize)3437 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
3438                                 SSL **serverssl, SSL_SESSION **sess, int idx,
3439                                 size_t mdsize)
3440 {
3441     int artificial = (artificial_ticket_time > 0);
3442 
3443     if (*sctx == NULL
3444             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3445                                               TLS_client_method(),
3446                                               TLS1_VERSION, 0,
3447                                               sctx, cctx, cert, privkey)))
3448         return 0;
3449 
3450     if (artificial)
3451         SSL_CTX_set_session_ticket_cb(*sctx, ed_gen_cb, NULL, NULL);
3452 
3453     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
3454         return 0;
3455 
3456     if (idx == 1) {
3457         /* When idx == 1 we repeat the tests with read_ahead set */
3458         SSL_CTX_set_read_ahead(*cctx, 1);
3459         SSL_CTX_set_read_ahead(*sctx, 1);
3460     } else if (idx == 2) {
3461         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
3462         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
3463         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
3464         use_session_cb_cnt = 0;
3465         find_session_cb_cnt = 0;
3466         srvid = pskid;
3467     }
3468 
3469     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
3470                                       NULL, NULL)))
3471         return 0;
3472 
3473     /*
3474      * For one of the run throughs (doesn't matter which one), we'll try sending
3475      * some SNI data in the initial ClientHello. This will be ignored (because
3476      * there is no SNI cb set up by the server), so it should not impact
3477      * early_data.
3478      */
3479     if (idx == 1
3480             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
3481         return 0;
3482 
3483     if (idx == 2) {
3484         clientpsk = create_a_psk(*clientssl, mdsize);
3485         if (!TEST_ptr(clientpsk)
3486                    /*
3487                     * We just choose an arbitrary value for max_early_data which
3488                     * should be big enough for testing purposes.
3489                     */
3490                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
3491                                                              0x100))
3492                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3493             SSL_SESSION_free(clientpsk);
3494             clientpsk = NULL;
3495             return 0;
3496         }
3497         serverpsk = clientpsk;
3498 
3499         if (sess != NULL) {
3500             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3501                 SSL_SESSION_free(clientpsk);
3502                 SSL_SESSION_free(serverpsk);
3503                 clientpsk = serverpsk = NULL;
3504                 return 0;
3505             }
3506             *sess = clientpsk;
3507         }
3508         return 1;
3509     }
3510 
3511     if (sess == NULL)
3512         return 1;
3513 
3514     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
3515                                          SSL_ERROR_NONE)))
3516         return 0;
3517 
3518     *sess = SSL_get1_session(*clientssl);
3519     SSL_shutdown(*clientssl);
3520     SSL_shutdown(*serverssl);
3521     SSL_free(*serverssl);
3522     SSL_free(*clientssl);
3523     *serverssl = *clientssl = NULL;
3524 
3525     /*
3526      * Artificially give the ticket some age to match the artificial age we
3527      * gave it on the server side
3528      */
3529     if (artificial
3530             && !TEST_true(sub_session_time(*sess)))
3531         return 0;
3532 
3533     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
3534                                       clientssl, NULL, NULL))
3535             || !TEST_true(SSL_set_session(*clientssl, *sess)))
3536         return 0;
3537 
3538     return 1;
3539 }
3540 
check_early_data_timeout(OSSL_TIME timer)3541 static int check_early_data_timeout(OSSL_TIME timer)
3542 {
3543     int res = 0;
3544 
3545     /*
3546      * Early data is time sensitive. We have an approx 8 second allowance
3547      * between writing the early data and reading it. If we exceed that time
3548      * then this test will fail. This can sometimes (rarely) occur in normal CI
3549      * operation. We can try and detect this and just ignore the result of this
3550      * test if it has taken too long. We assume anything over 7 seconds is too
3551      * long
3552      */
3553     timer = ossl_time_subtract(ossl_time_now(), timer);
3554     if (ossl_time_compare(timer, ossl_seconds2time(7)) >= 0)
3555         res = TEST_skip("Test took too long, ignoring result");
3556 
3557     return res;
3558 }
3559 
test_early_data_read_write(int idx)3560 static int test_early_data_read_write(int idx)
3561 {
3562     SSL_CTX *cctx = NULL, *sctx = NULL;
3563     SSL *clientssl = NULL, *serverssl = NULL;
3564     int testresult = 0;
3565     SSL_SESSION *sess = NULL;
3566     unsigned char buf[20], data[1024];
3567     size_t readbytes, written, eoedlen, rawread, rawwritten;
3568     BIO *rbio;
3569     OSSL_TIME timer;
3570 
3571     /* Artificially give the next 2 tickets some age for non PSK sessions */
3572     if (idx != 2)
3573         artificial_ticket_time = 2;
3574     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3575                                         &serverssl, &sess, idx,
3576                                         SHA384_DIGEST_LENGTH))) {
3577         artificial_ticket_time = 0;
3578         goto end;
3579     }
3580     artificial_ticket_time = 0;
3581 
3582     /* Write and read some early data */
3583     timer = ossl_time_now();
3584     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3585                                         &written))
3586             || !TEST_size_t_eq(written, strlen(MSG1)))
3587         goto end;
3588 
3589     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3590                                          &readbytes),
3591                      SSL_READ_EARLY_DATA_SUCCESS)) {
3592         testresult = check_early_data_timeout(timer);
3593         goto end;
3594     }
3595 
3596     if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
3597             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3598                             SSL_EARLY_DATA_ACCEPTED))
3599         goto end;
3600 
3601     /*
3602      * Server should be able to write data, and client should be able to
3603      * read it.
3604      */
3605     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
3606                                         &written))
3607             || !TEST_size_t_eq(written, strlen(MSG2))
3608             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3609             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3610         goto end;
3611 
3612     /* Even after reading normal data, client should be able write early data */
3613     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
3614                                         &written))
3615             || !TEST_size_t_eq(written, strlen(MSG3)))
3616         goto end;
3617 
3618     /* Server should still be able read early data after writing data */
3619     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3620                                          &readbytes),
3621                      SSL_READ_EARLY_DATA_SUCCESS)
3622             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
3623         goto end;
3624 
3625     /* Write more data from server and read it from client */
3626     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
3627                                         &written))
3628             || !TEST_size_t_eq(written, strlen(MSG4))
3629             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3630             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
3631         goto end;
3632 
3633     /*
3634      * If client writes normal data it should mean writing early data is no
3635      * longer possible.
3636      */
3637     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3638             || !TEST_size_t_eq(written, strlen(MSG5))
3639             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3640                             SSL_EARLY_DATA_ACCEPTED))
3641         goto end;
3642 
3643     /*
3644      * At this point the client has written EndOfEarlyData, ClientFinished and
3645      * normal (fully protected) data. We are going to cause a delay between the
3646      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
3647      * in the read BIO, and then just put back the EndOfEarlyData message.
3648      */
3649     rbio = SSL_get_rbio(serverssl);
3650     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
3651             || !TEST_size_t_lt(rawread, sizeof(data))
3652             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
3653         goto end;
3654 
3655     /* Record length is in the 4th and 5th bytes of the record header */
3656     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
3657     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
3658             || !TEST_size_t_eq(rawwritten, eoedlen))
3659         goto end;
3660 
3661     /* Server should be told that there is no more early data */
3662     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3663                                          &readbytes),
3664                      SSL_READ_EARLY_DATA_FINISH)
3665             || !TEST_size_t_eq(readbytes, 0))
3666         goto end;
3667 
3668     /*
3669      * Server has not finished init yet, so should still be able to write early
3670      * data.
3671      */
3672     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
3673                                         &written))
3674             || !TEST_size_t_eq(written, strlen(MSG6)))
3675         goto end;
3676 
3677     /* Push the ClientFinished and the normal data back into the server rbio */
3678     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
3679                                 &rawwritten))
3680             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
3681         goto end;
3682 
3683     /* Server should be able to read normal data */
3684     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3685             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3686         goto end;
3687 
3688     /* Client and server should not be able to write/read early data now */
3689     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3690                                          &written)))
3691         goto end;
3692     ERR_clear_error();
3693     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3694                                          &readbytes),
3695                      SSL_READ_EARLY_DATA_ERROR))
3696         goto end;
3697     ERR_clear_error();
3698 
3699     /* Client should be able to read the data sent by the server */
3700     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3701             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
3702         goto end;
3703 
3704     /*
3705      * Make sure we process the two NewSessionTickets. These arrive
3706      * post-handshake. We attempt reads which we do not expect to return any
3707      * data.
3708      */
3709     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3710             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3711                            &readbytes)))
3712         goto end;
3713 
3714     /* Server should be able to write normal data */
3715     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3716             || !TEST_size_t_eq(written, strlen(MSG7))
3717             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3718             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3719         goto end;
3720 
3721     SSL_SESSION_free(sess);
3722     sess = SSL_get1_session(clientssl);
3723     use_session_cb_cnt = 0;
3724     find_session_cb_cnt = 0;
3725 
3726     SSL_shutdown(clientssl);
3727     SSL_shutdown(serverssl);
3728     SSL_free(serverssl);
3729     SSL_free(clientssl);
3730     serverssl = clientssl = NULL;
3731     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3732                                       &clientssl, NULL, NULL))
3733             || !TEST_true(SSL_set_session(clientssl, sess)))
3734         goto end;
3735 
3736     /* Write and read some early data */
3737     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3738                                         &written))
3739             || !TEST_size_t_eq(written, strlen(MSG1))
3740             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3741                                                 &readbytes),
3742                             SSL_READ_EARLY_DATA_SUCCESS)
3743             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3744         goto end;
3745 
3746     if (!TEST_int_gt(SSL_connect(clientssl), 0)
3747             || !TEST_int_gt(SSL_accept(serverssl), 0))
3748         goto end;
3749 
3750     /* Client and server should not be able to write/read early data now */
3751     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3752                                          &written)))
3753         goto end;
3754     ERR_clear_error();
3755     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3756                                          &readbytes),
3757                      SSL_READ_EARLY_DATA_ERROR))
3758         goto end;
3759     ERR_clear_error();
3760 
3761     /* Client and server should be able to write/read normal data */
3762     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3763             || !TEST_size_t_eq(written, strlen(MSG5))
3764             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3765             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3766         goto end;
3767 
3768     testresult = 1;
3769 
3770  end:
3771     SSL_SESSION_free(sess);
3772     SSL_SESSION_free(clientpsk);
3773     SSL_SESSION_free(serverpsk);
3774     clientpsk = serverpsk = NULL;
3775     SSL_free(serverssl);
3776     SSL_free(clientssl);
3777     SSL_CTX_free(sctx);
3778     SSL_CTX_free(cctx);
3779     return testresult;
3780 }
3781 
3782 static int allow_ed_cb_called = 0;
3783 
allow_early_data_cb(SSL * s,void * arg)3784 static int allow_early_data_cb(SSL *s, void *arg)
3785 {
3786     int *usecb = (int *)arg;
3787 
3788     allow_ed_cb_called++;
3789 
3790     if (*usecb == 1)
3791         return 0;
3792 
3793     return 1;
3794 }
3795 
3796 /*
3797  * idx == 0: Standard early_data setup
3798  * idx == 1: early_data setup using read_ahead
3799  * usecb == 0: Don't use a custom early data callback
3800  * usecb == 1: Use a custom early data callback and reject the early data
3801  * usecb == 2: Use a custom early data callback and accept the early data
3802  * confopt == 0: Configure anti-replay directly
3803  * confopt == 1: Configure anti-replay using SSL_CONF
3804  */
test_early_data_replay_int(int idx,int usecb,int confopt)3805 static int test_early_data_replay_int(int idx, int usecb, int confopt)
3806 {
3807     SSL_CTX *cctx = NULL, *sctx = NULL;
3808     SSL *clientssl = NULL, *serverssl = NULL;
3809     int testresult = 0;
3810     SSL_SESSION *sess = NULL;
3811     size_t readbytes, written;
3812     unsigned char buf[20];
3813     OSSL_TIME timer;
3814 
3815     allow_ed_cb_called = 0;
3816 
3817     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3818                                        TLS_client_method(), TLS1_VERSION, 0,
3819                                        &sctx, &cctx, cert, privkey)))
3820         return 0;
3821 
3822     if (usecb > 0) {
3823         if (confopt == 0) {
3824             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3825         } else {
3826             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3827 
3828             if (!TEST_ptr(confctx))
3829                 goto end;
3830             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
3831                                             | SSL_CONF_FLAG_SERVER);
3832             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3833             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3834                              2)) {
3835                 SSL_CONF_CTX_free(confctx);
3836                 goto end;
3837             }
3838             SSL_CONF_CTX_free(confctx);
3839         }
3840         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3841     }
3842 
3843     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3844                                         &serverssl, &sess, idx,
3845                                         SHA384_DIGEST_LENGTH)))
3846         goto end;
3847 
3848     /*
3849      * The server is configured to accept early data. Create a connection to
3850      * "use up" the ticket
3851      */
3852     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3853             || !TEST_true(SSL_session_reused(clientssl)))
3854         goto end;
3855 
3856     SSL_shutdown(clientssl);
3857     SSL_shutdown(serverssl);
3858     SSL_free(serverssl);
3859     SSL_free(clientssl);
3860     serverssl = clientssl = NULL;
3861 
3862     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3863                                       &clientssl, NULL, NULL))
3864             || !TEST_true(SSL_set_session(clientssl, sess)))
3865         goto end;
3866 
3867     /* Write and read some early data */
3868     timer = ossl_time_now();
3869     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3870                                         &written))
3871             || !TEST_size_t_eq(written, strlen(MSG1)))
3872         goto end;
3873 
3874     if (usecb <= 1) {
3875         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3876                                              &readbytes),
3877                          SSL_READ_EARLY_DATA_FINISH)
3878                    /*
3879                     * The ticket was reused, so the we should have rejected the
3880                     * early data
3881                     */
3882                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3883                                 SSL_EARLY_DATA_REJECTED))
3884             goto end;
3885     } else {
3886         /* In this case the callback decides to accept the early data */
3887         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3888                                              &readbytes),
3889                          SSL_READ_EARLY_DATA_SUCCESS)) {
3890             testresult = check_early_data_timeout(timer);
3891             goto end;
3892         }
3893         if (!TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3894                    /*
3895                     * Server will have sent its flight so client can now send
3896                     * end of early data and complete its half of the handshake
3897                     */
3898                 || !TEST_int_gt(SSL_connect(clientssl), 0)
3899                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3900                                              &readbytes),
3901                                 SSL_READ_EARLY_DATA_FINISH)
3902                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3903                                 SSL_EARLY_DATA_ACCEPTED))
3904             goto end;
3905     }
3906 
3907     /* Complete the connection */
3908     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3909             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3910             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3911         goto end;
3912 
3913     testresult = 1;
3914 
3915  end:
3916     SSL_SESSION_free(sess);
3917     SSL_SESSION_free(clientpsk);
3918     SSL_SESSION_free(serverpsk);
3919     clientpsk = serverpsk = NULL;
3920     SSL_free(serverssl);
3921     SSL_free(clientssl);
3922     SSL_CTX_free(sctx);
3923     SSL_CTX_free(cctx);
3924     return testresult;
3925 }
3926 
test_early_data_replay(int idx)3927 static int test_early_data_replay(int idx)
3928 {
3929     int ret = 1, usecb, confopt;
3930 
3931     for (usecb = 0; usecb < 3; usecb++) {
3932         for (confopt = 0; confopt < 2; confopt++)
3933             ret &= test_early_data_replay_int(idx, usecb, confopt);
3934     }
3935 
3936     return ret;
3937 }
3938 
3939 static const char *ciphersuites[] = {
3940     "TLS_AES_128_CCM_8_SHA256",
3941     "TLS_AES_128_GCM_SHA256",
3942     "TLS_AES_256_GCM_SHA384",
3943     "TLS_AES_128_CCM_SHA256",
3944 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3945     "TLS_CHACHA20_POLY1305_SHA256",
3946 #else
3947     NULL,
3948 #endif
3949 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
3950     "TLS_SHA256_SHA256",
3951     "TLS_SHA384_SHA384"
3952 #endif
3953 };
3954 
3955 /*
3956  * Helper function to test that a server attempting to read early data can
3957  * handle a connection from a client where the early data should be skipped.
3958  * testtype: 0 == No HRR
3959  * testtype: 1 == HRR
3960  * testtype: 2 == HRR, invalid early_data sent after HRR
3961  * testtype: 3 == recv_max_early_data set to 0
3962  */
early_data_skip_helper(int testtype,int cipher,int idx)3963 static int early_data_skip_helper(int testtype, int cipher, int idx)
3964 {
3965     SSL_CTX *cctx = NULL, *sctx = NULL;
3966     SSL *clientssl = NULL, *serverssl = NULL;
3967     int testresult = 0;
3968     SSL_SESSION *sess = NULL;
3969     unsigned char buf[20];
3970     size_t readbytes, written;
3971 
3972     if (is_fips && cipher >= 4)
3973         return 1;
3974 
3975     if (ciphersuites[cipher] == NULL)
3976         return TEST_skip("Cipher not supported");
3977 
3978     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3979                                               TLS_client_method(),
3980                                               TLS1_VERSION, 0,
3981                                               &sctx, &cctx, cert, privkey)))
3982         goto end;
3983 
3984     if (cipher == 0 || cipher == 5 || cipher == 6) {
3985         SSL_CTX_set_security_level(sctx, 0);
3986         SSL_CTX_set_security_level(cctx, 0);
3987     }
3988 
3989     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, ciphersuites[cipher]))
3990             || !TEST_true(SSL_CTX_set_ciphersuites(cctx, ciphersuites[cipher])))
3991         goto end;
3992 
3993     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3994                                         &serverssl, &sess, idx,
3995                                         (cipher == 2 || cipher == 6)
3996                                             ? SHA384_DIGEST_LENGTH
3997                                             : SHA256_DIGEST_LENGTH)))
3998         goto end;
3999 
4000     if (testtype == 1 || testtype == 2) {
4001         /* Force an HRR to occur */
4002 #if defined(OPENSSL_NO_EC)
4003         if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
4004             goto end;
4005 #else
4006         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
4007             goto end;
4008 #endif
4009     } else if (idx == 2) {
4010         /*
4011          * We force early_data rejection by ensuring the PSK identity is
4012          * unrecognised
4013          */
4014         srvid = "Dummy Identity";
4015     } else {
4016         /*
4017          * Deliberately corrupt the creation time. We take 20 seconds off the
4018          * time. It could be any value as long as it is not within tolerance.
4019          * This should mean the ticket is rejected.
4020          */
4021         if (!TEST_true(SSL_SESSION_set_time_ex(sess, time(NULL) - 20)))
4022             goto end;
4023     }
4024 
4025     if (testtype == 3
4026             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
4027         goto end;
4028 
4029     /* Write some early data */
4030     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4031                                         &written))
4032             || !TEST_size_t_eq(written, strlen(MSG1)))
4033         goto end;
4034 
4035     /* Server should reject the early data */
4036     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4037                                          &readbytes),
4038                      SSL_READ_EARLY_DATA_FINISH)
4039             || !TEST_size_t_eq(readbytes, 0)
4040             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4041                             SSL_EARLY_DATA_REJECTED))
4042         goto end;
4043 
4044     switch (testtype) {
4045     case 0:
4046         /* Nothing to do */
4047         break;
4048 
4049     case 1:
4050         /*
4051          * Finish off the handshake. We perform the same writes and reads as
4052          * further down but we expect them to fail due to the incomplete
4053          * handshake.
4054          */
4055         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4056                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
4057                                &readbytes)))
4058             goto end;
4059         break;
4060 
4061     case 2:
4062         {
4063             BIO *wbio = SSL_get_wbio(clientssl);
4064             /* A record that will appear as bad early_data */
4065             const unsigned char bad_early_data[] = {
4066                 0x17, 0x03, 0x03, 0x00, 0x01, 0x00
4067             };
4068 
4069             /*
4070              * We force the client to attempt a write. This will fail because
4071              * we're still in the handshake. It will cause the second
4072              * ClientHello to be sent.
4073              */
4074             if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
4075                                          &written)))
4076                 goto end;
4077 
4078             /*
4079              * Inject some early_data after the second ClientHello. This should
4080              * cause the server to fail
4081              */
4082             if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
4083                                         sizeof(bad_early_data), &written)))
4084                 goto end;
4085         }
4086         /* FALLTHROUGH */
4087 
4088     case 3:
4089         /*
4090          * This client has sent more early_data than we are willing to skip
4091          * (case 3) or sent invalid early_data (case 2) so the connection should
4092          * abort.
4093          */
4094         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4095                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
4096             goto end;
4097 
4098         /* Connection has failed - nothing more to do */
4099         testresult = 1;
4100         goto end;
4101 
4102     default:
4103         TEST_error("Invalid test type");
4104         goto end;
4105     }
4106 
4107     ERR_clear_error();
4108     /*
4109      * Should be able to send normal data despite rejection of early data. The
4110      * early_data should be skipped.
4111      */
4112     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4113             || !TEST_size_t_eq(written, strlen(MSG2))
4114             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4115                             SSL_EARLY_DATA_REJECTED)
4116             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4117             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4118         goto end;
4119 
4120     /*
4121      * Failure to decrypt early data records should not leave spurious errors
4122      * on the error stack
4123      */
4124     if (!TEST_long_eq(ERR_peek_error(), 0))
4125         goto end;
4126 
4127     testresult = 1;
4128 
4129  end:
4130     SSL_SESSION_free(clientpsk);
4131     SSL_SESSION_free(serverpsk);
4132     clientpsk = serverpsk = NULL;
4133     SSL_SESSION_free(sess);
4134     SSL_free(serverssl);
4135     SSL_free(clientssl);
4136     SSL_CTX_free(sctx);
4137     SSL_CTX_free(cctx);
4138     return testresult;
4139 }
4140 
4141 /*
4142  * Test that a server attempting to read early data can handle a connection
4143  * from a client where the early data is not acceptable.
4144  */
test_early_data_skip(int idx)4145 static int test_early_data_skip(int idx)
4146 {
4147     return early_data_skip_helper(0,
4148                                   idx % OSSL_NELEM(ciphersuites),
4149                                   idx / OSSL_NELEM(ciphersuites));
4150 }
4151 
4152 /*
4153  * Test that a server attempting to read early data can handle a connection
4154  * from a client where an HRR occurs.
4155  */
test_early_data_skip_hrr(int idx)4156 static int test_early_data_skip_hrr(int idx)
4157 {
4158     return early_data_skip_helper(1,
4159                                   idx % OSSL_NELEM(ciphersuites),
4160                                   idx / OSSL_NELEM(ciphersuites));
4161 }
4162 
4163 /*
4164  * Test that a server attempting to read early data can handle a connection
4165  * from a client where an HRR occurs and correctly fails if early_data is sent
4166  * after the HRR
4167  */
test_early_data_skip_hrr_fail(int idx)4168 static int test_early_data_skip_hrr_fail(int idx)
4169 {
4170     return early_data_skip_helper(2,
4171                                   idx % OSSL_NELEM(ciphersuites),
4172                                   idx / OSSL_NELEM(ciphersuites));
4173 }
4174 
4175 /*
4176  * Test that a server attempting to read early data will abort if it tries to
4177  * skip over too much.
4178  */
test_early_data_skip_abort(int idx)4179 static int test_early_data_skip_abort(int idx)
4180 {
4181     return early_data_skip_helper(3,
4182                                   idx % OSSL_NELEM(ciphersuites),
4183                                   idx / OSSL_NELEM(ciphersuites));
4184 }
4185 
4186 /*
4187  * Test that a server attempting to read early data can handle a connection
4188  * from a client that doesn't send any.
4189  */
test_early_data_not_sent(int idx)4190 static int test_early_data_not_sent(int idx)
4191 {
4192     SSL_CTX *cctx = NULL, *sctx = NULL;
4193     SSL *clientssl = NULL, *serverssl = NULL;
4194     int testresult = 0;
4195     SSL_SESSION *sess = NULL;
4196     unsigned char buf[20];
4197     size_t readbytes, written;
4198 
4199     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4200                                         &serverssl, &sess, idx,
4201                                         SHA384_DIGEST_LENGTH)))
4202         goto end;
4203 
4204     /* Write some data - should block due to handshake with server */
4205     SSL_set_connect_state(clientssl);
4206     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4207         goto end;
4208 
4209     /* Server should detect that early data has not been sent */
4210     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4211                                          &readbytes),
4212                      SSL_READ_EARLY_DATA_FINISH)
4213             || !TEST_size_t_eq(readbytes, 0)
4214             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4215                             SSL_EARLY_DATA_NOT_SENT)
4216             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4217                             SSL_EARLY_DATA_NOT_SENT))
4218         goto end;
4219 
4220     /* Continue writing the message we started earlier */
4221     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4222             || !TEST_size_t_eq(written, strlen(MSG1))
4223             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4224             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4225             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
4226             || !TEST_size_t_eq(written, strlen(MSG2)))
4227         goto end;
4228 
4229     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4230             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4231         goto end;
4232 
4233     testresult = 1;
4234 
4235  end:
4236     SSL_SESSION_free(sess);
4237     SSL_SESSION_free(clientpsk);
4238     SSL_SESSION_free(serverpsk);
4239     clientpsk = serverpsk = NULL;
4240     SSL_free(serverssl);
4241     SSL_free(clientssl);
4242     SSL_CTX_free(sctx);
4243     SSL_CTX_free(cctx);
4244     return testresult;
4245 }
4246 
4247 static const char *servalpn;
4248 
alpn_select_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)4249 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
4250                           unsigned char *outlen, const unsigned char *in,
4251                           unsigned int inlen, void *arg)
4252 {
4253     unsigned int protlen = 0;
4254     const unsigned char *prot;
4255 
4256     for (prot = in; prot < in + inlen; prot += protlen) {
4257         protlen = *prot++;
4258         if (in + inlen < prot + protlen)
4259             return SSL_TLSEXT_ERR_NOACK;
4260 
4261         if (protlen == strlen(servalpn)
4262                 && memcmp(prot, servalpn, protlen) == 0) {
4263             *out = prot;
4264             *outlen = protlen;
4265             return SSL_TLSEXT_ERR_OK;
4266         }
4267     }
4268 
4269     return SSL_TLSEXT_ERR_NOACK;
4270 }
4271 
4272 /* Test that a PSK can be used to send early_data */
test_early_data_psk(int idx)4273 static int test_early_data_psk(int idx)
4274 {
4275     SSL_CTX *cctx = NULL, *sctx = NULL;
4276     SSL *clientssl = NULL, *serverssl = NULL;
4277     int testresult = 0;
4278     SSL_SESSION *sess = NULL;
4279     unsigned char alpnlist[] = {
4280         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
4281         'l', 'p', 'n'
4282     };
4283 #define GOODALPNLEN     9
4284 #define BADALPNLEN      8
4285 #define GOODALPN        (alpnlist)
4286 #define BADALPN         (alpnlist + GOODALPNLEN)
4287     int err = 0;
4288     unsigned char buf[20];
4289     size_t readbytes, written;
4290     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
4291     int edstatus = SSL_EARLY_DATA_ACCEPTED;
4292 
4293     /* We always set this up with a final parameter of "2" for PSK */
4294     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4295                                         &serverssl, &sess, 2,
4296                                         SHA384_DIGEST_LENGTH)))
4297         goto end;
4298 
4299     servalpn = "goodalpn";
4300 
4301     /*
4302      * Note: There is no test for inconsistent SNI with late client detection.
4303      * This is because servers do not acknowledge SNI even if they are using
4304      * it in a resumption handshake - so it is not actually possible for a
4305      * client to detect a problem.
4306      */
4307     switch (idx) {
4308     case 0:
4309         /* Set inconsistent SNI (early client detection) */
4310         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
4311         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4312                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
4313             goto end;
4314         break;
4315 
4316     case 1:
4317         /* Set inconsistent ALPN (early client detection) */
4318         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
4319         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
4320         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
4321                                                       GOODALPNLEN))
4322                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
4323                                                    BADALPNLEN)))
4324             goto end;
4325         break;
4326 
4327     case 2:
4328         /*
4329          * Set invalid protocol version. Technically this affects PSKs without
4330          * early_data too, but we test it here because it is similar to the
4331          * SNI/ALPN consistency tests.
4332          */
4333         err = SSL_R_BAD_PSK;
4334         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
4335             goto end;
4336         break;
4337 
4338     case 3:
4339         /*
4340          * Set inconsistent SNI (server side). In this case the connection
4341          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
4342          * is associated with each handshake - not the session. Therefore it
4343          * should not matter that we used a different server name last time.
4344          */
4345         SSL_SESSION_free(serverpsk);
4346         serverpsk = SSL_SESSION_dup(clientpsk);
4347         if (!TEST_ptr(serverpsk)
4348                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
4349             goto end;
4350         /* Fall through */
4351     case 4:
4352         /* Set consistent SNI */
4353         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4354                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
4355                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
4356                                 hostname_cb)))
4357             goto end;
4358         break;
4359 
4360     case 5:
4361         /*
4362          * Set inconsistent ALPN (server detected). In this case the connection
4363          * will succeed but reject early_data.
4364          */
4365         servalpn = "badalpn";
4366         edstatus = SSL_EARLY_DATA_REJECTED;
4367         readearlyres = SSL_READ_EARLY_DATA_FINISH;
4368         /* Fall through */
4369     case 6:
4370         /*
4371          * Set consistent ALPN.
4372          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
4373          * accepts a list of protos (each one length prefixed).
4374          * SSL_set1_alpn_selected accepts a single protocol (not length
4375          * prefixed)
4376          */
4377         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
4378                                                       GOODALPNLEN - 1))
4379                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
4380                                                    GOODALPNLEN)))
4381             goto end;
4382 
4383         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4384         break;
4385 
4386     case 7:
4387         /* Set inconsistent ALPN (late client detection) */
4388         SSL_SESSION_free(serverpsk);
4389         serverpsk = SSL_SESSION_dup(clientpsk);
4390         if (!TEST_ptr(serverpsk)
4391                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
4392                                                              BADALPN + 1,
4393                                                              BADALPNLEN - 1))
4394                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
4395                                                              GOODALPN + 1,
4396                                                              GOODALPNLEN - 1))
4397                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
4398                                                    sizeof(alpnlist))))
4399             goto end;
4400         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4401         edstatus = SSL_EARLY_DATA_ACCEPTED;
4402         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
4403         /* SSL_connect() call should fail */
4404         connectres = -1;
4405         break;
4406 
4407     default:
4408         TEST_error("Bad test index");
4409         goto end;
4410     }
4411 
4412     SSL_set_connect_state(clientssl);
4413     if (err != 0) {
4414         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4415                                             &written))
4416                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
4417                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
4418             goto end;
4419     } else {
4420         OSSL_TIME timer = ossl_time_now();
4421 
4422         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4423                                             &written)))
4424             goto end;
4425 
4426         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4427                                              &readbytes), readearlyres)) {
4428             testresult = check_early_data_timeout(timer);
4429             goto end;
4430         }
4431 
4432         if ((readearlyres == SSL_READ_EARLY_DATA_SUCCESS
4433                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
4434                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
4435                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
4436             goto end;
4437     }
4438 
4439     testresult = 1;
4440 
4441  end:
4442     SSL_SESSION_free(sess);
4443     SSL_SESSION_free(clientpsk);
4444     SSL_SESSION_free(serverpsk);
4445     clientpsk = serverpsk = NULL;
4446     SSL_free(serverssl);
4447     SSL_free(clientssl);
4448     SSL_CTX_free(sctx);
4449     SSL_CTX_free(cctx);
4450     return testresult;
4451 }
4452 
4453 /*
4454  * Test TLSv1.3 PSK can be used to send early_data with all 7 ciphersuites
4455  * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
4456  * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
4457  * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4458  * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
4459  * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
4460  * idx == 5: Test with TLS1_3_RFC_SHA256_SHA256
4461  * idx == 6: Test with TLS1_3_RFC_SHA384_SHA384
4462  */
test_early_data_psk_with_all_ciphers(int idx)4463 static int test_early_data_psk_with_all_ciphers(int idx)
4464 {
4465     SSL_CTX *cctx = NULL, *sctx = NULL;
4466     SSL *clientssl = NULL, *serverssl = NULL;
4467     int testresult = 0;
4468     SSL_SESSION *sess = NULL;
4469     unsigned char buf[20];
4470     size_t readbytes, written;
4471     const SSL_CIPHER *cipher;
4472     OSSL_TIME timer;
4473     const char *cipher_str[] = {
4474         TLS1_3_RFC_AES_128_GCM_SHA256,
4475         TLS1_3_RFC_AES_256_GCM_SHA384,
4476 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4477         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4478 # else
4479         NULL,
4480 # endif
4481         TLS1_3_RFC_AES_128_CCM_SHA256,
4482         TLS1_3_RFC_AES_128_CCM_8_SHA256,
4483 # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4484         TLS1_3_RFC_SHA256_SHA256,
4485         TLS1_3_RFC_SHA384_SHA384
4486 #else
4487         NULL,
4488         NULL
4489 #endif
4490     };
4491     const unsigned char *cipher_bytes[] = {
4492         TLS13_AES_128_GCM_SHA256_BYTES,
4493         TLS13_AES_256_GCM_SHA384_BYTES,
4494 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4495         TLS13_CHACHA20_POLY1305_SHA256_BYTES,
4496 # else
4497         NULL,
4498 # endif
4499         TLS13_AES_128_CCM_SHA256_BYTES,
4500         TLS13_AES_128_CCM_8_SHA256_BYTES,
4501 # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4502         TLS13_SHA256_SHA256_BYTES,
4503         TLS13_SHA384_SHA384_BYTES
4504 #else
4505         NULL,
4506         NULL
4507 #endif
4508     };
4509 
4510     if (cipher_str[idx] == NULL)
4511         return 1;
4512     /*
4513      * Skip ChaCha20Poly1305 and TLS_SHA{256,384}_SHA{256,384} ciphers
4514      * as currently FIPS module does not support them.
4515      */
4516     if ((idx == 2 || idx == 5 || idx == 6) && is_fips == 1)
4517         return 1;
4518 
4519     /* We always set this up with a final parameter of "2" for PSK */
4520     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4521                                         &serverssl, &sess, 2,
4522                                         SHA384_DIGEST_LENGTH)))
4523         goto end;
4524 
4525     if (idx == 4 || idx == 5 || idx == 6) {
4526         /*
4527          * CCM8 ciphers are considered low security due to their short tag.
4528          * Integrity-only cipher do not provide any confidentiality.
4529          */
4530         SSL_set_security_level(clientssl, 0);
4531         SSL_set_security_level(serverssl, 0);
4532     }
4533 
4534     if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
4535             || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
4536         goto end;
4537 
4538     /*
4539      * 'setupearly_data_test' creates only one instance of SSL_SESSION
4540      * and assigns to both client and server with incremented reference
4541      * and the same instance is updated in 'sess'.
4542      * So updating ciphersuite in 'sess' which will get reflected in
4543      * PSK handshake using psk use sess and find sess cb.
4544      */
4545     cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
4546     if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
4547         goto end;
4548 
4549     SSL_set_connect_state(clientssl);
4550     timer = ossl_time_now();
4551     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4552                                         &written)))
4553         goto end;
4554 
4555     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4556                                          &readbytes),
4557                                          SSL_READ_EARLY_DATA_SUCCESS)) {
4558         testresult = check_early_data_timeout(timer);
4559         goto end;
4560     }
4561 
4562     if (!TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4563             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4564                                                       SSL_EARLY_DATA_ACCEPTED)
4565             || !TEST_int_eq(SSL_connect(clientssl), 1)
4566             || !TEST_int_eq(SSL_accept(serverssl), 1))
4567         goto end;
4568 
4569     /* Send some normal data from client to server */
4570     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4571             || !TEST_size_t_eq(written, strlen(MSG2)))
4572         goto end;
4573 
4574     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4575             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4576         goto end;
4577 
4578     testresult = 1;
4579  end:
4580     SSL_SESSION_free(sess);
4581     SSL_SESSION_free(clientpsk);
4582     SSL_SESSION_free(serverpsk);
4583     clientpsk = serverpsk = NULL;
4584     if (clientssl != NULL)
4585         SSL_shutdown(clientssl);
4586     if (serverssl != NULL)
4587         SSL_shutdown(serverssl);
4588     SSL_free(serverssl);
4589     SSL_free(clientssl);
4590     SSL_CTX_free(sctx);
4591     SSL_CTX_free(cctx);
4592     return testresult;
4593 }
4594 
4595 /*
4596  * Test that a server that doesn't try to read early data can handle a
4597  * client sending some.
4598  */
test_early_data_not_expected(int idx)4599 static int test_early_data_not_expected(int idx)
4600 {
4601     SSL_CTX *cctx = NULL, *sctx = NULL;
4602     SSL *clientssl = NULL, *serverssl = NULL;
4603     int testresult = 0;
4604     SSL_SESSION *sess = NULL;
4605     unsigned char buf[20];
4606     size_t readbytes, written;
4607 
4608     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4609                                         &serverssl, &sess, idx,
4610                                         SHA384_DIGEST_LENGTH)))
4611         goto end;
4612 
4613     /* Write some early data */
4614     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4615                                         &written)))
4616         goto end;
4617 
4618     /*
4619      * Server should skip over early data and then block waiting for client to
4620      * continue handshake
4621      */
4622     if (!TEST_int_le(SSL_accept(serverssl), 0)
4623      || !TEST_int_gt(SSL_connect(clientssl), 0)
4624      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4625                      SSL_EARLY_DATA_REJECTED)
4626      || !TEST_int_gt(SSL_accept(serverssl), 0)
4627      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4628                      SSL_EARLY_DATA_REJECTED))
4629         goto end;
4630 
4631     /* Send some normal data from client to server */
4632     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4633             || !TEST_size_t_eq(written, strlen(MSG2)))
4634         goto end;
4635 
4636     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4637             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4638         goto end;
4639 
4640     testresult = 1;
4641 
4642  end:
4643     SSL_SESSION_free(sess);
4644     SSL_SESSION_free(clientpsk);
4645     SSL_SESSION_free(serverpsk);
4646     clientpsk = serverpsk = NULL;
4647     SSL_free(serverssl);
4648     SSL_free(clientssl);
4649     SSL_CTX_free(sctx);
4650     SSL_CTX_free(cctx);
4651     return testresult;
4652 }
4653 
4654 
4655 # ifndef OPENSSL_NO_TLS1_2
4656 /*
4657  * Test that a server attempting to read early data can handle a connection
4658  * from a TLSv1.2 client.
4659  */
test_early_data_tls1_2(int idx)4660 static int test_early_data_tls1_2(int idx)
4661 {
4662     SSL_CTX *cctx = NULL, *sctx = NULL;
4663     SSL *clientssl = NULL, *serverssl = NULL;
4664     int testresult = 0;
4665     unsigned char buf[20];
4666     size_t readbytes, written;
4667 
4668     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4669                                         &serverssl, NULL, idx,
4670                                         SHA384_DIGEST_LENGTH)))
4671         goto end;
4672 
4673     /* Write some data - should block due to handshake with server */
4674     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
4675     SSL_set_connect_state(clientssl);
4676     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4677         goto end;
4678 
4679     /*
4680      * Server should do TLSv1.2 handshake. First it will block waiting for more
4681      * messages from client after ServerDone. Then SSL_read_early_data should
4682      * finish and detect that early data has not been sent
4683      */
4684     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4685                                          &readbytes),
4686                      SSL_READ_EARLY_DATA_ERROR))
4687         goto end;
4688 
4689     /*
4690      * Continue writing the message we started earlier. Will still block waiting
4691      * for the CCS/Finished from server
4692      */
4693     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4694             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4695                                                 &readbytes),
4696                             SSL_READ_EARLY_DATA_FINISH)
4697             || !TEST_size_t_eq(readbytes, 0)
4698             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4699                             SSL_EARLY_DATA_NOT_SENT))
4700         goto end;
4701 
4702     /* Continue writing the message we started earlier */
4703     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4704             || !TEST_size_t_eq(written, strlen(MSG1))
4705             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4706                             SSL_EARLY_DATA_NOT_SENT)
4707             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4708             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4709             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
4710             || !TEST_size_t_eq(written, strlen(MSG2))
4711             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
4712             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4713         goto end;
4714 
4715     testresult = 1;
4716 
4717  end:
4718     SSL_SESSION_free(clientpsk);
4719     SSL_SESSION_free(serverpsk);
4720     clientpsk = serverpsk = NULL;
4721     SSL_free(serverssl);
4722     SSL_free(clientssl);
4723     SSL_CTX_free(sctx);
4724     SSL_CTX_free(cctx);
4725 
4726     return testresult;
4727 }
4728 # endif /* OPENSSL_NO_TLS1_2 */
4729 
4730 /*
4731  * Test configuring the TLSv1.3 ciphersuites
4732  *
4733  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
4734  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
4735  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
4736  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
4737  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4738  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4739  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
4740  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
4741  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
4742  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
4743  */
test_set_ciphersuite(int idx)4744 static int test_set_ciphersuite(int idx)
4745 {
4746     SSL_CTX *cctx = NULL, *sctx = NULL;
4747     SSL *clientssl = NULL, *serverssl = NULL;
4748     int testresult = 0;
4749 
4750     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4751                                        TLS_client_method(), TLS1_VERSION, 0,
4752                                        &sctx, &cctx, cert, privkey))
4753             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4754                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
4755         goto end;
4756 
4757     if (idx >=4 && idx <= 7) {
4758         /* SSL_CTX explicit cipher list */
4759         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
4760             goto end;
4761     }
4762 
4763     if (idx == 0 || idx == 4) {
4764         /* Default ciphersuite */
4765         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4766                                                 "TLS_AES_128_GCM_SHA256")))
4767             goto end;
4768     } else if (idx == 1 || idx == 5) {
4769         /* Non default ciphersuite */
4770         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4771                                                 "TLS_AES_128_CCM_SHA256")))
4772             goto end;
4773     }
4774 
4775     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4776                                           &clientssl, NULL, NULL)))
4777         goto end;
4778 
4779     if (idx == 8 || idx == 9) {
4780         /* SSL explicit cipher list */
4781         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
4782             goto end;
4783     }
4784 
4785     if (idx == 2 || idx == 6 || idx == 8) {
4786         /* Default ciphersuite */
4787         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4788                                             "TLS_AES_128_GCM_SHA256")))
4789             goto end;
4790     } else if (idx == 3 || idx == 7 || idx == 9) {
4791         /* Non default ciphersuite */
4792         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4793                                             "TLS_AES_128_CCM_SHA256")))
4794             goto end;
4795     }
4796 
4797     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4798         goto end;
4799 
4800     testresult = 1;
4801 
4802  end:
4803     SSL_free(serverssl);
4804     SSL_free(clientssl);
4805     SSL_CTX_free(sctx);
4806     SSL_CTX_free(cctx);
4807 
4808     return testresult;
4809 }
4810 
test_ciphersuite_change(void)4811 static int test_ciphersuite_change(void)
4812 {
4813     SSL_CTX *cctx = NULL, *sctx = NULL;
4814     SSL *clientssl = NULL, *serverssl = NULL;
4815     SSL_SESSION *clntsess = NULL;
4816     int testresult = 0;
4817     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
4818 
4819     /* Create a session based on SHA-256 */
4820     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4821                                        TLS_client_method(), TLS1_VERSION, 0,
4822                                        &sctx, &cctx, cert, privkey))
4823             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4824                                                    "TLS_AES_128_GCM_SHA256:"
4825                                                    "TLS_AES_256_GCM_SHA384:"
4826                                                    "TLS_AES_128_CCM_SHA256"))
4827             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4828                                                    "TLS_AES_128_GCM_SHA256")))
4829         goto end;
4830 
4831     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4832                                       NULL, NULL))
4833             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4834                                                 SSL_ERROR_NONE)))
4835         goto end;
4836 
4837     clntsess = SSL_get1_session(clientssl);
4838     /* Save for later */
4839     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
4840     SSL_shutdown(clientssl);
4841     SSL_shutdown(serverssl);
4842     SSL_free(serverssl);
4843     SSL_free(clientssl);
4844     serverssl = clientssl = NULL;
4845 
4846     /* Check we can resume a session with a different SHA-256 ciphersuite */
4847     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4848                                             "TLS_AES_128_CCM_SHA256"))
4849             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4850                                              &clientssl, NULL, NULL))
4851             || !TEST_true(SSL_set_session(clientssl, clntsess))
4852             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4853                                                 SSL_ERROR_NONE))
4854             || !TEST_true(SSL_session_reused(clientssl)))
4855         goto end;
4856 
4857     SSL_SESSION_free(clntsess);
4858     clntsess = SSL_get1_session(clientssl);
4859     SSL_shutdown(clientssl);
4860     SSL_shutdown(serverssl);
4861     SSL_free(serverssl);
4862     SSL_free(clientssl);
4863     serverssl = clientssl = NULL;
4864 
4865     /*
4866      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
4867      * succeeds but does not resume.
4868      */
4869     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4870             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4871                                              NULL, NULL))
4872             || !TEST_true(SSL_set_session(clientssl, clntsess))
4873             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4874                                                 SSL_ERROR_SSL))
4875             || !TEST_false(SSL_session_reused(clientssl)))
4876         goto end;
4877 
4878     SSL_SESSION_free(clntsess);
4879     clntsess = NULL;
4880     SSL_shutdown(clientssl);
4881     SSL_shutdown(serverssl);
4882     SSL_free(serverssl);
4883     SSL_free(clientssl);
4884     serverssl = clientssl = NULL;
4885 
4886     /* Create a session based on SHA384 */
4887     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4888             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4889                                           &clientssl, NULL, NULL))
4890             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4891                                                 SSL_ERROR_NONE)))
4892         goto end;
4893 
4894     clntsess = SSL_get1_session(clientssl);
4895     SSL_shutdown(clientssl);
4896     SSL_shutdown(serverssl);
4897     SSL_free(serverssl);
4898     SSL_free(clientssl);
4899     serverssl = clientssl = NULL;
4900 
4901     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4902                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
4903             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4904                                                    "TLS_AES_256_GCM_SHA384"))
4905             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4906                                              NULL, NULL))
4907             || !TEST_true(SSL_set_session(clientssl, clntsess))
4908                /*
4909                 * We use SSL_ERROR_WANT_READ below so that we can pause the
4910                 * connection after the initial ClientHello has been sent to
4911                 * enable us to make some session changes.
4912                 */
4913             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4914                                                 SSL_ERROR_WANT_READ)))
4915         goto end;
4916 
4917     /* Trick the client into thinking this session is for a different digest */
4918     clntsess->cipher = aes_128_gcm_sha256;
4919     clntsess->cipher_id = clntsess->cipher->id;
4920 
4921     /*
4922      * Continue the previously started connection. Server has selected a SHA-384
4923      * ciphersuite, but client thinks the session is for SHA-256, so it should
4924      * bail out.
4925      */
4926     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4927                                                 SSL_ERROR_SSL))
4928             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4929                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4930         goto end;
4931 
4932     testresult = 1;
4933 
4934  end:
4935     SSL_SESSION_free(clntsess);
4936     SSL_free(serverssl);
4937     SSL_free(clientssl);
4938     SSL_CTX_free(sctx);
4939     SSL_CTX_free(cctx);
4940 
4941     return testresult;
4942 }
4943 
4944 /*
4945  * Test TLSv1.3 Key exchange
4946  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4947  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4948  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4949  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4950  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4951  * Test 5 = Test NID_X448 with TLSv1.3 client and server
4952  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4953  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4954  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4955  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4956  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4957  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4958  * Test 12 = Test all ML-KEM with TLSv1.3 client and server
4959  * Test 13 = Test MLKEM512
4960  * Test 14 = Test MLKEM768
4961  * Test 15 = Test MLKEM1024
4962  * Test 16 = Test X25519MLKEM768
4963  * Test 17 = Test SecP256r1MLKEM768
4964  * Test 18 = Test SecP384r1MLKEM1024
4965  * Test 19 = Test all ML-KEM with TLSv1.2 client and server
4966  * Test 20 = Test all FFDHE with TLSv1.2 client and server
4967  * Test 21 = Test all ECDHE with TLSv1.2 client and server
4968  */
4969 # ifndef OPENSSL_NO_EC
4970 static int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
4971                                    NID_secp521r1,
4972 #  ifndef OPENSSL_NO_ECX
4973                                    NID_X25519, NID_X448
4974 #  endif
4975                                    };
4976 # endif
4977 # ifndef OPENSSL_NO_DH
4978 static int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4979                                    NID_ffdhe6144, NID_ffdhe8192};
4980 # endif
test_key_exchange(int idx)4981 static int test_key_exchange(int idx)
4982 {
4983     SSL_CTX *sctx = NULL, *cctx = NULL;
4984     SSL *serverssl = NULL, *clientssl = NULL;
4985     int testresult = 0;
4986     int kexch_alg = NID_undef;
4987     int *kexch_groups = &kexch_alg;
4988     int kexch_groups_size = 1;
4989     int max_version = TLS1_3_VERSION;
4990     char *kexch_name0 = NULL;
4991     const char *kexch_names = NULL;
4992     int shared_group0;
4993 
4994     switch (idx) {
4995 # ifndef OPENSSL_NO_EC
4996 # ifndef OPENSSL_NO_TLS1_2
4997         case 21:
4998             max_version = TLS1_2_VERSION;
4999 # endif
5000             /* Fall through */
5001         case 0:
5002             kexch_groups = ecdhe_kexch_groups;
5003             kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
5004             kexch_name0 = "secp256r1";
5005             break;
5006         case 1:
5007             kexch_alg = NID_X9_62_prime256v1;
5008             kexch_name0 = "secp256r1";
5009             break;
5010         case 2:
5011             kexch_alg = NID_secp384r1;
5012             kexch_name0 = "secp384r1";
5013             break;
5014         case 3:
5015             kexch_alg = NID_secp521r1;
5016             kexch_name0 = "secp521r1";
5017             break;
5018 #  ifndef OPENSSL_NO_ECX
5019         case 4:
5020             if (is_fips)
5021                 return TEST_skip("X25519 might not be supported by fips provider.");
5022             kexch_alg = NID_X25519;
5023             kexch_name0 = "x25519";
5024             break;
5025         case 5:
5026             if (is_fips)
5027                 return TEST_skip("X448 might not be supported by fips provider.");
5028             kexch_alg = NID_X448;
5029             kexch_name0 = "x448";
5030             break;
5031 #  endif
5032 # endif
5033 # ifndef OPENSSL_NO_DH
5034 # ifndef OPENSSL_NO_TLS1_2
5035         case 20:
5036             max_version = TLS1_2_VERSION;
5037             kexch_name0 = "ffdhe2048";
5038 # endif
5039             /* Fall through */
5040         case 6:
5041             kexch_groups = ffdhe_kexch_groups;
5042             kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
5043             kexch_name0 = "ffdhe2048";
5044             break;
5045         case 7:
5046             kexch_alg = NID_ffdhe2048;
5047             kexch_name0 = "ffdhe2048";
5048             break;
5049         case 8:
5050             kexch_alg = NID_ffdhe3072;
5051             kexch_name0 = "ffdhe3072";
5052             break;
5053         case 9:
5054             kexch_alg = NID_ffdhe4096;
5055             kexch_name0 = "ffdhe4096";
5056             break;
5057         case 10:
5058             kexch_alg = NID_ffdhe6144;
5059             kexch_name0 = "ffdhe6144";
5060             break;
5061         case 11:
5062             kexch_alg = NID_ffdhe8192;
5063             kexch_name0 = "ffdhe8192";
5064             break;
5065 # endif
5066 # ifndef OPENSSL_NO_ML_KEM
5067 #  if !defined(OPENSSL_NO_TLS1_2)
5068         case 19:
5069             max_version = TLS1_2_VERSION;
5070 #   if !defined(OPENSSL_NO_EC)
5071             /* Set at least one EC group so the handshake completes */
5072             kexch_names = "MLKEM512:MLKEM768:MLKEM1024:secp256r1";
5073 #   elif !defined(OPENSSL_NO_DH)
5074             kexch_names = "MLKEM512:MLKEM768:MLKEM1024";
5075 #   else
5076             /* With neither EC nor DH TLS 1.2 can't happen */
5077             return 1;
5078 #   endif
5079 #  endif
5080             /* Fall through */
5081         case 12:
5082             kexch_groups = NULL;
5083             if (kexch_names == NULL)
5084                 kexch_names = "MLKEM512:MLKEM768:MLKEM1024";
5085             kexch_name0 = "MLKEM512";
5086             break;
5087         case 13:
5088             kexch_groups = NULL;
5089             kexch_name0 = "MLKEM512";
5090             kexch_names = kexch_name0;
5091             break;
5092         case 14:
5093             kexch_groups = NULL;
5094             kexch_name0 = "MLKEM768";
5095             kexch_names = kexch_name0;
5096             break;
5097         case 15:
5098             kexch_groups = NULL;
5099             kexch_name0 = "MLKEM1024";
5100             kexch_names = kexch_name0;
5101             break;
5102 #  ifndef OPENSSL_NO_EC
5103 #   ifndef OPENSSL_NO_ECX
5104         case 16:
5105             kexch_groups = NULL;
5106             kexch_name0 = "X25519MLKEM768";
5107             kexch_names = kexch_name0;
5108             break;
5109 #   endif
5110         case 17:
5111             kexch_groups = NULL;
5112             kexch_name0 = "SecP256r1MLKEM768";
5113             kexch_names = kexch_name0;
5114             break;
5115         case 18:
5116             kexch_groups = NULL;
5117             kexch_name0 = "SecP384r1MLKEM1024";
5118             kexch_names = kexch_name0;
5119             break;
5120 #  endif
5121 # endif
5122         default:
5123             /* We're skipping this test */
5124             return 1;
5125     }
5126 
5127     if (is_fips && fips_provider_version_lt(libctx, 3, 5, 0)
5128             && idx >= 12 && idx <= 19)
5129         return TEST_skip("ML-KEM not supported in this version of fips provider");
5130 
5131     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5132                                        TLS_client_method(), TLS1_VERSION,
5133                                        max_version, &sctx, &cctx, cert,
5134                                        privkey)))
5135         goto end;
5136 
5137     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
5138                    TLS1_3_RFC_AES_128_GCM_SHA256)))
5139         goto end;
5140 
5141     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5142                    TLS1_3_RFC_AES_128_GCM_SHA256)))
5143         goto end;
5144 
5145     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5146                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5147                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5148             || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5149         goto end;
5150 
5151     /*
5152      * Must include an EC ciphersuite so that we send supported groups in
5153      * TLSv1.2
5154      */
5155 # ifndef OPENSSL_NO_TLS1_2
5156     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5157                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5158                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5159         goto end;
5160 # endif
5161 
5162     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5163                                              NULL, NULL)))
5164         goto end;
5165 
5166     if (kexch_groups != NULL) {
5167         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
5168             || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
5169             goto end;
5170     } else {
5171         if (!TEST_true(SSL_set1_groups_list(serverssl, kexch_names))
5172             || !TEST_true(SSL_set1_groups_list(clientssl, kexch_names)))
5173             goto end;
5174     }
5175 
5176     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5177         goto end;
5178 
5179     /*
5180      * If the handshake succeeds the negotiated kexch alg should be the first
5181      * one in configured, except in the case of "all" FFDHE and "all" ML-KEM
5182      * groups (idx == 19, 20), which are TLSv1.3 only so we expect no shared
5183      * group to exist.
5184      */
5185     shared_group0 = SSL_get_shared_group(serverssl, 0);
5186     switch (idx) {
5187     case 19:
5188 # if !defined(OPENSSL_NO_EC)
5189         /* MLKEM + TLS 1.2 and no DH => "secp526r1" */
5190         if (!TEST_int_eq(shared_group0, NID_X9_62_prime256v1))
5191             goto end;
5192         break;
5193 # endif
5194         /* Fall through */
5195     case 20:
5196         if (!TEST_int_eq(shared_group0, 0))
5197             goto end;
5198         break;
5199     default:
5200         if (kexch_groups != NULL
5201             && !TEST_int_eq(shared_group0, kexch_groups[0]))
5202             goto end;
5203         if (!TEST_str_eq(SSL_group_to_name(serverssl, shared_group0),
5204                          kexch_name0))
5205             goto end;
5206         if (!TEST_str_eq(SSL_get0_group_name(serverssl), kexch_name0)
5207             || !TEST_str_eq(SSL_get0_group_name(clientssl), kexch_name0))
5208             goto end;
5209         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), shared_group0))
5210             goto end;
5211         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), shared_group0))
5212             goto end;
5213         break;
5214     }
5215 
5216     testresult = 1;
5217  end:
5218     SSL_free(serverssl);
5219     SSL_free(clientssl);
5220     SSL_CTX_free(sctx);
5221     SSL_CTX_free(cctx);
5222     return testresult;
5223 }
5224 
5225 # if !defined(OPENSSL_NO_TLS1_2) \
5226      && !defined(OPENSSL_NO_EC)  \
5227      && !defined(OPENSSL_NO_DH)
set_ssl_groups(SSL * serverssl,SSL * clientssl,int clientmulti,int isecdhe,int idx)5228 static int set_ssl_groups(SSL *serverssl, SSL *clientssl, int clientmulti,
5229                           int isecdhe, int idx)
5230 {
5231     int kexch_alg;
5232     int *kexch_groups = &kexch_alg;
5233     int numec, numff;
5234 
5235     numec = OSSL_NELEM(ecdhe_kexch_groups);
5236     numff = OSSL_NELEM(ffdhe_kexch_groups);
5237     if (isecdhe)
5238         kexch_alg = ecdhe_kexch_groups[idx];
5239     else
5240         kexch_alg = ffdhe_kexch_groups[idx];
5241 
5242     if (clientmulti) {
5243         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, 1)))
5244             return 0;
5245         if (isecdhe) {
5246             if (!TEST_true(SSL_set1_groups(clientssl, ecdhe_kexch_groups,
5247                                            numec)))
5248                 return 0;
5249         } else {
5250             if (!TEST_true(SSL_set1_groups(clientssl, ffdhe_kexch_groups,
5251                                            numff)))
5252                 return 0;
5253         }
5254     } else {
5255         if (!TEST_true(SSL_set1_groups(clientssl, kexch_groups, 1)))
5256             return 0;
5257         if (isecdhe) {
5258             if (!TEST_true(SSL_set1_groups(serverssl, ecdhe_kexch_groups,
5259                                            numec)))
5260                 return 0;
5261         } else {
5262             if (!TEST_true(SSL_set1_groups(serverssl, ffdhe_kexch_groups,
5263                                            numff)))
5264                 return 0;
5265         }
5266     }
5267     return 1;
5268 }
5269 
5270 /*-
5271  * Test the SSL_get_negotiated_group() API across a battery of scenarios.
5272  * Run through both the ECDHE and FFDHE group lists used in the previous
5273  * test, for both TLS 1.2 and TLS 1.3, negotiating each group in turn,
5274  * confirming the expected result; then perform a resumption handshake
5275  * while offering the same group list, and another resumption handshake
5276  * offering a different group list.  The returned value should be the
5277  * negotiated group for the initial handshake; for TLS 1.3 resumption
5278  * handshakes the returned value will be negotiated on the resumption
5279  * handshake itself, but for TLS 1.2 resumption handshakes the value will
5280  * be cached in the session from the original handshake, regardless of what
5281  * was offered in the resumption ClientHello.
5282  *
5283  * Using E for the number of EC groups and F for the number of FF groups:
5284  * E tests of ECDHE with TLS 1.3, server only has one group
5285  * F tests of FFDHE with TLS 1.3, server only has one group
5286  * E tests of ECDHE with TLS 1.2, server only has one group
5287  * F tests of FFDHE with TLS 1.2, server only has one group
5288  * E tests of ECDHE with TLS 1.3, client sends only one group
5289  * F tests of FFDHE with TLS 1.3, client sends only one group
5290  * E tests of ECDHE with TLS 1.2, client sends only one group
5291  * F tests of FFDHE with TLS 1.2, client sends only one group
5292  */
test_negotiated_group(int idx)5293 static int test_negotiated_group(int idx)
5294 {
5295     int clientmulti, istls13, isecdhe, numec, numff, numgroups;
5296     int expectednid;
5297     SSL_CTX *sctx = NULL, *cctx = NULL;
5298     SSL *serverssl = NULL, *clientssl = NULL;
5299     SSL_SESSION *origsess = NULL;
5300     int testresult = 0;
5301     int kexch_alg;
5302     int max_version = TLS1_3_VERSION;
5303 
5304     numec = OSSL_NELEM(ecdhe_kexch_groups);
5305     numff = OSSL_NELEM(ffdhe_kexch_groups);
5306     numgroups = numec + numff;
5307     clientmulti = (idx < 2 * numgroups);
5308     idx = idx % (2 * numgroups);
5309     istls13 = (idx < numgroups);
5310     idx = idx % numgroups;
5311     isecdhe = (idx < numec);
5312     if (!isecdhe)
5313         idx -= numec;
5314     /* Now 'idx' is an index into ecdhe_kexch_groups or ffdhe_kexch_groups */
5315     if (isecdhe)
5316         kexch_alg = ecdhe_kexch_groups[idx];
5317     else
5318         kexch_alg = ffdhe_kexch_groups[idx];
5319     /* We expect nothing for the unimplemented TLS 1.2 FFDHE named groups */
5320     if (!istls13 && !isecdhe)
5321         expectednid = NID_undef;
5322     else
5323         expectednid = kexch_alg;
5324 
5325     if (is_fips && (kexch_alg == NID_X25519 || kexch_alg == NID_X448))
5326         return TEST_skip("X25519 and X448 might not be available in fips provider.");
5327 
5328     if (!istls13)
5329         max_version = TLS1_2_VERSION;
5330 
5331     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5332                                        TLS_client_method(), TLS1_VERSION,
5333                                        max_version, &sctx, &cctx, cert,
5334                                        privkey)))
5335         goto end;
5336 
5337     /*
5338      * Force (EC)DHE ciphers for TLS 1.2.
5339      * Be sure to enable auto tmp DH so that FFDHE can succeed.
5340      */
5341     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5342                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5343                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5344             || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5345         goto end;
5346     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5347                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5348                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5349         goto end;
5350 
5351     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5352                                              NULL, NULL)))
5353         goto end;
5354 
5355     if (!TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe,
5356                                   idx)))
5357         goto end;
5358 
5359     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5360         goto end;
5361 
5362     /* Initial handshake; always the configured one */
5363     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5364             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5365         goto end;
5366 
5367     if (!TEST_ptr((origsess = SSL_get1_session(clientssl))))
5368         goto end;
5369 
5370     SSL_shutdown(clientssl);
5371     SSL_shutdown(serverssl);
5372     SSL_free(serverssl);
5373     SSL_free(clientssl);
5374     serverssl = clientssl = NULL;
5375 
5376     /* First resumption attempt; use the same config as initial handshake */
5377     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5378                                              NULL, NULL))
5379             || !TEST_true(SSL_set_session(clientssl, origsess))
5380             || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5381                                          isecdhe, idx)))
5382         goto end;
5383 
5384     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5385             || !TEST_true(SSL_session_reused(clientssl)))
5386         goto end;
5387 
5388     /* Still had better agree, since nothing changed... */
5389     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5390             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5391         goto end;
5392 
5393     SSL_shutdown(clientssl);
5394     SSL_shutdown(serverssl);
5395     SSL_free(serverssl);
5396     SSL_free(clientssl);
5397     serverssl = clientssl = NULL;
5398 
5399     /*-
5400      * Second resumption attempt
5401      * The party that picks one group changes it, which we effectuate by
5402      * changing 'idx' and updating what we expect.
5403      */
5404     if (idx == 0)
5405         idx = 1;
5406     else
5407         idx--;
5408     if (istls13) {
5409         if (isecdhe)
5410             expectednid = ecdhe_kexch_groups[idx];
5411         else
5412             expectednid = ffdhe_kexch_groups[idx];
5413         /* Verify that we are changing what we expect. */
5414         if (!TEST_int_ne(expectednid, kexch_alg))
5415             goto end;
5416     } else {
5417         /* TLS 1.2 only supports named groups for ECDHE. */
5418         if (isecdhe)
5419             expectednid = kexch_alg;
5420         else
5421             expectednid = 0;
5422     }
5423     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5424                                              NULL, NULL))
5425             || !TEST_true(SSL_set_session(clientssl, origsess))
5426             || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5427                                          isecdhe, idx)))
5428         goto end;
5429 
5430     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5431             || !TEST_true(SSL_session_reused(clientssl)))
5432         goto end;
5433 
5434     /* Check that we get what we expected */
5435     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5436             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5437         goto end;
5438 
5439     testresult = 1;
5440  end:
5441     SSL_free(serverssl);
5442     SSL_free(clientssl);
5443     SSL_CTX_free(sctx);
5444     SSL_CTX_free(cctx);
5445     SSL_SESSION_free(origsess);
5446     return testresult;
5447 }
5448 # endif /* !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) */
5449 
5450 /*
5451  * Test TLSv1.3 Cipher Suite
5452  * Test 0 = Set TLS1.3 cipher on context
5453  * Test 1 = Set TLS1.3 cipher on SSL
5454  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
5455  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
5456  */
test_tls13_ciphersuite(int idx)5457 static int test_tls13_ciphersuite(int idx)
5458 {
5459     SSL_CTX *sctx = NULL, *cctx = NULL;
5460     SSL *serverssl = NULL, *clientssl = NULL;
5461     static const struct {
5462         const char *ciphername;
5463         int fipscapable;
5464         int low_security;
5465     } t13_ciphers[] = {
5466         { TLS1_3_RFC_AES_128_GCM_SHA256, 1, 0 },
5467         { TLS1_3_RFC_AES_256_GCM_SHA384, 1, 0 },
5468         { TLS1_3_RFC_AES_128_CCM_SHA256, 1, 0 },
5469 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5470         { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5471         { TLS1_3_RFC_AES_256_GCM_SHA384
5472           ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5473 # endif
5474         /* CCM8 ciphers are considered low security due to their short tag */
5475         { TLS1_3_RFC_AES_128_CCM_8_SHA256
5476           ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1, 1 },
5477 # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
5478         /* Integrity-only cipher do not provide any confidentiality */
5479         { TLS1_3_RFC_SHA256_SHA256, 0, 1 },
5480         { TLS1_3_RFC_SHA384_SHA384, 0, 1 }
5481 # endif
5482     };
5483     const char *t13_cipher = NULL;
5484     const char *t12_cipher = NULL;
5485     const char *negotiated_scipher;
5486     const char *negotiated_ccipher;
5487     int set_at_ctx = 0;
5488     int set_at_ssl = 0;
5489     int testresult = 0;
5490     int max_ver;
5491     size_t i;
5492 
5493     switch (idx) {
5494         case 0:
5495             set_at_ctx = 1;
5496             break;
5497         case 1:
5498             set_at_ssl = 1;
5499             break;
5500         case 2:
5501             set_at_ctx = 1;
5502             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5503             break;
5504         case 3:
5505             set_at_ssl = 1;
5506             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5507             break;
5508     }
5509 
5510     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
5511 # ifdef OPENSSL_NO_TLS1_2
5512         if (max_ver == TLS1_2_VERSION)
5513             continue;
5514 # endif
5515         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
5516             if (is_fips && !t13_ciphers[i].fipscapable)
5517                 continue;
5518             t13_cipher = t13_ciphers[i].ciphername;
5519             if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5520                                                TLS_client_method(),
5521                                                TLS1_VERSION, max_ver,
5522                                                &sctx, &cctx, cert, privkey)))
5523                 goto end;
5524 
5525             if (t13_ciphers[i].low_security) {
5526                 SSL_CTX_set_security_level(sctx, 0);
5527                 SSL_CTX_set_security_level(cctx, 0);
5528             }
5529 
5530             if (set_at_ctx) {
5531                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
5532                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
5533                     goto end;
5534                 if (t12_cipher != NULL) {
5535                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
5536                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
5537                                                               t12_cipher)))
5538                         goto end;
5539                 }
5540             }
5541 
5542             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5543                                               &clientssl, NULL, NULL)))
5544                 goto end;
5545 
5546             if (set_at_ssl) {
5547                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
5548                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
5549                     goto end;
5550                 if (t12_cipher != NULL) {
5551                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
5552                         || !TEST_true(SSL_set_cipher_list(clientssl,
5553                                                           t12_cipher)))
5554                         goto end;
5555                 }
5556             }
5557 
5558             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5559                                                  SSL_ERROR_NONE)))
5560                 goto end;
5561 
5562             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5563                                                                  serverssl));
5564             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5565                                                                  clientssl));
5566             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
5567                 goto end;
5568 
5569             /*
5570              * TEST_strn_eq is used below because t13_cipher can contain
5571              * multiple ciphersuites
5572              */
5573             if (max_ver == TLS1_3_VERSION
5574                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
5575                                  strlen(negotiated_scipher)))
5576                 goto end;
5577 
5578 # ifndef OPENSSL_NO_TLS1_2
5579             /* Below validation is not done when t12_cipher is NULL */
5580             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
5581                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
5582                 goto end;
5583 # endif
5584 
5585             SSL_free(serverssl);
5586             serverssl = NULL;
5587             SSL_free(clientssl);
5588             clientssl = NULL;
5589             SSL_CTX_free(sctx);
5590             sctx = NULL;
5591             SSL_CTX_free(cctx);
5592             cctx = NULL;
5593         }
5594     }
5595 
5596     testresult = 1;
5597  end:
5598     SSL_free(serverssl);
5599     SSL_free(clientssl);
5600     SSL_CTX_free(sctx);
5601     SSL_CTX_free(cctx);
5602     return testresult;
5603 }
5604 
5605 /*
5606  * Test TLSv1.3 PSKs
5607  * Test 0 = Test new style callbacks
5608  * Test 1 = Test both new and old style callbacks
5609  * Test 2 = Test old style callbacks
5610  * Test 3 = Test old style callbacks with no certificate
5611  */
test_tls13_psk(int idx)5612 static int test_tls13_psk(int idx)
5613 {
5614     SSL_CTX *sctx = NULL, *cctx = NULL;
5615     SSL *serverssl = NULL, *clientssl = NULL;
5616     const SSL_CIPHER *cipher = NULL;
5617     const unsigned char key[] = {
5618         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
5619         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5620         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
5621         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
5622     };
5623     int testresult = 0;
5624 
5625     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5626                                        TLS_client_method(), TLS1_VERSION, 0,
5627                                        &sctx, &cctx, idx == 3 ? NULL : cert,
5628                                        idx == 3 ? NULL : privkey)))
5629         goto end;
5630 
5631     if (idx != 3) {
5632         /*
5633          * We use a ciphersuite with SHA256 to ease testing old style PSK
5634          * callbacks which will always default to SHA256. This should not be
5635          * necessary if we have no cert/priv key. In that case the server should
5636          * prefer SHA256 automatically.
5637          */
5638         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5639                                                 "TLS_AES_128_GCM_SHA256")))
5640             goto end;
5641     } else {
5642         /*
5643          * As noted above the server should prefer SHA256 automatically. However
5644          * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
5645          * code works even if we are testing with only the FIPS provider loaded.
5646          */
5647         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5648                                                 "TLS_AES_256_GCM_SHA384:"
5649                                                 "TLS_AES_128_GCM_SHA256")))
5650             goto end;
5651     }
5652 
5653     /*
5654      * Test 0: New style callbacks only
5655      * Test 1: New and old style callbacks (only the new ones should be used)
5656      * Test 2: Old style callbacks only
5657      */
5658     if (idx == 0 || idx == 1) {
5659         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
5660         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
5661     }
5662 #ifndef OPENSSL_NO_PSK
5663     if (idx >= 1) {
5664         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
5665         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
5666     }
5667 #endif
5668     srvid = pskid;
5669     use_session_cb_cnt = 0;
5670     find_session_cb_cnt = 0;
5671     psk_client_cb_cnt = 0;
5672     psk_server_cb_cnt = 0;
5673 
5674     if (idx != 3) {
5675         /*
5676          * Check we can create a connection if callback decides not to send a
5677          * PSK
5678          */
5679         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5680                                                  NULL, NULL))
5681                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5682                                                     SSL_ERROR_NONE))
5683                 || !TEST_false(SSL_session_reused(clientssl))
5684                 || !TEST_false(SSL_session_reused(serverssl)))
5685             goto end;
5686 
5687         if (idx == 0 || idx == 1) {
5688             if (!TEST_true(use_session_cb_cnt == 1)
5689                     || !TEST_true(find_session_cb_cnt == 0)
5690                        /*
5691                         * If no old style callback then below should be 0
5692                         * otherwise 1
5693                         */
5694                     || !TEST_true(psk_client_cb_cnt == idx)
5695                     || !TEST_true(psk_server_cb_cnt == 0))
5696                 goto end;
5697         } else {
5698             if (!TEST_true(use_session_cb_cnt == 0)
5699                     || !TEST_true(find_session_cb_cnt == 0)
5700                     || !TEST_true(psk_client_cb_cnt == 1)
5701                     || !TEST_true(psk_server_cb_cnt == 0))
5702                 goto end;
5703         }
5704 
5705         shutdown_ssl_connection(serverssl, clientssl);
5706         serverssl = clientssl = NULL;
5707         use_session_cb_cnt = psk_client_cb_cnt = 0;
5708     }
5709 
5710     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5711                                              NULL, NULL)))
5712         goto end;
5713 
5714     /* Create the PSK */
5715     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
5716     clientpsk = SSL_SESSION_new();
5717     if (!TEST_ptr(clientpsk)
5718             || !TEST_ptr(cipher)
5719             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
5720                                                       sizeof(key)))
5721             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
5722             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
5723                                                            TLS1_3_VERSION))
5724             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
5725         goto end;
5726     serverpsk = clientpsk;
5727 
5728     /* Check we can create a connection and the PSK is used */
5729     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5730             || !TEST_true(SSL_session_reused(clientssl))
5731             || !TEST_true(SSL_session_reused(serverssl)))
5732         goto end;
5733 
5734     if (idx == 0 || idx == 1) {
5735         if (!TEST_true(use_session_cb_cnt == 1)
5736                 || !TEST_true(find_session_cb_cnt == 1)
5737                 || !TEST_true(psk_client_cb_cnt == 0)
5738                 || !TEST_true(psk_server_cb_cnt == 0))
5739             goto end;
5740     } else {
5741         if (!TEST_true(use_session_cb_cnt == 0)
5742                 || !TEST_true(find_session_cb_cnt == 0)
5743                 || !TEST_true(psk_client_cb_cnt == 1)
5744                 || !TEST_true(psk_server_cb_cnt == 1))
5745             goto end;
5746     }
5747 
5748     shutdown_ssl_connection(serverssl, clientssl);
5749     serverssl = clientssl = NULL;
5750     use_session_cb_cnt = find_session_cb_cnt = 0;
5751     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5752 
5753     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5754                                              NULL, NULL)))
5755         goto end;
5756 
5757     /* Force an HRR */
5758 #if defined(OPENSSL_NO_EC)
5759     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
5760         goto end;
5761 #else
5762     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
5763         goto end;
5764 #endif
5765 
5766     /*
5767      * Check we can create a connection, the PSK is used and the callbacks are
5768      * called twice.
5769      */
5770     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5771             || !TEST_true(SSL_session_reused(clientssl))
5772             || !TEST_true(SSL_session_reused(serverssl)))
5773         goto end;
5774 
5775     if (idx == 0 || idx == 1) {
5776         if (!TEST_true(use_session_cb_cnt == 2)
5777                 || !TEST_true(find_session_cb_cnt == 2)
5778                 || !TEST_true(psk_client_cb_cnt == 0)
5779                 || !TEST_true(psk_server_cb_cnt == 0))
5780             goto end;
5781     } else {
5782         if (!TEST_true(use_session_cb_cnt == 0)
5783                 || !TEST_true(find_session_cb_cnt == 0)
5784                 || !TEST_true(psk_client_cb_cnt == 2)
5785                 || !TEST_true(psk_server_cb_cnt == 2))
5786             goto end;
5787     }
5788 
5789     shutdown_ssl_connection(serverssl, clientssl);
5790     serverssl = clientssl = NULL;
5791     use_session_cb_cnt = find_session_cb_cnt = 0;
5792     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5793 
5794     if (idx != 3) {
5795         /*
5796          * Check that if the server rejects the PSK we can still connect, but with
5797          * a full handshake
5798          */
5799         srvid = "Dummy Identity";
5800         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5801                                                  NULL, NULL))
5802                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5803                                                     SSL_ERROR_NONE))
5804                 || !TEST_false(SSL_session_reused(clientssl))
5805                 || !TEST_false(SSL_session_reused(serverssl)))
5806             goto end;
5807 
5808         if (idx == 0 || idx == 1) {
5809             if (!TEST_true(use_session_cb_cnt == 1)
5810                     || !TEST_true(find_session_cb_cnt == 1)
5811                     || !TEST_true(psk_client_cb_cnt == 0)
5812                        /*
5813                         * If no old style callback then below should be 0
5814                         * otherwise 1
5815                         */
5816                     || !TEST_true(psk_server_cb_cnt == idx))
5817                 goto end;
5818         } else {
5819             if (!TEST_true(use_session_cb_cnt == 0)
5820                     || !TEST_true(find_session_cb_cnt == 0)
5821                     || !TEST_true(psk_client_cb_cnt == 1)
5822                     || !TEST_true(psk_server_cb_cnt == 1))
5823                 goto end;
5824         }
5825 
5826         shutdown_ssl_connection(serverssl, clientssl);
5827         serverssl = clientssl = NULL;
5828     }
5829     testresult = 1;
5830 
5831  end:
5832     SSL_SESSION_free(clientpsk);
5833     SSL_SESSION_free(serverpsk);
5834     clientpsk = serverpsk = NULL;
5835     SSL_free(serverssl);
5836     SSL_free(clientssl);
5837     SSL_CTX_free(sctx);
5838     SSL_CTX_free(cctx);
5839     return testresult;
5840 }
5841 
5842 #ifndef OSSL_NO_USABLE_TLS1_3
5843 /*
5844  * Test TLS1.3 connection establishment succeeds with various configurations of
5845  * the options `SSL_OP_ALLOW_NO_DHE_KEX` and `SSL_OP_PREFER_NO_DHE_KEX`.
5846  * The verification of whether the right KEX mode is chosen is not covered by
5847  * this test but by `test_tls13kexmodes`.
5848  *
5849  * Tests (idx & 1): Server has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5850  * Tests (idx & 2): Server has `SSL_OP_PREFER_NO_DHE_KEX` set.
5851  * Tests (idx & 4): Client has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5852  */
test_tls13_no_dhe_kex(const int idx)5853 static int test_tls13_no_dhe_kex(const int idx)
5854 {
5855     SSL_CTX *sctx = NULL, *cctx = NULL;
5856     SSL *serverssl = NULL, *clientssl = NULL;
5857     int testresult = 0;
5858     size_t j;
5859     SSL_SESSION *saved_session;
5860 
5861     int server_allow_no_dhe = (idx & 1) != 0;
5862     int server_prefer_no_dhe = (idx & 2) != 0;
5863     int client_allow_no_dhe = (idx & 4) != 0;
5864 
5865     uint64_t server_options = 0
5866             | (server_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0)
5867             | (server_prefer_no_dhe ? SSL_OP_PREFER_NO_DHE_KEX : 0);
5868 
5869     uint64_t client_options = 0
5870             | (client_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0);
5871 
5872     new_called = 0;
5873     do_cache = 1;
5874 
5875     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5876                                        TLS_client_method(), TLS1_3_VERSION, 0,
5877                                        &sctx, &cctx, cert, privkey)))
5878         goto end;
5879 
5880     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
5881                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5882 
5883     SSL_CTX_set_options(sctx, server_options);
5884     SSL_CTX_set_options(cctx, client_options);
5885 
5886     SSL_CTX_sess_set_new_cb(cctx, new_cachesession_cb);
5887 
5888     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5889                                       &clientssl, NULL, NULL)))
5890         goto end;
5891 
5892     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5893                                          SSL_ERROR_NONE))
5894             /* Check we got the number of tickets we were expecting */
5895             || !TEST_int_eq(2, new_called))
5896         goto end;
5897 
5898     /* We'll reuse the last ticket. */
5899     saved_session = sesscache[new_called - 1];
5900 
5901     SSL_shutdown(clientssl);
5902     SSL_shutdown(serverssl);
5903     SSL_free(serverssl);
5904     SSL_free(clientssl);
5905     SSL_CTX_free(cctx);
5906     clientssl = serverssl = NULL;
5907     cctx = NULL;
5908 
5909     /*
5910      * Now we resume with the last ticket we created.
5911      */
5912 
5913     /* The server context already exists, so we only create the client. */
5914     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5915                                        TLS_client_method(), TLS1_3_VERSION, 0,
5916                                        NULL, &cctx, cert, privkey)))
5917         goto end;
5918 
5919     SSL_CTX_set_options(cctx, client_options);
5920 
5921     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5922                                       &clientssl, NULL, NULL))
5923             || !TEST_true(SSL_set_session(clientssl, saved_session)))
5924         goto end;
5925 
5926     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5927                                          SSL_ERROR_NONE)))
5928         goto end;
5929 
5930     /*
5931      * Make sure, the session was resumed.
5932      */
5933     if (!TEST_true(SSL_session_reused(clientssl)))
5934         goto end;
5935 
5936     SSL_shutdown(clientssl);
5937     SSL_shutdown(serverssl);
5938 
5939     testresult = 1;
5940 
5941  end:
5942     SSL_free(serverssl);
5943     SSL_free(clientssl);
5944     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
5945         SSL_SESSION_free(sesscache[j]);
5946         sesscache[j] = NULL;
5947     }
5948     SSL_CTX_free(sctx);
5949     SSL_CTX_free(cctx);
5950 
5951     return testresult;
5952 }
5953 #endif /* OSSL_NO_USABLE_TLS1_3 */
5954 
5955 static unsigned char cookie_magic_value[] = "cookie magic";
5956 
generate_cookie_callback(SSL * ssl,unsigned char * cookie,unsigned int * cookie_len)5957 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
5958                                     unsigned int *cookie_len)
5959 {
5960     /*
5961      * Not suitable as a real cookie generation function but good enough for
5962      * testing!
5963      */
5964     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
5965     *cookie_len = sizeof(cookie_magic_value) - 1;
5966 
5967     return 1;
5968 }
5969 
verify_cookie_callback(SSL * ssl,const unsigned char * cookie,unsigned int cookie_len)5970 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
5971                                   unsigned int cookie_len)
5972 {
5973     if (cookie_len == sizeof(cookie_magic_value) - 1
5974         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
5975         return 1;
5976 
5977     return 0;
5978 }
5979 
generate_stateless_cookie_callback(SSL * ssl,unsigned char * cookie,size_t * cookie_len)5980 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
5981                                         size_t *cookie_len)
5982 {
5983     unsigned int temp;
5984     int res = generate_cookie_callback(ssl, cookie, &temp);
5985     *cookie_len = temp;
5986     return res;
5987 }
5988 
verify_stateless_cookie_callback(SSL * ssl,const unsigned char * cookie,size_t cookie_len)5989 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
5990                                       size_t cookie_len)
5991 {
5992     return verify_cookie_callback(ssl, cookie, cookie_len);
5993 }
5994 
test_stateless(void)5995 static int test_stateless(void)
5996 {
5997     SSL_CTX *sctx = NULL, *cctx = NULL;
5998     SSL *serverssl = NULL, *clientssl = NULL;
5999     int testresult = 0;
6000 
6001     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6002                                        TLS_client_method(), TLS1_VERSION, 0,
6003                                        &sctx, &cctx, cert, privkey)))
6004         goto end;
6005 
6006     /* The arrival of CCS messages can confuse the test */
6007     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6008 
6009     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6010                                       NULL, NULL))
6011                /* Send the first ClientHello */
6012             || !TEST_false(create_ssl_connection(serverssl, clientssl,
6013                                                  SSL_ERROR_WANT_READ))
6014                /*
6015                 * This should fail with a -1 return because we have no callbacks
6016                 * set up
6017                 */
6018             || !TEST_int_eq(SSL_stateless(serverssl), -1))
6019         goto end;
6020 
6021     /* Fatal error so abandon the connection from this client */
6022     SSL_free(clientssl);
6023     clientssl = NULL;
6024 
6025     /* Set up the cookie generation and verification callbacks */
6026     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
6027     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
6028 
6029     /*
6030      * Create a new connection from the client (we can reuse the server SSL
6031      * object).
6032      */
6033     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6034                                              NULL, NULL))
6035                /* Send the first ClientHello */
6036             || !TEST_false(create_ssl_connection(serverssl, clientssl,
6037                                                 SSL_ERROR_WANT_READ))
6038                /* This should fail because there is no cookie */
6039             || !TEST_int_eq(SSL_stateless(serverssl), 0))
6040         goto end;
6041 
6042     /* Abandon the connection from this client */
6043     SSL_free(clientssl);
6044     clientssl = NULL;
6045 
6046     /*
6047      * Now create a connection from a new client but with the same server SSL
6048      * object
6049      */
6050     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6051                                              NULL, NULL))
6052                /* Send the first ClientHello */
6053             || !TEST_false(create_ssl_connection(serverssl, clientssl,
6054                                                 SSL_ERROR_WANT_READ))
6055                /* This should fail because there is no cookie */
6056             || !TEST_int_eq(SSL_stateless(serverssl), 0)
6057                /* Send the second ClientHello */
6058             || !TEST_false(create_ssl_connection(serverssl, clientssl,
6059                                                 SSL_ERROR_WANT_READ))
6060                /* This should succeed because a cookie is now present */
6061             || !TEST_int_eq(SSL_stateless(serverssl), 1)
6062                /* Complete the connection */
6063             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6064                                                 SSL_ERROR_NONE)))
6065         goto end;
6066 
6067     shutdown_ssl_connection(serverssl, clientssl);
6068     serverssl = clientssl = NULL;
6069     testresult = 1;
6070 
6071  end:
6072     SSL_free(serverssl);
6073     SSL_free(clientssl);
6074     SSL_CTX_free(sctx);
6075     SSL_CTX_free(cctx);
6076     return testresult;
6077 
6078 }
6079 #endif /* OSSL_NO_USABLE_TLS1_3 */
6080 
6081 static int clntaddoldcb = 0;
6082 static int clntparseoldcb = 0;
6083 static int srvaddoldcb = 0;
6084 static int srvparseoldcb = 0;
6085 static int clntaddnewcb = 0;
6086 static int clntparsenewcb = 0;
6087 static int srvaddnewcb = 0;
6088 static int srvparsenewcb = 0;
6089 static int snicb = 0;
6090 
6091 #define TEST_EXT_TYPE1  0xff00
6092 
old_add_cb(SSL * s,unsigned int ext_type,const unsigned char ** out,size_t * outlen,int * al,void * add_arg)6093 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
6094                       size_t *outlen, int *al, void *add_arg)
6095 {
6096     int *server = (int *)add_arg;
6097     unsigned char *data;
6098 
6099     if (SSL_is_server(s))
6100         srvaddoldcb++;
6101     else
6102         clntaddoldcb++;
6103 
6104     if (*server != SSL_is_server(s)
6105             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
6106         return -1;
6107 
6108     *data = 1;
6109     *out = data;
6110     *outlen = sizeof(char);
6111     return 1;
6112 }
6113 
old_free_cb(SSL * s,unsigned int ext_type,const unsigned char * out,void * add_arg)6114 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
6115                         void *add_arg)
6116 {
6117     OPENSSL_free((unsigned char *)out);
6118 }
6119 
old_parse_cb(SSL * s,unsigned int ext_type,const unsigned char * in,size_t inlen,int * al,void * parse_arg)6120 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
6121                         size_t inlen, int *al, void *parse_arg)
6122 {
6123     int *server = (int *)parse_arg;
6124 
6125     if (SSL_is_server(s))
6126         srvparseoldcb++;
6127     else
6128         clntparseoldcb++;
6129 
6130     if (*server != SSL_is_server(s)
6131             || inlen != sizeof(char)
6132             || *in != 1)
6133         return -1;
6134 
6135     return 1;
6136 }
6137 
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)6138 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
6139                       const unsigned char **out, size_t *outlen, X509 *x,
6140                       size_t chainidx, int *al, void *add_arg)
6141 {
6142     int *server = (int *)add_arg;
6143     unsigned char *data;
6144 
6145     if (SSL_is_server(s))
6146         srvaddnewcb++;
6147     else
6148         clntaddnewcb++;
6149 
6150     if (*server != SSL_is_server(s)
6151             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
6152         return -1;
6153 
6154     *data = 1;
6155     *out = data;
6156     *outlen = sizeof(*data);
6157     return 1;
6158 }
6159 
new_free_cb(SSL * s,unsigned int ext_type,unsigned int context,const unsigned char * out,void * add_arg)6160 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
6161                         const unsigned char *out, void *add_arg)
6162 {
6163     OPENSSL_free((unsigned char *)out);
6164 }
6165 
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)6166 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
6167                         const unsigned char *in, size_t inlen, X509 *x,
6168                         size_t chainidx, int *al, void *parse_arg)
6169 {
6170     int *server = (int *)parse_arg;
6171 
6172     if (SSL_is_server(s))
6173         srvparsenewcb++;
6174     else
6175         clntparsenewcb++;
6176 
6177     if (*server != SSL_is_server(s)
6178             || inlen != sizeof(char) || *in != 1)
6179         return -1;
6180 
6181     return 1;
6182 }
6183 
sni_cb(SSL * s,int * al,void * arg)6184 static int sni_cb(SSL *s, int *al, void *arg)
6185 {
6186     SSL_CTX *ctx = (SSL_CTX *)arg;
6187 
6188     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
6189         *al = SSL_AD_INTERNAL_ERROR;
6190         return SSL_TLSEXT_ERR_ALERT_FATAL;
6191     }
6192     snicb++;
6193     return SSL_TLSEXT_ERR_OK;
6194 }
6195 
verify_cb(int preverify_ok,X509_STORE_CTX * x509_ctx)6196 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
6197 {
6198     return 1;
6199 }
6200 
6201 /*
6202  * Custom call back tests.
6203  * Test 0: Old style callbacks in TLSv1.2
6204  * Test 1: New style callbacks in TLSv1.2
6205  * Test 2: New style callbacks in TLSv1.2 with SNI
6206  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
6207  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
6208  * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
6209  */
test_custom_exts(int tst)6210 static int test_custom_exts(int tst)
6211 {
6212     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6213     SSL *clientssl = NULL, *serverssl = NULL;
6214     int testresult = 0;
6215     static int server = 1;
6216     static int client = 0;
6217     SSL_SESSION *sess = NULL;
6218     unsigned int context;
6219 
6220 #if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6221     /* Skip tests for TLSv1.2 and below in this case */
6222     if (tst < 3)
6223         return 1;
6224 #endif
6225 
6226     /* Reset callback counters */
6227     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
6228     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
6229     snicb = 0;
6230 
6231     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6232                                        TLS_client_method(), TLS1_VERSION, 0,
6233                                        &sctx, &cctx, cert, privkey)))
6234         goto end;
6235 
6236     if (tst == 2
6237             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
6238                                               TLS1_VERSION, 0,
6239                                               &sctx2, NULL, cert, privkey)))
6240         goto end;
6241 
6242 
6243     if (tst < 3) {
6244         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
6245         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
6246         if (sctx2 != NULL)
6247             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
6248     }
6249 
6250     if (tst == 5) {
6251         context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
6252                   | SSL_EXT_TLS1_3_CERTIFICATE;
6253         SSL_CTX_set_verify(sctx,
6254                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
6255                            verify_cb);
6256         if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
6257                                                       SSL_FILETYPE_PEM), 1)
6258                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
6259                                                             SSL_FILETYPE_PEM), 1)
6260                 || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
6261             goto end;
6262     } else if (tst == 4) {
6263         context = SSL_EXT_CLIENT_HELLO
6264                   | SSL_EXT_TLS1_2_SERVER_HELLO
6265                   | SSL_EXT_TLS1_3_SERVER_HELLO
6266                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
6267                   | SSL_EXT_TLS1_3_CERTIFICATE
6268                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
6269     } else {
6270         context = SSL_EXT_CLIENT_HELLO
6271                   | SSL_EXT_TLS1_2_SERVER_HELLO
6272                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
6273     }
6274 
6275     /* Create a client side custom extension */
6276     if (tst == 0) {
6277         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6278                                                      old_add_cb, old_free_cb,
6279                                                      &client, old_parse_cb,
6280                                                      &client)))
6281             goto end;
6282     } else {
6283         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
6284                                               new_add_cb, new_free_cb,
6285                                               &client, new_parse_cb, &client)))
6286             goto end;
6287     }
6288 
6289     /* Should not be able to add duplicates */
6290     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6291                                                   old_add_cb, old_free_cb,
6292                                                   &client, old_parse_cb,
6293                                                   &client))
6294             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
6295                                                   context, new_add_cb,
6296                                                   new_free_cb, &client,
6297                                                   new_parse_cb, &client)))
6298         goto end;
6299 
6300     /* Create a server side custom extension */
6301     if (tst == 0) {
6302         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6303                                                      old_add_cb, old_free_cb,
6304                                                      &server, old_parse_cb,
6305                                                      &server)))
6306             goto end;
6307     } else {
6308         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
6309                                               new_add_cb, new_free_cb,
6310                                               &server, new_parse_cb, &server)))
6311             goto end;
6312         if (sctx2 != NULL
6313                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
6314                                                      context, new_add_cb,
6315                                                      new_free_cb, &server,
6316                                                      new_parse_cb, &server)))
6317             goto end;
6318     }
6319 
6320     /* Should not be able to add duplicates */
6321     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6322                                                   old_add_cb, old_free_cb,
6323                                                   &server, old_parse_cb,
6324                                                   &server))
6325             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
6326                                                   context, new_add_cb,
6327                                                   new_free_cb, &server,
6328                                                   new_parse_cb, &server)))
6329         goto end;
6330 
6331     if (tst == 2) {
6332         /* Set up SNI */
6333         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
6334                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
6335             goto end;
6336     }
6337 
6338     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6339                                       &clientssl, NULL, NULL))
6340             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6341                                                 SSL_ERROR_NONE)))
6342         goto end;
6343 
6344     if (tst == 0) {
6345         if (clntaddoldcb != 1
6346                 || clntparseoldcb != 1
6347                 || srvaddoldcb != 1
6348                 || srvparseoldcb != 1)
6349             goto end;
6350     } else if (tst == 1 || tst == 2 || tst == 3) {
6351         if (clntaddnewcb != 1
6352                 || clntparsenewcb != 1
6353                 || srvaddnewcb != 1
6354                 || srvparsenewcb != 1
6355                 || (tst != 2 && snicb != 0)
6356                 || (tst == 2 && snicb != 1))
6357             goto end;
6358     } else if (tst == 5) {
6359         if (clntaddnewcb != 1
6360                 || clntparsenewcb != 1
6361                 || srvaddnewcb != 1
6362                 || srvparsenewcb != 1)
6363             goto end;
6364     } else {
6365         /* In this case there 2 NewSessionTicket messages created */
6366         if (clntaddnewcb != 1
6367                 || clntparsenewcb != 5
6368                 || srvaddnewcb != 5
6369                 || srvparsenewcb != 1)
6370             goto end;
6371     }
6372 
6373     sess = SSL_get1_session(clientssl);
6374     SSL_shutdown(clientssl);
6375     SSL_shutdown(serverssl);
6376     SSL_free(serverssl);
6377     SSL_free(clientssl);
6378     serverssl = clientssl = NULL;
6379 
6380     if (tst == 3 || tst == 5) {
6381         /* We don't bother with the resumption aspects for these tests */
6382         testresult = 1;
6383         goto end;
6384     }
6385 
6386     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6387                                       NULL, NULL))
6388             || !TEST_true(SSL_set_session(clientssl, sess))
6389             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6390                                                SSL_ERROR_NONE)))
6391         goto end;
6392 
6393     /*
6394      * For a resumed session we expect to add the ClientHello extension. For the
6395      * old style callbacks we ignore it on the server side because they set
6396      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
6397      * them.
6398      */
6399     if (tst == 0) {
6400         if (clntaddoldcb != 2
6401                 || clntparseoldcb != 1
6402                 || srvaddoldcb != 1
6403                 || srvparseoldcb != 1)
6404             goto end;
6405     } else if (tst == 1 || tst == 2 || tst == 3) {
6406         if (clntaddnewcb != 2
6407                 || clntparsenewcb != 2
6408                 || srvaddnewcb != 2
6409                 || srvparsenewcb != 2)
6410             goto end;
6411     } else {
6412         /*
6413          * No Certificate message extensions in the resumption handshake,
6414          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
6415          */
6416         if (clntaddnewcb != 2
6417                 || clntparsenewcb != 8
6418                 || srvaddnewcb != 8
6419                 || srvparsenewcb != 2)
6420             goto end;
6421     }
6422 
6423     testresult = 1;
6424 
6425 end:
6426     SSL_SESSION_free(sess);
6427     SSL_free(serverssl);
6428     SSL_free(clientssl);
6429     SSL_CTX_free(sctx2);
6430     SSL_CTX_free(sctx);
6431     SSL_CTX_free(cctx);
6432     return testresult;
6433 }
6434 
6435 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6436 
6437 #define  SYNTHV1CONTEXT     (SSL_EXT_TLS1_2_AND_BELOW_ONLY \
6438                              | SSL_EXT_CLIENT_HELLO \
6439                              | SSL_EXT_TLS1_2_SERVER_HELLO \
6440                              | SSL_EXT_IGNORE_ON_RESUMPTION)
6441 
6442 #define TLS13CONTEXT (SSL_EXT_TLS1_3_CERTIFICATE \
6443                       | SSL_EXT_TLS1_2_SERVER_HELLO \
6444                       | SSL_EXT_CLIENT_HELLO)
6445 
6446 #define SERVERINFO_CUSTOM                                 \
6447     0x00, (char)TLSEXT_TYPE_signed_certificate_timestamp, \
6448     0x00, 0x03,                                           \
6449     0x04, 0x05, 0x06                                      \
6450 
6451 static const unsigned char serverinfo_custom_tls13[] = {
6452     0x00, 0x00, (TLS13CONTEXT >> 8) & 0xff, TLS13CONTEXT & 0xff,
6453     SERVERINFO_CUSTOM
6454 };
6455 static const unsigned char serverinfo_custom_v2[] = {
6456     0x00, 0x00, (SYNTHV1CONTEXT >> 8) & 0xff,  SYNTHV1CONTEXT & 0xff,
6457     SERVERINFO_CUSTOM
6458 };
6459 static const unsigned char serverinfo_custom_v1[] = {
6460     SERVERINFO_CUSTOM
6461 };
6462 static const size_t serverinfo_custom_tls13_len = sizeof(serverinfo_custom_tls13);
6463 static const size_t serverinfo_custom_v2_len = sizeof(serverinfo_custom_v2);
6464 static const size_t serverinfo_custom_v1_len = sizeof(serverinfo_custom_v1);
6465 
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)6466 static int serverinfo_custom_parse_cb(SSL *s, unsigned int ext_type,
6467                                       unsigned int context,
6468                                       const unsigned char *in,
6469                                       size_t inlen, X509 *x,
6470                                       size_t chainidx, int *al,
6471                                       void *parse_arg)
6472 {
6473     const size_t len = serverinfo_custom_v1_len;
6474     const unsigned char *si = &serverinfo_custom_v1[len - 3];
6475     int *p_cb_result = (int*)parse_arg;
6476     *p_cb_result = TEST_mem_eq(in, inlen, si, 3);
6477     return 1;
6478 }
6479 
test_serverinfo_custom(const int idx)6480 static int test_serverinfo_custom(const int idx)
6481 {
6482     SSL_CTX *sctx = NULL, *cctx = NULL;
6483     SSL *clientssl = NULL, *serverssl = NULL;
6484     int testresult = 0;
6485     int cb_result = 0;
6486 
6487     /*
6488      * Following variables are set in the switch statement
6489      *  according to the test iteration.
6490      * Default values do not make much sense: test would fail with them.
6491      */
6492     int serverinfo_version = 0;
6493     int protocol_version = 0;
6494     unsigned int extension_context = 0;
6495     const unsigned char *si = NULL;
6496     size_t si_len = 0;
6497 
6498     const int call_use_serverinfo_ex = idx > 0;
6499     switch (idx) {
6500     case 0: /* FALLTHROUGH */
6501     case 1:
6502         serverinfo_version = SSL_SERVERINFOV1;
6503         protocol_version = TLS1_2_VERSION;
6504         extension_context = SYNTHV1CONTEXT;
6505         si = serverinfo_custom_v1;
6506         si_len = serverinfo_custom_v1_len;
6507         break;
6508     case 2:
6509         serverinfo_version = SSL_SERVERINFOV2;
6510         protocol_version = TLS1_2_VERSION;
6511         extension_context = SYNTHV1CONTEXT;
6512         si = serverinfo_custom_v2;
6513         si_len = serverinfo_custom_v2_len;
6514         break;
6515     case 3:
6516         serverinfo_version = SSL_SERVERINFOV2;
6517         protocol_version = TLS1_3_VERSION;
6518         extension_context = TLS13CONTEXT;
6519         si = serverinfo_custom_tls13;
6520         si_len = serverinfo_custom_tls13_len;
6521         break;
6522     }
6523 
6524     if (!TEST_true(create_ssl_ctx_pair(libctx,
6525                                        TLS_method(),
6526                                        TLS_method(),
6527                                        protocol_version,
6528                                        protocol_version,
6529                                        &sctx, &cctx, cert, privkey)))
6530         goto end;
6531 
6532     if (call_use_serverinfo_ex) {
6533         if (!TEST_true(SSL_CTX_use_serverinfo_ex(sctx, serverinfo_version,
6534                                                  si, si_len)))
6535             goto end;
6536     } else {
6537         if (!TEST_true(SSL_CTX_use_serverinfo(sctx, si, si_len)))
6538             goto end;
6539     }
6540 
6541     if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TLSEXT_TYPE_signed_certificate_timestamp,
6542                                           extension_context,
6543                                           NULL, NULL, NULL,
6544                                           serverinfo_custom_parse_cb,
6545                                           &cb_result))
6546         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6547                                          NULL, NULL))
6548         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6549                                             SSL_ERROR_NONE))
6550         || !TEST_int_eq(SSL_do_handshake(clientssl), 1))
6551         goto end;
6552 
6553     if (!TEST_true(cb_result))
6554         goto end;
6555 
6556     testresult = 1;
6557 
6558  end:
6559     SSL_free(serverssl);
6560     SSL_free(clientssl);
6561     SSL_CTX_free(sctx);
6562     SSL_CTX_free(cctx);
6563 
6564     return testresult;
6565 }
6566 #endif
6567 
6568 /*
6569  * Test that SSL_export_keying_material() produces expected results. There are
6570  * no test vectors so all we do is test that both sides of the communication
6571  * produce the same results for different protocol versions.
6572  */
6573 #define SMALL_LABEL_LEN 10
6574 #define LONG_LABEL_LEN  249
test_export_key_mat(int tst)6575 static int test_export_key_mat(int tst)
6576 {
6577     int testresult = 0;
6578     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6579     SSL *clientssl = NULL, *serverssl = NULL;
6580     const char label[LONG_LABEL_LEN + 1] = "test label";
6581     const unsigned char context[] = "context";
6582     const unsigned char *emptycontext = NULL;
6583     unsigned char longcontext[1280];
6584     int test_longcontext = fips_provider_version_ge(libctx, 3, 3, 0);
6585     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80], ckeymat4[80];
6586     unsigned char skeymat1[80], skeymat2[80], skeymat3[80], skeymat4[80];
6587     size_t labellen;
6588     const int protocols[] = {
6589         TLS1_VERSION,
6590         TLS1_1_VERSION,
6591         TLS1_2_VERSION,
6592         TLS1_3_VERSION,
6593         TLS1_3_VERSION,
6594         TLS1_3_VERSION
6595     };
6596 
6597 #ifdef OPENSSL_NO_TLS1
6598     if (tst == 0)
6599         return 1;
6600 #endif
6601 #ifdef OPENSSL_NO_TLS1_1
6602     if (tst == 1)
6603         return 1;
6604 #endif
6605     if (is_fips && (tst == 0 || tst == 1))
6606         return 1;
6607 #ifdef OPENSSL_NO_TLS1_2
6608     if (tst == 2)
6609         return 1;
6610 #endif
6611 #ifdef OSSL_NO_USABLE_TLS1_3
6612     if (tst >= 3)
6613         return 1;
6614 #endif
6615     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6616                                        TLS_client_method(), TLS1_VERSION, 0,
6617                                        &sctx, &cctx, cert, privkey)))
6618         goto end;
6619 
6620     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
6621     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
6622     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
6623     if ((protocols[tst] < TLS1_2_VERSION) &&
6624         (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0")
6625         || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
6626         goto end;
6627 
6628     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6629                                       NULL)))
6630         goto end;
6631 
6632     /*
6633      * Premature call of SSL_export_keying_material should just fail.
6634      */
6635     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6636                                                 sizeof(ckeymat1), label,
6637                                                 SMALL_LABEL_LEN + 1, context,
6638                                                 sizeof(context) - 1, 1), 0))
6639         goto end;
6640 
6641     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6642                                          SSL_ERROR_NONE)))
6643         goto end;
6644 
6645     if (tst == 5) {
6646         /*
6647          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
6648          * go over that.
6649          */
6650         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6651                                                     sizeof(ckeymat1), label,
6652                                                     LONG_LABEL_LEN + 1, context,
6653                                                     sizeof(context) - 1, 1), 0))
6654             goto end;
6655 
6656         testresult = 1;
6657         goto end;
6658     } else if (tst == 4) {
6659         labellen = LONG_LABEL_LEN;
6660     } else {
6661         labellen = SMALL_LABEL_LEN;
6662     }
6663 
6664     memset(longcontext, 1, sizeof(longcontext));
6665 
6666     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
6667                                                 sizeof(ckeymat1), label,
6668                                                 labellen, context,
6669                                                 sizeof(context) - 1, 1), 1)
6670             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
6671                                                        sizeof(ckeymat2), label,
6672                                                        labellen,
6673                                                        emptycontext,
6674                                                        0, 1), 1)
6675             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
6676                                                        sizeof(ckeymat3), label,
6677                                                        labellen,
6678                                                        NULL, 0, 0), 1)
6679             || (test_longcontext
6680                 && !TEST_int_eq(SSL_export_keying_material(clientssl,
6681                                                            ckeymat4,
6682                                                            sizeof(ckeymat4), label,
6683                                                            labellen,
6684                                                            longcontext,
6685                                                            sizeof(longcontext), 1),
6686                                 1))
6687             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
6688                                                        sizeof(skeymat1), label,
6689                                                        labellen,
6690                                                        context,
6691                                                        sizeof(context) -1, 1),
6692                             1)
6693             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
6694                                                        sizeof(skeymat2), label,
6695                                                        labellen,
6696                                                        emptycontext,
6697                                                        0, 1), 1)
6698             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
6699                                                        sizeof(skeymat3), label,
6700                                                        labellen,
6701                                                        NULL, 0, 0), 1)
6702             || (test_longcontext
6703                 && !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat4,
6704                                                            sizeof(skeymat4), label,
6705                                                            labellen,
6706                                                            longcontext,
6707                                                            sizeof(longcontext), 1),
6708                                 1))
6709                /*
6710                 * Check that both sides created the same key material with the
6711                 * same context.
6712                 */
6713             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6714                             sizeof(skeymat1))
6715                /*
6716                 * Check that both sides created the same key material with an
6717                 * empty context.
6718                 */
6719             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6720                             sizeof(skeymat2))
6721                /*
6722                 * Check that both sides created the same key material without a
6723                 * context.
6724                 */
6725             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
6726                             sizeof(skeymat3))
6727                /*
6728                 * Check that both sides created the same key material with a
6729                 * long context.
6730                 */
6731             || (test_longcontext
6732                 && !TEST_mem_eq(ckeymat4, sizeof(ckeymat4), skeymat4,
6733                                 sizeof(skeymat4)))
6734                /* Different contexts should produce different results */
6735             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6736                             sizeof(ckeymat2)))
6737         goto end;
6738 
6739     /*
6740      * Check that an empty context and no context produce different results in
6741      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
6742      */
6743     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
6744                                   sizeof(ckeymat3)))
6745             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
6746                                          sizeof(ckeymat3))))
6747         goto end;
6748 
6749     testresult = 1;
6750 
6751  end:
6752     SSL_free(serverssl);
6753     SSL_free(clientssl);
6754     SSL_CTX_free(sctx2);
6755     SSL_CTX_free(sctx);
6756     SSL_CTX_free(cctx);
6757 
6758     return testresult;
6759 }
6760 
6761 #ifndef OSSL_NO_USABLE_TLS1_3
6762 /*
6763  * Test that SSL_export_keying_material_early() produces expected
6764  * results. There are no test vectors so all we do is test that both
6765  * sides of the communication produce the same results for different
6766  * protocol versions.
6767  */
test_export_key_mat_early(int idx)6768 static int test_export_key_mat_early(int idx)
6769 {
6770     static const char label[] = "test label";
6771     static const unsigned char context[] = "context";
6772     int testresult = 0;
6773     SSL_CTX *cctx = NULL, *sctx = NULL;
6774     SSL *clientssl = NULL, *serverssl = NULL;
6775     SSL_SESSION *sess = NULL;
6776     const unsigned char *emptycontext = NULL;
6777     unsigned char ckeymat1[80], ckeymat2[80];
6778     unsigned char skeymat1[80], skeymat2[80];
6779     unsigned char buf[1];
6780     size_t readbytes, written;
6781 
6782     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
6783                                         &sess, idx, SHA384_DIGEST_LENGTH)))
6784         goto end;
6785 
6786     /* Here writing 0 length early data is enough. */
6787     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
6788             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
6789                                                 &readbytes),
6790                             SSL_READ_EARLY_DATA_ERROR)
6791             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6792                             SSL_EARLY_DATA_ACCEPTED))
6793         goto end;
6794 
6795     if (!TEST_int_eq(SSL_export_keying_material_early(
6796                      clientssl, ckeymat1, sizeof(ckeymat1), label,
6797                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
6798             || !TEST_int_eq(SSL_export_keying_material_early(
6799                             clientssl, ckeymat2, sizeof(ckeymat2), label,
6800                             sizeof(label) - 1, emptycontext, 0), 1)
6801             || !TEST_int_eq(SSL_export_keying_material_early(
6802                             serverssl, skeymat1, sizeof(skeymat1), label,
6803                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
6804             || !TEST_int_eq(SSL_export_keying_material_early(
6805                             serverssl, skeymat2, sizeof(skeymat2), label,
6806                             sizeof(label) - 1, emptycontext, 0), 1)
6807                /*
6808                 * Check that both sides created the same key material with the
6809                 * same context.
6810                 */
6811             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6812                             sizeof(skeymat1))
6813                /*
6814                 * Check that both sides created the same key material with an
6815                 * empty context.
6816                 */
6817             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6818                             sizeof(skeymat2))
6819                /* Different contexts should produce different results */
6820             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6821                             sizeof(ckeymat2)))
6822         goto end;
6823 
6824     testresult = 1;
6825 
6826  end:
6827     SSL_SESSION_free(sess);
6828     SSL_SESSION_free(clientpsk);
6829     SSL_SESSION_free(serverpsk);
6830     clientpsk = serverpsk = NULL;
6831     SSL_free(serverssl);
6832     SSL_free(clientssl);
6833     SSL_CTX_free(sctx);
6834     SSL_CTX_free(cctx);
6835 
6836     return testresult;
6837 }
6838 
6839 #define NUM_KEY_UPDATE_MESSAGES 40
6840 /*
6841  * Test KeyUpdate.
6842  */
test_key_update(void)6843 static int test_key_update(void)
6844 {
6845     SSL_CTX *cctx = NULL, *sctx = NULL;
6846     SSL *clientssl = NULL, *serverssl = NULL;
6847     int testresult = 0, i, j;
6848     char buf[20];
6849     static char *mess = "A test message";
6850 
6851     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6852                                        TLS_client_method(),
6853                                        TLS1_3_VERSION,
6854                                        0,
6855                                        &sctx, &cctx, cert, privkey))
6856             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6857                                              NULL, NULL))
6858             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6859                                                 SSL_ERROR_NONE)))
6860         goto end;
6861 
6862     for (j = 0; j < 2; j++) {
6863         /* Send lots of KeyUpdate messages */
6864         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
6865             if (!TEST_true(SSL_key_update(clientssl,
6866                                           (j == 0)
6867                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
6868                                           : SSL_KEY_UPDATE_REQUESTED))
6869                     || !TEST_true(SSL_do_handshake(clientssl)))
6870                 goto end;
6871         }
6872 
6873         /* Check that sending and receiving app data is ok */
6874         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
6875                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
6876                                          strlen(mess)))
6877             goto end;
6878 
6879         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
6880                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
6881                                          strlen(mess)))
6882             goto end;
6883     }
6884 
6885     testresult = 1;
6886 
6887  end:
6888     SSL_free(serverssl);
6889     SSL_free(clientssl);
6890     SSL_CTX_free(sctx);
6891     SSL_CTX_free(cctx);
6892 
6893     return testresult;
6894 }
6895 
6896 /*
6897  * Test we can handle a KeyUpdate (update requested) message while
6898  * write data is pending in peer.
6899  * Test 0: Client sends KeyUpdate while Server is writing
6900  * Test 1: Server sends KeyUpdate while Client is writing
6901  */
test_key_update_peer_in_write(int tst)6902 static int test_key_update_peer_in_write(int tst)
6903 {
6904     SSL_CTX *cctx = NULL, *sctx = NULL;
6905     SSL *clientssl = NULL, *serverssl = NULL;
6906     int testresult = 0;
6907     char buf[20];
6908     static char *mess = "A test message";
6909     BIO *bretry = BIO_new(bio_s_always_retry());
6910     BIO *tmp = NULL;
6911     SSL *peerupdate = NULL, *peerwrite = NULL;
6912 
6913     if (!TEST_ptr(bretry)
6914             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6915                                               TLS_client_method(),
6916                                               TLS1_3_VERSION,
6917                                               0,
6918                                               &sctx, &cctx, cert, privkey))
6919             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6920                                              NULL, NULL))
6921             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6922                                                 SSL_ERROR_NONE)))
6923         goto end;
6924 
6925     peerupdate = tst == 0 ? clientssl : serverssl;
6926     peerwrite = tst == 0 ? serverssl : clientssl;
6927 
6928     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
6929             || !TEST_int_eq(SSL_do_handshake(peerupdate), 1))
6930         goto end;
6931 
6932     /* Swap the writing endpoint's write BIO to force a retry */
6933     tmp = SSL_get_wbio(peerwrite);
6934     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6935         tmp = NULL;
6936         goto end;
6937     }
6938     SSL_set0_wbio(peerwrite, bretry);
6939     bretry = NULL;
6940 
6941     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
6942     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
6943             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE)
6944             || !TEST_true(SSL_want_write(peerwrite))
6945             || !TEST_true(SSL_net_write_desired(peerwrite)))
6946         goto end;
6947 
6948     /* Reinstate the original writing endpoint's write BIO */
6949     SSL_set0_wbio(peerwrite, tmp);
6950     tmp = NULL;
6951 
6952     /* Now read some data - we will read the key update */
6953     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
6954             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ)
6955             || !TEST_true(SSL_want_read(peerwrite))
6956             || !TEST_true(SSL_net_read_desired(peerwrite)))
6957         goto end;
6958 
6959     /*
6960      * Complete the write we started previously and read it from the other
6961      * endpoint
6962      */
6963     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6964             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6965         goto end;
6966 
6967     /* Write more data to ensure we send the KeyUpdate message back */
6968     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6969             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6970         goto end;
6971 
6972     if (!TEST_false(SSL_net_read_desired(peerwrite))
6973         || !TEST_false(SSL_net_write_desired(peerwrite))
6974         || !TEST_int_eq(SSL_want(peerwrite), SSL_NOTHING))
6975         goto end;
6976 
6977     testresult = 1;
6978 
6979  end:
6980     SSL_free(serverssl);
6981     SSL_free(clientssl);
6982     SSL_CTX_free(sctx);
6983     SSL_CTX_free(cctx);
6984     BIO_free(bretry);
6985     BIO_free(tmp);
6986 
6987     return testresult;
6988 }
6989 
6990 /*
6991  * Test we can handle a KeyUpdate (update requested) message while
6992  * peer read data is pending after peer accepted keyupdate(the msg header
6993  * had been read 5 bytes).
6994  * Test 0: Client sends KeyUpdate while Server is reading
6995  * Test 1: Server sends KeyUpdate while Client is reading
6996  */
test_key_update_peer_in_read(int tst)6997 static int test_key_update_peer_in_read(int tst)
6998 {
6999     SSL_CTX *cctx = NULL, *sctx = NULL;
7000     SSL *clientssl = NULL, *serverssl = NULL;
7001     int testresult = 0;
7002     char prbuf[515], lwbuf[515] = {0};
7003     static char *mess = "A test message";
7004     BIO *lbio = NULL, *pbio = NULL;
7005     SSL *local = NULL, *peer = NULL;
7006 
7007     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7008                                               TLS_client_method(),
7009                                               TLS1_3_VERSION,
7010                                               0,
7011                                               &sctx, &cctx, cert, privkey))
7012             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7013                                              NULL, NULL))
7014             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7015                                                 SSL_ERROR_NONE)))
7016         goto end;
7017 
7018     local = tst == 0 ? clientssl : serverssl;
7019     peer = tst == 0 ? serverssl : clientssl;
7020 
7021     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
7022         goto end;
7023 
7024     SSL_set_bio(local, lbio, lbio);
7025     SSL_set_bio(peer, pbio, pbio);
7026 
7027     /*
7028      * we first write keyupdate msg then appdata in local
7029      * write data in local will fail with SSL_ERROR_WANT_WRITE,because
7030      * lwbuf app data msg size + key updata msg size > 512(the size of
7031      * the bio pair buffer)
7032      */
7033     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7034             || !TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), -1)
7035             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
7036         goto end;
7037 
7038     /*
7039      * first read keyupdate msg in peer in peer
7040      * then read appdata that we know will fail with SSL_ERROR_WANT_READ
7041      */
7042     if (!TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), -1)
7043             || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_READ))
7044         goto end;
7045 
7046     /* Now write some data in peer - we will write the key update */
7047     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)))
7048         goto end;
7049 
7050     /*
7051      * write data in local previously that we will complete
7052      * read data in peer previously that we will complete
7053      */
7054     if (!TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), sizeof(lwbuf))
7055             || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), sizeof(prbuf)))
7056         goto end;
7057 
7058     /* check that sending and receiving appdata ok */
7059     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7060             || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
7061         goto end;
7062 
7063     testresult = 1;
7064 
7065  end:
7066     SSL_free(serverssl);
7067     SSL_free(clientssl);
7068     SSL_CTX_free(sctx);
7069     SSL_CTX_free(cctx);
7070 
7071     return testresult;
7072 }
7073 
7074 /*
7075  * Test we can't send a KeyUpdate (update requested) message while
7076  * local write data is pending.
7077  * Test 0: Client sends KeyUpdate while Client is writing
7078  * Test 1: Server sends KeyUpdate while Server is writing
7079  */
test_key_update_local_in_write(int tst)7080 static int test_key_update_local_in_write(int tst)
7081 {
7082     SSL_CTX *cctx = NULL, *sctx = NULL;
7083     SSL *clientssl = NULL, *serverssl = NULL;
7084     int testresult = 0;
7085     char buf[20];
7086     static char *mess = "A test message";
7087     BIO *bretry = BIO_new(bio_s_always_retry());
7088     BIO *tmp = NULL;
7089     SSL *local = NULL, *peer = NULL;
7090 
7091     if (!TEST_ptr(bretry)
7092             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7093                                               TLS_client_method(),
7094                                               TLS1_3_VERSION,
7095                                               0,
7096                                               &sctx, &cctx, cert, privkey))
7097             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7098                                              NULL, NULL))
7099             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7100                                                 SSL_ERROR_NONE)))
7101         goto end;
7102 
7103     local = tst == 0 ? clientssl : serverssl;
7104     peer = tst == 0 ? serverssl : clientssl;
7105 
7106     /* Swap the writing endpoint's write BIO to force a retry */
7107     tmp = SSL_get_wbio(local);
7108     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
7109         tmp = NULL;
7110         goto end;
7111     }
7112     SSL_set0_wbio(local, bretry);
7113     bretry = NULL;
7114 
7115     /* write data in local will fail with SSL_ERROR_WANT_WRITE */
7116     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), -1)
7117             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
7118         goto end;
7119 
7120     /* Reinstate the original writing endpoint's write BIO */
7121     SSL_set0_wbio(local, tmp);
7122     tmp = NULL;
7123 
7124     /* SSL_key_update will fail, because writing in local*/
7125     if (!TEST_false(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7126         || !TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_BAD_WRITE_RETRY))
7127     goto end;
7128 
7129     ERR_clear_error();
7130     /* write data in local previously that we will complete */
7131     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)))
7132         goto end;
7133 
7134     /* SSL_key_update will succeed because there is no pending write data */
7135     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7136         || !TEST_int_eq(SSL_do_handshake(local), 1))
7137         goto end;
7138 
7139     /*
7140      * we write some appdata in local
7141      * read data in peer - we will read the keyupdate msg
7142      */
7143     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7144         || !TEST_int_eq(SSL_read(peer, buf, sizeof(buf)), strlen(mess)))
7145         goto end;
7146 
7147     /* Write more peer more data to ensure we send the keyupdate message back */
7148     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7149             || !TEST_int_eq(SSL_read(local, buf, sizeof(buf)), strlen(mess)))
7150         goto end;
7151 
7152     testresult = 1;
7153 
7154  end:
7155     SSL_free(serverssl);
7156     SSL_free(clientssl);
7157     SSL_CTX_free(sctx);
7158     SSL_CTX_free(cctx);
7159     BIO_free(bretry);
7160     BIO_free(tmp);
7161 
7162     return testresult;
7163 }
7164 
7165 /*
7166  * Test we can handle a KeyUpdate (update requested) message while
7167  * local read data is pending(the msg header had been read 5 bytes).
7168  * Test 0: Client sends KeyUpdate while Client is reading
7169  * Test 1: Server sends KeyUpdate while Server is reading
7170  */
test_key_update_local_in_read(int tst)7171 static int test_key_update_local_in_read(int tst)
7172 {
7173     SSL_CTX *cctx = NULL, *sctx = NULL;
7174     SSL *clientssl = NULL, *serverssl = NULL;
7175     int testresult = 0;
7176     char lrbuf[515], pwbuf[515] = {0}, prbuf[20];
7177     static char *mess = "A test message";
7178     BIO *lbio = NULL, *pbio = NULL;
7179     SSL *local = NULL, *peer = NULL;
7180 
7181     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7182                                               TLS_client_method(),
7183                                               TLS1_3_VERSION,
7184                                               0,
7185                                               &sctx, &cctx, cert, privkey))
7186             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7187                                              NULL, NULL))
7188             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7189                                                 SSL_ERROR_NONE)))
7190         goto end;
7191 
7192     local = tst == 0 ? clientssl : serverssl;
7193     peer = tst == 0 ? serverssl : clientssl;
7194 
7195     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
7196         goto end;
7197 
7198     SSL_set_bio(local, lbio, lbio);
7199     SSL_set_bio(peer, pbio, pbio);
7200 
7201     /* write app data in peer will fail with SSL_ERROR_WANT_WRITE */
7202     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), -1)
7203         || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_WRITE))
7204         goto end;
7205 
7206     /* read appdata in local will fail with SSL_ERROR_WANT_READ */
7207     if (!TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), -1)
7208             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_READ))
7209         goto end;
7210 
7211     /* SSL_do_handshake will send keyupdate msg */
7212     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7213             || !TEST_int_eq(SSL_do_handshake(local), 1))
7214         goto end;
7215 
7216     /*
7217      * write data in peer previously that we will complete
7218      * read data in local previously that we will complete
7219      */
7220     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), sizeof(pwbuf))
7221         || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), sizeof(lrbuf)))
7222         goto end;
7223 
7224     /*
7225      * write data in local
7226      * read data in peer - we will read the key update
7227      */
7228     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7229         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
7230         goto end;
7231 
7232   /* Write more peer data to ensure we send the keyupdate message back */
7233     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7234             || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), strlen(mess)))
7235         goto end;
7236 
7237     testresult = 1;
7238 
7239  end:
7240     SSL_free(serverssl);
7241     SSL_free(clientssl);
7242     SSL_CTX_free(sctx);
7243     SSL_CTX_free(cctx);
7244 
7245     return testresult;
7246 }
7247 #endif /* OSSL_NO_USABLE_TLS1_3 */
7248 
7249 /*
7250  * Test clearing a connection via SSL_clear(), or resetting it via
7251  * SSL_set_connect_state()/SSL_set_accept_state()
7252  * Test 0: SSL_set_connect_state, TLSv1.3
7253  * Test 1: SSL_set_connect_state, TLSv1.2
7254  * Test 2: SSL_set_accept_state, TLSv1.3
7255  * Test 3: SSL_set_accept_state, TLSv1.2
7256  * Test 4: SSL_clear (client), TLSv1.3
7257  * Test 5: SSL_clear (client), TLSv1.2
7258  * Test 6: SSL_clear (server), TLSv1.3
7259  * Test 7: SSL_clear (server), TLSv1.2
7260  */
test_ssl_clear(int idx)7261 static int test_ssl_clear(int idx)
7262 {
7263     SSL_CTX *cctx = NULL, *sctx = NULL;
7264     SSL *clientssl = NULL, *serverssl = NULL;
7265     SSL *writer, *reader;
7266     int testresult = 0;
7267     int tls12test, servertest, cleartest;
7268     size_t written, readbytes;
7269     const char *msg = "Hello World";
7270     unsigned char buf[5];
7271 
7272     tls12test = idx & 1;
7273     idx >>= 1;
7274     servertest = idx & 1;
7275     idx >>= 1;
7276     cleartest = idx & 1;
7277 
7278 #ifdef OPENSSL_NO_TLS1_2
7279     if (tls12test == 1)
7280         return TEST_skip("No TLSv1.2 in this build");
7281 #endif
7282 
7283     /* Create an initial connection */
7284     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7285                                        TLS_client_method(), TLS1_VERSION, 0,
7286                                        &sctx, &cctx, cert, privkey))
7287             || (tls12test
7288                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
7289                                                             TLS1_2_VERSION)))
7290             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
7291                                           &clientssl, NULL, NULL))
7292             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7293                                                 SSL_ERROR_NONE)))
7294         goto end;
7295 
7296     if (servertest) {
7297         writer = clientssl;
7298         reader = serverssl;
7299     } else {
7300         writer = serverssl;
7301         reader = clientssl;
7302     }
7303 
7304     /* Write some data */
7305     if (!TEST_true(SSL_write_ex(writer, msg, strlen(msg), &written))
7306             || written != strlen(msg))
7307         goto end;
7308 
7309     /*
7310      * Read a partial record. The remaining buffered data should be cleared by
7311      * the subsequent clear/reset
7312      */
7313     if (!TEST_true(SSL_read_ex(reader, buf, sizeof(buf), &readbytes))
7314             || readbytes != sizeof(buf))
7315         goto end;
7316 
7317     SSL_shutdown(clientssl);
7318     SSL_shutdown(serverssl);
7319 
7320     /* Reset/clear one SSL object in order to reuse it. We free the other one */
7321     if (servertest) {
7322         if (cleartest) {
7323             if (!TEST_true(SSL_clear(serverssl)))
7324                 goto end;
7325         } else {
7326             SSL_set_accept_state(serverssl);
7327         }
7328         SSL_free(clientssl);
7329         clientssl = NULL;
7330     } else {
7331         if (cleartest) {
7332             if (!TEST_true(SSL_clear(clientssl)))
7333                 goto end;
7334         } else {
7335             SSL_set_connect_state(clientssl);
7336         }
7337         SSL_free(serverssl);
7338         serverssl = NULL;
7339     }
7340 
7341     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7342                                              NULL, NULL))
7343             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7344                                                 SSL_ERROR_NONE))
7345             || !TEST_true(servertest || SSL_session_reused(clientssl)))
7346         goto end;
7347 
7348     SSL_shutdown(clientssl);
7349     SSL_shutdown(serverssl);
7350 
7351     testresult = 1;
7352 
7353  end:
7354     SSL_free(serverssl);
7355     SSL_free(clientssl);
7356     SSL_CTX_free(sctx);
7357     SSL_CTX_free(cctx);
7358 
7359     return testresult;
7360 }
7361 
7362 /* Parse CH and retrieve any MFL extension value if present */
get_MFL_from_client_hello(BIO * bio,int * mfl_codemfl_code)7363 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
7364 {
7365     long len;
7366     unsigned char *data;
7367     PACKET pkt, pkt2, pkt3;
7368     unsigned int MFL_code = 0, type = 0;
7369 
7370     if (!TEST_uint_gt(len = BIO_get_mem_data(bio, (char **) &data), 0))
7371         goto end;
7372 
7373     memset(&pkt, 0, sizeof(pkt));
7374     memset(&pkt2, 0, sizeof(pkt2));
7375     memset(&pkt3, 0, sizeof(pkt3));
7376 
7377     if (!TEST_long_gt(len, 0)
7378             || !TEST_true(PACKET_buf_init(&pkt, data, len))
7379                /* Skip the record header */
7380             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
7381                /* Skip the handshake message header */
7382             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
7383                /* Skip client version and random */
7384             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
7385                                                + SSL3_RANDOM_SIZE))
7386                /* Skip session id */
7387             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7388                /* Skip ciphers */
7389             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
7390                /* Skip compression */
7391             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7392                /* Extensions len */
7393             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
7394         goto end;
7395 
7396     /* Loop through all extensions */
7397     while (PACKET_remaining(&pkt2)) {
7398         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
7399                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
7400             goto end;
7401 
7402         if (type == TLSEXT_TYPE_max_fragment_length) {
7403             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
7404                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
7405                 goto end;
7406 
7407             *mfl_codemfl_code = MFL_code;
7408             return 1;
7409         }
7410     }
7411 
7412  end:
7413     return 0;
7414 }
7415 
7416 /* Maximum-Fragment-Length TLS extension mode to test */
7417 static const unsigned char max_fragment_len_test[] = {
7418     TLSEXT_max_fragment_length_512,
7419     TLSEXT_max_fragment_length_1024,
7420     TLSEXT_max_fragment_length_2048,
7421     TLSEXT_max_fragment_length_4096
7422 };
7423 
test_max_fragment_len_ext(int idx_tst)7424 static int test_max_fragment_len_ext(int idx_tst)
7425 {
7426     SSL_CTX *ctx = NULL;
7427     SSL *con = NULL;
7428     int testresult = 0, MFL_mode = 0;
7429     BIO *rbio, *wbio;
7430 
7431     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(),
7432                                        TLS1_VERSION, 0, NULL, &ctx, NULL,
7433                                        NULL)))
7434         return 0;
7435 
7436     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
7437                    ctx, max_fragment_len_test[idx_tst])))
7438         goto end;
7439 
7440     con = SSL_new(ctx);
7441     if (!TEST_ptr(con))
7442         goto end;
7443 
7444     rbio = BIO_new(BIO_s_mem());
7445     wbio = BIO_new(BIO_s_mem());
7446     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
7447         BIO_free(rbio);
7448         BIO_free(wbio);
7449         goto end;
7450     }
7451 
7452     SSL_set_bio(con, rbio, wbio);
7453 
7454     if (!TEST_int_le(SSL_connect(con), 0)) {
7455         /* This shouldn't succeed because we don't have a server! */
7456         goto end;
7457     }
7458 
7459     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
7460         /* no MFL in client hello */
7461         goto end;
7462     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
7463         goto end;
7464 
7465     testresult = 1;
7466 
7467 end:
7468     SSL_free(con);
7469     SSL_CTX_free(ctx);
7470 
7471     return testresult;
7472 }
7473 
7474 #ifndef OSSL_NO_USABLE_TLS1_3
test_pha_key_update(void)7475 static int test_pha_key_update(void)
7476 {
7477     SSL_CTX *cctx = NULL, *sctx = NULL;
7478     SSL *clientssl = NULL, *serverssl = NULL;
7479     int testresult = 0;
7480 
7481     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7482                                        TLS_client_method(), TLS1_VERSION, 0,
7483                                        &sctx, &cctx, cert, privkey)))
7484         return 0;
7485 
7486     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
7487         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
7488         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
7489         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
7490         goto end;
7491 
7492     SSL_CTX_set_post_handshake_auth(cctx, 1);
7493 
7494     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7495                                       NULL, NULL)))
7496         goto end;
7497 
7498     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7499                                          SSL_ERROR_NONE)))
7500         goto end;
7501 
7502     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
7503     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
7504         goto end;
7505 
7506     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
7507         goto end;
7508 
7509     /* Start handshake on the server */
7510     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
7511         goto end;
7512 
7513     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
7514     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7515                                          SSL_ERROR_NONE)))
7516         goto end;
7517 
7518     SSL_shutdown(clientssl);
7519     SSL_shutdown(serverssl);
7520 
7521     testresult = 1;
7522 
7523  end:
7524     SSL_free(serverssl);
7525     SSL_free(clientssl);
7526     SSL_CTX_free(sctx);
7527     SSL_CTX_free(cctx);
7528     return testresult;
7529 }
7530 #endif
7531 
7532 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7533 
7534 static SRP_VBASE *vbase = NULL;
7535 
ssl_srp_cb(SSL * s,int * ad,void * arg)7536 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
7537 {
7538     int ret = SSL3_AL_FATAL;
7539     char *username;
7540     SRP_user_pwd *user = NULL;
7541 
7542     username = SSL_get_srp_username(s);
7543     if (username == NULL) {
7544         *ad = SSL_AD_INTERNAL_ERROR;
7545         goto err;
7546     }
7547 
7548     user = SRP_VBASE_get1_by_user(vbase, username);
7549     if (user == NULL) {
7550         *ad = SSL_AD_INTERNAL_ERROR;
7551         goto err;
7552     }
7553 
7554     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
7555                                  user->info) <= 0) {
7556         *ad = SSL_AD_INTERNAL_ERROR;
7557         goto err;
7558     }
7559 
7560     ret = 0;
7561 
7562  err:
7563     SRP_user_pwd_free(user);
7564     return ret;
7565 }
7566 
create_new_vfile(char * userid,char * password,const char * filename)7567 static int create_new_vfile(char *userid, char *password, const char *filename)
7568 {
7569     char *gNid = NULL;
7570     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
7571     TXT_DB *db = NULL;
7572     int ret = 0;
7573     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
7574     size_t i;
7575 
7576     if (!TEST_ptr(dummy) || !TEST_ptr(row))
7577         goto end;
7578 
7579     gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
7580                                   &row[DB_srpverifier], NULL, NULL, libctx, NULL);
7581     if (!TEST_ptr(gNid))
7582         goto end;
7583 
7584     /*
7585      * The only way to create an empty TXT_DB is to provide a BIO with no data
7586      * in it!
7587      */
7588     db = TXT_DB_read(dummy, DB_NUMBER);
7589     if (!TEST_ptr(db))
7590         goto end;
7591 
7592     out = BIO_new_file(filename, "w");
7593     if (!TEST_ptr(out))
7594         goto end;
7595 
7596     row[DB_srpid] = OPENSSL_strdup(userid);
7597     row[DB_srptype] = OPENSSL_strdup("V");
7598     row[DB_srpgN] = OPENSSL_strdup(gNid);
7599 
7600     if (!TEST_ptr(row[DB_srpid])
7601             || !TEST_ptr(row[DB_srptype])
7602             || !TEST_ptr(row[DB_srpgN])
7603             || !TEST_true(TXT_DB_insert(db, row)))
7604         goto end;
7605 
7606     row = NULL;
7607 
7608     if (TXT_DB_write(out, db) <= 0)
7609         goto end;
7610 
7611     ret = 1;
7612  end:
7613     if (row != NULL) {
7614         for (i = 0; i < DB_NUMBER; i++)
7615             OPENSSL_free(row[i]);
7616     }
7617     OPENSSL_free(row);
7618     BIO_free(dummy);
7619     BIO_free(out);
7620     TXT_DB_free(db);
7621 
7622     return ret;
7623 }
7624 
create_new_vbase(char * userid,char * password)7625 static int create_new_vbase(char *userid, char *password)
7626 {
7627     BIGNUM *verifier = NULL, *salt = NULL;
7628     const SRP_gN *lgN = NULL;
7629     SRP_user_pwd *user_pwd = NULL;
7630     int ret = 0;
7631 
7632     lgN = SRP_get_default_gN(NULL);
7633     if (!TEST_ptr(lgN))
7634         goto end;
7635 
7636     if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
7637                                              lgN->N, lgN->g, libctx, NULL)))
7638         goto end;
7639 
7640     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
7641     if (!TEST_ptr(user_pwd))
7642         goto end;
7643 
7644     user_pwd->N = lgN->N;
7645     user_pwd->g = lgN->g;
7646     user_pwd->id = OPENSSL_strdup(userid);
7647     if (!TEST_ptr(user_pwd->id))
7648         goto end;
7649 
7650     user_pwd->v = verifier;
7651     user_pwd->s = salt;
7652     verifier = salt = NULL;
7653 
7654     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
7655         goto end;
7656     user_pwd = NULL;
7657 
7658     ret = 1;
7659 end:
7660     SRP_user_pwd_free(user_pwd);
7661     BN_free(salt);
7662     BN_free(verifier);
7663 
7664     return ret;
7665 }
7666 
7667 /*
7668  * SRP tests
7669  *
7670  * Test 0: Simple successful SRP connection, new vbase
7671  * Test 1: Connection failure due to bad password, new vbase
7672  * Test 2: Simple successful SRP connection, vbase loaded from existing file
7673  * Test 3: Connection failure due to bad password, vbase loaded from existing
7674  *         file
7675  * Test 4: Simple successful SRP connection, vbase loaded from new file
7676  * Test 5: Connection failure due to bad password, vbase loaded from new file
7677  */
test_srp(int tst)7678 static int test_srp(int tst)
7679 {
7680     char *userid = "test", *password = "password", *tstsrpfile;
7681     SSL_CTX *cctx = NULL, *sctx = NULL;
7682     SSL *clientssl = NULL, *serverssl = NULL;
7683     int ret, testresult = 0;
7684 
7685     vbase = SRP_VBASE_new(NULL);
7686     if (!TEST_ptr(vbase))
7687         goto end;
7688 
7689     if (tst == 0 || tst == 1) {
7690         if (!TEST_true(create_new_vbase(userid, password)))
7691             goto end;
7692     } else {
7693         if (tst == 4 || tst == 5) {
7694             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
7695                 goto end;
7696             tstsrpfile = tmpfilename;
7697         } else {
7698             tstsrpfile = srpvfile;
7699         }
7700         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
7701             goto end;
7702     }
7703 
7704     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7705                                        TLS_client_method(), TLS1_VERSION, 0,
7706                                        &sctx, &cctx, cert, privkey)))
7707         goto end;
7708 
7709     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
7710             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
7711             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
7712             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
7713             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
7714         goto end;
7715 
7716     if (tst % 2 == 1) {
7717         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
7718             goto end;
7719     } else {
7720         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
7721             goto end;
7722     }
7723 
7724     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7725                                       NULL, NULL)))
7726         goto end;
7727 
7728     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
7729     if (ret) {
7730         if (!TEST_true(tst % 2 == 0))
7731             goto end;
7732     } else {
7733         if (!TEST_true(tst % 2 == 1))
7734             goto end;
7735     }
7736 
7737     testresult = 1;
7738 
7739  end:
7740     SRP_VBASE_free(vbase);
7741     vbase = NULL;
7742     SSL_free(serverssl);
7743     SSL_free(clientssl);
7744     SSL_CTX_free(sctx);
7745     SSL_CTX_free(cctx);
7746 
7747     return testresult;
7748 }
7749 #endif
7750 
7751 static int info_cb_failed = 0;
7752 static int info_cb_offset = 0;
7753 static int info_cb_this_state = -1;
7754 
7755 static struct info_cb_states_st {
7756     int where;
7757     const char *statestr;
7758 } info_cb_states[][60] = {
7759     {
7760         /* TLSv1.2 server followed by resumption */
7761         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7762         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7763         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
7764         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
7765         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
7766         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7767         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7768         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7769         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"},
7770         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7771         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
7772         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7773         {SSL_CB_EXIT, NULL}, {0, NULL},
7774     }, {
7775         /* TLSv1.2 client followed by resumption */
7776         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7777         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7778         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
7779         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
7780         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
7781         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7782         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7783         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7784         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7785         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7786         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
7787         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
7788     }, {
7789         /* TLSv1.3 server followed by resumption */
7790         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7791         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7792         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
7793         {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
7794         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
7795         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7796         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7797         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7798         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7799         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7800         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
7801         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7802         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7803     }, {
7804         /* TLSv1.3 client followed by resumption */
7805         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7806         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7807         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
7808         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
7809         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
7810         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7811         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"},
7812         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
7813         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7814         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
7815         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
7816         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7817         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7818         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"},
7819         {SSL_CB_EXIT, NULL}, {0, NULL},
7820     }, {
7821         /* TLSv1.3 server, early_data */
7822         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7823         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7824         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7825         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7826         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7827         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
7828         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7829         {SSL_CB_EXIT, NULL}, {0, NULL},
7830     }, {
7831         /* TLSv1.3 client, early_data */
7832         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7833         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
7834         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7835         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7836         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
7837         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
7838         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7839         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7840         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7841     }, {
7842         /* TLSv1.3 server, certificate compression, followed by resumption */
7843         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7844         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7845         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSCC"},
7846         {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
7847         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
7848         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7849         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7850         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7851         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7852         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7853         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
7854         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7855         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7856     }, {
7857         /* TLSv1.3 client, certificate compression, followed by resumption */
7858         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7859         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7860         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSCC"},
7861         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
7862         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
7863         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7864         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"},
7865         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
7866         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7867         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
7868         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
7869         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7870         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7871         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"},
7872         {SSL_CB_EXIT, NULL}, {0, NULL},
7873     }, {
7874         {0, NULL},
7875     }
7876 };
7877 
sslapi_info_callback(const SSL * s,int where,int ret)7878 static void sslapi_info_callback(const SSL *s, int where, int ret)
7879 {
7880     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
7881 
7882     /* We do not ever expect a connection to fail in this test */
7883     if (!TEST_false(ret == 0)) {
7884         info_cb_failed = 1;
7885         return;
7886     }
7887 
7888     /*
7889      * Do some sanity checks. We never expect these things to happen in this
7890      * test
7891      */
7892     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
7893             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
7894             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
7895         info_cb_failed = 1;
7896         return;
7897     }
7898 
7899     /* Now check we're in the right state */
7900     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
7901         info_cb_failed = 1;
7902         return;
7903     }
7904     if ((where & SSL_CB_LOOP) != 0
7905             && !TEST_int_eq(strcmp(SSL_state_string(s),
7906                             state[info_cb_this_state].statestr), 0)) {
7907         info_cb_failed = 1;
7908         return;
7909     }
7910 
7911     /*
7912      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
7913      */
7914     if ((where & SSL_CB_HANDSHAKE_DONE)
7915             && SSL_in_init((SSL *)s) != 0) {
7916         info_cb_failed = 1;
7917         return;
7918     }
7919 }
7920 
7921 /*
7922  * Test the info callback gets called when we expect it to.
7923  *
7924  * Test 0: TLSv1.2, server
7925  * Test 1: TLSv1.2, client
7926  * Test 2: TLSv1.3, server
7927  * Test 3: TLSv1.3, client
7928  * Test 4: TLSv1.3, server, early_data
7929  * Test 5: TLSv1.3, client, early_data
7930  * Test 6: TLSv1.3, server, compressed certificate
7931  * Test 7: TLSv1.3, client, compressed certificate
7932  */
test_info_callback(int tst)7933 static int test_info_callback(int tst)
7934 {
7935     SSL_CTX *cctx = NULL, *sctx = NULL;
7936     SSL *clientssl = NULL, *serverssl = NULL;
7937     SSL_SESSION *clntsess = NULL;
7938     int testresult = 0;
7939     int tlsvers;
7940 
7941     if (tst < 2) {
7942 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
7943 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
7944                                     || !defined(OPENSSL_NO_DH))
7945         tlsvers = TLS1_2_VERSION;
7946 #else
7947         return 1;
7948 #endif
7949     } else {
7950 #ifndef OSSL_NO_USABLE_TLS1_3
7951         tlsvers = TLS1_3_VERSION;
7952 #else
7953         return 1;
7954 #endif
7955     }
7956 
7957     /* Reset globals */
7958     info_cb_failed = 0;
7959     info_cb_this_state = -1;
7960     info_cb_offset = tst;
7961 
7962 #ifndef OSSL_NO_USABLE_TLS1_3
7963     if (tst >= 4 && tst < 6) {
7964         SSL_SESSION *sess = NULL;
7965         size_t written, readbytes;
7966         unsigned char buf[80];
7967         OSSL_TIME timer;
7968 
7969         /* early_data tests */
7970         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
7971                                             &serverssl, &sess, 0,
7972                                             SHA384_DIGEST_LENGTH)))
7973             goto end;
7974 
7975         /* We don't actually need this reference */
7976         SSL_SESSION_free(sess);
7977 
7978         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
7979                               sslapi_info_callback);
7980 
7981         /* Write and read some early data and then complete the connection */
7982         timer = ossl_time_now();
7983         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
7984                                             &written))
7985                 || !TEST_size_t_eq(written, strlen(MSG1)))
7986             goto end;
7987 
7988         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf,
7989                                              sizeof(buf), &readbytes),
7990                          SSL_READ_EARLY_DATA_SUCCESS)) {
7991             testresult = check_early_data_timeout(timer);
7992             goto end;
7993         }
7994 
7995         if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
7996                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
7997                                 SSL_EARLY_DATA_ACCEPTED)
7998                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
7999                                                     SSL_ERROR_NONE))
8000                 || !TEST_false(info_cb_failed))
8001             goto end;
8002 
8003         testresult = 1;
8004         goto end;
8005     }
8006 #endif
8007 
8008     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8009                                        TLS_client_method(),
8010                                        tlsvers, tlsvers, &sctx, &cctx, cert,
8011                                        privkey)))
8012         goto end;
8013 
8014     if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
8015         goto end;
8016 
8017     /*
8018      * For even numbered tests we check the server callbacks. For odd numbers we
8019      * check the client.
8020      */
8021     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
8022                               sslapi_info_callback);
8023     if (tst >= 6) {
8024         if (!SSL_CTX_compress_certs(sctx, 0))
8025             goto end;
8026     }
8027 
8028     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
8029                                           &clientssl, NULL, NULL))
8030         || !TEST_true(create_ssl_connection(serverssl, clientssl,
8031                                             SSL_ERROR_NONE))
8032         || !TEST_false(info_cb_failed))
8033     goto end;
8034 
8035 
8036 
8037     clntsess = SSL_get1_session(clientssl);
8038     SSL_shutdown(clientssl);
8039     SSL_shutdown(serverssl);
8040     SSL_free(serverssl);
8041     SSL_free(clientssl);
8042     serverssl = clientssl = NULL;
8043 
8044     /* Now do a resumption */
8045     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8046                                       NULL))
8047             || !TEST_true(SSL_set_session(clientssl, clntsess))
8048             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8049                                                 SSL_ERROR_NONE))
8050             || !TEST_true(SSL_session_reused(clientssl))
8051             || !TEST_false(info_cb_failed))
8052         goto end;
8053 
8054     testresult = 1;
8055 
8056  end:
8057     SSL_free(serverssl);
8058     SSL_free(clientssl);
8059     SSL_SESSION_free(clntsess);
8060     SSL_CTX_free(sctx);
8061     SSL_CTX_free(cctx);
8062     return testresult;
8063 }
8064 
test_ssl_pending(int tst)8065 static int test_ssl_pending(int tst)
8066 {
8067     SSL_CTX *cctx = NULL, *sctx = NULL;
8068     SSL *clientssl = NULL, *serverssl = NULL;
8069     int testresult = 0;
8070     char msg[] = "A test message";
8071     char buf[5];
8072     size_t written, readbytes;
8073 
8074     if (tst == 0) {
8075         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8076                                            TLS_client_method(),
8077                                            TLS1_VERSION, 0,
8078                                            &sctx, &cctx, cert, privkey)))
8079             goto end;
8080     } else {
8081 #ifndef OPENSSL_NO_DTLS
8082         if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
8083                                            DTLS_client_method(),
8084                                            DTLS1_VERSION, 0,
8085                                            &sctx, &cctx, cert, privkey)))
8086             goto end;
8087 
8088 # ifdef OPENSSL_NO_DTLS1_2
8089         /* Not supported in the FIPS provider */
8090         if (is_fips) {
8091             testresult = 1;
8092             goto end;
8093         };
8094         /*
8095          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
8096          * level 0
8097          */
8098         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
8099                 || !TEST_true(SSL_CTX_set_cipher_list(cctx,
8100                                                     "DEFAULT:@SECLEVEL=0")))
8101             goto end;
8102 # endif
8103 #else
8104         return 1;
8105 #endif
8106     }
8107 
8108     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8109                                              NULL, NULL))
8110             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8111                                                 SSL_ERROR_NONE)))
8112         goto end;
8113 
8114     if (!TEST_int_eq(SSL_pending(clientssl), 0)
8115             || !TEST_false(SSL_has_pending(clientssl))
8116             || !TEST_int_eq(SSL_pending(serverssl), 0)
8117             || !TEST_false(SSL_has_pending(serverssl))
8118             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8119             || !TEST_size_t_eq(written, sizeof(msg))
8120             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
8121             || !TEST_size_t_eq(readbytes, sizeof(buf))
8122             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
8123             || !TEST_true(SSL_has_pending(clientssl)))
8124         goto end;
8125 
8126     testresult = 1;
8127 
8128  end:
8129     SSL_free(serverssl);
8130     SSL_free(clientssl);
8131     SSL_CTX_free(sctx);
8132     SSL_CTX_free(cctx);
8133 
8134     return testresult;
8135 }
8136 
8137 static struct {
8138     unsigned int maxprot;
8139     const char *clntciphers;
8140     const char *clnttls13ciphers;
8141     const char *srvrciphers;
8142     const char *srvrtls13ciphers;
8143     const char *shared;
8144     const char *fipsshared;
8145 } shared_ciphers_data[] = {
8146 /*
8147  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
8148  * TLSv1.3 is enabled but TLSv1.2 is disabled.
8149  */
8150 #if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
8151     {
8152         TLS1_2_VERSION,
8153         "AES128-SHA:AES256-SHA",
8154         NULL,
8155         "AES256-SHA:DHE-RSA-AES128-SHA",
8156         NULL,
8157         "AES256-SHA",
8158         "AES256-SHA"
8159     },
8160 # if !defined(OPENSSL_NO_CHACHA) \
8161      && !defined(OPENSSL_NO_POLY1305) \
8162      && !defined(OPENSSL_NO_EC)
8163     {
8164         TLS1_2_VERSION,
8165         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8166         NULL,
8167         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8168         NULL,
8169         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8170         "AES128-SHA"
8171     },
8172 # endif
8173     {
8174         TLS1_2_VERSION,
8175         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
8176         NULL,
8177         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
8178         NULL,
8179         "AES128-SHA:AES256-SHA",
8180         "AES128-SHA:AES256-SHA"
8181     },
8182     {
8183         TLS1_2_VERSION,
8184         "AES128-SHA:AES256-SHA",
8185         NULL,
8186         "AES128-SHA:DHE-RSA-AES128-SHA",
8187         NULL,
8188         "AES128-SHA",
8189         "AES128-SHA"
8190     },
8191 #endif
8192 /*
8193  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
8194  * enabled.
8195  */
8196 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
8197     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
8198     {
8199         TLS1_3_VERSION,
8200         "AES128-SHA:AES256-SHA",
8201         NULL,
8202         "AES256-SHA:AES128-SHA256",
8203         NULL,
8204         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
8205         "TLS_AES_128_GCM_SHA256:AES256-SHA",
8206         "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA"
8207     },
8208 #endif
8209 #ifndef OSSL_NO_USABLE_TLS1_3
8210     {
8211         TLS1_3_VERSION,
8212         "AES128-SHA",
8213         "TLS_AES_256_GCM_SHA384",
8214         "AES256-SHA",
8215         "TLS_AES_256_GCM_SHA384",
8216         "TLS_AES_256_GCM_SHA384",
8217         "TLS_AES_256_GCM_SHA384"
8218     },
8219 #endif
8220 };
8221 
int_test_ssl_get_shared_ciphers(int tst,int clnt)8222 static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
8223 {
8224     SSL_CTX *cctx = NULL, *sctx = NULL;
8225     SSL *clientssl = NULL, *serverssl = NULL;
8226     int testresult = 0;
8227     char buf[1024];
8228     OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
8229 
8230     if (!TEST_ptr(tmplibctx))
8231         goto end;
8232 
8233     /*
8234      * Regardless of whether we're testing with the FIPS provider loaded into
8235      * libctx, we want one peer to always use the full set of ciphersuites
8236      * available. Therefore we use a separate libctx with the default provider
8237      * loaded into it. We run the same tests twice - once with the client side
8238      * having the full set of ciphersuites and once with the server side.
8239      */
8240     if (clnt) {
8241         cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
8242         if (!TEST_ptr(cctx))
8243             goto end;
8244     } else {
8245         sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
8246         if (!TEST_ptr(sctx))
8247             goto end;
8248     }
8249 
8250     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8251                                        TLS_client_method(),
8252                                        TLS1_VERSION,
8253                                        shared_ciphers_data[tst].maxprot,
8254                                        &sctx, &cctx, cert, privkey)))
8255         goto end;
8256 
8257     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
8258                                         shared_ciphers_data[tst].clntciphers))
8259             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
8260                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
8261                                     shared_ciphers_data[tst].clnttls13ciphers)))
8262             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
8263                                         shared_ciphers_data[tst].srvrciphers))
8264             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
8265                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
8266                                     shared_ciphers_data[tst].srvrtls13ciphers))))
8267         goto end;
8268 
8269 
8270     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8271                                              NULL, NULL))
8272             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8273                                                 SSL_ERROR_NONE)))
8274         goto end;
8275 
8276     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
8277             || !TEST_int_eq(strcmp(buf,
8278                                    is_fips
8279                                    ? shared_ciphers_data[tst].fipsshared
8280                                    : shared_ciphers_data[tst].shared),
8281                                    0)) {
8282         TEST_info("Shared ciphers are: %s\n", buf);
8283         goto end;
8284     }
8285 
8286     testresult = 1;
8287 
8288  end:
8289     SSL_free(serverssl);
8290     SSL_free(clientssl);
8291     SSL_CTX_free(sctx);
8292     SSL_CTX_free(cctx);
8293     OSSL_LIB_CTX_free(tmplibctx);
8294 
8295     return testresult;
8296 }
8297 
test_ssl_get_shared_ciphers(int tst)8298 static int test_ssl_get_shared_ciphers(int tst)
8299 {
8300     return int_test_ssl_get_shared_ciphers(tst, 0)
8301            && int_test_ssl_get_shared_ciphers(tst, 1);
8302 }
8303 
8304 
8305 static const char *appdata = "Hello World";
8306 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
8307 static int tick_key_renew = 0;
8308 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8309 
gen_tick_cb(SSL * s,void * arg)8310 static int gen_tick_cb(SSL *s, void *arg)
8311 {
8312     gen_tick_called = 1;
8313 
8314     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
8315                                            strlen(appdata));
8316 }
8317 
dec_tick_cb(SSL * s,SSL_SESSION * ss,const unsigned char * keyname,size_t keyname_length,SSL_TICKET_STATUS status,void * arg)8318 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
8319                                      const unsigned char *keyname,
8320                                      size_t keyname_length,
8321                                      SSL_TICKET_STATUS status,
8322                                      void *arg)
8323 {
8324     void *tickdata;
8325     size_t tickdlen;
8326 
8327     dec_tick_called = 1;
8328 
8329     if (status == SSL_TICKET_EMPTY)
8330         return SSL_TICKET_RETURN_IGNORE_RENEW;
8331 
8332     if (!TEST_true(status == SSL_TICKET_SUCCESS
8333                    || status == SSL_TICKET_SUCCESS_RENEW))
8334         return SSL_TICKET_RETURN_ABORT;
8335 
8336     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
8337                                                    &tickdlen))
8338             || !TEST_size_t_eq(tickdlen, strlen(appdata))
8339             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
8340         return SSL_TICKET_RETURN_ABORT;
8341 
8342     if (tick_key_cb_called)  {
8343         /* Don't change what the ticket key callback wanted to do */
8344         switch (status) {
8345         case SSL_TICKET_NO_DECRYPT:
8346             return SSL_TICKET_RETURN_IGNORE_RENEW;
8347 
8348         case SSL_TICKET_SUCCESS:
8349             return SSL_TICKET_RETURN_USE;
8350 
8351         case SSL_TICKET_SUCCESS_RENEW:
8352             return SSL_TICKET_RETURN_USE_RENEW;
8353 
8354         default:
8355             return SSL_TICKET_RETURN_ABORT;
8356         }
8357     }
8358     return tick_dec_ret;
8359 
8360 }
8361 
8362 #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)8363 static int tick_key_cb(SSL *s, unsigned char key_name[16],
8364                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
8365                        HMAC_CTX *hctx, int enc)
8366 {
8367     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8368     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
8369     EVP_CIPHER *aes128cbc;
8370     EVP_MD *sha256;
8371     int ret;
8372 
8373     tick_key_cb_called = 1;
8374 
8375     if (tick_key_renew == -1)
8376         return 0;
8377 
8378     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8379     if (!TEST_ptr(aes128cbc))
8380         return 0;
8381     sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
8382     if (!TEST_ptr(sha256)) {
8383         EVP_CIPHER_free(aes128cbc);
8384         return 0;
8385     }
8386 
8387     memset(iv, 0, AES_BLOCK_SIZE);
8388     memset(key_name, 0, 16);
8389     if (aes128cbc == NULL
8390             || sha256 == NULL
8391             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8392             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
8393                              NULL))
8394         ret = -1;
8395     else
8396         ret = tick_key_renew ? 2 : 1;
8397 
8398     EVP_CIPHER_free(aes128cbc);
8399     EVP_MD_free(sha256);
8400 
8401     return ret;
8402 }
8403 #endif
8404 
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)8405 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
8406                            unsigned char iv[EVP_MAX_IV_LENGTH],
8407                            EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
8408 {
8409     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8410     unsigned char tick_hmac_key[16] = "0123456789abcdef";
8411     OSSL_PARAM params[2];
8412     EVP_CIPHER *aes128cbc;
8413     int ret;
8414 
8415     tick_key_cb_called = 1;
8416 
8417     if (tick_key_renew == -1)
8418         return 0;
8419 
8420     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8421     if (!TEST_ptr(aes128cbc))
8422         return 0;
8423 
8424     memset(iv, 0, AES_BLOCK_SIZE);
8425     memset(key_name, 0, 16);
8426     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
8427                                                  "SHA256", 0);
8428     params[1] = OSSL_PARAM_construct_end();
8429     if (aes128cbc == NULL
8430             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8431             || !EVP_MAC_init(hctx, tick_hmac_key, sizeof(tick_hmac_key),
8432                              params))
8433         ret = -1;
8434     else
8435         ret = tick_key_renew ? 2 : 1;
8436 
8437     EVP_CIPHER_free(aes128cbc);
8438 
8439     return ret;
8440 }
8441 
8442 /*
8443  * Test the various ticket callbacks
8444  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
8445  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
8446  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
8447  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
8448  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
8449  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
8450  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
8451  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
8452  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
8453  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
8454  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
8455  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
8456  * Test 12: TLSv1.2, old ticket key callback, no ticket
8457  * Test 13: TLSv1.3, old ticket key callback, no ticket
8458  * Test 14: TLSv1.2, ticket key callback, ticket, no renewal
8459  * Test 15: TLSv1.3, ticket key callback, ticket, no renewal
8460  * Test 16: TLSv1.2, ticket key callback, ticket, renewal
8461  * Test 17: TLSv1.3, ticket key callback, ticket, renewal
8462  * Test 18: TLSv1.2, ticket key callback, no ticket
8463  * Test 19: TLSv1.3, ticket key callback, no ticket
8464  */
test_ticket_callbacks(int tst)8465 static int test_ticket_callbacks(int tst)
8466 {
8467     SSL_CTX *cctx = NULL, *sctx = NULL;
8468     SSL *clientssl = NULL, *serverssl = NULL;
8469     SSL_SESSION *clntsess = NULL;
8470     int testresult = 0;
8471 
8472 #ifdef OPENSSL_NO_TLS1_2
8473     if (tst % 2 == 0)
8474         return 1;
8475 #endif
8476 #ifdef OSSL_NO_USABLE_TLS1_3
8477     if (tst % 2 == 1)
8478         return 1;
8479 #endif
8480 #ifdef OPENSSL_NO_DEPRECATED_3_0
8481     if (tst >= 8 && tst <= 13)
8482         return 1;
8483 #endif
8484 
8485     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
8486 
8487     /* Which tests the ticket key callback should request renewal for */
8488 
8489     if (tst == 10 || tst == 11 || tst == 16 || tst == 17)
8490         tick_key_renew = 1;
8491     else if (tst == 12 || tst == 13 || tst == 18 || tst == 19)
8492         tick_key_renew = -1; /* abort sending the ticket/0-length ticket */
8493     else
8494         tick_key_renew = 0;
8495 
8496     /* Which tests the decrypt ticket callback should request renewal for */
8497     switch (tst) {
8498     case 0:
8499     case 1:
8500         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
8501         break;
8502 
8503     case 2:
8504     case 3:
8505         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
8506         break;
8507 
8508     case 4:
8509     case 5:
8510         tick_dec_ret = SSL_TICKET_RETURN_USE;
8511         break;
8512 
8513     case 6:
8514     case 7:
8515         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
8516         break;
8517 
8518     default:
8519         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8520     }
8521 
8522     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8523                                        TLS_client_method(),
8524                                        TLS1_VERSION,
8525                                        ((tst % 2) == 0) ? TLS1_2_VERSION
8526                                                         : TLS1_3_VERSION,
8527                                        &sctx, &cctx, cert, privkey)))
8528         goto end;
8529 
8530     /*
8531      * We only want sessions to resume from tickets - not the session cache. So
8532      * switch the cache off.
8533      */
8534     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
8535         goto end;
8536 
8537     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
8538                                                  NULL)))
8539         goto end;
8540 
8541     if (tst >= 14) {
8542         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
8543             goto end;
8544 #ifndef OPENSSL_NO_DEPRECATED_3_0
8545     } else if (tst >= 8) {
8546         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
8547             goto end;
8548 #endif
8549     }
8550 
8551     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8552                                              NULL, NULL))
8553             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8554                                                 SSL_ERROR_NONE)))
8555         goto end;
8556 
8557     /*
8558      * The decrypt ticket key callback in TLSv1.2 should be called even though
8559      * we have no ticket yet, because it gets called with a status of
8560      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
8561      * actually send any ticket data). This does not happen in TLSv1.3 because
8562      * it is not valid to send empty ticket data in TLSv1.3.
8563      */
8564     if (!TEST_int_eq(gen_tick_called, 1)
8565             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
8566         goto end;
8567 
8568     gen_tick_called = dec_tick_called = 0;
8569 
8570     clntsess = SSL_get1_session(clientssl);
8571     SSL_shutdown(clientssl);
8572     SSL_shutdown(serverssl);
8573     SSL_free(serverssl);
8574     SSL_free(clientssl);
8575     serverssl = clientssl = NULL;
8576 
8577     /* Now do a resumption */
8578     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8579                                       NULL))
8580             || !TEST_true(SSL_set_session(clientssl, clntsess))
8581             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8582                                                 SSL_ERROR_NONE)))
8583         goto end;
8584 
8585     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
8586             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8587             || tick_key_renew == -1) {
8588         if (!TEST_false(SSL_session_reused(clientssl)))
8589             goto end;
8590     } else {
8591         if (!TEST_true(SSL_session_reused(clientssl)))
8592             goto end;
8593     }
8594 
8595     if (!TEST_int_eq(gen_tick_called,
8596                      (tick_key_renew
8597                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8598                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
8599                      ? 1 : 0)
8600                /* There is no ticket to decrypt in tests 13 and 19 */
8601             || !TEST_int_eq(dec_tick_called, (tst == 13 || tst == 19) ? 0 : 1))
8602         goto end;
8603 
8604     testresult = 1;
8605 
8606  end:
8607     SSL_SESSION_free(clntsess);
8608     SSL_free(serverssl);
8609     SSL_free(clientssl);
8610     SSL_CTX_free(sctx);
8611     SSL_CTX_free(cctx);
8612 
8613     return testresult;
8614 }
8615 
8616 /*
8617  * Test incorrect shutdown.
8618  * Test 0: client does not shutdown properly,
8619  *         server does not set SSL_OP_IGNORE_UNEXPECTED_EOF,
8620  *         server should get SSL_ERROR_SSL
8621  * Test 1: client does not shutdown properly,
8622  *         server sets SSL_OP_IGNORE_UNEXPECTED_EOF,
8623  *         server should get SSL_ERROR_ZERO_RETURN
8624  */
test_incorrect_shutdown(int tst)8625 static int test_incorrect_shutdown(int tst)
8626 {
8627     SSL_CTX *cctx = NULL, *sctx = NULL;
8628     SSL *clientssl = NULL, *serverssl = NULL;
8629     int testresult = 0;
8630     char buf[80];
8631     BIO *c2s;
8632 
8633     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8634                                        TLS_client_method(), 0, 0,
8635                                        &sctx, &cctx, cert, privkey)))
8636         goto end;
8637 
8638     if (tst == 1)
8639         SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
8640 
8641     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8642                                             NULL, NULL)))
8643         goto end;
8644 
8645     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8646                                               SSL_ERROR_NONE)))
8647         goto end;
8648 
8649     c2s = SSL_get_rbio(serverssl);
8650     BIO_set_mem_eof_return(c2s, 0);
8651 
8652     if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf))))
8653         goto end;
8654 
8655     if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL) )
8656         goto end;
8657     if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN) )
8658         goto end;
8659 
8660     testresult = 1;
8661 
8662  end:
8663     SSL_free(serverssl);
8664     SSL_free(clientssl);
8665     SSL_CTX_free(sctx);
8666     SSL_CTX_free(cctx);
8667 
8668     return testresult;
8669 }
8670 
8671 /*
8672  * Test bi-directional shutdown.
8673  * Test 0: TLSv1.2
8674  * Test 1: TLSv1.2, server continues to read/write after client shutdown
8675  * Test 2: TLSv1.3, no pending NewSessionTicket messages
8676  * Test 3: TLSv1.3, pending NewSessionTicket messages
8677  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
8678  *                  sends key update, client reads it
8679  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
8680  *                  sends CertificateRequest, client reads and ignores it
8681  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
8682  *                  doesn't read it
8683  */
test_shutdown(int tst)8684 static int test_shutdown(int tst)
8685 {
8686     SSL_CTX *cctx = NULL, *sctx = NULL;
8687     SSL *clientssl = NULL, *serverssl = NULL;
8688     int testresult = 0;
8689     char msg[] = "A test message";
8690     char buf[80];
8691     size_t written, readbytes;
8692     SSL_SESSION *sess;
8693 
8694 #ifdef OPENSSL_NO_TLS1_2
8695     if (tst <= 1)
8696         return 1;
8697 #endif
8698 #ifdef OSSL_NO_USABLE_TLS1_3
8699     if (tst >= 2)
8700         return 1;
8701 #endif
8702 
8703     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8704                                        TLS_client_method(),
8705                                        TLS1_VERSION,
8706                                        (tst <= 1) ? TLS1_2_VERSION
8707                                                   : TLS1_3_VERSION,
8708                                        &sctx, &cctx, cert, privkey)))
8709         goto end;
8710 
8711     if (tst == 5)
8712         SSL_CTX_set_post_handshake_auth(cctx, 1);
8713 
8714     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8715                                              NULL, NULL)))
8716         goto end;
8717 
8718     if (tst == 3) {
8719         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
8720                                                   SSL_ERROR_NONE, 1, 0))
8721                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8722                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
8723             goto end;
8724     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8725                                               SSL_ERROR_NONE))
8726             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8727             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
8728         goto end;
8729     }
8730 
8731     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8732         goto end;
8733 
8734     if (tst >= 4) {
8735         /*
8736          * Reading on the server after the client has sent close_notify should
8737          * fail and provide SSL_ERROR_ZERO_RETURN
8738          */
8739         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
8740                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
8741                                 SSL_ERROR_ZERO_RETURN)
8742                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
8743                                 SSL_RECEIVED_SHUTDOWN)
8744                    /*
8745                     * Even though we're shutdown on receive we should still be
8746                     * able to write.
8747                     */
8748                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8749             goto end;
8750         if (tst == 4
8751                 && !TEST_true(SSL_key_update(serverssl,
8752                                              SSL_KEY_UPDATE_REQUESTED)))
8753             goto end;
8754         if (tst == 5) {
8755             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
8756             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
8757                 goto end;
8758         }
8759         if ((tst == 4 || tst == 5)
8760                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8761             goto end;
8762         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8763             goto end;
8764         if (tst == 4 || tst == 5) {
8765             /* Should still be able to read data from server */
8766             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8767                                        &readbytes))
8768                     || !TEST_size_t_eq(readbytes, sizeof(msg))
8769                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
8770                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8771                                               &readbytes))
8772                     || !TEST_size_t_eq(readbytes, sizeof(msg))
8773                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
8774                 goto end;
8775         }
8776     }
8777 
8778     /* Writing on the client after sending close_notify shouldn't be possible */
8779     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
8780         goto end;
8781 
8782     if (tst < 4) {
8783         /*
8784          * For these tests the client has sent close_notify but it has not yet
8785          * been received by the server. The server has not sent close_notify
8786          * yet.
8787          */
8788         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
8789                    /*
8790                     * Writing on the server after sending close_notify shouldn't
8791                     * be possible.
8792                     */
8793                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8794                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
8795                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8796                 || !TEST_true(SSL_SESSION_is_resumable(sess))
8797                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
8798             goto end;
8799     } else if (tst == 4 || tst == 5) {
8800         /*
8801          * In this test the client has sent close_notify and it has been
8802          * received by the server which has responded with a close_notify. The
8803          * client needs to read the close_notify sent by the server.
8804          */
8805         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
8806                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8807                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
8808             goto end;
8809     } else {
8810         /*
8811          * tst == 6
8812          *
8813          * The client has sent close_notify and is expecting a close_notify
8814          * back, but instead there is application data first. The shutdown
8815          * should fail with a fatal error.
8816          */
8817         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
8818                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
8819             goto end;
8820     }
8821 
8822     testresult = 1;
8823 
8824  end:
8825     SSL_free(serverssl);
8826     SSL_free(clientssl);
8827     SSL_CTX_free(sctx);
8828     SSL_CTX_free(cctx);
8829 
8830     return testresult;
8831 }
8832 
8833 /*
8834  * Test that sending close_notify alerts works correctly in the case of a
8835  * retryable write failure.
8836  */
test_async_shutdown(void)8837 static int test_async_shutdown(void)
8838 {
8839     SSL_CTX *cctx = NULL, *sctx = NULL;
8840     SSL *clientssl = NULL, *serverssl = NULL;
8841     int testresult = 0;
8842     BIO *bretry = BIO_new(bio_s_always_retry()), *tmp = NULL;
8843 
8844     if (!TEST_ptr(bretry))
8845         goto end;
8846 
8847     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8848                                        TLS_client_method(),
8849                                        0, 0,
8850                                        &sctx, &cctx, cert, privkey)))
8851         goto end;
8852 
8853     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8854                                       NULL)))
8855         goto end;
8856 
8857     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8858         goto end;
8859 
8860     /* Close write side of clientssl */
8861     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8862         goto end;
8863 
8864     tmp = SSL_get_wbio(serverssl);
8865     if (!TEST_true(BIO_up_ref(tmp))) {
8866         tmp = NULL;
8867         goto end;
8868     }
8869     SSL_set0_wbio(serverssl, bretry);
8870     bretry = NULL;
8871 
8872     /* First server shutdown should fail because of a retrable write failure */
8873     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
8874             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
8875         goto end;
8876 
8877     /* Second server shutdown should fail for the same reason */
8878     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
8879             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
8880         goto end;
8881 
8882     SSL_set0_wbio(serverssl, tmp);
8883     tmp = NULL;
8884 
8885     /* Third server shutdown should send close_notify */
8886     if (!TEST_int_eq(SSL_shutdown(serverssl), 0))
8887         goto end;
8888 
8889     /* Fourth server shutdown should read close_notify from client and finish */
8890     if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8891         goto end;
8892 
8893     /* Client should also successfully fully shutdown */
8894     if (!TEST_int_eq(SSL_shutdown(clientssl), 1))
8895         goto end;
8896 
8897     testresult = 1;
8898  end:
8899     SSL_free(serverssl);
8900     SSL_free(clientssl);
8901     SSL_CTX_free(sctx);
8902     SSL_CTX_free(cctx);
8903     BIO_free(bretry);
8904     BIO_free(tmp);
8905 
8906     return testresult;
8907 }
8908 
8909 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
8910 static int cert_cb_cnt;
8911 
load_chain(const char * file,EVP_PKEY ** pkey,X509 ** x509,STACK_OF (X509)* chain)8912 static int load_chain(const char *file, EVP_PKEY **pkey, X509 **x509,
8913                       STACK_OF(X509) *chain)
8914 {
8915     char *path = test_mk_file_path(certsdir, file);
8916     BIO *in = NULL;
8917     X509 *x = NULL;
8918     int ok = 0;
8919 
8920     if (path == NULL)
8921         return 0;
8922     if ((in = BIO_new(BIO_s_file())) == NULL
8923         || BIO_read_filename(in, path) <= 0)
8924         goto out;
8925     if (pkey == NULL) {
8926         if ((x = X509_new_ex(libctx, NULL)) == NULL
8927             || PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
8928             goto out;
8929         if (chain == NULL)
8930             *x509 = x;
8931         else if (!sk_X509_push(chain, x))
8932             goto out;
8933     } else if (PEM_read_bio_PrivateKey_ex(in, pkey, NULL, NULL,
8934                                           libctx, NULL) == NULL) {
8935         goto out;
8936     }
8937 
8938     x = NULL;
8939     ok = 1;
8940  out:
8941     X509_free(x);
8942     BIO_free(in);
8943     OPENSSL_free(path);
8944     return ok;
8945 }
8946 
cert_cb(SSL * s,void * arg)8947 static int cert_cb(SSL *s, void *arg)
8948 {
8949     SSL_CTX *ctx = (SSL_CTX *)arg;
8950     EVP_PKEY *pkey = NULL;
8951     X509 *x509 = NULL, *x = NULL;
8952     STACK_OF(X509) *chain = NULL;
8953     int ret = 0;
8954 
8955     if (cert_cb_cnt == 0) {
8956         /* Suspend the handshake */
8957         cert_cb_cnt++;
8958         return -1;
8959     } else if (cert_cb_cnt == 1) {
8960         /*
8961          * Update the SSL_CTX, set the certificate and private key and then
8962          * continue the handshake normally.
8963          */
8964         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
8965             return 0;
8966 
8967         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
8968                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
8969                                                       SSL_FILETYPE_PEM))
8970                 || !TEST_true(SSL_check_private_key(s)))
8971             return 0;
8972         cert_cb_cnt++;
8973         return 1;
8974     } else if (cert_cb_cnt == 3) {
8975         int rv;
8976 
8977         chain = sk_X509_new_null();
8978         if (!TEST_ptr(chain)
8979             || !TEST_true(load_chain("ca-cert.pem", NULL, NULL, chain))
8980             || !TEST_true(load_chain("root-cert.pem", NULL, NULL, chain))
8981             || !TEST_true(load_chain("p256-ee-rsa-ca-cert.pem", NULL,
8982                                      &x509, NULL))
8983             || !TEST_true(load_chain("p256-ee-rsa-ca-key.pem", &pkey,
8984                                      NULL, NULL)))
8985             goto out;
8986         rv = SSL_check_chain(s, x509, pkey, chain);
8987         /*
8988          * If the cert doesn't show as valid here (e.g., because we don't
8989          * have any shared sigalgs), then we will not set it, and there will
8990          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
8991          * will cause tls_choose_sigalgs() to fail the connection.
8992          */
8993         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
8994                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
8995             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
8996                 goto out;
8997         }
8998 
8999         ret = 1;
9000     }
9001 
9002     /* Abort the handshake */
9003  out:
9004     EVP_PKEY_free(pkey);
9005     X509_free(x509);
9006     X509_free(x);
9007     OSSL_STACK_OF_X509_free(chain);
9008     return ret;
9009 }
9010 
9011 /*
9012  * Test the certificate callback.
9013  * Test 0: Callback fails
9014  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
9015  * Test 2: Success - SSL_set_SSL_CTX() in the callback
9016  * Test 3: Success - Call SSL_check_chain from the callback
9017  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
9018  *                   chain
9019  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
9020  */
test_cert_cb_int(int prot,int tst)9021 static int test_cert_cb_int(int prot, int tst)
9022 {
9023     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
9024     SSL *clientssl = NULL, *serverssl = NULL;
9025     int testresult = 0, ret;
9026 
9027 #ifdef OPENSSL_NO_EC
9028     /* We use an EC cert in these tests, so we skip in a no-ec build */
9029     if (tst >= 3)
9030         return 1;
9031 #endif
9032 
9033     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9034                                        TLS_client_method(),
9035                                        prot,
9036                                        prot,
9037                                        &sctx, &cctx, NULL, NULL)))
9038         goto end;
9039 
9040     if (tst == 0)
9041         cert_cb_cnt = -1;
9042     else if (tst >= 3)
9043         cert_cb_cnt = 3;
9044     else
9045         cert_cb_cnt = 0;
9046 
9047     if (tst == 2) {
9048         snictx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
9049         if (!TEST_ptr(snictx))
9050             goto end;
9051     }
9052 
9053     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
9054 
9055     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9056                                       NULL, NULL)))
9057         goto end;
9058 
9059     if (tst == 4) {
9060         /*
9061          * We cause SSL_check_chain() to fail by specifying sig_algs that
9062          * the chain doesn't meet (the root uses an RSA cert)
9063          */
9064         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
9065                                              "ecdsa_secp256r1_sha256")))
9066             goto end;
9067     } else if (tst == 5) {
9068         /*
9069          * We cause SSL_check_chain() to fail by specifying sig_algs that
9070          * the ee cert doesn't meet (the ee uses an ECDSA cert)
9071          */
9072         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
9073                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
9074             goto end;
9075     }
9076 
9077     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
9078     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
9079             || (tst > 0
9080                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
9081         goto end;
9082     }
9083 
9084     testresult = 1;
9085 
9086  end:
9087     SSL_free(serverssl);
9088     SSL_free(clientssl);
9089     SSL_CTX_free(sctx);
9090     SSL_CTX_free(cctx);
9091     SSL_CTX_free(snictx);
9092 
9093     return testresult;
9094 }
9095 #endif
9096 
test_cert_cb(int tst)9097 static int test_cert_cb(int tst)
9098 {
9099     int testresult = 1;
9100 
9101 #ifndef OPENSSL_NO_TLS1_2
9102     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
9103 #endif
9104 #ifndef OSSL_NO_USABLE_TLS1_3
9105     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
9106 #endif
9107 
9108     return testresult;
9109 }
9110 
client_cert_cb(SSL * ssl,X509 ** x509,EVP_PKEY ** pkey)9111 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
9112 {
9113     X509 *xcert;
9114     EVP_PKEY *privpkey;
9115     BIO *in = NULL;
9116     BIO *priv_in = NULL;
9117 
9118     /* Check that SSL_get0_peer_certificate() returns something sensible */
9119     if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
9120         return 0;
9121 
9122     in = BIO_new_file(cert, "r");
9123     if (!TEST_ptr(in))
9124         return 0;
9125 
9126     if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL))
9127             || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
9128             || !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
9129             || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
9130                                                                NULL, NULL,
9131                                                                libctx, NULL)))
9132         goto err;
9133 
9134     *x509 = xcert;
9135     *pkey = privpkey;
9136 
9137     BIO_free(in);
9138     BIO_free(priv_in);
9139     return 1;
9140 err:
9141     X509_free(xcert);
9142     BIO_free(in);
9143     BIO_free(priv_in);
9144     return 0;
9145 }
9146 
test_client_cert_cb(int tst)9147 static int test_client_cert_cb(int tst)
9148 {
9149     SSL_CTX *cctx = NULL, *sctx = NULL;
9150     SSL *clientssl = NULL, *serverssl = NULL;
9151     int testresult = 0;
9152 
9153 #ifdef OPENSSL_NO_TLS1_2
9154     if (tst == 0)
9155         return 1;
9156 #endif
9157 #ifdef OSSL_NO_USABLE_TLS1_3
9158     if (tst == 1)
9159         return 1;
9160 #endif
9161 
9162     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9163                                        TLS_client_method(),
9164                                        TLS1_VERSION,
9165                                        tst == 0 ? TLS1_2_VERSION
9166                                                 : TLS1_3_VERSION,
9167                                        &sctx, &cctx, cert, privkey)))
9168         goto end;
9169 
9170     /*
9171      * Test that setting a client_cert_cb results in a client certificate being
9172      * sent.
9173      */
9174     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
9175     SSL_CTX_set_verify(sctx,
9176                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
9177                        verify_cb);
9178 
9179     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9180                                       NULL, NULL))
9181             || !TEST_true(create_ssl_connection(serverssl, clientssl,
9182                                                 SSL_ERROR_NONE)))
9183         goto end;
9184 
9185     testresult = 1;
9186 
9187  end:
9188     SSL_free(serverssl);
9189     SSL_free(clientssl);
9190     SSL_CTX_free(sctx);
9191     SSL_CTX_free(cctx);
9192 
9193     return testresult;
9194 }
9195 
9196 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
9197 /*
9198  * Test setting certificate authorities on both client and server.
9199  *
9200  * Test 0: SSL_CTX_set0_CA_list() only
9201  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
9202  * Test 2: Only SSL_CTX_set_client_CA_list()
9203  */
test_ca_names_int(int prot,int tst)9204 static int test_ca_names_int(int prot, int tst)
9205 {
9206     SSL_CTX *cctx = NULL, *sctx = NULL;
9207     SSL *clientssl = NULL, *serverssl = NULL;
9208     int testresult = 0;
9209     size_t i;
9210     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
9211     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
9212     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
9213     const STACK_OF(X509_NAME) *sktmp = NULL;
9214 
9215     for (i = 0; i < OSSL_NELEM(name); i++) {
9216         name[i] = X509_NAME_new();
9217         if (!TEST_ptr(name[i])
9218                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
9219                                                          MBSTRING_ASC,
9220                                                          (unsigned char *)
9221                                                          strnames[i],
9222                                                          -1, -1, 0)))
9223             goto end;
9224     }
9225 
9226     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9227                                        TLS_client_method(),
9228                                        TLS1_VERSION,
9229                                        prot,
9230                                        &sctx, &cctx, cert, privkey)))
9231         goto end;
9232 
9233     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
9234 
9235     if (tst == 0 || tst == 1) {
9236         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9237                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
9238                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
9239                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9240                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
9241                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
9242             goto end;
9243 
9244         SSL_CTX_set0_CA_list(sctx, sk1);
9245         SSL_CTX_set0_CA_list(cctx, sk2);
9246         sk1 = sk2 = NULL;
9247     }
9248     if (tst == 1 || tst == 2) {
9249         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9250                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
9251                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
9252                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9253                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
9254                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
9255             goto end;
9256 
9257         SSL_CTX_set_client_CA_list(sctx, sk1);
9258         SSL_CTX_set_client_CA_list(cctx, sk2);
9259         sk1 = sk2 = NULL;
9260     }
9261 
9262     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9263                                       NULL, NULL))
9264             || !TEST_true(create_ssl_connection(serverssl, clientssl,
9265                                                 SSL_ERROR_NONE)))
9266         goto end;
9267 
9268     /*
9269      * We only expect certificate authorities to have been sent to the server
9270      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
9271      */
9272     sktmp = SSL_get0_peer_CA_list(serverssl);
9273     if (prot == TLS1_3_VERSION
9274             && (tst == 0 || tst == 1)) {
9275         if (!TEST_ptr(sktmp)
9276                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9277                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9278                                               name[0]), 0)
9279                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9280                                               name[1]), 0))
9281             goto end;
9282     } else if (!TEST_ptr_null(sktmp)) {
9283         goto end;
9284     }
9285 
9286     /*
9287      * In all tests we expect certificate authorities to have been sent to the
9288      * client. However, SSL_set_client_CA_list() should override
9289      * SSL_set0_CA_list()
9290      */
9291     sktmp = SSL_get0_peer_CA_list(clientssl);
9292     if (!TEST_ptr(sktmp)
9293             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9294             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9295                                           name[tst == 0 ? 0 : 2]), 0)
9296             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9297                                           name[tst == 0 ? 1 : 3]), 0))
9298         goto end;
9299 
9300     testresult = 1;
9301 
9302  end:
9303     SSL_free(serverssl);
9304     SSL_free(clientssl);
9305     SSL_CTX_free(sctx);
9306     SSL_CTX_free(cctx);
9307     for (i = 0; i < OSSL_NELEM(name); i++)
9308         X509_NAME_free(name[i]);
9309     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
9310     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
9311 
9312     return testresult;
9313 }
9314 #endif
9315 
test_ca_names(int tst)9316 static int test_ca_names(int tst)
9317 {
9318     int testresult = 1;
9319 
9320 #ifndef OPENSSL_NO_TLS1_2
9321     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
9322 #endif
9323 #ifndef OSSL_NO_USABLE_TLS1_3
9324     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
9325 #endif
9326 
9327     return testresult;
9328 }
9329 
9330 #ifndef OPENSSL_NO_TLS1_2
9331 static const char *multiblock_cipherlist_data[]=
9332 {
9333     "AES128-SHA",
9334     "AES128-SHA256",
9335     "AES256-SHA",
9336     "AES256-SHA256",
9337 };
9338 
9339 /* Reduce the fragment size - so the multiblock test buffer can be small */
9340 # define MULTIBLOCK_FRAGSIZE 512
9341 
test_multiblock_write(int test_index)9342 static int test_multiblock_write(int test_index)
9343 {
9344     static const char *fetchable_ciphers[]=
9345     {
9346         "AES-128-CBC-HMAC-SHA1",
9347         "AES-128-CBC-HMAC-SHA256",
9348         "AES-256-CBC-HMAC-SHA1",
9349         "AES-256-CBC-HMAC-SHA256"
9350     };
9351     const char *cipherlist = multiblock_cipherlist_data[test_index];
9352     const SSL_METHOD *smeth = TLS_server_method();
9353     const SSL_METHOD *cmeth = TLS_client_method();
9354     int min_version = TLS1_VERSION;
9355     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
9356     SSL_CTX *cctx = NULL, *sctx = NULL;
9357     SSL *clientssl = NULL, *serverssl = NULL;
9358     int testresult = 0;
9359 
9360     /*
9361      * Choose a buffer large enough to perform a multi-block operation
9362      * i.e: write_len >= 4 * frag_size
9363      * 9 * is chosen so that multiple multiblocks are used + some leftover.
9364      */
9365     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
9366     unsigned char buf[sizeof(msg)], *p = buf;
9367     size_t readbytes, written, len;
9368     EVP_CIPHER *ciph = NULL;
9369 
9370     /*
9371      * Check if the cipher exists before attempting to use it since it only has
9372      * a hardware specific implementation.
9373      */
9374     ciph = EVP_CIPHER_fetch(libctx, fetchable_ciphers[test_index], "");
9375     if (ciph == NULL) {
9376         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
9377         return 1;
9378     }
9379     EVP_CIPHER_free(ciph);
9380 
9381     /* Set up a buffer with some data that will be sent to the client */
9382     RAND_bytes(msg, sizeof(msg));
9383 
9384     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
9385                                        max_version, &sctx, &cctx, cert,
9386                                        privkey)))
9387         goto end;
9388 
9389     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
9390         goto end;
9391 
9392     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9393                                       NULL, NULL)))
9394             goto end;
9395 
9396     /* settings to force it to use AES-CBC-HMAC_SHA */
9397     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
9398     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
9399        goto end;
9400 
9401     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9402         goto end;
9403 
9404     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
9405         || !TEST_size_t_eq(written, sizeof(msg)))
9406         goto end;
9407 
9408     len = written;
9409     while (len > 0) {
9410         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
9411             goto end;
9412         p += readbytes;
9413         len -= readbytes;
9414     }
9415     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
9416         goto end;
9417 
9418     testresult = 1;
9419 end:
9420     SSL_free(serverssl);
9421     SSL_free(clientssl);
9422     SSL_CTX_free(sctx);
9423     SSL_CTX_free(cctx);
9424 
9425     return testresult;
9426 }
9427 #endif /* OPENSSL_NO_TLS1_2 */
9428 
test_session_timeout(int test)9429 static int test_session_timeout(int test)
9430 {
9431     /*
9432      * Test session ordering and timeout
9433      * Can't explicitly test performance of the new code,
9434      * but can test to see if the ordering of the sessions
9435      * are correct, and they are removed as expected
9436      */
9437     SSL_SESSION *early = NULL;
9438     SSL_SESSION *middle = NULL;
9439     SSL_SESSION *late = NULL;
9440     SSL_CTX *ctx;
9441     int testresult = 0;
9442     time_t now = time(NULL);
9443 #define TIMEOUT 10
9444 
9445     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
9446         || !TEST_ptr(early = SSL_SESSION_new())
9447         || !TEST_ptr(middle = SSL_SESSION_new())
9448         || !TEST_ptr(late = SSL_SESSION_new()))
9449         goto end;
9450 
9451     /* assign unique session ids */
9452     early->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9453     memset(early->session_id, 1, SSL3_SSL_SESSION_ID_LENGTH);
9454     middle->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9455     memset(middle->session_id, 2, SSL3_SSL_SESSION_ID_LENGTH);
9456     late->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9457     memset(late->session_id, 3, SSL3_SSL_SESSION_ID_LENGTH);
9458 
9459     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9460         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9461         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9462         goto end;
9463 
9464     /* Make sure they are all added */
9465     if (!TEST_ptr(early->prev)
9466         || !TEST_ptr(middle->prev)
9467         || !TEST_ptr(late->prev))
9468         goto end;
9469 
9470     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now - 10), 0)
9471         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(middle, now), 0)
9472         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(late, now + 10), 0))
9473         goto end;
9474 
9475     if (!TEST_int_ne(SSL_SESSION_set_timeout(early, TIMEOUT), 0)
9476         || !TEST_int_ne(SSL_SESSION_set_timeout(middle, TIMEOUT), 0)
9477         || !TEST_int_ne(SSL_SESSION_set_timeout(late, TIMEOUT), 0))
9478         goto end;
9479 
9480     /* Make sure they are all still there */
9481     if (!TEST_ptr(early->prev)
9482         || !TEST_ptr(middle->prev)
9483         || !TEST_ptr(late->prev))
9484         goto end;
9485 
9486     /* Make sure they are in the expected order */
9487     if (!TEST_ptr_eq(late->next, middle)
9488         || !TEST_ptr_eq(middle->next, early)
9489         || !TEST_ptr_eq(early->prev, middle)
9490         || !TEST_ptr_eq(middle->prev, late))
9491         goto end;
9492 
9493     /* This should remove "early" */
9494     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT - 1);
9495     if (!TEST_ptr_null(early->prev)
9496         || !TEST_ptr(middle->prev)
9497         || !TEST_ptr(late->prev))
9498         goto end;
9499 
9500     /* This should remove "middle" */
9501     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 1);
9502     if (!TEST_ptr_null(early->prev)
9503         || !TEST_ptr_null(middle->prev)
9504         || !TEST_ptr(late->prev))
9505         goto end;
9506 
9507     /* This should remove "late" */
9508     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 11);
9509     if (!TEST_ptr_null(early->prev)
9510         || !TEST_ptr_null(middle->prev)
9511         || !TEST_ptr_null(late->prev))
9512         goto end;
9513 
9514     /* Add them back in again */
9515     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9516         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9517         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9518         goto end;
9519 
9520     /* Make sure they are all added */
9521     if (!TEST_ptr(early->prev)
9522         || !TEST_ptr(middle->prev)
9523         || !TEST_ptr(late->prev))
9524         goto end;
9525 
9526     /* This should remove all of them */
9527     SSL_CTX_flush_sessions_ex(ctx, 0);
9528     if (!TEST_ptr_null(early->prev)
9529         || !TEST_ptr_null(middle->prev)
9530         || !TEST_ptr_null(late->prev))
9531         goto end;
9532 
9533     (void)SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_UPDATE_TIME
9534                                          | SSL_CTX_get_session_cache_mode(ctx));
9535 
9536     /* make sure |now| is NOT  equal to the current time */
9537     now -= 10;
9538     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now), 0)
9539         || !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9540         || !TEST_time_t_ne(SSL_SESSION_get_time_ex(early), now))
9541         goto end;
9542 
9543     testresult = 1;
9544  end:
9545     SSL_CTX_free(ctx);
9546     SSL_SESSION_free(early);
9547     SSL_SESSION_free(middle);
9548     SSL_SESSION_free(late);
9549     return testresult;
9550 }
9551 
9552 /*
9553  * Test that a session cache overflow works as expected
9554  * Test 0: TLSv1.3, timeout on new session later than old session
9555  * Test 1: TLSv1.2, timeout on new session later than old session
9556  * Test 2: TLSv1.3, timeout on new session earlier than old session
9557  * Test 3: TLSv1.2, timeout on new session earlier than old session
9558  */
9559 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
test_session_cache_overflow(int idx)9560 static int test_session_cache_overflow(int idx)
9561 {
9562     SSL_CTX *sctx = NULL, *cctx = NULL;
9563     SSL *serverssl = NULL, *clientssl = NULL;
9564     int testresult = 0;
9565     SSL_SESSION *sess = NULL;
9566 
9567 #ifdef OSSL_NO_USABLE_TLS1_3
9568     /* If no TLSv1.3 available then do nothing in this case */
9569     if (idx % 2 == 0)
9570         return TEST_skip("No TLSv1.3 available");
9571 #endif
9572 #ifdef OPENSSL_NO_TLS1_2
9573     /* If no TLSv1.2 available then do nothing in this case */
9574     if (idx % 2 == 1)
9575         return TEST_skip("No TLSv1.2 available");
9576 #endif
9577 
9578     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9579                                        TLS_client_method(), TLS1_VERSION,
9580                                        (idx % 2 == 0) ? TLS1_3_VERSION
9581                                                       : TLS1_2_VERSION,
9582                                        &sctx, &cctx, cert, privkey))
9583             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET)))
9584         goto end;
9585 
9586     SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
9587     get_sess_val = NULL;
9588 
9589     SSL_CTX_sess_set_cache_size(sctx, 1);
9590 
9591     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9592                                       NULL, NULL)))
9593         goto end;
9594 
9595     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9596         goto end;
9597 
9598     if (idx > 1) {
9599         sess = SSL_get_session(serverssl);
9600         if (!TEST_ptr(sess))
9601             goto end;
9602 
9603         /*
9604          * Cause this session to have a longer timeout than the next session to
9605          * be added.
9606          */
9607         if (!TEST_true(SSL_SESSION_set_timeout(sess, LONG_MAX))) {
9608             sess = NULL;
9609             goto end;
9610         }
9611         sess = NULL;
9612     }
9613 
9614     SSL_shutdown(serverssl);
9615     SSL_shutdown(clientssl);
9616     SSL_free(serverssl);
9617     SSL_free(clientssl);
9618     serverssl = clientssl = NULL;
9619 
9620     /*
9621      * Session cache size is 1 and we already populated the cache with a session
9622      * so the next connection should cause an overflow.
9623      */
9624 
9625     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9626                                       NULL, NULL)))
9627         goto end;
9628 
9629     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9630         goto end;
9631 
9632     /*
9633      * The session we just negotiated may have been already removed from the
9634      * internal cache - but we will return it anyway from our external cache.
9635      */
9636     get_sess_val = SSL_get_session(serverssl);
9637     if (!TEST_ptr(get_sess_val))
9638         goto end;
9639     sess = SSL_get1_session(clientssl);
9640     if (!TEST_ptr(sess))
9641         goto end;
9642 
9643     SSL_shutdown(serverssl);
9644     SSL_shutdown(clientssl);
9645     SSL_free(serverssl);
9646     SSL_free(clientssl);
9647     serverssl = clientssl = NULL;
9648 
9649     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9650                                       NULL, NULL)))
9651         goto end;
9652 
9653     if (!TEST_true(SSL_set_session(clientssl, sess)))
9654         goto end;
9655 
9656     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9657         goto end;
9658 
9659     testresult = 1;
9660 
9661  end:
9662     SSL_free(serverssl);
9663     SSL_free(clientssl);
9664     SSL_CTX_free(sctx);
9665     SSL_CTX_free(cctx);
9666     SSL_SESSION_free(sess);
9667 
9668     return testresult;
9669 }
9670 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
9671 
9672 /*
9673  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
9674  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
9675  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
9676  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
9677  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
9678  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
9679  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
9680  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
9681  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
9682  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
9683  */
test_servername(int tst)9684 static int test_servername(int tst)
9685 {
9686     SSL_CTX *cctx = NULL, *sctx = NULL;
9687     SSL *clientssl = NULL, *serverssl = NULL;
9688     int testresult = 0;
9689     SSL_SESSION *sess = NULL;
9690     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
9691 
9692 #ifdef OPENSSL_NO_TLS1_2
9693     if (tst <= 4)
9694         return 1;
9695 #endif
9696 #ifdef OSSL_NO_USABLE_TLS1_3
9697     if (tst >= 5)
9698         return 1;
9699 #endif
9700 
9701     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9702                                        TLS_client_method(),
9703                                        TLS1_VERSION,
9704                                        (tst <= 4) ? TLS1_2_VERSION
9705                                                   : TLS1_3_VERSION,
9706                                        &sctx, &cctx, cert, privkey))
9707             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9708                                              NULL, NULL)))
9709         goto end;
9710 
9711     if (tst != 1 && tst != 6) {
9712         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
9713                                                               hostname_cb)))
9714             goto end;
9715     }
9716 
9717     if (tst != 3 && tst != 8) {
9718         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9719             goto end;
9720         sexpectedhost = cexpectedhost = "goodhost";
9721     }
9722 
9723     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9724         goto end;
9725 
9726     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
9727                      cexpectedhost)
9728             || !TEST_str_eq(SSL_get_servername(serverssl,
9729                                                TLSEXT_NAMETYPE_host_name),
9730                             sexpectedhost))
9731         goto end;
9732 
9733     /* Now repeat with a resumption handshake */
9734 
9735     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
9736             || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
9737             || !TEST_true(SSL_SESSION_is_resumable(sess))
9738             || !TEST_int_eq(SSL_shutdown(serverssl), 0))
9739         goto end;
9740 
9741     SSL_free(clientssl);
9742     SSL_free(serverssl);
9743     clientssl = serverssl = NULL;
9744 
9745     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9746                                       NULL)))
9747         goto end;
9748 
9749     if (!TEST_true(SSL_set_session(clientssl, sess)))
9750         goto end;
9751 
9752     sexpectedhost = cexpectedhost = "goodhost";
9753     if (tst == 2 || tst == 7) {
9754         /* Set an inconsistent hostname */
9755         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
9756             goto end;
9757         /*
9758          * In TLSv1.2 we expect the hostname from the original handshake, in
9759          * TLSv1.3 we expect the hostname from this handshake
9760          */
9761         if (tst == 7)
9762             sexpectedhost = cexpectedhost = "altgoodhost";
9763 
9764         if (!TEST_str_eq(SSL_get_servername(clientssl,
9765                                             TLSEXT_NAMETYPE_host_name),
9766                          "altgoodhost"))
9767             goto end;
9768     } else if (tst == 4 || tst == 9) {
9769         /*
9770          * A TLSv1.3 session does not associate a session with a servername,
9771          * but a TLSv1.2 session does.
9772          */
9773         if (tst == 9)
9774             sexpectedhost = cexpectedhost = NULL;
9775 
9776         if (!TEST_str_eq(SSL_get_servername(clientssl,
9777                                             TLSEXT_NAMETYPE_host_name),
9778                          cexpectedhost))
9779             goto end;
9780     } else {
9781         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9782             goto end;
9783         /*
9784          * In a TLSv1.2 resumption where the hostname was not acknowledged
9785          * we expect the hostname on the server to be empty. On the client we
9786          * return what was requested in this case.
9787          *
9788          * Similarly if the client didn't set a hostname on an original TLSv1.2
9789          * session but is now, the server hostname will be empty, but the client
9790          * is as we set it.
9791          */
9792         if (tst == 1 || tst == 3)
9793             sexpectedhost = NULL;
9794 
9795         if (!TEST_str_eq(SSL_get_servername(clientssl,
9796                                             TLSEXT_NAMETYPE_host_name),
9797                          "goodhost"))
9798             goto end;
9799     }
9800 
9801     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9802         goto end;
9803 
9804     if (!TEST_true(SSL_session_reused(clientssl))
9805             || !TEST_true(SSL_session_reused(serverssl))
9806             || !TEST_str_eq(SSL_get_servername(clientssl,
9807                                                TLSEXT_NAMETYPE_host_name),
9808                             cexpectedhost)
9809             || !TEST_str_eq(SSL_get_servername(serverssl,
9810                                                TLSEXT_NAMETYPE_host_name),
9811                             sexpectedhost))
9812         goto end;
9813 
9814     testresult = 1;
9815 
9816  end:
9817     SSL_SESSION_free(sess);
9818     SSL_free(serverssl);
9819     SSL_free(clientssl);
9820     SSL_CTX_free(sctx);
9821     SSL_CTX_free(cctx);
9822 
9823     return testresult;
9824 }
9825 
test_unknown_sigalgs_groups(void)9826 static int test_unknown_sigalgs_groups(void)
9827 {
9828     int ret = 0;
9829     SSL_CTX *ctx = NULL;
9830 
9831     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
9832         goto end;
9833 
9834     if (!TEST_int_gt(SSL_CTX_set1_sigalgs_list(ctx,
9835                                                "RSA+SHA256:?nonexistent:?RSA+SHA512"),
9836                                                0))
9837         goto end;
9838     if (!TEST_size_t_eq(ctx->cert->conf_sigalgslen, 2)
9839         || !TEST_int_eq(ctx->cert->conf_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
9840         || !TEST_int_eq(ctx->cert->conf_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
9841         goto end;
9842 
9843     if (!TEST_int_gt(SSL_CTX_set1_client_sigalgs_list(ctx,
9844                                                       "RSA+SHA256:?nonexistent:?RSA+SHA512"),
9845                                                       0))
9846         goto end;
9847     if (!TEST_size_t_eq(ctx->cert->client_sigalgslen, 2)
9848         || !TEST_int_eq(ctx->cert->client_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
9849         || !TEST_int_eq(ctx->cert->client_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
9850         goto end;
9851 
9852     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
9853                                               "nonexistent"),
9854                                               0))
9855         goto end;
9856 
9857     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx,
9858                                               "?nonexistent1:?nonexistent2:?nonexistent3"),
9859                                               0))
9860         goto end;
9861 
9862 #ifndef OPENSSL_NO_EC
9863     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
9864                                               "P-256:nonexistent"),
9865                                               0))
9866         goto end;
9867 
9868     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx,
9869                                               "P-384:?nonexistent:?P-521"),
9870                                               0))
9871         goto end;
9872     if (!TEST_size_t_eq(ctx->ext.supportedgroups_len, 2)
9873         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp384r1)
9874         || !TEST_int_eq(ctx->ext.supportedgroups[1], OSSL_TLS_GROUP_ID_secp521r1))
9875         goto end;
9876 #endif
9877 
9878     ret = 1;
9879  end:
9880     SSL_CTX_free(ctx);
9881     return ret;
9882 }
9883 
9884 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM)
test_configuration_of_groups(void)9885 static int test_configuration_of_groups(void)
9886 {
9887     int ret = 0;
9888     SSL_CTX *ctx = NULL;
9889     size_t groups_len;
9890 
9891     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
9892         goto end;
9893     groups_len = ctx->ext.supportedgroups_len;
9894 
9895     if (!TEST_size_t_gt(groups_len, 0)
9896         || !TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT"), 0)
9897         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len))
9898         goto end;
9899 
9900     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT:-?P-256"), 0)
9901 # if !defined(OPENSSL_NO_EC)
9902         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len - 1)
9903 # else
9904         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, groups_len)
9905 # endif
9906         )
9907         goto end;
9908 
9909 # if !defined(OPENSSL_NO_EC)
9910     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "?P-256:?P-521:-?P-256"), 0)
9911         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, 1)
9912         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp521r1)
9913         )
9914         goto end;
9915 # endif
9916 
9917     ret = 1;
9918 
9919 end:
9920     SSL_CTX_free(ctx);
9921     return ret;
9922 }
9923 #endif
9924 
9925 #if !defined(OPENSSL_NO_EC) \
9926     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
9927 /*
9928  * Test that if signature algorithms are not available, then we do not offer or
9929  * accept them.
9930  * Test 0: Two RSA sig algs available: both RSA sig algs shared
9931  * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared
9932  * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared
9933  * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared
9934  * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared
9935  * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared
9936  */
test_sigalgs_available(int idx)9937 static int test_sigalgs_available(int idx)
9938 {
9939     SSL_CTX *cctx = NULL, *sctx = NULL;
9940     SSL *clientssl = NULL, *serverssl = NULL;
9941     int testresult = 0;
9942     OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
9943     OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx;
9944     OSSL_PROVIDER *filterprov = NULL;
9945     int sig, hash, numshared, numshared_expected, hash_expected, sig_expected;
9946     const char *sigalg_name, *signame_expected;
9947 
9948     if (!TEST_ptr(tmpctx))
9949         goto end;
9950 
9951     if (idx != 0 && idx != 3) {
9952         if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter",
9953                                                  filter_provider_init)))
9954             goto end;
9955 
9956         filterprov = OSSL_PROVIDER_load(tmpctx, "filter");
9957         if (!TEST_ptr(filterprov))
9958             goto end;
9959 
9960         if (idx < 3) {
9961             /*
9962              * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered
9963              * or accepted for the peer that uses this libctx. Note that libssl
9964              * *requires* SHA2-256 to be available so we cannot disable that. We
9965              * also need SHA1 for our certificate.
9966              */
9967             if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST,
9968                                                       "SHA2-256:SHA1")))
9969                 goto end;
9970         } else {
9971             if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE,
9972                                                       "ECDSA"))
9973 # ifdef OPENSSL_NO_ECX
9974                     || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT, "EC"))
9975 # else
9976                     || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
9977                                                              "EC:X25519:X448"))
9978 # endif
9979                 )
9980                 goto end;
9981         }
9982 
9983         if (idx == 1 || idx == 4)
9984             clientctx = tmpctx;
9985         else
9986             serverctx = tmpctx;
9987     }
9988 
9989     cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method());
9990     sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method());
9991     if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
9992         goto end;
9993 
9994     /* Avoid MLKEM groups that depend on possibly filtered-out digests */
9995     if (!TEST_true(SSL_CTX_set1_groups_list(cctx,
9996                         "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072"))
9997         || !TEST_true(SSL_CTX_set1_groups_list(sctx,
9998                         "?X25519:?secp256r1:?ffdhe2048:?ffdhe3072")))
9999         goto end;
10000 
10001     if (idx != 5) {
10002         /* RSA first server key */
10003         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10004                                            TLS_client_method(),
10005                                            TLS1_VERSION,
10006                                            0,
10007                                            &sctx, &cctx, cert, privkey)))
10008             goto end;
10009     } else {
10010         /* ECDSA P-256 first server key */
10011         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10012                                            TLS_client_method(),
10013                                            TLS1_VERSION,
10014                                            0,
10015                                            &sctx, &cctx, cert2, privkey2)))
10016             goto end;
10017     }
10018 
10019     /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */
10020     if (idx < 4) {
10021         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
10022                                                "ECDHE-RSA-AES128-GCM-SHA256")))
10023             goto end;
10024     } else {
10025         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
10026                                                "ECDHE-ECDSA-AES128-GCM-SHA256")))
10027             goto end;
10028     }
10029 
10030     if (idx < 3) {
10031         if (!SSL_CTX_set1_sigalgs_list(cctx,
10032                                        "rsa_pss_rsae_sha384"
10033                                        ":rsa_pss_rsae_sha256")
10034                 || !SSL_CTX_set1_sigalgs_list(sctx,
10035                                               "rsa_pss_rsae_sha384"
10036                                               ":rsa_pss_rsae_sha256"))
10037             goto end;
10038     } else {
10039         if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")
10040                 || !SSL_CTX_set1_sigalgs_list(sctx,
10041                                               "rsa_pss_rsae_sha256:ECDSA+SHA256"))
10042             goto end;
10043     }
10044 
10045     /* ECDSA P-256 second server key, unless already first */
10046     if (idx != 5
10047         && (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2,
10048                                                       SSL_FILETYPE_PEM), 1)
10049             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
10050                                                         privkey2,
10051                                                         SSL_FILETYPE_PEM), 1)
10052             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)))
10053         goto end;
10054 
10055     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10056                                       NULL, NULL)))
10057         goto end;
10058 
10059     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10060         goto end;
10061 
10062     /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */
10063     numshared = SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash,
10064                                         NULL, NULL, NULL);
10065     numshared_expected = 1;
10066     hash_expected = NID_sha256;
10067     sig_expected = NID_rsassaPss;
10068     signame_expected = "rsa_pss_rsae_sha256";
10069     switch (idx) {
10070     case 0:
10071         hash_expected = NID_sha384;
10072         signame_expected = "rsa_pss_rsae_sha384";
10073         /* FALLTHROUGH */
10074     case 3:
10075         numshared_expected = 2;
10076         break;
10077     case 4:
10078     case 5:
10079         sig_expected = EVP_PKEY_EC;
10080         signame_expected = "ecdsa_secp256r1_sha256";
10081         break;
10082     }
10083     if (!TEST_int_eq(numshared, numshared_expected)
10084         || !TEST_int_eq(hash, hash_expected)
10085         || !TEST_int_eq(sig, sig_expected)
10086         || !TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name))
10087         || !TEST_ptr(sigalg_name)
10088         || !TEST_str_eq(sigalg_name, signame_expected))
10089         goto end;
10090 
10091     testresult = filter_provider_check_clean_finish();
10092 
10093  end:
10094     SSL_free(serverssl);
10095     SSL_free(clientssl);
10096     SSL_CTX_free(sctx);
10097     SSL_CTX_free(cctx);
10098     OSSL_PROVIDER_unload(filterprov);
10099     OSSL_LIB_CTX_free(tmpctx);
10100 
10101     return testresult;
10102 }
10103 #endif /*
10104         * !defined(OPENSSL_NO_EC) \
10105         * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
10106         */
10107 
10108 #ifndef OPENSSL_NO_TLS1_3
10109 /* This test can run in TLSv1.3 even if ec and dh are disabled */
test_pluggable_group(int idx)10110 static int test_pluggable_group(int idx)
10111 {
10112     SSL_CTX *cctx = NULL, *sctx = NULL;
10113     SSL *clientssl = NULL, *serverssl = NULL;
10114     int testresult = 0;
10115     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
10116     /* Check that we are not impacted by a provider without any groups */
10117     OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy");
10118     const char *group_name = idx == 0 ? "xorkemgroup" : "xorgroup";
10119 
10120     if (!TEST_ptr(tlsprov))
10121         goto end;
10122 
10123     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10124                                        TLS_client_method(),
10125                                        TLS1_3_VERSION,
10126                                        TLS1_3_VERSION,
10127                                        &sctx, &cctx, cert, privkey))
10128             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10129                                              NULL, NULL)))
10130         goto end;
10131 
10132     /* ensure GROUPLIST_INCREMENT (=40) logic triggers: */
10133     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"))
10134     /* removing a single algorithm from the list makes the test pass */
10135             || !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
10136         goto end;
10137 
10138     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10139         goto end;
10140 
10141     if (!TEST_str_eq(group_name,
10142                      SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
10143         goto end;
10144 
10145     if (!TEST_str_eq(group_name, SSL_get0_group_name(serverssl))
10146         || !TEST_str_eq(group_name, SSL_get0_group_name(clientssl)))
10147         goto end;
10148 
10149     testresult = 1;
10150 
10151  end:
10152     SSL_free(serverssl);
10153     SSL_free(clientssl);
10154     SSL_CTX_free(sctx);
10155     SSL_CTX_free(cctx);
10156     OSSL_PROVIDER_unload(tlsprov);
10157     OSSL_PROVIDER_unload(legacyprov);
10158 
10159     return testresult;
10160 }
10161 
10162 /*
10163  * This function triggers encode, decode and sign functions
10164  * of the artificial "xorhmacsig" algorithm implemented in tls-provider
10165  * creating private key and certificate files for use in TLS testing.
10166  */
create_cert_key(int idx,char * certfilename,char * privkeyfilename)10167 static int create_cert_key(int idx, char *certfilename, char *privkeyfilename)
10168 {
10169     EVP_PKEY_CTX *evpctx = EVP_PKEY_CTX_new_from_name(libctx,
10170                              (idx == 0) ? "xorhmacsig" : "xorhmacsha2sig", NULL);
10171     EVP_PKEY *pkey = NULL;
10172     X509 *x509 = X509_new();
10173     X509_NAME *name = NULL;
10174     BIO *keybio = NULL, *certbio = NULL;
10175     int ret = 1;
10176 
10177     if (!TEST_ptr(evpctx)
10178         || !TEST_int_gt(EVP_PKEY_keygen_init(evpctx), 0)
10179         || !TEST_true(EVP_PKEY_generate(evpctx, &pkey))
10180         || !TEST_ptr(pkey)
10181         || !TEST_ptr(x509)
10182         || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(x509), 1))
10183         || !TEST_true(X509_gmtime_adj(X509_getm_notBefore(x509), 0))
10184         || !TEST_true(X509_gmtime_adj(X509_getm_notAfter(x509), 31536000L))
10185         || !TEST_true(X509_set_pubkey(x509, pkey))
10186         || !TEST_ptr(name = X509_get_subject_name(x509))
10187         || !TEST_true(X509_NAME_add_entry_by_txt(name, "C",  MBSTRING_ASC,
10188                            (unsigned char *)"CH", -1, -1, 0))
10189         || !TEST_true(X509_NAME_add_entry_by_txt(name, "O",  MBSTRING_ASC,
10190                            (unsigned char *)"test.org", -1, -1, 0))
10191         || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
10192                            (unsigned char *)"localhost", -1, -1, 0))
10193         || !TEST_true(X509_set_issuer_name(x509, name))
10194         || !TEST_true(X509_sign(x509, pkey, EVP_sha1()))
10195         || !TEST_ptr(keybio = BIO_new_file(privkeyfilename, "wb"))
10196         || !TEST_true(PEM_write_bio_PrivateKey(keybio, pkey, NULL, NULL, 0, NULL, NULL))
10197         || !TEST_ptr(certbio = BIO_new_file(certfilename, "wb"))
10198         || !TEST_true(PEM_write_bio_X509(certbio, x509)))
10199         ret = 0;
10200 
10201     EVP_PKEY_free(pkey);
10202     X509_free(x509);
10203     EVP_PKEY_CTX_free(evpctx);
10204     BIO_free(keybio);
10205     BIO_free(certbio);
10206     return ret;
10207 }
10208 
10209 /*
10210  * Test that signature algorithms loaded via the provider interface can
10211  * correctly establish a TLS (1.3) connection.
10212  * Test 0: Signature algorithm with built-in hashing functionality: "xorhmacsig"
10213  * Test 1: Signature algorithm using external SHA2 hashing: "xorhmacsha2sig"
10214  * Test 2: Signature algorithm with built-in hashing configured via SSL_CONF_cmd
10215  * Test 3: Test 0 using RPK
10216  * Test 4: Test 1 using RPK
10217  * Test 5: Test 2 using RPK
10218  */
test_pluggable_signature(int idx)10219 static int test_pluggable_signature(int idx)
10220 {
10221     static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
10222     SSL_CTX *cctx = NULL, *sctx = NULL;
10223     SSL *clientssl = NULL, *serverssl = NULL;
10224     int testresult = 0;
10225     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
10226     OSSL_PROVIDER *defaultprov = OSSL_PROVIDER_load(libctx, "default");
10227     char *certfilename = "tls-prov-cert.pem";
10228     char *privkeyfilename = "tls-prov-key.pem";
10229     const char *sigalg_name = NULL, *expected_sigalg_name;
10230     int sigidx = idx % 3;
10231     int rpkidx = idx / 3;
10232     int do_conf_cmd = 0;
10233 
10234     if (sigidx == 2) {
10235         sigidx = 0;
10236         do_conf_cmd = 1;
10237     }
10238 
10239     /* See create_cert_key() above */
10240     expected_sigalg_name = (sigidx == 0) ? "xorhmacsig" : "xorhmacsha2sig";
10241 
10242     /* create key and certificate for the different algorithm types */
10243     if (!TEST_ptr(tlsprov)
10244         || !TEST_true(create_cert_key(sigidx, certfilename, privkeyfilename)))
10245         goto end;
10246 
10247     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10248                                        TLS_client_method(),
10249                                        TLS1_3_VERSION,
10250                                        TLS1_3_VERSION,
10251                                        &sctx, &cctx, NULL, NULL)))
10252         goto end;
10253 
10254     if (do_conf_cmd) {
10255         SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
10256 
10257         if (!TEST_ptr(confctx))
10258             goto end;
10259         SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
10260                                         | SSL_CONF_FLAG_SERVER
10261                                         | SSL_CONF_FLAG_CERTIFICATE
10262                                         | SSL_CONF_FLAG_REQUIRE_PRIVATE
10263                                         | SSL_CONF_FLAG_SHOW_ERRORS);
10264         SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
10265         if (!TEST_int_gt(SSL_CONF_cmd(confctx, "Certificate", certfilename), 0)
10266                 || !TEST_int_gt(SSL_CONF_cmd(confctx, "PrivateKey", privkeyfilename), 0)
10267                 || !TEST_true(SSL_CONF_CTX_finish(confctx))) {
10268             SSL_CONF_CTX_free(confctx);
10269             goto end;
10270         }
10271         SSL_CONF_CTX_free(confctx);
10272     } else {
10273         if (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, certfilename,
10274                                                       SSL_FILETYPE_PEM), 1)
10275                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
10276                                                             privkeyfilename,
10277                                                             SSL_FILETYPE_PEM), 1))
10278             goto end;
10279     }
10280     if (!TEST_int_eq(SSL_CTX_check_private_key(sctx), 1))
10281         goto end;
10282 
10283     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10284                                       NULL, NULL)))
10285         goto end;
10286 
10287     /* Enable RPK for server cert */
10288     if (rpkidx) {
10289         if (!TEST_true(SSL_set1_server_cert_type(serverssl, cert_type_rpk, sizeof(cert_type_rpk)))
10290                 || !TEST_true(SSL_set1_server_cert_type(clientssl, cert_type_rpk, sizeof(cert_type_rpk))))
10291             goto end;
10292     }
10293 
10294     /* This is necessary to pass minimal setup w/o other groups configured */
10295     if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup"))
10296             || !TEST_true(SSL_set1_groups_list(clientssl, "xorgroup")))
10297         goto end;
10298 
10299     /*
10300      * If this connection gets established, it must have been completed
10301      * via the tls-provider-implemented "hmacsig" algorithm, testing
10302      * both sign and verify functions during handshake.
10303      */
10304     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10305         goto end;
10306 
10307     /* If using RPK, make sure we got one */
10308     if (rpkidx && !TEST_long_eq(SSL_get_verify_result(clientssl), X509_V_ERR_RPK_UNTRUSTED))
10309         goto end;
10310 
10311     if (!TEST_true(SSL_get0_peer_signature_name(clientssl, &sigalg_name))
10312         || !TEST_str_eq(sigalg_name, expected_sigalg_name)
10313         || !TEST_ptr(sigalg_name))
10314         goto end;
10315 
10316     testresult = 1;
10317 
10318  end:
10319     SSL_free(serverssl);
10320     SSL_free(clientssl);
10321     SSL_CTX_free(sctx);
10322     SSL_CTX_free(cctx);
10323     OSSL_PROVIDER_unload(tlsprov);
10324     OSSL_PROVIDER_unload(defaultprov);
10325 
10326     return testresult;
10327 }
10328 #endif
10329 
10330 #ifndef OPENSSL_NO_TLS1_2
test_ssl_dup(void)10331 static int test_ssl_dup(void)
10332 {
10333     SSL_CTX *cctx = NULL, *sctx = NULL;
10334     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
10335     int testresult = 0;
10336     BIO *rbio = NULL, *wbio = NULL;
10337 
10338     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10339                                        TLS_client_method(),
10340                                        0,
10341                                        0,
10342                                        &sctx, &cctx, cert, privkey)))
10343         goto end;
10344 
10345     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10346                                              NULL, NULL)))
10347         goto end;
10348 
10349     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10350             || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
10351         goto end;
10352 
10353     client2ssl = SSL_dup(clientssl);
10354     rbio = SSL_get_rbio(clientssl);
10355     if (!TEST_ptr(rbio)
10356             || !TEST_true(BIO_up_ref(rbio)))
10357         goto end;
10358     SSL_set0_rbio(client2ssl, rbio);
10359     rbio = NULL;
10360 
10361     wbio = SSL_get_wbio(clientssl);
10362     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
10363         goto end;
10364     SSL_set0_wbio(client2ssl, wbio);
10365     rbio = NULL;
10366 
10367     if (!TEST_ptr(client2ssl)
10368                /* Handshake not started so pointers should be different */
10369             || !TEST_ptr_ne(clientssl, client2ssl))
10370         goto end;
10371 
10372     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
10373             || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
10374         goto end;
10375 
10376     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
10377         goto end;
10378 
10379     SSL_free(clientssl);
10380     clientssl = SSL_dup(client2ssl);
10381     if (!TEST_ptr(clientssl)
10382                /* Handshake has finished so pointers should be the same */
10383             || !TEST_ptr_eq(clientssl, client2ssl))
10384         goto end;
10385 
10386     testresult = 1;
10387 
10388  end:
10389     SSL_free(serverssl);
10390     SSL_free(clientssl);
10391     SSL_free(client2ssl);
10392     SSL_CTX_free(sctx);
10393     SSL_CTX_free(cctx);
10394 
10395     return testresult;
10396 }
10397 
secret_cb(SSL * s,void * secretin,int * secret_len,STACK_OF (SSL_CIPHER)* peer_ciphers,const SSL_CIPHER ** cipher,void * arg)10398 static int secret_cb(SSL *s, void *secretin, int *secret_len,
10399                      STACK_OF(SSL_CIPHER) *peer_ciphers,
10400                      const SSL_CIPHER **cipher, void *arg)
10401 {
10402     int i;
10403     unsigned char *secret = secretin;
10404 
10405     /* Just use a fixed master secret */
10406     for (i = 0; i < *secret_len; i++)
10407         secret[i] = 0xff;
10408 
10409     /* We don't set a preferred cipher */
10410 
10411     return 1;
10412 }
10413 
10414 /*
10415  * Test the session_secret_cb which is designed for use with EAP-FAST
10416  */
test_session_secret_cb(void)10417 static int test_session_secret_cb(void)
10418 {
10419     SSL_CTX *cctx = NULL, *sctx = NULL;
10420     SSL *clientssl = NULL, *serverssl = NULL;
10421     SSL_SESSION *secret_sess = NULL;
10422     int testresult = 0;
10423 
10424     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10425                                        TLS_client_method(),
10426                                        0,
10427                                        0,
10428                                        &sctx, &cctx, cert, privkey)))
10429         goto end;
10430 
10431     /* Create an initial connection and save the session */
10432     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10433                                       NULL, NULL)))
10434         goto end;
10435 
10436     /* session_secret_cb does not support TLSv1.3 */
10437     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10438             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION)))
10439         goto end;
10440 
10441     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10442         goto end;
10443 
10444     if (!TEST_ptr(secret_sess = SSL_get1_session(clientssl)))
10445         goto end;
10446 
10447     shutdown_ssl_connection(serverssl, clientssl);
10448     serverssl = clientssl = NULL;
10449 
10450     /* Resume the earlier session */
10451     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10452                                       NULL, NULL)))
10453         goto end;
10454 
10455     /*
10456      * No session ids for EAP-FAST - otherwise the state machine gets very
10457      * confused.
10458      */
10459     if (!TEST_true(SSL_SESSION_set1_id(secret_sess, NULL, 0)))
10460         goto end;
10461 
10462     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10463             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10464             || !TEST_true(SSL_set_session_secret_cb(serverssl, secret_cb,
10465                                                     NULL))
10466             || !TEST_true(SSL_set_session_secret_cb(clientssl, secret_cb,
10467                                                     NULL))
10468             || !TEST_true(SSL_set_session(clientssl, secret_sess)))
10469         goto end;
10470 
10471     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10472         goto end;
10473 
10474     testresult = 1;
10475 
10476  end:
10477     SSL_SESSION_free(secret_sess);
10478     SSL_free(serverssl);
10479     SSL_free(clientssl);
10480     SSL_CTX_free(sctx);
10481     SSL_CTX_free(cctx);
10482 
10483     return testresult;
10484 }
10485 
10486 # ifndef OPENSSL_NO_DH
10487 
10488 static EVP_PKEY *tmp_dh_params = NULL;
10489 
10490 /* Helper function for the test_set_tmp_dh() tests */
get_tmp_dh_params(void)10491 static EVP_PKEY *get_tmp_dh_params(void)
10492 {
10493     if (tmp_dh_params == NULL) {
10494         BIGNUM *p = NULL;
10495         OSSL_PARAM_BLD *tmpl = NULL;
10496         EVP_PKEY_CTX *pctx = NULL;
10497         OSSL_PARAM *params = NULL;
10498         EVP_PKEY *dhpkey = NULL;
10499 
10500         p = BN_get_rfc3526_prime_2048(NULL);
10501         if (!TEST_ptr(p))
10502             goto end;
10503 
10504         pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL);
10505         if (!TEST_ptr(pctx)
10506                 || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx), 1))
10507             goto end;
10508 
10509         tmpl = OSSL_PARAM_BLD_new();
10510         if (!TEST_ptr(tmpl)
10511                 || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl,
10512                                                         OSSL_PKEY_PARAM_FFC_P,
10513                                                         p))
10514                 || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl,
10515                                                         OSSL_PKEY_PARAM_FFC_G,
10516                                                         2)))
10517             goto end;
10518 
10519         params = OSSL_PARAM_BLD_to_param(tmpl);
10520         if (!TEST_ptr(params)
10521                 || !TEST_int_eq(EVP_PKEY_fromdata(pctx, &dhpkey,
10522                                                   EVP_PKEY_KEY_PARAMETERS,
10523                                                   params), 1))
10524             goto end;
10525 
10526         tmp_dh_params = dhpkey;
10527     end:
10528         BN_free(p);
10529         EVP_PKEY_CTX_free(pctx);
10530         OSSL_PARAM_BLD_free(tmpl);
10531         OSSL_PARAM_free(params);
10532     }
10533 
10534     if (tmp_dh_params != NULL && !EVP_PKEY_up_ref(tmp_dh_params))
10535         return NULL;
10536 
10537     return tmp_dh_params;
10538 }
10539 
10540 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10541 /* Callback used by test_set_tmp_dh() */
tmp_dh_callback(SSL * s,int is_export,int keylen)10542 static DH *tmp_dh_callback(SSL *s, int is_export, int keylen)
10543 {
10544     EVP_PKEY *dhpkey = get_tmp_dh_params();
10545     DH *ret = NULL;
10546 
10547     if (!TEST_ptr(dhpkey))
10548         return NULL;
10549 
10550     /*
10551      * libssl does not free the returned DH, so we free it now knowing that even
10552      * after we free dhpkey, there will still be a reference to the owning
10553      * EVP_PKEY in tmp_dh_params, and so the DH object will live for the length
10554      * of time we need it for.
10555      */
10556     ret = EVP_PKEY_get1_DH(dhpkey);
10557     DH_free(ret);
10558 
10559     EVP_PKEY_free(dhpkey);
10560 
10561     return ret;
10562 }
10563 #  endif
10564 
10565 /*
10566  * Test the various methods for setting temporary DH parameters
10567  *
10568  * Test  0: Default (no auto) setting
10569  * Test  1: Explicit SSL_CTX auto off
10570  * Test  2: Explicit SSL auto off
10571  * Test  3: Explicit SSL_CTX auto on
10572  * Test  4: Explicit SSL auto on
10573  * Test  5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY
10574  * Test  6: Explicit SSL auto off, custom DH params via EVP_PKEY
10575  *
10576  * The following are testing deprecated APIs, so we only run them if available
10577  * Test  7: Explicit SSL_CTX auto off, custom DH params via DH
10578  * Test  8: Explicit SSL auto off, custom DH params via DH
10579  * Test  9: Explicit SSL_CTX auto off, custom DH params via callback
10580  * Test 10: Explicit SSL auto off, custom DH params via callback
10581  */
test_set_tmp_dh(int idx)10582 static int test_set_tmp_dh(int idx)
10583 {
10584     SSL_CTX *cctx = NULL, *sctx = NULL;
10585     SSL *clientssl = NULL, *serverssl = NULL;
10586     int testresult = 0;
10587     int dhauto = (idx == 3 || idx == 4) ? 1 : 0;
10588     int expected = (idx <= 2) ? 0 : 1;
10589     EVP_PKEY *dhpkey = NULL;
10590 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10591     DH *dh = NULL;
10592 #  else
10593 
10594     if (idx >= 7)
10595         return 1;
10596 #  endif
10597 
10598     if (idx >= 5 && idx <= 8) {
10599         dhpkey = get_tmp_dh_params();
10600         if (!TEST_ptr(dhpkey))
10601             goto end;
10602     }
10603 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10604     if (idx == 7 || idx == 8) {
10605         dh = EVP_PKEY_get1_DH(dhpkey);
10606         if (!TEST_ptr(dh))
10607             goto end;
10608     }
10609 #  endif
10610 
10611     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10612                                        TLS_client_method(),
10613                                        0,
10614                                        0,
10615                                        &sctx, &cctx, cert, privkey)))
10616         goto end;
10617 
10618     if ((idx & 1) == 1) {
10619         if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto)))
10620             goto end;
10621     }
10622 
10623     if (idx == 5) {
10624         if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey)))
10625             goto end;
10626         dhpkey = NULL;
10627     }
10628 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10629     else if (idx == 7) {
10630         if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh)))
10631             goto end;
10632     } else if (idx == 9) {
10633         SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback);
10634     }
10635 #  endif
10636 
10637     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10638                                       NULL, NULL)))
10639         goto end;
10640 
10641     if ((idx & 1) == 0 && idx != 0) {
10642         if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto)))
10643             goto end;
10644     }
10645     if (idx == 6) {
10646         if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey)))
10647             goto end;
10648         dhpkey = NULL;
10649     }
10650 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10651     else if (idx == 8) {
10652         if (!TEST_true(SSL_set_tmp_dh(serverssl, dh)))
10653             goto end;
10654     } else if (idx == 10) {
10655         SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback);
10656     }
10657 #  endif
10658 
10659     if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10660             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10661             || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA")))
10662         goto end;
10663 
10664     /*
10665      * If autoon then we should succeed. Otherwise we expect failure because
10666      * there are no parameters
10667      */
10668     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
10669                                            SSL_ERROR_NONE), expected))
10670         goto end;
10671 
10672     testresult = 1;
10673 
10674  end:
10675 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10676     DH_free(dh);
10677 #  endif
10678     SSL_free(serverssl);
10679     SSL_free(clientssl);
10680     SSL_CTX_free(sctx);
10681     SSL_CTX_free(cctx);
10682     EVP_PKEY_free(dhpkey);
10683 
10684     return testresult;
10685 }
10686 
10687 /*
10688  * Test the auto DH keys are appropriately sized
10689  */
test_dh_auto(int idx)10690 static int test_dh_auto(int idx)
10691 {
10692     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method());
10693     SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10694     SSL *clientssl = NULL, *serverssl = NULL;
10695     int testresult = 0;
10696     EVP_PKEY *tmpkey = NULL;
10697     char *thiscert = NULL, *thiskey = NULL;
10698     size_t expdhsize = 0;
10699     const char *ciphersuite = "DHE-RSA-AES128-SHA";
10700 
10701     if (!TEST_ptr(sctx) || !TEST_ptr(cctx))
10702         goto end;
10703 
10704     switch (idx) {
10705     case 0:
10706         /* The FIPS provider doesn't support this DH size - so we ignore it */
10707         if (is_fips) {
10708             testresult = 1;
10709             goto end;
10710         }
10711         thiscert = cert1024;
10712         thiskey = privkey1024;
10713         expdhsize = 1024;
10714         SSL_CTX_set_security_level(sctx, 1);
10715         SSL_CTX_set_security_level(cctx, 1);
10716         break;
10717     case 1:
10718         /* 2048 bit prime */
10719         thiscert = cert;
10720         thiskey = privkey;
10721         expdhsize = 2048;
10722         break;
10723     case 2:
10724         thiscert = cert3072;
10725         thiskey = privkey3072;
10726         expdhsize = 3072;
10727         break;
10728     case 3:
10729         thiscert = cert4096;
10730         thiskey = privkey4096;
10731         expdhsize = 4096;
10732         break;
10733     case 4:
10734         thiscert = cert8192;
10735         thiskey = privkey8192;
10736         expdhsize = 8192;
10737         break;
10738     /* No certificate cases */
10739     case 5:
10740         /* The FIPS provider doesn't support this DH size - so we ignore it */
10741         if (is_fips) {
10742             testresult = 1;
10743             goto end;
10744         }
10745         ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0";
10746         expdhsize = 1024;
10747         break;
10748     case 6:
10749         ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0";
10750         expdhsize = 3072;
10751         break;
10752     default:
10753         TEST_error("Invalid text index");
10754         goto end;
10755     }
10756 
10757     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL,
10758                                        NULL,
10759                                        0,
10760                                        0,
10761                                        &sctx, &cctx, thiscert, thiskey)))
10762         goto end;
10763 
10764     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10765                                       NULL, NULL)))
10766         goto end;
10767 
10768     if (!TEST_true(SSL_set_dh_auto(serverssl, 1))
10769             || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10770             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10771             || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite))
10772             || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite)))
10773         goto end;
10774 
10775     /*
10776      * Send the server's first flight. At this point the server has created the
10777      * temporary DH key but hasn't finished using it yet. Once used it is
10778      * removed, so we cannot test it.
10779      */
10780     if (!TEST_int_le(SSL_connect(clientssl), 0)
10781             || !TEST_int_le(SSL_accept(serverssl), 0))
10782         goto end;
10783 
10784     if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0))
10785         goto end;
10786     if (!TEST_size_t_eq(EVP_PKEY_get_bits(tmpkey), expdhsize))
10787         goto end;
10788 
10789     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10790         goto end;
10791 
10792     testresult = 1;
10793 
10794  end:
10795     SSL_free(serverssl);
10796     SSL_free(clientssl);
10797     SSL_CTX_free(sctx);
10798     SSL_CTX_free(cctx);
10799     EVP_PKEY_free(tmpkey);
10800 
10801     return testresult;
10802 
10803 }
10804 # endif /* OPENSSL_NO_DH */
10805 #endif /* OPENSSL_NO_TLS1_2 */
10806 
10807 #ifndef OSSL_NO_USABLE_TLS1_3
10808 /*
10809  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
10810  * that it works even without a certificate configured for the original
10811  * SSL_CTX
10812  */
test_sni_tls13(void)10813 static int test_sni_tls13(void)
10814 {
10815     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
10816     SSL *clientssl = NULL, *serverssl = NULL;
10817     int testresult = 0;
10818 
10819     /* Reset callback counter */
10820     snicb = 0;
10821 
10822     /* Create an initial SSL_CTX with no certificate configured */
10823     sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10824     if (!TEST_ptr(sctx))
10825         goto end;
10826     /* Require TLSv1.3 as a minimum */
10827     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10828                                        TLS_client_method(), TLS1_3_VERSION, 0,
10829                                        &sctx2, &cctx, cert, privkey)))
10830         goto end;
10831 
10832     /* Set up SNI */
10833     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
10834             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
10835         goto end;
10836 
10837     /*
10838      * Connection should still succeed because the final SSL_CTX has the right
10839      * certificates configured.
10840      */
10841     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10842                                       &clientssl, NULL, NULL))
10843             || !TEST_true(create_ssl_connection(serverssl, clientssl,
10844                                                 SSL_ERROR_NONE)))
10845         goto end;
10846 
10847     /* We should have had the SNI callback called exactly once */
10848     if (!TEST_int_eq(snicb, 1))
10849         goto end;
10850 
10851     testresult = 1;
10852 
10853 end:
10854     SSL_free(serverssl);
10855     SSL_free(clientssl);
10856     SSL_CTX_free(sctx2);
10857     SSL_CTX_free(sctx);
10858     SSL_CTX_free(cctx);
10859     return testresult;
10860 }
10861 
10862 /*
10863  * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week
10864  * 0 = TLSv1.2
10865  * 1 = TLSv1.3
10866  */
test_ticket_lifetime(int idx)10867 static int test_ticket_lifetime(int idx)
10868 {
10869     SSL_CTX *cctx = NULL, *sctx = NULL;
10870     SSL *clientssl = NULL, *serverssl = NULL;
10871     int testresult = 0;
10872     int version = TLS1_3_VERSION;
10873 
10874 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
10875 #define TWO_WEEK_SEC (2 * ONE_WEEK_SEC)
10876 
10877     if (idx == 0) {
10878 #ifdef OPENSSL_NO_TLS1_2
10879         return TEST_skip("TLS 1.2 is disabled.");
10880 #else
10881         version = TLS1_2_VERSION;
10882 #endif
10883     }
10884 
10885     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10886                                        TLS_client_method(), version, version,
10887                                        &sctx, &cctx, cert, privkey)))
10888         goto end;
10889 
10890     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10891                                       &clientssl, NULL, NULL)))
10892         goto end;
10893 
10894     /*
10895      * Set the timeout to be more than 1 week
10896      * make sure the returned value is the default
10897      */
10898     if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC),
10899                       SSL_get_default_timeout(serverssl)))
10900         goto end;
10901 
10902     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10903         goto end;
10904 
10905     if (idx == 0) {
10906         /* TLSv1.2 uses the set value */
10907         if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC))
10908             goto end;
10909     } else {
10910         /* TLSv1.3 uses the limited value */
10911         if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC))
10912             goto end;
10913     }
10914     testresult = 1;
10915 
10916 end:
10917     SSL_free(serverssl);
10918     SSL_free(clientssl);
10919     SSL_CTX_free(sctx);
10920     SSL_CTX_free(cctx);
10921     return testresult;
10922 }
10923 #endif
10924 /*
10925  * Test that setting an ALPN does not violate RFC
10926  */
test_set_alpn(void)10927 static int test_set_alpn(void)
10928 {
10929     SSL_CTX *ctx = NULL;
10930     SSL *ssl = NULL;
10931     int testresult = 0;
10932 
10933     unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
10934     unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
10935     unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
10936     unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00};
10937     unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'};
10938     unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'};
10939 
10940     /* Create an initial SSL_CTX with no certificate configured */
10941     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10942     if (!TEST_ptr(ctx))
10943         goto end;
10944 
10945     /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
10946     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
10947         goto end;
10948     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
10949         goto end;
10950     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
10951         goto end;
10952     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
10953         goto end;
10954     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
10955         goto end;
10956     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
10957         goto end;
10958     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
10959         goto end;
10960     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
10961         goto end;
10962     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
10963         goto end;
10964 
10965     ssl = SSL_new(ctx);
10966     if (!TEST_ptr(ssl))
10967         goto end;
10968 
10969     if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
10970         goto end;
10971     if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
10972         goto end;
10973     if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
10974         goto end;
10975     if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
10976         goto end;
10977     if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
10978         goto end;
10979     if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
10980         goto end;
10981     if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
10982         goto end;
10983     if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
10984         goto end;
10985     if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
10986         goto end;
10987 
10988     testresult = 1;
10989 
10990 end:
10991     SSL_free(ssl);
10992     SSL_CTX_free(ctx);
10993     return testresult;
10994 }
10995 
10996 /*
10997  * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store.
10998  */
test_set_verify_cert_store_ssl_ctx(void)10999 static int test_set_verify_cert_store_ssl_ctx(void)
11000 {
11001    SSL_CTX *ctx = NULL;
11002    int testresult = 0;
11003    X509_STORE *store = NULL, *new_store = NULL,
11004               *cstore = NULL, *new_cstore = NULL;
11005 
11006    /* Create an initial SSL_CTX. */
11007    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11008    if (!TEST_ptr(ctx))
11009        goto end;
11010 
11011    /* Retrieve verify store pointer. */
11012    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11013        goto end;
11014 
11015    /* Retrieve chain store pointer. */
11016    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11017        goto end;
11018 
11019    /* We haven't set any yet, so this should be NULL. */
11020    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11021        goto end;
11022 
11023    /* Create stores. We use separate stores so pointers are different. */
11024    new_store = X509_STORE_new();
11025    if (!TEST_ptr(new_store))
11026        goto end;
11027 
11028    new_cstore = X509_STORE_new();
11029    if (!TEST_ptr(new_cstore))
11030        goto end;
11031 
11032    /* Set stores. */
11033    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store)))
11034        goto end;
11035 
11036    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore)))
11037        goto end;
11038 
11039    /* Should be able to retrieve the same pointer. */
11040    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11041        goto end;
11042 
11043    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11044        goto end;
11045 
11046    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
11047        goto end;
11048 
11049    /* Should be able to unset again. */
11050    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL)))
11051        goto end;
11052 
11053    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL)))
11054        goto end;
11055 
11056    /* Should now be NULL. */
11057    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
11058        goto end;
11059 
11060    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
11061        goto end;
11062 
11063    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11064        goto end;
11065 
11066    testresult = 1;
11067 
11068 end:
11069    X509_STORE_free(new_store);
11070    X509_STORE_free(new_cstore);
11071    SSL_CTX_free(ctx);
11072    return testresult;
11073 }
11074 
11075 /*
11076  * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store.
11077  */
test_set_verify_cert_store_ssl(void)11078 static int test_set_verify_cert_store_ssl(void)
11079 {
11080    SSL_CTX *ctx = NULL;
11081    SSL *ssl = NULL;
11082    int testresult = 0;
11083    X509_STORE *store = NULL, *new_store = NULL,
11084               *cstore = NULL, *new_cstore = NULL;
11085 
11086    /* Create an initial SSL_CTX. */
11087    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11088    if (!TEST_ptr(ctx))
11089        goto end;
11090 
11091    /* Create an SSL object. */
11092    ssl = SSL_new(ctx);
11093    if (!TEST_ptr(ssl))
11094        goto end;
11095 
11096    /* Retrieve verify store pointer. */
11097    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11098        goto end;
11099 
11100    /* Retrieve chain store pointer. */
11101    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11102        goto end;
11103 
11104    /* We haven't set any yet, so this should be NULL. */
11105    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11106        goto end;
11107 
11108    /* Create stores. We use separate stores so pointers are different. */
11109    new_store = X509_STORE_new();
11110    if (!TEST_ptr(new_store))
11111        goto end;
11112 
11113    new_cstore = X509_STORE_new();
11114    if (!TEST_ptr(new_cstore))
11115        goto end;
11116 
11117    /* Set stores. */
11118    if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store)))
11119        goto end;
11120 
11121    if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore)))
11122        goto end;
11123 
11124    /* Should be able to retrieve the same pointer. */
11125    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11126        goto end;
11127 
11128    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11129        goto end;
11130 
11131    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
11132        goto end;
11133 
11134    /* Should be able to unset again. */
11135    if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL)))
11136        goto end;
11137 
11138    if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL)))
11139        goto end;
11140 
11141    /* Should now be NULL. */
11142    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
11143        goto end;
11144 
11145    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
11146        goto end;
11147 
11148    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
11149        goto end;
11150 
11151    testresult = 1;
11152 
11153 end:
11154    X509_STORE_free(new_store);
11155    X509_STORE_free(new_cstore);
11156    SSL_free(ssl);
11157    SSL_CTX_free(ctx);
11158    return testresult;
11159 }
11160 
11161 
test_inherit_verify_param(void)11162 static int test_inherit_verify_param(void)
11163 {
11164     int testresult = 0;
11165 
11166     SSL_CTX *ctx = NULL;
11167     X509_VERIFY_PARAM *cp = NULL;
11168     SSL *ssl = NULL;
11169     X509_VERIFY_PARAM *sp = NULL;
11170     int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
11171 
11172     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
11173     if (!TEST_ptr(ctx))
11174         goto end;
11175 
11176     cp = SSL_CTX_get0_param(ctx);
11177     if (!TEST_ptr(cp))
11178         goto end;
11179     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
11180         goto end;
11181 
11182     X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
11183 
11184     ssl = SSL_new(ctx);
11185     if (!TEST_ptr(ssl))
11186         goto end;
11187 
11188     sp = SSL_get0_param(ssl);
11189     if (!TEST_ptr(sp))
11190         goto end;
11191     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
11192         goto end;
11193 
11194     testresult = 1;
11195 
11196  end:
11197     SSL_free(ssl);
11198     SSL_CTX_free(ctx);
11199 
11200     return testresult;
11201 }
11202 
test_load_dhfile(void)11203 static int test_load_dhfile(void)
11204 {
11205 #ifndef OPENSSL_NO_DH
11206     int testresult = 0;
11207 
11208     SSL_CTX *ctx = NULL;
11209     SSL_CONF_CTX *cctx = NULL;
11210 
11211     if (dhfile == NULL)
11212         return 1;
11213 
11214     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()))
11215         || !TEST_ptr(cctx = SSL_CONF_CTX_new()))
11216         goto end;
11217 
11218     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
11219     SSL_CONF_CTX_set_flags(cctx,
11220                            SSL_CONF_FLAG_CERTIFICATE
11221                            | SSL_CONF_FLAG_SERVER
11222                            | SSL_CONF_FLAG_FILE);
11223 
11224     if (!TEST_int_eq(SSL_CONF_cmd(cctx, "DHParameters", dhfile), 2))
11225         goto end;
11226 
11227     testresult = 1;
11228 end:
11229     SSL_CONF_CTX_free(cctx);
11230     SSL_CTX_free(ctx);
11231 
11232     return testresult;
11233 #else
11234     return TEST_skip("DH not supported by this build");
11235 #endif
11236 }
11237 
11238 #ifndef OSSL_NO_USABLE_TLS1_3
11239 /* Test that read_ahead works across a key change */
test_read_ahead_key_change(void)11240 static int test_read_ahead_key_change(void)
11241 {
11242     SSL_CTX *cctx = NULL, *sctx = NULL;
11243     SSL *clientssl = NULL, *serverssl = NULL;
11244     int testresult = 0;
11245     char *msg = "Hello World";
11246     size_t written, readbytes;
11247     char buf[80];
11248     int i;
11249 
11250     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11251                                        TLS_client_method(), TLS1_3_VERSION, 0,
11252                                        &sctx, &cctx, cert, privkey)))
11253         goto end;
11254 
11255     SSL_CTX_set_read_ahead(sctx, 1);
11256 
11257     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11258                                       &clientssl, NULL, NULL)))
11259         goto end;
11260 
11261     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11262         goto end;
11263 
11264     /* Write some data, send a key update, write more data */
11265     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11266         || !TEST_size_t_eq(written, strlen(msg)))
11267         goto end;
11268 
11269     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
11270         goto end;
11271 
11272     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11273         || !TEST_size_t_eq(written, strlen(msg)))
11274         goto end;
11275 
11276     /*
11277      * Since read_ahead is on the first read below should read the record with
11278      * the first app data, the second record with the key update message, and
11279      * the third record with the app data all in one go. We should be able to
11280      * still process the read_ahead data correctly even though it crosses
11281      * epochs
11282      */
11283     for (i = 0; i < 2; i++) {
11284         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11285                                     &readbytes)))
11286             goto end;
11287 
11288         buf[readbytes] = '\0';
11289         if (!TEST_str_eq(buf, msg))
11290             goto end;
11291     }
11292 
11293     testresult = 1;
11294 
11295 end:
11296     SSL_free(serverssl);
11297     SSL_free(clientssl);
11298     SSL_CTX_free(sctx);
11299     SSL_CTX_free(cctx);
11300     return testresult;
11301 }
11302 
record_pad_cb(SSL * s,int type,size_t len,void * arg)11303 static size_t record_pad_cb(SSL *s, int type, size_t len, void *arg)
11304 {
11305     int *called = arg;
11306 
11307     switch ((*called)++) {
11308     case 0:
11309         /* Add some padding to first record */
11310         return 512;
11311     case 1:
11312         /* Maximally pad the second record */
11313         return SSL3_RT_MAX_PLAIN_LENGTH - len;
11314     case 2:
11315         /*
11316          * Exceeding the maximum padding should be fine. It should just pad to
11317          * the maximum anyway
11318          */
11319         return SSL3_RT_MAX_PLAIN_LENGTH + 1 - len;
11320     case 3:
11321         /*
11322          * Very large padding should also be ok. Should just pad to the maximum
11323          * allowed
11324          */
11325         return SIZE_MAX;
11326     default:
11327         return 0;
11328     }
11329 }
11330 
11331 /*
11332  * Test that setting record padding in TLSv1.3 works as expected
11333  * Test 0: Record padding callback on the SSL_CTX
11334  * Test 1: Record padding callback on the SSL
11335  * Test 2: Record block padding on the SSL_CTX
11336  * Test 3: Record block padding on the SSL
11337  * Test 4: Extended record block padding on the SSL_CTX
11338  * Test 5: Extended record block padding on the SSL
11339  */
test_tls13_record_padding(int idx)11340 static int test_tls13_record_padding(int idx)
11341 {
11342     SSL_CTX *cctx = NULL, *sctx = NULL;
11343     SSL *clientssl = NULL, *serverssl = NULL;
11344     int testresult = 0;
11345     char *msg = "Hello World";
11346     size_t written, readbytes;
11347     char buf[80];
11348     int i;
11349     int called = 0;
11350 
11351     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11352                                        TLS_client_method(), TLS1_3_VERSION, 0,
11353                                        &sctx, &cctx, cert, privkey)))
11354         goto end;
11355 
11356     if (idx == 0) {
11357         SSL_CTX_set_record_padding_callback(cctx, record_pad_cb);
11358         SSL_CTX_set_record_padding_callback_arg(cctx, &called);
11359         if (!TEST_ptr_eq(SSL_CTX_get_record_padding_callback_arg(cctx), &called))
11360             goto end;
11361     } else if (idx == 2) {
11362         /* Exceeding the max plain length should fail */
11363         if (!TEST_false(SSL_CTX_set_block_padding(cctx,
11364                                                   SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11365             goto end;
11366         if (!TEST_true(SSL_CTX_set_block_padding(cctx, 512)))
11367             goto end;
11368     } else if (idx == 4) {
11369         /* pad only handshake/alert messages */
11370         if (!TEST_true(SSL_CTX_set_block_padding_ex(cctx, 0, 512)))
11371             goto end;
11372     }
11373 
11374     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11375                                       &clientssl, NULL, NULL)))
11376         goto end;
11377 
11378     if (idx == 1) {
11379         SSL_set_record_padding_callback(clientssl, record_pad_cb);
11380         SSL_set_record_padding_callback_arg(clientssl, &called);
11381         if (!TEST_ptr_eq(SSL_get_record_padding_callback_arg(clientssl), &called))
11382             goto end;
11383     } else if (idx == 3) {
11384         /* Exceeding the max plain length should fail */
11385         if (!TEST_false(SSL_set_block_padding(clientssl,
11386                                               SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11387             goto end;
11388         if (!TEST_true(SSL_set_block_padding(clientssl, 512)))
11389             goto end;
11390     } else if (idx == 5) {
11391         /* Exceeding the max plain length should fail */
11392         if (!TEST_false(SSL_set_block_padding_ex(clientssl, 0,
11393                                                  SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11394             goto end;
11395         /* pad server and client handshake only */
11396         if (!TEST_true(SSL_set_block_padding_ex(clientssl, 0, 512)))
11397             goto end;
11398         if (!TEST_true(SSL_set_block_padding_ex(serverssl, 0, 512)))
11399             goto end;
11400     }
11401 
11402     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11403         goto end;
11404 
11405     called = 0;
11406     /*
11407      * Write some data, then check we can read it. Do this four times to check
11408      * we can continue to write and read padded data after the initial record
11409      * padding has been added. We don't actually check that the padding has
11410      * been applied to the record - just that we can continue to communicate
11411      * normally and that the callback has been called (if appropriate).
11412      */
11413     for (i = 0; i < 4; i++) {
11414         if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11415             || !TEST_size_t_eq(written, strlen(msg)))
11416             goto end;
11417 
11418         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11419                                     &readbytes))
11420                 || !TEST_size_t_eq(written, readbytes))
11421             goto end;
11422 
11423         buf[readbytes] = '\0';
11424         if (!TEST_str_eq(buf, msg))
11425             goto end;
11426     }
11427 
11428     if ((idx == 0 || idx == 1) && !TEST_int_eq(called, 4))
11429         goto end;
11430 
11431     testresult = 1;
11432 end:
11433     SSL_free(serverssl);
11434     SSL_free(clientssl);
11435     SSL_CTX_free(sctx);
11436     SSL_CTX_free(cctx);
11437     return testresult;
11438 }
11439 #endif /* OSSL_NO_USABLE_TLS1_3 */
11440 
11441 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
11442 /*
11443  * Test TLSv1.2 with a pipeline capable cipher. TLSv1.3 and DTLS do not
11444  * support this yet. The only pipeline capable cipher that we have is in the
11445  * dasync engine (providers don't support this yet), so we have to use
11446  * deprecated APIs for this test.
11447  *
11448  * Test 0: Client has pipelining enabled, server does not
11449  * Test 1: Server has pipelining enabled, client does not
11450  * Test 2: Client has pipelining enabled, server does not: not enough data to
11451  *         fill all the pipelines
11452  * Test 3: Client has pipelining enabled, server does not: not enough data to
11453  *         fill all the pipelines by more than a full pipeline's worth
11454  * Test 4: Client has pipelining enabled, server does not: more data than all
11455  *         the available pipelines can take
11456  * Test 5: Client has pipelining enabled, server does not: Maximum size pipeline
11457  * Test 6: Repeat of test 0, but the engine is loaded late (after the SSL_CTX
11458  *         is created)
11459  */
test_pipelining(int idx)11460 static int test_pipelining(int idx)
11461 {
11462     SSL_CTX *cctx = NULL, *sctx = NULL;
11463     SSL *clientssl = NULL, *serverssl = NULL, *peera, *peerb;
11464     int testresult = 0, numreads;
11465     /* A 55 byte message */
11466     unsigned char *msg = (unsigned char *)
11467         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123";
11468     size_t written, readbytes, offset, msglen, fragsize = 10, numpipes = 5;
11469     size_t expectedreads;
11470     unsigned char *buf = NULL;
11471     ENGINE *e = NULL;
11472 
11473     if (idx != 6) {
11474         e = load_dasync();
11475         if (e == NULL)
11476             return 0;
11477     }
11478 
11479     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11480                                        TLS_client_method(), 0,
11481                                        TLS1_2_VERSION, &sctx, &cctx, cert,
11482                                        privkey)))
11483         goto end;
11484 
11485     if (idx == 6) {
11486         e = load_dasync();
11487         if (e == NULL)
11488             goto end;
11489         /* Now act like test 0 */
11490         idx = 0;
11491     }
11492 
11493     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11494                                       &clientssl, NULL, NULL)))
11495         goto end;
11496 
11497     if (!TEST_true(SSL_set_cipher_list(clientssl, "AES128-SHA")))
11498         goto end;
11499 
11500     /* peera is always configured for pipelining, while peerb is not. */
11501     if (idx == 1) {
11502         peera = serverssl;
11503         peerb = clientssl;
11504 
11505     } else {
11506         peera = clientssl;
11507         peerb = serverssl;
11508     }
11509 
11510     if (idx == 5) {
11511         numpipes = 2;
11512         /* Maximum allowed fragment size */
11513         fragsize = SSL3_RT_MAX_PLAIN_LENGTH;
11514         msglen = fragsize * numpipes;
11515         msg = OPENSSL_malloc(msglen);
11516         if (!TEST_ptr(msg))
11517             goto end;
11518         if (!TEST_int_gt(RAND_bytes_ex(libctx, msg, msglen, 0), 0))
11519             goto end;
11520     } else if (idx == 4) {
11521         msglen = 55;
11522     } else {
11523         msglen = 50;
11524     }
11525     if (idx == 2)
11526         msglen -= 2; /* Send 2 less bytes */
11527     else if (idx == 3)
11528         msglen -= 12; /* Send 12 less bytes */
11529 
11530     buf = OPENSSL_malloc(msglen);
11531     if (!TEST_ptr(buf))
11532         goto end;
11533 
11534     if (idx == 5) {
11535         /*
11536          * Test that setting a split send fragment longer than the maximum
11537          * allowed fails
11538          */
11539         if (!TEST_false(SSL_set_split_send_fragment(peera, fragsize + 1)))
11540             goto end;
11541     }
11542 
11543     /*
11544      * In the normal case. We have 5 pipelines with 10 bytes per pipeline
11545      * (50 bytes in total). This is a ridiculously small number of bytes -
11546      * but sufficient for our purposes
11547      */
11548     if (!TEST_true(SSL_set_max_pipelines(peera, numpipes))
11549             || !TEST_true(SSL_set_split_send_fragment(peera, fragsize)))
11550         goto end;
11551 
11552     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11553         goto end;
11554 
11555     /* Write some data from peera to peerb */
11556     if (!TEST_true(SSL_write_ex(peera, msg, msglen, &written))
11557         || !TEST_size_t_eq(written, msglen))
11558         goto end;
11559 
11560     /*
11561      * If the pipelining code worked, then we expect all |numpipes| pipelines to
11562      * have been used - except in test 3 where only |numpipes - 1| pipelines
11563      * will be used. This will result in |numpipes| records (|numpipes - 1| for
11564      * test 3) having been sent to peerb. Since peerb is not using read_ahead we
11565      * expect this to be read in |numpipes| or |numpipes - 1| separate
11566      * SSL_read_ex calls. In the case of test 4, there is then one additional
11567      * read for left over data that couldn't fit in the previous pipelines
11568      */
11569     for (offset = 0, numreads = 0;
11570          offset < msglen;
11571          offset += readbytes, numreads++) {
11572         if (!TEST_true(SSL_read_ex(peerb, buf + offset,
11573                                    msglen - offset, &readbytes)))
11574             goto end;
11575     }
11576 
11577     expectedreads = idx == 4 ? numpipes + 1
11578                              : (idx == 3 ? numpipes - 1 : numpipes);
11579     if (!TEST_mem_eq(msg, msglen, buf, offset)
11580             || !TEST_int_eq(numreads, expectedreads))
11581         goto end;
11582 
11583     /*
11584      * Write some data from peerb to peera. We do this in up to |numpipes + 1|
11585      * chunks to exercise the read pipelining code on peera.
11586      */
11587     for (offset = 0; offset < msglen; offset += fragsize) {
11588         size_t sendlen = msglen - offset;
11589 
11590         if (sendlen > fragsize)
11591             sendlen = fragsize;
11592         if (!TEST_true(SSL_write_ex(peerb, msg + offset, sendlen, &written))
11593                 || !TEST_size_t_eq(written, sendlen))
11594             goto end;
11595     }
11596 
11597     /*
11598      * The data was written in |numpipes|, |numpipes - 1| or |numpipes + 1|
11599      * separate chunks (depending on which test we are running). If the
11600      * pipelining is working then we expect peera to read up to numpipes chunks
11601      * and process them in parallel, giving back the complete result in a single
11602      * call to SSL_read_ex
11603      */
11604     if (!TEST_true(SSL_read_ex(peera, buf, msglen, &readbytes))
11605             || !TEST_size_t_le(readbytes, msglen))
11606         goto end;
11607 
11608     if (idx == 4) {
11609         size_t readbytes2;
11610 
11611         if (!TEST_true(SSL_read_ex(peera, buf + readbytes,
11612                                    msglen - readbytes, &readbytes2)))
11613             goto end;
11614         readbytes += readbytes2;
11615         if (!TEST_size_t_le(readbytes, msglen))
11616             goto end;
11617     }
11618 
11619     if (!TEST_mem_eq(msg, msglen, buf, readbytes))
11620         goto end;
11621 
11622     testresult = 1;
11623 end:
11624     SSL_free(serverssl);
11625     SSL_free(clientssl);
11626     SSL_CTX_free(sctx);
11627     SSL_CTX_free(cctx);
11628     if (e != NULL) {
11629         ENGINE_unregister_ciphers(e);
11630         ENGINE_finish(e);
11631         ENGINE_free(e);
11632     }
11633     OPENSSL_free(buf);
11634     if (fragsize == SSL3_RT_MAX_PLAIN_LENGTH)
11635         OPENSSL_free(msg);
11636     return testresult;
11637 }
11638 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */
11639 
check_version_string(SSL * s,int version)11640 static int check_version_string(SSL *s, int version)
11641 {
11642     const char *verstr = NULL;
11643 
11644     switch (version) {
11645     case SSL3_VERSION:
11646         verstr = "SSLv3";
11647         break;
11648     case TLS1_VERSION:
11649         verstr = "TLSv1";
11650         break;
11651     case TLS1_1_VERSION:
11652         verstr = "TLSv1.1";
11653         break;
11654     case TLS1_2_VERSION:
11655         verstr = "TLSv1.2";
11656         break;
11657     case TLS1_3_VERSION:
11658         verstr = "TLSv1.3";
11659         break;
11660     case DTLS1_VERSION:
11661         verstr = "DTLSv1";
11662         break;
11663     case DTLS1_2_VERSION:
11664         verstr = "DTLSv1.2";
11665     }
11666 
11667     return TEST_str_eq(verstr, SSL_get_version(s));
11668 }
11669 
11670 /*
11671  * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and
11672  * SSL_is_dtls return the expected results for a (D)TLS connection. Compare with
11673  * test_version() in quicapitest.c which does the same thing for QUIC
11674  * connections.
11675  */
test_version(int idx)11676 static int test_version(int idx)
11677 {
11678     SSL_CTX *cctx = NULL, *sctx = NULL;
11679     SSL *clientssl = NULL, *serverssl = NULL;
11680     int testresult = 0, version;
11681     const SSL_METHOD *servmeth = TLS_server_method();
11682     const SSL_METHOD *clientmeth = TLS_client_method();
11683 
11684     switch (idx) {
11685 #if !defined(OPENSSL_NO_SSL3)
11686     case 0:
11687         version = SSL3_VERSION;
11688         break;
11689 #endif
11690 #if !defined(OPENSSL_NO_TLS1)
11691     case 1:
11692         version = TLS1_VERSION;
11693         break;
11694 #endif
11695 #if !defined(OPENSSL_NO_TLS1_2)
11696     case 2:
11697         version = TLS1_2_VERSION;
11698         break;
11699 #endif
11700 #if !defined(OSSL_NO_USABLE_TLS1_3)
11701     case 3:
11702         version = TLS1_3_VERSION;
11703         break;
11704 #endif
11705 #if !defined(OPENSSL_NO_DTLS1)
11706     case 4:
11707         version = DTLS1_VERSION;
11708         break;
11709 #endif
11710 #if !defined(OPENSSL_NO_DTLS1_2)
11711     case 5:
11712         version = DTLS1_2_VERSION;
11713         break;
11714 #endif
11715     /*
11716      * NB we do not support QUIC in this test. That is covered by quicapitest.c
11717      * We also don't support DTLS1_BAD_VER since we have no server support for
11718      * that.
11719      */
11720     default:
11721         TEST_skip("Unsupported protocol version");
11722         return 1;
11723     }
11724 
11725     if (is_fips
11726             && (version == SSL3_VERSION
11727                 || version == TLS1_VERSION
11728                 || version == DTLS1_VERSION)) {
11729         TEST_skip("Protocol version not supported with FIPS");
11730         return 1;
11731     }
11732 
11733 #if !defined(OPENSSL_NO_DTLS)
11734     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11735         servmeth = DTLS_server_method();
11736         clientmeth = DTLS_client_method();
11737     }
11738 #endif
11739 
11740     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, version,
11741                                        version, &sctx, &cctx, cert, privkey)))
11742         goto end;
11743 
11744     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
11745             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
11746                                                 "DEFAULT:@SECLEVEL=0")))
11747         goto end;
11748 
11749     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11750                                       &clientssl, NULL, NULL)))
11751         goto end;
11752 
11753     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11754         goto end;
11755 
11756     if (!TEST_int_eq(SSL_version(serverssl), version)
11757             || !TEST_int_eq(SSL_version(clientssl), version)
11758             || !TEST_true(check_version_string(serverssl, version))
11759             || !TEST_true(check_version_string(clientssl, version)))
11760         goto end;
11761 
11762     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11763         if (!TEST_true(SSL_is_dtls(serverssl))
11764                 || !TEST_true(SSL_is_dtls(clientssl))
11765                 || !TEST_false(SSL_is_tls(serverssl))
11766                 || !TEST_false(SSL_is_tls(clientssl))
11767                 || !TEST_false(SSL_is_quic(serverssl))
11768                 || !TEST_false(SSL_is_quic(clientssl)))
11769         goto end;
11770     } else {
11771         if (!TEST_true(SSL_is_tls(serverssl))
11772                 || !TEST_true(SSL_is_tls(clientssl))
11773                 || !TEST_false(SSL_is_dtls(serverssl))
11774                 || !TEST_false(SSL_is_dtls(clientssl))
11775                 || !TEST_false(SSL_is_quic(serverssl))
11776                 || !TEST_false(SSL_is_quic(clientssl)))
11777         goto end;
11778     }
11779 
11780     testresult = 1;
11781 end:
11782     SSL_free(serverssl);
11783     SSL_free(clientssl);
11784     SSL_CTX_free(sctx);
11785     SSL_CTX_free(cctx);
11786     return testresult;
11787 }
11788 
11789 /*
11790  * Test that the SSL_rstate_string*() APIs return sane results
11791  */
test_rstate_string(void)11792 static int test_rstate_string(void)
11793 {
11794     SSL_CTX *cctx = NULL, *sctx = NULL;
11795     SSL *clientssl = NULL, *serverssl = NULL;
11796     int testresult = 0, version;
11797     const SSL_METHOD *servmeth = TLS_server_method();
11798     const SSL_METHOD *clientmeth = TLS_client_method();
11799     size_t written, readbytes;
11800     unsigned char buf[2];
11801     unsigned char dummyheader[SSL3_RT_HEADER_LENGTH] = {
11802         SSL3_RT_APPLICATION_DATA,
11803         TLS1_2_VERSION_MAJOR,
11804         0, /* To be filled in later */
11805         0,
11806         1
11807     };
11808 
11809     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, 0,
11810                                        0, &sctx, &cctx, cert, privkey)))
11811         goto end;
11812 
11813     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11814                                       &clientssl, NULL, NULL)))
11815         goto end;
11816 
11817     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11818             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11819         goto end;
11820 
11821     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11822         goto end;
11823 
11824     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11825             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11826         goto end;
11827 
11828     /* Fill in the correct version for the record header */
11829     version = SSL_version(serverssl);
11830     if (version == TLS1_3_VERSION)
11831         version = TLS1_2_VERSION;
11832     dummyheader[2] = version & 0xff;
11833 
11834     /*
11835      * Send a dummy header. If we continued to read the body as well this
11836      * would fail with a bad record mac, but we're not going to go that far.
11837      */
11838     if (!TEST_true(BIO_write_ex(SSL_get_rbio(serverssl), dummyheader,
11839                                 sizeof(dummyheader), &written))
11840             || !TEST_size_t_eq(written, SSL3_RT_HEADER_LENGTH))
11841         goto end;
11842 
11843     if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)))
11844         goto end;
11845 
11846     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RB")
11847             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read body"))
11848         goto end;
11849 
11850     testresult = 1;
11851 end:
11852     SSL_free(serverssl);
11853     SSL_free(clientssl);
11854     SSL_CTX_free(sctx);
11855     SSL_CTX_free(cctx);
11856     return testresult;
11857 }
11858 
11859 /*
11860  * Force a write retry during handshaking. We test various combinations of
11861  * scenarios. We test a large certificate message which will fill the buffering
11862  * BIO used in the handshake. We try with client auth on and off. Finally we
11863  * also try a BIO that indicates retry via a 0 return. BIO_write() is documented
11864  * to indicate retry via -1 - but sometimes BIOs don't do that.
11865  *
11866  * Test 0: Standard certificate message
11867  * Test 1: Large certificate message
11868  * Test 2: Standard cert, verify peer
11869  * Test 3: Large cert, verify peer
11870  * Test 4: Standard cert, BIO returns 0 on retry
11871  * Test 5: Large cert, BIO returns 0 on retry
11872  * Test 6: Standard cert, verify peer, BIO returns 0 on retry
11873  * Test 7: Large cert, verify peer, BIO returns 0 on retry
11874  * Test 8-15: Repeat of above with TLSv1.2
11875  */
test_handshake_retry(int idx)11876 static int test_handshake_retry(int idx)
11877 {
11878     SSL_CTX *cctx = NULL, *sctx = NULL;
11879     SSL *clientssl = NULL, *serverssl = NULL;
11880     int testresult = 0;
11881     BIO *tmp = NULL, *bretry = BIO_new(bio_s_always_retry());
11882     int maxversion = 0;
11883 
11884     if (!TEST_ptr(bretry))
11885         goto end;
11886 
11887 #ifndef OPENSSL_NO_TLS1_2
11888     if ((idx & 8) == 8)
11889         maxversion = TLS1_2_VERSION;
11890 #else
11891     if ((idx & 8) == 8)
11892         return TEST_skip("No TLSv1.2");
11893 #endif
11894 
11895     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11896                                        TLS_client_method(), 0, maxversion,
11897                                        &sctx, &cctx, cert, privkey)))
11898         goto end;
11899 
11900     /*
11901      * Add a large amount of data to fill the buffering BIO used by the SSL
11902      * object
11903      */
11904     if ((idx & 1) == 1 && !ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
11905         goto end;
11906 
11907     /*
11908      * We don't actually configure a client cert, but neither do we fail if one
11909      * isn't present.
11910      */
11911     if ((idx & 2) == 2)
11912         SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
11913 
11914     if ((idx & 4) == 4)
11915         set_always_retry_err_val(0);
11916 
11917     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11918                                       &clientssl, NULL, NULL)))
11919         goto end;
11920 
11921     tmp = SSL_get_wbio(serverssl);
11922     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
11923         tmp = NULL;
11924         goto end;
11925     }
11926     SSL_set0_wbio(serverssl, bretry);
11927     bretry = NULL;
11928 
11929     if (!TEST_int_eq(SSL_connect(clientssl), -1))
11930         goto end;
11931 
11932     if (!TEST_int_eq(SSL_accept(serverssl), -1)
11933             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
11934         goto end;
11935 
11936     /* Restore a BIO that will let the write succeed */
11937     SSL_set0_wbio(serverssl, tmp);
11938     tmp = NULL;
11939 
11940     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11941         goto end;
11942 
11943     testresult = 1;
11944 end:
11945     SSL_free(serverssl);
11946     SSL_free(clientssl);
11947     SSL_CTX_free(sctx);
11948     SSL_CTX_free(cctx);
11949     BIO_free(bretry);
11950     BIO_free(tmp);
11951     set_always_retry_err_val(-1);
11952     return testresult;
11953 }
11954 
11955 /*
11956  * Test that receiving retries when writing application data works as expected
11957  */
test_data_retry(void)11958 static int test_data_retry(void)
11959 {
11960     SSL_CTX *cctx = NULL, *sctx = NULL;
11961     SSL *clientssl = NULL, *serverssl = NULL;
11962     int testresult = 0;
11963     unsigned char inbuf[1200], outbuf[1200];
11964     size_t i;
11965     BIO *tmp = NULL;
11966     BIO *bretry = BIO_new(bio_s_maybe_retry());
11967     size_t written, readbytes, totread = 0;
11968 
11969     if (!TEST_ptr(bretry))
11970         goto end;
11971 
11972     for (i = 0; i < sizeof(inbuf); i++)
11973         inbuf[i] = (unsigned char)(0xff & i);
11974     memset(outbuf, 0, sizeof(outbuf));
11975 
11976     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11977                                        TLS_client_method(), 0, 0, &sctx, &cctx,
11978                                        cert, privkey)))
11979         goto end;
11980 
11981     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
11982                                       NULL)))
11983         goto end;
11984 
11985     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11986         goto end;
11987 
11988     /* Smallest possible max send fragment is 512 */
11989     if (!TEST_true(SSL_set_max_send_fragment(clientssl, 512)))
11990         goto end;
11991 
11992     tmp = SSL_get_wbio(clientssl);
11993     if (!TEST_ptr(tmp))
11994         goto end;
11995     if (!TEST_true(BIO_up_ref(tmp)))
11996         goto end;
11997     BIO_push(bretry, tmp);
11998     tmp = NULL;
11999     SSL_set0_wbio(clientssl, bretry);
12000     if (!BIO_up_ref(bretry)) {
12001         bretry = NULL;
12002         goto end;
12003     }
12004 
12005     for (i = 0; i < 3; i++) {
12006         /* We expect this call to make no progress and indicate retry */
12007         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12008             goto end;
12009         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
12010             goto end;
12011 
12012         /* Allow one write to progress, but the next one to signal retry */
12013         if (!TEST_true(BIO_ctrl(bretry, MAYBE_RETRY_CTRL_SET_RETRY_AFTER_CNT, 1,
12014                                 NULL)))
12015             goto end;
12016 
12017         if (i == 2)
12018             break;
12019 
12020         /*
12021          * This call will hopefully make progress but will still indicate retry
12022          * because there is more data than will fit into a single record.
12023          */
12024         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12025             goto end;
12026         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
12027             goto end;
12028     }
12029 
12030     /* The final call should write the last chunk of data and succeed */
12031     if (!TEST_true(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
12032         goto end;
12033     /* Read all the data available */
12034     while (SSL_read_ex(serverssl, outbuf + totread, sizeof(outbuf) - totread,
12035                        &readbytes))
12036         totread += readbytes;
12037     if (!TEST_mem_eq(inbuf, sizeof(inbuf), outbuf, totread))
12038         goto end;
12039 
12040     testresult = 1;
12041 end:
12042     SSL_free(serverssl);
12043     SSL_free(clientssl);
12044     SSL_CTX_free(sctx);
12045     SSL_CTX_free(cctx);
12046     BIO_free_all(bretry);
12047     BIO_free(tmp);
12048     return testresult;
12049 }
12050 
12051 struct resume_servername_cb_data {
12052     int i;
12053     SSL_CTX *cctx;
12054     SSL_CTX *sctx;
12055     SSL_SESSION *sess;
12056     int recurse;
12057 };
12058 
12059 /*
12060  * Servername callback. We use it here to run another complete handshake using
12061  * the same session - and mark the session as not_resuamble at the end
12062  */
resume_servername_cb(SSL * s,int * ad,void * arg)12063 static int resume_servername_cb(SSL *s, int *ad, void *arg)
12064 {
12065     struct resume_servername_cb_data *cbdata = arg;
12066     SSL *serverssl = NULL, *clientssl = NULL;
12067     int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
12068 
12069     if (cbdata->recurse)
12070         return SSL_TLSEXT_ERR_ALERT_FATAL;
12071 
12072     if ((cbdata->i % 3) != 1)
12073         return SSL_TLSEXT_ERR_OK;
12074 
12075     cbdata->recurse = 1;
12076 
12077     if (!TEST_true(create_ssl_objects(cbdata->sctx, cbdata->cctx, &serverssl,
12078                                       &clientssl, NULL, NULL))
12079             || !TEST_true(SSL_set_session(clientssl, cbdata->sess)))
12080         goto end;
12081 
12082     ERR_set_mark();
12083     /*
12084      * We expect this to fail - because the servername cb will fail. This will
12085      * mark the session as not_resumable.
12086      */
12087     if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) {
12088         ERR_clear_last_mark();
12089         goto end;
12090     }
12091     ERR_pop_to_mark();
12092 
12093     ret = SSL_TLSEXT_ERR_OK;
12094  end:
12095     SSL_free(serverssl);
12096     SSL_free(clientssl);
12097     cbdata->recurse = 0;
12098     return ret;
12099 }
12100 /*
12101  * Test multiple resumptions and cache size handling
12102  * Test 0: TLSv1.3 (max_early_data set)
12103  * Test 1: TLSv1.3 (SSL_OP_NO_TICKET set)
12104  * Test 2: TLSv1.3 (max_early_data and SSL_OP_NO_TICKET set)
12105  * Test 3: TLSv1.3 (SSL_OP_NO_TICKET, simultaneous resumes)
12106  * Test 4: TLSv1.2
12107  */
test_multi_resume(int idx)12108 static int test_multi_resume(int idx)
12109 {
12110     SSL_CTX *sctx = NULL, *cctx = NULL;
12111     SSL *serverssl = NULL, *clientssl = NULL;
12112     SSL_SESSION *sess = NULL;
12113     int max_version = TLS1_3_VERSION;
12114     int i, testresult = 0;
12115     struct resume_servername_cb_data cbdata;
12116 
12117 #if defined(OPENSSL_NO_TLS1_2)
12118     if (idx == 4)
12119         return TEST_skip("TLSv1.2 is disabled in this build");
12120 #else
12121     if (idx == 4)
12122         max_version = TLS1_2_VERSION;
12123 #endif
12124 #if defined(OSSL_NO_USABLE_TLS1_3)
12125     if (idx != 4)
12126         return TEST_skip("No usable TLSv1.3 in this build");
12127 #endif
12128 
12129     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12130                                        TLS_client_method(), TLS1_VERSION,
12131                                        max_version, &sctx, &cctx, cert,
12132                                        privkey)))
12133         goto end;
12134 
12135     /*
12136      * TLSv1.3 only uses a session cache if either max_early_data > 0 (used for
12137      * replay protection), or if SSL_OP_NO_TICKET is in use
12138      */
12139     if (idx == 0 || idx == 2)  {
12140         if (!TEST_true(SSL_CTX_set_max_early_data(sctx, 1024)))
12141             goto end;
12142     }
12143     if (idx == 1 || idx == 2 || idx == 3)
12144         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
12145 
12146     SSL_CTX_sess_set_cache_size(sctx, 5);
12147 
12148     if (idx == 3) {
12149         SSL_CTX_set_tlsext_servername_callback(sctx, resume_servername_cb);
12150         SSL_CTX_set_tlsext_servername_arg(sctx, &cbdata);
12151         cbdata.cctx = cctx;
12152         cbdata.sctx = sctx;
12153         cbdata.recurse = 0;
12154     }
12155 
12156     for (i = 0; i < 30; i++) {
12157         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
12158                                                 NULL, NULL))
12159                 || !TEST_true(SSL_set_session(clientssl, sess)))
12160             goto end;
12161 
12162         /*
12163          * Check simultaneous resumes. We pause the connection part way through
12164          * the handshake by (mis)using the servername_cb. The pause occurs after
12165          * session resumption has already occurred, but before any session
12166          * tickets have been issued. While paused we run another complete
12167          * handshake resuming the same session.
12168          */
12169         if (idx == 3) {
12170             cbdata.i = i;
12171             cbdata.sess = sess;
12172         }
12173 
12174         /*
12175          * Recreate a bug where dynamically changing the max_early_data value
12176          * can cause sessions in the session cache which cannot be deleted.
12177          */
12178         if ((idx == 0 || idx == 2) && (i % 3) == 2)
12179             SSL_set_max_early_data(serverssl, 0);
12180 
12181         if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12182             goto end;
12183 
12184         if (sess == NULL || (idx == 0 && (i % 3) == 2)) {
12185             if (!TEST_false(SSL_session_reused(clientssl)))
12186                 goto end;
12187         } else {
12188             if (!TEST_true(SSL_session_reused(clientssl)))
12189                 goto end;
12190         }
12191         SSL_SESSION_free(sess);
12192 
12193         /* Do a full handshake, followed by two resumptions */
12194         if ((i % 3) == 2) {
12195             sess = NULL;
12196         } else {
12197             if (!TEST_ptr((sess = SSL_get1_session(clientssl))))
12198                 goto end;
12199         }
12200 
12201         SSL_shutdown(clientssl);
12202         SSL_shutdown(serverssl);
12203         SSL_free(serverssl);
12204         SSL_free(clientssl);
12205         serverssl = clientssl = NULL;
12206     }
12207 
12208     /* We should never exceed the session cache size limit */
12209     if (!TEST_long_le(SSL_CTX_sess_number(sctx), 5))
12210         goto end;
12211 
12212     testresult = 1;
12213  end:
12214     SSL_free(serverssl);
12215     SSL_free(clientssl);
12216     SSL_CTX_free(sctx);
12217     SSL_CTX_free(cctx);
12218     SSL_SESSION_free(sess);
12219     return testresult;
12220 }
12221 
12222 static struct next_proto_st {
12223     int serverlen;
12224     unsigned char server[40];
12225     int clientlen;
12226     unsigned char client[40];
12227     int expected_ret;
12228     size_t selectedlen;
12229     unsigned char selected[40];
12230 } next_proto_tests[] = {
12231     {
12232         4, { 3, 'a', 'b', 'c' },
12233         4, { 3, 'a', 'b', 'c' },
12234         OPENSSL_NPN_NEGOTIATED,
12235         3, { 'a', 'b', 'c' }
12236     },
12237     {
12238         7, { 3, 'a', 'b', 'c', 2, 'a', 'b' },
12239         4, { 3, 'a', 'b', 'c' },
12240         OPENSSL_NPN_NEGOTIATED,
12241         3, { 'a', 'b', 'c' }
12242     },
12243     {
12244         7, { 2, 'a', 'b', 3, 'a', 'b', 'c', },
12245         4, { 3, 'a', 'b', 'c' },
12246         OPENSSL_NPN_NEGOTIATED,
12247         3, { 'a', 'b', 'c' }
12248     },
12249     {
12250         4, { 3, 'a', 'b', 'c' },
12251         7, { 3, 'a', 'b', 'c', 2, 'a', 'b', },
12252         OPENSSL_NPN_NEGOTIATED,
12253         3, { 'a', 'b', 'c' }
12254     },
12255     {
12256         4, { 3, 'a', 'b', 'c' },
12257         7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
12258         OPENSSL_NPN_NEGOTIATED,
12259         3, { 'a', 'b', 'c' }
12260     },
12261     {
12262         7, { 2, 'b', 'c', 3, 'a', 'b', 'c' },
12263         7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
12264         OPENSSL_NPN_NEGOTIATED,
12265         3, { 'a', 'b', 'c' }
12266     },
12267     {
12268         10, { 2, 'b', 'c', 3, 'a', 'b', 'c', 2, 'a', 'b' },
12269         7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
12270         OPENSSL_NPN_NEGOTIATED,
12271         3, { 'a', 'b', 'c' }
12272     },
12273     {
12274         4, { 3, 'b', 'c', 'd' },
12275         4, { 3, 'a', 'b', 'c' },
12276         OPENSSL_NPN_NO_OVERLAP,
12277         3, { 'a', 'b', 'c' }
12278     },
12279     {
12280         0, { 0 },
12281         4, { 3, 'a', 'b', 'c' },
12282         OPENSSL_NPN_NO_OVERLAP,
12283         3, { 'a', 'b', 'c' }
12284     },
12285     {
12286         -1, { 0 },
12287         4, { 3, 'a', 'b', 'c' },
12288         OPENSSL_NPN_NO_OVERLAP,
12289         3, { 'a', 'b', 'c' }
12290     },
12291     {
12292         4, { 3, 'a', 'b', 'c' },
12293         0, { 0 },
12294         OPENSSL_NPN_NO_OVERLAP,
12295         0, { 0 }
12296     },
12297     {
12298         4, { 3, 'a', 'b', 'c' },
12299         -1, { 0 },
12300         OPENSSL_NPN_NO_OVERLAP,
12301         0, { 0 }
12302     },
12303     {
12304         3, { 3, 'a', 'b', 'c' },
12305         4, { 3, 'a', 'b', 'c' },
12306         OPENSSL_NPN_NO_OVERLAP,
12307         3, { 'a', 'b', 'c' }
12308     },
12309     {
12310         4, { 3, 'a', 'b', 'c' },
12311         3, { 3, 'a', 'b', 'c' },
12312         OPENSSL_NPN_NO_OVERLAP,
12313         0, { 0 }
12314     }
12315 };
12316 
test_select_next_proto(int idx)12317 static int test_select_next_proto(int idx)
12318 {
12319     struct next_proto_st *np = &next_proto_tests[idx];
12320     int ret = 0;
12321     unsigned char *out, *client, *server;
12322     unsigned char outlen;
12323     unsigned int clientlen, serverlen;
12324 
12325     if (np->clientlen == -1) {
12326         client = NULL;
12327         clientlen = 0;
12328     } else {
12329         client = np->client;
12330         clientlen = (unsigned int)np->clientlen;
12331     }
12332     if (np->serverlen == -1) {
12333         server = NULL;
12334         serverlen = 0;
12335     } else {
12336         server = np->server;
12337         serverlen = (unsigned int)np->serverlen;
12338     }
12339 
12340     if (!TEST_int_eq(SSL_select_next_proto(&out, &outlen, server, serverlen,
12341                                            client, clientlen),
12342                      np->expected_ret))
12343         goto err;
12344 
12345     if (np->selectedlen == 0) {
12346         if (!TEST_ptr_null(out) || !TEST_uchar_eq(outlen, 0))
12347             goto err;
12348     } else {
12349         if (!TEST_mem_eq(out, outlen, np->selected, np->selectedlen))
12350             goto err;
12351     }
12352 
12353     ret = 1;
12354  err:
12355     return ret;
12356 }
12357 
12358 static const unsigned char fooprot[] = {3, 'f', 'o', 'o' };
12359 static const unsigned char barprot[] = {3, 'b', 'a', 'r' };
12360 
12361 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
npn_advert_cb(SSL * ssl,const unsigned char ** out,unsigned int * outlen,void * arg)12362 static int npn_advert_cb(SSL *ssl, const unsigned char **out,
12363                          unsigned int *outlen, void *arg)
12364 {
12365     int *idx = (int *)arg;
12366 
12367     switch (*idx) {
12368     default:
12369     case 0:
12370         *out = fooprot;
12371         *outlen = sizeof(fooprot);
12372         return SSL_TLSEXT_ERR_OK;
12373 
12374     case 1:
12375         *out = NULL;
12376         *outlen = 0;
12377         return SSL_TLSEXT_ERR_OK;
12378 
12379     case 2:
12380         return SSL_TLSEXT_ERR_NOACK;
12381     }
12382 }
12383 
npn_select_cb(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)12384 static int npn_select_cb(SSL *s, unsigned char **out, unsigned char *outlen,
12385                          const unsigned char *in, unsigned int inlen, void *arg)
12386 {
12387     int *idx = (int *)arg;
12388 
12389     switch (*idx) {
12390     case 0:
12391     case 1:
12392         *out = (unsigned char *)(fooprot + 1);
12393         *outlen = *fooprot;
12394         return SSL_TLSEXT_ERR_OK;
12395 
12396     case 3:
12397         *out = (unsigned char *)(barprot + 1);
12398         *outlen = *barprot;
12399         return SSL_TLSEXT_ERR_OK;
12400 
12401     case 4:
12402         *outlen = 0;
12403         return SSL_TLSEXT_ERR_OK;
12404 
12405     default:
12406     case 2:
12407         return SSL_TLSEXT_ERR_ALERT_FATAL;
12408     }
12409 }
12410 
12411 /*
12412  * Test the NPN callbacks
12413  * Test 0: advert = foo, select = foo
12414  * Test 1: advert = <empty>, select = foo
12415  * Test 2: no advert
12416  * Test 3: advert = foo, select = bar
12417  * Test 4: advert = foo, select = <empty> (should fail)
12418  */
test_npn(int idx)12419 static int test_npn(int idx)
12420 {
12421     SSL_CTX *sctx = NULL, *cctx = NULL;
12422     SSL *serverssl = NULL, *clientssl = NULL;
12423     int testresult = 0;
12424 
12425     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12426                                        TLS_client_method(), 0, TLS1_2_VERSION,
12427                                        &sctx, &cctx, cert, privkey)))
12428         goto end;
12429 
12430     SSL_CTX_set_next_protos_advertised_cb(sctx, npn_advert_cb, &idx);
12431     SSL_CTX_set_next_proto_select_cb(cctx, npn_select_cb, &idx);
12432 
12433     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12434                                       NULL)))
12435         goto end;
12436 
12437     if (idx == 4) {
12438         /* We don't allow empty selection of NPN, so this should fail */
12439         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12440                                               SSL_ERROR_NONE)))
12441             goto end;
12442     } else {
12443         const unsigned char *prot;
12444         unsigned int protlen;
12445 
12446         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12447                                              SSL_ERROR_NONE)))
12448             goto end;
12449 
12450         SSL_get0_next_proto_negotiated(serverssl, &prot, &protlen);
12451         switch (idx) {
12452         case 0:
12453         case 1:
12454             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12455                 goto end;
12456             break;
12457         case 2:
12458             if (!TEST_uint_eq(protlen, 0))
12459                 goto end;
12460             break;
12461         case 3:
12462             if (!TEST_mem_eq(prot, protlen, barprot + 1, *barprot))
12463                 goto end;
12464             break;
12465         default:
12466             TEST_error("Should not get here");
12467             goto end;
12468         }
12469     }
12470 
12471     testresult = 1;
12472  end:
12473     SSL_free(serverssl);
12474     SSL_free(clientssl);
12475     SSL_CTX_free(sctx);
12476     SSL_CTX_free(cctx);
12477 
12478     return testresult;
12479 }
12480 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) */
12481 
alpn_select_cb2(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)12482 static int alpn_select_cb2(SSL *ssl, const unsigned char **out,
12483                            unsigned char *outlen, const unsigned char *in,
12484                            unsigned int inlen, void *arg)
12485 {
12486     int *idx = (int *)arg;
12487 
12488     switch (*idx) {
12489     case 0:
12490         *out = (unsigned char *)(fooprot + 1);
12491         *outlen = *fooprot;
12492         return SSL_TLSEXT_ERR_OK;
12493 
12494     case 2:
12495         *out = (unsigned char *)(barprot + 1);
12496         *outlen = *barprot;
12497         return SSL_TLSEXT_ERR_OK;
12498 
12499     case 3:
12500         *outlen = 0;
12501         return SSL_TLSEXT_ERR_OK;
12502 
12503     default:
12504     case 1:
12505         return SSL_TLSEXT_ERR_ALERT_FATAL;
12506     }
12507     return 0;
12508 }
12509 
12510 /*
12511  * Test the ALPN callbacks
12512  * Test 0: client = foo, select = foo
12513  * Test 1: client = <empty>, select = none
12514  * Test 2: client = foo, select = bar (should fail)
12515  * Test 3: client = foo, select = <empty> (should fail)
12516  */
test_alpn(int idx)12517 static int test_alpn(int idx)
12518 {
12519     SSL_CTX *sctx = NULL, *cctx = NULL;
12520     SSL *serverssl = NULL, *clientssl = NULL;
12521     int testresult = 0;
12522     const unsigned char *prots = fooprot;
12523     unsigned int protslen = sizeof(fooprot);
12524 
12525     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12526                                        TLS_client_method(), 0, 0,
12527                                        &sctx, &cctx, cert, privkey)))
12528         goto end;
12529 
12530     SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb2, &idx);
12531 
12532     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12533                                       NULL)))
12534         goto end;
12535 
12536     if (idx == 1) {
12537         prots = NULL;
12538         protslen = 0;
12539     }
12540 
12541     /* SSL_set_alpn_protos returns 0 for success! */
12542     if (!TEST_false(SSL_set_alpn_protos(clientssl, prots, protslen)))
12543         goto end;
12544 
12545     if (idx == 2 || idx == 3) {
12546         /* We don't allow empty selection of NPN, so this should fail */
12547         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12548                                               SSL_ERROR_NONE)))
12549             goto end;
12550     } else {
12551         const unsigned char *prot;
12552         unsigned int protlen;
12553 
12554         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12555                                              SSL_ERROR_NONE)))
12556             goto end;
12557 
12558         SSL_get0_alpn_selected(clientssl, &prot, &protlen);
12559         switch (idx) {
12560         case 0:
12561             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12562                 goto end;
12563             break;
12564         case 1:
12565             if (!TEST_uint_eq(protlen, 0))
12566                 goto end;
12567             break;
12568         default:
12569             TEST_error("Should not get here");
12570             goto end;
12571         }
12572     }
12573 
12574     testresult = 1;
12575  end:
12576     SSL_free(serverssl);
12577     SSL_free(clientssl);
12578     SSL_CTX_free(sctx);
12579     SSL_CTX_free(cctx);
12580 
12581     return testresult;
12582 }
12583 
12584 #if !defined(OSSL_NO_USABLE_TLS1_3)
12585 struct quic_tls_test_data {
12586     struct quic_tls_test_data *peer;
12587     uint32_t renc_level;
12588     uint32_t wenc_level;
12589     unsigned char rcd_data[4][2048];
12590     size_t rcd_data_len[4];
12591     unsigned char rsecret[3][48];
12592     size_t rsecret_len[3];
12593     unsigned char wsecret[3][48];
12594     size_t wsecret_len[3];
12595     unsigned char params[3];
12596     size_t params_len;
12597     int alert;
12598     int err;
12599     int forcefail;
12600     int sm_count;
12601 };
12602 
12603 static int clientquicdata = 0xff, serverquicdata = 0xfe;
12604 
check_app_data(SSL * s)12605 static int check_app_data(SSL *s)
12606 {
12607     int *data, *comparedata;
12608 
12609     /* Check app data works */
12610     data = (int *)SSL_get_app_data(s);
12611     comparedata = SSL_is_server(s) ? &serverquicdata : &clientquicdata;
12612 
12613     if (!TEST_true(comparedata == data))
12614         return 0;
12615 
12616     return 1;
12617 }
12618 
crypto_send_cb(SSL * s,const unsigned char * buf,size_t buf_len,size_t * consumed,void * arg)12619 static int crypto_send_cb(SSL *s, const unsigned char *buf, size_t buf_len,
12620                           size_t *consumed, void *arg)
12621 {
12622     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12623     struct quic_tls_test_data *peer = data->peer;
12624     size_t max_len = sizeof(peer->rcd_data[data->wenc_level])
12625                      - peer->rcd_data_len[data->wenc_level];
12626 
12627     if (!check_app_data(s)) {
12628         data->err = 1;
12629         return 0;
12630     }
12631 
12632     if (buf_len > max_len)
12633         buf_len = max_len;
12634 
12635     if (buf_len == 0) {
12636         *consumed = 0;
12637         return 1;
12638     }
12639 
12640     memcpy(peer->rcd_data[data->wenc_level]
12641            + peer->rcd_data_len[data->wenc_level], buf, buf_len);
12642     peer->rcd_data_len[data->wenc_level] += buf_len;
12643 
12644     *consumed = buf_len;
12645     return 1;
12646 }
crypto_recv_rcd_cb(SSL * s,const unsigned char ** buf,size_t * bytes_read,void * arg)12647 static int crypto_recv_rcd_cb(SSL *s, const unsigned char **buf,
12648                               size_t *bytes_read, void *arg)
12649 {
12650     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12651 
12652     if (!check_app_data(s)) {
12653         data->err = 1;
12654         return 0;
12655     }
12656 
12657     *bytes_read = data->rcd_data_len[data->renc_level];
12658     *buf = data->rcd_data[data->renc_level];
12659     return 1;
12660 }
12661 
crypto_release_rcd_cb(SSL * s,size_t bytes_read,void * arg)12662 static int crypto_release_rcd_cb(SSL *s, size_t bytes_read, void *arg)
12663 {
12664     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12665 
12666     if (!check_app_data(s)) {
12667         data->err = 1;
12668         return 0;
12669     }
12670 
12671     /* See if we need to force a failure in this callback */
12672     if (data->forcefail) {
12673         data->forcefail = 0;
12674         data->err = 1;
12675         return 0;
12676     }
12677 
12678     if (!TEST_size_t_eq(bytes_read, data->rcd_data_len[data->renc_level])
12679             || !TEST_size_t_gt(bytes_read, 0)) {
12680         data->err = 1;
12681         return 0;
12682     }
12683     data->rcd_data_len[data->renc_level] = 0;
12684 
12685     return 1;
12686 }
12687 
12688 struct secret_yield_entry {
12689     uint8_t recorded;
12690     int prot_level;
12691     int direction;
12692     int sm_generation;
12693     SSL *ssl;
12694 };
12695 
12696 static struct secret_yield_entry secret_history[16];
12697 static int secret_history_idx = 0;
12698 /*
12699  * Note, this enum needs to match the direction values passed
12700  * to yield_secret_cb
12701  */
12702 typedef enum {
12703     LAST_DIR_READ = 0,
12704     LAST_DIR_WRITE = 1,
12705     LAST_DIR_UNSET = 2
12706 } last_dir_history_state;
12707 
check_secret_history(SSL * s)12708 static int check_secret_history(SSL *s)
12709 {
12710     int i;
12711     int ret = 0;
12712     last_dir_history_state last_state = LAST_DIR_UNSET;
12713     int last_prot_level = 0;
12714     int last_generation = 0;
12715 
12716     TEST_info("Checking history for %p\n", (void *)s);
12717     for (i = 0; secret_history[i].recorded == 1; i++) {
12718         if (secret_history[i].ssl != s)
12719             continue;
12720         TEST_info("Got %s(%d) secret for level %d, last level %d, last state %d, gen %d\n",
12721                   secret_history[i].direction == 1 ? "Write" : "Read", secret_history[i].direction,
12722                   secret_history[i].prot_level, last_prot_level, last_state,
12723                   secret_history[i].sm_generation);
12724 
12725         if (last_state == LAST_DIR_UNSET) {
12726             last_prot_level = secret_history[i].prot_level;
12727             last_state = secret_history[i].direction;
12728             last_generation = secret_history[i].sm_generation;
12729             continue;
12730         }
12731 
12732         switch(secret_history[i].direction) {
12733         case 1:
12734             /*
12735              * write case
12736              * NOTE: There is an odd corner case here.  It may occur that
12737              * in a single iteration of the state machine, the read key is yielded
12738              * prior to the write key for the same level.  This is undesireable
12739              * for quic, but it is ok, as the general implementation of every 3rd
12740              * party quic stack while prefering write keys before read, allows
12741              * for read before write if both keys are yielded in the same call
12742              * to SSL_do_handshake, as the tls adaptation code for that quic stack
12743              * can then cache keys until both are available, so we allow read before
12744              * write here iff they occur in the same iteration of SSL_do_handshake
12745              * as represented by the recorded sm_generation value.
12746              */
12747             if (last_prot_level == secret_history[i].prot_level
12748                 && last_state == LAST_DIR_READ) {
12749                 if (last_generation == secret_history[i].sm_generation) {
12750                     TEST_info("Read before write key in same SSL state machine iteration is ok");
12751                 } else {
12752                     TEST_error("Got read key before write key");
12753                     goto end;
12754                 }
12755             }
12756             /* FALLTHROUGH */
12757         case 0:
12758             /*
12759              * Read case
12760              */
12761             break;
12762         default:
12763             TEST_error("Unknown direction");
12764             goto end;
12765         }
12766         last_prot_level = secret_history[i].prot_level;
12767         last_state = secret_history[i].direction;
12768         last_generation = secret_history[i].sm_generation;
12769     }
12770 
12771     ret = 1;
12772 end:
12773     return ret;
12774 }
12775 
yield_secret_cb(SSL * s,uint32_t prot_level,int direction,const unsigned char * secret,size_t secret_len,void * arg)12776 static int yield_secret_cb(SSL *s, uint32_t prot_level, int direction,
12777                            const unsigned char *secret, size_t secret_len,
12778                            void *arg)
12779 {
12780     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12781 
12782     if (!check_app_data(s))
12783         goto err;
12784 
12785     if (prot_level < OSSL_RECORD_PROTECTION_LEVEL_EARLY
12786             || prot_level > OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
12787         goto err;
12788 
12789     switch (direction) {
12790     case 0: /* read */
12791         if (!TEST_size_t_le(secret_len, sizeof(data->rsecret)))
12792             goto err;
12793         data->renc_level = prot_level;
12794         memcpy(data->rsecret[prot_level - 1], secret, secret_len);
12795         data->rsecret_len[prot_level - 1] = secret_len;
12796         break;
12797 
12798     case 1: /* write */
12799         if (!TEST_size_t_le(secret_len, sizeof(data->wsecret)))
12800             goto err;
12801         data->wenc_level = prot_level;
12802         memcpy(data->wsecret[prot_level - 1], secret, secret_len);
12803         data->wsecret_len[prot_level - 1] = secret_len;
12804         break;
12805 
12806     default:
12807         goto err;
12808     }
12809 
12810     secret_history[secret_history_idx].direction = direction;
12811     secret_history[secret_history_idx].prot_level = (int)prot_level;
12812     secret_history[secret_history_idx].recorded = 1;
12813     secret_history[secret_history_idx].ssl = s;
12814     secret_history[secret_history_idx].sm_generation = data->sm_count;
12815     secret_history_idx++;
12816     return 1;
12817  err:
12818     data->err = 1;
12819     return 0;
12820 }
12821 
yield_secret_cb_fail(SSL * s,uint32_t prot_level,int direction,const unsigned char * secret,size_t secret_len,void * arg)12822 static int yield_secret_cb_fail(SSL *s, uint32_t prot_level, int direction,
12823                                 const unsigned char *secret, size_t secret_len,
12824                                 void *arg)
12825 {
12826     (void)s;
12827     (void)prot_level;
12828     (void)direction;
12829     (void)secret;
12830     (void)secret_len;
12831     (void)arg;
12832     /*
12833      * This callback is to test double free in quic tls
12834      */
12835     return 0;
12836 }
12837 
got_transport_params_cb(SSL * s,const unsigned char * params,size_t params_len,void * arg)12838 static int got_transport_params_cb(SSL *s, const unsigned char *params,
12839                                    size_t params_len,
12840                                    void *arg)
12841 {
12842     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12843 
12844     if (!check_app_data(s)) {
12845         data->err = 1;
12846         return 0;
12847     }
12848 
12849     if (!TEST_size_t_le(params_len, sizeof(data->params))) {
12850         data->err = 1;
12851         return 0;
12852     }
12853 
12854     memcpy(data->params, params, params_len);
12855     data->params_len = params_len;
12856 
12857     return 1;
12858 }
12859 
alert_cb(SSL * s,unsigned char alert_code,void * arg)12860 static int alert_cb(SSL *s, unsigned char alert_code, void *arg)
12861 {
12862     struct quic_tls_test_data *data = (struct quic_tls_test_data *)arg;
12863 
12864     if (!check_app_data(s)) {
12865         data->err = 1;
12866         return 0;
12867     }
12868 
12869     data->alert = 1;
12870     return 1;
12871 }
12872 
12873 /*
12874  * Test the QUIC TLS API
12875  * Test 0: Normal run
12876  * Test 1: Force a failure
12877  * Test 3: Use a CCM based ciphersuite
12878  * Test 4: fail yield_secret_cb to see double free
12879  * Test 5: Normal run with SNI
12880  */
test_quic_tls(int idx)12881 static int test_quic_tls(int idx)
12882 {
12883     SSL_CTX *sctx = NULL, *sctx2 = NULL, *cctx = NULL;
12884     SSL *serverssl = NULL, *clientssl = NULL;
12885     int testresult = 0;
12886     OSSL_DISPATCH qtdis[] = {
12887         {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb},
12888         {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD,
12889          (void (*)(void))crypto_recv_rcd_cb},
12890         {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD,
12891          (void (*)(void))crypto_release_rcd_cb},
12892         {OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET,
12893          (void (*)(void))yield_secret_cb},
12894         {OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS,
12895          (void (*)(void))got_transport_params_cb},
12896         {OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb},
12897         {0, NULL}
12898     };
12899     struct quic_tls_test_data sdata, cdata;
12900     const unsigned char cparams[] = {
12901         0xff, 0x01, 0x00
12902     };
12903     const unsigned char sparams[] = {
12904         0xfe, 0x01, 0x00
12905     };
12906     int i;
12907 
12908     if (idx == 4)
12909         qtdis[3].function = (void (*)(void))yield_secret_cb_fail;
12910 
12911     snicb = 0;
12912     memset(secret_history, 0, sizeof(secret_history));
12913     secret_history_idx = 0;
12914     memset(&sdata, 0, sizeof(sdata));
12915     memset(&cdata, 0, sizeof(cdata));
12916     sdata.peer = &cdata;
12917     cdata.peer = &sdata;
12918     if (idx == 1)
12919         sdata.forcefail = 1;
12920 
12921     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12922                                        TLS_client_method(), TLS1_3_VERSION, 0,
12923                                        &sctx, &cctx, cert, privkey)))
12924         goto end;
12925 
12926     if (idx == 5) {
12927         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
12928                                            TLS1_3_VERSION, 0,
12929                                            &sctx2, NULL, cert, privkey)))
12930             goto end;
12931 
12932         /* Set up SNI */
12933         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
12934                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
12935             goto end;
12936     }
12937 
12938     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12939                                       NULL)))
12940         goto end;
12941 
12942     /* Reset the BIOs we set in create_ssl_objects. We should not need them */
12943     SSL_set_bio(serverssl, NULL, NULL);
12944     SSL_set_bio(clientssl, NULL, NULL);
12945 
12946     if (idx == 2) {
12947         if (!TEST_true(SSL_set_ciphersuites(serverssl, "TLS_AES_128_CCM_SHA256"))
12948                 || !TEST_true(SSL_set_ciphersuites(clientssl, "TLS_AES_128_CCM_SHA256")))
12949             goto end;
12950     }
12951 
12952     if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata))
12953             || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata)))
12954         goto end;
12955 
12956     if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata))
12957             || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata))
12958             || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams,
12959                                                             sizeof(cparams)))
12960             || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams,
12961                                                             sizeof(sparams))))
12962         goto end;
12963 
12964     if (idx != 1 && idx != 4) {
12965         if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
12966                                                 &cdata.sm_count, &sdata.sm_count)))
12967             goto end;
12968     } else {
12969         /* We expect this connection to fail */
12970         if (!TEST_false(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
12971                                                  &cdata.sm_count, &sdata.sm_count)))
12972             goto end;
12973         testresult = 1;
12974         sdata.err = 0;
12975         goto end;
12976     }
12977 
12978     /* We should have had the SNI callback called exactly once */
12979     if (idx == 5) {
12980         if (!TEST_int_eq(snicb, 1))
12981             goto end;
12982     }
12983 
12984     /* Check no problems during the handshake */
12985     if (!TEST_false(sdata.alert)
12986             || !TEST_false(cdata.alert)
12987             || !TEST_false(sdata.err)
12988             || !TEST_false(cdata.err))
12989         goto end;
12990 
12991     /* Check the secrets all match */
12992     for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1;
12993          i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION;
12994          i++) {
12995         if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i],
12996                          cdata.rsecret[i], cdata.rsecret_len[i]))
12997             goto end;
12998     }
12999 
13000     /*
13001      * Check that our secret history yields write secrets before read secrets
13002      */
13003     if (!TEST_int_eq(check_secret_history(serverssl), 1))
13004         goto end;
13005     if (!TEST_int_eq(check_secret_history(clientssl), 1))
13006         goto end;
13007 
13008     /* Check the transport params */
13009     if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams))
13010             || !TEST_mem_eq(cdata.params, cdata.params_len, sparams,
13011                             sizeof(sparams)))
13012         goto end;
13013 
13014     /* Check the encryption levels are what we expect them to be */
13015     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13016             || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13017             || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13018             || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION))
13019         goto end;
13020 
13021     testresult = 1;
13022  end:
13023     SSL_free(serverssl);
13024     SSL_free(clientssl);
13025     SSL_CTX_free(sctx2);
13026     SSL_CTX_free(sctx);
13027     SSL_CTX_free(cctx);
13028 
13029     /* Check that we didn't suddenly hit an unexpected failure during cleanup */
13030     if (!TEST_false(sdata.err) || !TEST_false(cdata.err))
13031         testresult = 0;
13032 
13033     return testresult;
13034 }
13035 
assert_no_end_of_early_data(int write_p,int version,int content_type,const void * buf,size_t msglen,SSL * ssl,void * arg)13036 static void assert_no_end_of_early_data(int write_p, int version, int content_type,
13037                                         const void *buf, size_t msglen, SSL *ssl, void *arg)
13038 {
13039     const unsigned char *msg = buf;
13040 
13041     if (content_type == SSL3_RT_HANDSHAKE && msg[0] == SSL3_MT_END_OF_EARLY_DATA)
13042         end_of_early_data = 1;
13043 }
13044 
test_quic_tls_early_data(void)13045 static int test_quic_tls_early_data(void)
13046 {
13047     SSL_CTX *sctx = NULL, *cctx = NULL;
13048     SSL *serverssl = NULL, *clientssl = NULL;
13049     int testresult = 0;
13050     SSL_SESSION *sess = NULL;
13051     const OSSL_DISPATCH qtdis[] = {
13052         {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_SEND, (void (*)(void))crypto_send_cb},
13053         {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RECV_RCD,
13054          (void (*)(void))crypto_recv_rcd_cb},
13055         {OSSL_FUNC_SSL_QUIC_TLS_CRYPTO_RELEASE_RCD,
13056          (void (*)(void))crypto_release_rcd_cb},
13057         {OSSL_FUNC_SSL_QUIC_TLS_YIELD_SECRET,
13058          (void (*)(void))yield_secret_cb},
13059         {OSSL_FUNC_SSL_QUIC_TLS_GOT_TRANSPORT_PARAMS,
13060          (void (*)(void))got_transport_params_cb},
13061         {OSSL_FUNC_SSL_QUIC_TLS_ALERT, (void (*)(void))alert_cb},
13062         {0, NULL}
13063     };
13064     struct quic_tls_test_data sdata, cdata;
13065     const unsigned char cparams[] = {
13066         0xff, 0x01, 0x00
13067     };
13068     const unsigned char sparams[] = {
13069         0xfe, 0x01, 0x00
13070     };
13071     int i;
13072 
13073     memset(secret_history, 0, sizeof(secret_history));
13074     secret_history_idx = 0;
13075     memset(&sdata, 0, sizeof(sdata));
13076     memset(&cdata, 0, sizeof(cdata));
13077     sdata.peer = &cdata;
13078     cdata.peer = &sdata;
13079     end_of_early_data = 0;
13080 
13081     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13082                                        TLS_client_method(), TLS1_3_VERSION, 0,
13083                                        &sctx, &cctx, cert, privkey)))
13084         goto end;
13085 
13086     SSL_CTX_set_max_early_data(sctx, 0xffffffff);
13087     SSL_CTX_set_max_early_data(cctx, 0xffffffff);
13088 
13089     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13090                                       NULL)))
13091         goto end;
13092 
13093     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13094         goto end;
13095 
13096     sess = SSL_get1_session(clientssl);
13097     SSL_shutdown(clientssl);
13098     SSL_shutdown(serverssl);
13099     SSL_free(serverssl);
13100     SSL_free(clientssl);
13101     serverssl = clientssl = NULL;
13102 
13103     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
13104                                       &clientssl, NULL, NULL))
13105             || !TEST_true(SSL_set_session(clientssl, sess)))
13106         goto end;
13107 
13108     /* Reset the BIOs we set in create_ssl_objects. We should not need them */
13109     SSL_set_bio(serverssl, NULL, NULL);
13110     SSL_set_bio(clientssl, NULL, NULL);
13111 
13112     if (!TEST_true(SSL_set_app_data(clientssl, &clientquicdata))
13113         || !TEST_true(SSL_set_app_data(serverssl, &serverquicdata)))
13114         goto end;
13115 
13116     if (!TEST_true(SSL_set_quic_tls_cbs(clientssl, qtdis, &cdata))
13117             || !TEST_true(SSL_set_quic_tls_cbs(serverssl, qtdis, &sdata))
13118             || !TEST_true(SSL_set_quic_tls_transport_params(clientssl, cparams,
13119                                                             sizeof(cparams)))
13120             || !TEST_true(SSL_set_quic_tls_transport_params(serverssl, sparams,
13121                                                             sizeof(sparams))))
13122         goto end;
13123 
13124     /*
13125      * Reset our secret history so we get the record of the second connection
13126      */
13127     memset(secret_history, 0, sizeof(secret_history));
13128     secret_history_idx = 0;
13129 
13130     SSL_set_quic_tls_early_data_enabled(serverssl, 1);
13131     SSL_set_quic_tls_early_data_enabled(clientssl, 1);
13132 
13133     SSL_set_msg_callback(serverssl, assert_no_end_of_early_data);
13134     SSL_set_msg_callback(clientssl, assert_no_end_of_early_data);
13135 
13136     if (!TEST_int_eq(SSL_connect(clientssl), -1)
13137             || !TEST_int_eq(SSL_accept(serverssl), -1)
13138             || !TEST_int_eq(SSL_get_early_data_status(serverssl), SSL_EARLY_DATA_ACCEPTED)
13139             || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_READ)
13140             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_READ))
13141         goto end;
13142 
13143     /* Check the encryption levels are what we expect them to be */
13144     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE)
13145             || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13146             || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
13147             || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_EARLY))
13148         goto end;
13149 
13150     sdata.sm_count = 0;
13151     cdata.sm_count = 0;
13152     if (!TEST_true(create_ssl_connection_ex(serverssl, clientssl, SSL_ERROR_NONE,
13153                                             &cdata.sm_count, &sdata.sm_count)))
13154         goto end;
13155 
13156     /* Check no problems during the handshake */
13157     if (!TEST_false(sdata.alert)
13158             || !TEST_false(cdata.alert)
13159             || !TEST_false(sdata.err)
13160             || !TEST_false(cdata.err))
13161         goto end;
13162 
13163     /* Check the secrets all match */
13164     for (i = OSSL_RECORD_PROTECTION_LEVEL_EARLY - 1;
13165          i < OSSL_RECORD_PROTECTION_LEVEL_APPLICATION;
13166          i++) {
13167         if (!TEST_mem_eq(sdata.wsecret[i], sdata.wsecret_len[i],
13168                          cdata.rsecret[i], cdata.rsecret_len[i]))
13169             goto end;
13170     }
13171 
13172     if (!TEST_int_eq(check_secret_history(serverssl), 1))
13173         goto end;
13174     if (!TEST_int_eq(check_secret_history(clientssl), 1))
13175         goto end;
13176 
13177     /* Check the transport params */
13178     if (!TEST_mem_eq(sdata.params, sdata.params_len, cparams, sizeof(cparams))
13179             || !TEST_mem_eq(cdata.params, cdata.params_len, sparams,
13180                             sizeof(sparams)))
13181         goto end;
13182 
13183     /* Check the encryption levels are what we expect them to be */
13184     if (!TEST_true(sdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13185             || !TEST_true(sdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13186             || !TEST_true(cdata.renc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
13187             || !TEST_true(cdata.wenc_level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION))
13188         goto end;
13189 
13190     /* Check there is no EndOfEearlyData in handshake */
13191     if (!TEST_int_eq(end_of_early_data, 0))
13192         goto end;
13193 
13194     testresult = 1;
13195  end:
13196     SSL_SESSION_free(sess);
13197     SSL_SESSION_free(clientpsk);
13198     SSL_SESSION_free(serverpsk);
13199     clientpsk = serverpsk = NULL;
13200     SSL_free(serverssl);
13201     SSL_free(clientssl);
13202     SSL_CTX_free(sctx);
13203     SSL_CTX_free(cctx);
13204 
13205     return testresult;
13206 }
13207 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) */
13208 
test_no_renegotiation(int idx)13209 static int test_no_renegotiation(int idx)
13210 {
13211     SSL_CTX *sctx = NULL, *cctx = NULL;
13212     SSL *serverssl = NULL, *clientssl = NULL;
13213     int testresult = 0, ret;
13214     int max_proto;
13215     const SSL_METHOD *sm, *cm;
13216     unsigned char buf[5];
13217 
13218     if (idx == 0) {
13219 #ifndef OPENSSL_NO_TLS1_2
13220         max_proto = TLS1_2_VERSION;
13221         sm = TLS_server_method();
13222         cm = TLS_client_method();
13223 #else
13224         return TEST_skip("TLSv1.2 is disabled in this build");
13225 #endif
13226     } else {
13227 #ifndef OPENSSL_NO_DTLS1_2
13228         max_proto = DTLS1_2_VERSION;
13229         sm = DTLS_server_method();
13230         cm = DTLS_client_method();
13231 #else
13232         return TEST_skip("DTLSv1.2 is disabled in this build");
13233 #endif
13234     }
13235     if (!TEST_true(create_ssl_ctx_pair(libctx, sm, cm, 0, max_proto,
13236                                        &sctx, &cctx, cert, privkey)))
13237         goto end;
13238 
13239     SSL_CTX_set_options(sctx, SSL_OP_NO_RENEGOTIATION);
13240 
13241     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
13242                                       NULL)))
13243         goto end;
13244 
13245     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13246         goto end;
13247 
13248     if (!TEST_true(SSL_renegotiate(clientssl))
13249             || !TEST_int_le(ret = SSL_connect(clientssl), 0)
13250             || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_WANT_READ))
13251         goto end;
13252 
13253     /*
13254      * We've not sent any application data, so we expect this to fail. It should
13255      * also read the renegotiation attempt, and send back a no_renegotiation
13256      * warning alert because we have renegotiation disabled.
13257      */
13258     if (!TEST_int_le(ret = SSL_read(serverssl, buf, sizeof(buf)), 0))
13259         goto end;
13260     if (!TEST_int_eq(SSL_get_error(serverssl, ret), SSL_ERROR_WANT_READ))
13261         goto end;
13262 
13263     /*
13264      * The client should now see the no_renegotiation warning and fail the
13265      * connection
13266      */
13267     if (!TEST_int_le(ret = SSL_connect(clientssl), 0)
13268             || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_SSL)
13269             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_NO_RENEGOTIATION))
13270         goto end;
13271 
13272     testresult = 1;
13273  end:
13274     SSL_free(serverssl);
13275     SSL_free(clientssl);
13276     SSL_CTX_free(sctx);
13277     SSL_CTX_free(cctx);
13278 
13279     return testresult;
13280 }
13281 
13282 #if defined(DO_SSL_TRACE_TEST)
13283 /*
13284  * Tests that the SSL_trace() msg_callback works as expected with a PQ Groups.
13285  */
test_ssl_trace(void)13286 static int test_ssl_trace(void)
13287 {
13288     SSL_CTX *sctx = NULL, *cctx = NULL;
13289     SSL *serverssl = NULL, *clientssl = NULL;
13290     int testresult = 0;
13291     BIO *bio = NULL;
13292     char *reffile = NULL;
13293     char *grouplist = "MLKEM512:MLKEM768:MLKEM1024:X25519MLKEM768:SecP256r1MLKEM768"
13294         ":SecP384r1MLKEM1024:secp521r1:secp384r1:secp256r1";
13295 
13296     if (!fips_provider_version_ge(libctx, 3, 5, 0))
13297         return TEST_skip("FIPS provider does not support MLKEM algorithms");
13298 
13299     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
13300                                        TLS_client_method(),
13301                                        TLS1_3_VERSION, TLS1_3_VERSION,
13302                                        &sctx, &cctx, cert, privkey))
13303             || !TEST_ptr(bio = BIO_new(BIO_s_mem()))
13304             || !TEST_true(SSL_CTX_set1_groups_list(sctx, grouplist))
13305             || !TEST_true(SSL_CTX_set1_groups_list(cctx, grouplist))
13306             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
13307                                                    "TLS_AES_128_GCM_SHA256"))
13308             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
13309                                                    "TLS_AES_128_GCM_SHA256"))
13310 # ifdef SSL_OP_LEGACY_EC_POINT_FORMATS
13311             || !TEST_true(SSL_CTX_set_options(cctx, SSL_OP_LEGACY_EC_POINT_FORMATS))
13312             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_LEGACY_EC_POINT_FORMATS))
13313 # endif
13314             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
13315                                              NULL, NULL)))
13316         goto err;
13317 
13318     SSL_set_msg_callback(clientssl, SSL_trace);
13319     SSL_set_msg_callback_arg(clientssl, bio);
13320 
13321     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
13322         goto err;
13323 
13324     /* Skip the comparison of the trace when the fips provider is used. */
13325     if (is_fips) {
13326         /* Check whether there was something written. */
13327         if (!TEST_int_gt(BIO_pending(bio), 0))
13328             goto err;
13329     } else {
13330 
13331 # ifdef OPENSSL_NO_ZLIB
13332         reffile = test_mk_file_path(datadir, "ssltraceref.txt");
13333 # else
13334         reffile = test_mk_file_path(datadir, "ssltraceref-zlib.txt");
13335 # endif
13336         if (!TEST_true(compare_with_reference_file(bio, reffile)))
13337             goto err;
13338     }
13339 
13340     testresult = 1;
13341  err:
13342     BIO_free(bio);
13343     SSL_free(serverssl);
13344     SSL_free(clientssl);
13345     SSL_CTX_free(sctx);
13346     SSL_CTX_free(cctx);
13347     OPENSSL_free(reffile);
13348 
13349     return testresult;
13350 }
13351 #endif
13352 
13353 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config dhfile\n")
13354 
setup_tests(void)13355 int setup_tests(void)
13356 {
13357     char *modulename;
13358     char *configfile;
13359 
13360     libctx = OSSL_LIB_CTX_new();
13361     if (!TEST_ptr(libctx))
13362         return 0;
13363 
13364     defctxnull = OSSL_PROVIDER_load(NULL, "null");
13365 
13366     /*
13367      * Verify that the default and fips providers in the default libctx are not
13368      * available
13369      */
13370     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
13371             || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
13372         return 0;
13373 
13374     if (!test_skip_common_options()) {
13375         TEST_error("Error parsing test options\n");
13376         return 0;
13377     }
13378 
13379     if (!TEST_ptr(certsdir = test_get_argument(0))
13380             || !TEST_ptr(srpvfile = test_get_argument(1))
13381             || !TEST_ptr(tmpfilename = test_get_argument(2))
13382             || !TEST_ptr(modulename = test_get_argument(3))
13383             || !TEST_ptr(configfile = test_get_argument(4))
13384             || !TEST_ptr(dhfile = test_get_argument(5)))
13385         return 0;
13386 
13387     datadir = test_get_argument(6);
13388 
13389     if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
13390         return 0;
13391 
13392     /* Check we have the expected provider available */
13393     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
13394         return 0;
13395 
13396     /* Check the default provider is not available */
13397     if (strcmp(modulename, "default") != 0
13398             && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
13399         return 0;
13400 
13401     if (strcmp(modulename, "fips") == 0) {
13402         OSSL_PROVIDER *prov = NULL;
13403         OSSL_PARAM params[2];
13404 
13405         is_fips = 1;
13406 
13407         prov = OSSL_PROVIDER_load(libctx, "fips");
13408         if (prov != NULL) {
13409             /* Query the fips provider to check if the check ems option is enabled */
13410             params[0] =
13411                 OSSL_PARAM_construct_int(OSSL_PROV_PARAM_TLS1_PRF_EMS_CHECK,
13412                                          &fips_ems_check);
13413             params[1] = OSSL_PARAM_construct_end();
13414             OSSL_PROVIDER_get_params(prov, params);
13415             OSSL_PROVIDER_unload(prov);
13416         }
13417     }
13418 
13419     /*
13420      * We add, but don't load the test "tls-provider". We'll load it when we
13421      * need it.
13422      */
13423     if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider",
13424                                              tls_provider_init)))
13425         return 0;
13426 
13427 
13428     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
13429 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
13430         TEST_error("not supported in this build");
13431         return 0;
13432 #else
13433         int i, mcount, rcount, fcount;
13434 
13435         for (i = 0; i < 4; i++)
13436             test_export_key_mat(i);
13437         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
13438         test_printf_stdout("malloc %d realloc %d free %d\n",
13439                 mcount, rcount, fcount);
13440         return 1;
13441 #endif
13442     }
13443 
13444     cert = test_mk_file_path(certsdir, "servercert.pem");
13445     if (cert == NULL)
13446         goto err;
13447 
13448     privkey = test_mk_file_path(certsdir, "serverkey.pem");
13449     if (privkey == NULL)
13450         goto err;
13451 
13452     cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
13453     if (cert2 == NULL)
13454         goto err;
13455 
13456     privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
13457     if (privkey2 == NULL)
13458         goto err;
13459 
13460     cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem");
13461     if (cert1024 == NULL)
13462         goto err;
13463 
13464     privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem");
13465     if (privkey1024 == NULL)
13466         goto err;
13467 
13468     cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem");
13469     if (cert3072 == NULL)
13470         goto err;
13471 
13472     privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem");
13473     if (privkey3072 == NULL)
13474         goto err;
13475 
13476     cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem");
13477     if (cert4096 == NULL)
13478         goto err;
13479 
13480     privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem");
13481     if (privkey4096 == NULL)
13482         goto err;
13483 
13484     cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem");
13485     if (cert8192 == NULL)
13486         goto err;
13487 
13488     privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem");
13489     if (privkey8192 == NULL)
13490         goto err;
13491 
13492     if (fips_ems_check) {
13493 #ifndef OPENSSL_NO_TLS1_2
13494         ADD_TEST(test_no_ems);
13495 #endif
13496         return 1;
13497     }
13498 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
13499 # if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
13500     ADD_ALL_TESTS(test_ktls, NUM_KTLS_TEST_CIPHERS * 4);
13501     ADD_ALL_TESTS(test_ktls_sendfile, NUM_KTLS_TEST_CIPHERS * 2);
13502 # endif
13503 #endif
13504     ADD_TEST(test_large_message_tls);
13505     ADD_TEST(test_large_message_tls_read_ahead);
13506 #ifndef OPENSSL_NO_DTLS
13507     ADD_TEST(test_large_message_dtls);
13508 #endif
13509     ADD_ALL_TESTS(test_large_app_data, 28);
13510     ADD_TEST(test_cleanse_plaintext);
13511 #ifndef OPENSSL_NO_OCSP
13512     ADD_TEST(test_tlsext_status_type);
13513 #endif
13514     ADD_TEST(test_session_with_only_int_cache);
13515     ADD_TEST(test_session_with_only_ext_cache);
13516     ADD_TEST(test_session_with_both_cache);
13517     ADD_TEST(test_session_wo_ca_names);
13518 #ifndef OSSL_NO_USABLE_TLS1_3
13519     ADD_ALL_TESTS(test_stateful_tickets, 3);
13520     ADD_ALL_TESTS(test_stateless_tickets, 3);
13521     ADD_TEST(test_psk_tickets);
13522     ADD_ALL_TESTS(test_extra_tickets, 6);
13523 #endif
13524     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
13525     ADD_TEST(test_ssl_bio_pop_next_bio);
13526     ADD_TEST(test_ssl_bio_pop_ssl_bio);
13527     ADD_TEST(test_ssl_bio_change_rbio);
13528     ADD_TEST(test_ssl_bio_change_wbio);
13529 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
13530     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
13531     ADD_TEST(test_keylog);
13532 #endif
13533 #ifndef OSSL_NO_USABLE_TLS1_3
13534     ADD_TEST(test_keylog_no_master_key);
13535 #endif
13536     ADD_TEST(test_client_cert_verify_cb);
13537     ADD_TEST(test_ssl_build_cert_chain);
13538     ADD_TEST(test_ssl_ctx_build_cert_chain);
13539 #ifndef OPENSSL_NO_TLS1_2
13540     ADD_TEST(test_client_hello_cb);
13541     ADD_TEST(test_no_ems);
13542     ADD_TEST(test_ccs_change_cipher);
13543 #endif
13544 #ifndef OSSL_NO_USABLE_TLS1_3
13545     ADD_ALL_TESTS(test_early_data_read_write, 6);
13546     /*
13547      * We don't do replay tests for external PSK. Replay protection isn't used
13548      * in that scenario.
13549      */
13550     ADD_ALL_TESTS(test_early_data_replay, 2);
13551     ADD_ALL_TESTS(test_early_data_skip, OSSL_NELEM(ciphersuites) * 3);
13552     ADD_ALL_TESTS(test_early_data_skip_hrr, OSSL_NELEM(ciphersuites) * 3);
13553     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, OSSL_NELEM(ciphersuites) * 3);
13554     ADD_ALL_TESTS(test_early_data_skip_abort, OSSL_NELEM(ciphersuites) * 3);
13555     ADD_ALL_TESTS(test_early_data_not_sent, 3);
13556     ADD_ALL_TESTS(test_early_data_psk, 8);
13557     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 7);
13558     ADD_ALL_TESTS(test_early_data_not_expected, 3);
13559 # ifndef OPENSSL_NO_TLS1_2
13560     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
13561 # endif
13562 #endif
13563 #ifndef OSSL_NO_USABLE_TLS1_3
13564     ADD_ALL_TESTS(test_set_ciphersuite, 10);
13565     ADD_TEST(test_ciphersuite_change);
13566     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
13567 # ifdef OPENSSL_NO_PSK
13568     ADD_ALL_TESTS(test_tls13_psk, 1);
13569 # else
13570     ADD_ALL_TESTS(test_tls13_psk, 4);
13571 # endif  /* OPENSSL_NO_PSK */
13572 #ifndef OSSL_NO_USABLE_TLS1_3
13573     ADD_ALL_TESTS(test_tls13_no_dhe_kex, 8);
13574 #endif /* OSSL_NO_USABLE_TLS1_3 */
13575 # ifndef OPENSSL_NO_TLS1_2
13576     /* Test with both TLSv1.3 and 1.2 versions */
13577     ADD_ALL_TESTS(test_key_exchange, 21);
13578 #  if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH)
13579     ADD_ALL_TESTS(test_negotiated_group,
13580                   4 * (OSSL_NELEM(ecdhe_kexch_groups)
13581                        + OSSL_NELEM(ffdhe_kexch_groups)));
13582 #  endif
13583 # else
13584     /* Test with only TLSv1.3 versions */
13585     ADD_ALL_TESTS(test_key_exchange, 18);
13586 # endif
13587     ADD_ALL_TESTS(test_custom_exts, 6);
13588     ADD_TEST(test_stateless);
13589     ADD_TEST(test_pha_key_update);
13590 #else
13591     ADD_ALL_TESTS(test_custom_exts, 3);
13592 #endif
13593     ADD_ALL_TESTS(test_export_key_mat, 6);
13594 #ifndef OSSL_NO_USABLE_TLS1_3
13595     ADD_ALL_TESTS(test_export_key_mat_early, 3);
13596     ADD_TEST(test_key_update);
13597     ADD_ALL_TESTS(test_key_update_peer_in_write, 2);
13598     ADD_ALL_TESTS(test_key_update_peer_in_read, 2);
13599     ADD_ALL_TESTS(test_key_update_local_in_write, 2);
13600     ADD_ALL_TESTS(test_key_update_local_in_read, 2);
13601 #endif
13602     ADD_ALL_TESTS(test_ssl_clear, 8);
13603     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
13604 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
13605     ADD_ALL_TESTS(test_srp, 6);
13606 #endif
13607 #if !defined(OPENSSL_NO_COMP_ALG)
13608     /* Add compression case */
13609     ADD_ALL_TESTS(test_info_callback, 8);
13610 #else
13611     ADD_ALL_TESTS(test_info_callback, 6);
13612 #endif
13613     ADD_ALL_TESTS(test_ssl_pending, 2);
13614     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
13615     ADD_ALL_TESTS(test_ticket_callbacks, 20);
13616     ADD_ALL_TESTS(test_shutdown, 7);
13617     ADD_TEST(test_async_shutdown);
13618     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
13619     ADD_ALL_TESTS(test_cert_cb, 6);
13620     ADD_ALL_TESTS(test_client_cert_cb, 2);
13621     ADD_ALL_TESTS(test_ca_names, 3);
13622 #ifndef OPENSSL_NO_TLS1_2
13623     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
13624 #endif
13625     ADD_ALL_TESTS(test_servername, 10);
13626     ADD_TEST(test_unknown_sigalgs_groups);
13627 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)) || !defined(OPENSSL_NO_ML_KEM)
13628     ADD_TEST(test_configuration_of_groups);
13629 #endif
13630 #if !defined(OPENSSL_NO_EC) \
13631     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
13632     ADD_ALL_TESTS(test_sigalgs_available, 6);
13633 #endif
13634 #ifndef OPENSSL_NO_TLS1_3
13635     ADD_ALL_TESTS(test_pluggable_group, 2);
13636     ADD_ALL_TESTS(test_pluggable_signature, 6);
13637 #endif
13638 #ifndef OPENSSL_NO_TLS1_2
13639     ADD_TEST(test_ssl_dup);
13640     ADD_TEST(test_session_secret_cb);
13641 # ifndef OPENSSL_NO_DH
13642     ADD_ALL_TESTS(test_set_tmp_dh, 11);
13643     ADD_ALL_TESTS(test_dh_auto, 7);
13644 # endif
13645 #endif
13646 #ifndef OSSL_NO_USABLE_TLS1_3
13647     ADD_TEST(test_sni_tls13);
13648     ADD_ALL_TESTS(test_ticket_lifetime, 2);
13649 #endif
13650     ADD_TEST(test_inherit_verify_param);
13651     ADD_TEST(test_set_alpn);
13652     ADD_TEST(test_set_verify_cert_store_ssl_ctx);
13653     ADD_TEST(test_set_verify_cert_store_ssl);
13654     ADD_ALL_TESTS(test_session_timeout, 1);
13655 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
13656     ADD_ALL_TESTS(test_session_cache_overflow, 4);
13657 #endif
13658     ADD_TEST(test_load_dhfile);
13659 #ifndef OSSL_NO_USABLE_TLS1_3
13660     ADD_TEST(test_read_ahead_key_change);
13661     ADD_ALL_TESTS(test_tls13_record_padding, 6);
13662 #endif
13663 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
13664     ADD_ALL_TESTS(test_serverinfo_custom, 4);
13665 #endif
13666 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
13667     ADD_ALL_TESTS(test_pipelining, 7);
13668 #endif
13669     ADD_ALL_TESTS(test_version, 6);
13670     ADD_TEST(test_rstate_string);
13671     ADD_ALL_TESTS(test_handshake_retry, 16);
13672     ADD_TEST(test_data_retry);
13673     ADD_ALL_TESTS(test_multi_resume, 5);
13674     ADD_ALL_TESTS(test_select_next_proto, OSSL_NELEM(next_proto_tests));
13675 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
13676     ADD_ALL_TESTS(test_npn, 5);
13677 #endif
13678     ADD_ALL_TESTS(test_alpn, 4);
13679 #if !defined(OSSL_NO_USABLE_TLS1_3)
13680     ADD_ALL_TESTS(test_quic_tls, 6);
13681     ADD_TEST(test_quic_tls_early_data);
13682 #endif
13683     ADD_ALL_TESTS(test_no_renegotiation, 2);
13684 #if defined(DO_SSL_TRACE_TEST)
13685     if (datadir != NULL)
13686         ADD_TEST(test_ssl_trace);
13687 #endif
13688     return 1;
13689 
13690  err:
13691     OPENSSL_free(cert);
13692     OPENSSL_free(privkey);
13693     OPENSSL_free(cert2);
13694     OPENSSL_free(privkey2);
13695     return 0;
13696 }
13697 
cleanup_tests(void)13698 void cleanup_tests(void)
13699 {
13700 # if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH)
13701     EVP_PKEY_free(tmp_dh_params);
13702 #endif
13703     OPENSSL_free(cert);
13704     OPENSSL_free(privkey);
13705     OPENSSL_free(cert2);
13706     OPENSSL_free(privkey2);
13707     OPENSSL_free(cert1024);
13708     OPENSSL_free(privkey1024);
13709     OPENSSL_free(cert3072);
13710     OPENSSL_free(privkey3072);
13711     OPENSSL_free(cert4096);
13712     OPENSSL_free(privkey4096);
13713     OPENSSL_free(cert8192);
13714     OPENSSL_free(privkey8192);
13715     bio_s_mempacket_test_free();
13716     bio_s_always_retry_free();
13717     bio_s_maybe_retry_free();
13718     OSSL_PROVIDER_unload(defctxnull);
13719     OSSL_LIB_CTX_free(libctx);
13720 }
13721