xref: /openssl/test/sslapitest.c (revision 357e2734)
1 /*
2  * Copyright 2016-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 /*
11  * We need access to the deprecated low level HMAC APIs for legacy purposes
12  * when the deprecated calls are not hidden
13  */
14 #ifndef OPENSSL_NO_DEPRECATED_3_0
15 # define OPENSSL_SUPPRESS_DEPRECATED
16 #endif
17 
18 #include <stdio.h>
19 #include <string.h>
20 
21 #include <openssl/opensslconf.h>
22 #include <openssl/bio.h>
23 #include <openssl/crypto.h>
24 #include <openssl/ssl.h>
25 #include <openssl/ocsp.h>
26 #include <openssl/srp.h>
27 #include <openssl/txt_db.h>
28 #include <openssl/aes.h>
29 #include <openssl/rand.h>
30 #include <openssl/core_names.h>
31 #include <openssl/core_dispatch.h>
32 #include <openssl/provider.h>
33 #include <openssl/param_build.h>
34 #include <openssl/x509v3.h>
35 #include <openssl/dh.h>
36 #include <openssl/engine.h>
37 
38 #include "helpers/ssltestlib.h"
39 #include "testutil.h"
40 #include "testutil/output.h"
41 #include "internal/nelem.h"
42 #include "internal/tlsgroups.h"
43 #include "internal/ktls.h"
44 #include "../ssl/ssl_local.h"
45 #include "../ssl/record/methods/recmethod_local.h"
46 #include "filterprov.h"
47 
48 #undef OSSL_NO_USABLE_TLS1_3
49 #if defined(OPENSSL_NO_TLS1_3) \
50     || (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH))
51 /*
52  * If we don't have ec or dh then there are no built-in groups that are usable
53  * with TLSv1.3
54  */
55 # define OSSL_NO_USABLE_TLS1_3
56 #endif
57 
58 /* Defined in tls-provider.c */
59 int tls_provider_init(const OSSL_CORE_HANDLE *handle,
60                       const OSSL_DISPATCH *in,
61                       const OSSL_DISPATCH **out,
62                       void **provctx);
63 
64 static OSSL_LIB_CTX *libctx = NULL;
65 static OSSL_PROVIDER *defctxnull = NULL;
66 
67 #ifndef OSSL_NO_USABLE_TLS1_3
68 
69 static SSL_SESSION *clientpsk = NULL;
70 static SSL_SESSION *serverpsk = NULL;
71 static const char *pskid = "Identity";
72 static const char *srvid;
73 
74 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
75                           size_t *idlen, SSL_SESSION **sess);
76 static int find_session_cb(SSL *ssl, const unsigned char *identity,
77                            size_t identity_len, SSL_SESSION **sess);
78 
79 static int use_session_cb_cnt = 0;
80 static int find_session_cb_cnt = 0;
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 static int fips_ems_check = 0;
102 
103 #define LOG_BUFFER_SIZE 2048
104 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
105 static size_t server_log_buffer_index = 0;
106 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
107 static size_t client_log_buffer_index = 0;
108 static int error_writing_log = 0;
109 
110 #ifndef OPENSSL_NO_OCSP
111 static const unsigned char orespder[] = "Dummy OCSP Response";
112 static int ocsp_server_called = 0;
113 static int ocsp_client_called = 0;
114 
115 static int cdummyarg = 1;
116 static X509 *ocspcert = NULL;
117 #endif
118 
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         BIO_snprintf(hexed, sizeof(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 #ifdef OPENSSL_NO_EC
717     const unsigned char expected_ciphers[] = {0x00, 0x9d};
718 #else
719     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
720                                               0x2c};
721 #endif
722     const int expected_extensions[] = {
723                                        65281,
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, status;
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     status = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
815     if (fips_ems_check) {
816         if (status == 1) {
817             printf("When FIPS uses the EMS check a connection that doesn't use EMS should fail\n");
818             goto end;
819         }
820     } else {
821         if (!status) {
822             printf("Creating SSL connection failed\n");
823             goto end;
824         }
825         if (SSL_get_extms_support(serverssl)) {
826             printf("Server reports Extended Master Secret support\n");
827             goto end;
828         }
829         if (SSL_get_extms_support(clientssl)) {
830             printf("Client reports Extended Master Secret support\n");
831             goto end;
832         }
833     }
834     testresult = 1;
835 
836 end:
837     SSL_free(serverssl);
838     SSL_free(clientssl);
839     SSL_CTX_free(sctx);
840     SSL_CTX_free(cctx);
841 
842     return testresult;
843 }
844 
845 /*
846  * Very focused test to exercise a single case in the server-side state
847  * machine, when the ChangeCipherState message needs to actually change
848  * from one cipher to a different cipher (i.e., not changing from null
849  * encryption to real encryption).
850  */
test_ccs_change_cipher(void)851 static int test_ccs_change_cipher(void)
852 {
853     SSL_CTX *cctx = NULL, *sctx = NULL;
854     SSL *clientssl = NULL, *serverssl = NULL;
855     SSL_SESSION *sess = NULL, *sesspre, *sesspost;
856     int testresult = 0;
857     int i;
858     unsigned char buf;
859     size_t readbytes;
860 
861     /*
862      * Create a connection so we can resume and potentially (but not) use
863      * a different cipher in the second connection.
864      */
865     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
866                                        TLS_client_method(),
867                                        TLS1_VERSION, TLS1_2_VERSION,
868                                        &sctx, &cctx, cert, privkey))
869             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
870             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
871                           NULL, NULL))
872             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
873             || !TEST_true(create_ssl_connection(serverssl, clientssl,
874                                                 SSL_ERROR_NONE))
875             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
876             || !TEST_ptr(sess = SSL_get1_session(clientssl)))
877         goto end;
878 
879     shutdown_ssl_connection(serverssl, clientssl);
880     serverssl = clientssl = NULL;
881 
882     /* Resume, preferring a different cipher. Our server will force the
883      * same cipher to be used as the initial handshake. */
884     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
885                           NULL, NULL))
886             || !TEST_true(SSL_set_session(clientssl, sess))
887             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
888             || !TEST_true(create_ssl_connection(serverssl, clientssl,
889                                                 SSL_ERROR_NONE))
890             || !TEST_true(SSL_session_reused(clientssl))
891             || !TEST_true(SSL_session_reused(serverssl))
892             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
893             || !TEST_ptr_eq(sesspre, sesspost)
894             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
895                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
896         goto end;
897     shutdown_ssl_connection(serverssl, clientssl);
898     serverssl = clientssl = NULL;
899 
900     /*
901      * Now create a fresh connection and try to renegotiate a different
902      * cipher on it.
903      */
904     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
905                                       NULL, NULL))
906             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
907             || !TEST_true(create_ssl_connection(serverssl, clientssl,
908                                                 SSL_ERROR_NONE))
909             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
910             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
911             || !TEST_true(SSL_renegotiate(clientssl))
912             || !TEST_true(SSL_renegotiate_pending(clientssl)))
913         goto end;
914     /* Actually drive the renegotiation. */
915     for (i = 0; i < 3; i++) {
916         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
917             if (!TEST_ulong_eq(readbytes, 0))
918                 goto end;
919         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
920                                 SSL_ERROR_WANT_READ)) {
921             goto end;
922         }
923         if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
924             if (!TEST_ulong_eq(readbytes, 0))
925                 goto end;
926         } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
927                                 SSL_ERROR_WANT_READ)) {
928             goto end;
929         }
930     }
931     /* sesspre and sesspost should be different since the cipher changed. */
932     if (!TEST_false(SSL_renegotiate_pending(clientssl))
933             || !TEST_false(SSL_session_reused(clientssl))
934             || !TEST_false(SSL_session_reused(serverssl))
935             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
936             || !TEST_ptr_ne(sesspre, sesspost)
937             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
938                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
939         goto end;
940 
941     shutdown_ssl_connection(serverssl, clientssl);
942     serverssl = clientssl = NULL;
943 
944     testresult = 1;
945 
946 end:
947     SSL_free(serverssl);
948     SSL_free(clientssl);
949     SSL_CTX_free(sctx);
950     SSL_CTX_free(cctx);
951     SSL_SESSION_free(sess);
952 
953     return testresult;
954 }
955 #endif
956 
execute_test_large_message(const SSL_METHOD * smeth,const SSL_METHOD * cmeth,int min_version,int max_version,int read_ahead)957 static int execute_test_large_message(const SSL_METHOD *smeth,
958                                       const SSL_METHOD *cmeth,
959                                       int min_version, int max_version,
960                                       int read_ahead)
961 {
962     SSL_CTX *cctx = NULL, *sctx = NULL;
963     SSL *clientssl = NULL, *serverssl = NULL;
964     int testresult = 0;
965 
966     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
967                                        max_version, &sctx, &cctx, cert,
968                                        privkey)))
969         goto end;
970 
971 #ifdef OPENSSL_NO_DTLS1_2
972     if (smeth == DTLS_server_method()) {
973         /*
974          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
975          * level 0
976          */
977         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
978                 || !TEST_true(SSL_CTX_set_cipher_list(cctx,
979                                                     "DEFAULT:@SECLEVEL=0")))
980             goto end;
981     }
982 #endif
983 
984     if (read_ahead) {
985         /*
986          * Test that read_ahead works correctly when dealing with large
987          * records
988          */
989         SSL_CTX_set_read_ahead(cctx, 1);
990     }
991 
992     if (!ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
993         goto end;
994 
995     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
996                                       NULL, NULL))
997             || !TEST_true(create_ssl_connection(serverssl, clientssl,
998                                                 SSL_ERROR_NONE)))
999         goto end;
1000 
1001     /*
1002      * Calling SSL_clear() first is not required but this tests that SSL_clear()
1003      * doesn't leak.
1004      */
1005     if (!TEST_true(SSL_clear(serverssl)))
1006         goto end;
1007 
1008     testresult = 1;
1009  end:
1010     SSL_free(serverssl);
1011     SSL_free(clientssl);
1012     SSL_CTX_free(sctx);
1013     SSL_CTX_free(cctx);
1014 
1015     return testresult;
1016 }
1017 
1018 #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_KTLS) && \
1019     !(defined(OSSL_NO_USABLE_TLS1_3) && defined(OPENSSL_NO_TLS1_2))
1020 /* sock must be connected */
ktls_chk_platform(int sock)1021 static int ktls_chk_platform(int sock)
1022 {
1023     if (!ktls_enable(sock))
1024         return 0;
1025     return 1;
1026 }
1027 
ping_pong_query(SSL * clientssl,SSL * serverssl)1028 static int ping_pong_query(SSL *clientssl, SSL *serverssl)
1029 {
1030     static char count = 1;
1031     unsigned char cbuf[16000] = {0};
1032     unsigned char sbuf[16000];
1033     size_t err = 0;
1034     char crec_wseq_before[SEQ_NUM_SIZE];
1035     char crec_wseq_after[SEQ_NUM_SIZE];
1036     char crec_rseq_before[SEQ_NUM_SIZE];
1037     char crec_rseq_after[SEQ_NUM_SIZE];
1038     char srec_wseq_before[SEQ_NUM_SIZE];
1039     char srec_wseq_after[SEQ_NUM_SIZE];
1040     char srec_rseq_before[SEQ_NUM_SIZE];
1041     char srec_rseq_after[SEQ_NUM_SIZE];
1042     SSL_CONNECTION *clientsc, *serversc;
1043 
1044     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1045         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1046         goto end;
1047 
1048     cbuf[0] = count++;
1049     memcpy(crec_wseq_before, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1050     memcpy(srec_wseq_before, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1051     memcpy(crec_rseq_before, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1052     memcpy(srec_rseq_before, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1053 
1054     if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf)))
1055         goto end;
1056 
1057     while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) {
1058         if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) {
1059             goto end;
1060         }
1061     }
1062 
1063     if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf)))
1064         goto end;
1065 
1066     while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) {
1067         if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) {
1068             goto end;
1069         }
1070     }
1071 
1072     memcpy(crec_wseq_after, &clientsc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1073     memcpy(srec_wseq_after, &serversc->rlayer.wrl->sequence, SEQ_NUM_SIZE);
1074     memcpy(crec_rseq_after, &clientsc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1075     memcpy(srec_rseq_after, &serversc->rlayer.rrl->sequence, SEQ_NUM_SIZE);
1076 
1077     /* verify the payload */
1078     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1079         goto end;
1080 
1081     /*
1082      * If ktls is used then kernel sequences are used instead of
1083      * OpenSSL sequences
1084      */
1085     if (!BIO_get_ktls_send(clientsc->wbio)) {
1086         if (!TEST_mem_ne(crec_wseq_before, SEQ_NUM_SIZE,
1087                          crec_wseq_after, SEQ_NUM_SIZE))
1088             goto end;
1089     } else {
1090         if (!TEST_mem_eq(crec_wseq_before, SEQ_NUM_SIZE,
1091                          crec_wseq_after, SEQ_NUM_SIZE))
1092             goto end;
1093     }
1094 
1095     if (!BIO_get_ktls_send(serversc->wbio)) {
1096         if (!TEST_mem_ne(srec_wseq_before, SEQ_NUM_SIZE,
1097                          srec_wseq_after, SEQ_NUM_SIZE))
1098             goto end;
1099     } else {
1100         if (!TEST_mem_eq(srec_wseq_before, SEQ_NUM_SIZE,
1101                          srec_wseq_after, SEQ_NUM_SIZE))
1102             goto end;
1103     }
1104 
1105     if (!BIO_get_ktls_recv(clientsc->wbio)) {
1106         if (!TEST_mem_ne(crec_rseq_before, SEQ_NUM_SIZE,
1107                          crec_rseq_after, SEQ_NUM_SIZE))
1108             goto end;
1109     } else {
1110         if (!TEST_mem_eq(crec_rseq_before, SEQ_NUM_SIZE,
1111                          crec_rseq_after, SEQ_NUM_SIZE))
1112             goto end;
1113     }
1114 
1115     if (!BIO_get_ktls_recv(serversc->wbio)) {
1116         if (!TEST_mem_ne(srec_rseq_before, SEQ_NUM_SIZE,
1117                          srec_rseq_after, SEQ_NUM_SIZE))
1118             goto end;
1119     } else {
1120         if (!TEST_mem_eq(srec_rseq_before, SEQ_NUM_SIZE,
1121                          srec_rseq_after, SEQ_NUM_SIZE))
1122             goto end;
1123     }
1124 
1125     return 1;
1126 end:
1127     return 0;
1128 }
1129 
execute_test_ktls(int cis_ktls,int sis_ktls,int tls_version,const char * cipher)1130 static int execute_test_ktls(int cis_ktls, int sis_ktls,
1131                              int tls_version, const char *cipher)
1132 {
1133     SSL_CTX *cctx = NULL, *sctx = NULL;
1134     SSL *clientssl = NULL, *serverssl = NULL;
1135     int ktls_used = 0, testresult = 0;
1136     int cfd = -1, sfd = -1;
1137     int rx_supported;
1138     SSL_CONNECTION *clientsc, *serversc;
1139     unsigned char *buf = NULL;
1140     const size_t bufsz = SSL3_RT_MAX_PLAIN_LENGTH + 16;
1141     int ret;
1142     size_t offset = 0, i;
1143 
1144     if (!TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1145         goto end;
1146 
1147     /* Skip this test if the platform does not support ktls */
1148     if (!ktls_chk_platform(cfd)) {
1149         testresult = TEST_skip("Kernel does not support KTLS");
1150         goto end;
1151     }
1152 
1153     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1154         testresult = TEST_skip("CHACHA is not supported in FIPS");
1155         goto end;
1156     }
1157 
1158     /* Create a session based on SHA-256 */
1159     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1160                                        TLS_client_method(),
1161                                        tls_version, tls_version,
1162                                        &sctx, &cctx, cert, privkey)))
1163         goto end;
1164 
1165     if (tls_version == TLS1_3_VERSION) {
1166         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1167             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1168             goto end;
1169     } else {
1170         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1171             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1172             goto end;
1173     }
1174 
1175     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1176                                        &clientssl, sfd, cfd)))
1177         goto end;
1178 
1179     if (!TEST_ptr(clientsc = SSL_CONNECTION_FROM_SSL_ONLY(clientssl))
1180         || !TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1181         goto end;
1182 
1183     if (cis_ktls) {
1184         if (!TEST_true(SSL_set_options(clientssl, SSL_OP_ENABLE_KTLS)))
1185             goto end;
1186     }
1187 
1188     if (sis_ktls) {
1189         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1190             goto end;
1191     }
1192 
1193     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1194         goto end;
1195 
1196     /*
1197      * The running kernel may not support a given cipher suite
1198      * or direction, so just check that KTLS isn't used when it
1199      * isn't enabled.
1200      */
1201     if (!cis_ktls) {
1202         if (!TEST_false(BIO_get_ktls_send(clientsc->wbio)))
1203             goto end;
1204     } else {
1205         if (BIO_get_ktls_send(clientsc->wbio))
1206             ktls_used = 1;
1207     }
1208 
1209     if (!sis_ktls) {
1210         if (!TEST_false(BIO_get_ktls_send(serversc->wbio)))
1211             goto end;
1212     } else {
1213         if (BIO_get_ktls_send(serversc->wbio))
1214             ktls_used = 1;
1215     }
1216 
1217 #if defined(OPENSSL_NO_KTLS_RX)
1218     rx_supported = 0;
1219 #else
1220     rx_supported = 1;
1221 #endif
1222     if (!cis_ktls || !rx_supported) {
1223         if (!TEST_false(BIO_get_ktls_recv(clientsc->rbio)))
1224             goto end;
1225     } else {
1226         if (BIO_get_ktls_send(clientsc->rbio))
1227             ktls_used = 1;
1228     }
1229 
1230     if (!sis_ktls || !rx_supported) {
1231         if (!TEST_false(BIO_get_ktls_recv(serversc->rbio)))
1232             goto end;
1233     } else {
1234         if (BIO_get_ktls_send(serversc->rbio))
1235             ktls_used = 1;
1236     }
1237 
1238     if ((cis_ktls || sis_ktls) && !ktls_used) {
1239         testresult = TEST_skip("KTLS not supported for %s cipher %s",
1240                                tls_version == TLS1_3_VERSION ? "TLS 1.3" :
1241                                "TLS 1.2", cipher);
1242         goto end;
1243     }
1244 
1245     if (!TEST_true(ping_pong_query(clientssl, serverssl)))
1246         goto end;
1247 
1248     buf = OPENSSL_zalloc(bufsz);
1249     if (!TEST_ptr(buf))
1250         goto end;
1251 
1252     /*
1253      * Write some data that exceeds the maximum record length. KTLS may choose
1254      * to coalesce this data into a single buffer when we read it again.
1255      */
1256     while ((ret = SSL_write(clientssl, buf, bufsz)) != (int)bufsz) {
1257         if (!TEST_true(SSL_get_error(clientssl, ret) == SSL_ERROR_WANT_WRITE))
1258             goto end;
1259     }
1260 
1261     /* Now check that we can read all the data we wrote */
1262     do {
1263         ret = SSL_read(serverssl, buf + offset, bufsz - offset);
1264         if (ret <= 0) {
1265             if (!TEST_true(SSL_get_error(serverssl, ret) == SSL_ERROR_WANT_READ))
1266                 goto end;
1267         } else {
1268             offset += ret;
1269         }
1270     } while (offset < bufsz);
1271 
1272     if (!TEST_true(offset == bufsz))
1273         goto end;
1274     for (i = 0; i < bufsz; i++)
1275         if (!TEST_true(buf[i] == 0))
1276             goto end;
1277 
1278     testresult = 1;
1279 end:
1280     OPENSSL_free(buf);
1281     if (clientssl) {
1282         SSL_shutdown(clientssl);
1283         SSL_free(clientssl);
1284     }
1285     if (serverssl) {
1286         SSL_shutdown(serverssl);
1287         SSL_free(serverssl);
1288     }
1289     SSL_CTX_free(sctx);
1290     SSL_CTX_free(cctx);
1291     serverssl = clientssl = NULL;
1292     if (cfd != -1)
1293         close(cfd);
1294     if (sfd != -1)
1295         close(sfd);
1296     return testresult;
1297 }
1298 
1299 #define SENDFILE_SZ                     (16 * 4096)
1300 #define SENDFILE_CHUNK                  (4 * 4096)
1301 #define min(a,b)                        ((a) > (b) ? (b) : (a))
1302 
execute_test_ktls_sendfile(int tls_version,const char * cipher,int zerocopy)1303 static int execute_test_ktls_sendfile(int tls_version, const char *cipher,
1304                                       int zerocopy)
1305 {
1306     SSL_CTX *cctx = NULL, *sctx = NULL;
1307     SSL *clientssl = NULL, *serverssl = NULL;
1308     unsigned char *buf, *buf_dst;
1309     BIO *out = NULL, *in = NULL;
1310     int cfd = -1, sfd = -1, ffd, err;
1311     ssize_t chunk_size = 0;
1312     off_t chunk_off = 0;
1313     int testresult = 0;
1314     FILE *ffdp;
1315     SSL_CONNECTION *serversc;
1316 
1317     buf = OPENSSL_zalloc(SENDFILE_SZ);
1318     buf_dst = OPENSSL_zalloc(SENDFILE_SZ);
1319     if (!TEST_ptr(buf) || !TEST_ptr(buf_dst)
1320         || !TEST_true(create_test_sockets(&cfd, &sfd, SOCK_STREAM, NULL)))
1321         goto end;
1322 
1323     /* Skip this test if the platform does not support ktls */
1324     if (!ktls_chk_platform(sfd)) {
1325         testresult = TEST_skip("Kernel does not support KTLS");
1326         goto end;
1327     }
1328 
1329     if (is_fips && strstr(cipher, "CHACHA") != NULL) {
1330         testresult = TEST_skip("CHACHA is not supported in FIPS");
1331         goto end;
1332     }
1333 
1334     /* Create a session based on SHA-256 */
1335     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1336                                        TLS_client_method(),
1337                                        tls_version, tls_version,
1338                                        &sctx, &cctx, cert, privkey)))
1339         goto end;
1340 
1341     if (tls_version == TLS1_3_VERSION) {
1342         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, cipher))
1343             || !TEST_true(SSL_CTX_set_ciphersuites(sctx, cipher)))
1344             goto end;
1345     } else {
1346         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipher))
1347             || !TEST_true(SSL_CTX_set_cipher_list(sctx, cipher)))
1348             goto end;
1349     }
1350 
1351     if (!TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1352                                        &clientssl, sfd, cfd)))
1353         goto end;
1354 
1355     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1356         goto end;
1357 
1358     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_ENABLE_KTLS)))
1359         goto end;
1360 
1361     if (zerocopy) {
1362         if (!TEST_true(SSL_set_options(serverssl,
1363                                        SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE)))
1364             goto end;
1365     }
1366 
1367     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1368                                          SSL_ERROR_NONE)))
1369         goto end;
1370 
1371     if (!BIO_get_ktls_send(serversc->wbio)) {
1372         testresult = TEST_skip("Failed to enable KTLS for %s cipher %s",
1373                                tls_version == TLS1_3_VERSION ? "TLS 1.3" :
1374                                "TLS 1.2", cipher);
1375         goto end;
1376     }
1377 
1378     if (!TEST_int_gt(RAND_bytes_ex(libctx, buf, SENDFILE_SZ, 0), 0))
1379         goto end;
1380 
1381     out = BIO_new_file(tmpfilename, "wb");
1382     if (!TEST_ptr(out))
1383         goto end;
1384 
1385     if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ)
1386         goto end;
1387 
1388     BIO_free(out);
1389     out = NULL;
1390     in = BIO_new_file(tmpfilename, "rb");
1391     BIO_get_fp(in, &ffdp);
1392     ffd = fileno(ffdp);
1393 
1394     while (chunk_off < SENDFILE_SZ) {
1395         chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off);
1396         while ((err = SSL_sendfile(serverssl,
1397                                    ffd,
1398                                    chunk_off,
1399                                    chunk_size,
1400                                    0)) != chunk_size) {
1401             if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE)
1402                 goto end;
1403         }
1404         while ((err = SSL_read(clientssl,
1405                                buf_dst + chunk_off,
1406                                chunk_size)) != chunk_size) {
1407             if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ)
1408                 goto end;
1409         }
1410 
1411         /* verify the payload */
1412         if (!TEST_mem_eq(buf_dst + chunk_off,
1413                          chunk_size,
1414                          buf + chunk_off,
1415                          chunk_size))
1416             goto end;
1417 
1418         chunk_off += chunk_size;
1419     }
1420 
1421     testresult = 1;
1422 end:
1423     if (clientssl) {
1424         SSL_shutdown(clientssl);
1425         SSL_free(clientssl);
1426     }
1427     if (serverssl) {
1428         SSL_shutdown(serverssl);
1429         SSL_free(serverssl);
1430     }
1431     SSL_CTX_free(sctx);
1432     SSL_CTX_free(cctx);
1433     serverssl = clientssl = NULL;
1434     BIO_free(out);
1435     BIO_free(in);
1436     if (cfd != -1)
1437         close(cfd);
1438     if (sfd != -1)
1439         close(sfd);
1440     OPENSSL_free(buf);
1441     OPENSSL_free(buf_dst);
1442     return testresult;
1443 }
1444 
1445 static struct ktls_test_cipher {
1446     int tls_version;
1447     const char *cipher;
1448 } ktls_test_ciphers[] = {
1449 # if !defined(OPENSSL_NO_TLS1_2)
1450 #  ifdef OPENSSL_KTLS_AES_GCM_128
1451     { TLS1_2_VERSION, "AES128-GCM-SHA256" },
1452 #  endif
1453 #  ifdef OPENSSL_KTLS_AES_CCM_128
1454     { TLS1_2_VERSION, "AES128-CCM"},
1455 #  endif
1456 #  ifdef OPENSSL_KTLS_AES_GCM_256
1457     { TLS1_2_VERSION, "AES256-GCM-SHA384"},
1458 #  endif
1459 #  ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1460 #    ifndef OPENSSL_NO_EC
1461     { TLS1_2_VERSION, "ECDHE-RSA-CHACHA20-POLY1305"},
1462 #    endif
1463 #  endif
1464 # endif
1465 # if !defined(OSSL_NO_USABLE_TLS1_3)
1466 #  ifdef OPENSSL_KTLS_AES_GCM_128
1467     { TLS1_3_VERSION, "TLS_AES_128_GCM_SHA256" },
1468 #  endif
1469 #  ifdef OPENSSL_KTLS_AES_CCM_128
1470     { TLS1_3_VERSION, "TLS_AES_128_CCM_SHA256" },
1471 #  endif
1472 #  ifdef OPENSSL_KTLS_AES_GCM_256
1473     { TLS1_3_VERSION, "TLS_AES_256_GCM_SHA384" },
1474 #  endif
1475 #  ifdef OPENSSL_KTLS_CHACHA20_POLY1305
1476     { TLS1_3_VERSION, "TLS_CHACHA20_POLY1305_SHA256" },
1477 #  endif
1478 # endif
1479 };
1480 
1481 #define NUM_KTLS_TEST_CIPHERS OSSL_NELEM(ktls_test_ciphers)
1482 
test_ktls(int test)1483 static int test_ktls(int test)
1484 {
1485     struct ktls_test_cipher *cipher;
1486     int cis_ktls, sis_ktls;
1487 
1488     OPENSSL_assert(test / 4 < (int)NUM_KTLS_TEST_CIPHERS);
1489     cipher = &ktls_test_ciphers[test / 4];
1490 
1491     cis_ktls = (test & 1) != 0;
1492     sis_ktls = (test & 2) != 0;
1493 
1494     return execute_test_ktls(cis_ktls, sis_ktls, cipher->tls_version,
1495                              cipher->cipher);
1496 }
1497 
test_ktls_sendfile(int test)1498 static int test_ktls_sendfile(int test)
1499 {
1500     struct ktls_test_cipher *cipher;
1501     int tst = test >> 1;
1502 
1503     OPENSSL_assert(tst < (int)NUM_KTLS_TEST_CIPHERS);
1504     cipher = &ktls_test_ciphers[tst];
1505 
1506     return execute_test_ktls_sendfile(cipher->tls_version, cipher->cipher,
1507                                       test & 1);
1508 }
1509 #endif
1510 
test_large_message_tls(void)1511 static int test_large_message_tls(void)
1512 {
1513     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1514                                       TLS1_VERSION, 0, 0);
1515 }
1516 
test_large_message_tls_read_ahead(void)1517 static int test_large_message_tls_read_ahead(void)
1518 {
1519     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1520                                       TLS1_VERSION, 0, 1);
1521 }
1522 
1523 #ifndef OPENSSL_NO_DTLS
test_large_message_dtls(void)1524 static int test_large_message_dtls(void)
1525 {
1526 # ifdef OPENSSL_NO_DTLS1_2
1527     /* Not supported in the FIPS provider */
1528     if (is_fips)
1529         return 1;
1530 # endif
1531     /*
1532      * read_ahead is not relevant to DTLS because DTLS always acts as if
1533      * read_ahead is set.
1534      */
1535     return execute_test_large_message(DTLS_server_method(),
1536                                       DTLS_client_method(),
1537                                       DTLS1_VERSION, 0, 0);
1538 }
1539 #endif
1540 
1541 /*
1542  * Test we can successfully send the maximum amount of application data. We
1543  * test each protocol version individually, each with and without EtM enabled.
1544  * TLSv1.3 doesn't use EtM so technically it is redundant to test both but it is
1545  * simpler this way. We also test all combinations with and without the
1546  * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS option which affects the size of the
1547  * underlying buffer.
1548  */
test_large_app_data(int tst)1549 static int test_large_app_data(int tst)
1550 {
1551     SSL_CTX *cctx = NULL, *sctx = NULL;
1552     SSL *clientssl = NULL, *serverssl = NULL;
1553     int testresult = 0, prot;
1554     unsigned char *msg, *buf = NULL;
1555     size_t written, readbytes;
1556     const SSL_METHOD *smeth = TLS_server_method();
1557     const SSL_METHOD *cmeth = TLS_client_method();
1558 
1559     switch (tst >> 2) {
1560     case 0:
1561 #ifndef OSSL_NO_USABLE_TLS1_3
1562         prot = TLS1_3_VERSION;
1563         break;
1564 #else
1565         return TEST_skip("TLS 1.3 not supported");
1566 #endif
1567 
1568     case 1:
1569 #ifndef OPENSSL_NO_TLS1_2
1570         prot = TLS1_2_VERSION;
1571         break;
1572 #else
1573         return TEST_skip("TLS 1.2 not supported");
1574 #endif
1575 
1576     case 2:
1577 #ifndef OPENSSL_NO_TLS1_1
1578         prot = TLS1_1_VERSION;
1579         break;
1580 #else
1581         return TEST_skip("TLS 1.1 not supported");
1582 #endif
1583 
1584     case 3:
1585 #ifndef OPENSSL_NO_TLS1
1586         prot = TLS1_VERSION;
1587         break;
1588 #else
1589         return TEST_skip("TLS 1 not supported");
1590 #endif
1591 
1592     case 4:
1593 #ifndef OPENSSL_NO_SSL3
1594         prot = SSL3_VERSION;
1595         break;
1596 #else
1597         return TEST_skip("SSL 3 not supported");
1598 #endif
1599 
1600     case 5:
1601 #ifndef OPENSSL_NO_DTLS1_2
1602         prot = DTLS1_2_VERSION;
1603         smeth = DTLS_server_method();
1604         cmeth = DTLS_client_method();
1605         break;
1606 #else
1607         return TEST_skip("DTLS 1.2 not supported");
1608 #endif
1609 
1610     case 6:
1611 #ifndef OPENSSL_NO_DTLS1
1612         if (is_fips)
1613             return TEST_skip("DTLS 1 not supported by FIPS provider");
1614         prot = DTLS1_VERSION;
1615         smeth = DTLS_server_method();
1616         cmeth = DTLS_client_method();
1617         break;
1618 #else
1619         return TEST_skip("DTLS 1 not supported");
1620 #endif
1621 
1622     default:
1623         /* Shouldn't happen */
1624         return 0;
1625     }
1626 
1627     if (is_fips && prot < TLS1_2_VERSION)
1628         return TEST_skip("TLS versions < 1.2 not supported by FIPS provider");
1629 
1630     /* Maximal sized message of zeros */
1631     msg = OPENSSL_zalloc(SSL3_RT_MAX_PLAIN_LENGTH);
1632     if (!TEST_ptr(msg))
1633         goto end;
1634 
1635     buf = OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH + 1);
1636     if (!TEST_ptr(buf))
1637         goto end;
1638     /* Set whole buffer to all bits set */
1639     memset(buf, 0xff, SSL3_RT_MAX_PLAIN_LENGTH + 1);
1640 
1641     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, prot, prot,
1642                                        &sctx, &cctx, cert, privkey)))
1643         goto end;
1644 
1645     if (prot < TLS1_2_VERSION || prot == DTLS1_VERSION) {
1646         /* Older protocol versions need SECLEVEL=0 due to SHA1 usage */
1647         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0"))
1648                 || !TEST_true(SSL_CTX_set_cipher_list(sctx,
1649                                                       "DEFAULT:@SECLEVEL=0")))
1650         goto end;
1651     }
1652 
1653     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1654                                       &clientssl, NULL, NULL)))
1655         goto end;
1656 
1657     if ((tst & 1) != 0) {
1658         /* Setting this option gives us a minimally sized underlying buffer */
1659         if (!TEST_true(SSL_set_options(serverssl,
1660                                        SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
1661                 || !TEST_true(SSL_set_options(clientssl,
1662                                               SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)))
1663             goto end;
1664     }
1665 
1666     if ((tst & 2) != 0) {
1667         /*
1668          * Setting this option means the MAC is added before encryption
1669          * giving us a larger record for the encryption process
1670          */
1671         if (!TEST_true(SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC))
1672                 || !TEST_true(SSL_set_options(clientssl,
1673                                               SSL_OP_NO_ENCRYPT_THEN_MAC)))
1674             goto end;
1675     }
1676 
1677     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
1678         goto end;
1679 
1680     if (!TEST_true(SSL_write_ex(clientssl, msg, SSL3_RT_MAX_PLAIN_LENGTH,
1681                                 &written))
1682             || !TEST_size_t_eq(written, SSL3_RT_MAX_PLAIN_LENGTH))
1683         goto end;
1684 
1685     /* We provide a buffer slightly larger than what we are actually expecting */
1686     if (!TEST_true(SSL_read_ex(serverssl, buf, SSL3_RT_MAX_PLAIN_LENGTH + 1,
1687                                &readbytes)))
1688         goto end;
1689 
1690     if (!TEST_mem_eq(msg, written, buf, readbytes))
1691         goto end;
1692 
1693     testresult = 1;
1694 end:
1695     OPENSSL_free(msg);
1696     OPENSSL_free(buf);
1697     SSL_free(serverssl);
1698     SSL_free(clientssl);
1699     SSL_CTX_free(sctx);
1700     SSL_CTX_free(cctx);
1701     return testresult;
1702 }
1703 
1704 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3) \
1705     || !defined(OPENSSL_NO_DTLS)
execute_cleanse_plaintext(const SSL_METHOD * smeth,const SSL_METHOD * cmeth,int min_version,int max_version)1706 static int execute_cleanse_plaintext(const SSL_METHOD *smeth,
1707                                      const SSL_METHOD *cmeth,
1708                                      int min_version, int max_version)
1709 {
1710     size_t i;
1711     SSL_CTX *cctx = NULL, *sctx = NULL;
1712     SSL *clientssl = NULL, *serverssl = NULL;
1713     int testresult = 0;
1714     const unsigned char *zbuf;
1715     SSL_CONNECTION *serversc;
1716     TLS_RECORD *rr;
1717 
1718     static unsigned char cbuf[16000];
1719     static unsigned char sbuf[16000];
1720 
1721     if (!TEST_true(create_ssl_ctx_pair(libctx,
1722                                        smeth, cmeth,
1723                                        min_version, max_version,
1724                                        &sctx, &cctx, cert,
1725                                        privkey)))
1726         goto end;
1727 
1728 # ifdef OPENSSL_NO_DTLS1_2
1729     if (smeth == DTLS_server_method()) {
1730         /* Not supported in the FIPS provider */
1731         if (is_fips) {
1732             testresult = 1;
1733             goto end;
1734         };
1735         /*
1736          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
1737          * level 0
1738          */
1739         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
1740                 || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1741                                                     "DEFAULT:@SECLEVEL=0")))
1742             goto end;
1743     }
1744 # endif
1745 
1746     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1747                                       NULL, NULL)))
1748         goto end;
1749 
1750     if (!TEST_true(SSL_set_options(serverssl, SSL_OP_CLEANSE_PLAINTEXT)))
1751         goto end;
1752 
1753     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1754                                          SSL_ERROR_NONE)))
1755         goto end;
1756 
1757     for (i = 0; i < sizeof(cbuf); i++) {
1758         cbuf[i] = i & 0xff;
1759     }
1760 
1761     if (!TEST_int_eq(SSL_write(clientssl, cbuf, sizeof(cbuf)), sizeof(cbuf)))
1762         goto end;
1763 
1764     if (!TEST_int_eq(SSL_peek(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1765         goto end;
1766 
1767     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
1768         goto end;
1769 
1770     /*
1771      * Since we called SSL_peek(), we know the data in the record
1772      * layer is a plaintext record. We can gather the pointer to check
1773      * for zeroization after SSL_read().
1774      */
1775     if (!TEST_ptr(serversc = SSL_CONNECTION_FROM_SSL_ONLY(serverssl)))
1776         goto end;
1777     rr = serversc->rlayer.tlsrecs;
1778 
1779     zbuf = &rr->data[rr->off];
1780     if (!TEST_int_eq(rr->length, sizeof(cbuf)))
1781         goto end;
1782 
1783     /*
1784      * After SSL_peek() the plaintext must still be stored in the
1785      * record.
1786      */
1787     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1788         goto end;
1789 
1790     memset(sbuf, 0, sizeof(sbuf));
1791     if (!TEST_int_eq(SSL_read(serverssl, &sbuf, sizeof(sbuf)), sizeof(sbuf)))
1792         goto end;
1793 
1794     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(cbuf)))
1795         goto end;
1796 
1797     /* Check if rbuf is cleansed */
1798     memset(cbuf, 0, sizeof(cbuf));
1799     if (!TEST_mem_eq(cbuf, sizeof(cbuf), zbuf, sizeof(cbuf)))
1800         goto end;
1801 
1802     testresult = 1;
1803  end:
1804     SSL_free(serverssl);
1805     SSL_free(clientssl);
1806     SSL_CTX_free(sctx);
1807     SSL_CTX_free(cctx);
1808 
1809     return testresult;
1810 }
1811 #endif /*
1812         * !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
1813         * || !defined(OPENSSL_NO_DTLS)
1814         */
1815 
test_cleanse_plaintext(void)1816 static int test_cleanse_plaintext(void)
1817 {
1818 #if !defined(OPENSSL_NO_TLS1_2)
1819     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1820                                              TLS_client_method(),
1821                                              TLS1_2_VERSION,
1822                                              TLS1_2_VERSION)))
1823         return 0;
1824 
1825 #endif
1826 
1827 #if !defined(OSSL_NO_USABLE_TLS1_3)
1828     if (!TEST_true(execute_cleanse_plaintext(TLS_server_method(),
1829                                              TLS_client_method(),
1830                                              TLS1_3_VERSION,
1831                                              TLS1_3_VERSION)))
1832         return 0;
1833 #endif
1834 
1835 #if !defined(OPENSSL_NO_DTLS)
1836 
1837     if (!TEST_true(execute_cleanse_plaintext(DTLS_server_method(),
1838                                              DTLS_client_method(),
1839                                              DTLS1_VERSION,
1840                                              0)))
1841         return 0;
1842 #endif
1843     return 1;
1844 }
1845 
1846 #ifndef OPENSSL_NO_OCSP
ocsp_server_cb(SSL * s,void * arg)1847 static int ocsp_server_cb(SSL *s, void *arg)
1848 {
1849     int *argi = (int *)arg;
1850     unsigned char *copy = NULL;
1851     STACK_OF(OCSP_RESPID) *ids = NULL;
1852     OCSP_RESPID *id = NULL;
1853 
1854     if (*argi == 2) {
1855         /* In this test we are expecting exactly 1 OCSP_RESPID */
1856         SSL_get_tlsext_status_ids(s, &ids);
1857         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
1858             return SSL_TLSEXT_ERR_ALERT_FATAL;
1859 
1860         id = sk_OCSP_RESPID_value(ids, 0);
1861         if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL))
1862             return SSL_TLSEXT_ERR_ALERT_FATAL;
1863     } else if (*argi != 1) {
1864         return SSL_TLSEXT_ERR_ALERT_FATAL;
1865     }
1866 
1867     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
1868         return SSL_TLSEXT_ERR_ALERT_FATAL;
1869 
1870     if (!TEST_true(SSL_set_tlsext_status_ocsp_resp(s, copy,
1871                                                    sizeof(orespder)))) {
1872         OPENSSL_free(copy);
1873         return SSL_TLSEXT_ERR_ALERT_FATAL;
1874     }
1875     ocsp_server_called = 1;
1876     return SSL_TLSEXT_ERR_OK;
1877 }
1878 
ocsp_client_cb(SSL * s,void * arg)1879 static int ocsp_client_cb(SSL *s, void *arg)
1880 {
1881     int *argi = (int *)arg;
1882     const unsigned char *respderin;
1883     size_t len;
1884 
1885     if (*argi != 1 && *argi != 2)
1886         return 0;
1887 
1888     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
1889     if (!TEST_mem_eq(orespder, len, respderin, len))
1890         return 0;
1891 
1892     ocsp_client_called = 1;
1893     return 1;
1894 }
1895 
test_tlsext_status_type(void)1896 static int test_tlsext_status_type(void)
1897 {
1898     SSL_CTX *cctx = NULL, *sctx = NULL;
1899     SSL *clientssl = NULL, *serverssl = NULL;
1900     int testresult = 0;
1901     STACK_OF(OCSP_RESPID) *ids = NULL;
1902     OCSP_RESPID *id = NULL;
1903     BIO *certbio = NULL;
1904 
1905     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
1906                              TLS1_VERSION, 0,
1907                              &sctx, &cctx, cert, privkey))
1908         return 0;
1909 
1910     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
1911         goto end;
1912 
1913     /* First just do various checks getting and setting tlsext_status_type */
1914 
1915     clientssl = SSL_new(cctx);
1916     if (!TEST_ptr(clientssl))
1917         goto end;
1918     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
1919             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
1920                                                       TLSEXT_STATUSTYPE_ocsp))
1921             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
1922                             TLSEXT_STATUSTYPE_ocsp))
1923         goto end;
1924 
1925     SSL_free(clientssl);
1926     clientssl = NULL;
1927 
1928     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
1929      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
1930         goto end;
1931 
1932     clientssl = SSL_new(cctx);
1933     if (!TEST_ptr(clientssl))
1934         goto end;
1935     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
1936         goto end;
1937     SSL_free(clientssl);
1938     clientssl = NULL;
1939 
1940     /*
1941      * Now actually do a handshake and check OCSP information is exchanged and
1942      * the callbacks get called
1943      */
1944     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
1945     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
1946     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
1947     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
1948     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1949                                       &clientssl, NULL, NULL))
1950             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1951                                                 SSL_ERROR_NONE))
1952             || !TEST_true(ocsp_client_called)
1953             || !TEST_true(ocsp_server_called))
1954         goto end;
1955     SSL_free(serverssl);
1956     SSL_free(clientssl);
1957     serverssl = NULL;
1958     clientssl = NULL;
1959 
1960     /* Try again but this time force the server side callback to fail */
1961     ocsp_client_called = 0;
1962     ocsp_server_called = 0;
1963     cdummyarg = 0;
1964     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1965                                       &clientssl, NULL, NULL))
1966                 /* This should fail because the callback will fail */
1967             || !TEST_false(create_ssl_connection(serverssl, clientssl,
1968                                                  SSL_ERROR_NONE))
1969             || !TEST_false(ocsp_client_called)
1970             || !TEST_false(ocsp_server_called))
1971         goto end;
1972     SSL_free(serverssl);
1973     SSL_free(clientssl);
1974     serverssl = NULL;
1975     clientssl = NULL;
1976 
1977     /*
1978      * This time we'll get the client to send an OCSP_RESPID that it will
1979      * accept.
1980      */
1981     ocsp_client_called = 0;
1982     ocsp_server_called = 0;
1983     cdummyarg = 2;
1984     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1985                                       &clientssl, NULL, NULL)))
1986         goto end;
1987 
1988     /*
1989      * We'll just use any old cert for this test - it doesn't have to be an OCSP
1990      * specific one. We'll use the server cert.
1991      */
1992     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
1993             || !TEST_ptr(id = OCSP_RESPID_new())
1994             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
1995             || !TEST_ptr(ocspcert = X509_new_ex(libctx, NULL))
1996             || !TEST_ptr(PEM_read_bio_X509(certbio, &ocspcert, NULL, NULL))
1997             || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL))
1998             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
1999         goto end;
2000     id = NULL;
2001     SSL_set_tlsext_status_ids(clientssl, ids);
2002     /* Control has been transferred */
2003     ids = NULL;
2004 
2005     BIO_free(certbio);
2006     certbio = NULL;
2007 
2008     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2009                                          SSL_ERROR_NONE))
2010             || !TEST_true(ocsp_client_called)
2011             || !TEST_true(ocsp_server_called))
2012         goto end;
2013 
2014     testresult = 1;
2015 
2016  end:
2017     SSL_free(serverssl);
2018     SSL_free(clientssl);
2019     SSL_CTX_free(sctx);
2020     SSL_CTX_free(cctx);
2021     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
2022     OCSP_RESPID_free(id);
2023     BIO_free(certbio);
2024     X509_free(ocspcert);
2025     ocspcert = NULL;
2026 
2027     return testresult;
2028 }
2029 #endif
2030 
2031 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
2032 static int new_called, remove_called, get_called;
2033 
new_session_cb(SSL * ssl,SSL_SESSION * sess)2034 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
2035 {
2036     new_called++;
2037     /*
2038      * sess has been up-refed for us, but we don't actually need it so free it
2039      * immediately.
2040      */
2041     SSL_SESSION_free(sess);
2042     return 1;
2043 }
2044 
remove_session_cb(SSL_CTX * ctx,SSL_SESSION * sess)2045 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
2046 {
2047     remove_called++;
2048 }
2049 
2050 static SSL_SESSION *get_sess_val = NULL;
2051 
get_session_cb(SSL * ssl,const unsigned char * id,int len,int * copy)2052 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
2053                                    int *copy)
2054 {
2055     get_called++;
2056     *copy = 1;
2057     return get_sess_val;
2058 }
2059 
execute_test_session(int maxprot,int use_int_cache,int use_ext_cache,long s_options)2060 static int execute_test_session(int maxprot, int use_int_cache,
2061                                 int use_ext_cache, long s_options)
2062 {
2063     SSL_CTX *sctx = NULL, *cctx = NULL;
2064     SSL *serverssl1 = NULL, *clientssl1 = NULL;
2065     SSL *serverssl2 = NULL, *clientssl2 = NULL;
2066 # ifndef OPENSSL_NO_TLS1_1
2067     SSL *serverssl3 = NULL, *clientssl3 = NULL;
2068 # endif
2069     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
2070     int testresult = 0, numnewsesstick = 1;
2071 
2072     new_called = remove_called = 0;
2073 
2074     /* TLSv1.3 sends 2 NewSessionTickets */
2075     if (maxprot == TLS1_3_VERSION)
2076         numnewsesstick = 2;
2077 
2078     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2079                                        TLS_client_method(), TLS1_VERSION, 0,
2080                                        &sctx, &cctx, cert, privkey)))
2081         return 0;
2082 
2083     /*
2084      * Only allow the max protocol version so we can force a connection failure
2085      * later
2086      */
2087     SSL_CTX_set_min_proto_version(cctx, maxprot);
2088     SSL_CTX_set_max_proto_version(cctx, maxprot);
2089 
2090     /* Set up session cache */
2091     if (use_ext_cache) {
2092         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2093         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
2094     }
2095     if (use_int_cache) {
2096         /* Also covers instance where both are set */
2097         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
2098     } else {
2099         SSL_CTX_set_session_cache_mode(cctx,
2100                                        SSL_SESS_CACHE_CLIENT
2101                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2102     }
2103 
2104     if (s_options) {
2105         SSL_CTX_set_options(sctx, s_options);
2106     }
2107 
2108     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2109                                       NULL, NULL))
2110             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2111                                                 SSL_ERROR_NONE))
2112             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
2113         goto end;
2114 
2115     /* Should fail because it should already be in the cache */
2116     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
2117         goto end;
2118     if (use_ext_cache
2119             && (!TEST_int_eq(new_called, numnewsesstick)
2120 
2121                 || !TEST_int_eq(remove_called, 0)))
2122         goto end;
2123 
2124     new_called = remove_called = 0;
2125     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2126                                       &clientssl2, NULL, NULL))
2127             || !TEST_true(SSL_set_session(clientssl2, sess1))
2128             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2129                                                 SSL_ERROR_NONE))
2130             || !TEST_true(SSL_session_reused(clientssl2)))
2131         goto end;
2132 
2133     if (maxprot == TLS1_3_VERSION) {
2134         /*
2135          * In TLSv1.3 we should have created a new session even though we have
2136          * resumed. Since we attempted a resume we should also have removed the
2137          * old ticket from the cache so that we try to only use tickets once.
2138          */
2139         if (use_ext_cache
2140                 && (!TEST_int_eq(new_called, 1)
2141                     || !TEST_int_eq(remove_called, 1)))
2142             goto end;
2143     } else {
2144         /*
2145          * In TLSv1.2 we expect to have resumed so no sessions added or
2146          * removed.
2147          */
2148         if (use_ext_cache
2149                 && (!TEST_int_eq(new_called, 0)
2150                     || !TEST_int_eq(remove_called, 0)))
2151             goto end;
2152     }
2153 
2154     SSL_SESSION_free(sess1);
2155     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
2156         goto end;
2157     shutdown_ssl_connection(serverssl2, clientssl2);
2158     serverssl2 = clientssl2 = NULL;
2159 
2160     new_called = remove_called = 0;
2161     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2162                                       &clientssl2, NULL, NULL))
2163             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2164                                                 SSL_ERROR_NONE)))
2165         goto end;
2166 
2167     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
2168         goto end;
2169 
2170     if (use_ext_cache
2171             && (!TEST_int_eq(new_called, numnewsesstick)
2172                 || !TEST_int_eq(remove_called, 0)))
2173         goto end;
2174 
2175     new_called = remove_called = 0;
2176     /*
2177      * This should clear sess2 from the cache because it is a "bad" session.
2178      * See SSL_set_session() documentation.
2179      */
2180     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
2181         goto end;
2182     if (use_ext_cache
2183             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2184         goto end;
2185     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
2186         goto end;
2187 
2188     if (use_int_cache) {
2189         /* Should succeeded because it should not already be in the cache */
2190         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
2191                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
2192             goto end;
2193     }
2194 
2195     new_called = remove_called = 0;
2196     /* This shouldn't be in the cache so should fail */
2197     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
2198         goto end;
2199 
2200     if (use_ext_cache
2201             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2202         goto end;
2203 
2204 # if !defined(OPENSSL_NO_TLS1_1)
2205     new_called = remove_called = 0;
2206     /* Force a connection failure */
2207     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
2208     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
2209                                       &clientssl3, NULL, NULL))
2210             || !TEST_true(SSL_set_session(clientssl3, sess1))
2211             /* This should fail because of the mismatched protocol versions */
2212             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
2213                                                  SSL_ERROR_NONE)))
2214         goto end;
2215 
2216     /* We should have automatically removed the session from the cache */
2217     if (use_ext_cache
2218             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
2219         goto end;
2220 
2221     /* Should succeed because it should not already be in the cache */
2222     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
2223         goto end;
2224 # endif
2225 
2226     /* Now do some tests for server side caching */
2227     if (use_ext_cache) {
2228         SSL_CTX_sess_set_new_cb(cctx, NULL);
2229         SSL_CTX_sess_set_remove_cb(cctx, NULL);
2230         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2231         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
2232         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
2233         get_sess_val = NULL;
2234     }
2235 
2236     SSL_CTX_set_session_cache_mode(cctx, 0);
2237     /* Internal caching is the default on the server side */
2238     if (!use_int_cache)
2239         SSL_CTX_set_session_cache_mode(sctx,
2240                                        SSL_SESS_CACHE_SERVER
2241                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2242 
2243     SSL_free(serverssl1);
2244     SSL_free(clientssl1);
2245     serverssl1 = clientssl1 = NULL;
2246     SSL_free(serverssl2);
2247     SSL_free(clientssl2);
2248     serverssl2 = clientssl2 = NULL;
2249     SSL_SESSION_free(sess1);
2250     sess1 = NULL;
2251     SSL_SESSION_free(sess2);
2252     sess2 = NULL;
2253 
2254     SSL_CTX_set_max_proto_version(sctx, maxprot);
2255     if (maxprot == TLS1_2_VERSION)
2256         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
2257     new_called = remove_called = get_called = 0;
2258     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
2259                                       NULL, NULL))
2260             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
2261                                                 SSL_ERROR_NONE))
2262             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
2263             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
2264         goto end;
2265 
2266     if (use_int_cache) {
2267         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
2268             /*
2269              * In TLSv1.3 it should not have been added to the internal cache,
2270              * except in the case where we also have an external cache (in that
2271              * case it gets added to the cache in order to generate remove
2272              * events after timeout).
2273              */
2274             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
2275                 goto end;
2276         } else {
2277             /* Should fail because it should already be in the cache */
2278             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
2279                 goto end;
2280         }
2281     }
2282 
2283     if (use_ext_cache) {
2284         SSL_SESSION *tmp = sess2;
2285 
2286         if (!TEST_int_eq(new_called, numnewsesstick)
2287                 || !TEST_int_eq(remove_called, 0)
2288                 || !TEST_int_eq(get_called, 0))
2289             goto end;
2290         /*
2291          * Delete the session from the internal cache to force a lookup from
2292          * the external cache. We take a copy first because
2293          * SSL_CTX_remove_session() also marks the session as non-resumable.
2294          */
2295         if (use_int_cache && maxprot != TLS1_3_VERSION) {
2296             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
2297                 || !TEST_true(sess2->owner != NULL)
2298                 || !TEST_true(tmp->owner == NULL)
2299                 || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
2300                 goto end;
2301             SSL_SESSION_free(sess2);
2302         }
2303         sess2 = tmp;
2304     }
2305 
2306     new_called = remove_called = get_called = 0;
2307     get_sess_val = sess2;
2308     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
2309                                       &clientssl2, NULL, NULL))
2310             || !TEST_true(SSL_set_session(clientssl2, sess1))
2311             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
2312                                                 SSL_ERROR_NONE))
2313             || !TEST_true(SSL_session_reused(clientssl2)))
2314         goto end;
2315 
2316     if (use_ext_cache) {
2317         if (!TEST_int_eq(remove_called, 0))
2318             goto end;
2319 
2320         if (maxprot == TLS1_3_VERSION) {
2321             if (!TEST_int_eq(new_called, 1)
2322                     || !TEST_int_eq(get_called, 0))
2323                 goto end;
2324         } else {
2325             if (!TEST_int_eq(new_called, 0)
2326                     || !TEST_int_eq(get_called, 1))
2327                 goto end;
2328         }
2329     }
2330     /*
2331      * Make a small cache, force out all other sessions but
2332      * sess2, try to add sess1, which should succeed. Then
2333      * make sure it's there by checking the owners. Despite
2334      * the timeouts, sess1 should have kicked out sess2
2335      */
2336 
2337     /* Make sess1 expire before sess2 */
2338     if (!TEST_time_t_gt(SSL_SESSION_set_time_ex(sess1, 1000), 0)
2339             || !TEST_long_gt(SSL_SESSION_set_timeout(sess1, 1000), 0)
2340             || !TEST_time_t_gt(SSL_SESSION_set_time_ex(sess2, 2000), 0)
2341             || !TEST_long_gt(SSL_SESSION_set_timeout(sess2, 2000), 0))
2342         goto end;
2343 
2344     if (!TEST_long_ne(SSL_CTX_sess_set_cache_size(sctx, 1), 0))
2345         goto end;
2346 
2347     /* Don't care about results - cache should only be sess2 at end */
2348     SSL_CTX_add_session(sctx, sess1);
2349     SSL_CTX_add_session(sctx, sess2);
2350 
2351     /* Now add sess1, and make sure it remains, despite timeout */
2352     if (!TEST_true(SSL_CTX_add_session(sctx, sess1))
2353             || !TEST_ptr(sess1->owner)
2354             || !TEST_ptr_null(sess2->owner))
2355         goto end;
2356 
2357     testresult = 1;
2358 
2359  end:
2360     SSL_free(serverssl1);
2361     SSL_free(clientssl1);
2362     SSL_free(serverssl2);
2363     SSL_free(clientssl2);
2364 # ifndef OPENSSL_NO_TLS1_1
2365     SSL_free(serverssl3);
2366     SSL_free(clientssl3);
2367 # endif
2368     SSL_SESSION_free(sess1);
2369     SSL_SESSION_free(sess2);
2370     SSL_CTX_free(sctx);
2371     SSL_CTX_free(cctx);
2372 
2373     return testresult;
2374 }
2375 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
2376 
test_session_with_only_int_cache(void)2377 static int test_session_with_only_int_cache(void)
2378 {
2379 #ifndef OSSL_NO_USABLE_TLS1_3
2380     if (!execute_test_session(TLS1_3_VERSION, 1, 0, 0))
2381         return 0;
2382 #endif
2383 
2384 #ifndef OPENSSL_NO_TLS1_2
2385     return execute_test_session(TLS1_2_VERSION, 1, 0, 0);
2386 #else
2387     return 1;
2388 #endif
2389 }
2390 
test_session_with_only_ext_cache(void)2391 static int test_session_with_only_ext_cache(void)
2392 {
2393 #ifndef OSSL_NO_USABLE_TLS1_3
2394     if (!execute_test_session(TLS1_3_VERSION, 0, 1, 0))
2395         return 0;
2396 #endif
2397 
2398 #ifndef OPENSSL_NO_TLS1_2
2399     return execute_test_session(TLS1_2_VERSION, 0, 1, 0);
2400 #else
2401     return 1;
2402 #endif
2403 }
2404 
test_session_with_both_cache(void)2405 static int test_session_with_both_cache(void)
2406 {
2407 #ifndef OSSL_NO_USABLE_TLS1_3
2408     if (!execute_test_session(TLS1_3_VERSION, 1, 1, 0))
2409         return 0;
2410 #endif
2411 
2412 #ifndef OPENSSL_NO_TLS1_2
2413     return execute_test_session(TLS1_2_VERSION, 1, 1, 0);
2414 #else
2415     return 1;
2416 #endif
2417 }
2418 
test_session_wo_ca_names(void)2419 static int test_session_wo_ca_names(void)
2420 {
2421 #ifndef OSSL_NO_USABLE_TLS1_3
2422     if (!execute_test_session(TLS1_3_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES))
2423         return 0;
2424 #endif
2425 
2426 #ifndef OPENSSL_NO_TLS1_2
2427     return execute_test_session(TLS1_2_VERSION, 1, 0, SSL_OP_DISABLE_TLSEXT_CA_NAMES);
2428 #else
2429     return 1;
2430 #endif
2431 }
2432 
2433 #ifndef OSSL_NO_USABLE_TLS1_3
2434 static SSL_SESSION *sesscache[6];
2435 static int do_cache;
2436 
new_cachesession_cb(SSL * ssl,SSL_SESSION * sess)2437 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
2438 {
2439     if (do_cache) {
2440         sesscache[new_called] = sess;
2441     } else {
2442         /* We don't need the reference to the session, so free it */
2443         SSL_SESSION_free(sess);
2444     }
2445     new_called++;
2446 
2447     return 1;
2448 }
2449 
post_handshake_verify(SSL * sssl,SSL * cssl)2450 static int post_handshake_verify(SSL *sssl, SSL *cssl)
2451 {
2452     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
2453     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
2454         return 0;
2455 
2456     /* Start handshake on the server and client */
2457     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
2458             || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
2459             || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
2460             || !TEST_true(create_ssl_connection(sssl, cssl,
2461                                                 SSL_ERROR_NONE)))
2462         return 0;
2463 
2464     return 1;
2465 }
2466 
setup_ticket_test(int stateful,int idx,SSL_CTX ** sctx,SSL_CTX ** cctx)2467 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
2468                              SSL_CTX **cctx)
2469 {
2470     int sess_id_ctx = 1;
2471 
2472     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2473                                        TLS_client_method(), TLS1_VERSION, 0,
2474                                        sctx, cctx, cert, privkey))
2475             || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
2476             || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
2477                                                          (void *)&sess_id_ctx,
2478                                                          sizeof(sess_id_ctx))))
2479         return 0;
2480 
2481     if (stateful)
2482         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
2483 
2484     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT
2485                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2486     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
2487 
2488     return 1;
2489 }
2490 
check_resumption(int idx,SSL_CTX * sctx,SSL_CTX * cctx,int succ)2491 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
2492 {
2493     SSL *serverssl = NULL, *clientssl = NULL;
2494     int i;
2495 
2496     /* Test that we can resume with all the tickets we got given */
2497     for (i = 0; i < idx * 2; i++) {
2498         new_called = 0;
2499         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2500                                               &clientssl, NULL, NULL))
2501                 || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
2502             goto end;
2503 
2504         SSL_set_post_handshake_auth(clientssl, 1);
2505 
2506         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2507                                                     SSL_ERROR_NONE)))
2508             goto end;
2509 
2510         /*
2511          * Following a successful resumption we only get 1 ticket. After a
2512          * failed one we should get idx tickets.
2513          */
2514         if (succ) {
2515             if (!TEST_true(SSL_session_reused(clientssl))
2516                     || !TEST_int_eq(new_called, 1))
2517                 goto end;
2518         } else {
2519             if (!TEST_false(SSL_session_reused(clientssl))
2520                     || !TEST_int_eq(new_called, idx))
2521                 goto end;
2522         }
2523 
2524         new_called = 0;
2525         /* After a post-handshake authentication we should get 1 new ticket */
2526         if (succ
2527                 && (!post_handshake_verify(serverssl, clientssl)
2528                     || !TEST_int_eq(new_called, 1)))
2529             goto end;
2530 
2531         SSL_shutdown(clientssl);
2532         SSL_shutdown(serverssl);
2533         SSL_free(serverssl);
2534         SSL_free(clientssl);
2535         serverssl = clientssl = NULL;
2536         SSL_SESSION_free(sesscache[i]);
2537         sesscache[i] = NULL;
2538     }
2539 
2540     return 1;
2541 
2542  end:
2543     SSL_free(clientssl);
2544     SSL_free(serverssl);
2545     return 0;
2546 }
2547 
test_tickets(int stateful,int idx)2548 static int test_tickets(int stateful, int idx)
2549 {
2550     SSL_CTX *sctx = NULL, *cctx = NULL;
2551     SSL *serverssl = NULL, *clientssl = NULL;
2552     int testresult = 0;
2553     size_t j;
2554 
2555     /* idx is the test number, but also the number of tickets we want */
2556 
2557     new_called = 0;
2558     do_cache = 1;
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     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2568                                                 SSL_ERROR_NONE))
2569                /* Check we got the number of tickets we were expecting */
2570             || !TEST_int_eq(idx, new_called))
2571         goto end;
2572 
2573     SSL_shutdown(clientssl);
2574     SSL_shutdown(serverssl);
2575     SSL_free(serverssl);
2576     SSL_free(clientssl);
2577     SSL_CTX_free(sctx);
2578     SSL_CTX_free(cctx);
2579     clientssl = serverssl = NULL;
2580     sctx = cctx = NULL;
2581 
2582     /*
2583      * Now we try to resume with the tickets we previously created. The
2584      * resumption attempt is expected to fail (because we're now using a new
2585      * SSL_CTX). We should see idx number of tickets issued again.
2586      */
2587 
2588     /* Stop caching sessions - just count them */
2589     do_cache = 0;
2590 
2591     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2592         goto end;
2593 
2594     if (!check_resumption(idx, sctx, cctx, 0))
2595         goto end;
2596 
2597     /* Start again with caching sessions */
2598     new_called = 0;
2599     do_cache = 1;
2600     SSL_CTX_free(sctx);
2601     SSL_CTX_free(cctx);
2602     sctx = cctx = NULL;
2603 
2604     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
2605         goto end;
2606 
2607     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2608                                           &clientssl, NULL, NULL)))
2609         goto end;
2610 
2611     SSL_set_post_handshake_auth(clientssl, 1);
2612 
2613     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2614                                                 SSL_ERROR_NONE))
2615                /* Check we got the number of tickets we were expecting */
2616             || !TEST_int_eq(idx, new_called))
2617         goto end;
2618 
2619     /* After a post-handshake authentication we should get new tickets issued */
2620     if (!post_handshake_verify(serverssl, clientssl)
2621             || !TEST_int_eq(idx * 2, new_called))
2622         goto end;
2623 
2624     SSL_shutdown(clientssl);
2625     SSL_shutdown(serverssl);
2626     SSL_free(serverssl);
2627     SSL_free(clientssl);
2628     serverssl = clientssl = NULL;
2629 
2630     /* Stop caching sessions - just count them */
2631     do_cache = 0;
2632 
2633     /*
2634      * Check we can resume with all the tickets we created. This time around the
2635      * resumptions should all be successful.
2636      */
2637     if (!check_resumption(idx, sctx, cctx, 1))
2638         goto end;
2639 
2640     testresult = 1;
2641 
2642  end:
2643     SSL_free(serverssl);
2644     SSL_free(clientssl);
2645     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2646         SSL_SESSION_free(sesscache[j]);
2647         sesscache[j] = NULL;
2648     }
2649     SSL_CTX_free(sctx);
2650     SSL_CTX_free(cctx);
2651 
2652     return testresult;
2653 }
2654 
test_stateless_tickets(int idx)2655 static int test_stateless_tickets(int idx)
2656 {
2657     return test_tickets(0, idx);
2658 }
2659 
test_stateful_tickets(int idx)2660 static int test_stateful_tickets(int idx)
2661 {
2662     return test_tickets(1, idx);
2663 }
2664 
test_psk_tickets(void)2665 static int test_psk_tickets(void)
2666 {
2667     SSL_CTX *sctx = NULL, *cctx = NULL;
2668     SSL *serverssl = NULL, *clientssl = NULL;
2669     int testresult = 0;
2670     int sess_id_ctx = 1;
2671 
2672     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2673                                        TLS_client_method(), TLS1_VERSION, 0,
2674                                        &sctx, &cctx, NULL, NULL))
2675             || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2676                                                          (void *)&sess_id_ctx,
2677                                                          sizeof(sess_id_ctx))))
2678         goto end;
2679 
2680     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
2681                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2682     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2683     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2684     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2685     use_session_cb_cnt = 0;
2686     find_session_cb_cnt = 0;
2687     srvid = pskid;
2688     new_called = 0;
2689 
2690     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2691                                       NULL, NULL)))
2692         goto end;
2693     clientpsk = serverpsk = create_a_psk(clientssl, SHA384_DIGEST_LENGTH);
2694     if (!TEST_ptr(clientpsk))
2695         goto end;
2696     SSL_SESSION_up_ref(clientpsk);
2697 
2698     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2699                                                 SSL_ERROR_NONE))
2700             || !TEST_int_eq(1, find_session_cb_cnt)
2701             || !TEST_int_eq(1, use_session_cb_cnt)
2702                /* We should always get 1 ticket when using external PSK */
2703             || !TEST_int_eq(1, new_called))
2704         goto end;
2705 
2706     testresult = 1;
2707 
2708  end:
2709     SSL_free(serverssl);
2710     SSL_free(clientssl);
2711     SSL_CTX_free(sctx);
2712     SSL_CTX_free(cctx);
2713     SSL_SESSION_free(clientpsk);
2714     SSL_SESSION_free(serverpsk);
2715     clientpsk = serverpsk = NULL;
2716 
2717     return testresult;
2718 }
2719 
test_extra_tickets(int idx)2720 static int test_extra_tickets(int idx)
2721 {
2722     SSL_CTX *sctx = NULL, *cctx = NULL;
2723     SSL *serverssl = NULL, *clientssl = NULL;
2724     BIO *bretry = BIO_new(bio_s_always_retry());
2725     BIO *tmp = NULL;
2726     int testresult = 0;
2727     int stateful = 0;
2728     size_t nbytes;
2729     unsigned char c, buf[1];
2730 
2731     new_called = 0;
2732     do_cache = 1;
2733 
2734     if (idx >= 3) {
2735         idx -= 3;
2736         stateful = 1;
2737     }
2738 
2739     if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2740         goto end;
2741     SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2742     /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2743     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2744 
2745     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2746                                           &clientssl, NULL, NULL)))
2747         goto end;
2748 
2749     /*
2750      * Note that we have new_session_cb on both sctx and cctx, so new_called is
2751      * incremented by both client and server.
2752      */
2753     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2754                                                 SSL_ERROR_NONE))
2755                /* Check we got the number of tickets we were expecting */
2756             || !TEST_int_eq(idx * 2, new_called)
2757             || !TEST_true(SSL_new_session_ticket(serverssl))
2758             || !TEST_true(SSL_new_session_ticket(serverssl))
2759             || !TEST_int_eq(idx * 2, new_called))
2760         goto end;
2761 
2762     /* Now try a (real) write to actually send the tickets */
2763     c = '1';
2764     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2765             || !TEST_size_t_eq(1, nbytes)
2766             || !TEST_int_eq(idx * 2 + 2, new_called)
2767             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2768             || !TEST_int_eq(idx * 2 + 4, new_called)
2769             || !TEST_int_eq(sizeof(buf), nbytes)
2770             || !TEST_int_eq(c, buf[0])
2771             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2772         goto end;
2773 
2774     /* Try with only requesting one new ticket, too */
2775     c = '2';
2776     new_called = 0;
2777     if (!TEST_true(SSL_new_session_ticket(serverssl))
2778             || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2779             || !TEST_size_t_eq(sizeof(c), nbytes)
2780             || !TEST_int_eq(1, new_called)
2781             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2782             || !TEST_int_eq(2, new_called)
2783             || !TEST_size_t_eq(sizeof(buf), nbytes)
2784             || !TEST_int_eq(c, buf[0]))
2785         goto end;
2786 
2787     /* Do it again but use dummy writes to drive the ticket generation */
2788     c = '3';
2789     new_called = 0;
2790     if (!TEST_true(SSL_new_session_ticket(serverssl))
2791             || !TEST_true(SSL_new_session_ticket(serverssl))
2792             || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2793             || !TEST_size_t_eq(0, nbytes)
2794             || !TEST_int_eq(2, new_called)
2795             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2796             || !TEST_int_eq(4, new_called))
2797         goto end;
2798 
2799     /* Once more, but with SSL_do_handshake() to drive the ticket generation */
2800     c = '4';
2801     new_called = 0;
2802     if (!TEST_true(SSL_new_session_ticket(serverssl))
2803             || !TEST_true(SSL_new_session_ticket(serverssl))
2804             || !TEST_true(SSL_do_handshake(serverssl))
2805             || !TEST_int_eq(2, new_called)
2806             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2807             || !TEST_int_eq(4, new_called))
2808         goto end;
2809 
2810     /*
2811      * Use the always-retry BIO to exercise the logic that forces ticket
2812      * generation to wait until a record boundary.
2813      */
2814     c = '5';
2815     new_called = 0;
2816     tmp = SSL_get_wbio(serverssl);
2817     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2818         tmp = NULL;
2819         goto end;
2820     }
2821     SSL_set0_wbio(serverssl, bretry);
2822     bretry = NULL;
2823     if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2824             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2825             || !TEST_size_t_eq(nbytes, 0))
2826         goto end;
2827     /* Restore a BIO that will let the write succeed */
2828     SSL_set0_wbio(serverssl, tmp);
2829     tmp = NULL;
2830     /*
2831      * These calls should just queue the request and not send anything
2832      * even if we explicitly try to hit the state machine.
2833      */
2834     if (!TEST_true(SSL_new_session_ticket(serverssl))
2835             || !TEST_true(SSL_new_session_ticket(serverssl))
2836             || !TEST_int_eq(0, new_called)
2837             || !TEST_true(SSL_do_handshake(serverssl))
2838             || !TEST_int_eq(0, new_called))
2839         goto end;
2840     /* Re-do the write; still no tickets sent */
2841     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2842             || !TEST_size_t_eq(1, nbytes)
2843             || !TEST_int_eq(0, new_called)
2844             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2845             || !TEST_int_eq(0, new_called)
2846             || !TEST_int_eq(sizeof(buf), nbytes)
2847             || !TEST_int_eq(c, buf[0])
2848             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2849         goto end;
2850     /* Even trying to hit the state machine now will still not send tickets */
2851     if (!TEST_true(SSL_do_handshake(serverssl))
2852             || !TEST_int_eq(0, new_called))
2853         goto end;
2854     /* Now the *next* write should send the tickets */
2855     c = '6';
2856     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2857             || !TEST_size_t_eq(1, nbytes)
2858             || !TEST_int_eq(2, new_called)
2859             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2860             || !TEST_int_eq(4, new_called)
2861             || !TEST_int_eq(sizeof(buf), nbytes)
2862             || !TEST_int_eq(c, buf[0])
2863             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2864         goto end;
2865 
2866     SSL_shutdown(clientssl);
2867     SSL_shutdown(serverssl);
2868     testresult = 1;
2869 
2870  end:
2871     BIO_free(bretry);
2872     BIO_free(tmp);
2873     SSL_free(serverssl);
2874     SSL_free(clientssl);
2875     SSL_CTX_free(sctx);
2876     SSL_CTX_free(cctx);
2877     clientssl = serverssl = NULL;
2878     sctx = cctx = NULL;
2879     return testresult;
2880 }
2881 #endif
2882 
2883 #define USE_NULL            0
2884 #define USE_BIO_1           1
2885 #define USE_BIO_2           2
2886 #define USE_DEFAULT         3
2887 
2888 #define CONNTYPE_CONNECTION_SUCCESS  0
2889 #define CONNTYPE_CONNECTION_FAIL     1
2890 #define CONNTYPE_NO_CONNECTION       2
2891 
2892 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
2893 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
2894 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2895 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
2896 #else
2897 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
2898 #endif
2899 
2900 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
2901                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2902                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2903 
setupbio(BIO ** res,BIO * bio1,BIO * bio2,int type)2904 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2905 {
2906     switch (type) {
2907     case USE_NULL:
2908         *res = NULL;
2909         break;
2910     case USE_BIO_1:
2911         *res = bio1;
2912         break;
2913     case USE_BIO_2:
2914         *res = bio2;
2915         break;
2916     }
2917 }
2918 
2919 
2920 /*
2921  * Tests calls to SSL_set_bio() under various conditions.
2922  *
2923  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2924  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2925  * then do more tests where we create a successful connection first using our
2926  * standard connection setup functions, and then call SSL_set_bio() with
2927  * various combinations of valid BIOs or NULL. We then repeat these tests
2928  * following a failed connection. In this last case we are looking to check that
2929  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2930  */
test_ssl_set_bio(int idx)2931 static int test_ssl_set_bio(int idx)
2932 {
2933     SSL_CTX *sctx = NULL, *cctx = NULL;
2934     BIO *bio1 = NULL;
2935     BIO *bio2 = NULL;
2936     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2937     SSL *serverssl = NULL, *clientssl = NULL;
2938     int initrbio, initwbio, newrbio, newwbio, conntype;
2939     int testresult = 0;
2940 
2941     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2942         initrbio = idx % 3;
2943         idx /= 3;
2944         initwbio = idx % 3;
2945         idx /= 3;
2946         newrbio = idx % 3;
2947         idx /= 3;
2948         newwbio = idx % 3;
2949         conntype = CONNTYPE_NO_CONNECTION;
2950     } else {
2951         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2952         initrbio = initwbio = USE_DEFAULT;
2953         newrbio = idx % 2;
2954         idx /= 2;
2955         newwbio = idx % 2;
2956         idx /= 2;
2957         conntype = idx % 2;
2958     }
2959 
2960     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2961                                        TLS_client_method(), TLS1_VERSION, 0,
2962                                        &sctx, &cctx, cert, privkey)))
2963         goto end;
2964 
2965     if (conntype == CONNTYPE_CONNECTION_FAIL) {
2966         /*
2967          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2968          * because we reduced the number of tests in the definition of
2969          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2970          * mismatched protocol versions we will force a connection failure.
2971          */
2972         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2973         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2974     }
2975 
2976     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2977                                       NULL, NULL)))
2978         goto end;
2979 
2980     if (initrbio == USE_BIO_1
2981             || initwbio == USE_BIO_1
2982             || newrbio == USE_BIO_1
2983             || newwbio == USE_BIO_1) {
2984         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2985             goto end;
2986     }
2987 
2988     if (initrbio == USE_BIO_2
2989             || initwbio == USE_BIO_2
2990             || newrbio == USE_BIO_2
2991             || newwbio == USE_BIO_2) {
2992         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
2993             goto end;
2994     }
2995 
2996     if (initrbio != USE_DEFAULT) {
2997         setupbio(&irbio, bio1, bio2, initrbio);
2998         setupbio(&iwbio, bio1, bio2, initwbio);
2999         SSL_set_bio(clientssl, irbio, iwbio);
3000 
3001         /*
3002          * We want to maintain our own refs to these BIO, so do an up ref for
3003          * each BIO that will have ownership transferred in the SSL_set_bio()
3004          * call
3005          */
3006         if (irbio != NULL)
3007             BIO_up_ref(irbio);
3008         if (iwbio != NULL && iwbio != irbio)
3009             BIO_up_ref(iwbio);
3010     }
3011 
3012     if (conntype != CONNTYPE_NO_CONNECTION
3013             && !TEST_true(create_ssl_connection(serverssl, clientssl,
3014                                                 SSL_ERROR_NONE)
3015                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
3016         goto end;
3017 
3018     setupbio(&nrbio, bio1, bio2, newrbio);
3019     setupbio(&nwbio, bio1, bio2, newwbio);
3020 
3021     /*
3022      * We will (maybe) transfer ownership again so do more up refs.
3023      * SSL_set_bio() has some really complicated ownership rules where BIOs have
3024      * already been set!
3025      */
3026     if (nrbio != NULL
3027             && nrbio != irbio
3028             && (nwbio != iwbio || nrbio != nwbio))
3029         BIO_up_ref(nrbio);
3030     if (nwbio != NULL
3031             && nwbio != nrbio
3032             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
3033         BIO_up_ref(nwbio);
3034 
3035     SSL_set_bio(clientssl, nrbio, nwbio);
3036 
3037     testresult = 1;
3038 
3039  end:
3040     BIO_free(bio1);
3041     BIO_free(bio2);
3042 
3043     /*
3044      * This test is checking that the ref counting for SSL_set_bio is correct.
3045      * If we get here and we did too many frees then we will fail in the above
3046      * functions.
3047      */
3048     SSL_free(serverssl);
3049     SSL_free(clientssl);
3050     SSL_CTX_free(sctx);
3051     SSL_CTX_free(cctx);
3052     return testresult;
3053 }
3054 
3055 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
3056 
execute_test_ssl_bio(int pop_ssl,bio_change_t change_bio)3057 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
3058 {
3059     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
3060     SSL_CTX *ctx;
3061     SSL *ssl = NULL;
3062     int testresult = 0;
3063 
3064     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
3065             || !TEST_ptr(ssl = SSL_new(ctx))
3066             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
3067             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
3068         goto end;
3069 
3070     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
3071 
3072     /*
3073      * If anything goes wrong here then we could leak memory.
3074      */
3075     BIO_push(sslbio, membio1);
3076 
3077     /* Verify changing the rbio/wbio directly does not cause leaks */
3078     if (change_bio != NO_BIO_CHANGE) {
3079         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem()))) {
3080             ssl = NULL;
3081             goto end;
3082         }
3083         if (change_bio == CHANGE_RBIO)
3084             SSL_set0_rbio(ssl, membio2);
3085         else
3086             SSL_set0_wbio(ssl, membio2);
3087     }
3088     ssl = NULL;
3089 
3090     if (pop_ssl)
3091         BIO_pop(sslbio);
3092     else
3093         BIO_pop(membio1);
3094 
3095     testresult = 1;
3096  end:
3097     BIO_free(membio1);
3098     BIO_free(sslbio);
3099     SSL_free(ssl);
3100     SSL_CTX_free(ctx);
3101 
3102     return testresult;
3103 }
3104 
test_ssl_bio_pop_next_bio(void)3105 static int test_ssl_bio_pop_next_bio(void)
3106 {
3107     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
3108 }
3109 
test_ssl_bio_pop_ssl_bio(void)3110 static int test_ssl_bio_pop_ssl_bio(void)
3111 {
3112     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
3113 }
3114 
test_ssl_bio_change_rbio(void)3115 static int test_ssl_bio_change_rbio(void)
3116 {
3117     return execute_test_ssl_bio(0, CHANGE_RBIO);
3118 }
3119 
test_ssl_bio_change_wbio(void)3120 static int test_ssl_bio_change_wbio(void)
3121 {
3122     return execute_test_ssl_bio(0, CHANGE_WBIO);
3123 }
3124 
3125 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
3126 typedef struct {
3127     /* The list of sig algs */
3128     const int *list;
3129     /* The length of the list */
3130     size_t listlen;
3131     /* A sigalgs list in string format */
3132     const char *liststr;
3133     /* Whether setting the list should succeed */
3134     int valid;
3135     /* Whether creating a connection with the list should succeed */
3136     int connsuccess;
3137 } sigalgs_list;
3138 
3139 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
3140 # ifndef OPENSSL_NO_EC
3141 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
3142 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
3143 # endif
3144 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
3145 static const int invalidlist2[] = {NID_sha256, NID_undef};
3146 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
3147 static const int invalidlist4[] = {NID_sha256};
3148 static const sigalgs_list testsigalgs[] = {
3149     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
3150 # ifndef OPENSSL_NO_EC
3151     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
3152     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
3153 # endif
3154     {NULL, 0, "RSA+SHA256", 1, 1},
3155     {NULL, 0, "RSA+SHA256:?Invalid", 1, 1},
3156 # ifndef OPENSSL_NO_EC
3157     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
3158     {NULL, 0, "ECDSA+SHA512", 1, 0},
3159 # endif
3160     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
3161     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
3162     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
3163     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
3164     {NULL, 0, "RSA", 0, 0},
3165     {NULL, 0, "SHA256", 0, 0},
3166     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
3167     {NULL, 0, "Invalid", 0, 0}
3168 };
3169 
test_set_sigalgs(int idx)3170 static int test_set_sigalgs(int idx)
3171 {
3172     SSL_CTX *cctx = NULL, *sctx = NULL;
3173     SSL *clientssl = NULL, *serverssl = NULL;
3174     int testresult = 0;
3175     const sigalgs_list *curr;
3176     int testctx;
3177 
3178     /* Should never happen */
3179     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
3180         return 0;
3181 
3182     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
3183     curr = testctx ? &testsigalgs[idx]
3184                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
3185 
3186     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3187                                        TLS_client_method(), TLS1_VERSION, 0,
3188                                        &sctx, &cctx, cert, privkey)))
3189         return 0;
3190 
3191     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
3192 
3193     if (testctx) {
3194         int ret;
3195 
3196         if (curr->list != NULL)
3197             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
3198         else
3199             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
3200 
3201         if (!ret) {
3202             if (curr->valid)
3203                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
3204             else
3205                 testresult = 1;
3206             goto end;
3207         }
3208         if (!curr->valid) {
3209             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
3210             goto end;
3211         }
3212     }
3213 
3214     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3215                                       &clientssl, NULL, NULL)))
3216         goto end;
3217 
3218     if (!testctx) {
3219         int ret;
3220 
3221         if (curr->list != NULL)
3222             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
3223         else
3224             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
3225         if (!ret) {
3226             if (curr->valid)
3227                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
3228             else
3229                 testresult = 1;
3230             goto end;
3231         }
3232         if (!curr->valid)
3233             goto end;
3234     }
3235 
3236     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
3237                                            SSL_ERROR_NONE),
3238                 curr->connsuccess))
3239         goto end;
3240 
3241     testresult = 1;
3242 
3243  end:
3244     SSL_free(serverssl);
3245     SSL_free(clientssl);
3246     SSL_CTX_free(sctx);
3247     SSL_CTX_free(cctx);
3248 
3249     return testresult;
3250 }
3251 #endif
3252 
3253 #ifndef OSSL_NO_USABLE_TLS1_3
3254 static int psk_client_cb_cnt = 0;
3255 static int psk_server_cb_cnt = 0;
3256 
use_session_cb(SSL * ssl,const EVP_MD * md,const unsigned char ** id,size_t * idlen,SSL_SESSION ** sess)3257 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
3258                           size_t *idlen, SSL_SESSION **sess)
3259 {
3260     switch (++use_session_cb_cnt) {
3261     case 1:
3262         /* The first call should always have a NULL md */
3263         if (md != NULL)
3264             return 0;
3265         break;
3266 
3267     case 2:
3268         /* The second call should always have an md */
3269         if (md == NULL)
3270             return 0;
3271         break;
3272 
3273     default:
3274         /* We should only be called a maximum of twice */
3275         return 0;
3276     }
3277 
3278     if (clientpsk != NULL)
3279         SSL_SESSION_up_ref(clientpsk);
3280 
3281     *sess = clientpsk;
3282     *id = (const unsigned char *)pskid;
3283     *idlen = strlen(pskid);
3284 
3285     return 1;
3286 }
3287 
3288 #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)3289 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
3290                                   unsigned int max_id_len,
3291                                   unsigned char *psk,
3292                                   unsigned int max_psk_len)
3293 {
3294     unsigned int psklen = 0;
3295 
3296     psk_client_cb_cnt++;
3297 
3298     if (strlen(pskid) + 1 > max_id_len)
3299         return 0;
3300 
3301     /* We should only ever be called a maximum of twice per connection */
3302     if (psk_client_cb_cnt > 2)
3303         return 0;
3304 
3305     if (clientpsk == NULL)
3306         return 0;
3307 
3308     /* We'll reuse the PSK we set up for TLSv1.3 */
3309     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
3310         return 0;
3311     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
3312     strncpy(id, pskid, max_id_len);
3313 
3314     return psklen;
3315 }
3316 #endif /* OPENSSL_NO_PSK */
3317 
find_session_cb(SSL * ssl,const unsigned char * identity,size_t identity_len,SSL_SESSION ** sess)3318 static int find_session_cb(SSL *ssl, const unsigned char *identity,
3319                            size_t identity_len, SSL_SESSION **sess)
3320 {
3321     find_session_cb_cnt++;
3322 
3323     /* We should only ever be called a maximum of twice per connection */
3324     if (find_session_cb_cnt > 2)
3325         return 0;
3326 
3327     if (serverpsk == NULL)
3328         return 0;
3329 
3330     /* Identity should match that set by the client */
3331     if (strlen(srvid) != identity_len
3332             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
3333         /* No PSK found, continue but without a PSK */
3334         *sess = NULL;
3335         return 1;
3336     }
3337 
3338     SSL_SESSION_up_ref(serverpsk);
3339     *sess = serverpsk;
3340 
3341     return 1;
3342 }
3343 
3344 #ifndef OPENSSL_NO_PSK
psk_server_cb(SSL * ssl,const char * identity,unsigned char * psk,unsigned int max_psk_len)3345 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
3346                                   unsigned char *psk, unsigned int max_psk_len)
3347 {
3348     unsigned int psklen = 0;
3349 
3350     psk_server_cb_cnt++;
3351 
3352     /* We should only ever be called a maximum of twice per connection */
3353     if (find_session_cb_cnt > 2)
3354         return 0;
3355 
3356     if (serverpsk == NULL)
3357         return 0;
3358 
3359     /* Identity should match that set by the client */
3360     if (strcmp(srvid, identity) != 0) {
3361         return 0;
3362     }
3363 
3364     /* We'll reuse the PSK we set up for TLSv1.3 */
3365     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
3366         return 0;
3367     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
3368 
3369     return psklen;
3370 }
3371 #endif /* OPENSSL_NO_PSK */
3372 
3373 #define MSG1    "Hello"
3374 #define MSG2    "World."
3375 #define MSG3    "This"
3376 #define MSG4    "is"
3377 #define MSG5    "a"
3378 #define MSG6    "test"
3379 #define MSG7    "message."
3380 
3381 static int artificial_ticket_time = 0;
3382 
sub_session_time(SSL_SESSION * sess)3383 static int sub_session_time(SSL_SESSION *sess)
3384 {
3385     OSSL_TIME tick_time;
3386 
3387     tick_time = ossl_time_from_time_t(SSL_SESSION_get_time_ex(sess));
3388     tick_time = ossl_time_subtract(tick_time, ossl_seconds2time(10));
3389 
3390     return SSL_SESSION_set_time_ex(sess, ossl_time_to_time_t(tick_time)) != 0;
3391 }
3392 
ed_gen_cb(SSL * s,void * arg)3393 static int ed_gen_cb(SSL *s, void *arg)
3394 {
3395     SSL_SESSION *sess = SSL_get0_session(s);
3396 
3397     if (sess == NULL)
3398         return 0;
3399 
3400     /*
3401      * Artificially give the ticket some age. Just do it for the number of
3402      * tickets we've been told to do.
3403      */
3404     if (artificial_ticket_time == 0)
3405         return 1;
3406     artificial_ticket_time--;
3407 
3408     return sub_session_time(sess);
3409 }
3410 
3411 /*
3412  * Helper method to setup objects for early data test. Caller frees objects on
3413  * error.
3414  */
setupearly_data_test(SSL_CTX ** cctx,SSL_CTX ** sctx,SSL ** clientssl,SSL ** serverssl,SSL_SESSION ** sess,int idx,size_t mdsize)3415 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
3416                                 SSL **serverssl, SSL_SESSION **sess, int idx,
3417                                 size_t mdsize)
3418 {
3419     int artificial = (artificial_ticket_time > 0);
3420 
3421     if (*sctx == NULL
3422             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3423                                               TLS_client_method(),
3424                                               TLS1_VERSION, 0,
3425                                               sctx, cctx, cert, privkey)))
3426         return 0;
3427 
3428     if (artificial)
3429         SSL_CTX_set_session_ticket_cb(*sctx, ed_gen_cb, NULL, NULL);
3430 
3431     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
3432         return 0;
3433 
3434     if (idx == 1) {
3435         /* When idx == 1 we repeat the tests with read_ahead set */
3436         SSL_CTX_set_read_ahead(*cctx, 1);
3437         SSL_CTX_set_read_ahead(*sctx, 1);
3438     } else if (idx == 2) {
3439         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
3440         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
3441         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
3442         use_session_cb_cnt = 0;
3443         find_session_cb_cnt = 0;
3444         srvid = pskid;
3445     }
3446 
3447     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
3448                                       NULL, NULL)))
3449         return 0;
3450 
3451     /*
3452      * For one of the run throughs (doesn't matter which one), we'll try sending
3453      * some SNI data in the initial ClientHello. This will be ignored (because
3454      * there is no SNI cb set up by the server), so it should not impact
3455      * early_data.
3456      */
3457     if (idx == 1
3458             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
3459         return 0;
3460 
3461     if (idx == 2) {
3462         clientpsk = create_a_psk(*clientssl, mdsize);
3463         if (!TEST_ptr(clientpsk)
3464                    /*
3465                     * We just choose an arbitrary value for max_early_data which
3466                     * should be big enough for testing purposes.
3467                     */
3468                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
3469                                                              0x100))
3470                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3471             SSL_SESSION_free(clientpsk);
3472             clientpsk = NULL;
3473             return 0;
3474         }
3475         serverpsk = clientpsk;
3476 
3477         if (sess != NULL) {
3478             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
3479                 SSL_SESSION_free(clientpsk);
3480                 SSL_SESSION_free(serverpsk);
3481                 clientpsk = serverpsk = NULL;
3482                 return 0;
3483             }
3484             *sess = clientpsk;
3485         }
3486         return 1;
3487     }
3488 
3489     if (sess == NULL)
3490         return 1;
3491 
3492     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
3493                                          SSL_ERROR_NONE)))
3494         return 0;
3495 
3496     *sess = SSL_get1_session(*clientssl);
3497     SSL_shutdown(*clientssl);
3498     SSL_shutdown(*serverssl);
3499     SSL_free(*serverssl);
3500     SSL_free(*clientssl);
3501     *serverssl = *clientssl = NULL;
3502 
3503     /*
3504      * Artificially give the ticket some age to match the artificial age we
3505      * gave it on the server side
3506      */
3507     if (artificial
3508             && !TEST_true(sub_session_time(*sess)))
3509         return 0;
3510 
3511     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
3512                                       clientssl, NULL, NULL))
3513             || !TEST_true(SSL_set_session(*clientssl, *sess)))
3514         return 0;
3515 
3516     return 1;
3517 }
3518 
check_early_data_timeout(OSSL_TIME timer)3519 static int check_early_data_timeout(OSSL_TIME timer)
3520 {
3521     int res = 0;
3522 
3523     /*
3524      * Early data is time sensitive. We have an approx 8 second allowance
3525      * between writing the early data and reading it. If we exceed that time
3526      * then this test will fail. This can sometimes (rarely) occur in normal CI
3527      * operation. We can try and detect this and just ignore the result of this
3528      * test if it has taken too long. We assume anything over 7 seconds is too
3529      * long
3530      */
3531     timer = ossl_time_subtract(ossl_time_now(), timer);
3532     if (ossl_time_compare(timer, ossl_seconds2time(7)) >= 0)
3533         res = TEST_skip("Test took too long, ignoring result");
3534 
3535     return res;
3536 }
3537 
test_early_data_read_write(int idx)3538 static int test_early_data_read_write(int idx)
3539 {
3540     SSL_CTX *cctx = NULL, *sctx = NULL;
3541     SSL *clientssl = NULL, *serverssl = NULL;
3542     int testresult = 0;
3543     SSL_SESSION *sess = NULL;
3544     unsigned char buf[20], data[1024];
3545     size_t readbytes, written, eoedlen, rawread, rawwritten;
3546     BIO *rbio;
3547     OSSL_TIME timer;
3548 
3549     /* Artificially give the next 2 tickets some age for non PSK sessions */
3550     if (idx != 2)
3551         artificial_ticket_time = 2;
3552     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3553                                         &serverssl, &sess, idx,
3554                                         SHA384_DIGEST_LENGTH))) {
3555         artificial_ticket_time = 0;
3556         goto end;
3557     }
3558     artificial_ticket_time = 0;
3559 
3560     /* Write and read some early data */
3561     timer = ossl_time_now();
3562     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3563                                         &written))
3564             || !TEST_size_t_eq(written, strlen(MSG1)))
3565         goto end;
3566 
3567     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3568                                          &readbytes),
3569                      SSL_READ_EARLY_DATA_SUCCESS)) {
3570         testresult = check_early_data_timeout(timer);
3571         goto end;
3572     }
3573 
3574     if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
3575             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3576                             SSL_EARLY_DATA_ACCEPTED))
3577         goto end;
3578 
3579     /*
3580      * Server should be able to write data, and client should be able to
3581      * read it.
3582      */
3583     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
3584                                         &written))
3585             || !TEST_size_t_eq(written, strlen(MSG2))
3586             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3587             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3588         goto end;
3589 
3590     /* Even after reading normal data, client should be able write early data */
3591     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
3592                                         &written))
3593             || !TEST_size_t_eq(written, strlen(MSG3)))
3594         goto end;
3595 
3596     /* Server should still be able read early data after writing data */
3597     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3598                                          &readbytes),
3599                      SSL_READ_EARLY_DATA_SUCCESS)
3600             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
3601         goto end;
3602 
3603     /* Write more data from server and read it from client */
3604     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
3605                                         &written))
3606             || !TEST_size_t_eq(written, strlen(MSG4))
3607             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3608             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
3609         goto end;
3610 
3611     /*
3612      * If client writes normal data it should mean writing early data is no
3613      * longer possible.
3614      */
3615     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3616             || !TEST_size_t_eq(written, strlen(MSG5))
3617             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3618                             SSL_EARLY_DATA_ACCEPTED))
3619         goto end;
3620 
3621     /*
3622      * At this point the client has written EndOfEarlyData, ClientFinished and
3623      * normal (fully protected) data. We are going to cause a delay between the
3624      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
3625      * in the read BIO, and then just put back the EndOfEarlyData message.
3626      */
3627     rbio = SSL_get_rbio(serverssl);
3628     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
3629             || !TEST_size_t_lt(rawread, sizeof(data))
3630             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
3631         goto end;
3632 
3633     /* Record length is in the 4th and 5th bytes of the record header */
3634     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
3635     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
3636             || !TEST_size_t_eq(rawwritten, eoedlen))
3637         goto end;
3638 
3639     /* Server should be told that there is no more early data */
3640     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3641                                          &readbytes),
3642                      SSL_READ_EARLY_DATA_FINISH)
3643             || !TEST_size_t_eq(readbytes, 0))
3644         goto end;
3645 
3646     /*
3647      * Server has not finished init yet, so should still be able to write early
3648      * data.
3649      */
3650     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
3651                                         &written))
3652             || !TEST_size_t_eq(written, strlen(MSG6)))
3653         goto end;
3654 
3655     /* Push the ClientFinished and the normal data back into the server rbio */
3656     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
3657                                 &rawwritten))
3658             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
3659         goto end;
3660 
3661     /* Server should be able to read normal data */
3662     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3663             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3664         goto end;
3665 
3666     /* Client and server should not be able to write/read early data now */
3667     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3668                                          &written)))
3669         goto end;
3670     ERR_clear_error();
3671     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3672                                          &readbytes),
3673                      SSL_READ_EARLY_DATA_ERROR))
3674         goto end;
3675     ERR_clear_error();
3676 
3677     /* Client should be able to read the data sent by the server */
3678     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3679             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
3680         goto end;
3681 
3682     /*
3683      * Make sure we process the two NewSessionTickets. These arrive
3684      * post-handshake. We attempt reads which we do not expect to return any
3685      * data.
3686      */
3687     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3688             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3689                            &readbytes)))
3690         goto end;
3691 
3692     /* Server should be able to write normal data */
3693     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3694             || !TEST_size_t_eq(written, strlen(MSG7))
3695             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3696             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3697         goto end;
3698 
3699     SSL_SESSION_free(sess);
3700     sess = SSL_get1_session(clientssl);
3701     use_session_cb_cnt = 0;
3702     find_session_cb_cnt = 0;
3703 
3704     SSL_shutdown(clientssl);
3705     SSL_shutdown(serverssl);
3706     SSL_free(serverssl);
3707     SSL_free(clientssl);
3708     serverssl = clientssl = NULL;
3709     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3710                                       &clientssl, NULL, NULL))
3711             || !TEST_true(SSL_set_session(clientssl, sess)))
3712         goto end;
3713 
3714     /* Write and read some early data */
3715     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3716                                         &written))
3717             || !TEST_size_t_eq(written, strlen(MSG1))
3718             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3719                                                 &readbytes),
3720                             SSL_READ_EARLY_DATA_SUCCESS)
3721             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3722         goto end;
3723 
3724     if (!TEST_int_gt(SSL_connect(clientssl), 0)
3725             || !TEST_int_gt(SSL_accept(serverssl), 0))
3726         goto end;
3727 
3728     /* Client and server should not be able to write/read early data now */
3729     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3730                                          &written)))
3731         goto end;
3732     ERR_clear_error();
3733     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3734                                          &readbytes),
3735                      SSL_READ_EARLY_DATA_ERROR))
3736         goto end;
3737     ERR_clear_error();
3738 
3739     /* Client and server should be able to write/read normal data */
3740     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3741             || !TEST_size_t_eq(written, strlen(MSG5))
3742             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3743             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3744         goto end;
3745 
3746     testresult = 1;
3747 
3748  end:
3749     SSL_SESSION_free(sess);
3750     SSL_SESSION_free(clientpsk);
3751     SSL_SESSION_free(serverpsk);
3752     clientpsk = serverpsk = NULL;
3753     SSL_free(serverssl);
3754     SSL_free(clientssl);
3755     SSL_CTX_free(sctx);
3756     SSL_CTX_free(cctx);
3757     return testresult;
3758 }
3759 
3760 static int allow_ed_cb_called = 0;
3761 
allow_early_data_cb(SSL * s,void * arg)3762 static int allow_early_data_cb(SSL *s, void *arg)
3763 {
3764     int *usecb = (int *)arg;
3765 
3766     allow_ed_cb_called++;
3767 
3768     if (*usecb == 1)
3769         return 0;
3770 
3771     return 1;
3772 }
3773 
3774 /*
3775  * idx == 0: Standard early_data setup
3776  * idx == 1: early_data setup using read_ahead
3777  * usecb == 0: Don't use a custom early data callback
3778  * usecb == 1: Use a custom early data callback and reject the early data
3779  * usecb == 2: Use a custom early data callback and accept the early data
3780  * confopt == 0: Configure anti-replay directly
3781  * confopt == 1: Configure anti-replay using SSL_CONF
3782  */
test_early_data_replay_int(int idx,int usecb,int confopt)3783 static int test_early_data_replay_int(int idx, int usecb, int confopt)
3784 {
3785     SSL_CTX *cctx = NULL, *sctx = NULL;
3786     SSL *clientssl = NULL, *serverssl = NULL;
3787     int testresult = 0;
3788     SSL_SESSION *sess = NULL;
3789     size_t readbytes, written;
3790     unsigned char buf[20];
3791     OSSL_TIME timer;
3792 
3793     allow_ed_cb_called = 0;
3794 
3795     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3796                                        TLS_client_method(), TLS1_VERSION, 0,
3797                                        &sctx, &cctx, cert, privkey)))
3798         return 0;
3799 
3800     if (usecb > 0) {
3801         if (confopt == 0) {
3802             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3803         } else {
3804             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3805 
3806             if (!TEST_ptr(confctx))
3807                 goto end;
3808             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
3809                                             | SSL_CONF_FLAG_SERVER);
3810             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3811             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3812                              2)) {
3813                 SSL_CONF_CTX_free(confctx);
3814                 goto end;
3815             }
3816             SSL_CONF_CTX_free(confctx);
3817         }
3818         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3819     }
3820 
3821     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3822                                         &serverssl, &sess, idx,
3823                                         SHA384_DIGEST_LENGTH)))
3824         goto end;
3825 
3826     /*
3827      * The server is configured to accept early data. Create a connection to
3828      * "use up" the ticket
3829      */
3830     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3831             || !TEST_true(SSL_session_reused(clientssl)))
3832         goto end;
3833 
3834     SSL_shutdown(clientssl);
3835     SSL_shutdown(serverssl);
3836     SSL_free(serverssl);
3837     SSL_free(clientssl);
3838     serverssl = clientssl = NULL;
3839 
3840     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3841                                       &clientssl, NULL, NULL))
3842             || !TEST_true(SSL_set_session(clientssl, sess)))
3843         goto end;
3844 
3845     /* Write and read some early data */
3846     timer = ossl_time_now();
3847     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3848                                         &written))
3849             || !TEST_size_t_eq(written, strlen(MSG1)))
3850         goto end;
3851 
3852     if (usecb <= 1) {
3853         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3854                                              &readbytes),
3855                          SSL_READ_EARLY_DATA_FINISH)
3856                    /*
3857                     * The ticket was reused, so the we should have rejected the
3858                     * early data
3859                     */
3860                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3861                                 SSL_EARLY_DATA_REJECTED))
3862             goto end;
3863     } else {
3864         /* In this case the callback decides to accept the early data */
3865         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3866                                              &readbytes),
3867                          SSL_READ_EARLY_DATA_SUCCESS)) {
3868             testresult = check_early_data_timeout(timer);
3869             goto end;
3870         }
3871         if (!TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3872                    /*
3873                     * Server will have sent its flight so client can now send
3874                     * end of early data and complete its half of the handshake
3875                     */
3876                 || !TEST_int_gt(SSL_connect(clientssl), 0)
3877                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3878                                              &readbytes),
3879                                 SSL_READ_EARLY_DATA_FINISH)
3880                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3881                                 SSL_EARLY_DATA_ACCEPTED))
3882             goto end;
3883     }
3884 
3885     /* Complete the connection */
3886     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3887             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3888             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3889         goto end;
3890 
3891     testresult = 1;
3892 
3893  end:
3894     SSL_SESSION_free(sess);
3895     SSL_SESSION_free(clientpsk);
3896     SSL_SESSION_free(serverpsk);
3897     clientpsk = serverpsk = NULL;
3898     SSL_free(serverssl);
3899     SSL_free(clientssl);
3900     SSL_CTX_free(sctx);
3901     SSL_CTX_free(cctx);
3902     return testresult;
3903 }
3904 
test_early_data_replay(int idx)3905 static int test_early_data_replay(int idx)
3906 {
3907     int ret = 1, usecb, confopt;
3908 
3909     for (usecb = 0; usecb < 3; usecb++) {
3910         for (confopt = 0; confopt < 2; confopt++)
3911             ret &= test_early_data_replay_int(idx, usecb, confopt);
3912     }
3913 
3914     return ret;
3915 }
3916 
3917 static const char *ciphersuites[] = {
3918     "TLS_AES_128_CCM_8_SHA256",
3919     "TLS_AES_128_GCM_SHA256",
3920     "TLS_AES_256_GCM_SHA384",
3921     "TLS_AES_128_CCM_SHA256",
3922 #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
3923     "TLS_CHACHA20_POLY1305_SHA256",
3924 #else
3925     NULL,
3926 #endif
3927 #if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
3928     "TLS_SHA256_SHA256",
3929     "TLS_SHA384_SHA384"
3930 #endif
3931 };
3932 
3933 /*
3934  * Helper function to test that a server attempting to read early data can
3935  * handle a connection from a client where the early data should be skipped.
3936  * testtype: 0 == No HRR
3937  * testtype: 1 == HRR
3938  * testtype: 2 == HRR, invalid early_data sent after HRR
3939  * testtype: 3 == recv_max_early_data set to 0
3940  */
early_data_skip_helper(int testtype,int cipher,int idx)3941 static int early_data_skip_helper(int testtype, int cipher, int idx)
3942 {
3943     SSL_CTX *cctx = NULL, *sctx = NULL;
3944     SSL *clientssl = NULL, *serverssl = NULL;
3945     int testresult = 0;
3946     SSL_SESSION *sess = NULL;
3947     unsigned char buf[20];
3948     size_t readbytes, written;
3949 
3950     if (is_fips && cipher >= 4)
3951         return 1;
3952 
3953     if (ciphersuites[cipher] == NULL)
3954         return TEST_skip("Cipher not supported");
3955 
3956     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3957                                               TLS_client_method(),
3958                                               TLS1_VERSION, 0,
3959                                               &sctx, &cctx, cert, privkey)))
3960         goto end;
3961 
3962     if (cipher == 0 || cipher == 5 || cipher == 6) {
3963         SSL_CTX_set_security_level(sctx, 0);
3964         SSL_CTX_set_security_level(cctx, 0);
3965     }
3966 
3967     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, ciphersuites[cipher]))
3968             || !TEST_true(SSL_CTX_set_ciphersuites(cctx, ciphersuites[cipher])))
3969         goto end;
3970 
3971     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3972                                         &serverssl, &sess, idx,
3973                                         (cipher == 2 || cipher == 6)
3974                                             ? SHA384_DIGEST_LENGTH
3975                                             : SHA256_DIGEST_LENGTH)))
3976         goto end;
3977 
3978     if (testtype == 1 || testtype == 2) {
3979         /* Force an HRR to occur */
3980 #if defined(OPENSSL_NO_EC)
3981         if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
3982             goto end;
3983 #else
3984         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
3985             goto end;
3986 #endif
3987     } else if (idx == 2) {
3988         /*
3989          * We force early_data rejection by ensuring the PSK identity is
3990          * unrecognised
3991          */
3992         srvid = "Dummy Identity";
3993     } else {
3994         /*
3995          * Deliberately corrupt the creation time. We take 20 seconds off the
3996          * time. It could be any value as long as it is not within tolerance.
3997          * This should mean the ticket is rejected.
3998          */
3999         if (!TEST_true(SSL_SESSION_set_time_ex(sess, time(NULL) - 20)))
4000             goto end;
4001     }
4002 
4003     if (testtype == 3
4004             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
4005         goto end;
4006 
4007     /* Write some early data */
4008     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4009                                         &written))
4010             || !TEST_size_t_eq(written, strlen(MSG1)))
4011         goto end;
4012 
4013     /* Server should reject the early data */
4014     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4015                                          &readbytes),
4016                      SSL_READ_EARLY_DATA_FINISH)
4017             || !TEST_size_t_eq(readbytes, 0)
4018             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4019                             SSL_EARLY_DATA_REJECTED))
4020         goto end;
4021 
4022     switch (testtype) {
4023     case 0:
4024         /* Nothing to do */
4025         break;
4026 
4027     case 1:
4028         /*
4029          * Finish off the handshake. We perform the same writes and reads as
4030          * further down but we expect them to fail due to the incomplete
4031          * handshake.
4032          */
4033         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4034                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
4035                                &readbytes)))
4036             goto end;
4037         break;
4038 
4039     case 2:
4040         {
4041             BIO *wbio = SSL_get_wbio(clientssl);
4042             /* A record that will appear as bad early_data */
4043             const unsigned char bad_early_data[] = {
4044                 0x17, 0x03, 0x03, 0x00, 0x01, 0x00
4045             };
4046 
4047             /*
4048              * We force the client to attempt a write. This will fail because
4049              * we're still in the handshake. It will cause the second
4050              * ClientHello to be sent.
4051              */
4052             if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
4053                                          &written)))
4054                 goto end;
4055 
4056             /*
4057              * Inject some early_data after the second ClientHello. This should
4058              * cause the server to fail
4059              */
4060             if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
4061                                         sizeof(bad_early_data), &written)))
4062                 goto end;
4063         }
4064         /* fallthrough */
4065 
4066     case 3:
4067         /*
4068          * This client has sent more early_data than we are willing to skip
4069          * (case 3) or sent invalid early_data (case 2) so the connection should
4070          * abort.
4071          */
4072         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4073                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
4074             goto end;
4075 
4076         /* Connection has failed - nothing more to do */
4077         testresult = 1;
4078         goto end;
4079 
4080     default:
4081         TEST_error("Invalid test type");
4082         goto end;
4083     }
4084 
4085     ERR_clear_error();
4086     /*
4087      * Should be able to send normal data despite rejection of early data. The
4088      * early_data should be skipped.
4089      */
4090     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4091             || !TEST_size_t_eq(written, strlen(MSG2))
4092             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4093                             SSL_EARLY_DATA_REJECTED)
4094             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4095             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4096         goto end;
4097 
4098     /*
4099      * Failure to decrypt early data records should not leave spurious errors
4100      * on the error stack
4101      */
4102     if (!TEST_long_eq(ERR_peek_error(), 0))
4103         goto end;
4104 
4105     testresult = 1;
4106 
4107  end:
4108     SSL_SESSION_free(clientpsk);
4109     SSL_SESSION_free(serverpsk);
4110     clientpsk = serverpsk = NULL;
4111     SSL_SESSION_free(sess);
4112     SSL_free(serverssl);
4113     SSL_free(clientssl);
4114     SSL_CTX_free(sctx);
4115     SSL_CTX_free(cctx);
4116     return testresult;
4117 }
4118 
4119 /*
4120  * Test that a server attempting to read early data can handle a connection
4121  * from a client where the early data is not acceptable.
4122  */
test_early_data_skip(int idx)4123 static int test_early_data_skip(int idx)
4124 {
4125     return early_data_skip_helper(0,
4126                                   idx % OSSL_NELEM(ciphersuites),
4127                                   idx / OSSL_NELEM(ciphersuites));
4128 }
4129 
4130 /*
4131  * Test that a server attempting to read early data can handle a connection
4132  * from a client where an HRR occurs.
4133  */
test_early_data_skip_hrr(int idx)4134 static int test_early_data_skip_hrr(int idx)
4135 {
4136     return early_data_skip_helper(1,
4137                                   idx % OSSL_NELEM(ciphersuites),
4138                                   idx / OSSL_NELEM(ciphersuites));
4139 }
4140 
4141 /*
4142  * Test that a server attempting to read early data can handle a connection
4143  * from a client where an HRR occurs and correctly fails if early_data is sent
4144  * after the HRR
4145  */
test_early_data_skip_hrr_fail(int idx)4146 static int test_early_data_skip_hrr_fail(int idx)
4147 {
4148     return early_data_skip_helper(2,
4149                                   idx % OSSL_NELEM(ciphersuites),
4150                                   idx / OSSL_NELEM(ciphersuites));
4151 }
4152 
4153 /*
4154  * Test that a server attempting to read early data will abort if it tries to
4155  * skip over too much.
4156  */
test_early_data_skip_abort(int idx)4157 static int test_early_data_skip_abort(int idx)
4158 {
4159     return early_data_skip_helper(3,
4160                                   idx % OSSL_NELEM(ciphersuites),
4161                                   idx / OSSL_NELEM(ciphersuites));
4162 }
4163 
4164 /*
4165  * Test that a server attempting to read early data can handle a connection
4166  * from a client that doesn't send any.
4167  */
test_early_data_not_sent(int idx)4168 static int test_early_data_not_sent(int idx)
4169 {
4170     SSL_CTX *cctx = NULL, *sctx = NULL;
4171     SSL *clientssl = NULL, *serverssl = NULL;
4172     int testresult = 0;
4173     SSL_SESSION *sess = NULL;
4174     unsigned char buf[20];
4175     size_t readbytes, written;
4176 
4177     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4178                                         &serverssl, &sess, idx,
4179                                         SHA384_DIGEST_LENGTH)))
4180         goto end;
4181 
4182     /* Write some data - should block due to handshake with server */
4183     SSL_set_connect_state(clientssl);
4184     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4185         goto end;
4186 
4187     /* Server should detect that early data has not been sent */
4188     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4189                                          &readbytes),
4190                      SSL_READ_EARLY_DATA_FINISH)
4191             || !TEST_size_t_eq(readbytes, 0)
4192             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4193                             SSL_EARLY_DATA_NOT_SENT)
4194             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4195                             SSL_EARLY_DATA_NOT_SENT))
4196         goto end;
4197 
4198     /* Continue writing the message we started earlier */
4199     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4200             || !TEST_size_t_eq(written, strlen(MSG1))
4201             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4202             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4203             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
4204             || !TEST_size_t_eq(written, strlen(MSG2)))
4205         goto end;
4206 
4207     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4208             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4209         goto end;
4210 
4211     testresult = 1;
4212 
4213  end:
4214     SSL_SESSION_free(sess);
4215     SSL_SESSION_free(clientpsk);
4216     SSL_SESSION_free(serverpsk);
4217     clientpsk = serverpsk = NULL;
4218     SSL_free(serverssl);
4219     SSL_free(clientssl);
4220     SSL_CTX_free(sctx);
4221     SSL_CTX_free(cctx);
4222     return testresult;
4223 }
4224 
4225 static const char *servalpn;
4226 
alpn_select_cb(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)4227 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
4228                           unsigned char *outlen, const unsigned char *in,
4229                           unsigned int inlen, void *arg)
4230 {
4231     unsigned int protlen = 0;
4232     const unsigned char *prot;
4233 
4234     for (prot = in; prot < in + inlen; prot += protlen) {
4235         protlen = *prot++;
4236         if (in + inlen < prot + protlen)
4237             return SSL_TLSEXT_ERR_NOACK;
4238 
4239         if (protlen == strlen(servalpn)
4240                 && memcmp(prot, servalpn, protlen) == 0) {
4241             *out = prot;
4242             *outlen = protlen;
4243             return SSL_TLSEXT_ERR_OK;
4244         }
4245     }
4246 
4247     return SSL_TLSEXT_ERR_NOACK;
4248 }
4249 
4250 /* Test that a PSK can be used to send early_data */
test_early_data_psk(int idx)4251 static int test_early_data_psk(int idx)
4252 {
4253     SSL_CTX *cctx = NULL, *sctx = NULL;
4254     SSL *clientssl = NULL, *serverssl = NULL;
4255     int testresult = 0;
4256     SSL_SESSION *sess = NULL;
4257     unsigned char alpnlist[] = {
4258         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
4259         'l', 'p', 'n'
4260     };
4261 #define GOODALPNLEN     9
4262 #define BADALPNLEN      8
4263 #define GOODALPN        (alpnlist)
4264 #define BADALPN         (alpnlist + GOODALPNLEN)
4265     int err = 0;
4266     unsigned char buf[20];
4267     size_t readbytes, written;
4268     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
4269     int edstatus = SSL_EARLY_DATA_ACCEPTED;
4270 
4271     /* We always set this up with a final parameter of "2" for PSK */
4272     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4273                                         &serverssl, &sess, 2,
4274                                         SHA384_DIGEST_LENGTH)))
4275         goto end;
4276 
4277     servalpn = "goodalpn";
4278 
4279     /*
4280      * Note: There is no test for inconsistent SNI with late client detection.
4281      * This is because servers do not acknowledge SNI even if they are using
4282      * it in a resumption handshake - so it is not actually possible for a
4283      * client to detect a problem.
4284      */
4285     switch (idx) {
4286     case 0:
4287         /* Set inconsistent SNI (early client detection) */
4288         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
4289         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4290                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
4291             goto end;
4292         break;
4293 
4294     case 1:
4295         /* Set inconsistent ALPN (early client detection) */
4296         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
4297         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
4298         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
4299                                                       GOODALPNLEN))
4300                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
4301                                                    BADALPNLEN)))
4302             goto end;
4303         break;
4304 
4305     case 2:
4306         /*
4307          * Set invalid protocol version. Technically this affects PSKs without
4308          * early_data too, but we test it here because it is similar to the
4309          * SNI/ALPN consistency tests.
4310          */
4311         err = SSL_R_BAD_PSK;
4312         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
4313             goto end;
4314         break;
4315 
4316     case 3:
4317         /*
4318          * Set inconsistent SNI (server side). In this case the connection
4319          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
4320          * is associated with each handshake - not the session. Therefore it
4321          * should not matter that we used a different server name last time.
4322          */
4323         SSL_SESSION_free(serverpsk);
4324         serverpsk = SSL_SESSION_dup(clientpsk);
4325         if (!TEST_ptr(serverpsk)
4326                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
4327             goto end;
4328         /* Fall through */
4329     case 4:
4330         /* Set consistent SNI */
4331         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
4332                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
4333                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
4334                                 hostname_cb)))
4335             goto end;
4336         break;
4337 
4338     case 5:
4339         /*
4340          * Set inconsistent ALPN (server detected). In this case the connection
4341          * will succeed but reject early_data.
4342          */
4343         servalpn = "badalpn";
4344         edstatus = SSL_EARLY_DATA_REJECTED;
4345         readearlyres = SSL_READ_EARLY_DATA_FINISH;
4346         /* Fall through */
4347     case 6:
4348         /*
4349          * Set consistent ALPN.
4350          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
4351          * accepts a list of protos (each one length prefixed).
4352          * SSL_set1_alpn_selected accepts a single protocol (not length
4353          * prefixed)
4354          */
4355         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
4356                                                       GOODALPNLEN - 1))
4357                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
4358                                                    GOODALPNLEN)))
4359             goto end;
4360 
4361         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4362         break;
4363 
4364     case 7:
4365         /* Set inconsistent ALPN (late client detection) */
4366         SSL_SESSION_free(serverpsk);
4367         serverpsk = SSL_SESSION_dup(clientpsk);
4368         if (!TEST_ptr(serverpsk)
4369                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
4370                                                              BADALPN + 1,
4371                                                              BADALPNLEN - 1))
4372                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
4373                                                              GOODALPN + 1,
4374                                                              GOODALPNLEN - 1))
4375                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
4376                                                    sizeof(alpnlist))))
4377             goto end;
4378         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
4379         edstatus = SSL_EARLY_DATA_ACCEPTED;
4380         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
4381         /* SSL_connect() call should fail */
4382         connectres = -1;
4383         break;
4384 
4385     default:
4386         TEST_error("Bad test index");
4387         goto end;
4388     }
4389 
4390     SSL_set_connect_state(clientssl);
4391     if (err != 0) {
4392         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4393                                             &written))
4394                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
4395                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
4396             goto end;
4397     } else {
4398         OSSL_TIME timer = ossl_time_now();
4399 
4400         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4401                                             &written)))
4402             goto end;
4403 
4404         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4405                                              &readbytes), readearlyres)) {
4406             testresult = check_early_data_timeout(timer);
4407             goto end;
4408         }
4409 
4410         if ((readearlyres == SSL_READ_EARLY_DATA_SUCCESS
4411                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
4412                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
4413                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
4414             goto end;
4415     }
4416 
4417     testresult = 1;
4418 
4419  end:
4420     SSL_SESSION_free(sess);
4421     SSL_SESSION_free(clientpsk);
4422     SSL_SESSION_free(serverpsk);
4423     clientpsk = serverpsk = NULL;
4424     SSL_free(serverssl);
4425     SSL_free(clientssl);
4426     SSL_CTX_free(sctx);
4427     SSL_CTX_free(cctx);
4428     return testresult;
4429 }
4430 
4431 /*
4432  * Test TLSv1.3 PSK can be used to send early_data with all 7 ciphersuites
4433  * idx == 0: Test with TLS1_3_RFC_AES_128_GCM_SHA256
4434  * idx == 1: Test with TLS1_3_RFC_AES_256_GCM_SHA384
4435  * idx == 2: Test with TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4436  * idx == 3: Test with TLS1_3_RFC_AES_128_CCM_SHA256
4437  * idx == 4: Test with TLS1_3_RFC_AES_128_CCM_8_SHA256
4438  * idx == 5: Test with TLS1_3_RFC_SHA256_SHA256
4439  * idx == 6: Test with TLS1_3_RFC_SHA384_SHA384
4440  */
test_early_data_psk_with_all_ciphers(int idx)4441 static int test_early_data_psk_with_all_ciphers(int idx)
4442 {
4443     SSL_CTX *cctx = NULL, *sctx = NULL;
4444     SSL *clientssl = NULL, *serverssl = NULL;
4445     int testresult = 0;
4446     SSL_SESSION *sess = NULL;
4447     unsigned char buf[20];
4448     size_t readbytes, written;
4449     const SSL_CIPHER *cipher;
4450     OSSL_TIME timer;
4451     const char *cipher_str[] = {
4452         TLS1_3_RFC_AES_128_GCM_SHA256,
4453         TLS1_3_RFC_AES_256_GCM_SHA384,
4454 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4455         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
4456 # else
4457         NULL,
4458 # endif
4459         TLS1_3_RFC_AES_128_CCM_SHA256,
4460         TLS1_3_RFC_AES_128_CCM_8_SHA256,
4461 # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4462         TLS1_3_RFC_SHA256_SHA256,
4463         TLS1_3_RFC_SHA384_SHA384
4464 #else
4465         NULL,
4466         NULL
4467 #endif
4468     };
4469     const unsigned char *cipher_bytes[] = {
4470         TLS13_AES_128_GCM_SHA256_BYTES,
4471         TLS13_AES_256_GCM_SHA384_BYTES,
4472 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4473         TLS13_CHACHA20_POLY1305_SHA256_BYTES,
4474 # else
4475         NULL,
4476 # endif
4477         TLS13_AES_128_CCM_SHA256_BYTES,
4478         TLS13_AES_128_CCM_8_SHA256_BYTES,
4479 # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
4480         TLS13_SHA256_SHA256_BYTES,
4481         TLS13_SHA384_SHA384_BYTES
4482 #else
4483         NULL,
4484         NULL
4485 #endif
4486     };
4487 
4488     if (cipher_str[idx] == NULL)
4489         return 1;
4490     /*
4491      * Skip ChaCha20Poly1305 and TLS_SHA{256,384}_SHA{256,384} ciphers
4492      * as currently FIPS module does not support them.
4493      */
4494     if ((idx == 2 || idx == 5 || idx == 6) && is_fips == 1)
4495         return 1;
4496 
4497     /* We always set this up with a final parameter of "2" for PSK */
4498     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4499                                         &serverssl, &sess, 2,
4500                                         SHA384_DIGEST_LENGTH)))
4501         goto end;
4502 
4503     if (idx == 4 || idx == 5 || idx == 6) {
4504         /*
4505          * CCM8 ciphers are considered low security due to their short tag.
4506          * Integrity-only cipher do not provide any confidentiality.
4507          */
4508         SSL_set_security_level(clientssl, 0);
4509         SSL_set_security_level(serverssl, 0);
4510     }
4511 
4512     if (!TEST_true(SSL_set_ciphersuites(clientssl, cipher_str[idx]))
4513             || !TEST_true(SSL_set_ciphersuites(serverssl, cipher_str[idx])))
4514         goto end;
4515 
4516     /*
4517      * 'setupearly_data_test' creates only one instance of SSL_SESSION
4518      * and assigns to both client and server with incremented reference
4519      * and the same instance is updated in 'sess'.
4520      * So updating ciphersuite in 'sess' which will get reflected in
4521      * PSK handshake using psk use sess and find sess cb.
4522      */
4523     cipher = SSL_CIPHER_find(clientssl, cipher_bytes[idx]);
4524     if (!TEST_ptr(cipher) || !TEST_true(SSL_SESSION_set_cipher(sess, cipher)))
4525         goto end;
4526 
4527     SSL_set_connect_state(clientssl);
4528     timer = ossl_time_now();
4529     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4530                                         &written)))
4531         goto end;
4532 
4533     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4534                                          &readbytes),
4535                                          SSL_READ_EARLY_DATA_SUCCESS)) {
4536         testresult = check_early_data_timeout(timer);
4537         goto end;
4538     }
4539 
4540     if (!TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4541             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4542                                                       SSL_EARLY_DATA_ACCEPTED)
4543             || !TEST_int_eq(SSL_connect(clientssl), 1)
4544             || !TEST_int_eq(SSL_accept(serverssl), 1))
4545         goto end;
4546 
4547     /* Send some normal data from client to server */
4548     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4549             || !TEST_size_t_eq(written, strlen(MSG2)))
4550         goto end;
4551 
4552     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4553             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4554         goto end;
4555 
4556     testresult = 1;
4557  end:
4558     SSL_SESSION_free(sess);
4559     SSL_SESSION_free(clientpsk);
4560     SSL_SESSION_free(serverpsk);
4561     clientpsk = serverpsk = NULL;
4562     if (clientssl != NULL)
4563         SSL_shutdown(clientssl);
4564     if (serverssl != NULL)
4565         SSL_shutdown(serverssl);
4566     SSL_free(serverssl);
4567     SSL_free(clientssl);
4568     SSL_CTX_free(sctx);
4569     SSL_CTX_free(cctx);
4570     return testresult;
4571 }
4572 
4573 /*
4574  * Test that a server that doesn't try to read early data can handle a
4575  * client sending some.
4576  */
test_early_data_not_expected(int idx)4577 static int test_early_data_not_expected(int idx)
4578 {
4579     SSL_CTX *cctx = NULL, *sctx = NULL;
4580     SSL *clientssl = NULL, *serverssl = NULL;
4581     int testresult = 0;
4582     SSL_SESSION *sess = NULL;
4583     unsigned char buf[20];
4584     size_t readbytes, written;
4585 
4586     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4587                                         &serverssl, &sess, idx,
4588                                         SHA384_DIGEST_LENGTH)))
4589         goto end;
4590 
4591     /* Write some early data */
4592     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4593                                         &written)))
4594         goto end;
4595 
4596     /*
4597      * Server should skip over early data and then block waiting for client to
4598      * continue handshake
4599      */
4600     if (!TEST_int_le(SSL_accept(serverssl), 0)
4601      || !TEST_int_gt(SSL_connect(clientssl), 0)
4602      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4603                      SSL_EARLY_DATA_REJECTED)
4604      || !TEST_int_gt(SSL_accept(serverssl), 0)
4605      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4606                      SSL_EARLY_DATA_REJECTED))
4607         goto end;
4608 
4609     /* Send some normal data from client to server */
4610     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
4611             || !TEST_size_t_eq(written, strlen(MSG2)))
4612         goto end;
4613 
4614     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4615             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4616         goto end;
4617 
4618     testresult = 1;
4619 
4620  end:
4621     SSL_SESSION_free(sess);
4622     SSL_SESSION_free(clientpsk);
4623     SSL_SESSION_free(serverpsk);
4624     clientpsk = serverpsk = NULL;
4625     SSL_free(serverssl);
4626     SSL_free(clientssl);
4627     SSL_CTX_free(sctx);
4628     SSL_CTX_free(cctx);
4629     return testresult;
4630 }
4631 
4632 
4633 # ifndef OPENSSL_NO_TLS1_2
4634 /*
4635  * Test that a server attempting to read early data can handle a connection
4636  * from a TLSv1.2 client.
4637  */
test_early_data_tls1_2(int idx)4638 static int test_early_data_tls1_2(int idx)
4639 {
4640     SSL_CTX *cctx = NULL, *sctx = NULL;
4641     SSL *clientssl = NULL, *serverssl = NULL;
4642     int testresult = 0;
4643     unsigned char buf[20];
4644     size_t readbytes, written;
4645 
4646     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4647                                         &serverssl, NULL, idx,
4648                                         SHA384_DIGEST_LENGTH)))
4649         goto end;
4650 
4651     /* Write some data - should block due to handshake with server */
4652     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
4653     SSL_set_connect_state(clientssl);
4654     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
4655         goto end;
4656 
4657     /*
4658      * Server should do TLSv1.2 handshake. First it will block waiting for more
4659      * messages from client after ServerDone. Then SSL_read_early_data should
4660      * finish and detect that early data has not been sent
4661      */
4662     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4663                                          &readbytes),
4664                      SSL_READ_EARLY_DATA_ERROR))
4665         goto end;
4666 
4667     /*
4668      * Continue writing the message we started earlier. Will still block waiting
4669      * for the CCS/Finished from server
4670      */
4671     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4672             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
4673                                                 &readbytes),
4674                             SSL_READ_EARLY_DATA_FINISH)
4675             || !TEST_size_t_eq(readbytes, 0)
4676             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4677                             SSL_EARLY_DATA_NOT_SENT))
4678         goto end;
4679 
4680     /* Continue writing the message we started earlier */
4681     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
4682             || !TEST_size_t_eq(written, strlen(MSG1))
4683             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
4684                             SSL_EARLY_DATA_NOT_SENT)
4685             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
4686             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
4687             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
4688             || !TEST_size_t_eq(written, strlen(MSG2))
4689             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
4690             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
4691         goto end;
4692 
4693     testresult = 1;
4694 
4695  end:
4696     SSL_SESSION_free(clientpsk);
4697     SSL_SESSION_free(serverpsk);
4698     clientpsk = serverpsk = NULL;
4699     SSL_free(serverssl);
4700     SSL_free(clientssl);
4701     SSL_CTX_free(sctx);
4702     SSL_CTX_free(cctx);
4703 
4704     return testresult;
4705 }
4706 # endif /* OPENSSL_NO_TLS1_2 */
4707 
4708 /*
4709  * Test configuring the TLSv1.3 ciphersuites
4710  *
4711  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
4712  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
4713  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
4714  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
4715  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4716  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
4717  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
4718  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
4719  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
4720  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
4721  */
test_set_ciphersuite(int idx)4722 static int test_set_ciphersuite(int idx)
4723 {
4724     SSL_CTX *cctx = NULL, *sctx = NULL;
4725     SSL *clientssl = NULL, *serverssl = NULL;
4726     int testresult = 0;
4727 
4728     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4729                                        TLS_client_method(), TLS1_VERSION, 0,
4730                                        &sctx, &cctx, cert, privkey))
4731             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4732                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
4733         goto end;
4734 
4735     if (idx >=4 && idx <= 7) {
4736         /* SSL_CTX explicit cipher list */
4737         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
4738             goto end;
4739     }
4740 
4741     if (idx == 0 || idx == 4) {
4742         /* Default ciphersuite */
4743         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4744                                                 "TLS_AES_128_GCM_SHA256")))
4745             goto end;
4746     } else if (idx == 1 || idx == 5) {
4747         /* Non default ciphersuite */
4748         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4749                                                 "TLS_AES_128_CCM_SHA256")))
4750             goto end;
4751     }
4752 
4753     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4754                                           &clientssl, NULL, NULL)))
4755         goto end;
4756 
4757     if (idx == 8 || idx == 9) {
4758         /* SSL explicit cipher list */
4759         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
4760             goto end;
4761     }
4762 
4763     if (idx == 2 || idx == 6 || idx == 8) {
4764         /* Default ciphersuite */
4765         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4766                                             "TLS_AES_128_GCM_SHA256")))
4767             goto end;
4768     } else if (idx == 3 || idx == 7 || idx == 9) {
4769         /* Non default ciphersuite */
4770         if (!TEST_true(SSL_set_ciphersuites(clientssl,
4771                                             "TLS_AES_128_CCM_SHA256")))
4772             goto end;
4773     }
4774 
4775     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4776         goto end;
4777 
4778     testresult = 1;
4779 
4780  end:
4781     SSL_free(serverssl);
4782     SSL_free(clientssl);
4783     SSL_CTX_free(sctx);
4784     SSL_CTX_free(cctx);
4785 
4786     return testresult;
4787 }
4788 
test_ciphersuite_change(void)4789 static int test_ciphersuite_change(void)
4790 {
4791     SSL_CTX *cctx = NULL, *sctx = NULL;
4792     SSL *clientssl = NULL, *serverssl = NULL;
4793     SSL_SESSION *clntsess = NULL;
4794     int testresult = 0;
4795     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
4796 
4797     /* Create a session based on SHA-256 */
4798     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4799                                        TLS_client_method(), TLS1_VERSION, 0,
4800                                        &sctx, &cctx, cert, privkey))
4801             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4802                                                    "TLS_AES_128_GCM_SHA256:"
4803                                                    "TLS_AES_256_GCM_SHA384:"
4804                                                    "TLS_AES_128_CCM_SHA256"))
4805             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4806                                                    "TLS_AES_128_GCM_SHA256")))
4807         goto end;
4808 
4809     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4810                                       NULL, NULL))
4811             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4812                                                 SSL_ERROR_NONE)))
4813         goto end;
4814 
4815     clntsess = SSL_get1_session(clientssl);
4816     /* Save for later */
4817     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
4818     SSL_shutdown(clientssl);
4819     SSL_shutdown(serverssl);
4820     SSL_free(serverssl);
4821     SSL_free(clientssl);
4822     serverssl = clientssl = NULL;
4823 
4824     /* Check we can resume a session with a different SHA-256 ciphersuite */
4825     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4826                                             "TLS_AES_128_CCM_SHA256"))
4827             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4828                                              &clientssl, NULL, NULL))
4829             || !TEST_true(SSL_set_session(clientssl, clntsess))
4830             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4831                                                 SSL_ERROR_NONE))
4832             || !TEST_true(SSL_session_reused(clientssl)))
4833         goto end;
4834 
4835     SSL_SESSION_free(clntsess);
4836     clntsess = SSL_get1_session(clientssl);
4837     SSL_shutdown(clientssl);
4838     SSL_shutdown(serverssl);
4839     SSL_free(serverssl);
4840     SSL_free(clientssl);
4841     serverssl = clientssl = NULL;
4842 
4843     /*
4844      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
4845      * succeeds but does not resume.
4846      */
4847     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4848             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4849                                              NULL, NULL))
4850             || !TEST_true(SSL_set_session(clientssl, clntsess))
4851             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4852                                                 SSL_ERROR_SSL))
4853             || !TEST_false(SSL_session_reused(clientssl)))
4854         goto end;
4855 
4856     SSL_SESSION_free(clntsess);
4857     clntsess = NULL;
4858     SSL_shutdown(clientssl);
4859     SSL_shutdown(serverssl);
4860     SSL_free(serverssl);
4861     SSL_free(clientssl);
4862     serverssl = clientssl = NULL;
4863 
4864     /* Create a session based on SHA384 */
4865     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
4866             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4867                                           &clientssl, NULL, NULL))
4868             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4869                                                 SSL_ERROR_NONE)))
4870         goto end;
4871 
4872     clntsess = SSL_get1_session(clientssl);
4873     SSL_shutdown(clientssl);
4874     SSL_shutdown(serverssl);
4875     SSL_free(serverssl);
4876     SSL_free(clientssl);
4877     serverssl = clientssl = NULL;
4878 
4879     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4880                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
4881             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4882                                                    "TLS_AES_256_GCM_SHA384"))
4883             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4884                                              NULL, NULL))
4885             || !TEST_true(SSL_set_session(clientssl, clntsess))
4886                /*
4887                 * We use SSL_ERROR_WANT_READ below so that we can pause the
4888                 * connection after the initial ClientHello has been sent to
4889                 * enable us to make some session changes.
4890                 */
4891             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4892                                                 SSL_ERROR_WANT_READ)))
4893         goto end;
4894 
4895     /* Trick the client into thinking this session is for a different digest */
4896     clntsess->cipher = aes_128_gcm_sha256;
4897     clntsess->cipher_id = clntsess->cipher->id;
4898 
4899     /*
4900      * Continue the previously started connection. Server has selected a SHA-384
4901      * ciphersuite, but client thinks the session is for SHA-256, so it should
4902      * bail out.
4903      */
4904     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4905                                                 SSL_ERROR_SSL))
4906             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4907                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4908         goto end;
4909 
4910     testresult = 1;
4911 
4912  end:
4913     SSL_SESSION_free(clntsess);
4914     SSL_free(serverssl);
4915     SSL_free(clientssl);
4916     SSL_CTX_free(sctx);
4917     SSL_CTX_free(cctx);
4918 
4919     return testresult;
4920 }
4921 
4922 /*
4923  * Test TLSv1.3 Key exchange
4924  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4925  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4926  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4927  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4928  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4929  * Test 5 = Test NID_X448 with TLSv1.3 client and server
4930  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4931  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4932  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4933  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4934  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4935  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4936  * Test 12 = Test all ECDHE with TLSv1.2 client and server
4937  * Test 13 = Test all FFDHE with TLSv1.2 client and server
4938  */
4939 # ifndef OPENSSL_NO_EC
4940 static int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
4941                                    NID_secp521r1,
4942 #  ifndef OPENSSL_NO_ECX
4943                                    NID_X25519, NID_X448
4944 #  endif
4945                                    };
4946 # endif
4947 # ifndef OPENSSL_NO_DH
4948 static int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4949                                    NID_ffdhe6144, NID_ffdhe8192};
4950 # endif
test_key_exchange(int idx)4951 static int test_key_exchange(int idx)
4952 {
4953     SSL_CTX *sctx = NULL, *cctx = NULL;
4954     SSL *serverssl = NULL, *clientssl = NULL;
4955     int testresult = 0;
4956     int kexch_alg;
4957     int *kexch_groups = &kexch_alg;
4958     int kexch_groups_size = 1;
4959     int max_version = TLS1_3_VERSION;
4960     char *kexch_name0 = NULL;
4961 
4962     switch (idx) {
4963 # ifndef OPENSSL_NO_EC
4964 # ifndef OPENSSL_NO_TLS1_2
4965         case 12:
4966             max_version = TLS1_2_VERSION;
4967 # endif
4968             /* Fall through */
4969         case 0:
4970             kexch_groups = ecdhe_kexch_groups;
4971             kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
4972             kexch_name0 = "secp256r1";
4973             break;
4974         case 1:
4975             kexch_alg = NID_X9_62_prime256v1;
4976             kexch_name0 = "secp256r1";
4977             break;
4978         case 2:
4979             kexch_alg = NID_secp384r1;
4980             kexch_name0 = "secp384r1";
4981             break;
4982         case 3:
4983             kexch_alg = NID_secp521r1;
4984             kexch_name0 = "secp521r1";
4985             break;
4986 #  ifndef OPENSSL_NO_ECX
4987         case 4:
4988             if (is_fips)
4989                 return TEST_skip("X25519 might not be supported by fips provider.");
4990             kexch_alg = NID_X25519;
4991             kexch_name0 = "x25519";
4992             break;
4993         case 5:
4994             if (is_fips)
4995                 return TEST_skip("X448 might not be supported by fips provider.");
4996             kexch_alg = NID_X448;
4997             kexch_name0 = "x448";
4998             break;
4999 #  endif
5000 # endif
5001 # ifndef OPENSSL_NO_DH
5002 # ifndef OPENSSL_NO_TLS1_2
5003         case 13:
5004             max_version = TLS1_2_VERSION;
5005             kexch_name0 = "ffdhe2048";
5006 # endif
5007             /* Fall through */
5008         case 6:
5009             kexch_groups = ffdhe_kexch_groups;
5010             kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
5011             kexch_name0 = "ffdhe2048";
5012             break;
5013         case 7:
5014             kexch_alg = NID_ffdhe2048;
5015             kexch_name0 = "ffdhe2048";
5016             break;
5017         case 8:
5018             kexch_alg = NID_ffdhe3072;
5019             kexch_name0 = "ffdhe3072";
5020             break;
5021         case 9:
5022             kexch_alg = NID_ffdhe4096;
5023             kexch_name0 = "ffdhe4096";
5024             break;
5025         case 10:
5026             kexch_alg = NID_ffdhe6144;
5027             kexch_name0 = "ffdhe6144";
5028             break;
5029         case 11:
5030             kexch_alg = NID_ffdhe8192;
5031             kexch_name0 = "ffdhe8192";
5032             break;
5033 # endif
5034         default:
5035             /* We're skipping this test */
5036             return 1;
5037     }
5038 
5039     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5040                                        TLS_client_method(), TLS1_VERSION,
5041                                        max_version, &sctx, &cctx, cert,
5042                                        privkey)))
5043         goto end;
5044 
5045     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
5046                    TLS1_3_RFC_AES_128_GCM_SHA256)))
5047         goto end;
5048 
5049     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5050                    TLS1_3_RFC_AES_128_GCM_SHA256)))
5051         goto end;
5052 
5053     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5054                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5055                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5056             || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5057         goto end;
5058 
5059     /*
5060      * Must include an EC ciphersuite so that we send supported groups in
5061      * TLSv1.2
5062      */
5063 # ifndef OPENSSL_NO_TLS1_2
5064     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5065                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5066                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5067         goto end;
5068 # endif
5069 
5070     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5071                                              NULL, NULL)))
5072         goto end;
5073 
5074     if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
5075         || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
5076         goto end;
5077 
5078     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5079         goto end;
5080 
5081     /*
5082      * If Handshake succeeds the negotiated kexch alg should be the first one in
5083      * configured, except in the case of FFDHE groups (idx 13), which are
5084      * TLSv1.3 only so we expect no shared group to exist.
5085      */
5086     if (!TEST_int_eq(SSL_get_shared_group(serverssl, 0),
5087                      idx == 13 ? 0 : kexch_groups[0]))
5088         goto end;
5089 
5090     if (!TEST_str_eq(SSL_group_to_name(serverssl, kexch_groups[0]),
5091                      kexch_name0))
5092         goto end;
5093 
5094     /* We don't implement RFC 7919 named groups for TLS 1.2. */
5095     if (idx != 13) {
5096         if (!TEST_str_eq(SSL_get0_group_name(serverssl), kexch_name0)
5097             || !TEST_str_eq(SSL_get0_group_name(clientssl), kexch_name0))
5098             goto end;
5099         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), kexch_groups[0]))
5100             goto end;
5101         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), kexch_groups[0]))
5102             goto end;
5103     }
5104 
5105     testresult = 1;
5106  end:
5107     SSL_free(serverssl);
5108     SSL_free(clientssl);
5109     SSL_CTX_free(sctx);
5110     SSL_CTX_free(cctx);
5111     return testresult;
5112 }
5113 
5114 # if !defined(OPENSSL_NO_TLS1_2) \
5115      && !defined(OPENSSL_NO_EC)  \
5116      && !defined(OPENSSL_NO_DH)
set_ssl_groups(SSL * serverssl,SSL * clientssl,int clientmulti,int isecdhe,int idx)5117 static int set_ssl_groups(SSL *serverssl, SSL *clientssl, int clientmulti,
5118                           int isecdhe, int idx)
5119 {
5120     int kexch_alg;
5121     int *kexch_groups = &kexch_alg;
5122     int numec, numff;
5123 
5124     numec = OSSL_NELEM(ecdhe_kexch_groups);
5125     numff = OSSL_NELEM(ffdhe_kexch_groups);
5126     if (isecdhe)
5127         kexch_alg = ecdhe_kexch_groups[idx];
5128     else
5129         kexch_alg = ffdhe_kexch_groups[idx];
5130 
5131     if (clientmulti) {
5132         if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, 1)))
5133             return 0;
5134         if (isecdhe) {
5135             if (!TEST_true(SSL_set1_groups(clientssl, ecdhe_kexch_groups,
5136                                            numec)))
5137                 return 0;
5138         } else {
5139             if (!TEST_true(SSL_set1_groups(clientssl, ffdhe_kexch_groups,
5140                                            numff)))
5141                 return 0;
5142         }
5143     } else {
5144         if (!TEST_true(SSL_set1_groups(clientssl, kexch_groups, 1)))
5145             return 0;
5146         if (isecdhe) {
5147             if (!TEST_true(SSL_set1_groups(serverssl, ecdhe_kexch_groups,
5148                                            numec)))
5149                 return 0;
5150         } else {
5151             if (!TEST_true(SSL_set1_groups(serverssl, ffdhe_kexch_groups,
5152                                            numff)))
5153                 return 0;
5154         }
5155     }
5156     return 1;
5157 }
5158 
5159 /*-
5160  * Test the SSL_get_negotiated_group() API across a battery of scenarios.
5161  * Run through both the ECDHE and FFDHE group lists used in the previous
5162  * test, for both TLS 1.2 and TLS 1.3, negotiating each group in turn,
5163  * confirming the expected result; then perform a resumption handshake
5164  * while offering the same group list, and another resumption handshake
5165  * offering a different group list.  The returned value should be the
5166  * negotiated group for the initial handshake; for TLS 1.3 resumption
5167  * handshakes the returned value will be negotiated on the resumption
5168  * handshake itself, but for TLS 1.2 resumption handshakes the value will
5169  * be cached in the session from the original handshake, regardless of what
5170  * was offered in the resumption ClientHello.
5171  *
5172  * Using E for the number of EC groups and F for the number of FF groups:
5173  * E tests of ECDHE with TLS 1.3, server only has one group
5174  * F tests of FFDHE with TLS 1.3, server only has one group
5175  * E tests of ECDHE with TLS 1.2, server only has one group
5176  * F tests of FFDHE with TLS 1.2, server only has one group
5177  * E tests of ECDHE with TLS 1.3, client sends only one group
5178  * F tests of FFDHE with TLS 1.3, client sends only one group
5179  * E tests of ECDHE with TLS 1.2, client sends only one group
5180  * F tests of FFDHE with TLS 1.2, client sends only one group
5181  */
test_negotiated_group(int idx)5182 static int test_negotiated_group(int idx)
5183 {
5184     int clientmulti, istls13, isecdhe, numec, numff, numgroups;
5185     int expectednid;
5186     SSL_CTX *sctx = NULL, *cctx = NULL;
5187     SSL *serverssl = NULL, *clientssl = NULL;
5188     SSL_SESSION *origsess = NULL;
5189     int testresult = 0;
5190     int kexch_alg;
5191     int max_version = TLS1_3_VERSION;
5192 
5193     numec = OSSL_NELEM(ecdhe_kexch_groups);
5194     numff = OSSL_NELEM(ffdhe_kexch_groups);
5195     numgroups = numec + numff;
5196     clientmulti = (idx < 2 * numgroups);
5197     idx = idx % (2 * numgroups);
5198     istls13 = (idx < numgroups);
5199     idx = idx % numgroups;
5200     isecdhe = (idx < numec);
5201     if (!isecdhe)
5202         idx -= numec;
5203     /* Now 'idx' is an index into ecdhe_kexch_groups or ffdhe_kexch_groups */
5204     if (isecdhe)
5205         kexch_alg = ecdhe_kexch_groups[idx];
5206     else
5207         kexch_alg = ffdhe_kexch_groups[idx];
5208     /* We expect nothing for the unimplemented TLS 1.2 FFDHE named groups */
5209     if (!istls13 && !isecdhe)
5210         expectednid = NID_undef;
5211     else
5212         expectednid = kexch_alg;
5213 
5214     if (is_fips && (kexch_alg == NID_X25519 || kexch_alg == NID_X448))
5215         return TEST_skip("X25519 and X448 might not be available in fips provider.");
5216 
5217     if (!istls13)
5218         max_version = TLS1_2_VERSION;
5219 
5220     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5221                                        TLS_client_method(), TLS1_VERSION,
5222                                        max_version, &sctx, &cctx, cert,
5223                                        privkey)))
5224         goto end;
5225 
5226     /*
5227      * Force (EC)DHE ciphers for TLS 1.2.
5228      * Be sure to enable auto tmp DH so that FFDHE can succeed.
5229      */
5230     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
5231                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5232                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256))
5233             || !TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
5234         goto end;
5235     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
5236                    TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
5237                    TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256)))
5238         goto end;
5239 
5240     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5241                                              NULL, NULL)))
5242         goto end;
5243 
5244     if (!TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti, isecdhe,
5245                                   idx)))
5246         goto end;
5247 
5248     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
5249         goto end;
5250 
5251     /* Initial handshake; always the configured one */
5252     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5253             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5254         goto end;
5255 
5256     if (!TEST_ptr((origsess = SSL_get1_session(clientssl))))
5257         goto end;
5258 
5259     SSL_shutdown(clientssl);
5260     SSL_shutdown(serverssl);
5261     SSL_free(serverssl);
5262     SSL_free(clientssl);
5263     serverssl = clientssl = NULL;
5264 
5265     /* First resumption attempt; use the same config as initial handshake */
5266     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5267                                              NULL, NULL))
5268             || !TEST_true(SSL_set_session(clientssl, origsess))
5269             || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5270                                          isecdhe, idx)))
5271         goto end;
5272 
5273     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5274             || !TEST_true(SSL_session_reused(clientssl)))
5275         goto end;
5276 
5277     /* Still had better agree, since nothing changed... */
5278     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5279             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5280         goto end;
5281 
5282     SSL_shutdown(clientssl);
5283     SSL_shutdown(serverssl);
5284     SSL_free(serverssl);
5285     SSL_free(clientssl);
5286     serverssl = clientssl = NULL;
5287 
5288     /*-
5289      * Second resumption attempt
5290      * The party that picks one group changes it, which we effectuate by
5291      * changing 'idx' and updating what we expect.
5292      */
5293     if (idx == 0)
5294         idx = 1;
5295     else
5296         idx--;
5297     if (istls13) {
5298         if (isecdhe)
5299             expectednid = ecdhe_kexch_groups[idx];
5300         else
5301             expectednid = ffdhe_kexch_groups[idx];
5302         /* Verify that we are changing what we expect. */
5303         if (!TEST_int_ne(expectednid, kexch_alg))
5304             goto end;
5305     } else {
5306         /* TLS 1.2 only supports named groups for ECDHE. */
5307         if (isecdhe)
5308             expectednid = kexch_alg;
5309         else
5310             expectednid = 0;
5311     }
5312     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5313                                              NULL, NULL))
5314             || !TEST_true(SSL_set_session(clientssl, origsess))
5315             || !TEST_true(set_ssl_groups(serverssl, clientssl, clientmulti,
5316                                          isecdhe, idx)))
5317         goto end;
5318 
5319     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5320             || !TEST_true(SSL_session_reused(clientssl)))
5321         goto end;
5322 
5323     /* Check that we get what we expected */
5324     if (!TEST_uint_eq(SSL_get_negotiated_group(clientssl), expectednid)
5325             || !TEST_uint_eq(SSL_get_negotiated_group(serverssl), expectednid))
5326         goto end;
5327 
5328     testresult = 1;
5329  end:
5330     SSL_free(serverssl);
5331     SSL_free(clientssl);
5332     SSL_CTX_free(sctx);
5333     SSL_CTX_free(cctx);
5334     SSL_SESSION_free(origsess);
5335     return testresult;
5336 }
5337 # endif /* !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH) */
5338 
5339 /*
5340  * Test TLSv1.3 Cipher Suite
5341  * Test 0 = Set TLS1.3 cipher on context
5342  * Test 1 = Set TLS1.3 cipher on SSL
5343  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
5344  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
5345  */
test_tls13_ciphersuite(int idx)5346 static int test_tls13_ciphersuite(int idx)
5347 {
5348     SSL_CTX *sctx = NULL, *cctx = NULL;
5349     SSL *serverssl = NULL, *clientssl = NULL;
5350     static const struct {
5351         const char *ciphername;
5352         int fipscapable;
5353         int low_security;
5354     } t13_ciphers[] = {
5355         { TLS1_3_RFC_AES_128_GCM_SHA256, 1, 0 },
5356         { TLS1_3_RFC_AES_256_GCM_SHA384, 1, 0 },
5357         { TLS1_3_RFC_AES_128_CCM_SHA256, 1, 0 },
5358 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
5359         { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5360         { TLS1_3_RFC_AES_256_GCM_SHA384
5361           ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0, 0 },
5362 # endif
5363         /* CCM8 ciphers are considered low security due to their short tag */
5364         { TLS1_3_RFC_AES_128_CCM_8_SHA256
5365           ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1, 1 },
5366 # if !defined(OPENSSL_NO_INTEGRITY_ONLY_CIPHERS)
5367         /* Integrity-only cipher do not provide any confidentiality */
5368         { TLS1_3_RFC_SHA256_SHA256, 0, 1 },
5369         { TLS1_3_RFC_SHA384_SHA384, 0, 1 }
5370 # endif
5371     };
5372     const char *t13_cipher = NULL;
5373     const char *t12_cipher = NULL;
5374     const char *negotiated_scipher;
5375     const char *negotiated_ccipher;
5376     int set_at_ctx = 0;
5377     int set_at_ssl = 0;
5378     int testresult = 0;
5379     int max_ver;
5380     size_t i;
5381 
5382     switch (idx) {
5383         case 0:
5384             set_at_ctx = 1;
5385             break;
5386         case 1:
5387             set_at_ssl = 1;
5388             break;
5389         case 2:
5390             set_at_ctx = 1;
5391             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5392             break;
5393         case 3:
5394             set_at_ssl = 1;
5395             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
5396             break;
5397     }
5398 
5399     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
5400 # ifdef OPENSSL_NO_TLS1_2
5401         if (max_ver == TLS1_2_VERSION)
5402             continue;
5403 # endif
5404         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
5405             if (is_fips && !t13_ciphers[i].fipscapable)
5406                 continue;
5407             t13_cipher = t13_ciphers[i].ciphername;
5408             if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5409                                                TLS_client_method(),
5410                                                TLS1_VERSION, max_ver,
5411                                                &sctx, &cctx, cert, privkey)))
5412                 goto end;
5413 
5414             if (t13_ciphers[i].low_security) {
5415                 SSL_CTX_set_security_level(sctx, 0);
5416                 SSL_CTX_set_security_level(cctx, 0);
5417             }
5418 
5419             if (set_at_ctx) {
5420                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
5421                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
5422                     goto end;
5423                 if (t12_cipher != NULL) {
5424                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
5425                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
5426                                                               t12_cipher)))
5427                         goto end;
5428                 }
5429             }
5430 
5431             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5432                                               &clientssl, NULL, NULL)))
5433                 goto end;
5434 
5435             if (set_at_ssl) {
5436                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
5437                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
5438                     goto end;
5439                 if (t12_cipher != NULL) {
5440                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
5441                         || !TEST_true(SSL_set_cipher_list(clientssl,
5442                                                           t12_cipher)))
5443                         goto end;
5444                 }
5445             }
5446 
5447             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5448                                                  SSL_ERROR_NONE)))
5449                 goto end;
5450 
5451             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5452                                                                  serverssl));
5453             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
5454                                                                  clientssl));
5455             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
5456                 goto end;
5457 
5458             /*
5459              * TEST_strn_eq is used below because t13_cipher can contain
5460              * multiple ciphersuites
5461              */
5462             if (max_ver == TLS1_3_VERSION
5463                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
5464                                  strlen(negotiated_scipher)))
5465                 goto end;
5466 
5467 # ifndef OPENSSL_NO_TLS1_2
5468             /* Below validation is not done when t12_cipher is NULL */
5469             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
5470                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
5471                 goto end;
5472 # endif
5473 
5474             SSL_free(serverssl);
5475             serverssl = NULL;
5476             SSL_free(clientssl);
5477             clientssl = NULL;
5478             SSL_CTX_free(sctx);
5479             sctx = NULL;
5480             SSL_CTX_free(cctx);
5481             cctx = NULL;
5482         }
5483     }
5484 
5485     testresult = 1;
5486  end:
5487     SSL_free(serverssl);
5488     SSL_free(clientssl);
5489     SSL_CTX_free(sctx);
5490     SSL_CTX_free(cctx);
5491     return testresult;
5492 }
5493 
5494 /*
5495  * Test TLSv1.3 PSKs
5496  * Test 0 = Test new style callbacks
5497  * Test 1 = Test both new and old style callbacks
5498  * Test 2 = Test old style callbacks
5499  * Test 3 = Test old style callbacks with no certificate
5500  */
test_tls13_psk(int idx)5501 static int test_tls13_psk(int idx)
5502 {
5503     SSL_CTX *sctx = NULL, *cctx = NULL;
5504     SSL *serverssl = NULL, *clientssl = NULL;
5505     const SSL_CIPHER *cipher = NULL;
5506     const unsigned char key[] = {
5507         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
5508         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5509         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
5510         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
5511     };
5512     int testresult = 0;
5513 
5514     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5515                                        TLS_client_method(), TLS1_VERSION, 0,
5516                                        &sctx, &cctx, idx == 3 ? NULL : cert,
5517                                        idx == 3 ? NULL : privkey)))
5518         goto end;
5519 
5520     if (idx != 3) {
5521         /*
5522          * We use a ciphersuite with SHA256 to ease testing old style PSK
5523          * callbacks which will always default to SHA256. This should not be
5524          * necessary if we have no cert/priv key. In that case the server should
5525          * prefer SHA256 automatically.
5526          */
5527         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5528                                                 "TLS_AES_128_GCM_SHA256")))
5529             goto end;
5530     } else {
5531         /*
5532          * As noted above the server should prefer SHA256 automatically. However
5533          * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
5534          * code works even if we are testing with only the FIPS provider loaded.
5535          */
5536         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
5537                                                 "TLS_AES_256_GCM_SHA384:"
5538                                                 "TLS_AES_128_GCM_SHA256")))
5539             goto end;
5540     }
5541 
5542     /*
5543      * Test 0: New style callbacks only
5544      * Test 1: New and old style callbacks (only the new ones should be used)
5545      * Test 2: Old style callbacks only
5546      */
5547     if (idx == 0 || idx == 1) {
5548         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
5549         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
5550     }
5551 #ifndef OPENSSL_NO_PSK
5552     if (idx >= 1) {
5553         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
5554         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
5555     }
5556 #endif
5557     srvid = pskid;
5558     use_session_cb_cnt = 0;
5559     find_session_cb_cnt = 0;
5560     psk_client_cb_cnt = 0;
5561     psk_server_cb_cnt = 0;
5562 
5563     if (idx != 3) {
5564         /*
5565          * Check we can create a connection if callback decides not to send a
5566          * PSK
5567          */
5568         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5569                                                  NULL, NULL))
5570                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5571                                                     SSL_ERROR_NONE))
5572                 || !TEST_false(SSL_session_reused(clientssl))
5573                 || !TEST_false(SSL_session_reused(serverssl)))
5574             goto end;
5575 
5576         if (idx == 0 || idx == 1) {
5577             if (!TEST_true(use_session_cb_cnt == 1)
5578                     || !TEST_true(find_session_cb_cnt == 0)
5579                        /*
5580                         * If no old style callback then below should be 0
5581                         * otherwise 1
5582                         */
5583                     || !TEST_true(psk_client_cb_cnt == idx)
5584                     || !TEST_true(psk_server_cb_cnt == 0))
5585                 goto end;
5586         } else {
5587             if (!TEST_true(use_session_cb_cnt == 0)
5588                     || !TEST_true(find_session_cb_cnt == 0)
5589                     || !TEST_true(psk_client_cb_cnt == 1)
5590                     || !TEST_true(psk_server_cb_cnt == 0))
5591                 goto end;
5592         }
5593 
5594         shutdown_ssl_connection(serverssl, clientssl);
5595         serverssl = clientssl = NULL;
5596         use_session_cb_cnt = psk_client_cb_cnt = 0;
5597     }
5598 
5599     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5600                                              NULL, NULL)))
5601         goto end;
5602 
5603     /* Create the PSK */
5604     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
5605     clientpsk = SSL_SESSION_new();
5606     if (!TEST_ptr(clientpsk)
5607             || !TEST_ptr(cipher)
5608             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
5609                                                       sizeof(key)))
5610             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
5611             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
5612                                                            TLS1_3_VERSION))
5613             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
5614         goto end;
5615     serverpsk = clientpsk;
5616 
5617     /* Check we can create a connection and the PSK is used */
5618     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5619             || !TEST_true(SSL_session_reused(clientssl))
5620             || !TEST_true(SSL_session_reused(serverssl)))
5621         goto end;
5622 
5623     if (idx == 0 || idx == 1) {
5624         if (!TEST_true(use_session_cb_cnt == 1)
5625                 || !TEST_true(find_session_cb_cnt == 1)
5626                 || !TEST_true(psk_client_cb_cnt == 0)
5627                 || !TEST_true(psk_server_cb_cnt == 0))
5628             goto end;
5629     } else {
5630         if (!TEST_true(use_session_cb_cnt == 0)
5631                 || !TEST_true(find_session_cb_cnt == 0)
5632                 || !TEST_true(psk_client_cb_cnt == 1)
5633                 || !TEST_true(psk_server_cb_cnt == 1))
5634             goto end;
5635     }
5636 
5637     shutdown_ssl_connection(serverssl, clientssl);
5638     serverssl = clientssl = NULL;
5639     use_session_cb_cnt = find_session_cb_cnt = 0;
5640     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5641 
5642     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5643                                              NULL, NULL)))
5644         goto end;
5645 
5646     /* Force an HRR */
5647 #if defined(OPENSSL_NO_EC)
5648     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
5649         goto end;
5650 #else
5651     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-384")))
5652         goto end;
5653 #endif
5654 
5655     /*
5656      * Check we can create a connection, the PSK is used and the callbacks are
5657      * called twice.
5658      */
5659     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
5660             || !TEST_true(SSL_session_reused(clientssl))
5661             || !TEST_true(SSL_session_reused(serverssl)))
5662         goto end;
5663 
5664     if (idx == 0 || idx == 1) {
5665         if (!TEST_true(use_session_cb_cnt == 2)
5666                 || !TEST_true(find_session_cb_cnt == 2)
5667                 || !TEST_true(psk_client_cb_cnt == 0)
5668                 || !TEST_true(psk_server_cb_cnt == 0))
5669             goto end;
5670     } else {
5671         if (!TEST_true(use_session_cb_cnt == 0)
5672                 || !TEST_true(find_session_cb_cnt == 0)
5673                 || !TEST_true(psk_client_cb_cnt == 2)
5674                 || !TEST_true(psk_server_cb_cnt == 2))
5675             goto end;
5676     }
5677 
5678     shutdown_ssl_connection(serverssl, clientssl);
5679     serverssl = clientssl = NULL;
5680     use_session_cb_cnt = find_session_cb_cnt = 0;
5681     psk_client_cb_cnt = psk_server_cb_cnt = 0;
5682 
5683     if (idx != 3) {
5684         /*
5685          * Check that if the server rejects the PSK we can still connect, but with
5686          * a full handshake
5687          */
5688         srvid = "Dummy Identity";
5689         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5690                                                  NULL, NULL))
5691                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
5692                                                     SSL_ERROR_NONE))
5693                 || !TEST_false(SSL_session_reused(clientssl))
5694                 || !TEST_false(SSL_session_reused(serverssl)))
5695             goto end;
5696 
5697         if (idx == 0 || idx == 1) {
5698             if (!TEST_true(use_session_cb_cnt == 1)
5699                     || !TEST_true(find_session_cb_cnt == 1)
5700                     || !TEST_true(psk_client_cb_cnt == 0)
5701                        /*
5702                         * If no old style callback then below should be 0
5703                         * otherwise 1
5704                         */
5705                     || !TEST_true(psk_server_cb_cnt == idx))
5706                 goto end;
5707         } else {
5708             if (!TEST_true(use_session_cb_cnt == 0)
5709                     || !TEST_true(find_session_cb_cnt == 0)
5710                     || !TEST_true(psk_client_cb_cnt == 1)
5711                     || !TEST_true(psk_server_cb_cnt == 1))
5712                 goto end;
5713         }
5714 
5715         shutdown_ssl_connection(serverssl, clientssl);
5716         serverssl = clientssl = NULL;
5717     }
5718     testresult = 1;
5719 
5720  end:
5721     SSL_SESSION_free(clientpsk);
5722     SSL_SESSION_free(serverpsk);
5723     clientpsk = serverpsk = NULL;
5724     SSL_free(serverssl);
5725     SSL_free(clientssl);
5726     SSL_CTX_free(sctx);
5727     SSL_CTX_free(cctx);
5728     return testresult;
5729 }
5730 
5731 #ifndef OSSL_NO_USABLE_TLS1_3
5732 /*
5733  * Test TLS1.3 connection establishment succeeds with various configurations of
5734  * the options `SSL_OP_ALLOW_NO_DHE_KEX` and `SSL_OP_PREFER_NO_DHE_KEX`.
5735  * The verification of whether the right KEX mode is chosen is not covered by
5736  * this test but by `test_tls13kexmodes`.
5737  *
5738  * Tests (idx & 1): Server has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5739  * Tests (idx & 2): Server has `SSL_OP_PREFER_NO_DHE_KEX` set.
5740  * Tests (idx & 4): Client has `SSL_OP_ALLOW_NO_DHE_KEX` set.
5741  */
test_tls13_no_dhe_kex(const int idx)5742 static int test_tls13_no_dhe_kex(const int idx)
5743 {
5744     SSL_CTX *sctx = NULL, *cctx = NULL;
5745     SSL *serverssl = NULL, *clientssl = NULL;
5746     int testresult = 0;
5747     size_t j;
5748     SSL_SESSION *saved_session;
5749 
5750     int server_allow_no_dhe = (idx & 1) != 0;
5751     int server_prefer_no_dhe = (idx & 2) != 0;
5752     int client_allow_no_dhe = (idx & 4) != 0;
5753 
5754     uint64_t server_options = 0
5755             | (server_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0)
5756             | (server_prefer_no_dhe ? SSL_OP_PREFER_NO_DHE_KEX : 0);
5757 
5758     uint64_t client_options = 0
5759             | (client_allow_no_dhe ? SSL_OP_ALLOW_NO_DHE_KEX : 0);
5760 
5761     new_called = 0;
5762     do_cache = 1;
5763 
5764     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5765                                        TLS_client_method(), TLS1_3_VERSION, 0,
5766                                        &sctx, &cctx, cert, privkey)))
5767         goto end;
5768 
5769     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
5770                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
5771 
5772     SSL_CTX_set_options(sctx, server_options);
5773     SSL_CTX_set_options(cctx, client_options);
5774 
5775     SSL_CTX_sess_set_new_cb(cctx, new_cachesession_cb);
5776 
5777     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5778                                       &clientssl, NULL, NULL)))
5779         goto end;
5780 
5781     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5782                                          SSL_ERROR_NONE))
5783             /* Check we got the number of tickets we were expecting */
5784             || !TEST_int_eq(2, new_called))
5785         goto end;
5786 
5787     /* We'll reuse the last ticket. */
5788     saved_session = sesscache[new_called - 1];
5789 
5790     SSL_shutdown(clientssl);
5791     SSL_shutdown(serverssl);
5792     SSL_free(serverssl);
5793     SSL_free(clientssl);
5794     SSL_CTX_free(cctx);
5795     clientssl = serverssl = NULL;
5796     cctx = NULL;
5797 
5798     /*
5799      * Now we resume with the last ticket we created.
5800      */
5801 
5802     /* The server context already exists, so we only create the client. */
5803     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5804                                        TLS_client_method(), TLS1_3_VERSION, 0,
5805                                        NULL, &cctx, cert, privkey)))
5806         goto end;
5807 
5808     SSL_CTX_set_options(cctx, client_options);
5809 
5810     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5811                                       &clientssl, NULL, NULL))
5812             || !TEST_true(SSL_set_session(clientssl, saved_session)))
5813         goto end;
5814 
5815     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5816                                          SSL_ERROR_NONE)))
5817         goto end;
5818 
5819     /*
5820      * Make sure, the session was resumed.
5821      */
5822     if (!TEST_true(SSL_session_reused(clientssl)))
5823         goto end;
5824 
5825     SSL_shutdown(clientssl);
5826     SSL_shutdown(serverssl);
5827 
5828     testresult = 1;
5829 
5830  end:
5831     SSL_free(serverssl);
5832     SSL_free(clientssl);
5833     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
5834         SSL_SESSION_free(sesscache[j]);
5835         sesscache[j] = NULL;
5836     }
5837     SSL_CTX_free(sctx);
5838     SSL_CTX_free(cctx);
5839 
5840     return testresult;
5841 }
5842 #endif /* OSSL_NO_USABLE_TLS1_3 */
5843 
5844 static unsigned char cookie_magic_value[] = "cookie magic";
5845 
generate_cookie_callback(SSL * ssl,unsigned char * cookie,unsigned int * cookie_len)5846 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
5847                                     unsigned int *cookie_len)
5848 {
5849     /*
5850      * Not suitable as a real cookie generation function but good enough for
5851      * testing!
5852      */
5853     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
5854     *cookie_len = sizeof(cookie_magic_value) - 1;
5855 
5856     return 1;
5857 }
5858 
verify_cookie_callback(SSL * ssl,const unsigned char * cookie,unsigned int cookie_len)5859 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
5860                                   unsigned int cookie_len)
5861 {
5862     if (cookie_len == sizeof(cookie_magic_value) - 1
5863         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
5864         return 1;
5865 
5866     return 0;
5867 }
5868 
generate_stateless_cookie_callback(SSL * ssl,unsigned char * cookie,size_t * cookie_len)5869 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
5870                                         size_t *cookie_len)
5871 {
5872     unsigned int temp;
5873     int res = generate_cookie_callback(ssl, cookie, &temp);
5874     *cookie_len = temp;
5875     return res;
5876 }
5877 
verify_stateless_cookie_callback(SSL * ssl,const unsigned char * cookie,size_t cookie_len)5878 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
5879                                       size_t cookie_len)
5880 {
5881     return verify_cookie_callback(ssl, cookie, cookie_len);
5882 }
5883 
test_stateless(void)5884 static int test_stateless(void)
5885 {
5886     SSL_CTX *sctx = NULL, *cctx = NULL;
5887     SSL *serverssl = NULL, *clientssl = NULL;
5888     int testresult = 0;
5889 
5890     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5891                                        TLS_client_method(), TLS1_VERSION, 0,
5892                                        &sctx, &cctx, cert, privkey)))
5893         goto end;
5894 
5895     /* The arrival of CCS messages can confuse the test */
5896     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5897 
5898     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5899                                       NULL, NULL))
5900                /* Send the first ClientHello */
5901             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5902                                                  SSL_ERROR_WANT_READ))
5903                /*
5904                 * This should fail with a -1 return because we have no callbacks
5905                 * set up
5906                 */
5907             || !TEST_int_eq(SSL_stateless(serverssl), -1))
5908         goto end;
5909 
5910     /* Fatal error so abandon the connection from this client */
5911     SSL_free(clientssl);
5912     clientssl = NULL;
5913 
5914     /* Set up the cookie generation and verification callbacks */
5915     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
5916     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
5917 
5918     /*
5919      * Create a new connection from the client (we can reuse the server SSL
5920      * object).
5921      */
5922     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5923                                              NULL, NULL))
5924                /* Send the first ClientHello */
5925             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5926                                                 SSL_ERROR_WANT_READ))
5927                /* This should fail because there is no cookie */
5928             || !TEST_int_eq(SSL_stateless(serverssl), 0))
5929         goto end;
5930 
5931     /* Abandon the connection from this client */
5932     SSL_free(clientssl);
5933     clientssl = NULL;
5934 
5935     /*
5936      * Now create a connection from a new client but with the same server SSL
5937      * object
5938      */
5939     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5940                                              NULL, NULL))
5941                /* Send the first ClientHello */
5942             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5943                                                 SSL_ERROR_WANT_READ))
5944                /* This should fail because there is no cookie */
5945             || !TEST_int_eq(SSL_stateless(serverssl), 0)
5946                /* Send the second ClientHello */
5947             || !TEST_false(create_ssl_connection(serverssl, clientssl,
5948                                                 SSL_ERROR_WANT_READ))
5949                /* This should succeed because a cookie is now present */
5950             || !TEST_int_eq(SSL_stateless(serverssl), 1)
5951                /* Complete the connection */
5952             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5953                                                 SSL_ERROR_NONE)))
5954         goto end;
5955 
5956     shutdown_ssl_connection(serverssl, clientssl);
5957     serverssl = clientssl = NULL;
5958     testresult = 1;
5959 
5960  end:
5961     SSL_free(serverssl);
5962     SSL_free(clientssl);
5963     SSL_CTX_free(sctx);
5964     SSL_CTX_free(cctx);
5965     return testresult;
5966 
5967 }
5968 #endif /* OSSL_NO_USABLE_TLS1_3 */
5969 
5970 static int clntaddoldcb = 0;
5971 static int clntparseoldcb = 0;
5972 static int srvaddoldcb = 0;
5973 static int srvparseoldcb = 0;
5974 static int clntaddnewcb = 0;
5975 static int clntparsenewcb = 0;
5976 static int srvaddnewcb = 0;
5977 static int srvparsenewcb = 0;
5978 static int snicb = 0;
5979 
5980 #define TEST_EXT_TYPE1  0xff00
5981 
old_add_cb(SSL * s,unsigned int ext_type,const unsigned char ** out,size_t * outlen,int * al,void * add_arg)5982 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
5983                       size_t *outlen, int *al, void *add_arg)
5984 {
5985     int *server = (int *)add_arg;
5986     unsigned char *data;
5987 
5988     if (SSL_is_server(s))
5989         srvaddoldcb++;
5990     else
5991         clntaddoldcb++;
5992 
5993     if (*server != SSL_is_server(s)
5994             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
5995         return -1;
5996 
5997     *data = 1;
5998     *out = data;
5999     *outlen = sizeof(char);
6000     return 1;
6001 }
6002 
old_free_cb(SSL * s,unsigned int ext_type,const unsigned char * out,void * add_arg)6003 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
6004                         void *add_arg)
6005 {
6006     OPENSSL_free((unsigned char *)out);
6007 }
6008 
old_parse_cb(SSL * s,unsigned int ext_type,const unsigned char * in,size_t inlen,int * al,void * parse_arg)6009 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
6010                         size_t inlen, int *al, void *parse_arg)
6011 {
6012     int *server = (int *)parse_arg;
6013 
6014     if (SSL_is_server(s))
6015         srvparseoldcb++;
6016     else
6017         clntparseoldcb++;
6018 
6019     if (*server != SSL_is_server(s)
6020             || inlen != sizeof(char)
6021             || *in != 1)
6022         return -1;
6023 
6024     return 1;
6025 }
6026 
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)6027 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
6028                       const unsigned char **out, size_t *outlen, X509 *x,
6029                       size_t chainidx, int *al, void *add_arg)
6030 {
6031     int *server = (int *)add_arg;
6032     unsigned char *data;
6033 
6034     if (SSL_is_server(s))
6035         srvaddnewcb++;
6036     else
6037         clntaddnewcb++;
6038 
6039     if (*server != SSL_is_server(s)
6040             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
6041         return -1;
6042 
6043     *data = 1;
6044     *out = data;
6045     *outlen = sizeof(*data);
6046     return 1;
6047 }
6048 
new_free_cb(SSL * s,unsigned int ext_type,unsigned int context,const unsigned char * out,void * add_arg)6049 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
6050                         const unsigned char *out, void *add_arg)
6051 {
6052     OPENSSL_free((unsigned char *)out);
6053 }
6054 
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)6055 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
6056                         const unsigned char *in, size_t inlen, X509 *x,
6057                         size_t chainidx, int *al, void *parse_arg)
6058 {
6059     int *server = (int *)parse_arg;
6060 
6061     if (SSL_is_server(s))
6062         srvparsenewcb++;
6063     else
6064         clntparsenewcb++;
6065 
6066     if (*server != SSL_is_server(s)
6067             || inlen != sizeof(char) || *in != 1)
6068         return -1;
6069 
6070     return 1;
6071 }
6072 
sni_cb(SSL * s,int * al,void * arg)6073 static int sni_cb(SSL *s, int *al, void *arg)
6074 {
6075     SSL_CTX *ctx = (SSL_CTX *)arg;
6076 
6077     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
6078         *al = SSL_AD_INTERNAL_ERROR;
6079         return SSL_TLSEXT_ERR_ALERT_FATAL;
6080     }
6081     snicb++;
6082     return SSL_TLSEXT_ERR_OK;
6083 }
6084 
verify_cb(int preverify_ok,X509_STORE_CTX * x509_ctx)6085 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
6086 {
6087     return 1;
6088 }
6089 
6090 /*
6091  * Custom call back tests.
6092  * Test 0: Old style callbacks in TLSv1.2
6093  * Test 1: New style callbacks in TLSv1.2
6094  * Test 2: New style callbacks in TLSv1.2 with SNI
6095  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
6096  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
6097  * Test 5: New style callbacks in TLSv1.3. Extensions in CR + Client Cert
6098  */
test_custom_exts(int tst)6099 static int test_custom_exts(int tst)
6100 {
6101     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6102     SSL *clientssl = NULL, *serverssl = NULL;
6103     int testresult = 0;
6104     static int server = 1;
6105     static int client = 0;
6106     SSL_SESSION *sess = NULL;
6107     unsigned int context;
6108 
6109 #if defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6110     /* Skip tests for TLSv1.2 and below in this case */
6111     if (tst < 3)
6112         return 1;
6113 #endif
6114 
6115     /* Reset callback counters */
6116     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
6117     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
6118     snicb = 0;
6119 
6120     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6121                                        TLS_client_method(), TLS1_VERSION, 0,
6122                                        &sctx, &cctx, cert, privkey)))
6123         goto end;
6124 
6125     if (tst == 2
6126             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
6127                                               TLS1_VERSION, 0,
6128                                               &sctx2, NULL, cert, privkey)))
6129         goto end;
6130 
6131 
6132     if (tst < 3) {
6133         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
6134         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
6135         if (sctx2 != NULL)
6136             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
6137     }
6138 
6139     if (tst == 5) {
6140         context = SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
6141                   | SSL_EXT_TLS1_3_CERTIFICATE;
6142         SSL_CTX_set_verify(sctx,
6143                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
6144                            verify_cb);
6145         if (!TEST_int_eq(SSL_CTX_use_certificate_file(cctx, cert,
6146                                                       SSL_FILETYPE_PEM), 1)
6147                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(cctx, privkey,
6148                                                             SSL_FILETYPE_PEM), 1)
6149                 || !TEST_int_eq(SSL_CTX_check_private_key(cctx), 1))
6150             goto end;
6151     } else if (tst == 4) {
6152         context = SSL_EXT_CLIENT_HELLO
6153                   | SSL_EXT_TLS1_2_SERVER_HELLO
6154                   | SSL_EXT_TLS1_3_SERVER_HELLO
6155                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
6156                   | SSL_EXT_TLS1_3_CERTIFICATE
6157                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
6158     } else {
6159         context = SSL_EXT_CLIENT_HELLO
6160                   | SSL_EXT_TLS1_2_SERVER_HELLO
6161                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
6162     }
6163 
6164     /* Create a client side custom extension */
6165     if (tst == 0) {
6166         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6167                                                      old_add_cb, old_free_cb,
6168                                                      &client, old_parse_cb,
6169                                                      &client)))
6170             goto end;
6171     } else {
6172         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
6173                                               new_add_cb, new_free_cb,
6174                                               &client, new_parse_cb, &client)))
6175             goto end;
6176     }
6177 
6178     /* Should not be able to add duplicates */
6179     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
6180                                                   old_add_cb, old_free_cb,
6181                                                   &client, old_parse_cb,
6182                                                   &client))
6183             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
6184                                                   context, new_add_cb,
6185                                                   new_free_cb, &client,
6186                                                   new_parse_cb, &client)))
6187         goto end;
6188 
6189     /* Create a server side custom extension */
6190     if (tst == 0) {
6191         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6192                                                      old_add_cb, old_free_cb,
6193                                                      &server, old_parse_cb,
6194                                                      &server)))
6195             goto end;
6196     } else {
6197         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
6198                                               new_add_cb, new_free_cb,
6199                                               &server, new_parse_cb, &server)))
6200             goto end;
6201         if (sctx2 != NULL
6202                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
6203                                                      context, new_add_cb,
6204                                                      new_free_cb, &server,
6205                                                      new_parse_cb, &server)))
6206             goto end;
6207     }
6208 
6209     /* Should not be able to add duplicates */
6210     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
6211                                                   old_add_cb, old_free_cb,
6212                                                   &server, old_parse_cb,
6213                                                   &server))
6214             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
6215                                                   context, new_add_cb,
6216                                                   new_free_cb, &server,
6217                                                   new_parse_cb, &server)))
6218         goto end;
6219 
6220     if (tst == 2) {
6221         /* Set up SNI */
6222         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
6223                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
6224             goto end;
6225     }
6226 
6227     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6228                                       &clientssl, NULL, NULL))
6229             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6230                                                 SSL_ERROR_NONE)))
6231         goto end;
6232 
6233     if (tst == 0) {
6234         if (clntaddoldcb != 1
6235                 || clntparseoldcb != 1
6236                 || srvaddoldcb != 1
6237                 || srvparseoldcb != 1)
6238             goto end;
6239     } else if (tst == 1 || tst == 2 || tst == 3) {
6240         if (clntaddnewcb != 1
6241                 || clntparsenewcb != 1
6242                 || srvaddnewcb != 1
6243                 || srvparsenewcb != 1
6244                 || (tst != 2 && snicb != 0)
6245                 || (tst == 2 && snicb != 1))
6246             goto end;
6247     } else if (tst == 5) {
6248         if (clntaddnewcb != 1
6249                 || clntparsenewcb != 1
6250                 || srvaddnewcb != 1
6251                 || srvparsenewcb != 1)
6252             goto end;
6253     } else {
6254         /* In this case there 2 NewSessionTicket messages created */
6255         if (clntaddnewcb != 1
6256                 || clntparsenewcb != 5
6257                 || srvaddnewcb != 5
6258                 || srvparsenewcb != 1)
6259             goto end;
6260     }
6261 
6262     sess = SSL_get1_session(clientssl);
6263     SSL_shutdown(clientssl);
6264     SSL_shutdown(serverssl);
6265     SSL_free(serverssl);
6266     SSL_free(clientssl);
6267     serverssl = clientssl = NULL;
6268 
6269     if (tst == 3 || tst == 5) {
6270         /* We don't bother with the resumption aspects for these tests */
6271         testresult = 1;
6272         goto end;
6273     }
6274 
6275     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6276                                       NULL, NULL))
6277             || !TEST_true(SSL_set_session(clientssl, sess))
6278             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6279                                                SSL_ERROR_NONE)))
6280         goto end;
6281 
6282     /*
6283      * For a resumed session we expect to add the ClientHello extension. For the
6284      * old style callbacks we ignore it on the server side because they set
6285      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
6286      * them.
6287      */
6288     if (tst == 0) {
6289         if (clntaddoldcb != 2
6290                 || clntparseoldcb != 1
6291                 || srvaddoldcb != 1
6292                 || srvparseoldcb != 1)
6293             goto end;
6294     } else if (tst == 1 || tst == 2 || tst == 3) {
6295         if (clntaddnewcb != 2
6296                 || clntparsenewcb != 2
6297                 || srvaddnewcb != 2
6298                 || srvparsenewcb != 2)
6299             goto end;
6300     } else {
6301         /*
6302          * No Certificate message extensions in the resumption handshake,
6303          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
6304          */
6305         if (clntaddnewcb != 2
6306                 || clntparsenewcb != 8
6307                 || srvaddnewcb != 8
6308                 || srvparsenewcb != 2)
6309             goto end;
6310     }
6311 
6312     testresult = 1;
6313 
6314 end:
6315     SSL_SESSION_free(sess);
6316     SSL_free(serverssl);
6317     SSL_free(clientssl);
6318     SSL_CTX_free(sctx2);
6319     SSL_CTX_free(sctx);
6320     SSL_CTX_free(cctx);
6321     return testresult;
6322 }
6323 
6324 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
6325 
6326 #define  SYNTHV1CONTEXT     (SSL_EXT_TLS1_2_AND_BELOW_ONLY \
6327                              | SSL_EXT_CLIENT_HELLO \
6328                              | SSL_EXT_TLS1_2_SERVER_HELLO \
6329                              | SSL_EXT_IGNORE_ON_RESUMPTION)
6330 
6331 #define TLS13CONTEXT (SSL_EXT_TLS1_3_CERTIFICATE \
6332                       | SSL_EXT_TLS1_2_SERVER_HELLO \
6333                       | SSL_EXT_CLIENT_HELLO)
6334 
6335 #define SERVERINFO_CUSTOM                                 \
6336     0x00, (char)TLSEXT_TYPE_signed_certificate_timestamp, \
6337     0x00, 0x03,                                           \
6338     0x04, 0x05, 0x06                                      \
6339 
6340 static const unsigned char serverinfo_custom_tls13[] = {
6341     0x00, 0x00, (TLS13CONTEXT >> 8) & 0xff, TLS13CONTEXT & 0xff,
6342     SERVERINFO_CUSTOM
6343 };
6344 static const unsigned char serverinfo_custom_v2[] = {
6345     0x00, 0x00, (SYNTHV1CONTEXT >> 8) & 0xff,  SYNTHV1CONTEXT & 0xff,
6346     SERVERINFO_CUSTOM
6347 };
6348 static const unsigned char serverinfo_custom_v1[] = {
6349     SERVERINFO_CUSTOM
6350 };
6351 static const size_t serverinfo_custom_tls13_len = sizeof(serverinfo_custom_tls13);
6352 static const size_t serverinfo_custom_v2_len = sizeof(serverinfo_custom_v2);
6353 static const size_t serverinfo_custom_v1_len = sizeof(serverinfo_custom_v1);
6354 
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)6355 static int serverinfo_custom_parse_cb(SSL *s, unsigned int ext_type,
6356                                       unsigned int context,
6357                                       const unsigned char *in,
6358                                       size_t inlen, X509 *x,
6359                                       size_t chainidx, int *al,
6360                                       void *parse_arg)
6361 {
6362     const size_t len = serverinfo_custom_v1_len;
6363     const unsigned char *si = &serverinfo_custom_v1[len - 3];
6364     int *p_cb_result = (int*)parse_arg;
6365     *p_cb_result = TEST_mem_eq(in, inlen, si, 3);
6366     return 1;
6367 }
6368 
test_serverinfo_custom(const int idx)6369 static int test_serverinfo_custom(const int idx)
6370 {
6371     SSL_CTX *sctx = NULL, *cctx = NULL;
6372     SSL *clientssl = NULL, *serverssl = NULL;
6373     int testresult = 0;
6374     int cb_result = 0;
6375 
6376     /*
6377      * Following variables are set in the switch statement
6378      *  according to the test iteration.
6379      * Default values do not make much sense: test would fail with them.
6380      */
6381     int serverinfo_version = 0;
6382     int protocol_version = 0;
6383     unsigned int extension_context = 0;
6384     const unsigned char *si = NULL;
6385     size_t si_len = 0;
6386 
6387     const int call_use_serverinfo_ex = idx > 0;
6388     switch (idx) {
6389     case 0: /* FALLTHROUGH */
6390     case 1:
6391         serverinfo_version = SSL_SERVERINFOV1;
6392         protocol_version = TLS1_2_VERSION;
6393         extension_context = SYNTHV1CONTEXT;
6394         si = serverinfo_custom_v1;
6395         si_len = serverinfo_custom_v1_len;
6396         break;
6397     case 2:
6398         serverinfo_version = SSL_SERVERINFOV2;
6399         protocol_version = TLS1_2_VERSION;
6400         extension_context = SYNTHV1CONTEXT;
6401         si = serverinfo_custom_v2;
6402         si_len = serverinfo_custom_v2_len;
6403         break;
6404     case 3:
6405         serverinfo_version = SSL_SERVERINFOV2;
6406         protocol_version = TLS1_3_VERSION;
6407         extension_context = TLS13CONTEXT;
6408         si = serverinfo_custom_tls13;
6409         si_len = serverinfo_custom_tls13_len;
6410         break;
6411     }
6412 
6413     if (!TEST_true(create_ssl_ctx_pair(libctx,
6414                                        TLS_method(),
6415                                        TLS_method(),
6416                                        protocol_version,
6417                                        protocol_version,
6418                                        &sctx, &cctx, cert, privkey)))
6419         goto end;
6420 
6421     if (call_use_serverinfo_ex) {
6422         if (!TEST_true(SSL_CTX_use_serverinfo_ex(sctx, serverinfo_version,
6423                                                  si, si_len)))
6424             goto end;
6425     } else {
6426         if (!TEST_true(SSL_CTX_use_serverinfo(sctx, si, si_len)))
6427             goto end;
6428     }
6429 
6430     if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TLSEXT_TYPE_signed_certificate_timestamp,
6431                                           extension_context,
6432                                           NULL, NULL, NULL,
6433                                           serverinfo_custom_parse_cb,
6434                                           &cb_result))
6435         || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6436                                          NULL, NULL))
6437         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6438                                             SSL_ERROR_NONE))
6439         || !TEST_int_eq(SSL_do_handshake(clientssl), 1))
6440         goto end;
6441 
6442     if (!TEST_true(cb_result))
6443         goto end;
6444 
6445     testresult = 1;
6446 
6447  end:
6448     SSL_free(serverssl);
6449     SSL_free(clientssl);
6450     SSL_CTX_free(sctx);
6451     SSL_CTX_free(cctx);
6452 
6453     return testresult;
6454 }
6455 #endif
6456 
6457 /*
6458  * Test that SSL_export_keying_material() produces expected results. There are
6459  * no test vectors so all we do is test that both sides of the communication
6460  * produce the same results for different protocol versions.
6461  */
6462 #define SMALL_LABEL_LEN 10
6463 #define LONG_LABEL_LEN  249
test_export_key_mat(int tst)6464 static int test_export_key_mat(int tst)
6465 {
6466     int testresult = 0;
6467     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
6468     SSL *clientssl = NULL, *serverssl = NULL;
6469     const char label[LONG_LABEL_LEN + 1] = "test label";
6470     const unsigned char context[] = "context";
6471     const unsigned char *emptycontext = NULL;
6472     unsigned char longcontext[1280];
6473     int test_longcontext = fips_provider_version_ge(libctx, 3, 3, 0);
6474     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80], ckeymat4[80];
6475     unsigned char skeymat1[80], skeymat2[80], skeymat3[80], skeymat4[80];
6476     size_t labellen;
6477     const int protocols[] = {
6478         TLS1_VERSION,
6479         TLS1_1_VERSION,
6480         TLS1_2_VERSION,
6481         TLS1_3_VERSION,
6482         TLS1_3_VERSION,
6483         TLS1_3_VERSION
6484     };
6485 
6486 #ifdef OPENSSL_NO_TLS1
6487     if (tst == 0)
6488         return 1;
6489 #endif
6490 #ifdef OPENSSL_NO_TLS1_1
6491     if (tst == 1)
6492         return 1;
6493 #endif
6494     if (is_fips && (tst == 0 || tst == 1))
6495         return 1;
6496 #ifdef OPENSSL_NO_TLS1_2
6497     if (tst == 2)
6498         return 1;
6499 #endif
6500 #ifdef OSSL_NO_USABLE_TLS1_3
6501     if (tst >= 3)
6502         return 1;
6503 #endif
6504     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6505                                        TLS_client_method(), TLS1_VERSION, 0,
6506                                        &sctx, &cctx, cert, privkey)))
6507         goto end;
6508 
6509     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
6510     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
6511     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
6512     if ((protocols[tst] < TLS1_2_VERSION) &&
6513         (!SSL_CTX_set_cipher_list(cctx, "DEFAULT:@SECLEVEL=0")
6514         || !SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
6515         goto end;
6516 
6517     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6518                                       NULL)))
6519         goto end;
6520 
6521     /*
6522      * Premature call of SSL_export_keying_material should just fail.
6523      */
6524     if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6525                                                 sizeof(ckeymat1), label,
6526                                                 SMALL_LABEL_LEN + 1, context,
6527                                                 sizeof(context) - 1, 1), 0))
6528         goto end;
6529 
6530     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6531                                          SSL_ERROR_NONE)))
6532         goto end;
6533 
6534     if (tst == 5) {
6535         /*
6536          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
6537          * go over that.
6538          */
6539         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
6540                                                     sizeof(ckeymat1), label,
6541                                                     LONG_LABEL_LEN + 1, context,
6542                                                     sizeof(context) - 1, 1), 0))
6543             goto end;
6544 
6545         testresult = 1;
6546         goto end;
6547     } else if (tst == 4) {
6548         labellen = LONG_LABEL_LEN;
6549     } else {
6550         labellen = SMALL_LABEL_LEN;
6551     }
6552 
6553     memset(longcontext, 1, sizeof(longcontext));
6554 
6555     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
6556                                                 sizeof(ckeymat1), label,
6557                                                 labellen, context,
6558                                                 sizeof(context) - 1, 1), 1)
6559             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
6560                                                        sizeof(ckeymat2), label,
6561                                                        labellen,
6562                                                        emptycontext,
6563                                                        0, 1), 1)
6564             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
6565                                                        sizeof(ckeymat3), label,
6566                                                        labellen,
6567                                                        NULL, 0, 0), 1)
6568             || (test_longcontext
6569                 && !TEST_int_eq(SSL_export_keying_material(clientssl,
6570                                                            ckeymat4,
6571                                                            sizeof(ckeymat4), label,
6572                                                            labellen,
6573                                                            longcontext,
6574                                                            sizeof(longcontext), 1),
6575                                 1))
6576             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
6577                                                        sizeof(skeymat1), label,
6578                                                        labellen,
6579                                                        context,
6580                                                        sizeof(context) -1, 1),
6581                             1)
6582             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
6583                                                        sizeof(skeymat2), label,
6584                                                        labellen,
6585                                                        emptycontext,
6586                                                        0, 1), 1)
6587             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
6588                                                        sizeof(skeymat3), label,
6589                                                        labellen,
6590                                                        NULL, 0, 0), 1)
6591             || (test_longcontext
6592                 && !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat4,
6593                                                            sizeof(skeymat4), label,
6594                                                            labellen,
6595                                                            longcontext,
6596                                                            sizeof(longcontext), 1),
6597                                 1))
6598                /*
6599                 * Check that both sides created the same key material with the
6600                 * same context.
6601                 */
6602             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6603                             sizeof(skeymat1))
6604                /*
6605                 * Check that both sides created the same key material with an
6606                 * empty context.
6607                 */
6608             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6609                             sizeof(skeymat2))
6610                /*
6611                 * Check that both sides created the same key material without a
6612                 * context.
6613                 */
6614             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
6615                             sizeof(skeymat3))
6616                /*
6617                 * Check that both sides created the same key material with a
6618                 * long context.
6619                 */
6620             || (test_longcontext
6621                 && !TEST_mem_eq(ckeymat4, sizeof(ckeymat4), skeymat4,
6622                                 sizeof(skeymat4)))
6623                /* Different contexts should produce different results */
6624             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6625                             sizeof(ckeymat2)))
6626         goto end;
6627 
6628     /*
6629      * Check that an empty context and no context produce different results in
6630      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
6631      */
6632     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
6633                                   sizeof(ckeymat3)))
6634             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
6635                                          sizeof(ckeymat3))))
6636         goto end;
6637 
6638     testresult = 1;
6639 
6640  end:
6641     SSL_free(serverssl);
6642     SSL_free(clientssl);
6643     SSL_CTX_free(sctx2);
6644     SSL_CTX_free(sctx);
6645     SSL_CTX_free(cctx);
6646 
6647     return testresult;
6648 }
6649 
6650 #ifndef OSSL_NO_USABLE_TLS1_3
6651 /*
6652  * Test that SSL_export_keying_material_early() produces expected
6653  * results. There are no test vectors so all we do is test that both
6654  * sides of the communication produce the same results for different
6655  * protocol versions.
6656  */
test_export_key_mat_early(int idx)6657 static int test_export_key_mat_early(int idx)
6658 {
6659     static const char label[] = "test label";
6660     static const unsigned char context[] = "context";
6661     int testresult = 0;
6662     SSL_CTX *cctx = NULL, *sctx = NULL;
6663     SSL *clientssl = NULL, *serverssl = NULL;
6664     SSL_SESSION *sess = NULL;
6665     const unsigned char *emptycontext = NULL;
6666     unsigned char ckeymat1[80], ckeymat2[80];
6667     unsigned char skeymat1[80], skeymat2[80];
6668     unsigned char buf[1];
6669     size_t readbytes, written;
6670 
6671     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
6672                                         &sess, idx, SHA384_DIGEST_LENGTH)))
6673         goto end;
6674 
6675     /* Here writing 0 length early data is enough. */
6676     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
6677             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
6678                                                 &readbytes),
6679                             SSL_READ_EARLY_DATA_ERROR)
6680             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6681                             SSL_EARLY_DATA_ACCEPTED))
6682         goto end;
6683 
6684     if (!TEST_int_eq(SSL_export_keying_material_early(
6685                      clientssl, ckeymat1, sizeof(ckeymat1), label,
6686                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
6687             || !TEST_int_eq(SSL_export_keying_material_early(
6688                             clientssl, ckeymat2, sizeof(ckeymat2), label,
6689                             sizeof(label) - 1, emptycontext, 0), 1)
6690             || !TEST_int_eq(SSL_export_keying_material_early(
6691                             serverssl, skeymat1, sizeof(skeymat1), label,
6692                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
6693             || !TEST_int_eq(SSL_export_keying_material_early(
6694                             serverssl, skeymat2, sizeof(skeymat2), label,
6695                             sizeof(label) - 1, emptycontext, 0), 1)
6696                /*
6697                 * Check that both sides created the same key material with the
6698                 * same context.
6699                 */
6700             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
6701                             sizeof(skeymat1))
6702                /*
6703                 * Check that both sides created the same key material with an
6704                 * empty context.
6705                 */
6706             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
6707                             sizeof(skeymat2))
6708                /* Different contexts should produce different results */
6709             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
6710                             sizeof(ckeymat2)))
6711         goto end;
6712 
6713     testresult = 1;
6714 
6715  end:
6716     SSL_SESSION_free(sess);
6717     SSL_SESSION_free(clientpsk);
6718     SSL_SESSION_free(serverpsk);
6719     clientpsk = serverpsk = NULL;
6720     SSL_free(serverssl);
6721     SSL_free(clientssl);
6722     SSL_CTX_free(sctx);
6723     SSL_CTX_free(cctx);
6724 
6725     return testresult;
6726 }
6727 
6728 #define NUM_KEY_UPDATE_MESSAGES 40
6729 /*
6730  * Test KeyUpdate.
6731  */
test_key_update(void)6732 static int test_key_update(void)
6733 {
6734     SSL_CTX *cctx = NULL, *sctx = NULL;
6735     SSL *clientssl = NULL, *serverssl = NULL;
6736     int testresult = 0, i, j;
6737     char buf[20];
6738     static char *mess = "A test message";
6739 
6740     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6741                                        TLS_client_method(),
6742                                        TLS1_3_VERSION,
6743                                        0,
6744                                        &sctx, &cctx, cert, privkey))
6745             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6746                                              NULL, NULL))
6747             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6748                                                 SSL_ERROR_NONE)))
6749         goto end;
6750 
6751     for (j = 0; j < 2; j++) {
6752         /* Send lots of KeyUpdate messages */
6753         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
6754             if (!TEST_true(SSL_key_update(clientssl,
6755                                           (j == 0)
6756                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
6757                                           : SSL_KEY_UPDATE_REQUESTED))
6758                     || !TEST_true(SSL_do_handshake(clientssl)))
6759                 goto end;
6760         }
6761 
6762         /* Check that sending and receiving app data is ok */
6763         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
6764                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
6765                                          strlen(mess)))
6766             goto end;
6767 
6768         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
6769                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
6770                                          strlen(mess)))
6771             goto end;
6772     }
6773 
6774     testresult = 1;
6775 
6776  end:
6777     SSL_free(serverssl);
6778     SSL_free(clientssl);
6779     SSL_CTX_free(sctx);
6780     SSL_CTX_free(cctx);
6781 
6782     return testresult;
6783 }
6784 
6785 /*
6786  * Test we can handle a KeyUpdate (update requested) message while
6787  * write data is pending in peer.
6788  * Test 0: Client sends KeyUpdate while Server is writing
6789  * Test 1: Server sends KeyUpdate while Client is writing
6790  */
test_key_update_peer_in_write(int tst)6791 static int test_key_update_peer_in_write(int tst)
6792 {
6793     SSL_CTX *cctx = NULL, *sctx = NULL;
6794     SSL *clientssl = NULL, *serverssl = NULL;
6795     int testresult = 0;
6796     char buf[20];
6797     static char *mess = "A test message";
6798     BIO *bretry = BIO_new(bio_s_always_retry());
6799     BIO *tmp = NULL;
6800     SSL *peerupdate = NULL, *peerwrite = NULL;
6801 
6802     if (!TEST_ptr(bretry)
6803             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6804                                               TLS_client_method(),
6805                                               TLS1_3_VERSION,
6806                                               0,
6807                                               &sctx, &cctx, cert, privkey))
6808             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6809                                              NULL, NULL))
6810             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6811                                                 SSL_ERROR_NONE)))
6812         goto end;
6813 
6814     peerupdate = tst == 0 ? clientssl : serverssl;
6815     peerwrite = tst == 0 ? serverssl : clientssl;
6816 
6817     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
6818             || !TEST_int_eq(SSL_do_handshake(peerupdate), 1))
6819         goto end;
6820 
6821     /* Swap the writing endpoint's write BIO to force a retry */
6822     tmp = SSL_get_wbio(peerwrite);
6823     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6824         tmp = NULL;
6825         goto end;
6826     }
6827     SSL_set0_wbio(peerwrite, bretry);
6828     bretry = NULL;
6829 
6830     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
6831     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
6832             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE)
6833             || !TEST_true(SSL_want_write(peerwrite))
6834             || !TEST_true(SSL_net_write_desired(peerwrite)))
6835         goto end;
6836 
6837     /* Reinstate the original writing endpoint's write BIO */
6838     SSL_set0_wbio(peerwrite, tmp);
6839     tmp = NULL;
6840 
6841     /* Now read some data - we will read the key update */
6842     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
6843             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ)
6844             || !TEST_true(SSL_want_read(peerwrite))
6845             || !TEST_true(SSL_net_read_desired(peerwrite)))
6846         goto end;
6847 
6848     /*
6849      * Complete the write we started previously and read it from the other
6850      * endpoint
6851      */
6852     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6853             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6854         goto end;
6855 
6856     /* Write more data to ensure we send the KeyUpdate message back */
6857     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
6858             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
6859         goto end;
6860 
6861     if (!TEST_false(SSL_net_read_desired(peerwrite))
6862         || !TEST_false(SSL_net_write_desired(peerwrite))
6863         || !TEST_int_eq(SSL_want(peerwrite), SSL_NOTHING))
6864         goto end;
6865 
6866     testresult = 1;
6867 
6868  end:
6869     SSL_free(serverssl);
6870     SSL_free(clientssl);
6871     SSL_CTX_free(sctx);
6872     SSL_CTX_free(cctx);
6873     BIO_free(bretry);
6874     BIO_free(tmp);
6875 
6876     return testresult;
6877 }
6878 
6879 /*
6880  * Test we can handle a KeyUpdate (update requested) message while
6881  * peer read data is pending after peer accepted keyupdate(the msg header
6882  * had been read 5 bytes).
6883  * Test 0: Client sends KeyUpdate while Server is reading
6884  * Test 1: Server sends KeyUpdate while Client is reading
6885  */
test_key_update_peer_in_read(int tst)6886 static int test_key_update_peer_in_read(int tst)
6887 {
6888     SSL_CTX *cctx = NULL, *sctx = NULL;
6889     SSL *clientssl = NULL, *serverssl = NULL;
6890     int testresult = 0;
6891     char prbuf[515], lwbuf[515] = {0};
6892     static char *mess = "A test message";
6893     BIO *lbio = NULL, *pbio = NULL;
6894     SSL *local = NULL, *peer = NULL;
6895 
6896     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6897                                               TLS_client_method(),
6898                                               TLS1_3_VERSION,
6899                                               0,
6900                                               &sctx, &cctx, cert, privkey))
6901             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6902                                              NULL, NULL))
6903             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6904                                                 SSL_ERROR_NONE)))
6905         goto end;
6906 
6907     local = tst == 0 ? clientssl : serverssl;
6908     peer = tst == 0 ? serverssl : clientssl;
6909 
6910     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
6911         goto end;
6912 
6913     SSL_set_bio(local, lbio, lbio);
6914     SSL_set_bio(peer, pbio, pbio);
6915 
6916     /*
6917      * we first write keyupdate msg then appdata in local
6918      * write data in local will fail with SSL_ERROR_WANT_WRITE,because
6919      * lwbuf app data msg size + key updata msg size > 512(the size of
6920      * the bio pair buffer)
6921      */
6922     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
6923             || !TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), -1)
6924             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
6925         goto end;
6926 
6927     /*
6928      * first read keyupdate msg in peer in peer
6929      * then read appdata that we know will fail with SSL_ERROR_WANT_READ
6930      */
6931     if (!TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), -1)
6932             || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_READ))
6933         goto end;
6934 
6935     /* Now write some data in peer - we will write the key update */
6936     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess)))
6937         goto end;
6938 
6939     /*
6940      * write data in local previously that we will complete
6941      * read data in peer previously that we will complete
6942      */
6943     if (!TEST_int_eq(SSL_write(local, lwbuf, sizeof(lwbuf)), sizeof(lwbuf))
6944             || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), sizeof(prbuf)))
6945         goto end;
6946 
6947     /* check that sending and receiving appdata ok */
6948     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
6949             || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
6950         goto end;
6951 
6952     testresult = 1;
6953 
6954  end:
6955     SSL_free(serverssl);
6956     SSL_free(clientssl);
6957     SSL_CTX_free(sctx);
6958     SSL_CTX_free(cctx);
6959 
6960     return testresult;
6961 }
6962 
6963 /*
6964  * Test we can't send a KeyUpdate (update requested) message while
6965  * local write data is pending.
6966  * Test 0: Client sends KeyUpdate while Client is writing
6967  * Test 1: Server sends KeyUpdate while Server is writing
6968  */
test_key_update_local_in_write(int tst)6969 static int test_key_update_local_in_write(int tst)
6970 {
6971     SSL_CTX *cctx = NULL, *sctx = NULL;
6972     SSL *clientssl = NULL, *serverssl = NULL;
6973     int testresult = 0;
6974     char buf[20];
6975     static char *mess = "A test message";
6976     BIO *bretry = BIO_new(bio_s_always_retry());
6977     BIO *tmp = NULL;
6978     SSL *local = NULL, *peer = NULL;
6979 
6980     if (!TEST_ptr(bretry)
6981             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6982                                               TLS_client_method(),
6983                                               TLS1_3_VERSION,
6984                                               0,
6985                                               &sctx, &cctx, cert, privkey))
6986             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6987                                              NULL, NULL))
6988             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6989                                                 SSL_ERROR_NONE)))
6990         goto end;
6991 
6992     local = tst == 0 ? clientssl : serverssl;
6993     peer = tst == 0 ? serverssl : clientssl;
6994 
6995     /* Swap the writing endpoint's write BIO to force a retry */
6996     tmp = SSL_get_wbio(local);
6997     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
6998         tmp = NULL;
6999         goto end;
7000     }
7001     SSL_set0_wbio(local, bretry);
7002     bretry = NULL;
7003 
7004     /* write data in local will fail with SSL_ERROR_WANT_WRITE */
7005     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), -1)
7006             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_WRITE))
7007         goto end;
7008 
7009     /* Reinstate the original writing endpoint's write BIO */
7010     SSL_set0_wbio(local, tmp);
7011     tmp = NULL;
7012 
7013     /* SSL_key_update will fail, because writing in local*/
7014     if (!TEST_false(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7015         || !TEST_int_eq(ERR_GET_REASON(ERR_peek_error()), SSL_R_BAD_WRITE_RETRY))
7016     goto end;
7017 
7018     ERR_clear_error();
7019     /* write data in local previously that we will complete */
7020     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess)))
7021         goto end;
7022 
7023     /* SSL_key_update will succeed because there is no pending write data */
7024     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7025         || !TEST_int_eq(SSL_do_handshake(local), 1))
7026         goto end;
7027 
7028     /*
7029      * we write some appdata in local
7030      * read data in peer - we will read the keyupdate msg
7031      */
7032     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7033         || !TEST_int_eq(SSL_read(peer, buf, sizeof(buf)), strlen(mess)))
7034         goto end;
7035 
7036     /* Write more peer more data to ensure we send the keyupdate message back */
7037     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7038             || !TEST_int_eq(SSL_read(local, buf, sizeof(buf)), strlen(mess)))
7039         goto end;
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     BIO_free(bretry);
7049     BIO_free(tmp);
7050 
7051     return testresult;
7052 }
7053 
7054 /*
7055  * Test we can handle a KeyUpdate (update requested) message while
7056  * local read data is pending(the msg header had been read 5 bytes).
7057  * Test 0: Client sends KeyUpdate while Client is reading
7058  * Test 1: Server sends KeyUpdate while Server is reading
7059  */
test_key_update_local_in_read(int tst)7060 static int test_key_update_local_in_read(int tst)
7061 {
7062     SSL_CTX *cctx = NULL, *sctx = NULL;
7063     SSL *clientssl = NULL, *serverssl = NULL;
7064     int testresult = 0;
7065     char lrbuf[515], pwbuf[515] = {0}, prbuf[20];
7066     static char *mess = "A test message";
7067     BIO *lbio = NULL, *pbio = NULL;
7068     SSL *local = NULL, *peer = NULL;
7069 
7070     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7071                                               TLS_client_method(),
7072                                               TLS1_3_VERSION,
7073                                               0,
7074                                               &sctx, &cctx, cert, privkey))
7075             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7076                                              NULL, NULL))
7077             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7078                                                 SSL_ERROR_NONE)))
7079         goto end;
7080 
7081     local = tst == 0 ? clientssl : serverssl;
7082     peer = tst == 0 ? serverssl : clientssl;
7083 
7084     if (!TEST_int_eq(BIO_new_bio_pair(&lbio, 512, &pbio, 512), 1))
7085         goto end;
7086 
7087     SSL_set_bio(local, lbio, lbio);
7088     SSL_set_bio(peer, pbio, pbio);
7089 
7090     /* write app data in peer will fail with SSL_ERROR_WANT_WRITE */
7091     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), -1)
7092         || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_WANT_WRITE))
7093         goto end;
7094 
7095     /* read appdata in local will fail with SSL_ERROR_WANT_READ */
7096     if (!TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), -1)
7097             || !TEST_int_eq(SSL_get_error(local, -1), SSL_ERROR_WANT_READ))
7098         goto end;
7099 
7100     /* SSL_do_handshake will send keyupdate msg */
7101     if (!TEST_true(SSL_key_update(local, SSL_KEY_UPDATE_REQUESTED))
7102             || !TEST_int_eq(SSL_do_handshake(local), 1))
7103         goto end;
7104 
7105     /*
7106      * write data in peer previously that we will complete
7107      * read data in local previously that we will complete
7108      */
7109     if (!TEST_int_eq(SSL_write(peer, pwbuf, sizeof(pwbuf)), sizeof(pwbuf))
7110         || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), sizeof(lrbuf)))
7111         goto end;
7112 
7113     /*
7114      * write data in local
7115      * read data in peer - we will read the key update
7116      */
7117     if (!TEST_int_eq(SSL_write(local, mess, strlen(mess)), strlen(mess))
7118         || !TEST_int_eq(SSL_read(peer, prbuf, sizeof(prbuf)), strlen(mess)))
7119         goto end;
7120 
7121   /* Write more peer data to ensure we send the keyupdate message back */
7122     if (!TEST_int_eq(SSL_write(peer, mess, strlen(mess)), strlen(mess))
7123             || !TEST_int_eq(SSL_read(local, lrbuf, sizeof(lrbuf)), strlen(mess)))
7124         goto end;
7125 
7126     testresult = 1;
7127 
7128  end:
7129     SSL_free(serverssl);
7130     SSL_free(clientssl);
7131     SSL_CTX_free(sctx);
7132     SSL_CTX_free(cctx);
7133 
7134     return testresult;
7135 }
7136 #endif /* OSSL_NO_USABLE_TLS1_3 */
7137 
7138 /*
7139  * Test clearing a connection via SSL_clear(), or resetting it via
7140  * SSL_set_connect_state()/SSL_set_accept_state()
7141  * Test 0: SSL_set_connect_state, TLSv1.3
7142  * Test 1: SSL_set_connect_state, TLSv1.2
7143  * Test 2: SSL_set_accept_state, TLSv1.3
7144  * Test 3: SSL_set_accept_state, TLSv1.2
7145  * Test 4: SSL_clear (client), TLSv1.3
7146  * Test 5: SSL_clear (client), TLSv1.2
7147  * Test 6: SSL_clear (server), TLSv1.3
7148  * Test 7: SSL_clear (server), TLSv1.2
7149  */
test_ssl_clear(int idx)7150 static int test_ssl_clear(int idx)
7151 {
7152     SSL_CTX *cctx = NULL, *sctx = NULL;
7153     SSL *clientssl = NULL, *serverssl = NULL;
7154     SSL *writer, *reader;
7155     int testresult = 0;
7156     int tls12test, servertest, cleartest;
7157     size_t written, readbytes;
7158     const char *msg = "Hello World";
7159     unsigned char buf[5];
7160 
7161     tls12test = idx & 1;
7162     idx >>= 1;
7163     servertest = idx & 1;
7164     idx >>= 1;
7165     cleartest = idx & 1;
7166 
7167 #ifdef OPENSSL_NO_TLS1_2
7168     if (tls12test == 1)
7169         return TEST_skip("No TLSv1.2 in this build");
7170 #endif
7171 
7172     /* Create an initial connection */
7173     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7174                                        TLS_client_method(), TLS1_VERSION, 0,
7175                                        &sctx, &cctx, cert, privkey))
7176             || (tls12test
7177                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
7178                                                             TLS1_2_VERSION)))
7179             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
7180                                           &clientssl, NULL, NULL))
7181             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7182                                                 SSL_ERROR_NONE)))
7183         goto end;
7184 
7185     if (servertest) {
7186         writer = clientssl;
7187         reader = serverssl;
7188     } else {
7189         writer = serverssl;
7190         reader = clientssl;
7191     }
7192 
7193     /* Write some data */
7194     if (!TEST_true(SSL_write_ex(writer, msg, strlen(msg), &written))
7195             || written != strlen(msg))
7196         goto end;
7197 
7198     /*
7199      * Read a partial record. The remaining buffered data should be cleared by
7200      * the subsequent clear/reset
7201      */
7202     if (!TEST_true(SSL_read_ex(reader, buf, sizeof(buf), &readbytes))
7203             || readbytes != sizeof(buf))
7204         goto end;
7205 
7206     SSL_shutdown(clientssl);
7207     SSL_shutdown(serverssl);
7208 
7209     /* Reset/clear one SSL object in order to reuse it. We free the other one */
7210     if (servertest) {
7211         if (cleartest) {
7212             if (!TEST_true(SSL_clear(serverssl)))
7213                 goto end;
7214         } else {
7215             SSL_set_accept_state(serverssl);
7216         }
7217         /*
7218          * A peculiarity of SSL_clear() is that it does not clear the session.
7219          * This is intended behaviour so that a client can create a new
7220          * connection and reuse the session. But this doesn't make much sense
7221          * on the server side - and causes incorrect behaviour due to the
7222          * handshake failing (even though the documentation does say SSL_clear()
7223          * is supposed to work on the server side). We clear the session
7224          * explicitly - although note that the documentation for
7225          * SSL_set_session() says that its only useful for clients!
7226          */
7227         if (!TEST_true(SSL_set_session(serverssl, NULL)))
7228             goto end;
7229         SSL_free(clientssl);
7230         clientssl = NULL;
7231     } else {
7232         if (cleartest) {
7233             if (!TEST_true(SSL_clear(clientssl)))
7234                 goto end;
7235         } else {
7236             SSL_set_connect_state(clientssl);
7237         }
7238         SSL_free(serverssl);
7239         serverssl = NULL;
7240     }
7241 
7242     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7243                                              NULL, NULL))
7244             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7245                                                 SSL_ERROR_NONE))
7246             || !TEST_true(servertest || SSL_session_reused(clientssl)))
7247         goto end;
7248 
7249     SSL_shutdown(clientssl);
7250     SSL_shutdown(serverssl);
7251 
7252     testresult = 1;
7253 
7254  end:
7255     SSL_free(serverssl);
7256     SSL_free(clientssl);
7257     SSL_CTX_free(sctx);
7258     SSL_CTX_free(cctx);
7259 
7260     return testresult;
7261 }
7262 
7263 /* Parse CH and retrieve any MFL extension value if present */
get_MFL_from_client_hello(BIO * bio,int * mfl_codemfl_code)7264 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
7265 {
7266     long len;
7267     unsigned char *data;
7268     PACKET pkt, pkt2, pkt3;
7269     unsigned int MFL_code = 0, type = 0;
7270 
7271     if (!TEST_uint_gt(len = BIO_get_mem_data(bio, (char **) &data), 0))
7272         goto end;
7273 
7274     memset(&pkt, 0, sizeof(pkt));
7275     memset(&pkt2, 0, sizeof(pkt2));
7276     memset(&pkt3, 0, sizeof(pkt3));
7277 
7278     if (!TEST_long_gt(len, 0)
7279             || !TEST_true(PACKET_buf_init(&pkt, data, len))
7280                /* Skip the record header */
7281             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
7282                /* Skip the handshake message header */
7283             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
7284                /* Skip client version and random */
7285             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
7286                                                + SSL3_RANDOM_SIZE))
7287                /* Skip session id */
7288             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7289                /* Skip ciphers */
7290             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
7291                /* Skip compression */
7292             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
7293                /* Extensions len */
7294             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
7295         goto end;
7296 
7297     /* Loop through all extensions */
7298     while (PACKET_remaining(&pkt2)) {
7299         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
7300                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
7301             goto end;
7302 
7303         if (type == TLSEXT_TYPE_max_fragment_length) {
7304             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
7305                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
7306                 goto end;
7307 
7308             *mfl_codemfl_code = MFL_code;
7309             return 1;
7310         }
7311     }
7312 
7313  end:
7314     return 0;
7315 }
7316 
7317 /* Maximum-Fragment-Length TLS extension mode to test */
7318 static const unsigned char max_fragment_len_test[] = {
7319     TLSEXT_max_fragment_length_512,
7320     TLSEXT_max_fragment_length_1024,
7321     TLSEXT_max_fragment_length_2048,
7322     TLSEXT_max_fragment_length_4096
7323 };
7324 
test_max_fragment_len_ext(int idx_tst)7325 static int test_max_fragment_len_ext(int idx_tst)
7326 {
7327     SSL_CTX *ctx = NULL;
7328     SSL *con = NULL;
7329     int testresult = 0, MFL_mode = 0;
7330     BIO *rbio, *wbio;
7331 
7332     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL, TLS_client_method(),
7333                                        TLS1_VERSION, 0, NULL, &ctx, NULL,
7334                                        NULL)))
7335         return 0;
7336 
7337     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
7338                    ctx, max_fragment_len_test[idx_tst])))
7339         goto end;
7340 
7341     con = SSL_new(ctx);
7342     if (!TEST_ptr(con))
7343         goto end;
7344 
7345     rbio = BIO_new(BIO_s_mem());
7346     wbio = BIO_new(BIO_s_mem());
7347     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
7348         BIO_free(rbio);
7349         BIO_free(wbio);
7350         goto end;
7351     }
7352 
7353     SSL_set_bio(con, rbio, wbio);
7354 
7355     if (!TEST_int_le(SSL_connect(con), 0)) {
7356         /* This shouldn't succeed because we don't have a server! */
7357         goto end;
7358     }
7359 
7360     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
7361         /* no MFL in client hello */
7362         goto end;
7363     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
7364         goto end;
7365 
7366     testresult = 1;
7367 
7368 end:
7369     SSL_free(con);
7370     SSL_CTX_free(ctx);
7371 
7372     return testresult;
7373 }
7374 
7375 #ifndef OSSL_NO_USABLE_TLS1_3
test_pha_key_update(void)7376 static int test_pha_key_update(void)
7377 {
7378     SSL_CTX *cctx = NULL, *sctx = NULL;
7379     SSL *clientssl = NULL, *serverssl = NULL;
7380     int testresult = 0;
7381 
7382     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7383                                        TLS_client_method(), TLS1_VERSION, 0,
7384                                        &sctx, &cctx, cert, privkey)))
7385         return 0;
7386 
7387     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
7388         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
7389         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
7390         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
7391         goto end;
7392 
7393     SSL_CTX_set_post_handshake_auth(cctx, 1);
7394 
7395     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7396                                       NULL, NULL)))
7397         goto end;
7398 
7399     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7400                                          SSL_ERROR_NONE)))
7401         goto end;
7402 
7403     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
7404     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
7405         goto end;
7406 
7407     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
7408         goto end;
7409 
7410     /* Start handshake on the server */
7411     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
7412         goto end;
7413 
7414     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
7415     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
7416                                          SSL_ERROR_NONE)))
7417         goto end;
7418 
7419     SSL_shutdown(clientssl);
7420     SSL_shutdown(serverssl);
7421 
7422     testresult = 1;
7423 
7424  end:
7425     SSL_free(serverssl);
7426     SSL_free(clientssl);
7427     SSL_CTX_free(sctx);
7428     SSL_CTX_free(cctx);
7429     return testresult;
7430 }
7431 #endif
7432 
7433 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7434 
7435 static SRP_VBASE *vbase = NULL;
7436 
ssl_srp_cb(SSL * s,int * ad,void * arg)7437 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
7438 {
7439     int ret = SSL3_AL_FATAL;
7440     char *username;
7441     SRP_user_pwd *user = NULL;
7442 
7443     username = SSL_get_srp_username(s);
7444     if (username == NULL) {
7445         *ad = SSL_AD_INTERNAL_ERROR;
7446         goto err;
7447     }
7448 
7449     user = SRP_VBASE_get1_by_user(vbase, username);
7450     if (user == NULL) {
7451         *ad = SSL_AD_INTERNAL_ERROR;
7452         goto err;
7453     }
7454 
7455     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
7456                                  user->info) <= 0) {
7457         *ad = SSL_AD_INTERNAL_ERROR;
7458         goto err;
7459     }
7460 
7461     ret = 0;
7462 
7463  err:
7464     SRP_user_pwd_free(user);
7465     return ret;
7466 }
7467 
create_new_vfile(char * userid,char * password,const char * filename)7468 static int create_new_vfile(char *userid, char *password, const char *filename)
7469 {
7470     char *gNid = NULL;
7471     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
7472     TXT_DB *db = NULL;
7473     int ret = 0;
7474     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
7475     size_t i;
7476 
7477     if (!TEST_ptr(dummy) || !TEST_ptr(row))
7478         goto end;
7479 
7480     gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
7481                                   &row[DB_srpverifier], NULL, NULL, libctx, NULL);
7482     if (!TEST_ptr(gNid))
7483         goto end;
7484 
7485     /*
7486      * The only way to create an empty TXT_DB is to provide a BIO with no data
7487      * in it!
7488      */
7489     db = TXT_DB_read(dummy, DB_NUMBER);
7490     if (!TEST_ptr(db))
7491         goto end;
7492 
7493     out = BIO_new_file(filename, "w");
7494     if (!TEST_ptr(out))
7495         goto end;
7496 
7497     row[DB_srpid] = OPENSSL_strdup(userid);
7498     row[DB_srptype] = OPENSSL_strdup("V");
7499     row[DB_srpgN] = OPENSSL_strdup(gNid);
7500 
7501     if (!TEST_ptr(row[DB_srpid])
7502             || !TEST_ptr(row[DB_srptype])
7503             || !TEST_ptr(row[DB_srpgN])
7504             || !TEST_true(TXT_DB_insert(db, row)))
7505         goto end;
7506 
7507     row = NULL;
7508 
7509     if (TXT_DB_write(out, db) <= 0)
7510         goto end;
7511 
7512     ret = 1;
7513  end:
7514     if (row != NULL) {
7515         for (i = 0; i < DB_NUMBER; i++)
7516             OPENSSL_free(row[i]);
7517     }
7518     OPENSSL_free(row);
7519     BIO_free(dummy);
7520     BIO_free(out);
7521     TXT_DB_free(db);
7522 
7523     return ret;
7524 }
7525 
create_new_vbase(char * userid,char * password)7526 static int create_new_vbase(char *userid, char *password)
7527 {
7528     BIGNUM *verifier = NULL, *salt = NULL;
7529     const SRP_gN *lgN = NULL;
7530     SRP_user_pwd *user_pwd = NULL;
7531     int ret = 0;
7532 
7533     lgN = SRP_get_default_gN(NULL);
7534     if (!TEST_ptr(lgN))
7535         goto end;
7536 
7537     if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
7538                                              lgN->N, lgN->g, libctx, NULL)))
7539         goto end;
7540 
7541     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
7542     if (!TEST_ptr(user_pwd))
7543         goto end;
7544 
7545     user_pwd->N = lgN->N;
7546     user_pwd->g = lgN->g;
7547     user_pwd->id = OPENSSL_strdup(userid);
7548     if (!TEST_ptr(user_pwd->id))
7549         goto end;
7550 
7551     user_pwd->v = verifier;
7552     user_pwd->s = salt;
7553     verifier = salt = NULL;
7554 
7555     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
7556         goto end;
7557     user_pwd = NULL;
7558 
7559     ret = 1;
7560 end:
7561     SRP_user_pwd_free(user_pwd);
7562     BN_free(salt);
7563     BN_free(verifier);
7564 
7565     return ret;
7566 }
7567 
7568 /*
7569  * SRP tests
7570  *
7571  * Test 0: Simple successful SRP connection, new vbase
7572  * Test 1: Connection failure due to bad password, new vbase
7573  * Test 2: Simple successful SRP connection, vbase loaded from existing file
7574  * Test 3: Connection failure due to bad password, vbase loaded from existing
7575  *         file
7576  * Test 4: Simple successful SRP connection, vbase loaded from new file
7577  * Test 5: Connection failure due to bad password, vbase loaded from new file
7578  */
test_srp(int tst)7579 static int test_srp(int tst)
7580 {
7581     char *userid = "test", *password = "password", *tstsrpfile;
7582     SSL_CTX *cctx = NULL, *sctx = NULL;
7583     SSL *clientssl = NULL, *serverssl = NULL;
7584     int ret, testresult = 0;
7585 
7586     vbase = SRP_VBASE_new(NULL);
7587     if (!TEST_ptr(vbase))
7588         goto end;
7589 
7590     if (tst == 0 || tst == 1) {
7591         if (!TEST_true(create_new_vbase(userid, password)))
7592             goto end;
7593     } else {
7594         if (tst == 4 || tst == 5) {
7595             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
7596                 goto end;
7597             tstsrpfile = tmpfilename;
7598         } else {
7599             tstsrpfile = srpvfile;
7600         }
7601         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
7602             goto end;
7603     }
7604 
7605     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7606                                        TLS_client_method(), TLS1_VERSION, 0,
7607                                        &sctx, &cctx, cert, privkey)))
7608         goto end;
7609 
7610     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
7611             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
7612             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
7613             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
7614             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
7615         goto end;
7616 
7617     if (tst % 2 == 1) {
7618         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
7619             goto end;
7620     } else {
7621         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
7622             goto end;
7623     }
7624 
7625     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7626                                       NULL, NULL)))
7627         goto end;
7628 
7629     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
7630     if (ret) {
7631         if (!TEST_true(tst % 2 == 0))
7632             goto end;
7633     } else {
7634         if (!TEST_true(tst % 2 == 1))
7635             goto end;
7636     }
7637 
7638     testresult = 1;
7639 
7640  end:
7641     SRP_VBASE_free(vbase);
7642     vbase = NULL;
7643     SSL_free(serverssl);
7644     SSL_free(clientssl);
7645     SSL_CTX_free(sctx);
7646     SSL_CTX_free(cctx);
7647 
7648     return testresult;
7649 }
7650 #endif
7651 
7652 static int info_cb_failed = 0;
7653 static int info_cb_offset = 0;
7654 static int info_cb_this_state = -1;
7655 
7656 static struct info_cb_states_st {
7657     int where;
7658     const char *statestr;
7659 } info_cb_states[][60] = {
7660     {
7661         /* TLSv1.2 server followed by resumption */
7662         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7663         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7664         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
7665         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
7666         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
7667         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7668         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7669         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7670         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"},
7671         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7672         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
7673         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7674         {SSL_CB_EXIT, NULL}, {0, NULL},
7675     }, {
7676         /* TLSv1.2 client followed by resumption */
7677         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7678         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7679         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
7680         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
7681         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
7682         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7683         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7684         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7685         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7686         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
7687         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
7688         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
7689     }, {
7690         /* TLSv1.3 server followed by resumption */
7691         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7692         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7693         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
7694         {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
7695         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
7696         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7697         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7698         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7699         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7700         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7701         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
7702         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7703         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7704     }, {
7705         /* TLSv1.3 client followed by resumption */
7706         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7707         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7708         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
7709         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
7710         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
7711         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7712         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"},
7713         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
7714         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7715         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
7716         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
7717         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7718         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7719         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"},
7720         {SSL_CB_EXIT, NULL}, {0, NULL},
7721     }, {
7722         /* TLSv1.3 server, early_data */
7723         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7724         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7725         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7726         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7727         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7728         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
7729         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7730         {SSL_CB_EXIT, NULL}, {0, NULL},
7731     }, {
7732         /* TLSv1.3 client, early_data */
7733         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7734         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
7735         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7736         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
7737         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
7738         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
7739         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7740         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7741         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7742     }, {
7743         /* TLSv1.3 server, certificate compression, followed by resumption */
7744         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7745         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7746         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSCC"},
7747         {SSL_CB_LOOP, "TWSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
7748         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
7749         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
7750         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
7751         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7752         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
7753         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
7754         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
7755         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
7756         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
7757     }, {
7758         /* TLSv1.3 client, certificate compression, followed by resumption */
7759         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT"},
7760         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
7761         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSCC"},
7762         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
7763         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
7764         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"},
7765         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK"},
7766         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
7767         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
7768         {SSL_CB_LOOP, "PINIT"}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
7769         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
7770         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
7771         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
7772         {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "SSLOK"}, {SSL_CB_LOOP, "TRST"},
7773         {SSL_CB_EXIT, NULL}, {0, NULL},
7774     }, {
7775         {0, NULL},
7776     }
7777 };
7778 
sslapi_info_callback(const SSL * s,int where,int ret)7779 static void sslapi_info_callback(const SSL *s, int where, int ret)
7780 {
7781     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
7782 
7783     /* We do not ever expect a connection to fail in this test */
7784     if (!TEST_false(ret == 0)) {
7785         info_cb_failed = 1;
7786         return;
7787     }
7788 
7789     /*
7790      * Do some sanity checks. We never expect these things to happen in this
7791      * test
7792      */
7793     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
7794             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
7795             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
7796         info_cb_failed = 1;
7797         return;
7798     }
7799 
7800     /* Now check we're in the right state */
7801     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
7802         info_cb_failed = 1;
7803         return;
7804     }
7805     if ((where & SSL_CB_LOOP) != 0
7806             && !TEST_int_eq(strcmp(SSL_state_string(s),
7807                             state[info_cb_this_state].statestr), 0)) {
7808         info_cb_failed = 1;
7809         return;
7810     }
7811 
7812     /*
7813      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
7814      */
7815     if ((where & SSL_CB_HANDSHAKE_DONE)
7816             && SSL_in_init((SSL *)s) != 0) {
7817         info_cb_failed = 1;
7818         return;
7819     }
7820 }
7821 
7822 /*
7823  * Test the info callback gets called when we expect it to.
7824  *
7825  * Test 0: TLSv1.2, server
7826  * Test 1: TLSv1.2, client
7827  * Test 2: TLSv1.3, server
7828  * Test 3: TLSv1.3, client
7829  * Test 4: TLSv1.3, server, early_data
7830  * Test 5: TLSv1.3, client, early_data
7831  * Test 6: TLSv1.3, server, compressed certificate
7832  * Test 7: TLSv1.3, client, compressed certificate
7833  */
test_info_callback(int tst)7834 static int test_info_callback(int tst)
7835 {
7836     SSL_CTX *cctx = NULL, *sctx = NULL;
7837     SSL *clientssl = NULL, *serverssl = NULL;
7838     SSL_SESSION *clntsess = NULL;
7839     int testresult = 0;
7840     int tlsvers;
7841 
7842     if (tst < 2) {
7843 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
7844 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
7845                                     || !defined(OPENSSL_NO_DH))
7846         tlsvers = TLS1_2_VERSION;
7847 #else
7848         return 1;
7849 #endif
7850     } else {
7851 #ifndef OSSL_NO_USABLE_TLS1_3
7852         tlsvers = TLS1_3_VERSION;
7853 #else
7854         return 1;
7855 #endif
7856     }
7857 
7858     /* Reset globals */
7859     info_cb_failed = 0;
7860     info_cb_this_state = -1;
7861     info_cb_offset = tst;
7862 
7863 #ifndef OSSL_NO_USABLE_TLS1_3
7864     if (tst >= 4 && tst < 6) {
7865         SSL_SESSION *sess = NULL;
7866         size_t written, readbytes;
7867         unsigned char buf[80];
7868         OSSL_TIME timer;
7869 
7870         /* early_data tests */
7871         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
7872                                             &serverssl, &sess, 0,
7873                                             SHA384_DIGEST_LENGTH)))
7874             goto end;
7875 
7876         /* We don't actually need this reference */
7877         SSL_SESSION_free(sess);
7878 
7879         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
7880                               sslapi_info_callback);
7881 
7882         /* Write and read some early data and then complete the connection */
7883         timer = ossl_time_now();
7884         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
7885                                             &written))
7886                 || !TEST_size_t_eq(written, strlen(MSG1)))
7887             goto end;
7888 
7889         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf,
7890                                              sizeof(buf), &readbytes),
7891                          SSL_READ_EARLY_DATA_SUCCESS)) {
7892             testresult = check_early_data_timeout(timer);
7893             goto end;
7894         }
7895 
7896         if (!TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
7897                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
7898                                 SSL_EARLY_DATA_ACCEPTED)
7899                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
7900                                                     SSL_ERROR_NONE))
7901                 || !TEST_false(info_cb_failed))
7902             goto end;
7903 
7904         testresult = 1;
7905         goto end;
7906     }
7907 #endif
7908 
7909     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7910                                        TLS_client_method(),
7911                                        tlsvers, tlsvers, &sctx, &cctx, cert,
7912                                        privkey)))
7913         goto end;
7914 
7915     if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
7916         goto end;
7917 
7918     /*
7919      * For even numbered tests we check the server callbacks. For odd numbers we
7920      * check the client.
7921      */
7922     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
7923                               sslapi_info_callback);
7924     if (tst >= 6) {
7925         if (!SSL_CTX_compress_certs(sctx, 0))
7926             goto end;
7927     }
7928 
7929     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
7930                                           &clientssl, NULL, NULL))
7931         || !TEST_true(create_ssl_connection(serverssl, clientssl,
7932                                             SSL_ERROR_NONE))
7933         || !TEST_false(info_cb_failed))
7934     goto end;
7935 
7936 
7937 
7938     clntsess = SSL_get1_session(clientssl);
7939     SSL_shutdown(clientssl);
7940     SSL_shutdown(serverssl);
7941     SSL_free(serverssl);
7942     SSL_free(clientssl);
7943     serverssl = clientssl = NULL;
7944 
7945     /* Now do a resumption */
7946     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
7947                                       NULL))
7948             || !TEST_true(SSL_set_session(clientssl, clntsess))
7949             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7950                                                 SSL_ERROR_NONE))
7951             || !TEST_true(SSL_session_reused(clientssl))
7952             || !TEST_false(info_cb_failed))
7953         goto end;
7954 
7955     testresult = 1;
7956 
7957  end:
7958     SSL_free(serverssl);
7959     SSL_free(clientssl);
7960     SSL_SESSION_free(clntsess);
7961     SSL_CTX_free(sctx);
7962     SSL_CTX_free(cctx);
7963     return testresult;
7964 }
7965 
test_ssl_pending(int tst)7966 static int test_ssl_pending(int tst)
7967 {
7968     SSL_CTX *cctx = NULL, *sctx = NULL;
7969     SSL *clientssl = NULL, *serverssl = NULL;
7970     int testresult = 0;
7971     char msg[] = "A test message";
7972     char buf[5];
7973     size_t written, readbytes;
7974 
7975     if (tst == 0) {
7976         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7977                                            TLS_client_method(),
7978                                            TLS1_VERSION, 0,
7979                                            &sctx, &cctx, cert, privkey)))
7980             goto end;
7981     } else {
7982 #ifndef OPENSSL_NO_DTLS
7983         if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
7984                                            DTLS_client_method(),
7985                                            DTLS1_VERSION, 0,
7986                                            &sctx, &cctx, cert, privkey)))
7987             goto end;
7988 
7989 # ifdef OPENSSL_NO_DTLS1_2
7990         /* Not supported in the FIPS provider */
7991         if (is_fips) {
7992             testresult = 1;
7993             goto end;
7994         };
7995         /*
7996          * Default sigalgs are SHA1 based in <DTLS1.2 which is in security
7997          * level 0
7998          */
7999         if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
8000                 || !TEST_true(SSL_CTX_set_cipher_list(cctx,
8001                                                     "DEFAULT:@SECLEVEL=0")))
8002             goto end;
8003 # endif
8004 #else
8005         return 1;
8006 #endif
8007     }
8008 
8009     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8010                                              NULL, NULL))
8011             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8012                                                 SSL_ERROR_NONE)))
8013         goto end;
8014 
8015     if (!TEST_int_eq(SSL_pending(clientssl), 0)
8016             || !TEST_false(SSL_has_pending(clientssl))
8017             || !TEST_int_eq(SSL_pending(serverssl), 0)
8018             || !TEST_false(SSL_has_pending(serverssl))
8019             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8020             || !TEST_size_t_eq(written, sizeof(msg))
8021             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
8022             || !TEST_size_t_eq(readbytes, sizeof(buf))
8023             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
8024             || !TEST_true(SSL_has_pending(clientssl)))
8025         goto end;
8026 
8027     testresult = 1;
8028 
8029  end:
8030     SSL_free(serverssl);
8031     SSL_free(clientssl);
8032     SSL_CTX_free(sctx);
8033     SSL_CTX_free(cctx);
8034 
8035     return testresult;
8036 }
8037 
8038 static struct {
8039     unsigned int maxprot;
8040     const char *clntciphers;
8041     const char *clnttls13ciphers;
8042     const char *srvrciphers;
8043     const char *srvrtls13ciphers;
8044     const char *shared;
8045     const char *fipsshared;
8046 } shared_ciphers_data[] = {
8047 /*
8048  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
8049  * TLSv1.3 is enabled but TLSv1.2 is disabled.
8050  */
8051 #if defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
8052     {
8053         TLS1_2_VERSION,
8054         "AES128-SHA:AES256-SHA",
8055         NULL,
8056         "AES256-SHA:DHE-RSA-AES128-SHA",
8057         NULL,
8058         "AES256-SHA",
8059         "AES256-SHA"
8060     },
8061 # if !defined(OPENSSL_NO_CHACHA) \
8062      && !defined(OPENSSL_NO_POLY1305) \
8063      && !defined(OPENSSL_NO_EC)
8064     {
8065         TLS1_2_VERSION,
8066         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8067         NULL,
8068         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8069         NULL,
8070         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
8071         "AES128-SHA"
8072     },
8073 # endif
8074     {
8075         TLS1_2_VERSION,
8076         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
8077         NULL,
8078         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
8079         NULL,
8080         "AES128-SHA:AES256-SHA",
8081         "AES128-SHA:AES256-SHA"
8082     },
8083     {
8084         TLS1_2_VERSION,
8085         "AES128-SHA:AES256-SHA",
8086         NULL,
8087         "AES128-SHA:DHE-RSA-AES128-SHA",
8088         NULL,
8089         "AES128-SHA",
8090         "AES128-SHA"
8091     },
8092 #endif
8093 /*
8094  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
8095  * enabled.
8096  */
8097 #if !defined(OSSL_NO_USABLE_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
8098     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
8099     {
8100         TLS1_3_VERSION,
8101         "AES128-SHA:AES256-SHA",
8102         NULL,
8103         "AES256-SHA:AES128-SHA256",
8104         NULL,
8105         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
8106         "TLS_AES_128_GCM_SHA256:AES256-SHA",
8107         "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA"
8108     },
8109 #endif
8110 #ifndef OSSL_NO_USABLE_TLS1_3
8111     {
8112         TLS1_3_VERSION,
8113         "AES128-SHA",
8114         "TLS_AES_256_GCM_SHA384",
8115         "AES256-SHA",
8116         "TLS_AES_256_GCM_SHA384",
8117         "TLS_AES_256_GCM_SHA384",
8118         "TLS_AES_256_GCM_SHA384"
8119     },
8120 #endif
8121 };
8122 
int_test_ssl_get_shared_ciphers(int tst,int clnt)8123 static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
8124 {
8125     SSL_CTX *cctx = NULL, *sctx = NULL;
8126     SSL *clientssl = NULL, *serverssl = NULL;
8127     int testresult = 0;
8128     char buf[1024];
8129     OSSL_LIB_CTX *tmplibctx = OSSL_LIB_CTX_new();
8130 
8131     if (!TEST_ptr(tmplibctx))
8132         goto end;
8133 
8134     /*
8135      * Regardless of whether we're testing with the FIPS provider loaded into
8136      * libctx, we want one peer to always use the full set of ciphersuites
8137      * available. Therefore we use a separate libctx with the default provider
8138      * loaded into it. We run the same tests twice - once with the client side
8139      * having the full set of ciphersuites and once with the server side.
8140      */
8141     if (clnt) {
8142         cctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_client_method());
8143         if (!TEST_ptr(cctx))
8144             goto end;
8145     } else {
8146         sctx = SSL_CTX_new_ex(tmplibctx, NULL, TLS_server_method());
8147         if (!TEST_ptr(sctx))
8148             goto end;
8149     }
8150 
8151     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8152                                        TLS_client_method(),
8153                                        TLS1_VERSION,
8154                                        shared_ciphers_data[tst].maxprot,
8155                                        &sctx, &cctx, cert, privkey)))
8156         goto end;
8157 
8158     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
8159                                         shared_ciphers_data[tst].clntciphers))
8160             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
8161                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
8162                                     shared_ciphers_data[tst].clnttls13ciphers)))
8163             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
8164                                         shared_ciphers_data[tst].srvrciphers))
8165             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
8166                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
8167                                     shared_ciphers_data[tst].srvrtls13ciphers))))
8168         goto end;
8169 
8170 
8171     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8172                                              NULL, NULL))
8173             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8174                                                 SSL_ERROR_NONE)))
8175         goto end;
8176 
8177     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
8178             || !TEST_int_eq(strcmp(buf,
8179                                    is_fips
8180                                    ? shared_ciphers_data[tst].fipsshared
8181                                    : shared_ciphers_data[tst].shared),
8182                                    0)) {
8183         TEST_info("Shared ciphers are: %s\n", buf);
8184         goto end;
8185     }
8186 
8187     testresult = 1;
8188 
8189  end:
8190     SSL_free(serverssl);
8191     SSL_free(clientssl);
8192     SSL_CTX_free(sctx);
8193     SSL_CTX_free(cctx);
8194     OSSL_LIB_CTX_free(tmplibctx);
8195 
8196     return testresult;
8197 }
8198 
test_ssl_get_shared_ciphers(int tst)8199 static int test_ssl_get_shared_ciphers(int tst)
8200 {
8201     return int_test_ssl_get_shared_ciphers(tst, 0)
8202            && int_test_ssl_get_shared_ciphers(tst, 1);
8203 }
8204 
8205 
8206 static const char *appdata = "Hello World";
8207 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
8208 static int tick_key_renew = 0;
8209 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8210 
gen_tick_cb(SSL * s,void * arg)8211 static int gen_tick_cb(SSL *s, void *arg)
8212 {
8213     gen_tick_called = 1;
8214 
8215     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
8216                                            strlen(appdata));
8217 }
8218 
dec_tick_cb(SSL * s,SSL_SESSION * ss,const unsigned char * keyname,size_t keyname_length,SSL_TICKET_STATUS status,void * arg)8219 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
8220                                      const unsigned char *keyname,
8221                                      size_t keyname_length,
8222                                      SSL_TICKET_STATUS status,
8223                                      void *arg)
8224 {
8225     void *tickdata;
8226     size_t tickdlen;
8227 
8228     dec_tick_called = 1;
8229 
8230     if (status == SSL_TICKET_EMPTY)
8231         return SSL_TICKET_RETURN_IGNORE_RENEW;
8232 
8233     if (!TEST_true(status == SSL_TICKET_SUCCESS
8234                    || status == SSL_TICKET_SUCCESS_RENEW))
8235         return SSL_TICKET_RETURN_ABORT;
8236 
8237     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
8238                                                    &tickdlen))
8239             || !TEST_size_t_eq(tickdlen, strlen(appdata))
8240             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
8241         return SSL_TICKET_RETURN_ABORT;
8242 
8243     if (tick_key_cb_called)  {
8244         /* Don't change what the ticket key callback wanted to do */
8245         switch (status) {
8246         case SSL_TICKET_NO_DECRYPT:
8247             return SSL_TICKET_RETURN_IGNORE_RENEW;
8248 
8249         case SSL_TICKET_SUCCESS:
8250             return SSL_TICKET_RETURN_USE;
8251 
8252         case SSL_TICKET_SUCCESS_RENEW:
8253             return SSL_TICKET_RETURN_USE_RENEW;
8254 
8255         default:
8256             return SSL_TICKET_RETURN_ABORT;
8257         }
8258     }
8259     return tick_dec_ret;
8260 
8261 }
8262 
8263 #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)8264 static int tick_key_cb(SSL *s, unsigned char key_name[16],
8265                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
8266                        HMAC_CTX *hctx, int enc)
8267 {
8268     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8269     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
8270     EVP_CIPHER *aes128cbc;
8271     EVP_MD *sha256;
8272     int ret;
8273 
8274     tick_key_cb_called = 1;
8275 
8276     if (tick_key_renew == -1)
8277         return 0;
8278 
8279     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8280     if (!TEST_ptr(aes128cbc))
8281         return 0;
8282     sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
8283     if (!TEST_ptr(sha256)) {
8284         EVP_CIPHER_free(aes128cbc);
8285         return 0;
8286     }
8287 
8288     memset(iv, 0, AES_BLOCK_SIZE);
8289     memset(key_name, 0, 16);
8290     if (aes128cbc == NULL
8291             || sha256 == NULL
8292             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8293             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
8294                              NULL))
8295         ret = -1;
8296     else
8297         ret = tick_key_renew ? 2 : 1;
8298 
8299     EVP_CIPHER_free(aes128cbc);
8300     EVP_MD_free(sha256);
8301 
8302     return ret;
8303 }
8304 #endif
8305 
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)8306 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
8307                            unsigned char iv[EVP_MAX_IV_LENGTH],
8308                            EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
8309 {
8310     const unsigned char tick_aes_key[16] = "0123456789abcdef";
8311     unsigned char tick_hmac_key[16] = "0123456789abcdef";
8312     OSSL_PARAM params[2];
8313     EVP_CIPHER *aes128cbc;
8314     int ret;
8315 
8316     tick_key_cb_called = 1;
8317 
8318     if (tick_key_renew == -1)
8319         return 0;
8320 
8321     aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
8322     if (!TEST_ptr(aes128cbc))
8323         return 0;
8324 
8325     memset(iv, 0, AES_BLOCK_SIZE);
8326     memset(key_name, 0, 16);
8327     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
8328                                                  "SHA256", 0);
8329     params[1] = OSSL_PARAM_construct_end();
8330     if (aes128cbc == NULL
8331             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
8332             || !EVP_MAC_init(hctx, tick_hmac_key, sizeof(tick_hmac_key),
8333                              params))
8334         ret = -1;
8335     else
8336         ret = tick_key_renew ? 2 : 1;
8337 
8338     EVP_CIPHER_free(aes128cbc);
8339 
8340     return ret;
8341 }
8342 
8343 /*
8344  * Test the various ticket callbacks
8345  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
8346  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
8347  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
8348  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
8349  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
8350  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
8351  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
8352  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
8353  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
8354  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
8355  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
8356  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
8357  * Test 12: TLSv1.2, old ticket key callback, no ticket
8358  * Test 13: TLSv1.3, old ticket key callback, no ticket
8359  * Test 14: TLSv1.2, ticket key callback, ticket, no renewal
8360  * Test 15: TLSv1.3, ticket key callback, ticket, no renewal
8361  * Test 16: TLSv1.2, ticket key callback, ticket, renewal
8362  * Test 17: TLSv1.3, ticket key callback, ticket, renewal
8363  * Test 18: TLSv1.2, ticket key callback, no ticket
8364  * Test 19: TLSv1.3, ticket key callback, no ticket
8365  */
test_ticket_callbacks(int tst)8366 static int test_ticket_callbacks(int tst)
8367 {
8368     SSL_CTX *cctx = NULL, *sctx = NULL;
8369     SSL *clientssl = NULL, *serverssl = NULL;
8370     SSL_SESSION *clntsess = NULL;
8371     int testresult = 0;
8372 
8373 #ifdef OPENSSL_NO_TLS1_2
8374     if (tst % 2 == 0)
8375         return 1;
8376 #endif
8377 #ifdef OSSL_NO_USABLE_TLS1_3
8378     if (tst % 2 == 1)
8379         return 1;
8380 #endif
8381 #ifdef OPENSSL_NO_DEPRECATED_3_0
8382     if (tst >= 8 && tst <= 13)
8383         return 1;
8384 #endif
8385 
8386     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
8387 
8388     /* Which tests the ticket key callback should request renewal for */
8389 
8390     if (tst == 10 || tst == 11 || tst == 16 || tst == 17)
8391         tick_key_renew = 1;
8392     else if (tst == 12 || tst == 13 || tst == 18 || tst == 19)
8393         tick_key_renew = -1; /* abort sending the ticket/0-length ticket */
8394     else
8395         tick_key_renew = 0;
8396 
8397     /* Which tests the decrypt ticket callback should request renewal for */
8398     switch (tst) {
8399     case 0:
8400     case 1:
8401         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
8402         break;
8403 
8404     case 2:
8405     case 3:
8406         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
8407         break;
8408 
8409     case 4:
8410     case 5:
8411         tick_dec_ret = SSL_TICKET_RETURN_USE;
8412         break;
8413 
8414     case 6:
8415     case 7:
8416         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
8417         break;
8418 
8419     default:
8420         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
8421     }
8422 
8423     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8424                                        TLS_client_method(),
8425                                        TLS1_VERSION,
8426                                        ((tst % 2) == 0) ? TLS1_2_VERSION
8427                                                         : TLS1_3_VERSION,
8428                                        &sctx, &cctx, cert, privkey)))
8429         goto end;
8430 
8431     /*
8432      * We only want sessions to resume from tickets - not the session cache. So
8433      * switch the cache off.
8434      */
8435     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
8436         goto end;
8437 
8438     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
8439                                                  NULL)))
8440         goto end;
8441 
8442     if (tst >= 14) {
8443         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
8444             goto end;
8445 #ifndef OPENSSL_NO_DEPRECATED_3_0
8446     } else if (tst >= 8) {
8447         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
8448             goto end;
8449 #endif
8450     }
8451 
8452     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8453                                              NULL, NULL))
8454             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8455                                                 SSL_ERROR_NONE)))
8456         goto end;
8457 
8458     /*
8459      * The decrypt ticket key callback in TLSv1.2 should be called even though
8460      * we have no ticket yet, because it gets called with a status of
8461      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
8462      * actually send any ticket data). This does not happen in TLSv1.3 because
8463      * it is not valid to send empty ticket data in TLSv1.3.
8464      */
8465     if (!TEST_int_eq(gen_tick_called, 1)
8466             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
8467         goto end;
8468 
8469     gen_tick_called = dec_tick_called = 0;
8470 
8471     clntsess = SSL_get1_session(clientssl);
8472     SSL_shutdown(clientssl);
8473     SSL_shutdown(serverssl);
8474     SSL_free(serverssl);
8475     SSL_free(clientssl);
8476     serverssl = clientssl = NULL;
8477 
8478     /* Now do a resumption */
8479     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8480                                       NULL))
8481             || !TEST_true(SSL_set_session(clientssl, clntsess))
8482             || !TEST_true(create_ssl_connection(serverssl, clientssl,
8483                                                 SSL_ERROR_NONE)))
8484         goto end;
8485 
8486     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
8487             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8488             || tick_key_renew == -1) {
8489         if (!TEST_false(SSL_session_reused(clientssl)))
8490             goto end;
8491     } else {
8492         if (!TEST_true(SSL_session_reused(clientssl)))
8493             goto end;
8494     }
8495 
8496     if (!TEST_int_eq(gen_tick_called,
8497                      (tick_key_renew
8498                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
8499                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
8500                      ? 1 : 0)
8501                /* There is no ticket to decrypt in tests 13 and 19 */
8502             || !TEST_int_eq(dec_tick_called, (tst == 13 || tst == 19) ? 0 : 1))
8503         goto end;
8504 
8505     testresult = 1;
8506 
8507  end:
8508     SSL_SESSION_free(clntsess);
8509     SSL_free(serverssl);
8510     SSL_free(clientssl);
8511     SSL_CTX_free(sctx);
8512     SSL_CTX_free(cctx);
8513 
8514     return testresult;
8515 }
8516 
8517 /*
8518  * Test incorrect shutdown.
8519  * Test 0: client does not shutdown properly,
8520  *         server does not set SSL_OP_IGNORE_UNEXPECTED_EOF,
8521  *         server should get SSL_ERROR_SSL
8522  * Test 1: client does not shutdown properly,
8523  *         server sets SSL_OP_IGNORE_UNEXPECTED_EOF,
8524  *         server should get SSL_ERROR_ZERO_RETURN
8525  */
test_incorrect_shutdown(int tst)8526 static int test_incorrect_shutdown(int tst)
8527 {
8528     SSL_CTX *cctx = NULL, *sctx = NULL;
8529     SSL *clientssl = NULL, *serverssl = NULL;
8530     int testresult = 0;
8531     char buf[80];
8532     BIO *c2s;
8533 
8534     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8535                                        TLS_client_method(), 0, 0,
8536                                        &sctx, &cctx, cert, privkey)))
8537         goto end;
8538 
8539     if (tst == 1)
8540         SSL_CTX_set_options(sctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
8541 
8542     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8543                                             NULL, NULL)))
8544         goto end;
8545 
8546     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8547                                               SSL_ERROR_NONE)))
8548         goto end;
8549 
8550     c2s = SSL_get_rbio(serverssl);
8551     BIO_set_mem_eof_return(c2s, 0);
8552 
8553     if (!TEST_false(SSL_read(serverssl, buf, sizeof(buf))))
8554         goto end;
8555 
8556     if (tst == 0 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL) )
8557         goto end;
8558     if (tst == 1 && !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_ZERO_RETURN) )
8559         goto end;
8560 
8561     testresult = 1;
8562 
8563  end:
8564     SSL_free(serverssl);
8565     SSL_free(clientssl);
8566     SSL_CTX_free(sctx);
8567     SSL_CTX_free(cctx);
8568 
8569     return testresult;
8570 }
8571 
8572 /*
8573  * Test bi-directional shutdown.
8574  * Test 0: TLSv1.2
8575  * Test 1: TLSv1.2, server continues to read/write after client shutdown
8576  * Test 2: TLSv1.3, no pending NewSessionTicket messages
8577  * Test 3: TLSv1.3, pending NewSessionTicket messages
8578  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
8579  *                  sends key update, client reads it
8580  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
8581  *                  sends CertificateRequest, client reads and ignores it
8582  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
8583  *                  doesn't read it
8584  */
test_shutdown(int tst)8585 static int test_shutdown(int tst)
8586 {
8587     SSL_CTX *cctx = NULL, *sctx = NULL;
8588     SSL *clientssl = NULL, *serverssl = NULL;
8589     int testresult = 0;
8590     char msg[] = "A test message";
8591     char buf[80];
8592     size_t written, readbytes;
8593     SSL_SESSION *sess;
8594 
8595 #ifdef OPENSSL_NO_TLS1_2
8596     if (tst <= 1)
8597         return 1;
8598 #endif
8599 #ifdef OSSL_NO_USABLE_TLS1_3
8600     if (tst >= 2)
8601         return 1;
8602 #endif
8603 
8604     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8605                                        TLS_client_method(),
8606                                        TLS1_VERSION,
8607                                        (tst <= 1) ? TLS1_2_VERSION
8608                                                   : TLS1_3_VERSION,
8609                                        &sctx, &cctx, cert, privkey)))
8610         goto end;
8611 
8612     if (tst == 5)
8613         SSL_CTX_set_post_handshake_auth(cctx, 1);
8614 
8615     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8616                                              NULL, NULL)))
8617         goto end;
8618 
8619     if (tst == 3) {
8620         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
8621                                                   SSL_ERROR_NONE, 1, 0))
8622                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8623                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
8624             goto end;
8625     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
8626                                               SSL_ERROR_NONE))
8627             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8628             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
8629         goto end;
8630     }
8631 
8632     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8633         goto end;
8634 
8635     if (tst >= 4) {
8636         /*
8637          * Reading on the server after the client has sent close_notify should
8638          * fail and provide SSL_ERROR_ZERO_RETURN
8639          */
8640         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
8641                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
8642                                 SSL_ERROR_ZERO_RETURN)
8643                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
8644                                 SSL_RECEIVED_SHUTDOWN)
8645                    /*
8646                     * Even though we're shutdown on receive we should still be
8647                     * able to write.
8648                     */
8649                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8650             goto end;
8651         if (tst == 4
8652                 && !TEST_true(SSL_key_update(serverssl,
8653                                              SSL_KEY_UPDATE_REQUESTED)))
8654             goto end;
8655         if (tst == 5) {
8656             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
8657             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
8658                 goto end;
8659         }
8660         if ((tst == 4 || tst == 5)
8661                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
8662             goto end;
8663         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8664             goto end;
8665         if (tst == 4 || tst == 5) {
8666             /* Should still be able to read data from server */
8667             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8668                                        &readbytes))
8669                     || !TEST_size_t_eq(readbytes, sizeof(msg))
8670                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
8671                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
8672                                               &readbytes))
8673                     || !TEST_size_t_eq(readbytes, sizeof(msg))
8674                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
8675                 goto end;
8676         }
8677     }
8678 
8679     /* Writing on the client after sending close_notify shouldn't be possible */
8680     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
8681         goto end;
8682 
8683     if (tst < 4) {
8684         /*
8685          * For these tests the client has sent close_notify but it has not yet
8686          * been received by the server. The server has not sent close_notify
8687          * yet.
8688          */
8689         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
8690                    /*
8691                     * Writing on the server after sending close_notify shouldn't
8692                     * be possible.
8693                     */
8694                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
8695                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
8696                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8697                 || !TEST_true(SSL_SESSION_is_resumable(sess))
8698                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
8699             goto end;
8700     } else if (tst == 4 || tst == 5) {
8701         /*
8702          * In this test the client has sent close_notify and it has been
8703          * received by the server which has responded with a close_notify. The
8704          * client needs to read the close_notify sent by the server.
8705          */
8706         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
8707                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
8708                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
8709             goto end;
8710     } else {
8711         /*
8712          * tst == 6
8713          *
8714          * The client has sent close_notify and is expecting a close_notify
8715          * back, but instead there is application data first. The shutdown
8716          * should fail with a fatal error.
8717          */
8718         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
8719                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
8720             goto end;
8721     }
8722 
8723     testresult = 1;
8724 
8725  end:
8726     SSL_free(serverssl);
8727     SSL_free(clientssl);
8728     SSL_CTX_free(sctx);
8729     SSL_CTX_free(cctx);
8730 
8731     return testresult;
8732 }
8733 
8734 /*
8735  * Test that sending close_notify alerts works correctly in the case of a
8736  * retryable write failure.
8737  */
test_async_shutdown(void)8738 static int test_async_shutdown(void)
8739 {
8740     SSL_CTX *cctx = NULL, *sctx = NULL;
8741     SSL *clientssl = NULL, *serverssl = NULL;
8742     int testresult = 0;
8743     BIO *bretry = BIO_new(bio_s_always_retry()), *tmp = NULL;
8744 
8745     if (!TEST_ptr(bretry))
8746         goto end;
8747 
8748     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8749                                        TLS_client_method(),
8750                                        0, 0,
8751                                        &sctx, &cctx, cert, privkey)))
8752         goto end;
8753 
8754     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
8755                                       NULL)))
8756         goto end;
8757 
8758     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
8759         goto end;
8760 
8761     /* Close write side of clientssl */
8762     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
8763         goto end;
8764 
8765     tmp = SSL_get_wbio(serverssl);
8766     if (!TEST_true(BIO_up_ref(tmp))) {
8767         tmp = NULL;
8768         goto end;
8769     }
8770     SSL_set0_wbio(serverssl, bretry);
8771     bretry = NULL;
8772 
8773     /* First server shutdown should fail because of a retrable write failure */
8774     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
8775             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
8776         goto end;
8777 
8778     /* Second server shutdown should fail for the same reason */
8779     if (!TEST_int_eq(SSL_shutdown(serverssl), -1)
8780             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
8781         goto end;
8782 
8783     SSL_set0_wbio(serverssl, tmp);
8784     tmp = NULL;
8785 
8786     /* Third server shutdown should send close_notify */
8787     if (!TEST_int_eq(SSL_shutdown(serverssl), 0))
8788         goto end;
8789 
8790     /* Fourth server shutdown should read close_notify from client and finish */
8791     if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
8792         goto end;
8793 
8794     /* Client should also successfully fully shutdown */
8795     if (!TEST_int_eq(SSL_shutdown(clientssl), 1))
8796         goto end;
8797 
8798     testresult = 1;
8799  end:
8800     SSL_free(serverssl);
8801     SSL_free(clientssl);
8802     SSL_CTX_free(sctx);
8803     SSL_CTX_free(cctx);
8804     BIO_free(bretry);
8805     BIO_free(tmp);
8806 
8807     return testresult;
8808 }
8809 
8810 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
8811 static int cert_cb_cnt;
8812 
cert_cb(SSL * s,void * arg)8813 static int cert_cb(SSL *s, void *arg)
8814 {
8815     SSL_CTX *ctx = (SSL_CTX *)arg;
8816     BIO *in = NULL;
8817     EVP_PKEY *pkey = NULL;
8818     X509 *x509 = NULL, *rootx = NULL;
8819     STACK_OF(X509) *chain = NULL;
8820     char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
8821     int ret = 0;
8822 
8823     if (cert_cb_cnt == 0) {
8824         /* Suspend the handshake */
8825         cert_cb_cnt++;
8826         return -1;
8827     } else if (cert_cb_cnt == 1) {
8828         /*
8829          * Update the SSL_CTX, set the certificate and private key and then
8830          * continue the handshake normally.
8831          */
8832         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
8833             return 0;
8834 
8835         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
8836                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
8837                                                       SSL_FILETYPE_PEM))
8838                 || !TEST_true(SSL_check_private_key(s)))
8839             return 0;
8840         cert_cb_cnt++;
8841         return 1;
8842     } else if (cert_cb_cnt == 3) {
8843         int rv;
8844 
8845         rootfile = test_mk_file_path(certsdir, "rootcert.pem");
8846         ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
8847         ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
8848         if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
8849             goto out;
8850         chain = sk_X509_new_null();
8851         if (!TEST_ptr(chain))
8852             goto out;
8853         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8854                 || !TEST_int_gt(BIO_read_filename(in, rootfile), 0)
8855                 || !TEST_ptr(rootx = X509_new_ex(libctx, NULL))
8856                 || !TEST_ptr(PEM_read_bio_X509(in, &rootx, NULL, NULL))
8857                 || !TEST_true(sk_X509_push(chain, rootx)))
8858             goto out;
8859         rootx = NULL;
8860         BIO_free(in);
8861         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8862                 || !TEST_int_gt(BIO_read_filename(in, ecdsacert), 0)
8863                 || !TEST_ptr(x509 = X509_new_ex(libctx, NULL))
8864                 || !TEST_ptr(PEM_read_bio_X509(in, &x509, NULL, NULL)))
8865             goto out;
8866         BIO_free(in);
8867         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
8868                 || !TEST_int_gt(BIO_read_filename(in, ecdsakey), 0)
8869                 || !TEST_ptr(pkey = PEM_read_bio_PrivateKey_ex(in, NULL,
8870                                                                NULL, NULL,
8871                                                                libctx, NULL)))
8872             goto out;
8873         rv = SSL_check_chain(s, x509, pkey, chain);
8874         /*
8875          * If the cert doesn't show as valid here (e.g., because we don't
8876          * have any shared sigalgs), then we will not set it, and there will
8877          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
8878          * will cause tls_choose_sigalgs() to fail the connection.
8879          */
8880         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
8881                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
8882             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
8883                 goto out;
8884         }
8885 
8886         ret = 1;
8887     }
8888 
8889     /* Abort the handshake */
8890  out:
8891     OPENSSL_free(ecdsacert);
8892     OPENSSL_free(ecdsakey);
8893     OPENSSL_free(rootfile);
8894     BIO_free(in);
8895     EVP_PKEY_free(pkey);
8896     X509_free(x509);
8897     X509_free(rootx);
8898     OSSL_STACK_OF_X509_free(chain);
8899     return ret;
8900 }
8901 
8902 /*
8903  * Test the certificate callback.
8904  * Test 0: Callback fails
8905  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
8906  * Test 2: Success - SSL_set_SSL_CTX() in the callback
8907  * Test 3: Success - Call SSL_check_chain from the callback
8908  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
8909  *                   chain
8910  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
8911  */
test_cert_cb_int(int prot,int tst)8912 static int test_cert_cb_int(int prot, int tst)
8913 {
8914     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
8915     SSL *clientssl = NULL, *serverssl = NULL;
8916     int testresult = 0, ret;
8917 
8918 #ifdef OPENSSL_NO_EC
8919     /* We use an EC cert in these tests, so we skip in a no-ec build */
8920     if (tst >= 3)
8921         return 1;
8922 #endif
8923 
8924     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
8925                                        TLS_client_method(),
8926                                        TLS1_VERSION,
8927                                        prot,
8928                                        &sctx, &cctx, NULL, NULL)))
8929         goto end;
8930 
8931     if (tst == 0)
8932         cert_cb_cnt = -1;
8933     else if (tst >= 3)
8934         cert_cb_cnt = 3;
8935     else
8936         cert_cb_cnt = 0;
8937 
8938     if (tst == 2) {
8939         snictx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
8940         if (!TEST_ptr(snictx))
8941             goto end;
8942     }
8943 
8944     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
8945 
8946     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
8947                                       NULL, NULL)))
8948         goto end;
8949 
8950     if (tst == 4) {
8951         /*
8952          * We cause SSL_check_chain() to fail by specifying sig_algs that
8953          * the chain doesn't meet (the root uses an RSA cert)
8954          */
8955         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
8956                                              "ecdsa_secp256r1_sha256")))
8957             goto end;
8958     } else if (tst == 5) {
8959         /*
8960          * We cause SSL_check_chain() to fail by specifying sig_algs that
8961          * the ee cert doesn't meet (the ee uses an ECDSA cert)
8962          */
8963         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
8964                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
8965             goto end;
8966     }
8967 
8968     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
8969     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
8970             || (tst > 0
8971                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
8972         goto end;
8973     }
8974 
8975     testresult = 1;
8976 
8977  end:
8978     SSL_free(serverssl);
8979     SSL_free(clientssl);
8980     SSL_CTX_free(sctx);
8981     SSL_CTX_free(cctx);
8982     SSL_CTX_free(snictx);
8983 
8984     return testresult;
8985 }
8986 #endif
8987 
test_cert_cb(int tst)8988 static int test_cert_cb(int tst)
8989 {
8990     int testresult = 1;
8991 
8992 #ifndef OPENSSL_NO_TLS1_2
8993     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
8994 #endif
8995 #ifndef OSSL_NO_USABLE_TLS1_3
8996     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
8997 #endif
8998 
8999     return testresult;
9000 }
9001 
client_cert_cb(SSL * ssl,X509 ** x509,EVP_PKEY ** pkey)9002 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
9003 {
9004     X509 *xcert;
9005     EVP_PKEY *privpkey;
9006     BIO *in = NULL;
9007     BIO *priv_in = NULL;
9008 
9009     /* Check that SSL_get0_peer_certificate() returns something sensible */
9010     if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
9011         return 0;
9012 
9013     in = BIO_new_file(cert, "r");
9014     if (!TEST_ptr(in))
9015         return 0;
9016 
9017     if (!TEST_ptr(xcert = X509_new_ex(libctx, NULL))
9018             || !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
9019             || !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
9020             || !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
9021                                                                NULL, NULL,
9022                                                                libctx, NULL)))
9023         goto err;
9024 
9025     *x509 = xcert;
9026     *pkey = privpkey;
9027 
9028     BIO_free(in);
9029     BIO_free(priv_in);
9030     return 1;
9031 err:
9032     X509_free(xcert);
9033     BIO_free(in);
9034     BIO_free(priv_in);
9035     return 0;
9036 }
9037 
test_client_cert_cb(int tst)9038 static int test_client_cert_cb(int tst)
9039 {
9040     SSL_CTX *cctx = NULL, *sctx = NULL;
9041     SSL *clientssl = NULL, *serverssl = NULL;
9042     int testresult = 0;
9043 
9044 #ifdef OPENSSL_NO_TLS1_2
9045     if (tst == 0)
9046         return 1;
9047 #endif
9048 #ifdef OSSL_NO_USABLE_TLS1_3
9049     if (tst == 1)
9050         return 1;
9051 #endif
9052 
9053     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9054                                        TLS_client_method(),
9055                                        TLS1_VERSION,
9056                                        tst == 0 ? TLS1_2_VERSION
9057                                                 : TLS1_3_VERSION,
9058                                        &sctx, &cctx, cert, privkey)))
9059         goto end;
9060 
9061     /*
9062      * Test that setting a client_cert_cb results in a client certificate being
9063      * sent.
9064      */
9065     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
9066     SSL_CTX_set_verify(sctx,
9067                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
9068                        verify_cb);
9069 
9070     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9071                                       NULL, NULL))
9072             || !TEST_true(create_ssl_connection(serverssl, clientssl,
9073                                                 SSL_ERROR_NONE)))
9074         goto end;
9075 
9076     testresult = 1;
9077 
9078  end:
9079     SSL_free(serverssl);
9080     SSL_free(clientssl);
9081     SSL_CTX_free(sctx);
9082     SSL_CTX_free(cctx);
9083 
9084     return testresult;
9085 }
9086 
9087 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
9088 /*
9089  * Test setting certificate authorities on both client and server.
9090  *
9091  * Test 0: SSL_CTX_set0_CA_list() only
9092  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
9093  * Test 2: Only SSL_CTX_set_client_CA_list()
9094  */
test_ca_names_int(int prot,int tst)9095 static int test_ca_names_int(int prot, int tst)
9096 {
9097     SSL_CTX *cctx = NULL, *sctx = NULL;
9098     SSL *clientssl = NULL, *serverssl = NULL;
9099     int testresult = 0;
9100     size_t i;
9101     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
9102     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
9103     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
9104     const STACK_OF(X509_NAME) *sktmp = NULL;
9105 
9106     for (i = 0; i < OSSL_NELEM(name); i++) {
9107         name[i] = X509_NAME_new();
9108         if (!TEST_ptr(name[i])
9109                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
9110                                                          MBSTRING_ASC,
9111                                                          (unsigned char *)
9112                                                          strnames[i],
9113                                                          -1, -1, 0)))
9114             goto end;
9115     }
9116 
9117     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9118                                        TLS_client_method(),
9119                                        TLS1_VERSION,
9120                                        prot,
9121                                        &sctx, &cctx, cert, privkey)))
9122         goto end;
9123 
9124     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
9125 
9126     if (tst == 0 || tst == 1) {
9127         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9128                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
9129                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
9130                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9131                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
9132                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
9133             goto end;
9134 
9135         SSL_CTX_set0_CA_list(sctx, sk1);
9136         SSL_CTX_set0_CA_list(cctx, sk2);
9137         sk1 = sk2 = NULL;
9138     }
9139     if (tst == 1 || tst == 2) {
9140         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
9141                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
9142                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
9143                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
9144                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
9145                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
9146             goto end;
9147 
9148         SSL_CTX_set_client_CA_list(sctx, sk1);
9149         SSL_CTX_set_client_CA_list(cctx, sk2);
9150         sk1 = sk2 = NULL;
9151     }
9152 
9153     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9154                                       NULL, NULL))
9155             || !TEST_true(create_ssl_connection(serverssl, clientssl,
9156                                                 SSL_ERROR_NONE)))
9157         goto end;
9158 
9159     /*
9160      * We only expect certificate authorities to have been sent to the server
9161      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
9162      */
9163     sktmp = SSL_get0_peer_CA_list(serverssl);
9164     if (prot == TLS1_3_VERSION
9165             && (tst == 0 || tst == 1)) {
9166         if (!TEST_ptr(sktmp)
9167                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9168                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9169                                               name[0]), 0)
9170                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9171                                               name[1]), 0))
9172             goto end;
9173     } else if (!TEST_ptr_null(sktmp)) {
9174         goto end;
9175     }
9176 
9177     /*
9178      * In all tests we expect certificate authorities to have been sent to the
9179      * client. However, SSL_set_client_CA_list() should override
9180      * SSL_set0_CA_list()
9181      */
9182     sktmp = SSL_get0_peer_CA_list(clientssl);
9183     if (!TEST_ptr(sktmp)
9184             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
9185             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
9186                                           name[tst == 0 ? 0 : 2]), 0)
9187             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
9188                                           name[tst == 0 ? 1 : 3]), 0))
9189         goto end;
9190 
9191     testresult = 1;
9192 
9193  end:
9194     SSL_free(serverssl);
9195     SSL_free(clientssl);
9196     SSL_CTX_free(sctx);
9197     SSL_CTX_free(cctx);
9198     for (i = 0; i < OSSL_NELEM(name); i++)
9199         X509_NAME_free(name[i]);
9200     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
9201     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
9202 
9203     return testresult;
9204 }
9205 #endif
9206 
test_ca_names(int tst)9207 static int test_ca_names(int tst)
9208 {
9209     int testresult = 1;
9210 
9211 #ifndef OPENSSL_NO_TLS1_2
9212     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
9213 #endif
9214 #ifndef OSSL_NO_USABLE_TLS1_3
9215     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
9216 #endif
9217 
9218     return testresult;
9219 }
9220 
9221 #ifndef OPENSSL_NO_TLS1_2
9222 static const char *multiblock_cipherlist_data[]=
9223 {
9224     "AES128-SHA",
9225     "AES128-SHA256",
9226     "AES256-SHA",
9227     "AES256-SHA256",
9228 };
9229 
9230 /* Reduce the fragment size - so the multiblock test buffer can be small */
9231 # define MULTIBLOCK_FRAGSIZE 512
9232 
test_multiblock_write(int test_index)9233 static int test_multiblock_write(int test_index)
9234 {
9235     static const char *fetchable_ciphers[]=
9236     {
9237         "AES-128-CBC-HMAC-SHA1",
9238         "AES-128-CBC-HMAC-SHA256",
9239         "AES-256-CBC-HMAC-SHA1",
9240         "AES-256-CBC-HMAC-SHA256"
9241     };
9242     const char *cipherlist = multiblock_cipherlist_data[test_index];
9243     const SSL_METHOD *smeth = TLS_server_method();
9244     const SSL_METHOD *cmeth = TLS_client_method();
9245     int min_version = TLS1_VERSION;
9246     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
9247     SSL_CTX *cctx = NULL, *sctx = NULL;
9248     SSL *clientssl = NULL, *serverssl = NULL;
9249     int testresult = 0;
9250 
9251     /*
9252      * Choose a buffer large enough to perform a multi-block operation
9253      * i.e: write_len >= 4 * frag_size
9254      * 9 * is chosen so that multiple multiblocks are used + some leftover.
9255      */
9256     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
9257     unsigned char buf[sizeof(msg)], *p = buf;
9258     size_t readbytes, written, len;
9259     EVP_CIPHER *ciph = NULL;
9260 
9261     /*
9262      * Check if the cipher exists before attempting to use it since it only has
9263      * a hardware specific implementation.
9264      */
9265     ciph = EVP_CIPHER_fetch(libctx, fetchable_ciphers[test_index], "");
9266     if (ciph == NULL) {
9267         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
9268         return 1;
9269     }
9270     EVP_CIPHER_free(ciph);
9271 
9272     /* Set up a buffer with some data that will be sent to the client */
9273     RAND_bytes(msg, sizeof(msg));
9274 
9275     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
9276                                        max_version, &sctx, &cctx, cert,
9277                                        privkey)))
9278         goto end;
9279 
9280     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
9281         goto end;
9282 
9283     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9284                                       NULL, NULL)))
9285             goto end;
9286 
9287     /* settings to force it to use AES-CBC-HMAC_SHA */
9288     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
9289     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
9290        goto end;
9291 
9292     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9293         goto end;
9294 
9295     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
9296         || !TEST_size_t_eq(written, sizeof(msg)))
9297         goto end;
9298 
9299     len = written;
9300     while (len > 0) {
9301         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
9302             goto end;
9303         p += readbytes;
9304         len -= readbytes;
9305     }
9306     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
9307         goto end;
9308 
9309     testresult = 1;
9310 end:
9311     SSL_free(serverssl);
9312     SSL_free(clientssl);
9313     SSL_CTX_free(sctx);
9314     SSL_CTX_free(cctx);
9315 
9316     return testresult;
9317 }
9318 #endif /* OPENSSL_NO_TLS1_2 */
9319 
test_session_timeout(int test)9320 static int test_session_timeout(int test)
9321 {
9322     /*
9323      * Test session ordering and timeout
9324      * Can't explicitly test performance of the new code,
9325      * but can test to see if the ordering of the sessions
9326      * are correct, and they are removed as expected
9327      */
9328     SSL_SESSION *early = NULL;
9329     SSL_SESSION *middle = NULL;
9330     SSL_SESSION *late = NULL;
9331     SSL_CTX *ctx;
9332     int testresult = 0;
9333     time_t now = time(NULL);
9334 #define TIMEOUT 10
9335 
9336     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_method()))
9337         || !TEST_ptr(early = SSL_SESSION_new())
9338         || !TEST_ptr(middle = SSL_SESSION_new())
9339         || !TEST_ptr(late = SSL_SESSION_new()))
9340         goto end;
9341 
9342     /* assign unique session ids */
9343     early->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9344     memset(early->session_id, 1, SSL3_SSL_SESSION_ID_LENGTH);
9345     middle->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9346     memset(middle->session_id, 2, SSL3_SSL_SESSION_ID_LENGTH);
9347     late->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
9348     memset(late->session_id, 3, SSL3_SSL_SESSION_ID_LENGTH);
9349 
9350     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9351         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9352         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9353         goto end;
9354 
9355     /* Make sure they are all added */
9356     if (!TEST_ptr(early->prev)
9357         || !TEST_ptr(middle->prev)
9358         || !TEST_ptr(late->prev))
9359         goto end;
9360 
9361     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now - 10), 0)
9362         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(middle, now), 0)
9363         || !TEST_time_t_ne(SSL_SESSION_set_time_ex(late, now + 10), 0))
9364         goto end;
9365 
9366     if (!TEST_int_ne(SSL_SESSION_set_timeout(early, TIMEOUT), 0)
9367         || !TEST_int_ne(SSL_SESSION_set_timeout(middle, TIMEOUT), 0)
9368         || !TEST_int_ne(SSL_SESSION_set_timeout(late, TIMEOUT), 0))
9369         goto end;
9370 
9371     /* Make sure they are all still there */
9372     if (!TEST_ptr(early->prev)
9373         || !TEST_ptr(middle->prev)
9374         || !TEST_ptr(late->prev))
9375         goto end;
9376 
9377     /* Make sure they are in the expected order */
9378     if (!TEST_ptr_eq(late->next, middle)
9379         || !TEST_ptr_eq(middle->next, early)
9380         || !TEST_ptr_eq(early->prev, middle)
9381         || !TEST_ptr_eq(middle->prev, late))
9382         goto end;
9383 
9384     /* This should remove "early" */
9385     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT - 1);
9386     if (!TEST_ptr_null(early->prev)
9387         || !TEST_ptr(middle->prev)
9388         || !TEST_ptr(late->prev))
9389         goto end;
9390 
9391     /* This should remove "middle" */
9392     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 1);
9393     if (!TEST_ptr_null(early->prev)
9394         || !TEST_ptr_null(middle->prev)
9395         || !TEST_ptr(late->prev))
9396         goto end;
9397 
9398     /* This should remove "late" */
9399     SSL_CTX_flush_sessions_ex(ctx, now + TIMEOUT + 11);
9400     if (!TEST_ptr_null(early->prev)
9401         || !TEST_ptr_null(middle->prev)
9402         || !TEST_ptr_null(late->prev))
9403         goto end;
9404 
9405     /* Add them back in again */
9406     if (!TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9407         || !TEST_int_eq(SSL_CTX_add_session(ctx, middle), 1)
9408         || !TEST_int_eq(SSL_CTX_add_session(ctx, late), 1))
9409         goto end;
9410 
9411     /* Make sure they are all added */
9412     if (!TEST_ptr(early->prev)
9413         || !TEST_ptr(middle->prev)
9414         || !TEST_ptr(late->prev))
9415         goto end;
9416 
9417     /* This should remove all of them */
9418     SSL_CTX_flush_sessions_ex(ctx, 0);
9419     if (!TEST_ptr_null(early->prev)
9420         || !TEST_ptr_null(middle->prev)
9421         || !TEST_ptr_null(late->prev))
9422         goto end;
9423 
9424     (void)SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_UPDATE_TIME
9425                                          | SSL_CTX_get_session_cache_mode(ctx));
9426 
9427     /* make sure |now| is NOT  equal to the current time */
9428     now -= 10;
9429     if (!TEST_time_t_ne(SSL_SESSION_set_time_ex(early, now), 0)
9430         || !TEST_int_eq(SSL_CTX_add_session(ctx, early), 1)
9431         || !TEST_time_t_ne(SSL_SESSION_get_time_ex(early), now))
9432         goto end;
9433 
9434     testresult = 1;
9435  end:
9436     SSL_CTX_free(ctx);
9437     SSL_SESSION_free(early);
9438     SSL_SESSION_free(middle);
9439     SSL_SESSION_free(late);
9440     return testresult;
9441 }
9442 
9443 /*
9444  * Test that a session cache overflow works as expected
9445  * Test 0: TLSv1.3, timeout on new session later than old session
9446  * Test 1: TLSv1.2, timeout on new session later than old session
9447  * Test 2: TLSv1.3, timeout on new session earlier than old session
9448  * Test 3: TLSv1.2, timeout on new session earlier than old session
9449  */
9450 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
test_session_cache_overflow(int idx)9451 static int test_session_cache_overflow(int idx)
9452 {
9453     SSL_CTX *sctx = NULL, *cctx = NULL;
9454     SSL *serverssl = NULL, *clientssl = NULL;
9455     int testresult = 0;
9456     SSL_SESSION *sess = NULL;
9457 
9458 #ifdef OSSL_NO_USABLE_TLS1_3
9459     /* If no TLSv1.3 available then do nothing in this case */
9460     if (idx % 2 == 0)
9461         return TEST_skip("No TLSv1.3 available");
9462 #endif
9463 #ifdef OPENSSL_NO_TLS1_2
9464     /* If no TLSv1.2 available then do nothing in this case */
9465     if (idx % 2 == 1)
9466         return TEST_skip("No TLSv1.2 available");
9467 #endif
9468 
9469     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9470                                        TLS_client_method(), TLS1_VERSION,
9471                                        (idx % 2 == 0) ? TLS1_3_VERSION
9472                                                       : TLS1_2_VERSION,
9473                                        &sctx, &cctx, cert, privkey))
9474             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET)))
9475         goto end;
9476 
9477     SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
9478     get_sess_val = NULL;
9479 
9480     SSL_CTX_sess_set_cache_size(sctx, 1);
9481 
9482     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9483                                       NULL, NULL)))
9484         goto end;
9485 
9486     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9487         goto end;
9488 
9489     if (idx > 1) {
9490         sess = SSL_get_session(serverssl);
9491         if (!TEST_ptr(sess))
9492             goto end;
9493 
9494         /*
9495          * Cause this session to have a longer timeout than the next session to
9496          * be added.
9497          */
9498         if (!TEST_true(SSL_SESSION_set_timeout(sess, LONG_MAX))) {
9499             sess = NULL;
9500             goto end;
9501         }
9502         sess = NULL;
9503     }
9504 
9505     SSL_shutdown(serverssl);
9506     SSL_shutdown(clientssl);
9507     SSL_free(serverssl);
9508     SSL_free(clientssl);
9509     serverssl = clientssl = NULL;
9510 
9511     /*
9512      * Session cache size is 1 and we already populated the cache with a session
9513      * so the next connection should cause an overflow.
9514      */
9515 
9516     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9517                                       NULL, NULL)))
9518         goto end;
9519 
9520     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9521         goto end;
9522 
9523     /*
9524      * The session we just negotiated may have been already removed from the
9525      * internal cache - but we will return it anyway from our external cache.
9526      */
9527     get_sess_val = SSL_get_session(serverssl);
9528     if (!TEST_ptr(get_sess_val))
9529         goto end;
9530     sess = SSL_get1_session(clientssl);
9531     if (!TEST_ptr(sess))
9532         goto end;
9533 
9534     SSL_shutdown(serverssl);
9535     SSL_shutdown(clientssl);
9536     SSL_free(serverssl);
9537     SSL_free(clientssl);
9538     serverssl = clientssl = NULL;
9539 
9540     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9541                                       NULL, NULL)))
9542         goto end;
9543 
9544     if (!TEST_true(SSL_set_session(clientssl, sess)))
9545         goto end;
9546 
9547     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9548         goto end;
9549 
9550     testresult = 1;
9551 
9552  end:
9553     SSL_free(serverssl);
9554     SSL_free(clientssl);
9555     SSL_CTX_free(sctx);
9556     SSL_CTX_free(cctx);
9557     SSL_SESSION_free(sess);
9558 
9559     return testresult;
9560 }
9561 #endif /* !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
9562 
9563 /*
9564  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
9565  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
9566  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
9567  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
9568  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
9569  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
9570  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
9571  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
9572  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
9573  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
9574  */
test_servername(int tst)9575 static int test_servername(int tst)
9576 {
9577     SSL_CTX *cctx = NULL, *sctx = NULL;
9578     SSL *clientssl = NULL, *serverssl = NULL;
9579     int testresult = 0;
9580     SSL_SESSION *sess = NULL;
9581     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
9582 
9583 #ifdef OPENSSL_NO_TLS1_2
9584     if (tst <= 4)
9585         return 1;
9586 #endif
9587 #ifdef OSSL_NO_USABLE_TLS1_3
9588     if (tst >= 5)
9589         return 1;
9590 #endif
9591 
9592     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9593                                        TLS_client_method(),
9594                                        TLS1_VERSION,
9595                                        (tst <= 4) ? TLS1_2_VERSION
9596                                                   : TLS1_3_VERSION,
9597                                        &sctx, &cctx, cert, privkey))
9598             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9599                                              NULL, NULL)))
9600         goto end;
9601 
9602     if (tst != 1 && tst != 6) {
9603         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
9604                                                               hostname_cb)))
9605             goto end;
9606     }
9607 
9608     if (tst != 3 && tst != 8) {
9609         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9610             goto end;
9611         sexpectedhost = cexpectedhost = "goodhost";
9612     }
9613 
9614     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9615         goto end;
9616 
9617     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
9618                      cexpectedhost)
9619             || !TEST_str_eq(SSL_get_servername(serverssl,
9620                                                TLSEXT_NAMETYPE_host_name),
9621                             sexpectedhost))
9622         goto end;
9623 
9624     /* Now repeat with a resumption handshake */
9625 
9626     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
9627             || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
9628             || !TEST_true(SSL_SESSION_is_resumable(sess))
9629             || !TEST_int_eq(SSL_shutdown(serverssl), 0))
9630         goto end;
9631 
9632     SSL_free(clientssl);
9633     SSL_free(serverssl);
9634     clientssl = serverssl = NULL;
9635 
9636     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
9637                                       NULL)))
9638         goto end;
9639 
9640     if (!TEST_true(SSL_set_session(clientssl, sess)))
9641         goto end;
9642 
9643     sexpectedhost = cexpectedhost = "goodhost";
9644     if (tst == 2 || tst == 7) {
9645         /* Set an inconsistent hostname */
9646         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
9647             goto end;
9648         /*
9649          * In TLSv1.2 we expect the hostname from the original handshake, in
9650          * TLSv1.3 we expect the hostname from this handshake
9651          */
9652         if (tst == 7)
9653             sexpectedhost = cexpectedhost = "altgoodhost";
9654 
9655         if (!TEST_str_eq(SSL_get_servername(clientssl,
9656                                             TLSEXT_NAMETYPE_host_name),
9657                          "altgoodhost"))
9658             goto end;
9659     } else if (tst == 4 || tst == 9) {
9660         /*
9661          * A TLSv1.3 session does not associate a session with a servername,
9662          * but a TLSv1.2 session does.
9663          */
9664         if (tst == 9)
9665             sexpectedhost = cexpectedhost = NULL;
9666 
9667         if (!TEST_str_eq(SSL_get_servername(clientssl,
9668                                             TLSEXT_NAMETYPE_host_name),
9669                          cexpectedhost))
9670             goto end;
9671     } else {
9672         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
9673             goto end;
9674         /*
9675          * In a TLSv1.2 resumption where the hostname was not acknowledged
9676          * we expect the hostname on the server to be empty. On the client we
9677          * return what was requested in this case.
9678          *
9679          * Similarly if the client didn't set a hostname on an original TLSv1.2
9680          * session but is now, the server hostname will be empty, but the client
9681          * is as we set it.
9682          */
9683         if (tst == 1 || tst == 3)
9684             sexpectedhost = NULL;
9685 
9686         if (!TEST_str_eq(SSL_get_servername(clientssl,
9687                                             TLSEXT_NAMETYPE_host_name),
9688                          "goodhost"))
9689             goto end;
9690     }
9691 
9692     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9693         goto end;
9694 
9695     if (!TEST_true(SSL_session_reused(clientssl))
9696             || !TEST_true(SSL_session_reused(serverssl))
9697             || !TEST_str_eq(SSL_get_servername(clientssl,
9698                                                TLSEXT_NAMETYPE_host_name),
9699                             cexpectedhost)
9700             || !TEST_str_eq(SSL_get_servername(serverssl,
9701                                                TLSEXT_NAMETYPE_host_name),
9702                             sexpectedhost))
9703         goto end;
9704 
9705     testresult = 1;
9706 
9707  end:
9708     SSL_SESSION_free(sess);
9709     SSL_free(serverssl);
9710     SSL_free(clientssl);
9711     SSL_CTX_free(sctx);
9712     SSL_CTX_free(cctx);
9713 
9714     return testresult;
9715 }
9716 
test_unknown_sigalgs_groups(void)9717 static int test_unknown_sigalgs_groups(void)
9718 {
9719     int ret = 0;
9720     SSL_CTX *ctx = NULL;
9721 
9722     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
9723         goto end;
9724 
9725     if (!TEST_int_gt(SSL_CTX_set1_sigalgs_list(ctx,
9726                                                "RSA+SHA256:?nonexistent:?RSA+SHA512"),
9727                                                0))
9728         goto end;
9729     if (!TEST_size_t_eq(ctx->cert->conf_sigalgslen, 2)
9730         || !TEST_int_eq(ctx->cert->conf_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
9731         || !TEST_int_eq(ctx->cert->conf_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
9732         goto end;
9733 
9734     if (!TEST_int_gt(SSL_CTX_set1_client_sigalgs_list(ctx,
9735                                                       "RSA+SHA256:?nonexistent:?RSA+SHA512"),
9736                                                       0))
9737         goto end;
9738     if (!TEST_size_t_eq(ctx->cert->client_sigalgslen, 2)
9739         || !TEST_int_eq(ctx->cert->client_sigalgs[0], TLSEXT_SIGALG_rsa_pkcs1_sha256)
9740         || !TEST_int_eq(ctx->cert->client_sigalgs[1], TLSEXT_SIGALG_rsa_pkcs1_sha512))
9741         goto end;
9742 
9743     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
9744                                               "nonexistent"),
9745                                               0))
9746         goto end;
9747 
9748     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
9749                                               "?nonexistent1:?nonexistent2:?nonexistent3"),
9750                                               0))
9751         goto end;
9752 
9753 #ifndef OPENSSL_NO_EC
9754     if (!TEST_int_le(SSL_CTX_set1_groups_list(ctx,
9755                                               "P-256:nonexistent"),
9756                                               0))
9757         goto end;
9758 
9759     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx,
9760                                               "P-384:?nonexistent:?P-521"),
9761                                               0))
9762         goto end;
9763     if (!TEST_size_t_eq(ctx->ext.supportedgroups_len, 2)
9764         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp384r1)
9765         || !TEST_int_eq(ctx->ext.supportedgroups[1], OSSL_TLS_GROUP_ID_secp521r1))
9766         goto end;
9767 #endif
9768 
9769     ret = 1;
9770  end:
9771     SSL_CTX_free(ctx);
9772     return ret;
9773 }
9774 
test_configuration_of_groups(void)9775 static int test_configuration_of_groups(void)
9776 {
9777     int ret = 0;
9778     SSL_CTX *ctx = NULL;
9779 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH))
9780     size_t default_groups_len;
9781 #endif
9782 
9783     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method())))
9784         goto end;
9785 
9786 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH))
9787     default_groups_len = ctx->ext.supported_groups_default_len;
9788 
9789     if (!TEST_size_t_gt(default_groups_len, 0)
9790         || !TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT"), 0)
9791         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, default_groups_len))
9792         goto end;
9793 #endif
9794 
9795 #if (!defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH))
9796     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "DEFAULT:-?P-256"), 0)
9797 # if !defined(OPENSSL_NO_EC)
9798         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, default_groups_len - 1)
9799 # else
9800         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, default_groups_len)
9801 # endif
9802         )
9803         goto end;
9804 #endif
9805 
9806 #if !defined(OPENSSL_NO_EC)
9807     if (!TEST_int_gt(SSL_CTX_set1_groups_list(ctx, "?P-256:?P-521:-?P-256"), 0)
9808         || !TEST_size_t_eq(ctx->ext.supportedgroups_len, 1)
9809         || !TEST_int_eq(ctx->ext.supportedgroups[0], OSSL_TLS_GROUP_ID_secp521r1)
9810         )
9811         goto end;
9812 #endif
9813 
9814     ret = 1;
9815 
9816 end:
9817     SSL_CTX_free(ctx);
9818     return ret;
9819 }
9820 
9821 #if !defined(OPENSSL_NO_EC) \
9822     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
9823 /*
9824  * Test that if signature algorithms are not available, then we do not offer or
9825  * accept them.
9826  * Test 0: Two RSA sig algs available: both RSA sig algs shared
9827  * Test 1: The client only has SHA2-256: only SHA2-256 algorithms shared
9828  * Test 2: The server only has SHA2-256: only SHA2-256 algorithms shared
9829  * Test 3: An RSA and an ECDSA sig alg available: both sig algs shared
9830  * Test 4: The client only has an ECDSA sig alg: only ECDSA algorithms shared
9831  * Test 5: The server only has an ECDSA sig alg: only ECDSA algorithms shared
9832  */
test_sigalgs_available(int idx)9833 static int test_sigalgs_available(int idx)
9834 {
9835     SSL_CTX *cctx = NULL, *sctx = NULL;
9836     SSL *clientssl = NULL, *serverssl = NULL;
9837     int testresult = 0;
9838     OSSL_LIB_CTX *tmpctx = OSSL_LIB_CTX_new();
9839     OSSL_LIB_CTX *clientctx = libctx, *serverctx = libctx;
9840     OSSL_PROVIDER *filterprov = NULL;
9841     int sig, hash;
9842 
9843     if (!TEST_ptr(tmpctx))
9844         goto end;
9845 
9846     if (idx != 0 && idx != 3) {
9847         if (!TEST_true(OSSL_PROVIDER_add_builtin(tmpctx, "filter",
9848                                                  filter_provider_init)))
9849             goto end;
9850 
9851         filterprov = OSSL_PROVIDER_load(tmpctx, "filter");
9852         if (!TEST_ptr(filterprov))
9853             goto end;
9854 
9855         if (idx < 3) {
9856             /*
9857              * Only enable SHA2-256 so rsa_pss_rsae_sha384 should not be offered
9858              * or accepted for the peer that uses this libctx. Note that libssl
9859              * *requires* SHA2-256 to be available so we cannot disable that. We
9860              * also need SHA1 for our certificate.
9861              */
9862             if (!TEST_true(filter_provider_set_filter(OSSL_OP_DIGEST,
9863                                                       "SHA2-256:SHA1")))
9864                 goto end;
9865         } else {
9866             if (!TEST_true(filter_provider_set_filter(OSSL_OP_SIGNATURE,
9867                                                       "ECDSA"))
9868 # ifdef OPENSSL_NO_ECX
9869                     || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT, "EC"))
9870 # else
9871                     || !TEST_true(filter_provider_set_filter(OSSL_OP_KEYMGMT,
9872                                                              "EC:X25519:X448"))
9873 # endif
9874                 )
9875                 goto end;
9876         }
9877 
9878         if (idx == 1 || idx == 4)
9879             clientctx = tmpctx;
9880         else
9881             serverctx = tmpctx;
9882     }
9883 
9884     cctx = SSL_CTX_new_ex(clientctx, NULL, TLS_client_method());
9885     sctx = SSL_CTX_new_ex(serverctx, NULL, TLS_server_method());
9886     if (!TEST_ptr(cctx) || !TEST_ptr(sctx))
9887         goto end;
9888 
9889     if (idx != 5) {
9890         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9891                                            TLS_client_method(),
9892                                            TLS1_VERSION,
9893                                            0,
9894                                            &sctx, &cctx, cert, privkey)))
9895             goto end;
9896     } else {
9897         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9898                                            TLS_client_method(),
9899                                            TLS1_VERSION,
9900                                            0,
9901                                            &sctx, &cctx, cert2, privkey2)))
9902             goto end;
9903     }
9904 
9905     /* Ensure we only use TLSv1.2 ciphersuites based on SHA256 */
9906     if (idx < 4) {
9907         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
9908                                                "ECDHE-RSA-AES128-GCM-SHA256")))
9909             goto end;
9910     } else {
9911         if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
9912                                                "ECDHE-ECDSA-AES128-GCM-SHA256")))
9913             goto end;
9914     }
9915 
9916     if (idx < 3) {
9917         if (!SSL_CTX_set1_sigalgs_list(cctx,
9918                                        "rsa_pss_rsae_sha384"
9919                                        ":rsa_pss_rsae_sha256")
9920                 || !SSL_CTX_set1_sigalgs_list(sctx,
9921                                               "rsa_pss_rsae_sha384"
9922                                               ":rsa_pss_rsae_sha256"))
9923             goto end;
9924     } else {
9925         if (!SSL_CTX_set1_sigalgs_list(cctx, "rsa_pss_rsae_sha256:ECDSA+SHA256")
9926                 || !SSL_CTX_set1_sigalgs_list(sctx,
9927                                               "rsa_pss_rsae_sha256:ECDSA+SHA256"))
9928             goto end;
9929     }
9930 
9931     if (idx != 5
9932         && (!TEST_int_eq(SSL_CTX_use_certificate_file(sctx, cert2,
9933                                                       SSL_FILETYPE_PEM), 1)
9934             || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(sctx,
9935                                                         privkey2,
9936                                                         SSL_FILETYPE_PEM), 1)
9937             || !TEST_int_eq(SSL_CTX_check_private_key(sctx), 1)))
9938         goto end;
9939 
9940     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9941                                       NULL, NULL)))
9942         goto end;
9943 
9944     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
9945         goto end;
9946 
9947     /* For tests 0 and 3 we expect 2 shared sigalgs, otherwise exactly 1 */
9948     if (!TEST_int_eq(SSL_get_shared_sigalgs(serverssl, 0, &sig, &hash, NULL,
9949                                             NULL, NULL),
9950                      (idx == 0 || idx == 3) ? 2 : 1))
9951         goto end;
9952 
9953     if (!TEST_int_eq(hash, idx == 0 ? NID_sha384 : NID_sha256))
9954         goto end;
9955 
9956     if (!TEST_int_eq(sig, (idx == 4 || idx == 5) ? EVP_PKEY_EC
9957                                                  : NID_rsassaPss))
9958         goto end;
9959 
9960     testresult = filter_provider_check_clean_finish();
9961 
9962  end:
9963     SSL_free(serverssl);
9964     SSL_free(clientssl);
9965     SSL_CTX_free(sctx);
9966     SSL_CTX_free(cctx);
9967     OSSL_PROVIDER_unload(filterprov);
9968     OSSL_LIB_CTX_free(tmpctx);
9969 
9970     return testresult;
9971 }
9972 #endif /*
9973         * !defined(OPENSSL_NO_EC) \
9974         * && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
9975         */
9976 
9977 #ifndef OPENSSL_NO_TLS1_3
9978 /* This test can run in TLSv1.3 even if ec and dh are disabled */
test_pluggable_group(int idx)9979 static int test_pluggable_group(int idx)
9980 {
9981     SSL_CTX *cctx = NULL, *sctx = NULL;
9982     SSL *clientssl = NULL, *serverssl = NULL;
9983     int testresult = 0;
9984     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
9985     /* Check that we are not impacted by a provider without any groups */
9986     OSSL_PROVIDER *legacyprov = OSSL_PROVIDER_load(libctx, "legacy");
9987     const char *group_name = idx == 0 ? "xorkemgroup" : "xorgroup";
9988 
9989     if (!TEST_ptr(tlsprov))
9990         goto end;
9991 
9992     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
9993                                        TLS_client_method(),
9994                                        TLS1_3_VERSION,
9995                                        TLS1_3_VERSION,
9996                                        &sctx, &cctx, cert, privkey))
9997             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
9998                                              NULL, NULL)))
9999         goto end;
10000 
10001     /* ensure GROUPLIST_INCREMENT (=40) logic triggers: */
10002     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"))
10003     /* removing a single algorithm from the list makes the test pass */
10004             || !TEST_true(SSL_set1_groups_list(clientssl, group_name)))
10005         goto end;
10006 
10007     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10008         goto end;
10009 
10010     if (!TEST_str_eq(group_name,
10011                      SSL_group_to_name(serverssl, SSL_get_shared_group(serverssl, 0))))
10012         goto end;
10013 
10014     if (!TEST_str_eq(group_name, SSL_get0_group_name(serverssl))
10015         || !TEST_str_eq(group_name, SSL_get0_group_name(clientssl)))
10016         goto end;
10017 
10018     testresult = 1;
10019 
10020  end:
10021     SSL_free(serverssl);
10022     SSL_free(clientssl);
10023     SSL_CTX_free(sctx);
10024     SSL_CTX_free(cctx);
10025     OSSL_PROVIDER_unload(tlsprov);
10026     OSSL_PROVIDER_unload(legacyprov);
10027 
10028     return testresult;
10029 }
10030 
10031 /*
10032  * This function triggers encode, decode and sign functions
10033  * of the artificial "xorhmacsig" algorithm implemented in tls-provider
10034  * creating private key and certificate files for use in TLS testing.
10035  */
create_cert_key(int idx,char * certfilename,char * privkeyfilename)10036 static int create_cert_key(int idx, char *certfilename, char *privkeyfilename)
10037 {
10038     EVP_PKEY_CTX *evpctx = EVP_PKEY_CTX_new_from_name(libctx,
10039                              (idx == 0) ? "xorhmacsig" : "xorhmacsha2sig", NULL);
10040     EVP_PKEY *pkey = NULL;
10041     X509 *x509 = X509_new();
10042     X509_NAME *name = NULL;
10043     BIO *keybio = NULL, *certbio = NULL;
10044     int ret = 1;
10045 
10046     if (!TEST_ptr(evpctx)
10047         || !TEST_true(EVP_PKEY_keygen_init(evpctx))
10048         || !TEST_true(EVP_PKEY_generate(evpctx, &pkey))
10049         || !TEST_ptr(pkey)
10050         || !TEST_ptr(x509)
10051         || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(x509), 1))
10052         || !TEST_true(X509_gmtime_adj(X509_getm_notBefore(x509), 0))
10053         || !TEST_true(X509_gmtime_adj(X509_getm_notAfter(x509), 31536000L))
10054         || !TEST_true(X509_set_pubkey(x509, pkey))
10055         || !TEST_ptr(name = X509_get_subject_name(x509))
10056         || !TEST_true(X509_NAME_add_entry_by_txt(name, "C",  MBSTRING_ASC,
10057                            (unsigned char *)"CH", -1, -1, 0))
10058         || !TEST_true(X509_NAME_add_entry_by_txt(name, "O",  MBSTRING_ASC,
10059                            (unsigned char *)"test.org", -1, -1, 0))
10060         || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
10061                            (unsigned char *)"localhost", -1, -1, 0))
10062         || !TEST_true(X509_set_issuer_name(x509, name))
10063         || !TEST_true(X509_sign(x509, pkey, EVP_sha1()))
10064         || !TEST_ptr(keybio = BIO_new_file(privkeyfilename, "wb"))
10065         || !TEST_true(PEM_write_bio_PrivateKey(keybio, pkey, NULL, NULL, 0, NULL, NULL))
10066         || !TEST_ptr(certbio = BIO_new_file(certfilename, "wb"))
10067         || !TEST_true(PEM_write_bio_X509(certbio, x509)))
10068         ret = 0;
10069 
10070     EVP_PKEY_free(pkey);
10071     X509_free(x509);
10072     EVP_PKEY_CTX_free(evpctx);
10073     BIO_free(keybio);
10074     BIO_free(certbio);
10075     return ret;
10076 }
10077 
10078 /*
10079  * Test that signature algorithms loaded via the provider interface can
10080  * correctly establish a TLS (1.3) connection.
10081  * Test 0: Signature algorithm with built-in hashing functionality: "xorhmacsig"
10082  * Test 1: Signature algorithm using external SHA2 hashing: "xorhmacsha2sig"
10083  * Test 2: Test 0 using RPK
10084  * Test 3: Test 1 using RPK
10085  */
test_pluggable_signature(int idx)10086 static int test_pluggable_signature(int idx)
10087 {
10088     static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
10089     SSL_CTX *cctx = NULL, *sctx = NULL;
10090     SSL *clientssl = NULL, *serverssl = NULL;
10091     int testresult = 0;
10092     OSSL_PROVIDER *tlsprov = OSSL_PROVIDER_load(libctx, "tls-provider");
10093     OSSL_PROVIDER *defaultprov = OSSL_PROVIDER_load(libctx, "default");
10094     char *certfilename = "tls-prov-cert.pem";
10095     char *privkeyfilename = "tls-prov-key.pem";
10096     int sigidx = idx % 2;
10097     int rpkidx = idx / 2;
10098 
10099     /* create key and certificate for the different algorithm types */
10100     if (!TEST_ptr(tlsprov)
10101         || !TEST_true(create_cert_key(sigidx, certfilename, privkeyfilename)))
10102         goto end;
10103 
10104     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10105                                        TLS_client_method(),
10106                                        TLS1_3_VERSION,
10107                                        TLS1_3_VERSION,
10108                                        &sctx, &cctx, certfilename, privkeyfilename))
10109             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10110                                              NULL, NULL)))
10111         goto end;
10112 
10113     /* Enable RPK for server cert */
10114     if (rpkidx) {
10115         if (!TEST_true(SSL_set1_server_cert_type(serverssl, cert_type_rpk, sizeof(cert_type_rpk)))
10116                 || !TEST_true(SSL_set1_server_cert_type(clientssl, cert_type_rpk, sizeof(cert_type_rpk))))
10117             goto end;
10118     }
10119 
10120     /* This is necessary to pass minimal setup w/o other groups configured */
10121     if (!TEST_true(SSL_set1_groups_list(serverssl, "xorgroup"))
10122             || !TEST_true(SSL_set1_groups_list(clientssl, "xorgroup")))
10123         goto end;
10124 
10125     /*
10126      * If this connection gets established, it must have been completed
10127      * via the tls-provider-implemented "hmacsig" algorithm, testing
10128      * both sign and verify functions during handshake.
10129      */
10130     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10131         goto end;
10132 
10133     /* If using RPK, make sure we got one */
10134     if (rpkidx && !TEST_long_eq(SSL_get_verify_result(clientssl), X509_V_ERR_RPK_UNTRUSTED))
10135         goto end;
10136 
10137     testresult = 1;
10138 
10139  end:
10140     SSL_free(serverssl);
10141     SSL_free(clientssl);
10142     SSL_CTX_free(sctx);
10143     SSL_CTX_free(cctx);
10144     OSSL_PROVIDER_unload(tlsprov);
10145     OSSL_PROVIDER_unload(defaultprov);
10146 
10147     return testresult;
10148 }
10149 #endif
10150 
10151 #ifndef OPENSSL_NO_TLS1_2
test_ssl_dup(void)10152 static int test_ssl_dup(void)
10153 {
10154     SSL_CTX *cctx = NULL, *sctx = NULL;
10155     SSL *clientssl = NULL, *serverssl = NULL, *client2ssl = NULL;
10156     int testresult = 0;
10157     BIO *rbio = NULL, *wbio = NULL;
10158 
10159     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10160                                        TLS_client_method(),
10161                                        0,
10162                                        0,
10163                                        &sctx, &cctx, cert, privkey)))
10164         goto end;
10165 
10166     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10167                                              NULL, NULL)))
10168         goto end;
10169 
10170     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10171             || !TEST_true(SSL_set_max_proto_version(clientssl, TLS1_2_VERSION)))
10172         goto end;
10173 
10174     client2ssl = SSL_dup(clientssl);
10175     rbio = SSL_get_rbio(clientssl);
10176     if (!TEST_ptr(rbio)
10177             || !TEST_true(BIO_up_ref(rbio)))
10178         goto end;
10179     SSL_set0_rbio(client2ssl, rbio);
10180     rbio = NULL;
10181 
10182     wbio = SSL_get_wbio(clientssl);
10183     if (!TEST_ptr(wbio) || !TEST_true(BIO_up_ref(wbio)))
10184         goto end;
10185     SSL_set0_wbio(client2ssl, wbio);
10186     rbio = NULL;
10187 
10188     if (!TEST_ptr(client2ssl)
10189                /* Handshake not started so pointers should be different */
10190             || !TEST_ptr_ne(clientssl, client2ssl))
10191         goto end;
10192 
10193     if (!TEST_int_eq(SSL_get_min_proto_version(client2ssl), TLS1_2_VERSION)
10194             || !TEST_int_eq(SSL_get_max_proto_version(client2ssl), TLS1_2_VERSION))
10195         goto end;
10196 
10197     if (!TEST_true(create_ssl_connection(serverssl, client2ssl, SSL_ERROR_NONE)))
10198         goto end;
10199 
10200     SSL_free(clientssl);
10201     clientssl = SSL_dup(client2ssl);
10202     if (!TEST_ptr(clientssl)
10203                /* Handshake has finished so pointers should be the same */
10204             || !TEST_ptr_eq(clientssl, client2ssl))
10205         goto end;
10206 
10207     testresult = 1;
10208 
10209  end:
10210     SSL_free(serverssl);
10211     SSL_free(clientssl);
10212     SSL_free(client2ssl);
10213     SSL_CTX_free(sctx);
10214     SSL_CTX_free(cctx);
10215 
10216     return testresult;
10217 }
10218 
secret_cb(SSL * s,void * secretin,int * secret_len,STACK_OF (SSL_CIPHER)* peer_ciphers,const SSL_CIPHER ** cipher,void * arg)10219 static int secret_cb(SSL *s, void *secretin, int *secret_len,
10220                      STACK_OF(SSL_CIPHER) *peer_ciphers,
10221                      const SSL_CIPHER **cipher, void *arg)
10222 {
10223     int i;
10224     unsigned char *secret = secretin;
10225 
10226     /* Just use a fixed master secret */
10227     for (i = 0; i < *secret_len; i++)
10228         secret[i] = 0xff;
10229 
10230     /* We don't set a preferred cipher */
10231 
10232     return 1;
10233 }
10234 
10235 /*
10236  * Test the session_secret_cb which is designed for use with EAP-FAST
10237  */
test_session_secret_cb(void)10238 static int test_session_secret_cb(void)
10239 {
10240     SSL_CTX *cctx = NULL, *sctx = NULL;
10241     SSL *clientssl = NULL, *serverssl = NULL;
10242     SSL_SESSION *secret_sess = NULL;
10243     int testresult = 0;
10244 
10245     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10246                                        TLS_client_method(),
10247                                        0,
10248                                        0,
10249                                        &sctx, &cctx, cert, privkey)))
10250         goto end;
10251 
10252     /* Create an initial connection and save the session */
10253     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10254                                       NULL, NULL)))
10255         goto end;
10256 
10257     /* session_secret_cb does not support TLSv1.3 */
10258     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10259             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION)))
10260         goto end;
10261 
10262     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10263         goto end;
10264 
10265     if (!TEST_ptr(secret_sess = SSL_get1_session(clientssl)))
10266         goto end;
10267 
10268     shutdown_ssl_connection(serverssl, clientssl);
10269     serverssl = clientssl = NULL;
10270 
10271     /* Resume the earlier session */
10272     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10273                                       NULL, NULL)))
10274         goto end;
10275 
10276     /*
10277      * No session ids for EAP-FAST - otherwise the state machine gets very
10278      * confused.
10279      */
10280     if (!TEST_true(SSL_SESSION_set1_id(secret_sess, NULL, 0)))
10281         goto end;
10282 
10283     if (!TEST_true(SSL_set_min_proto_version(clientssl, TLS1_2_VERSION))
10284             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10285             || !TEST_true(SSL_set_session_secret_cb(serverssl, secret_cb,
10286                                                     NULL))
10287             || !TEST_true(SSL_set_session_secret_cb(clientssl, secret_cb,
10288                                                     NULL))
10289             || !TEST_true(SSL_set_session(clientssl, secret_sess)))
10290         goto end;
10291 
10292     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10293         goto end;
10294 
10295     testresult = 1;
10296 
10297  end:
10298     SSL_SESSION_free(secret_sess);
10299     SSL_free(serverssl);
10300     SSL_free(clientssl);
10301     SSL_CTX_free(sctx);
10302     SSL_CTX_free(cctx);
10303 
10304     return testresult;
10305 }
10306 
10307 # ifndef OPENSSL_NO_DH
10308 
10309 static EVP_PKEY *tmp_dh_params = NULL;
10310 
10311 /* Helper function for the test_set_tmp_dh() tests */
get_tmp_dh_params(void)10312 static EVP_PKEY *get_tmp_dh_params(void)
10313 {
10314     if (tmp_dh_params == NULL) {
10315         BIGNUM *p = NULL;
10316         OSSL_PARAM_BLD *tmpl = NULL;
10317         EVP_PKEY_CTX *pctx = NULL;
10318         OSSL_PARAM *params = NULL;
10319         EVP_PKEY *dhpkey = NULL;
10320 
10321         p = BN_get_rfc3526_prime_2048(NULL);
10322         if (!TEST_ptr(p))
10323             goto end;
10324 
10325         pctx = EVP_PKEY_CTX_new_from_name(libctx, "DH", NULL);
10326         if (!TEST_ptr(pctx)
10327                 || !TEST_int_eq(EVP_PKEY_fromdata_init(pctx), 1))
10328             goto end;
10329 
10330         tmpl = OSSL_PARAM_BLD_new();
10331         if (!TEST_ptr(tmpl)
10332                 || !TEST_true(OSSL_PARAM_BLD_push_BN(tmpl,
10333                                                         OSSL_PKEY_PARAM_FFC_P,
10334                                                         p))
10335                 || !TEST_true(OSSL_PARAM_BLD_push_uint(tmpl,
10336                                                         OSSL_PKEY_PARAM_FFC_G,
10337                                                         2)))
10338             goto end;
10339 
10340         params = OSSL_PARAM_BLD_to_param(tmpl);
10341         if (!TEST_ptr(params)
10342                 || !TEST_int_eq(EVP_PKEY_fromdata(pctx, &dhpkey,
10343                                                   EVP_PKEY_KEY_PARAMETERS,
10344                                                   params), 1))
10345             goto end;
10346 
10347         tmp_dh_params = dhpkey;
10348     end:
10349         BN_free(p);
10350         EVP_PKEY_CTX_free(pctx);
10351         OSSL_PARAM_BLD_free(tmpl);
10352         OSSL_PARAM_free(params);
10353     }
10354 
10355     if (tmp_dh_params != NULL && !EVP_PKEY_up_ref(tmp_dh_params))
10356         return NULL;
10357 
10358     return tmp_dh_params;
10359 }
10360 
10361 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10362 /* Callback used by test_set_tmp_dh() */
tmp_dh_callback(SSL * s,int is_export,int keylen)10363 static DH *tmp_dh_callback(SSL *s, int is_export, int keylen)
10364 {
10365     EVP_PKEY *dhpkey = get_tmp_dh_params();
10366     DH *ret = NULL;
10367 
10368     if (!TEST_ptr(dhpkey))
10369         return NULL;
10370 
10371     /*
10372      * libssl does not free the returned DH, so we free it now knowing that even
10373      * after we free dhpkey, there will still be a reference to the owning
10374      * EVP_PKEY in tmp_dh_params, and so the DH object will live for the length
10375      * of time we need it for.
10376      */
10377     ret = EVP_PKEY_get1_DH(dhpkey);
10378     DH_free(ret);
10379 
10380     EVP_PKEY_free(dhpkey);
10381 
10382     return ret;
10383 }
10384 #  endif
10385 
10386 /*
10387  * Test the various methods for setting temporary DH parameters
10388  *
10389  * Test  0: Default (no auto) setting
10390  * Test  1: Explicit SSL_CTX auto off
10391  * Test  2: Explicit SSL auto off
10392  * Test  3: Explicit SSL_CTX auto on
10393  * Test  4: Explicit SSL auto on
10394  * Test  5: Explicit SSL_CTX auto off, custom DH params via EVP_PKEY
10395  * Test  6: Explicit SSL auto off, custom DH params via EVP_PKEY
10396  *
10397  * The following are testing deprecated APIs, so we only run them if available
10398  * Test  7: Explicit SSL_CTX auto off, custom DH params via DH
10399  * Test  8: Explicit SSL auto off, custom DH params via DH
10400  * Test  9: Explicit SSL_CTX auto off, custom DH params via callback
10401  * Test 10: Explicit SSL auto off, custom DH params via callback
10402  */
test_set_tmp_dh(int idx)10403 static int test_set_tmp_dh(int idx)
10404 {
10405     SSL_CTX *cctx = NULL, *sctx = NULL;
10406     SSL *clientssl = NULL, *serverssl = NULL;
10407     int testresult = 0;
10408     int dhauto = (idx == 3 || idx == 4) ? 1 : 0;
10409     int expected = (idx <= 2) ? 0 : 1;
10410     EVP_PKEY *dhpkey = NULL;
10411 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10412     DH *dh = NULL;
10413 #  else
10414 
10415     if (idx >= 7)
10416         return 1;
10417 #  endif
10418 
10419     if (idx >= 5 && idx <= 8) {
10420         dhpkey = get_tmp_dh_params();
10421         if (!TEST_ptr(dhpkey))
10422             goto end;
10423     }
10424 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10425     if (idx == 7 || idx == 8) {
10426         dh = EVP_PKEY_get1_DH(dhpkey);
10427         if (!TEST_ptr(dh))
10428             goto end;
10429     }
10430 #  endif
10431 
10432     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10433                                        TLS_client_method(),
10434                                        0,
10435                                        0,
10436                                        &sctx, &cctx, cert, privkey)))
10437         goto end;
10438 
10439     if ((idx & 1) == 1) {
10440         if (!TEST_true(SSL_CTX_set_dh_auto(sctx, dhauto)))
10441             goto end;
10442     }
10443 
10444     if (idx == 5) {
10445         if (!TEST_true(SSL_CTX_set0_tmp_dh_pkey(sctx, dhpkey)))
10446             goto end;
10447         dhpkey = NULL;
10448     }
10449 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10450     else if (idx == 7) {
10451         if (!TEST_true(SSL_CTX_set_tmp_dh(sctx, dh)))
10452             goto end;
10453     } else if (idx == 9) {
10454         SSL_CTX_set_tmp_dh_callback(sctx, tmp_dh_callback);
10455     }
10456 #  endif
10457 
10458     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10459                                       NULL, NULL)))
10460         goto end;
10461 
10462     if ((idx & 1) == 0 && idx != 0) {
10463         if (!TEST_true(SSL_set_dh_auto(serverssl, dhauto)))
10464             goto end;
10465     }
10466     if (idx == 6) {
10467         if (!TEST_true(SSL_set0_tmp_dh_pkey(serverssl, dhpkey)))
10468             goto end;
10469         dhpkey = NULL;
10470     }
10471 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10472     else if (idx == 8) {
10473         if (!TEST_true(SSL_set_tmp_dh(serverssl, dh)))
10474             goto end;
10475     } else if (idx == 10) {
10476         SSL_set_tmp_dh_callback(serverssl, tmp_dh_callback);
10477     }
10478 #  endif
10479 
10480     if (!TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10481             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10482             || !TEST_true(SSL_set_cipher_list(serverssl, "DHE-RSA-AES128-SHA")))
10483         goto end;
10484 
10485     /*
10486      * If autoon then we should succeed. Otherwise we expect failure because
10487      * there are no parameters
10488      */
10489     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
10490                                            SSL_ERROR_NONE), expected))
10491         goto end;
10492 
10493     testresult = 1;
10494 
10495  end:
10496 #  ifndef OPENSSL_NO_DEPRECATED_3_0
10497     DH_free(dh);
10498 #  endif
10499     SSL_free(serverssl);
10500     SSL_free(clientssl);
10501     SSL_CTX_free(sctx);
10502     SSL_CTX_free(cctx);
10503     EVP_PKEY_free(dhpkey);
10504 
10505     return testresult;
10506 }
10507 
10508 /*
10509  * Test the auto DH keys are appropriately sized
10510  */
test_dh_auto(int idx)10511 static int test_dh_auto(int idx)
10512 {
10513     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method());
10514     SSL_CTX *sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10515     SSL *clientssl = NULL, *serverssl = NULL;
10516     int testresult = 0;
10517     EVP_PKEY *tmpkey = NULL;
10518     char *thiscert = NULL, *thiskey = NULL;
10519     size_t expdhsize = 0;
10520     const char *ciphersuite = "DHE-RSA-AES128-SHA";
10521 
10522     if (!TEST_ptr(sctx) || !TEST_ptr(cctx))
10523         goto end;
10524 
10525     switch (idx) {
10526     case 0:
10527         /* The FIPS provider doesn't support this DH size - so we ignore it */
10528         if (is_fips) {
10529             testresult = 1;
10530             goto end;
10531         }
10532         thiscert = cert1024;
10533         thiskey = privkey1024;
10534         expdhsize = 1024;
10535         SSL_CTX_set_security_level(sctx, 1);
10536         SSL_CTX_set_security_level(cctx, 1);
10537         break;
10538     case 1:
10539         /* 2048 bit prime */
10540         thiscert = cert;
10541         thiskey = privkey;
10542         expdhsize = 2048;
10543         break;
10544     case 2:
10545         thiscert = cert3072;
10546         thiskey = privkey3072;
10547         expdhsize = 3072;
10548         break;
10549     case 3:
10550         thiscert = cert4096;
10551         thiskey = privkey4096;
10552         expdhsize = 4096;
10553         break;
10554     case 4:
10555         thiscert = cert8192;
10556         thiskey = privkey8192;
10557         expdhsize = 8192;
10558         break;
10559     /* No certificate cases */
10560     case 5:
10561         /* The FIPS provider doesn't support this DH size - so we ignore it */
10562         if (is_fips) {
10563             testresult = 1;
10564             goto end;
10565         }
10566         ciphersuite = "ADH-AES128-SHA256:@SECLEVEL=0";
10567         expdhsize = 1024;
10568         break;
10569     case 6:
10570         ciphersuite = "ADH-AES256-SHA256:@SECLEVEL=0";
10571         expdhsize = 3072;
10572         break;
10573     default:
10574         TEST_error("Invalid text index");
10575         goto end;
10576     }
10577 
10578     if (!TEST_true(create_ssl_ctx_pair(libctx, NULL,
10579                                        NULL,
10580                                        0,
10581                                        0,
10582                                        &sctx, &cctx, thiscert, thiskey)))
10583         goto end;
10584 
10585     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
10586                                       NULL, NULL)))
10587         goto end;
10588 
10589     if (!TEST_true(SSL_set_dh_auto(serverssl, 1))
10590             || !TEST_true(SSL_set_min_proto_version(serverssl, TLS1_2_VERSION))
10591             || !TEST_true(SSL_set_max_proto_version(serverssl, TLS1_2_VERSION))
10592             || !TEST_true(SSL_set_cipher_list(serverssl, ciphersuite))
10593             || !TEST_true(SSL_set_cipher_list(clientssl, ciphersuite)))
10594         goto end;
10595 
10596     /*
10597      * Send the server's first flight. At this point the server has created the
10598      * temporary DH key but hasn't finished using it yet. Once used it is
10599      * removed, so we cannot test it.
10600      */
10601     if (!TEST_int_le(SSL_connect(clientssl), 0)
10602             || !TEST_int_le(SSL_accept(serverssl), 0))
10603         goto end;
10604 
10605     if (!TEST_int_gt(SSL_get_tmp_key(serverssl, &tmpkey), 0))
10606         goto end;
10607     if (!TEST_size_t_eq(EVP_PKEY_get_bits(tmpkey), expdhsize))
10608         goto end;
10609 
10610     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10611         goto end;
10612 
10613     testresult = 1;
10614 
10615  end:
10616     SSL_free(serverssl);
10617     SSL_free(clientssl);
10618     SSL_CTX_free(sctx);
10619     SSL_CTX_free(cctx);
10620     EVP_PKEY_free(tmpkey);
10621 
10622     return testresult;
10623 
10624 }
10625 # endif /* OPENSSL_NO_DH */
10626 #endif /* OPENSSL_NO_TLS1_2 */
10627 
10628 #ifndef OSSL_NO_USABLE_TLS1_3
10629 /*
10630  * Test that setting an SNI callback works with TLSv1.3. Specifically we check
10631  * that it works even without a certificate configured for the original
10632  * SSL_CTX
10633  */
test_sni_tls13(void)10634 static int test_sni_tls13(void)
10635 {
10636     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
10637     SSL *clientssl = NULL, *serverssl = NULL;
10638     int testresult = 0;
10639 
10640     /* Reset callback counter */
10641     snicb = 0;
10642 
10643     /* Create an initial SSL_CTX with no certificate configured */
10644     sctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10645     if (!TEST_ptr(sctx))
10646         goto end;
10647     /* Require TLSv1.3 as a minimum */
10648     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10649                                        TLS_client_method(), TLS1_3_VERSION, 0,
10650                                        &sctx2, &cctx, cert, privkey)))
10651         goto end;
10652 
10653     /* Set up SNI */
10654     if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
10655             || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
10656         goto end;
10657 
10658     /*
10659      * Connection should still succeed because the final SSL_CTX has the right
10660      * certificates configured.
10661      */
10662     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10663                                       &clientssl, NULL, NULL))
10664             || !TEST_true(create_ssl_connection(serverssl, clientssl,
10665                                                 SSL_ERROR_NONE)))
10666         goto end;
10667 
10668     /* We should have had the SNI callback called exactly once */
10669     if (!TEST_int_eq(snicb, 1))
10670         goto end;
10671 
10672     testresult = 1;
10673 
10674 end:
10675     SSL_free(serverssl);
10676     SSL_free(clientssl);
10677     SSL_CTX_free(sctx2);
10678     SSL_CTX_free(sctx);
10679     SSL_CTX_free(cctx);
10680     return testresult;
10681 }
10682 
10683 /*
10684  * Test that the lifetime hint of a TLSv1.3 ticket is no more than 1 week
10685  * 0 = TLSv1.2
10686  * 1 = TLSv1.3
10687  */
test_ticket_lifetime(int idx)10688 static int test_ticket_lifetime(int idx)
10689 {
10690     SSL_CTX *cctx = NULL, *sctx = NULL;
10691     SSL *clientssl = NULL, *serverssl = NULL;
10692     int testresult = 0;
10693     int version = TLS1_3_VERSION;
10694 
10695 #define ONE_WEEK_SEC (7 * 24 * 60 * 60)
10696 #define TWO_WEEK_SEC (2 * ONE_WEEK_SEC)
10697 
10698     if (idx == 0) {
10699 #ifdef OPENSSL_NO_TLS1_2
10700         return TEST_skip("TLS 1.2 is disabled.");
10701 #else
10702         version = TLS1_2_VERSION;
10703 #endif
10704     }
10705 
10706     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
10707                                        TLS_client_method(), version, version,
10708                                        &sctx, &cctx, cert, privkey)))
10709         goto end;
10710 
10711     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
10712                                       &clientssl, NULL, NULL)))
10713         goto end;
10714 
10715     /*
10716      * Set the timeout to be more than 1 week
10717      * make sure the returned value is the default
10718      */
10719     if (!TEST_long_eq(SSL_CTX_set_timeout(sctx, TWO_WEEK_SEC),
10720                       SSL_get_default_timeout(serverssl)))
10721         goto end;
10722 
10723     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
10724         goto end;
10725 
10726     if (idx == 0) {
10727         /* TLSv1.2 uses the set value */
10728         if (!TEST_ulong_eq(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), TWO_WEEK_SEC))
10729             goto end;
10730     } else {
10731         /* TLSv1.3 uses the limited value */
10732         if (!TEST_ulong_le(SSL_SESSION_get_ticket_lifetime_hint(SSL_get_session(clientssl)), ONE_WEEK_SEC))
10733             goto end;
10734     }
10735     testresult = 1;
10736 
10737 end:
10738     SSL_free(serverssl);
10739     SSL_free(clientssl);
10740     SSL_CTX_free(sctx);
10741     SSL_CTX_free(cctx);
10742     return testresult;
10743 }
10744 #endif
10745 /*
10746  * Test that setting an ALPN does not violate RFC
10747  */
test_set_alpn(void)10748 static int test_set_alpn(void)
10749 {
10750     SSL_CTX *ctx = NULL;
10751     SSL *ssl = NULL;
10752     int testresult = 0;
10753 
10754     unsigned char bad0[] = { 0x00, 'b', 'a', 'd' };
10755     unsigned char good[] = { 0x04, 'g', 'o', 'o', 'd' };
10756     unsigned char bad1[] = { 0x01, 'b', 'a', 'd' };
10757     unsigned char bad2[] = { 0x03, 'b', 'a', 'd', 0x00};
10758     unsigned char bad3[] = { 0x03, 'b', 'a', 'd', 0x01, 'b', 'a', 'd'};
10759     unsigned char bad4[] = { 0x03, 'b', 'a', 'd', 0x06, 'b', 'a', 'd'};
10760 
10761     /* Create an initial SSL_CTX with no certificate configured */
10762     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10763     if (!TEST_ptr(ctx))
10764         goto end;
10765 
10766     /* the set_alpn functions return 0 (false) on success, non-zero (true) on failure */
10767     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, NULL, 2)))
10768         goto end;
10769     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, 0)))
10770         goto end;
10771     if (!TEST_false(SSL_CTX_set_alpn_protos(ctx, good, sizeof(good))))
10772         goto end;
10773     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, good, 1)))
10774         goto end;
10775     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad0, sizeof(bad0))))
10776         goto end;
10777     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad1, sizeof(bad1))))
10778         goto end;
10779     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad2, sizeof(bad2))))
10780         goto end;
10781     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad3, sizeof(bad3))))
10782         goto end;
10783     if (!TEST_true(SSL_CTX_set_alpn_protos(ctx, bad4, sizeof(bad4))))
10784         goto end;
10785 
10786     ssl = SSL_new(ctx);
10787     if (!TEST_ptr(ssl))
10788         goto end;
10789 
10790     if (!TEST_false(SSL_set_alpn_protos(ssl, NULL, 2)))
10791         goto end;
10792     if (!TEST_false(SSL_set_alpn_protos(ssl, good, 0)))
10793         goto end;
10794     if (!TEST_false(SSL_set_alpn_protos(ssl, good, sizeof(good))))
10795         goto end;
10796     if (!TEST_true(SSL_set_alpn_protos(ssl, good, 1)))
10797         goto end;
10798     if (!TEST_true(SSL_set_alpn_protos(ssl, bad0, sizeof(bad0))))
10799         goto end;
10800     if (!TEST_true(SSL_set_alpn_protos(ssl, bad1, sizeof(bad1))))
10801         goto end;
10802     if (!TEST_true(SSL_set_alpn_protos(ssl, bad2, sizeof(bad2))))
10803         goto end;
10804     if (!TEST_true(SSL_set_alpn_protos(ssl, bad3, sizeof(bad3))))
10805         goto end;
10806     if (!TEST_true(SSL_set_alpn_protos(ssl, bad4, sizeof(bad4))))
10807         goto end;
10808 
10809     testresult = 1;
10810 
10811 end:
10812     SSL_free(ssl);
10813     SSL_CTX_free(ctx);
10814     return testresult;
10815 }
10816 
10817 /*
10818  * Test SSL_CTX_set1_verify/chain_cert_store and SSL_CTX_get_verify/chain_cert_store.
10819  */
test_set_verify_cert_store_ssl_ctx(void)10820 static int test_set_verify_cert_store_ssl_ctx(void)
10821 {
10822    SSL_CTX *ctx = NULL;
10823    int testresult = 0;
10824    X509_STORE *store = NULL, *new_store = NULL,
10825               *cstore = NULL, *new_cstore = NULL;
10826 
10827    /* Create an initial SSL_CTX. */
10828    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10829    if (!TEST_ptr(ctx))
10830        goto end;
10831 
10832    /* Retrieve verify store pointer. */
10833    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
10834        goto end;
10835 
10836    /* Retrieve chain store pointer. */
10837    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
10838        goto end;
10839 
10840    /* We haven't set any yet, so this should be NULL. */
10841    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10842        goto end;
10843 
10844    /* Create stores. We use separate stores so pointers are different. */
10845    new_store = X509_STORE_new();
10846    if (!TEST_ptr(new_store))
10847        goto end;
10848 
10849    new_cstore = X509_STORE_new();
10850    if (!TEST_ptr(new_cstore))
10851        goto end;
10852 
10853    /* Set stores. */
10854    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, new_store)))
10855        goto end;
10856 
10857    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, new_cstore)))
10858        goto end;
10859 
10860    /* Should be able to retrieve the same pointer. */
10861    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
10862        goto end;
10863 
10864    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
10865        goto end;
10866 
10867    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
10868        goto end;
10869 
10870    /* Should be able to unset again. */
10871    if (!TEST_true(SSL_CTX_set1_verify_cert_store(ctx, NULL)))
10872        goto end;
10873 
10874    if (!TEST_true(SSL_CTX_set1_chain_cert_store(ctx, NULL)))
10875        goto end;
10876 
10877    /* Should now be NULL. */
10878    if (!TEST_true(SSL_CTX_get0_verify_cert_store(ctx, &store)))
10879        goto end;
10880 
10881    if (!TEST_true(SSL_CTX_get0_chain_cert_store(ctx, &cstore)))
10882        goto end;
10883 
10884    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10885        goto end;
10886 
10887    testresult = 1;
10888 
10889 end:
10890    X509_STORE_free(new_store);
10891    X509_STORE_free(new_cstore);
10892    SSL_CTX_free(ctx);
10893    return testresult;
10894 }
10895 
10896 /*
10897  * Test SSL_set1_verify/chain_cert_store and SSL_get_verify/chain_cert_store.
10898  */
test_set_verify_cert_store_ssl(void)10899 static int test_set_verify_cert_store_ssl(void)
10900 {
10901    SSL_CTX *ctx = NULL;
10902    SSL *ssl = NULL;
10903    int testresult = 0;
10904    X509_STORE *store = NULL, *new_store = NULL,
10905               *cstore = NULL, *new_cstore = NULL;
10906 
10907    /* Create an initial SSL_CTX. */
10908    ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10909    if (!TEST_ptr(ctx))
10910        goto end;
10911 
10912    /* Create an SSL object. */
10913    ssl = SSL_new(ctx);
10914    if (!TEST_ptr(ssl))
10915        goto end;
10916 
10917    /* Retrieve verify store pointer. */
10918    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10919        goto end;
10920 
10921    /* Retrieve chain store pointer. */
10922    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10923        goto end;
10924 
10925    /* We haven't set any yet, so this should be NULL. */
10926    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10927        goto end;
10928 
10929    /* Create stores. We use separate stores so pointers are different. */
10930    new_store = X509_STORE_new();
10931    if (!TEST_ptr(new_store))
10932        goto end;
10933 
10934    new_cstore = X509_STORE_new();
10935    if (!TEST_ptr(new_cstore))
10936        goto end;
10937 
10938    /* Set stores. */
10939    if (!TEST_true(SSL_set1_verify_cert_store(ssl, new_store)))
10940        goto end;
10941 
10942    if (!TEST_true(SSL_set1_chain_cert_store(ssl, new_cstore)))
10943        goto end;
10944 
10945    /* Should be able to retrieve the same pointer. */
10946    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10947        goto end;
10948 
10949    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10950        goto end;
10951 
10952    if (!TEST_ptr_eq(store, new_store) || !TEST_ptr_eq(cstore, new_cstore))
10953        goto end;
10954 
10955    /* Should be able to unset again. */
10956    if (!TEST_true(SSL_set1_verify_cert_store(ssl, NULL)))
10957        goto end;
10958 
10959    if (!TEST_true(SSL_set1_chain_cert_store(ssl, NULL)))
10960        goto end;
10961 
10962    /* Should now be NULL. */
10963    if (!TEST_true(SSL_get0_verify_cert_store(ssl, &store)))
10964        goto end;
10965 
10966    if (!TEST_true(SSL_get0_chain_cert_store(ssl, &cstore)))
10967        goto end;
10968 
10969    if (!TEST_ptr_null(store) || !TEST_ptr_null(cstore))
10970        goto end;
10971 
10972    testresult = 1;
10973 
10974 end:
10975    X509_STORE_free(new_store);
10976    X509_STORE_free(new_cstore);
10977    SSL_free(ssl);
10978    SSL_CTX_free(ctx);
10979    return testresult;
10980 }
10981 
10982 
test_inherit_verify_param(void)10983 static int test_inherit_verify_param(void)
10984 {
10985     int testresult = 0;
10986 
10987     SSL_CTX *ctx = NULL;
10988     X509_VERIFY_PARAM *cp = NULL;
10989     SSL *ssl = NULL;
10990     X509_VERIFY_PARAM *sp = NULL;
10991     int hostflags = X509_CHECK_FLAG_NEVER_CHECK_SUBJECT;
10992 
10993     ctx = SSL_CTX_new_ex(libctx, NULL, TLS_server_method());
10994     if (!TEST_ptr(ctx))
10995         goto end;
10996 
10997     cp = SSL_CTX_get0_param(ctx);
10998     if (!TEST_ptr(cp))
10999         goto end;
11000     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(cp), 0))
11001         goto end;
11002 
11003     X509_VERIFY_PARAM_set_hostflags(cp, hostflags);
11004 
11005     ssl = SSL_new(ctx);
11006     if (!TEST_ptr(ssl))
11007         goto end;
11008 
11009     sp = SSL_get0_param(ssl);
11010     if (!TEST_ptr(sp))
11011         goto end;
11012     if (!TEST_int_eq(X509_VERIFY_PARAM_get_hostflags(sp), hostflags))
11013         goto end;
11014 
11015     testresult = 1;
11016 
11017  end:
11018     SSL_free(ssl);
11019     SSL_CTX_free(ctx);
11020 
11021     return testresult;
11022 }
11023 
test_load_dhfile(void)11024 static int test_load_dhfile(void)
11025 {
11026 #ifndef OPENSSL_NO_DH
11027     int testresult = 0;
11028 
11029     SSL_CTX *ctx = NULL;
11030     SSL_CONF_CTX *cctx = NULL;
11031 
11032     if (dhfile == NULL)
11033         return 1;
11034 
11035     if (!TEST_ptr(ctx = SSL_CTX_new_ex(libctx, NULL, TLS_client_method()))
11036         || !TEST_ptr(cctx = SSL_CONF_CTX_new()))
11037         goto end;
11038 
11039     SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
11040     SSL_CONF_CTX_set_flags(cctx,
11041                            SSL_CONF_FLAG_CERTIFICATE
11042                            | SSL_CONF_FLAG_SERVER
11043                            | SSL_CONF_FLAG_FILE);
11044 
11045     if (!TEST_int_eq(SSL_CONF_cmd(cctx, "DHParameters", dhfile), 2))
11046         goto end;
11047 
11048     testresult = 1;
11049 end:
11050     SSL_CONF_CTX_free(cctx);
11051     SSL_CTX_free(ctx);
11052 
11053     return testresult;
11054 #else
11055     return TEST_skip("DH not supported by this build");
11056 #endif
11057 }
11058 
11059 #ifndef OSSL_NO_USABLE_TLS1_3
11060 /* Test that read_ahead works across a key change */
test_read_ahead_key_change(void)11061 static int test_read_ahead_key_change(void)
11062 {
11063     SSL_CTX *cctx = NULL, *sctx = NULL;
11064     SSL *clientssl = NULL, *serverssl = NULL;
11065     int testresult = 0;
11066     char *msg = "Hello World";
11067     size_t written, readbytes;
11068     char buf[80];
11069     int i;
11070 
11071     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11072                                        TLS_client_method(), TLS1_3_VERSION, 0,
11073                                        &sctx, &cctx, cert, privkey)))
11074         goto end;
11075 
11076     SSL_CTX_set_read_ahead(sctx, 1);
11077 
11078     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11079                                       &clientssl, NULL, NULL)))
11080         goto end;
11081 
11082     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11083         goto end;
11084 
11085     /* Write some data, send a key update, write more data */
11086     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11087         || !TEST_size_t_eq(written, strlen(msg)))
11088         goto end;
11089 
11090     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
11091         goto end;
11092 
11093     if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11094         || !TEST_size_t_eq(written, strlen(msg)))
11095         goto end;
11096 
11097     /*
11098      * Since read_ahead is on the first read below should read the record with
11099      * the first app data, the second record with the key update message, and
11100      * the third record with the app data all in one go. We should be able to
11101      * still process the read_ahead data correctly even though it crosses
11102      * epochs
11103      */
11104     for (i = 0; i < 2; i++) {
11105         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11106                                     &readbytes)))
11107             goto end;
11108 
11109         buf[readbytes] = '\0';
11110         if (!TEST_str_eq(buf, msg))
11111             goto end;
11112     }
11113 
11114     testresult = 1;
11115 
11116 end:
11117     SSL_free(serverssl);
11118     SSL_free(clientssl);
11119     SSL_CTX_free(sctx);
11120     SSL_CTX_free(cctx);
11121     return testresult;
11122 }
11123 
record_pad_cb(SSL * s,int type,size_t len,void * arg)11124 static size_t record_pad_cb(SSL *s, int type, size_t len, void *arg)
11125 {
11126     int *called = arg;
11127 
11128     switch ((*called)++) {
11129     case 0:
11130         /* Add some padding to first record */
11131         return 512;
11132     case 1:
11133         /* Maximally pad the second record */
11134         return SSL3_RT_MAX_PLAIN_LENGTH - len;
11135     case 2:
11136         /*
11137          * Exceeding the maximum padding should be fine. It should just pad to
11138          * the maximum anyway
11139          */
11140         return SSL3_RT_MAX_PLAIN_LENGTH + 1 - len;
11141     case 3:
11142         /*
11143          * Very large padding should also be ok. Should just pad to the maximum
11144          * allowed
11145          */
11146         return SIZE_MAX;
11147     default:
11148         return 0;
11149     }
11150 }
11151 
11152 /*
11153  * Test that setting record padding in TLSv1.3 works as expected
11154  * Test 0: Record padding callback on the SSL_CTX
11155  * Test 1: Record padding callback on the SSL
11156  * Test 2: Record block padding on the SSL_CTX
11157  * Test 3: Record block padding on the SSL
11158  * Test 4: Extended record block padding on the SSL_CTX
11159  * Test 5: Extended record block padding on the SSL
11160  */
test_tls13_record_padding(int idx)11161 static int test_tls13_record_padding(int idx)
11162 {
11163     SSL_CTX *cctx = NULL, *sctx = NULL;
11164     SSL *clientssl = NULL, *serverssl = NULL;
11165     int testresult = 0;
11166     char *msg = "Hello World";
11167     size_t written, readbytes;
11168     char buf[80];
11169     int i;
11170     int called = 0;
11171 
11172     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11173                                        TLS_client_method(), TLS1_3_VERSION, 0,
11174                                        &sctx, &cctx, cert, privkey)))
11175         goto end;
11176 
11177     if (idx == 0) {
11178         SSL_CTX_set_record_padding_callback(cctx, record_pad_cb);
11179         SSL_CTX_set_record_padding_callback_arg(cctx, &called);
11180         if (!TEST_ptr_eq(SSL_CTX_get_record_padding_callback_arg(cctx), &called))
11181             goto end;
11182     } else if (idx == 2) {
11183         /* Exceeding the max plain length should fail */
11184         if (!TEST_false(SSL_CTX_set_block_padding(cctx,
11185                                                   SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11186             goto end;
11187         if (!TEST_true(SSL_CTX_set_block_padding(cctx, 512)))
11188             goto end;
11189     } else if (idx == 4) {
11190         /* pad only handshake/alert messages */
11191         if (!TEST_true(SSL_CTX_set_block_padding_ex(cctx, 0, 512)))
11192             goto end;
11193     }
11194 
11195     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11196                                       &clientssl, NULL, NULL)))
11197         goto end;
11198 
11199     if (idx == 1) {
11200         SSL_set_record_padding_callback(clientssl, record_pad_cb);
11201         SSL_set_record_padding_callback_arg(clientssl, &called);
11202         if (!TEST_ptr_eq(SSL_get_record_padding_callback_arg(clientssl), &called))
11203             goto end;
11204     } else if (idx == 3) {
11205         /* Exceeding the max plain length should fail */
11206         if (!TEST_false(SSL_set_block_padding(clientssl,
11207                                               SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11208             goto end;
11209         if (!TEST_true(SSL_set_block_padding(clientssl, 512)))
11210             goto end;
11211     } else if (idx == 5) {
11212         /* Exceeding the max plain length should fail */
11213         if (!TEST_false(SSL_set_block_padding_ex(clientssl, 0,
11214                                                  SSL3_RT_MAX_PLAIN_LENGTH + 1)))
11215             goto end;
11216         /* pad server and client handshake only */
11217         if (!TEST_true(SSL_set_block_padding_ex(clientssl, 0, 512)))
11218             goto end;
11219         if (!TEST_true(SSL_set_block_padding_ex(serverssl, 0, 512)))
11220             goto end;
11221     }
11222 
11223     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11224         goto end;
11225 
11226     called = 0;
11227     /*
11228      * Write some data, then check we can read it. Do this four times to check
11229      * we can continue to write and read padded data after the initial record
11230      * padding has been added. We don't actually check that the padding has
11231      * been applied to the record - just that we can continue to communicate
11232      * normally and that the callback has been called (if appropriate).
11233      */
11234     for (i = 0; i < 4; i++) {
11235         if (!TEST_true(SSL_write_ex(clientssl, msg, strlen(msg), &written))
11236             || !TEST_size_t_eq(written, strlen(msg)))
11237             goto end;
11238 
11239         if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf) - 1,
11240                                     &readbytes))
11241                 || !TEST_size_t_eq(written, readbytes))
11242             goto end;
11243 
11244         buf[readbytes] = '\0';
11245         if (!TEST_str_eq(buf, msg))
11246             goto end;
11247     }
11248 
11249     if ((idx == 0 || idx == 1) && !TEST_int_eq(called, 4))
11250         goto end;
11251 
11252     testresult = 1;
11253 end:
11254     SSL_free(serverssl);
11255     SSL_free(clientssl);
11256     SSL_CTX_free(sctx);
11257     SSL_CTX_free(cctx);
11258     return testresult;
11259 }
11260 #endif /* OSSL_NO_USABLE_TLS1_3 */
11261 
11262 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
11263 /*
11264  * Test TLSv1.2 with a pipeline capable cipher. TLSv1.3 and DTLS do not
11265  * support this yet. The only pipeline capable cipher that we have is in the
11266  * dasync engine (providers don't support this yet), so we have to use
11267  * deprecated APIs for this test.
11268  *
11269  * Test 0: Client has pipelining enabled, server does not
11270  * Test 1: Server has pipelining enabled, client does not
11271  * Test 2: Client has pipelining enabled, server does not: not enough data to
11272  *         fill all the pipelines
11273  * Test 3: Client has pipelining enabled, server does not: not enough data to
11274  *         fill all the pipelines by more than a full pipeline's worth
11275  * Test 4: Client has pipelining enabled, server does not: more data than all
11276  *         the available pipelines can take
11277  * Test 5: Client has pipelining enabled, server does not: Maximum size pipeline
11278  * Test 6: Repeat of test 0, but the engine is loaded late (after the SSL_CTX
11279  *         is created)
11280  */
test_pipelining(int idx)11281 static int test_pipelining(int idx)
11282 {
11283     SSL_CTX *cctx = NULL, *sctx = NULL;
11284     SSL *clientssl = NULL, *serverssl = NULL, *peera, *peerb;
11285     int testresult = 0, numreads;
11286     /* A 55 byte message */
11287     unsigned char *msg = (unsigned char *)
11288         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123";
11289     size_t written, readbytes, offset, msglen, fragsize = 10, numpipes = 5;
11290     size_t expectedreads;
11291     unsigned char *buf = NULL;
11292     ENGINE *e = NULL;
11293 
11294     if (idx != 6) {
11295         e = load_dasync();
11296         if (e == NULL)
11297             return 0;
11298     }
11299 
11300     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11301                                        TLS_client_method(), 0,
11302                                        TLS1_2_VERSION, &sctx, &cctx, cert,
11303                                        privkey)))
11304         goto end;
11305 
11306     if (idx == 6) {
11307         e = load_dasync();
11308         if (e == NULL)
11309             goto end;
11310         /* Now act like test 0 */
11311         idx = 0;
11312     }
11313 
11314     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11315                                       &clientssl, NULL, NULL)))
11316         goto end;
11317 
11318     if (!TEST_true(SSL_set_cipher_list(clientssl, "AES128-SHA")))
11319         goto end;
11320 
11321     /* peera is always configured for pipelining, while peerb is not. */
11322     if (idx == 1) {
11323         peera = serverssl;
11324         peerb = clientssl;
11325 
11326     } else {
11327         peera = clientssl;
11328         peerb = serverssl;
11329     }
11330 
11331     if (idx == 5) {
11332         numpipes = 2;
11333         /* Maximum allowed fragment size */
11334         fragsize = SSL3_RT_MAX_PLAIN_LENGTH;
11335         msglen = fragsize * numpipes;
11336         msg = OPENSSL_malloc(msglen);
11337         if (!TEST_ptr(msg))
11338             goto end;
11339         if (!TEST_int_gt(RAND_bytes_ex(libctx, msg, msglen, 0), 0))
11340             goto end;
11341     } else if (idx == 4) {
11342         msglen = 55;
11343     } else {
11344         msglen = 50;
11345     }
11346     if (idx == 2)
11347         msglen -= 2; /* Send 2 less bytes */
11348     else if (idx == 3)
11349         msglen -= 12; /* Send 12 less bytes */
11350 
11351     buf = OPENSSL_malloc(msglen);
11352     if (!TEST_ptr(buf))
11353         goto end;
11354 
11355     if (idx == 5) {
11356         /*
11357          * Test that setting a split send fragment longer than the maximum
11358          * allowed fails
11359          */
11360         if (!TEST_false(SSL_set_split_send_fragment(peera, fragsize + 1)))
11361             goto end;
11362     }
11363 
11364     /*
11365      * In the normal case. We have 5 pipelines with 10 bytes per pipeline
11366      * (50 bytes in total). This is a ridiculously small number of bytes -
11367      * but sufficient for our purposes
11368      */
11369     if (!TEST_true(SSL_set_max_pipelines(peera, numpipes))
11370             || !TEST_true(SSL_set_split_send_fragment(peera, fragsize)))
11371         goto end;
11372 
11373     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11374         goto end;
11375 
11376     /* Write some data from peera to peerb */
11377     if (!TEST_true(SSL_write_ex(peera, msg, msglen, &written))
11378         || !TEST_size_t_eq(written, msglen))
11379         goto end;
11380 
11381     /*
11382      * If the pipelining code worked, then we expect all |numpipes| pipelines to
11383      * have been used - except in test 3 where only |numpipes - 1| pipelines
11384      * will be used. This will result in |numpipes| records (|numpipes - 1| for
11385      * test 3) having been sent to peerb. Since peerb is not using read_ahead we
11386      * expect this to be read in |numpipes| or |numpipes - 1| separate
11387      * SSL_read_ex calls. In the case of test 4, there is then one additional
11388      * read for left over data that couldn't fit in the previous pipelines
11389      */
11390     for (offset = 0, numreads = 0;
11391          offset < msglen;
11392          offset += readbytes, numreads++) {
11393         if (!TEST_true(SSL_read_ex(peerb, buf + offset,
11394                                    msglen - offset, &readbytes)))
11395             goto end;
11396     }
11397 
11398     expectedreads = idx == 4 ? numpipes + 1
11399                              : (idx == 3 ? numpipes - 1 : numpipes);
11400     if (!TEST_mem_eq(msg, msglen, buf, offset)
11401             || !TEST_int_eq(numreads, expectedreads))
11402         goto end;
11403 
11404     /*
11405      * Write some data from peerb to peera. We do this in up to |numpipes + 1|
11406      * chunks to exercise the read pipelining code on peera.
11407      */
11408     for (offset = 0; offset < msglen; offset += fragsize) {
11409         size_t sendlen = msglen - offset;
11410 
11411         if (sendlen > fragsize)
11412             sendlen = fragsize;
11413         if (!TEST_true(SSL_write_ex(peerb, msg + offset, sendlen, &written))
11414                 || !TEST_size_t_eq(written, sendlen))
11415             goto end;
11416     }
11417 
11418     /*
11419      * The data was written in |numpipes|, |numpipes - 1| or |numpipes + 1|
11420      * separate chunks (depending on which test we are running). If the
11421      * pipelining is working then we expect peera to read up to numpipes chunks
11422      * and process them in parallel, giving back the complete result in a single
11423      * call to SSL_read_ex
11424      */
11425     if (!TEST_true(SSL_read_ex(peera, buf, msglen, &readbytes))
11426             || !TEST_size_t_le(readbytes, msglen))
11427         goto end;
11428 
11429     if (idx == 4) {
11430         size_t readbytes2;
11431 
11432         if (!TEST_true(SSL_read_ex(peera, buf + readbytes,
11433                                    msglen - readbytes, &readbytes2)))
11434             goto end;
11435         readbytes += readbytes2;
11436         if (!TEST_size_t_le(readbytes, msglen))
11437             goto end;
11438     }
11439 
11440     if (!TEST_mem_eq(msg, msglen, buf, readbytes))
11441         goto end;
11442 
11443     testresult = 1;
11444 end:
11445     SSL_free(serverssl);
11446     SSL_free(clientssl);
11447     SSL_CTX_free(sctx);
11448     SSL_CTX_free(cctx);
11449     if (e != NULL) {
11450         ENGINE_unregister_ciphers(e);
11451         ENGINE_finish(e);
11452         ENGINE_free(e);
11453     }
11454     OPENSSL_free(buf);
11455     if (fragsize == SSL3_RT_MAX_PLAIN_LENGTH)
11456         OPENSSL_free(msg);
11457     return testresult;
11458 }
11459 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE) */
11460 
check_version_string(SSL * s,int version)11461 static int check_version_string(SSL *s, int version)
11462 {
11463     const char *verstr = NULL;
11464 
11465     switch (version) {
11466     case SSL3_VERSION:
11467         verstr = "SSLv3";
11468         break;
11469     case TLS1_VERSION:
11470         verstr = "TLSv1";
11471         break;
11472     case TLS1_1_VERSION:
11473         verstr = "TLSv1.1";
11474         break;
11475     case TLS1_2_VERSION:
11476         verstr = "TLSv1.2";
11477         break;
11478     case TLS1_3_VERSION:
11479         verstr = "TLSv1.3";
11480         break;
11481     case DTLS1_VERSION:
11482         verstr = "DTLSv1";
11483         break;
11484     case DTLS1_2_VERSION:
11485         verstr = "DTLSv1.2";
11486     }
11487 
11488     return TEST_str_eq(verstr, SSL_get_version(s));
11489 }
11490 
11491 /*
11492  * Test that SSL_version, SSL_get_version, SSL_is_quic, SSL_is_tls and
11493  * SSL_is_dtls return the expected results for a (D)TLS connection. Compare with
11494  * test_version() in quicapitest.c which does the same thing for QUIC
11495  * connections.
11496  */
test_version(int idx)11497 static int test_version(int idx)
11498 {
11499     SSL_CTX *cctx = NULL, *sctx = NULL;
11500     SSL *clientssl = NULL, *serverssl = NULL;
11501     int testresult = 0, version;
11502     const SSL_METHOD *servmeth = TLS_server_method();
11503     const SSL_METHOD *clientmeth = TLS_client_method();
11504 
11505     switch (idx) {
11506 #if !defined(OPENSSL_NO_SSL3)
11507     case 0:
11508         version = SSL3_VERSION;
11509         break;
11510 #endif
11511 #if !defined(OPENSSL_NO_TLS1)
11512     case 1:
11513         version = TLS1_VERSION;
11514         break;
11515 #endif
11516 #if !defined(OPENSSL_NO_TLS1_2)
11517     case 2:
11518         version = TLS1_2_VERSION;
11519         break;
11520 #endif
11521 #if !defined(OSSL_NO_USABLE_TLS1_3)
11522     case 3:
11523         version = TLS1_3_VERSION;
11524         break;
11525 #endif
11526 #if !defined(OPENSSL_NO_DTLS1)
11527     case 4:
11528         version = DTLS1_VERSION;
11529         break;
11530 #endif
11531 #if !defined(OPENSSL_NO_DTLS1_2)
11532     case 5:
11533         version = DTLS1_2_VERSION;
11534         break;
11535 #endif
11536     /*
11537      * NB we do not support QUIC in this test. That is covered by quicapitest.c
11538      * We also don't support DTLS1_BAD_VER since we have no server support for
11539      * that.
11540      */
11541     default:
11542         TEST_skip("Unsupported protocol version");
11543         return 1;
11544     }
11545 
11546     if (is_fips
11547             && (version == SSL3_VERSION
11548                 || version == TLS1_VERSION
11549                 || version == DTLS1_VERSION)) {
11550         TEST_skip("Protocol version not supported with FIPS");
11551         return 1;
11552     }
11553 
11554 #if !defined(OPENSSL_NO_DTLS)
11555     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11556         servmeth = DTLS_server_method();
11557         clientmeth = DTLS_client_method();
11558     }
11559 #endif
11560 
11561     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, version,
11562                                        version, &sctx, &cctx, cert, privkey)))
11563         goto end;
11564 
11565     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
11566             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
11567                                                 "DEFAULT:@SECLEVEL=0")))
11568         goto end;
11569 
11570     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11571                                       &clientssl, NULL, NULL)))
11572         goto end;
11573 
11574     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11575         goto end;
11576 
11577     if (!TEST_int_eq(SSL_version(serverssl), version)
11578             || !TEST_int_eq(SSL_version(clientssl), version)
11579             || !TEST_true(check_version_string(serverssl, version))
11580             || !TEST_true(check_version_string(clientssl, version)))
11581         goto end;
11582 
11583     if (version == DTLS1_VERSION || version == DTLS1_2_VERSION) {
11584         if (!TEST_true(SSL_is_dtls(serverssl))
11585                 || !TEST_true(SSL_is_dtls(clientssl))
11586                 || !TEST_false(SSL_is_tls(serverssl))
11587                 || !TEST_false(SSL_is_tls(clientssl))
11588                 || !TEST_false(SSL_is_quic(serverssl))
11589                 || !TEST_false(SSL_is_quic(clientssl)))
11590         goto end;
11591     } else {
11592         if (!TEST_true(SSL_is_tls(serverssl))
11593                 || !TEST_true(SSL_is_tls(clientssl))
11594                 || !TEST_false(SSL_is_dtls(serverssl))
11595                 || !TEST_false(SSL_is_dtls(clientssl))
11596                 || !TEST_false(SSL_is_quic(serverssl))
11597                 || !TEST_false(SSL_is_quic(clientssl)))
11598         goto end;
11599     }
11600 
11601     testresult = 1;
11602 end:
11603     SSL_free(serverssl);
11604     SSL_free(clientssl);
11605     SSL_CTX_free(sctx);
11606     SSL_CTX_free(cctx);
11607     return testresult;
11608 }
11609 
11610 /*
11611  * Test that the SSL_rstate_string*() APIs return sane results
11612  */
test_rstate_string(void)11613 static int test_rstate_string(void)
11614 {
11615     SSL_CTX *cctx = NULL, *sctx = NULL;
11616     SSL *clientssl = NULL, *serverssl = NULL;
11617     int testresult = 0, version;
11618     const SSL_METHOD *servmeth = TLS_server_method();
11619     const SSL_METHOD *clientmeth = TLS_client_method();
11620     size_t written, readbytes;
11621     unsigned char buf[2];
11622     unsigned char dummyheader[SSL3_RT_HEADER_LENGTH] = {
11623         SSL3_RT_APPLICATION_DATA,
11624         TLS1_2_VERSION_MAJOR,
11625         0, /* To be filled in later */
11626         0,
11627         1
11628     };
11629 
11630     if (!TEST_true(create_ssl_ctx_pair(libctx, servmeth, clientmeth, 0,
11631                                        0, &sctx, &cctx, cert, privkey)))
11632         goto end;
11633 
11634     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11635                                       &clientssl, NULL, NULL)))
11636         goto end;
11637 
11638     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11639             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11640         goto end;
11641 
11642     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11643         goto end;
11644 
11645     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RH")
11646             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read header"))
11647         goto end;
11648 
11649     /* Fill in the correct version for the record header */
11650     version = SSL_version(serverssl);
11651     if (version == TLS1_3_VERSION)
11652         version = TLS1_2_VERSION;
11653     dummyheader[2] = version & 0xff;
11654 
11655     /*
11656      * Send a dummy header. If we continued to read the body as well this
11657      * would fail with a bad record mac, but we're not going to go that far.
11658      */
11659     if (!TEST_true(BIO_write_ex(SSL_get_rbio(serverssl), dummyheader,
11660                                 sizeof(dummyheader), &written))
11661             || !TEST_size_t_eq(written, SSL3_RT_HEADER_LENGTH))
11662         goto end;
11663 
11664     if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes)))
11665         goto end;
11666 
11667     if (!TEST_str_eq(SSL_rstate_string(serverssl), "RB")
11668             || !TEST_str_eq(SSL_rstate_string_long(serverssl), "read body"))
11669         goto end;
11670 
11671     testresult = 1;
11672 end:
11673     SSL_free(serverssl);
11674     SSL_free(clientssl);
11675     SSL_CTX_free(sctx);
11676     SSL_CTX_free(cctx);
11677     return testresult;
11678 }
11679 
11680 /*
11681  * Force a write retry during handshaking. We test various combinations of
11682  * scenarios. We test a large certificate message which will fill the buffering
11683  * BIO used in the handshake. We try with client auth on and off. Finally we
11684  * also try a BIO that indicates retry via a 0 return. BIO_write() is documented
11685  * to indicate retry via -1 - but sometimes BIOs don't do that.
11686  *
11687  * Test 0: Standard certificate message
11688  * Test 1: Large certificate message
11689  * Test 2: Standard cert, verify peer
11690  * Test 3: Large cert, verify peer
11691  * Test 4: Standard cert, BIO returns 0 on retry
11692  * Test 5: Large cert, BIO returns 0 on retry
11693  * Test 6: Standard cert, verify peer, BIO returns 0 on retry
11694  * Test 7: Large cert, verify peer, BIO returns 0 on retry
11695  * Test 8-15: Repeat of above with TLSv1.2
11696  */
test_handshake_retry(int idx)11697 static int test_handshake_retry(int idx)
11698 {
11699     SSL_CTX *cctx = NULL, *sctx = NULL;
11700     SSL *clientssl = NULL, *serverssl = NULL;
11701     int testresult = 0;
11702     BIO *tmp = NULL, *bretry = BIO_new(bio_s_always_retry());
11703     int maxversion = 0;
11704 
11705     if (!TEST_ptr(bretry))
11706         goto end;
11707 
11708 #ifndef OPENSSL_NO_TLS1_2
11709     if ((idx & 8) == 8)
11710         maxversion = TLS1_2_VERSION;
11711 #else
11712     if ((idx & 8) == 8)
11713         return TEST_skip("No TLSv1.2");
11714 #endif
11715 
11716     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11717                                        TLS_client_method(), 0, maxversion,
11718                                        &sctx, &cctx, cert, privkey)))
11719         goto end;
11720 
11721     /*
11722      * Add a large amount of data to fill the buffering BIO used by the SSL
11723      * object
11724      */
11725     if ((idx & 1) == 1 && !ssl_ctx_add_large_cert_chain(libctx, sctx, cert))
11726         goto end;
11727 
11728     /*
11729      * We don't actually configure a client cert, but neither do we fail if one
11730      * isn't present.
11731      */
11732     if ((idx & 2) == 2)
11733         SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
11734 
11735     if ((idx & 4) == 4)
11736         set_always_retry_err_val(0);
11737 
11738     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
11739                                       &clientssl, NULL, NULL)))
11740         goto end;
11741 
11742     tmp = SSL_get_wbio(serverssl);
11743     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
11744         tmp = NULL;
11745         goto end;
11746     }
11747     SSL_set0_wbio(serverssl, bretry);
11748     bretry = NULL;
11749 
11750     if (!TEST_int_eq(SSL_connect(clientssl), -1))
11751         goto end;
11752 
11753     if (!TEST_int_eq(SSL_accept(serverssl), -1)
11754             || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_WRITE))
11755         goto end;
11756 
11757     /* Restore a BIO that will let the write succeed */
11758     SSL_set0_wbio(serverssl, tmp);
11759     tmp = NULL;
11760 
11761     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11762         goto end;
11763 
11764     testresult = 1;
11765 end:
11766     SSL_free(serverssl);
11767     SSL_free(clientssl);
11768     SSL_CTX_free(sctx);
11769     SSL_CTX_free(cctx);
11770     BIO_free(bretry);
11771     BIO_free(tmp);
11772     set_always_retry_err_val(-1);
11773     return testresult;
11774 }
11775 
11776 /*
11777  * Test that receiving retries when writing application data works as expected
11778  */
test_data_retry(void)11779 static int test_data_retry(void)
11780 {
11781     SSL_CTX *cctx = NULL, *sctx = NULL;
11782     SSL *clientssl = NULL, *serverssl = NULL;
11783     int testresult = 0;
11784     unsigned char inbuf[1200], outbuf[1200];
11785     size_t i;
11786     BIO *tmp = NULL;
11787     BIO *bretry = BIO_new(bio_s_maybe_retry());
11788     size_t written, readbytes, totread = 0;
11789 
11790     if (!TEST_ptr(bretry))
11791         goto end;
11792 
11793     for (i = 0; i < sizeof(inbuf); i++)
11794         inbuf[i] = (unsigned char)(0xff & i);
11795     memset(outbuf, 0, sizeof(outbuf));
11796 
11797     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11798                                        TLS_client_method(), 0, 0, &sctx, &cctx,
11799                                        cert, privkey)))
11800         goto end;
11801 
11802     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
11803                                       NULL)))
11804         goto end;
11805 
11806     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
11807         goto end;
11808 
11809     /* Smallest possible max send fragment is 512 */
11810     if (!TEST_true(SSL_set_max_send_fragment(clientssl, 512)))
11811         goto end;
11812 
11813     tmp = SSL_get_wbio(clientssl);
11814     if (!TEST_ptr(tmp))
11815         goto end;
11816     if (!TEST_true(BIO_up_ref(tmp)))
11817         goto end;
11818     BIO_push(bretry, tmp);
11819     tmp = NULL;
11820     SSL_set0_wbio(clientssl, bretry);
11821     if (!BIO_up_ref(bretry)) {
11822         bretry = NULL;
11823         goto end;
11824     }
11825 
11826     for (i = 0; i < 3; i++) {
11827         /* We expect this call to make no progress and indicate retry */
11828         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
11829             goto end;
11830         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
11831             goto end;
11832 
11833         /* Allow one write to progress, but the next one to signal retry */
11834         if (!TEST_true(BIO_ctrl(bretry, MAYBE_RETRY_CTRL_SET_RETRY_AFTER_CNT, 1,
11835                                 NULL)))
11836             goto end;
11837 
11838         if (i == 2)
11839             break;
11840 
11841         /*
11842          * This call will hopefully make progress but will still indicate retry
11843          * because there is more data than will fit into a single record.
11844          */
11845         if (!TEST_false(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
11846             goto end;
11847         if (!TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_WANT_WRITE))
11848             goto end;
11849     }
11850 
11851     /* The final call should write the last chunk of data and succeed */
11852     if (!TEST_true(SSL_write_ex(clientssl, inbuf, sizeof(inbuf), &written)))
11853         goto end;
11854     /* Read all the data available */
11855     while (SSL_read_ex(serverssl, outbuf + totread, sizeof(outbuf) - totread,
11856                        &readbytes))
11857         totread += readbytes;
11858     if (!TEST_mem_eq(inbuf, sizeof(inbuf), outbuf, totread))
11859         goto end;
11860 
11861     testresult = 1;
11862 end:
11863     SSL_free(serverssl);
11864     SSL_free(clientssl);
11865     SSL_CTX_free(sctx);
11866     SSL_CTX_free(cctx);
11867     BIO_free_all(bretry);
11868     BIO_free(tmp);
11869     return testresult;
11870 }
11871 
11872 struct resume_servername_cb_data {
11873     int i;
11874     SSL_CTX *cctx;
11875     SSL_CTX *sctx;
11876     SSL_SESSION *sess;
11877     int recurse;
11878 };
11879 
11880 /*
11881  * Servername callback. We use it here to run another complete handshake using
11882  * the same session - and mark the session as not_resuamble at the end
11883  */
resume_servername_cb(SSL * s,int * ad,void * arg)11884 static int resume_servername_cb(SSL *s, int *ad, void *arg)
11885 {
11886     struct resume_servername_cb_data *cbdata = arg;
11887     SSL *serverssl = NULL, *clientssl = NULL;
11888     int ret = SSL_TLSEXT_ERR_ALERT_FATAL;
11889 
11890     if (cbdata->recurse)
11891         return SSL_TLSEXT_ERR_ALERT_FATAL;
11892 
11893     if ((cbdata->i % 3) != 1)
11894         return SSL_TLSEXT_ERR_OK;
11895 
11896     cbdata->recurse = 1;
11897 
11898     if (!TEST_true(create_ssl_objects(cbdata->sctx, cbdata->cctx, &serverssl,
11899                                       &clientssl, NULL, NULL))
11900             || !TEST_true(SSL_set_session(clientssl, cbdata->sess)))
11901         goto end;
11902 
11903     ERR_set_mark();
11904     /*
11905      * We expect this to fail - because the servername cb will fail. This will
11906      * mark the session as not_resumable.
11907      */
11908     if (!TEST_false(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))) {
11909         ERR_clear_last_mark();
11910         goto end;
11911     }
11912     ERR_pop_to_mark();
11913 
11914     ret = SSL_TLSEXT_ERR_OK;
11915  end:
11916     SSL_free(serverssl);
11917     SSL_free(clientssl);
11918     cbdata->recurse = 0;
11919     return ret;
11920 }
11921 /*
11922  * Test multiple resumptions and cache size handling
11923  * Test 0: TLSv1.3 (max_early_data set)
11924  * Test 1: TLSv1.3 (SSL_OP_NO_TICKET set)
11925  * Test 2: TLSv1.3 (max_early_data and SSL_OP_NO_TICKET set)
11926  * Test 3: TLSv1.3 (SSL_OP_NO_TICKET, simultaneous resumes)
11927  * Test 4: TLSv1.2
11928  */
test_multi_resume(int idx)11929 static int test_multi_resume(int idx)
11930 {
11931     SSL_CTX *sctx = NULL, *cctx = NULL;
11932     SSL *serverssl = NULL, *clientssl = NULL;
11933     SSL_SESSION *sess = NULL;
11934     int max_version = TLS1_3_VERSION;
11935     int i, testresult = 0;
11936     struct resume_servername_cb_data cbdata;
11937 
11938 #if defined(OPENSSL_NO_TLS1_2)
11939     if (idx == 4)
11940         return TEST_skip("TLSv1.2 is disabled in this build");
11941 #else
11942     if (idx == 4)
11943         max_version = TLS1_2_VERSION;
11944 #endif
11945 #if defined(OSSL_NO_USABLE_TLS1_3)
11946     if (idx != 4)
11947         return TEST_skip("No usable TLSv1.3 in this build");
11948 #endif
11949 
11950     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
11951                                        TLS_client_method(), TLS1_VERSION,
11952                                        max_version, &sctx, &cctx, cert,
11953                                        privkey)))
11954         goto end;
11955 
11956     /*
11957      * TLSv1.3 only uses a session cache if either max_early_data > 0 (used for
11958      * replay protection), or if SSL_OP_NO_TICKET is in use
11959      */
11960     if (idx == 0 || idx == 2)  {
11961         if (!TEST_true(SSL_CTX_set_max_early_data(sctx, 1024)))
11962             goto end;
11963     }
11964     if (idx == 1 || idx == 2 || idx == 3)
11965         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
11966 
11967     SSL_CTX_sess_set_cache_size(sctx, 5);
11968 
11969     if (idx == 3) {
11970         SSL_CTX_set_tlsext_servername_callback(sctx, resume_servername_cb);
11971         SSL_CTX_set_tlsext_servername_arg(sctx, &cbdata);
11972         cbdata.cctx = cctx;
11973         cbdata.sctx = sctx;
11974         cbdata.recurse = 0;
11975     }
11976 
11977     for (i = 0; i < 30; i++) {
11978         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
11979                                                 NULL, NULL))
11980                 || !TEST_true(SSL_set_session(clientssl, sess)))
11981             goto end;
11982 
11983         /*
11984          * Check simultaneous resumes. We pause the connection part way through
11985          * the handshake by (mis)using the servername_cb. The pause occurs after
11986          * session resumption has already occurred, but before any session
11987          * tickets have been issued. While paused we run another complete
11988          * handshake resuming the same session.
11989          */
11990         if (idx == 3) {
11991             cbdata.i = i;
11992             cbdata.sess = sess;
11993         }
11994 
11995         /*
11996          * Recreate a bug where dynamically changing the max_early_data value
11997          * can cause sessions in the session cache which cannot be deleted.
11998          */
11999         if ((idx == 0 || idx == 2) && (i % 3) == 2)
12000             SSL_set_max_early_data(serverssl, 0);
12001 
12002         if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
12003             goto end;
12004 
12005         if (sess == NULL || (idx == 0 && (i % 3) == 2)) {
12006             if (!TEST_false(SSL_session_reused(clientssl)))
12007                 goto end;
12008         } else {
12009             if (!TEST_true(SSL_session_reused(clientssl)))
12010                 goto end;
12011         }
12012         SSL_SESSION_free(sess);
12013 
12014         /* Do a full handshake, followed by two resumptions */
12015         if ((i % 3) == 2) {
12016             sess = NULL;
12017         } else {
12018             if (!TEST_ptr((sess = SSL_get1_session(clientssl))))
12019                 goto end;
12020         }
12021 
12022         SSL_shutdown(clientssl);
12023         SSL_shutdown(serverssl);
12024         SSL_free(serverssl);
12025         SSL_free(clientssl);
12026         serverssl = clientssl = NULL;
12027     }
12028 
12029     /* We should never exceed the session cache size limit */
12030     if (!TEST_long_le(SSL_CTX_sess_number(sctx), 5))
12031         goto end;
12032 
12033     testresult = 1;
12034  end:
12035     SSL_free(serverssl);
12036     SSL_free(clientssl);
12037     SSL_CTX_free(sctx);
12038     SSL_CTX_free(cctx);
12039     SSL_SESSION_free(sess);
12040     return testresult;
12041 }
12042 
12043 static struct next_proto_st {
12044     int serverlen;
12045     unsigned char server[40];
12046     int clientlen;
12047     unsigned char client[40];
12048     int expected_ret;
12049     size_t selectedlen;
12050     unsigned char selected[40];
12051 } next_proto_tests[] = {
12052     {
12053         4, { 3, 'a', 'b', 'c' },
12054         4, { 3, 'a', 'b', 'c' },
12055         OPENSSL_NPN_NEGOTIATED,
12056         3, { 'a', 'b', 'c' }
12057     },
12058     {
12059         7, { 3, 'a', 'b', 'c', 2, 'a', 'b' },
12060         4, { 3, 'a', 'b', 'c' },
12061         OPENSSL_NPN_NEGOTIATED,
12062         3, { 'a', 'b', 'c' }
12063     },
12064     {
12065         7, { 2, 'a', 'b', 3, 'a', 'b', 'c', },
12066         4, { 3, 'a', 'b', 'c' },
12067         OPENSSL_NPN_NEGOTIATED,
12068         3, { 'a', 'b', 'c' }
12069     },
12070     {
12071         4, { 3, 'a', 'b', 'c' },
12072         7, { 3, 'a', 'b', 'c', 2, 'a', 'b', },
12073         OPENSSL_NPN_NEGOTIATED,
12074         3, { 'a', 'b', 'c' }
12075     },
12076     {
12077         4, { 3, 'a', 'b', 'c' },
12078         7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
12079         OPENSSL_NPN_NEGOTIATED,
12080         3, { 'a', 'b', 'c' }
12081     },
12082     {
12083         7, { 2, 'b', 'c', 3, 'a', 'b', 'c' },
12084         7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
12085         OPENSSL_NPN_NEGOTIATED,
12086         3, { 'a', 'b', 'c' }
12087     },
12088     {
12089         10, { 2, 'b', 'c', 3, 'a', 'b', 'c', 2, 'a', 'b' },
12090         7, { 2, 'a', 'b', 3, 'a', 'b', 'c'},
12091         OPENSSL_NPN_NEGOTIATED,
12092         3, { 'a', 'b', 'c' }
12093     },
12094     {
12095         4, { 3, 'b', 'c', 'd' },
12096         4, { 3, 'a', 'b', 'c' },
12097         OPENSSL_NPN_NO_OVERLAP,
12098         3, { 'a', 'b', 'c' }
12099     },
12100     {
12101         0, { 0 },
12102         4, { 3, 'a', 'b', 'c' },
12103         OPENSSL_NPN_NO_OVERLAP,
12104         3, { 'a', 'b', 'c' }
12105     },
12106     {
12107         -1, { 0 },
12108         4, { 3, 'a', 'b', 'c' },
12109         OPENSSL_NPN_NO_OVERLAP,
12110         3, { 'a', 'b', 'c' }
12111     },
12112     {
12113         4, { 3, 'a', 'b', 'c' },
12114         0, { 0 },
12115         OPENSSL_NPN_NO_OVERLAP,
12116         0, { 0 }
12117     },
12118     {
12119         4, { 3, 'a', 'b', 'c' },
12120         -1, { 0 },
12121         OPENSSL_NPN_NO_OVERLAP,
12122         0, { 0 }
12123     },
12124     {
12125         3, { 3, 'a', 'b', 'c' },
12126         4, { 3, 'a', 'b', 'c' },
12127         OPENSSL_NPN_NO_OVERLAP,
12128         3, { 'a', 'b', 'c' }
12129     },
12130     {
12131         4, { 3, 'a', 'b', 'c' },
12132         3, { 3, 'a', 'b', 'c' },
12133         OPENSSL_NPN_NO_OVERLAP,
12134         0, { 0 }
12135     }
12136 };
12137 
test_select_next_proto(int idx)12138 static int test_select_next_proto(int idx)
12139 {
12140     struct next_proto_st *np = &next_proto_tests[idx];
12141     int ret = 0;
12142     unsigned char *out, *client, *server;
12143     unsigned char outlen;
12144     unsigned int clientlen, serverlen;
12145 
12146     if (np->clientlen == -1) {
12147         client = NULL;
12148         clientlen = 0;
12149     } else {
12150         client = np->client;
12151         clientlen = (unsigned int)np->clientlen;
12152     }
12153     if (np->serverlen == -1) {
12154         server = NULL;
12155         serverlen = 0;
12156     } else {
12157         server = np->server;
12158         serverlen = (unsigned int)np->serverlen;
12159     }
12160 
12161     if (!TEST_int_eq(SSL_select_next_proto(&out, &outlen, server, serverlen,
12162                                            client, clientlen),
12163                      np->expected_ret))
12164         goto err;
12165 
12166     if (np->selectedlen == 0) {
12167         if (!TEST_ptr_null(out) || !TEST_uchar_eq(outlen, 0))
12168             goto err;
12169     } else {
12170         if (!TEST_mem_eq(out, outlen, np->selected, np->selectedlen))
12171             goto err;
12172     }
12173 
12174     ret = 1;
12175  err:
12176     return ret;
12177 }
12178 
12179 static const unsigned char fooprot[] = {3, 'f', 'o', 'o' };
12180 static const unsigned char barprot[] = {3, 'b', 'a', 'r' };
12181 
12182 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
npn_advert_cb(SSL * ssl,const unsigned char ** out,unsigned int * outlen,void * arg)12183 static int npn_advert_cb(SSL *ssl, const unsigned char **out,
12184                          unsigned int *outlen, void *arg)
12185 {
12186     int *idx = (int *)arg;
12187 
12188     switch (*idx) {
12189     default:
12190     case 0:
12191         *out = fooprot;
12192         *outlen = sizeof(fooprot);
12193         return SSL_TLSEXT_ERR_OK;
12194 
12195     case 1:
12196         *outlen = 0;
12197         return SSL_TLSEXT_ERR_OK;
12198 
12199     case 2:
12200         return SSL_TLSEXT_ERR_NOACK;
12201     }
12202 }
12203 
npn_select_cb(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)12204 static int npn_select_cb(SSL *s, unsigned char **out, unsigned char *outlen,
12205                          const unsigned char *in, unsigned int inlen, void *arg)
12206 {
12207     int *idx = (int *)arg;
12208 
12209     switch (*idx) {
12210     case 0:
12211     case 1:
12212         *out = (unsigned char *)(fooprot + 1);
12213         *outlen = *fooprot;
12214         return SSL_TLSEXT_ERR_OK;
12215 
12216     case 3:
12217         *out = (unsigned char *)(barprot + 1);
12218         *outlen = *barprot;
12219         return SSL_TLSEXT_ERR_OK;
12220 
12221     case 4:
12222         *outlen = 0;
12223         return SSL_TLSEXT_ERR_OK;
12224 
12225     default:
12226     case 2:
12227         return SSL_TLSEXT_ERR_ALERT_FATAL;
12228     }
12229 }
12230 
12231 /*
12232  * Test the NPN callbacks
12233  * Test 0: advert = foo, select = foo
12234  * Test 1: advert = <empty>, select = foo
12235  * Test 2: no advert
12236  * Test 3: advert = foo, select = bar
12237  * Test 4: advert = foo, select = <empty> (should fail)
12238  */
test_npn(int idx)12239 static int test_npn(int idx)
12240 {
12241     SSL_CTX *sctx = NULL, *cctx = NULL;
12242     SSL *serverssl = NULL, *clientssl = NULL;
12243     int testresult = 0;
12244 
12245     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12246                                        TLS_client_method(), 0, TLS1_2_VERSION,
12247                                        &sctx, &cctx, cert, privkey)))
12248         goto end;
12249 
12250     SSL_CTX_set_next_protos_advertised_cb(sctx, npn_advert_cb, &idx);
12251     SSL_CTX_set_next_proto_select_cb(cctx, npn_select_cb, &idx);
12252 
12253     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12254                                       NULL)))
12255         goto end;
12256 
12257     if (idx == 4) {
12258         /* We don't allow empty selection of NPN, so this should fail */
12259         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12260                                               SSL_ERROR_NONE)))
12261             goto end;
12262     } else {
12263         const unsigned char *prot;
12264         unsigned int protlen;
12265 
12266         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12267                                              SSL_ERROR_NONE)))
12268             goto end;
12269 
12270         SSL_get0_next_proto_negotiated(serverssl, &prot, &protlen);
12271         switch (idx) {
12272         case 0:
12273         case 1:
12274             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12275                 goto end;
12276             break;
12277         case 2:
12278             if (!TEST_uint_eq(protlen, 0))
12279                 goto end;
12280             break;
12281         case 3:
12282             if (!TEST_mem_eq(prot, protlen, barprot + 1, *barprot))
12283                 goto end;
12284             break;
12285         default:
12286             TEST_error("Should not get here");
12287             goto end;
12288         }
12289     }
12290 
12291     testresult = 1;
12292  end:
12293     SSL_free(serverssl);
12294     SSL_free(clientssl);
12295     SSL_CTX_free(sctx);
12296     SSL_CTX_free(cctx);
12297 
12298     return testresult;
12299 }
12300 #endif /* !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG) */
12301 
alpn_select_cb2(SSL * ssl,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)12302 static int alpn_select_cb2(SSL *ssl, const unsigned char **out,
12303                            unsigned char *outlen, const unsigned char *in,
12304                            unsigned int inlen, void *arg)
12305 {
12306     int *idx = (int *)arg;
12307 
12308     switch (*idx) {
12309     case 0:
12310         *out = (unsigned char *)(fooprot + 1);
12311         *outlen = *fooprot;
12312         return SSL_TLSEXT_ERR_OK;
12313 
12314     case 2:
12315         *out = (unsigned char *)(barprot + 1);
12316         *outlen = *barprot;
12317         return SSL_TLSEXT_ERR_OK;
12318 
12319     case 3:
12320         *outlen = 0;
12321         return SSL_TLSEXT_ERR_OK;
12322 
12323     default:
12324     case 1:
12325         return SSL_TLSEXT_ERR_ALERT_FATAL;
12326     }
12327     return 0;
12328 }
12329 
12330 /*
12331  * Test the ALPN callbacks
12332  * Test 0: client = foo, select = foo
12333  * Test 1: client = <empty>, select = none
12334  * Test 2: client = foo, select = bar (should fail)
12335  * Test 3: client = foo, select = <empty> (should fail)
12336  */
test_alpn(int idx)12337 static int test_alpn(int idx)
12338 {
12339     SSL_CTX *sctx = NULL, *cctx = NULL;
12340     SSL *serverssl = NULL, *clientssl = NULL;
12341     int testresult = 0;
12342     const unsigned char *prots = fooprot;
12343     unsigned int protslen = sizeof(fooprot);
12344 
12345     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
12346                                        TLS_client_method(), 0, 0,
12347                                        &sctx, &cctx, cert, privkey)))
12348         goto end;
12349 
12350     SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb2, &idx);
12351 
12352     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
12353                                       NULL)))
12354         goto end;
12355 
12356     if (idx == 1) {
12357         prots = NULL;
12358         protslen = 0;
12359     }
12360 
12361     /* SSL_set_alpn_protos returns 0 for success! */
12362     if (!TEST_false(SSL_set_alpn_protos(clientssl, prots, protslen)))
12363         goto end;
12364 
12365     if (idx == 2 || idx == 3) {
12366         /* We don't allow empty selection of NPN, so this should fail */
12367         if (!TEST_false(create_ssl_connection(serverssl, clientssl,
12368                                               SSL_ERROR_NONE)))
12369             goto end;
12370     } else {
12371         const unsigned char *prot;
12372         unsigned int protlen;
12373 
12374         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
12375                                              SSL_ERROR_NONE)))
12376             goto end;
12377 
12378         SSL_get0_alpn_selected(clientssl, &prot, &protlen);
12379         switch (idx) {
12380         case 0:
12381             if (!TEST_mem_eq(prot, protlen, fooprot + 1, *fooprot))
12382                 goto end;
12383             break;
12384         case 1:
12385             if (!TEST_uint_eq(protlen, 0))
12386                 goto end;
12387             break;
12388         default:
12389             TEST_error("Should not get here");
12390             goto end;
12391         }
12392     }
12393 
12394     testresult = 1;
12395  end:
12396     SSL_free(serverssl);
12397     SSL_free(clientssl);
12398     SSL_CTX_free(sctx);
12399     SSL_CTX_free(cctx);
12400 
12401     return testresult;
12402 }
12403 
12404 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config dhfile\n")
12405 
setup_tests(void)12406 int setup_tests(void)
12407 {
12408     char *modulename;
12409     char *configfile;
12410 
12411     libctx = OSSL_LIB_CTX_new();
12412     if (!TEST_ptr(libctx))
12413         return 0;
12414 
12415     defctxnull = OSSL_PROVIDER_load(NULL, "null");
12416 
12417     /*
12418      * Verify that the default and fips providers in the default libctx are not
12419      * available
12420      */
12421     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
12422             || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
12423         return 0;
12424 
12425     if (!test_skip_common_options()) {
12426         TEST_error("Error parsing test options\n");
12427         return 0;
12428     }
12429 
12430     if (!TEST_ptr(certsdir = test_get_argument(0))
12431             || !TEST_ptr(srpvfile = test_get_argument(1))
12432             || !TEST_ptr(tmpfilename = test_get_argument(2))
12433             || !TEST_ptr(modulename = test_get_argument(3))
12434             || !TEST_ptr(configfile = test_get_argument(4))
12435             || !TEST_ptr(dhfile = test_get_argument(5)))
12436         return 0;
12437 
12438     if (!TEST_true(OSSL_LIB_CTX_load_config(libctx, configfile)))
12439         return 0;
12440 
12441     /* Check we have the expected provider available */
12442     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
12443         return 0;
12444 
12445     /* Check the default provider is not available */
12446     if (strcmp(modulename, "default") != 0
12447             && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
12448         return 0;
12449 
12450     if (strcmp(modulename, "fips") == 0) {
12451         OSSL_PROVIDER *prov = NULL;
12452         OSSL_PARAM params[2];
12453 
12454         is_fips = 1;
12455 
12456         prov = OSSL_PROVIDER_load(libctx, "fips");
12457         if (prov != NULL) {
12458             /* Query the fips provider to check if the check ems option is enabled */
12459             params[0] =
12460                 OSSL_PARAM_construct_int(OSSL_PROV_PARAM_TLS1_PRF_EMS_CHECK,
12461                                          &fips_ems_check);
12462             params[1] = OSSL_PARAM_construct_end();
12463             OSSL_PROVIDER_get_params(prov, params);
12464             OSSL_PROVIDER_unload(prov);
12465         }
12466     }
12467 
12468     /*
12469      * We add, but don't load the test "tls-provider". We'll load it when we
12470      * need it.
12471      */
12472     if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "tls-provider",
12473                                              tls_provider_init)))
12474         return 0;
12475 
12476 
12477     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
12478 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
12479         TEST_error("not supported in this build");
12480         return 0;
12481 #else
12482         int i, mcount, rcount, fcount;
12483 
12484         for (i = 0; i < 4; i++)
12485             test_export_key_mat(i);
12486         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
12487         test_printf_stdout("malloc %d realloc %d free %d\n",
12488                 mcount, rcount, fcount);
12489         return 1;
12490 #endif
12491     }
12492 
12493     cert = test_mk_file_path(certsdir, "servercert.pem");
12494     if (cert == NULL)
12495         goto err;
12496 
12497     privkey = test_mk_file_path(certsdir, "serverkey.pem");
12498     if (privkey == NULL)
12499         goto err;
12500 
12501     cert2 = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
12502     if (cert2 == NULL)
12503         goto err;
12504 
12505     privkey2 = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
12506     if (privkey2 == NULL)
12507         goto err;
12508 
12509     cert1024 = test_mk_file_path(certsdir, "ee-cert-1024.pem");
12510     if (cert1024 == NULL)
12511         goto err;
12512 
12513     privkey1024 = test_mk_file_path(certsdir, "ee-key-1024.pem");
12514     if (privkey1024 == NULL)
12515         goto err;
12516 
12517     cert3072 = test_mk_file_path(certsdir, "ee-cert-3072.pem");
12518     if (cert3072 == NULL)
12519         goto err;
12520 
12521     privkey3072 = test_mk_file_path(certsdir, "ee-key-3072.pem");
12522     if (privkey3072 == NULL)
12523         goto err;
12524 
12525     cert4096 = test_mk_file_path(certsdir, "ee-cert-4096.pem");
12526     if (cert4096 == NULL)
12527         goto err;
12528 
12529     privkey4096 = test_mk_file_path(certsdir, "ee-key-4096.pem");
12530     if (privkey4096 == NULL)
12531         goto err;
12532 
12533     cert8192 = test_mk_file_path(certsdir, "ee-cert-8192.pem");
12534     if (cert8192 == NULL)
12535         goto err;
12536 
12537     privkey8192 = test_mk_file_path(certsdir, "ee-key-8192.pem");
12538     if (privkey8192 == NULL)
12539         goto err;
12540 
12541     if (fips_ems_check) {
12542 #ifndef OPENSSL_NO_TLS1_2
12543         ADD_TEST(test_no_ems);
12544 #endif
12545         return 1;
12546     }
12547 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
12548 # if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
12549     ADD_ALL_TESTS(test_ktls, NUM_KTLS_TEST_CIPHERS * 4);
12550     ADD_ALL_TESTS(test_ktls_sendfile, NUM_KTLS_TEST_CIPHERS * 2);
12551 # endif
12552 #endif
12553     ADD_TEST(test_large_message_tls);
12554     ADD_TEST(test_large_message_tls_read_ahead);
12555 #ifndef OPENSSL_NO_DTLS
12556     ADD_TEST(test_large_message_dtls);
12557 #endif
12558     ADD_ALL_TESTS(test_large_app_data, 28);
12559     ADD_TEST(test_cleanse_plaintext);
12560 #ifndef OPENSSL_NO_OCSP
12561     ADD_TEST(test_tlsext_status_type);
12562 #endif
12563     ADD_TEST(test_session_with_only_int_cache);
12564     ADD_TEST(test_session_with_only_ext_cache);
12565     ADD_TEST(test_session_with_both_cache);
12566     ADD_TEST(test_session_wo_ca_names);
12567 #ifndef OSSL_NO_USABLE_TLS1_3
12568     ADD_ALL_TESTS(test_stateful_tickets, 3);
12569     ADD_ALL_TESTS(test_stateless_tickets, 3);
12570     ADD_TEST(test_psk_tickets);
12571     ADD_ALL_TESTS(test_extra_tickets, 6);
12572 #endif
12573     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
12574     ADD_TEST(test_ssl_bio_pop_next_bio);
12575     ADD_TEST(test_ssl_bio_pop_ssl_bio);
12576     ADD_TEST(test_ssl_bio_change_rbio);
12577     ADD_TEST(test_ssl_bio_change_wbio);
12578 #if !defined(OPENSSL_NO_TLS1_2) || defined(OSSL_NO_USABLE_TLS1_3)
12579     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
12580     ADD_TEST(test_keylog);
12581 #endif
12582 #ifndef OSSL_NO_USABLE_TLS1_3
12583     ADD_TEST(test_keylog_no_master_key);
12584 #endif
12585     ADD_TEST(test_client_cert_verify_cb);
12586     ADD_TEST(test_ssl_build_cert_chain);
12587     ADD_TEST(test_ssl_ctx_build_cert_chain);
12588 #ifndef OPENSSL_NO_TLS1_2
12589     ADD_TEST(test_client_hello_cb);
12590     ADD_TEST(test_no_ems);
12591     ADD_TEST(test_ccs_change_cipher);
12592 #endif
12593 #ifndef OSSL_NO_USABLE_TLS1_3
12594     ADD_ALL_TESTS(test_early_data_read_write, 6);
12595     /*
12596      * We don't do replay tests for external PSK. Replay protection isn't used
12597      * in that scenario.
12598      */
12599     ADD_ALL_TESTS(test_early_data_replay, 2);
12600     ADD_ALL_TESTS(test_early_data_skip, OSSL_NELEM(ciphersuites) * 3);
12601     ADD_ALL_TESTS(test_early_data_skip_hrr, OSSL_NELEM(ciphersuites) * 3);
12602     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, OSSL_NELEM(ciphersuites) * 3);
12603     ADD_ALL_TESTS(test_early_data_skip_abort, OSSL_NELEM(ciphersuites) * 3);
12604     ADD_ALL_TESTS(test_early_data_not_sent, 3);
12605     ADD_ALL_TESTS(test_early_data_psk, 8);
12606     ADD_ALL_TESTS(test_early_data_psk_with_all_ciphers, 7);
12607     ADD_ALL_TESTS(test_early_data_not_expected, 3);
12608 # ifndef OPENSSL_NO_TLS1_2
12609     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
12610 # endif
12611 #endif
12612 #ifndef OSSL_NO_USABLE_TLS1_3
12613     ADD_ALL_TESTS(test_set_ciphersuite, 10);
12614     ADD_TEST(test_ciphersuite_change);
12615     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
12616 # ifdef OPENSSL_NO_PSK
12617     ADD_ALL_TESTS(test_tls13_psk, 1);
12618 # else
12619     ADD_ALL_TESTS(test_tls13_psk, 4);
12620 # endif  /* OPENSSL_NO_PSK */
12621 #ifndef OSSL_NO_USABLE_TLS1_3
12622     ADD_ALL_TESTS(test_tls13_no_dhe_kex, 8);
12623 #endif /* OSSL_NO_USABLE_TLS1_3 */
12624 # ifndef OPENSSL_NO_TLS1_2
12625     /* Test with both TLSv1.3 and 1.2 versions */
12626     ADD_ALL_TESTS(test_key_exchange, 14);
12627 #  if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_DH)
12628     ADD_ALL_TESTS(test_negotiated_group,
12629                   4 * (OSSL_NELEM(ecdhe_kexch_groups)
12630                        + OSSL_NELEM(ffdhe_kexch_groups)));
12631 #  endif
12632 # else
12633     /* Test with only TLSv1.3 versions */
12634     ADD_ALL_TESTS(test_key_exchange, 12);
12635 # endif
12636     ADD_ALL_TESTS(test_custom_exts, 6);
12637     ADD_TEST(test_stateless);
12638     ADD_TEST(test_pha_key_update);
12639 #else
12640     ADD_ALL_TESTS(test_custom_exts, 3);
12641 #endif
12642     ADD_ALL_TESTS(test_export_key_mat, 6);
12643 #ifndef OSSL_NO_USABLE_TLS1_3
12644     ADD_ALL_TESTS(test_export_key_mat_early, 3);
12645     ADD_TEST(test_key_update);
12646     ADD_ALL_TESTS(test_key_update_peer_in_write, 2);
12647     ADD_ALL_TESTS(test_key_update_peer_in_read, 2);
12648     ADD_ALL_TESTS(test_key_update_local_in_write, 2);
12649     ADD_ALL_TESTS(test_key_update_local_in_read, 2);
12650 #endif
12651     ADD_ALL_TESTS(test_ssl_clear, 8);
12652     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
12653 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
12654     ADD_ALL_TESTS(test_srp, 6);
12655 #endif
12656 #if !defined(OPENSSL_NO_COMP_ALG)
12657     /* Add compression case */
12658     ADD_ALL_TESTS(test_info_callback, 8);
12659 #else
12660     ADD_ALL_TESTS(test_info_callback, 6);
12661 #endif
12662     ADD_ALL_TESTS(test_ssl_pending, 2);
12663     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
12664     ADD_ALL_TESTS(test_ticket_callbacks, 20);
12665     ADD_ALL_TESTS(test_shutdown, 7);
12666     ADD_TEST(test_async_shutdown);
12667     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
12668     ADD_ALL_TESTS(test_cert_cb, 6);
12669     ADD_ALL_TESTS(test_client_cert_cb, 2);
12670     ADD_ALL_TESTS(test_ca_names, 3);
12671 #ifndef OPENSSL_NO_TLS1_2
12672     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
12673 #endif
12674     ADD_ALL_TESTS(test_servername, 10);
12675     ADD_TEST(test_unknown_sigalgs_groups);
12676     ADD_TEST(test_configuration_of_groups);
12677 #if !defined(OPENSSL_NO_EC) \
12678     && (!defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2))
12679     ADD_ALL_TESTS(test_sigalgs_available, 6);
12680 #endif
12681 #ifndef OPENSSL_NO_TLS1_3
12682     ADD_ALL_TESTS(test_pluggable_group, 2);
12683     ADD_ALL_TESTS(test_pluggable_signature, 4);
12684 #endif
12685 #ifndef OPENSSL_NO_TLS1_2
12686     ADD_TEST(test_ssl_dup);
12687     ADD_TEST(test_session_secret_cb);
12688 # ifndef OPENSSL_NO_DH
12689     ADD_ALL_TESTS(test_set_tmp_dh, 11);
12690     ADD_ALL_TESTS(test_dh_auto, 7);
12691 # endif
12692 #endif
12693 #ifndef OSSL_NO_USABLE_TLS1_3
12694     ADD_TEST(test_sni_tls13);
12695     ADD_ALL_TESTS(test_ticket_lifetime, 2);
12696 #endif
12697     ADD_TEST(test_inherit_verify_param);
12698     ADD_TEST(test_set_alpn);
12699     ADD_TEST(test_set_verify_cert_store_ssl_ctx);
12700     ADD_TEST(test_set_verify_cert_store_ssl);
12701     ADD_ALL_TESTS(test_session_timeout, 1);
12702 #if !defined(OSSL_NO_USABLE_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
12703     ADD_ALL_TESTS(test_session_cache_overflow, 4);
12704 #endif
12705     ADD_TEST(test_load_dhfile);
12706 #ifndef OSSL_NO_USABLE_TLS1_3
12707     ADD_TEST(test_read_ahead_key_change);
12708     ADD_ALL_TESTS(test_tls13_record_padding, 6);
12709 #endif
12710 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OSSL_NO_USABLE_TLS1_3)
12711     ADD_ALL_TESTS(test_serverinfo_custom, 4);
12712 #endif
12713 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
12714     ADD_ALL_TESTS(test_pipelining, 7);
12715 #endif
12716     ADD_ALL_TESTS(test_version, 6);
12717     ADD_TEST(test_rstate_string);
12718     ADD_ALL_TESTS(test_handshake_retry, 16);
12719     ADD_TEST(test_data_retry);
12720     ADD_ALL_TESTS(test_multi_resume, 5);
12721     ADD_ALL_TESTS(test_select_next_proto, OSSL_NELEM(next_proto_tests));
12722 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_NEXTPROTONEG)
12723     ADD_ALL_TESTS(test_npn, 5);
12724 #endif
12725     ADD_ALL_TESTS(test_alpn, 4);
12726     return 1;
12727 
12728  err:
12729     OPENSSL_free(cert);
12730     OPENSSL_free(privkey);
12731     OPENSSL_free(cert2);
12732     OPENSSL_free(privkey2);
12733     return 0;
12734 }
12735 
cleanup_tests(void)12736 void cleanup_tests(void)
12737 {
12738 # if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DH)
12739     EVP_PKEY_free(tmp_dh_params);
12740 #endif
12741     OPENSSL_free(cert);
12742     OPENSSL_free(privkey);
12743     OPENSSL_free(cert2);
12744     OPENSSL_free(privkey2);
12745     OPENSSL_free(cert1024);
12746     OPENSSL_free(privkey1024);
12747     OPENSSL_free(cert3072);
12748     OPENSSL_free(privkey3072);
12749     OPENSSL_free(cert4096);
12750     OPENSSL_free(privkey4096);
12751     OPENSSL_free(cert8192);
12752     OPENSSL_free(privkey8192);
12753     bio_s_mempacket_test_free();
12754     bio_s_always_retry_free();
12755     bio_s_maybe_retry_free();
12756     OSSL_PROVIDER_unload(defctxnull);
12757     OSSL_LIB_CTX_free(libctx);
12758 }
12759