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