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