Extend test_ssl_get_shared_ciphers
[openssl.git] / test / sslapitest.c
1 /*
2  * Copyright 2016-2020 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/provider.h>
32
33 #include "ssltestlib.h"
34 #include "testutil.h"
35 #include "testutil/output.h"
36 #include "internal/nelem.h"
37 #include "internal/ktls.h"
38 #include "../ssl/ssl_local.h"
39
40 DEFINE_STACK_OF(OCSP_RESPID)
41 DEFINE_STACK_OF(X509)
42 DEFINE_STACK_OF(X509_NAME)
43
44 static OPENSSL_CTX *libctx = NULL;
45 static OSSL_PROVIDER *defctxnull = NULL;
46
47 #ifndef OPENSSL_NO_TLS1_3
48
49 static SSL_SESSION *clientpsk = NULL;
50 static SSL_SESSION *serverpsk = NULL;
51 static const char *pskid = "Identity";
52 static const char *srvid;
53
54 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
55                           size_t *idlen, SSL_SESSION **sess);
56 static int find_session_cb(SSL *ssl, const unsigned char *identity,
57                            size_t identity_len, SSL_SESSION **sess);
58
59 static int use_session_cb_cnt = 0;
60 static int find_session_cb_cnt = 0;
61
62 static SSL_SESSION *create_a_psk(SSL *ssl);
63 #endif
64
65 static char *certsdir = NULL;
66 static char *cert = NULL;
67 static char *privkey = NULL;
68 static char *srpvfile = NULL;
69 static char *tmpfilename = NULL;
70
71 static int is_fips = 0;
72
73 #define LOG_BUFFER_SIZE 2048
74 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
75 static size_t server_log_buffer_index = 0;
76 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
77 static size_t client_log_buffer_index = 0;
78 static int error_writing_log = 0;
79
80 #ifndef OPENSSL_NO_OCSP
81 static const unsigned char orespder[] = "Dummy OCSP Response";
82 static int ocsp_server_called = 0;
83 static int ocsp_client_called = 0;
84
85 static int cdummyarg = 1;
86 static X509 *ocspcert = NULL;
87 #endif
88
89 #define NUM_EXTRA_CERTS 40
90 #define CLIENT_VERSION_LEN      2
91
92 /*
93  * This structure is used to validate that the correct number of log messages
94  * of various types are emitted when emitting secret logs.
95  */
96 struct sslapitest_log_counts {
97     unsigned int rsa_key_exchange_count;
98     unsigned int master_secret_count;
99     unsigned int client_early_secret_count;
100     unsigned int client_handshake_secret_count;
101     unsigned int server_handshake_secret_count;
102     unsigned int client_application_secret_count;
103     unsigned int server_application_secret_count;
104     unsigned int early_exporter_secret_count;
105     unsigned int exporter_secret_count;
106 };
107
108
109 static unsigned char serverinfov1[] = {
110     0xff, 0xff, /* Dummy extension type */
111     0x00, 0x01, /* Extension length is 1 byte */
112     0xff        /* Dummy extension data */
113 };
114
115 static unsigned char serverinfov2[] = {
116     0x00, 0x00, 0x00,
117     (unsigned char)(SSL_EXT_CLIENT_HELLO & 0xff), /* Dummy context - 4 bytes */
118     0xff, 0xff, /* Dummy extension type */
119     0x00, 0x01, /* Extension length is 1 byte */
120     0xff        /* Dummy extension data */
121 };
122
123 static int hostname_cb(SSL *s, int *al, void *arg)
124 {
125     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
126
127     if (hostname != NULL && (strcmp(hostname, "goodhost") == 0
128                              || strcmp(hostname, "altgoodhost") == 0))
129         return  SSL_TLSEXT_ERR_OK;
130
131     return SSL_TLSEXT_ERR_NOACK;
132 }
133
134 static void client_keylog_callback(const SSL *ssl, const char *line)
135 {
136     int line_length = strlen(line);
137
138     /* If the log doesn't fit, error out. */
139     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
140         TEST_info("Client log too full");
141         error_writing_log = 1;
142         return;
143     }
144
145     strcat(client_log_buffer, line);
146     client_log_buffer_index += line_length;
147     client_log_buffer[client_log_buffer_index++] = '\n';
148 }
149
150 static void server_keylog_callback(const SSL *ssl, const char *line)
151 {
152     int line_length = strlen(line);
153
154     /* If the log doesn't fit, error out. */
155     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
156         TEST_info("Server log too full");
157         error_writing_log = 1;
158         return;
159     }
160
161     strcat(server_log_buffer, line);
162     server_log_buffer_index += line_length;
163     server_log_buffer[server_log_buffer_index++] = '\n';
164 }
165
166 static int compare_hex_encoded_buffer(const char *hex_encoded,
167                                       size_t hex_length,
168                                       const uint8_t *raw,
169                                       size_t raw_length)
170 {
171     size_t i, j;
172     char hexed[3];
173
174     if (!TEST_size_t_eq(raw_length * 2, hex_length))
175         return 1;
176
177     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
178         sprintf(hexed, "%02x", raw[i]);
179         if (!TEST_int_eq(hexed[0], hex_encoded[j])
180                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
181             return 1;
182     }
183
184     return 0;
185 }
186
187 static int test_keylog_output(char *buffer, const SSL *ssl,
188                               const SSL_SESSION *session,
189                               struct sslapitest_log_counts *expected)
190 {
191     char *token = NULL;
192     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
193     size_t client_random_size = SSL3_RANDOM_SIZE;
194     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
195     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
196     unsigned int rsa_key_exchange_count = 0;
197     unsigned int master_secret_count = 0;
198     unsigned int client_early_secret_count = 0;
199     unsigned int client_handshake_secret_count = 0;
200     unsigned int server_handshake_secret_count = 0;
201     unsigned int client_application_secret_count = 0;
202     unsigned int server_application_secret_count = 0;
203     unsigned int early_exporter_secret_count = 0;
204     unsigned int exporter_secret_count = 0;
205
206     for (token = strtok(buffer, " \n"); token != NULL;
207          token = strtok(NULL, " \n")) {
208         if (strcmp(token, "RSA") == 0) {
209             /*
210              * Premaster secret. Tokens should be: 16 ASCII bytes of
211              * hex-encoded encrypted secret, then the hex-encoded pre-master
212              * secret.
213              */
214             if (!TEST_ptr(token = strtok(NULL, " \n")))
215                 return 0;
216             if (!TEST_size_t_eq(strlen(token), 16))
217                 return 0;
218             if (!TEST_ptr(token = strtok(NULL, " \n")))
219                 return 0;
220             /*
221              * We can't sensibly check the log because the premaster secret is
222              * transient, and OpenSSL doesn't keep hold of it once the master
223              * secret is generated.
224              */
225             rsa_key_exchange_count++;
226         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
227             /*
228              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
229              * client random, then the hex-encoded master secret.
230              */
231             client_random_size = SSL_get_client_random(ssl,
232                                                        actual_client_random,
233                                                        SSL3_RANDOM_SIZE);
234             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
235                 return 0;
236
237             if (!TEST_ptr(token = strtok(NULL, " \n")))
238                 return 0;
239             if (!TEST_size_t_eq(strlen(token), 64))
240                 return 0;
241             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
242                                                        actual_client_random,
243                                                        client_random_size)))
244                 return 0;
245
246             if (!TEST_ptr(token = strtok(NULL, " \n")))
247                 return 0;
248             master_key_size = SSL_SESSION_get_master_key(session,
249                                                          actual_master_key,
250                                                          master_key_size);
251             if (!TEST_size_t_ne(master_key_size, 0))
252                 return 0;
253             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
254                                                        actual_master_key,
255                                                        master_key_size)))
256                 return 0;
257             master_secret_count++;
258         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
259                     || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
260                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
261                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
262                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
263                     || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
264                     || strcmp(token, "EXPORTER_SECRET") == 0) {
265             /*
266              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
267              * client random, and then the hex-encoded secret. In this case,
268              * we treat all of these secrets identically and then just
269              * distinguish between them when counting what we saw.
270              */
271             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
272                 client_early_secret_count++;
273             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
274                 client_handshake_secret_count++;
275             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
276                 server_handshake_secret_count++;
277             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
278                 client_application_secret_count++;
279             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
280                 server_application_secret_count++;
281             else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
282                 early_exporter_secret_count++;
283             else if (strcmp(token, "EXPORTER_SECRET") == 0)
284                 exporter_secret_count++;
285
286             client_random_size = SSL_get_client_random(ssl,
287                                                        actual_client_random,
288                                                        SSL3_RANDOM_SIZE);
289             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
290                 return 0;
291
292             if (!TEST_ptr(token = strtok(NULL, " \n")))
293                 return 0;
294             if (!TEST_size_t_eq(strlen(token), 64))
295                 return 0;
296             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
297                                                        actual_client_random,
298                                                        client_random_size)))
299                 return 0;
300
301             if (!TEST_ptr(token = strtok(NULL, " \n")))
302                 return 0;
303
304             /*
305              * TODO(TLS1.3): test that application traffic secrets are what
306              * we expect */
307         } else {
308             TEST_info("Unexpected token %s\n", token);
309             return 0;
310         }
311     }
312
313     /* Got what we expected? */
314     if (!TEST_size_t_eq(rsa_key_exchange_count,
315                         expected->rsa_key_exchange_count)
316             || !TEST_size_t_eq(master_secret_count,
317                                expected->master_secret_count)
318             || !TEST_size_t_eq(client_early_secret_count,
319                                expected->client_early_secret_count)
320             || !TEST_size_t_eq(client_handshake_secret_count,
321                                expected->client_handshake_secret_count)
322             || !TEST_size_t_eq(server_handshake_secret_count,
323                                expected->server_handshake_secret_count)
324             || !TEST_size_t_eq(client_application_secret_count,
325                                expected->client_application_secret_count)
326             || !TEST_size_t_eq(server_application_secret_count,
327                                expected->server_application_secret_count)
328             || !TEST_size_t_eq(early_exporter_secret_count,
329                                expected->early_exporter_secret_count)
330             || !TEST_size_t_eq(exporter_secret_count,
331                                expected->exporter_secret_count))
332         return 0;
333     return 1;
334 }
335
336 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
337 static int test_keylog(void)
338 {
339     SSL_CTX *cctx = NULL, *sctx = NULL;
340     SSL *clientssl = NULL, *serverssl = NULL;
341     int testresult = 0;
342     struct sslapitest_log_counts expected;
343
344     /* Clean up logging space */
345     memset(&expected, 0, sizeof(expected));
346     memset(client_log_buffer, 0, sizeof(client_log_buffer));
347     memset(server_log_buffer, 0, sizeof(server_log_buffer));
348     client_log_buffer_index = 0;
349     server_log_buffer_index = 0;
350     error_writing_log = 0;
351
352     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
353                                        TLS_client_method(),
354                                        TLS1_VERSION, 0,
355                                        &sctx, &cctx, cert, privkey)))
356         return 0;
357
358     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
359     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
360     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
361
362     /* We also want to ensure that we use RSA-based key exchange. */
363     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
364         goto end;
365
366     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
367             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
368         goto end;
369     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
370     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
371                    == client_keylog_callback))
372         goto end;
373     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
374     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
375                    == server_keylog_callback))
376         goto end;
377
378     /* Now do a handshake and check that the logs have been written to. */
379     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
380                                       &clientssl, NULL, NULL))
381             || !TEST_true(create_ssl_connection(serverssl, clientssl,
382                                                 SSL_ERROR_NONE))
383             || !TEST_false(error_writing_log)
384             || !TEST_int_gt(client_log_buffer_index, 0)
385             || !TEST_int_gt(server_log_buffer_index, 0))
386         goto end;
387
388     /*
389      * Now we want to test that our output data was vaguely sensible. We
390      * do that by using strtok and confirming that we have more or less the
391      * data we expect. For both client and server, we expect to see one master
392      * secret. The client should also see a RSA key exchange.
393      */
394     expected.rsa_key_exchange_count = 1;
395     expected.master_secret_count = 1;
396     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
397                                       SSL_get_session(clientssl), &expected)))
398         goto end;
399
400     expected.rsa_key_exchange_count = 0;
401     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
402                                       SSL_get_session(serverssl), &expected)))
403         goto end;
404
405     testresult = 1;
406
407 end:
408     SSL_free(serverssl);
409     SSL_free(clientssl);
410     SSL_CTX_free(sctx);
411     SSL_CTX_free(cctx);
412
413     return testresult;
414 }
415 #endif
416
417 #ifndef OPENSSL_NO_TLS1_3
418 static int test_keylog_no_master_key(void)
419 {
420     SSL_CTX *cctx = NULL, *sctx = NULL;
421     SSL *clientssl = NULL, *serverssl = NULL;
422     SSL_SESSION *sess = NULL;
423     int testresult = 0;
424     struct sslapitest_log_counts expected;
425     unsigned char buf[1];
426     size_t readbytes, written;
427
428     /* Clean up logging space */
429     memset(&expected, 0, sizeof(expected));
430     memset(client_log_buffer, 0, sizeof(client_log_buffer));
431     memset(server_log_buffer, 0, sizeof(server_log_buffer));
432     client_log_buffer_index = 0;
433     server_log_buffer_index = 0;
434     error_writing_log = 0;
435
436     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
437                                        TLS_client_method(), TLS1_VERSION, 0,
438                                        &sctx, &cctx, cert, privkey))
439         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
440                                                  SSL3_RT_MAX_PLAIN_LENGTH)))
441         return 0;
442
443     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
444             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
445         goto end;
446
447     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
448     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
449                    == client_keylog_callback))
450         goto end;
451
452     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
453     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
454                    == server_keylog_callback))
455         goto end;
456
457     /* Now do a handshake and check that the logs have been written to. */
458     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
459                                       &clientssl, NULL, NULL))
460             || !TEST_true(create_ssl_connection(serverssl, clientssl,
461                                                 SSL_ERROR_NONE))
462             || !TEST_false(error_writing_log))
463         goto end;
464
465     /*
466      * Now we want to test that our output data was vaguely sensible. For this
467      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
468      * TLSv1.3, but we do expect both client and server to emit keys.
469      */
470     expected.client_handshake_secret_count = 1;
471     expected.server_handshake_secret_count = 1;
472     expected.client_application_secret_count = 1;
473     expected.server_application_secret_count = 1;
474     expected.exporter_secret_count = 1;
475     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
476                                       SSL_get_session(clientssl), &expected))
477             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
478                                              SSL_get_session(serverssl),
479                                              &expected)))
480         goto end;
481
482     /* Terminate old session and resume with early data. */
483     sess = SSL_get1_session(clientssl);
484     SSL_shutdown(clientssl);
485     SSL_shutdown(serverssl);
486     SSL_free(serverssl);
487     SSL_free(clientssl);
488     serverssl = clientssl = NULL;
489
490     /* Reset key log */
491     memset(client_log_buffer, 0, sizeof(client_log_buffer));
492     memset(server_log_buffer, 0, sizeof(server_log_buffer));
493     client_log_buffer_index = 0;
494     server_log_buffer_index = 0;
495
496     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
497                                       &clientssl, NULL, NULL))
498             || !TEST_true(SSL_set_session(clientssl, sess))
499             /* Here writing 0 length early data is enough. */
500             || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
501             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
502                                                 &readbytes),
503                             SSL_READ_EARLY_DATA_ERROR)
504             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
505                             SSL_EARLY_DATA_ACCEPTED)
506             || !TEST_true(create_ssl_connection(serverssl, clientssl,
507                           SSL_ERROR_NONE))
508             || !TEST_true(SSL_session_reused(clientssl)))
509         goto end;
510
511     /* In addition to the previous entries, expect early secrets. */
512     expected.client_early_secret_count = 1;
513     expected.early_exporter_secret_count = 1;
514     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
515                                       SSL_get_session(clientssl), &expected))
516             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
517                                              SSL_get_session(serverssl),
518                                              &expected)))
519         goto end;
520
521     testresult = 1;
522
523 end:
524     SSL_SESSION_free(sess);
525     SSL_free(serverssl);
526     SSL_free(clientssl);
527     SSL_CTX_free(sctx);
528     SSL_CTX_free(cctx);
529
530     return testresult;
531 }
532 #endif
533
534 #ifndef OPENSSL_NO_TLS1_2
535 static int full_client_hello_callback(SSL *s, int *al, void *arg)
536 {
537     int *ctr = arg;
538     const unsigned char *p;
539     int *exts;
540     /* We only configure two ciphers, but the SCSV is added automatically. */
541 #ifdef OPENSSL_NO_EC
542     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
543 #else
544     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
545                                               0x2c, 0x00, 0xff};
546 #endif
547     const int expected_extensions[] = {
548 #ifndef OPENSSL_NO_EC
549                                        11, 10,
550 #endif
551                                        35, 22, 23, 13};
552     size_t len;
553
554     /* Make sure we can defer processing and get called back. */
555     if ((*ctr)++ == 0)
556         return SSL_CLIENT_HELLO_RETRY;
557
558     len = SSL_client_hello_get0_ciphers(s, &p);
559     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
560             || !TEST_size_t_eq(
561                        SSL_client_hello_get0_compression_methods(s, &p), 1)
562             || !TEST_int_eq(*p, 0))
563         return SSL_CLIENT_HELLO_ERROR;
564     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
565         return SSL_CLIENT_HELLO_ERROR;
566     if (len != OSSL_NELEM(expected_extensions) ||
567         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
568         printf("ClientHello callback expected extensions mismatch\n");
569         OPENSSL_free(exts);
570         return SSL_CLIENT_HELLO_ERROR;
571     }
572     OPENSSL_free(exts);
573     return SSL_CLIENT_HELLO_SUCCESS;
574 }
575
576 static int test_client_hello_cb(void)
577 {
578     SSL_CTX *cctx = NULL, *sctx = NULL;
579     SSL *clientssl = NULL, *serverssl = NULL;
580     int testctr = 0, testresult = 0;
581
582     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
583                                        TLS_client_method(), TLS1_VERSION, 0,
584                                        &sctx, &cctx, cert, privkey)))
585         goto end;
586     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
587
588     /* The gimpy cipher list we configure can't do TLS 1.3. */
589     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
590
591     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
592                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
593             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
594                                              &clientssl, NULL, NULL))
595             || !TEST_false(create_ssl_connection(serverssl, clientssl,
596                         SSL_ERROR_WANT_CLIENT_HELLO_CB))
597                 /*
598                  * Passing a -1 literal is a hack since
599                  * the real value was lost.
600                  * */
601             || !TEST_int_eq(SSL_get_error(serverssl, -1),
602                             SSL_ERROR_WANT_CLIENT_HELLO_CB)
603             || !TEST_true(create_ssl_connection(serverssl, clientssl,
604                                                 SSL_ERROR_NONE)))
605         goto end;
606
607     testresult = 1;
608
609 end:
610     SSL_free(serverssl);
611     SSL_free(clientssl);
612     SSL_CTX_free(sctx);
613     SSL_CTX_free(cctx);
614
615     return testresult;
616 }
617
618 static int test_no_ems(void)
619 {
620     SSL_CTX *cctx = NULL, *sctx = NULL;
621     SSL *clientssl = NULL, *serverssl = NULL;
622     int testresult = 0;
623
624     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
625                              TLS1_VERSION, TLS1_2_VERSION,
626                              &sctx, &cctx, cert, privkey)) {
627         printf("Unable to create SSL_CTX pair\n");
628         goto end;
629     }
630
631     SSL_CTX_set_options(sctx, SSL_OP_NO_EXTENDED_MASTER_SECRET);
632
633     if (!create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL, NULL)) {
634         printf("Unable to create SSL objects\n");
635         goto end;
636     }
637
638     if (!create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)) {
639         printf("Creating SSL connection failed\n");
640         goto end;
641     }
642
643     if (SSL_get_extms_support(serverssl)) {
644         printf("Server reports Extended Master Secret support\n");
645         goto end;
646     }
647
648     if (SSL_get_extms_support(clientssl)) {
649         printf("Client reports Extended Master Secret support\n");
650         goto end;
651     }
652     testresult = 1;
653
654 end:
655     SSL_free(serverssl);
656     SSL_free(clientssl);
657     SSL_CTX_free(sctx);
658     SSL_CTX_free(cctx);
659
660     return testresult;
661 }
662
663 /*
664  * Very focused test to exercise a single case in the server-side state
665  * machine, when the ChangeCipherState message needs to actually change
666  * from one cipher to a different cipher (i.e., not changing from null
667  * encryption to real encryption).
668  */
669 static int test_ccs_change_cipher(void)
670 {
671     SSL_CTX *cctx = NULL, *sctx = NULL;
672     SSL *clientssl = NULL, *serverssl = NULL;
673     SSL_SESSION *sess = NULL, *sesspre, *sesspost;
674     int testresult = 0;
675     int i;
676     unsigned char buf;
677     size_t readbytes;
678
679     /*
680      * Create a conection so we can resume and potentially (but not) use
681      * a different cipher in the second connection.
682      */
683     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
684                                        TLS_client_method(),
685                                        TLS1_VERSION, TLS1_2_VERSION,
686                                        &sctx, &cctx, cert, privkey))
687             || !TEST_true(SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET))
688             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
689                           NULL, NULL))
690             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
691             || !TEST_true(create_ssl_connection(serverssl, clientssl,
692                                                 SSL_ERROR_NONE))
693             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
694             || !TEST_ptr(sess = SSL_get1_session(clientssl)))
695         goto end;
696
697     shutdown_ssl_connection(serverssl, clientssl);
698     serverssl = clientssl = NULL;
699
700     /* Resume, preferring a different cipher. Our server will force the
701      * same cipher to be used as the initial handshake. */
702     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
703                           NULL, NULL))
704             || !TEST_true(SSL_set_session(clientssl, sess))
705             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384:AES128-GCM-SHA256"))
706             || !TEST_true(create_ssl_connection(serverssl, clientssl,
707                                                 SSL_ERROR_NONE))
708             || !TEST_true(SSL_session_reused(clientssl))
709             || !TEST_true(SSL_session_reused(serverssl))
710             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
711             || !TEST_ptr_eq(sesspre, sesspost)
712             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
713                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
714         goto end;
715     shutdown_ssl_connection(serverssl, clientssl);
716     serverssl = clientssl = NULL;
717
718     /*
719      * Now create a fresh connection and try to renegotiate a different
720      * cipher on it.
721      */
722     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
723                                       NULL, NULL))
724             || !TEST_true(SSL_set_cipher_list(clientssl, "AES128-GCM-SHA256"))
725             || !TEST_true(create_ssl_connection(serverssl, clientssl,
726                                                 SSL_ERROR_NONE))
727             || !TEST_ptr(sesspre = SSL_get0_session(serverssl))
728             || !TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384"))
729             || !TEST_true(SSL_renegotiate(clientssl))
730             || !TEST_true(SSL_renegotiate_pending(clientssl)))
731         goto end;
732     /* Actually drive the renegotiation. */
733     for (i = 0; i < 3; i++) {
734         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
735             if (!TEST_ulong_eq(readbytes, 0))
736                 goto end;
737         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
738                                 SSL_ERROR_WANT_READ)) {
739             goto end;
740         }
741         if (SSL_read_ex(serverssl, &buf, sizeof(buf), &readbytes) > 0) {
742             if (!TEST_ulong_eq(readbytes, 0))
743                 goto end;
744         } else if (!TEST_int_eq(SSL_get_error(serverssl, 0),
745                                 SSL_ERROR_WANT_READ)) {
746             goto end;
747         }
748     }
749     /* sesspre and sesspost should be different since the cipher changed. */
750     if (!TEST_false(SSL_renegotiate_pending(clientssl))
751             || !TEST_false(SSL_session_reused(clientssl))
752             || !TEST_false(SSL_session_reused(serverssl))
753             || !TEST_ptr(sesspost = SSL_get0_session(serverssl))
754             || !TEST_ptr_ne(sesspre, sesspost)
755             || !TEST_int_eq(TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
756                             SSL_CIPHER_get_id(SSL_get_current_cipher(clientssl))))
757         goto end;
758
759     shutdown_ssl_connection(serverssl, clientssl);
760     serverssl = clientssl = NULL;
761
762     testresult = 1;
763
764 end:
765     SSL_free(serverssl);
766     SSL_free(clientssl);
767     SSL_CTX_free(sctx);
768     SSL_CTX_free(cctx);
769     SSL_SESSION_free(sess);
770
771     return testresult;
772 }
773 #endif
774
775 static int execute_test_large_message(const SSL_METHOD *smeth,
776                                       const SSL_METHOD *cmeth,
777                                       int min_version, int max_version,
778                                       int read_ahead)
779 {
780     SSL_CTX *cctx = NULL, *sctx = NULL;
781     SSL *clientssl = NULL, *serverssl = NULL;
782     int testresult = 0;
783     int i;
784     BIO *certbio = NULL;
785     X509 *chaincert = NULL;
786     int certlen;
787
788     if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
789         goto end;
790     chaincert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
791     BIO_free(certbio);
792     certbio = NULL;
793     if (!TEST_ptr(chaincert))
794         goto end;
795
796     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
797                                        max_version, &sctx, &cctx, cert,
798                                        privkey)))
799         goto end;
800
801     if (read_ahead) {
802         /*
803          * Test that read_ahead works correctly when dealing with large
804          * records
805          */
806         SSL_CTX_set_read_ahead(cctx, 1);
807     }
808
809     /*
810      * We assume the supplied certificate is big enough so that if we add
811      * NUM_EXTRA_CERTS it will make the overall message large enough. The
812      * default buffer size is requested to be 16k, but due to the way BUF_MEM
813      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
814      * test we need to have a message larger than that.
815      */
816     certlen = i2d_X509(chaincert, NULL);
817     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
818                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
819     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
820         if (!X509_up_ref(chaincert))
821             goto end;
822         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
823             X509_free(chaincert);
824             goto end;
825         }
826     }
827
828     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
829                                       NULL, NULL))
830             || !TEST_true(create_ssl_connection(serverssl, clientssl,
831                                                 SSL_ERROR_NONE)))
832         goto end;
833
834     /*
835      * Calling SSL_clear() first is not required but this tests that SSL_clear()
836      * doesn't leak.
837      */
838     if (!TEST_true(SSL_clear(serverssl)))
839         goto end;
840
841     testresult = 1;
842  end:
843     X509_free(chaincert);
844     SSL_free(serverssl);
845     SSL_free(clientssl);
846     SSL_CTX_free(sctx);
847     SSL_CTX_free(cctx);
848
849     return testresult;
850 }
851
852 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_KTLS) \
853     && !defined(OPENSSL_NO_SOCK)
854
855 /* sock must be connected */
856 static int ktls_chk_platform(int sock)
857 {
858     if (!ktls_enable(sock))
859         return 0;
860     return 1;
861 }
862
863 static int ping_pong_query(SSL *clientssl, SSL *serverssl, int cfd, int sfd)
864 {
865     static char count = 1;
866     unsigned char cbuf[16000] = {0};
867     unsigned char sbuf[16000];
868     size_t err = 0;
869     char crec_wseq_before[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
870     char crec_wseq_after[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
871     char crec_rseq_before[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
872     char crec_rseq_after[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
873     char srec_wseq_before[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
874     char srec_wseq_after[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
875     char srec_rseq_before[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
876     char srec_rseq_after[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
877
878     cbuf[0] = count++;
879     memcpy(crec_wseq_before, &clientssl->rlayer.write_sequence,
880             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
881     memcpy(crec_rseq_before, &clientssl->rlayer.read_sequence,
882             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
883     memcpy(srec_wseq_before, &serverssl->rlayer.write_sequence,
884             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
885     memcpy(srec_rseq_before, &serverssl->rlayer.read_sequence,
886             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
887
888     if (!TEST_true(SSL_write(clientssl, cbuf, sizeof(cbuf)) == sizeof(cbuf)))
889         goto end;
890
891     while ((err = SSL_read(serverssl, &sbuf, sizeof(sbuf))) != sizeof(sbuf)) {
892         if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_READ) {
893             goto end;
894         }
895     }
896
897     if (!TEST_true(SSL_write(serverssl, sbuf, sizeof(sbuf)) == sizeof(sbuf)))
898         goto end;
899
900     while ((err = SSL_read(clientssl, &cbuf, sizeof(cbuf))) != sizeof(cbuf)) {
901         if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ) {
902             goto end;
903         }
904     }
905
906     memcpy(crec_wseq_after, &clientssl->rlayer.write_sequence,
907             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
908     memcpy(crec_rseq_after, &clientssl->rlayer.read_sequence,
909             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
910     memcpy(srec_wseq_after, &serverssl->rlayer.write_sequence,
911             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
912     memcpy(srec_rseq_after, &serverssl->rlayer.read_sequence,
913             TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
914
915     /* verify the payload */
916     if (!TEST_mem_eq(cbuf, sizeof(cbuf), sbuf, sizeof(sbuf)))
917         goto end;
918
919     /* ktls is used then kernel sequences are used instead of OpenSSL sequences */
920     if (clientssl->mode & SSL_MODE_NO_KTLS_TX) {
921         if (!TEST_mem_ne(crec_wseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
922                          crec_wseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
923             goto end;
924     } else {
925         if (!TEST_mem_eq(crec_wseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
926                          crec_wseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
927             goto end;
928     }
929
930     if (serverssl->mode & SSL_MODE_NO_KTLS_TX) {
931         if (!TEST_mem_ne(srec_wseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
932                          srec_wseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
933             goto end;
934     } else {
935         if (!TEST_mem_eq(srec_wseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
936                          srec_wseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
937             goto end;
938     }
939
940     if (clientssl->mode & SSL_MODE_NO_KTLS_RX) {
941         if (!TEST_mem_ne(crec_rseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
942                          crec_rseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
943             goto end;
944     } else {
945         if (!TEST_mem_eq(crec_rseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
946                          crec_rseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
947             goto end;
948     }
949
950     if (serverssl->mode & SSL_MODE_NO_KTLS_RX) {
951         if (!TEST_mem_ne(srec_rseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
952                          srec_rseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
953             goto end;
954     } else {
955         if (!TEST_mem_eq(srec_rseq_before, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE,
956                          srec_rseq_after, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE))
957             goto end;
958     }
959
960     return 1;
961 end:
962     return 0;
963 }
964
965 static int execute_test_ktls(int cis_ktls_tx, int cis_ktls_rx,
966                              int sis_ktls_tx, int sis_ktls_rx)
967 {
968     SSL_CTX *cctx = NULL, *sctx = NULL;
969     SSL *clientssl = NULL, *serverssl = NULL;
970     int testresult = 0;
971     int cfd, sfd;
972
973     if (!TEST_true(create_test_sockets(&cfd, &sfd)))
974         goto end;
975
976     /* Skip this test if the platform does not support ktls */
977     if (!ktls_chk_platform(cfd))
978         return 1;
979
980     /* Create a session based on SHA-256 */
981     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
982                                        TLS_client_method(),
983                                        TLS1_2_VERSION, TLS1_2_VERSION,
984                                        &sctx, &cctx, cert, privkey))
985             || !TEST_true(SSL_CTX_set_cipher_list(cctx,
986                                                   "AES128-GCM-SHA256"))
987             || !TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
988                                           &clientssl, sfd, cfd)))
989         goto end;
990
991     if (!cis_ktls_tx) {
992         if (!TEST_true(SSL_set_mode(clientssl, SSL_MODE_NO_KTLS_TX)))
993             goto end;
994     }
995
996     if (!sis_ktls_tx) {
997         if (!TEST_true(SSL_set_mode(serverssl, SSL_MODE_NO_KTLS_TX)))
998             goto end;
999     }
1000
1001     if (!cis_ktls_rx) {
1002         if (!TEST_true(SSL_set_mode(clientssl, SSL_MODE_NO_KTLS_RX)))
1003             goto end;
1004     }
1005
1006     if (!sis_ktls_rx) {
1007         if (!TEST_true(SSL_set_mode(serverssl, SSL_MODE_NO_KTLS_RX)))
1008             goto end;
1009     }
1010
1011     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1012                                                 SSL_ERROR_NONE)))
1013         goto end;
1014
1015     if (!cis_ktls_tx) {
1016         if (!TEST_false(BIO_get_ktls_send(clientssl->wbio)))
1017             goto end;
1018     } else {
1019         if (!TEST_true(BIO_get_ktls_send(clientssl->wbio)))
1020             goto end;
1021     }
1022
1023     if (!sis_ktls_tx) {
1024         if (!TEST_false(BIO_get_ktls_send(serverssl->wbio)))
1025             goto end;
1026     } else {
1027         if (!TEST_true(BIO_get_ktls_send(serverssl->wbio)))
1028             goto end;
1029     }
1030
1031     if (!cis_ktls_rx) {
1032         if (!TEST_false(BIO_get_ktls_recv(clientssl->rbio)))
1033             goto end;
1034     } else {
1035         if (!TEST_true(BIO_get_ktls_recv(clientssl->rbio)))
1036             goto end;
1037     }
1038
1039     if (!sis_ktls_rx) {
1040         if (!TEST_false(BIO_get_ktls_recv(serverssl->rbio)))
1041             goto end;
1042     } else {
1043         if (!TEST_true(BIO_get_ktls_recv(serverssl->rbio)))
1044             goto end;
1045     }
1046
1047     if (!TEST_true(ping_pong_query(clientssl, serverssl, cfd, sfd)))
1048         goto end;
1049
1050     testresult = 1;
1051 end:
1052     if (clientssl) {
1053         SSL_shutdown(clientssl);
1054         SSL_free(clientssl);
1055     }
1056     if (serverssl) {
1057         SSL_shutdown(serverssl);
1058         SSL_free(serverssl);
1059     }
1060     SSL_CTX_free(sctx);
1061     SSL_CTX_free(cctx);
1062     serverssl = clientssl = NULL;
1063     return testresult;
1064 }
1065
1066 #define SENDFILE_SZ                     (16 * 4096)
1067 #define SENDFILE_CHUNK                  (4 * 4096)
1068 #define min(a,b)                        ((a) > (b) ? (b) : (a))
1069
1070 static int test_ktls_sendfile(void)
1071 {
1072     SSL_CTX *cctx = NULL, *sctx = NULL;
1073     SSL *clientssl = NULL, *serverssl = NULL;
1074     unsigned char *buf, *buf_dst;
1075     BIO *out = NULL, *in = NULL;
1076     int cfd, sfd, ffd, err;
1077     ssize_t chunk_size = 0;
1078     off_t chunk_off = 0;
1079     int testresult = 0;
1080     FILE *ffdp;
1081
1082     buf = OPENSSL_zalloc(SENDFILE_SZ);
1083     buf_dst = OPENSSL_zalloc(SENDFILE_SZ);
1084     if (!TEST_ptr(buf) || !TEST_ptr(buf_dst)
1085         || !TEST_true(create_test_sockets(&cfd, &sfd)))
1086         goto end;
1087
1088     /* Skip this test if the platform does not support ktls */
1089     if (!ktls_chk_platform(sfd)) {
1090         testresult = 1;
1091         goto end;
1092     }
1093
1094     /* Create a session based on SHA-256 */
1095     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1096                                        TLS_client_method(),
1097                                        TLS1_2_VERSION, TLS1_2_VERSION,
1098                                        &sctx, &cctx, cert, privkey))
1099         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
1100                                               "AES128-GCM-SHA256"))
1101         || !TEST_true(create_ssl_objects2(sctx, cctx, &serverssl,
1102                                           &clientssl, sfd, cfd)))
1103         goto end;
1104
1105     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1106                                          SSL_ERROR_NONE))
1107         || !TEST_true(BIO_get_ktls_send(serverssl->wbio)))
1108         goto end;
1109
1110     RAND_bytes(buf, SENDFILE_SZ);
1111     out = BIO_new_file(tmpfilename, "wb");
1112     if (!TEST_ptr(out))
1113         goto end;
1114
1115     if (BIO_write(out, buf, SENDFILE_SZ) != SENDFILE_SZ)
1116         goto end;
1117
1118     BIO_free(out);
1119     out = NULL;
1120     in = BIO_new_file(tmpfilename, "rb");
1121     BIO_get_fp(in, &ffdp);
1122     ffd = fileno(ffdp);
1123
1124     while (chunk_off < SENDFILE_SZ) {
1125         chunk_size = min(SENDFILE_CHUNK, SENDFILE_SZ - chunk_off);
1126         while ((err = SSL_sendfile(serverssl,
1127                                    ffd,
1128                                    chunk_off,
1129                                    chunk_size,
1130                                    0)) != chunk_size) {
1131             if (SSL_get_error(serverssl, err) != SSL_ERROR_WANT_WRITE)
1132                 goto end;
1133         }
1134         while ((err = SSL_read(clientssl,
1135                                buf_dst + chunk_off,
1136                                chunk_size)) != chunk_size) {
1137             if (SSL_get_error(clientssl, err) != SSL_ERROR_WANT_READ)
1138                 goto end;
1139         }
1140
1141         /* verify the payload */
1142         if (!TEST_mem_eq(buf_dst + chunk_off,
1143                          chunk_size,
1144                          buf + chunk_off,
1145                          chunk_size))
1146             goto end;
1147
1148         chunk_off += chunk_size;
1149     }
1150
1151     testresult = 1;
1152 end:
1153     if (clientssl) {
1154         SSL_shutdown(clientssl);
1155         SSL_free(clientssl);
1156     }
1157     if (serverssl) {
1158         SSL_shutdown(serverssl);
1159         SSL_free(serverssl);
1160     }
1161     SSL_CTX_free(sctx);
1162     SSL_CTX_free(cctx);
1163     serverssl = clientssl = NULL;
1164     BIO_free(out);
1165     BIO_free(in);
1166     OPENSSL_free(buf);
1167     OPENSSL_free(buf_dst);
1168     return testresult;
1169 }
1170
1171 static int test_ktls_no_txrx_client_no_txrx_server(void)
1172 {
1173     return execute_test_ktls(0, 0, 0, 0);
1174 }
1175
1176 static int test_ktls_no_rx_client_no_txrx_server(void)
1177 {
1178     return execute_test_ktls(1, 0, 0, 0);
1179 }
1180
1181 static int test_ktls_no_tx_client_no_txrx_server(void)
1182 {
1183     return execute_test_ktls(0, 1, 0, 0);
1184 }
1185
1186 static int test_ktls_client_no_txrx_server(void)
1187 {
1188     return execute_test_ktls(1, 1, 0, 0);
1189 }
1190
1191 static int test_ktls_no_txrx_client_no_rx_server(void)
1192 {
1193     return execute_test_ktls(0, 0, 1, 0);
1194 }
1195
1196 static int test_ktls_no_rx_client_no_rx_server(void)
1197 {
1198     return execute_test_ktls(1, 0, 1, 0);
1199 }
1200
1201 static int test_ktls_no_tx_client_no_rx_server(void)
1202 {
1203     return execute_test_ktls(0, 1, 1, 0);
1204 }
1205
1206 static int test_ktls_client_no_rx_server(void)
1207 {
1208     return execute_test_ktls(1, 1, 1, 0);
1209 }
1210
1211 static int test_ktls_no_txrx_client_no_tx_server(void)
1212 {
1213     return execute_test_ktls(0, 0, 0, 1);
1214 }
1215
1216 static int test_ktls_no_rx_client_no_tx_server(void)
1217 {
1218     return execute_test_ktls(1, 0, 0, 1);
1219 }
1220
1221 static int test_ktls_no_tx_client_no_tx_server(void)
1222 {
1223     return execute_test_ktls(0, 1, 0, 1);
1224 }
1225
1226 static int test_ktls_client_no_tx_server(void)
1227 {
1228     return execute_test_ktls(1, 1, 0, 1);
1229 }
1230
1231 static int test_ktls_no_txrx_client_server(void)
1232 {
1233     return execute_test_ktls(0, 0, 1, 1);
1234 }
1235
1236 static int test_ktls_no_rx_client_server(void)
1237 {
1238     return execute_test_ktls(1, 0, 1, 1);
1239 }
1240
1241 static int test_ktls_no_tx_client_server(void)
1242 {
1243     return execute_test_ktls(0, 1, 1, 1);
1244 }
1245
1246 static int test_ktls_client_server(void)
1247 {
1248     return execute_test_ktls(1, 1, 1, 1);
1249 }
1250 #endif
1251
1252 static int test_large_message_tls(void)
1253 {
1254     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1255                                       TLS1_VERSION, 0, 0);
1256 }
1257
1258 static int test_large_message_tls_read_ahead(void)
1259 {
1260     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
1261                                       TLS1_VERSION, 0, 1);
1262 }
1263
1264 #ifndef OPENSSL_NO_DTLS
1265 static int test_large_message_dtls(void)
1266 {
1267     /*
1268      * read_ahead is not relevant to DTLS because DTLS always acts as if
1269      * read_ahead is set.
1270      */
1271     return execute_test_large_message(DTLS_server_method(),
1272                                       DTLS_client_method(),
1273                                       DTLS1_VERSION, 0, 0);
1274 }
1275 #endif
1276
1277 #ifndef OPENSSL_NO_OCSP
1278 static int ocsp_server_cb(SSL *s, void *arg)
1279 {
1280     int *argi = (int *)arg;
1281     unsigned char *copy = NULL;
1282     STACK_OF(OCSP_RESPID) *ids = NULL;
1283     OCSP_RESPID *id = NULL;
1284
1285     if (*argi == 2) {
1286         /* In this test we are expecting exactly 1 OCSP_RESPID */
1287         SSL_get_tlsext_status_ids(s, &ids);
1288         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
1289             return SSL_TLSEXT_ERR_ALERT_FATAL;
1290
1291         id = sk_OCSP_RESPID_value(ids, 0);
1292         if (id == NULL || !OCSP_RESPID_match_ex(id, ocspcert, libctx, NULL))
1293             return SSL_TLSEXT_ERR_ALERT_FATAL;
1294     } else if (*argi != 1) {
1295         return SSL_TLSEXT_ERR_ALERT_FATAL;
1296     }
1297
1298     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
1299         return SSL_TLSEXT_ERR_ALERT_FATAL;
1300
1301     SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder));
1302     ocsp_server_called = 1;
1303     return SSL_TLSEXT_ERR_OK;
1304 }
1305
1306 static int ocsp_client_cb(SSL *s, void *arg)
1307 {
1308     int *argi = (int *)arg;
1309     const unsigned char *respderin;
1310     size_t len;
1311
1312     if (*argi != 1 && *argi != 2)
1313         return 0;
1314
1315     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
1316     if (!TEST_mem_eq(orespder, len, respderin, len))
1317         return 0;
1318
1319     ocsp_client_called = 1;
1320     return 1;
1321 }
1322
1323 static int test_tlsext_status_type(void)
1324 {
1325     SSL_CTX *cctx = NULL, *sctx = NULL;
1326     SSL *clientssl = NULL, *serverssl = NULL;
1327     int testresult = 0;
1328     STACK_OF(OCSP_RESPID) *ids = NULL;
1329     OCSP_RESPID *id = NULL;
1330     BIO *certbio = NULL;
1331
1332     if (!create_ssl_ctx_pair(libctx, TLS_server_method(), TLS_client_method(),
1333                              TLS1_VERSION, 0,
1334                              &sctx, &cctx, cert, privkey))
1335         return 0;
1336
1337     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
1338         goto end;
1339
1340     /* First just do various checks getting and setting tlsext_status_type */
1341
1342     clientssl = SSL_new(cctx);
1343     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
1344             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
1345                                                       TLSEXT_STATUSTYPE_ocsp))
1346             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
1347                             TLSEXT_STATUSTYPE_ocsp))
1348         goto end;
1349
1350     SSL_free(clientssl);
1351     clientssl = NULL;
1352
1353     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
1354      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
1355         goto end;
1356
1357     clientssl = SSL_new(cctx);
1358     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
1359         goto end;
1360     SSL_free(clientssl);
1361     clientssl = NULL;
1362
1363     /*
1364      * Now actually do a handshake and check OCSP information is exchanged and
1365      * the callbacks get called
1366      */
1367     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
1368     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
1369     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
1370     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
1371     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1372                                       &clientssl, NULL, NULL))
1373             || !TEST_true(create_ssl_connection(serverssl, clientssl,
1374                                                 SSL_ERROR_NONE))
1375             || !TEST_true(ocsp_client_called)
1376             || !TEST_true(ocsp_server_called))
1377         goto end;
1378     SSL_free(serverssl);
1379     SSL_free(clientssl);
1380     serverssl = NULL;
1381     clientssl = NULL;
1382
1383     /* Try again but this time force the server side callback to fail */
1384     ocsp_client_called = 0;
1385     ocsp_server_called = 0;
1386     cdummyarg = 0;
1387     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1388                                       &clientssl, NULL, NULL))
1389                 /* This should fail because the callback will fail */
1390             || !TEST_false(create_ssl_connection(serverssl, clientssl,
1391                                                  SSL_ERROR_NONE))
1392             || !TEST_false(ocsp_client_called)
1393             || !TEST_false(ocsp_server_called))
1394         goto end;
1395     SSL_free(serverssl);
1396     SSL_free(clientssl);
1397     serverssl = NULL;
1398     clientssl = NULL;
1399
1400     /*
1401      * This time we'll get the client to send an OCSP_RESPID that it will
1402      * accept.
1403      */
1404     ocsp_client_called = 0;
1405     ocsp_server_called = 0;
1406     cdummyarg = 2;
1407     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1408                                       &clientssl, NULL, NULL)))
1409         goto end;
1410
1411     /*
1412      * We'll just use any old cert for this test - it doesn't have to be an OCSP
1413      * specific one. We'll use the server cert.
1414      */
1415     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
1416             || !TEST_ptr(id = OCSP_RESPID_new())
1417             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
1418             || !TEST_ptr(ocspcert = PEM_read_bio_X509(certbio,
1419                                                       NULL, NULL, NULL))
1420             || !TEST_true(OCSP_RESPID_set_by_key_ex(id, ocspcert, libctx, NULL))
1421             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
1422         goto end;
1423     id = NULL;
1424     SSL_set_tlsext_status_ids(clientssl, ids);
1425     /* Control has been transferred */
1426     ids = NULL;
1427
1428     BIO_free(certbio);
1429     certbio = NULL;
1430
1431     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1432                                          SSL_ERROR_NONE))
1433             || !TEST_true(ocsp_client_called)
1434             || !TEST_true(ocsp_server_called))
1435         goto end;
1436
1437     testresult = 1;
1438
1439  end:
1440     SSL_free(serverssl);
1441     SSL_free(clientssl);
1442     SSL_CTX_free(sctx);
1443     SSL_CTX_free(cctx);
1444     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
1445     OCSP_RESPID_free(id);
1446     BIO_free(certbio);
1447     X509_free(ocspcert);
1448     ocspcert = NULL;
1449
1450     return testresult;
1451 }
1452 #endif
1453
1454 #if !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
1455 static int new_called, remove_called, get_called;
1456
1457 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
1458 {
1459     new_called++;
1460     /*
1461      * sess has been up-refed for us, but we don't actually need it so free it
1462      * immediately.
1463      */
1464     SSL_SESSION_free(sess);
1465     return 1;
1466 }
1467
1468 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
1469 {
1470     remove_called++;
1471 }
1472
1473 static SSL_SESSION *get_sess_val = NULL;
1474
1475 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
1476                                    int *copy)
1477 {
1478     get_called++;
1479     *copy = 1;
1480     return get_sess_val;
1481 }
1482
1483 static int execute_test_session(int maxprot, int use_int_cache,
1484                                 int use_ext_cache)
1485 {
1486     SSL_CTX *sctx = NULL, *cctx = NULL;
1487     SSL *serverssl1 = NULL, *clientssl1 = NULL;
1488     SSL *serverssl2 = NULL, *clientssl2 = NULL;
1489 # ifndef OPENSSL_NO_TLS1_1
1490     SSL *serverssl3 = NULL, *clientssl3 = NULL;
1491 # endif
1492     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
1493     int testresult = 0, numnewsesstick = 1;
1494
1495     new_called = remove_called = 0;
1496
1497     /* TLSv1.3 sends 2 NewSessionTickets */
1498     if (maxprot == TLS1_3_VERSION)
1499         numnewsesstick = 2;
1500
1501     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1502                                        TLS_client_method(), TLS1_VERSION, 0,
1503                                        &sctx, &cctx, cert, privkey)))
1504         return 0;
1505
1506     /*
1507      * Only allow the max protocol version so we can force a connection failure
1508      * later
1509      */
1510     SSL_CTX_set_min_proto_version(cctx, maxprot);
1511     SSL_CTX_set_max_proto_version(cctx, maxprot);
1512
1513     /* Set up session cache */
1514     if (use_ext_cache) {
1515         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
1516         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
1517     }
1518     if (use_int_cache) {
1519         /* Also covers instance where both are set */
1520         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
1521     } else {
1522         SSL_CTX_set_session_cache_mode(cctx,
1523                                        SSL_SESS_CACHE_CLIENT
1524                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1525     }
1526
1527     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1528                                       NULL, NULL))
1529             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1530                                                 SSL_ERROR_NONE))
1531             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
1532         goto end;
1533
1534     /* Should fail because it should already be in the cache */
1535     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
1536         goto end;
1537     if (use_ext_cache
1538             && (!TEST_int_eq(new_called, numnewsesstick)
1539
1540                 || !TEST_int_eq(remove_called, 0)))
1541         goto end;
1542
1543     new_called = remove_called = 0;
1544     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1545                                       &clientssl2, NULL, NULL))
1546             || !TEST_true(SSL_set_session(clientssl2, sess1))
1547             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1548                                                 SSL_ERROR_NONE))
1549             || !TEST_true(SSL_session_reused(clientssl2)))
1550         goto end;
1551
1552     if (maxprot == TLS1_3_VERSION) {
1553         /*
1554          * In TLSv1.3 we should have created a new session even though we have
1555          * resumed. Since we attempted a resume we should also have removed the
1556          * old ticket from the cache so that we try to only use tickets once.
1557          */
1558         if (use_ext_cache
1559                 && (!TEST_int_eq(new_called, 1)
1560                     || !TEST_int_eq(remove_called, 1)))
1561             goto end;
1562     } else {
1563         /*
1564          * In TLSv1.2 we expect to have resumed so no sessions added or
1565          * removed.
1566          */
1567         if (use_ext_cache
1568                 && (!TEST_int_eq(new_called, 0)
1569                     || !TEST_int_eq(remove_called, 0)))
1570             goto end;
1571     }
1572
1573     SSL_SESSION_free(sess1);
1574     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
1575         goto end;
1576     shutdown_ssl_connection(serverssl2, clientssl2);
1577     serverssl2 = clientssl2 = NULL;
1578
1579     new_called = remove_called = 0;
1580     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1581                                       &clientssl2, NULL, NULL))
1582             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1583                                                 SSL_ERROR_NONE)))
1584         goto end;
1585
1586     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
1587         goto end;
1588
1589     if (use_ext_cache
1590             && (!TEST_int_eq(new_called, numnewsesstick)
1591                 || !TEST_int_eq(remove_called, 0)))
1592         goto end;
1593
1594     new_called = remove_called = 0;
1595     /*
1596      * This should clear sess2 from the cache because it is a "bad" session.
1597      * See SSL_set_session() documentation.
1598      */
1599     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
1600         goto end;
1601     if (use_ext_cache
1602             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1603         goto end;
1604     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
1605         goto end;
1606
1607     if (use_int_cache) {
1608         /* Should succeeded because it should not already be in the cache */
1609         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
1610                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
1611             goto end;
1612     }
1613
1614     new_called = remove_called = 0;
1615     /* This shouldn't be in the cache so should fail */
1616     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
1617         goto end;
1618
1619     if (use_ext_cache
1620             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1621         goto end;
1622
1623 # if !defined(OPENSSL_NO_TLS1_1)
1624     new_called = remove_called = 0;
1625     /* Force a connection failure */
1626     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
1627     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
1628                                       &clientssl3, NULL, NULL))
1629             || !TEST_true(SSL_set_session(clientssl3, sess1))
1630             /* This should fail because of the mismatched protocol versions */
1631             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
1632                                                  SSL_ERROR_NONE)))
1633         goto end;
1634
1635     /* We should have automatically removed the session from the cache */
1636     if (use_ext_cache
1637             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1638         goto end;
1639
1640     /* Should succeed because it should not already be in the cache */
1641     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
1642         goto end;
1643 # endif
1644
1645     /* Now do some tests for server side caching */
1646     if (use_ext_cache) {
1647         SSL_CTX_sess_set_new_cb(cctx, NULL);
1648         SSL_CTX_sess_set_remove_cb(cctx, NULL);
1649         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
1650         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
1651         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
1652         get_sess_val = NULL;
1653     }
1654
1655     SSL_CTX_set_session_cache_mode(cctx, 0);
1656     /* Internal caching is the default on the server side */
1657     if (!use_int_cache)
1658         SSL_CTX_set_session_cache_mode(sctx,
1659                                        SSL_SESS_CACHE_SERVER
1660                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1661
1662     SSL_free(serverssl1);
1663     SSL_free(clientssl1);
1664     serverssl1 = clientssl1 = NULL;
1665     SSL_free(serverssl2);
1666     SSL_free(clientssl2);
1667     serverssl2 = clientssl2 = NULL;
1668     SSL_SESSION_free(sess1);
1669     sess1 = NULL;
1670     SSL_SESSION_free(sess2);
1671     sess2 = NULL;
1672
1673     SSL_CTX_set_max_proto_version(sctx, maxprot);
1674     if (maxprot == TLS1_2_VERSION)
1675         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
1676     new_called = remove_called = get_called = 0;
1677     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1678                                       NULL, NULL))
1679             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1680                                                 SSL_ERROR_NONE))
1681             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
1682             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
1683         goto end;
1684
1685     if (use_int_cache) {
1686         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
1687             /*
1688              * In TLSv1.3 it should not have been added to the internal cache,
1689              * except in the case where we also have an external cache (in that
1690              * case it gets added to the cache in order to generate remove
1691              * events after timeout).
1692              */
1693             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
1694                 goto end;
1695         } else {
1696             /* Should fail because it should already be in the cache */
1697             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
1698                 goto end;
1699         }
1700     }
1701
1702     if (use_ext_cache) {
1703         SSL_SESSION *tmp = sess2;
1704
1705         if (!TEST_int_eq(new_called, numnewsesstick)
1706                 || !TEST_int_eq(remove_called, 0)
1707                 || !TEST_int_eq(get_called, 0))
1708             goto end;
1709         /*
1710          * Delete the session from the internal cache to force a lookup from
1711          * the external cache. We take a copy first because
1712          * SSL_CTX_remove_session() also marks the session as non-resumable.
1713          */
1714         if (use_int_cache && maxprot != TLS1_3_VERSION) {
1715             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
1716                     || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
1717                 goto end;
1718             SSL_SESSION_free(sess2);
1719         }
1720         sess2 = tmp;
1721     }
1722
1723     new_called = remove_called = get_called = 0;
1724     get_sess_val = sess2;
1725     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1726                                       &clientssl2, NULL, NULL))
1727             || !TEST_true(SSL_set_session(clientssl2, sess1))
1728             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1729                                                 SSL_ERROR_NONE))
1730             || !TEST_true(SSL_session_reused(clientssl2)))
1731         goto end;
1732
1733     if (use_ext_cache) {
1734         if (!TEST_int_eq(remove_called, 0))
1735             goto end;
1736
1737         if (maxprot == TLS1_3_VERSION) {
1738             if (!TEST_int_eq(new_called, 1)
1739                     || !TEST_int_eq(get_called, 0))
1740                 goto end;
1741         } else {
1742             if (!TEST_int_eq(new_called, 0)
1743                     || !TEST_int_eq(get_called, 1))
1744                 goto end;
1745         }
1746     }
1747
1748     testresult = 1;
1749
1750  end:
1751     SSL_free(serverssl1);
1752     SSL_free(clientssl1);
1753     SSL_free(serverssl2);
1754     SSL_free(clientssl2);
1755 # ifndef OPENSSL_NO_TLS1_1
1756     SSL_free(serverssl3);
1757     SSL_free(clientssl3);
1758 # endif
1759     SSL_SESSION_free(sess1);
1760     SSL_SESSION_free(sess2);
1761     SSL_CTX_free(sctx);
1762     SSL_CTX_free(cctx);
1763
1764     return testresult;
1765 }
1766 #endif /* !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
1767
1768 static int test_session_with_only_int_cache(void)
1769 {
1770 #ifndef OPENSSL_NO_TLS1_3
1771     if (!execute_test_session(TLS1_3_VERSION, 1, 0))
1772         return 0;
1773 #endif
1774
1775 #ifndef OPENSSL_NO_TLS1_2
1776     return execute_test_session(TLS1_2_VERSION, 1, 0);
1777 #else
1778     return 1;
1779 #endif
1780 }
1781
1782 static int test_session_with_only_ext_cache(void)
1783 {
1784 #ifndef OPENSSL_NO_TLS1_3
1785     if (!execute_test_session(TLS1_3_VERSION, 0, 1))
1786         return 0;
1787 #endif
1788
1789 #ifndef OPENSSL_NO_TLS1_2
1790     return execute_test_session(TLS1_2_VERSION, 0, 1);
1791 #else
1792     return 1;
1793 #endif
1794 }
1795
1796 static int test_session_with_both_cache(void)
1797 {
1798 #ifndef OPENSSL_NO_TLS1_3
1799     if (!execute_test_session(TLS1_3_VERSION, 1, 1))
1800         return 0;
1801 #endif
1802
1803 #ifndef OPENSSL_NO_TLS1_2
1804     return execute_test_session(TLS1_2_VERSION, 1, 1);
1805 #else
1806     return 1;
1807 #endif
1808 }
1809
1810 #ifndef OPENSSL_NO_TLS1_3
1811 static SSL_SESSION *sesscache[6];
1812 static int do_cache;
1813
1814 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
1815 {
1816     if (do_cache) {
1817         sesscache[new_called] = sess;
1818     } else {
1819         /* We don't need the reference to the session, so free it */
1820         SSL_SESSION_free(sess);
1821     }
1822     new_called++;
1823
1824     return 1;
1825 }
1826
1827 static int post_handshake_verify(SSL *sssl, SSL *cssl)
1828 {
1829     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
1830     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
1831         return 0;
1832
1833     /* Start handshake on the server and client */
1834     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
1835             || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
1836             || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
1837             || !TEST_true(create_ssl_connection(sssl, cssl,
1838                                                 SSL_ERROR_NONE)))
1839         return 0;
1840
1841     return 1;
1842 }
1843
1844 static int setup_ticket_test(int stateful, int idx, SSL_CTX **sctx,
1845                              SSL_CTX **cctx)
1846 {
1847     int sess_id_ctx = 1;
1848
1849     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
1850                                        TLS_client_method(), TLS1_VERSION, 0,
1851                                        sctx, cctx, cert, privkey))
1852             || !TEST_true(SSL_CTX_set_num_tickets(*sctx, idx))
1853             || !TEST_true(SSL_CTX_set_session_id_context(*sctx,
1854                                                          (void *)&sess_id_ctx,
1855                                                          sizeof(sess_id_ctx))))
1856         return 0;
1857
1858     if (stateful)
1859         SSL_CTX_set_options(*sctx, SSL_OP_NO_TICKET);
1860
1861     SSL_CTX_set_session_cache_mode(*cctx, SSL_SESS_CACHE_CLIENT
1862                                           | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1863     SSL_CTX_sess_set_new_cb(*cctx, new_cachesession_cb);
1864
1865     return 1;
1866 }
1867
1868 static int check_resumption(int idx, SSL_CTX *sctx, SSL_CTX *cctx, int succ)
1869 {
1870     SSL *serverssl = NULL, *clientssl = NULL;
1871     int i;
1872
1873     /* Test that we can resume with all the tickets we got given */
1874     for (i = 0; i < idx * 2; i++) {
1875         new_called = 0;
1876         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1877                                               &clientssl, NULL, NULL))
1878                 || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
1879             goto end;
1880
1881         SSL_set_post_handshake_auth(clientssl, 1);
1882
1883         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1884                                                     SSL_ERROR_NONE)))
1885             goto end;
1886
1887         /*
1888          * Following a successful resumption we only get 1 ticket. After a
1889          * failed one we should get idx tickets.
1890          */
1891         if (succ) {
1892             if (!TEST_true(SSL_session_reused(clientssl))
1893                     || !TEST_int_eq(new_called, 1))
1894                 goto end;
1895         } else {
1896             if (!TEST_false(SSL_session_reused(clientssl))
1897                     || !TEST_int_eq(new_called, idx))
1898                 goto end;
1899         }
1900
1901         new_called = 0;
1902         /* After a post-handshake authentication we should get 1 new ticket */
1903         if (succ
1904                 && (!post_handshake_verify(serverssl, clientssl)
1905                     || !TEST_int_eq(new_called, 1)))
1906             goto end;
1907
1908         SSL_shutdown(clientssl);
1909         SSL_shutdown(serverssl);
1910         SSL_free(serverssl);
1911         SSL_free(clientssl);
1912         serverssl = clientssl = NULL;
1913         SSL_SESSION_free(sesscache[i]);
1914         sesscache[i] = NULL;
1915     }
1916
1917     return 1;
1918
1919  end:
1920     SSL_free(clientssl);
1921     SSL_free(serverssl);
1922     return 0;
1923 }
1924
1925 static int test_tickets(int stateful, int idx)
1926 {
1927     SSL_CTX *sctx = NULL, *cctx = NULL;
1928     SSL *serverssl = NULL, *clientssl = NULL;
1929     int testresult = 0;
1930     size_t j;
1931
1932     /* idx is the test number, but also the number of tickets we want */
1933
1934     new_called = 0;
1935     do_cache = 1;
1936
1937     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
1938         goto end;
1939
1940     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1941                                           &clientssl, NULL, NULL)))
1942         goto end;
1943
1944     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1945                                                 SSL_ERROR_NONE))
1946                /* Check we got the number of tickets we were expecting */
1947             || !TEST_int_eq(idx, new_called))
1948         goto end;
1949
1950     SSL_shutdown(clientssl);
1951     SSL_shutdown(serverssl);
1952     SSL_free(serverssl);
1953     SSL_free(clientssl);
1954     SSL_CTX_free(sctx);
1955     SSL_CTX_free(cctx);
1956     clientssl = serverssl = NULL;
1957     sctx = cctx = NULL;
1958
1959     /*
1960      * Now we try to resume with the tickets we previously created. The
1961      * resumption attempt is expected to fail (because we're now using a new
1962      * SSL_CTX). We should see idx number of tickets issued again.
1963      */
1964
1965     /* Stop caching sessions - just count them */
1966     do_cache = 0;
1967
1968     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
1969         goto end;
1970
1971     if (!check_resumption(idx, sctx, cctx, 0))
1972         goto end;
1973
1974     /* Start again with caching sessions */
1975     new_called = 0;
1976     do_cache = 1;
1977     SSL_CTX_free(sctx);
1978     SSL_CTX_free(cctx);
1979     sctx = cctx = NULL;
1980
1981     if (!setup_ticket_test(stateful, idx, &sctx, &cctx))
1982         goto end;
1983
1984     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1985                                           &clientssl, NULL, NULL)))
1986         goto end;
1987
1988     SSL_set_post_handshake_auth(clientssl, 1);
1989
1990     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1991                                                 SSL_ERROR_NONE))
1992                /* Check we got the number of tickets we were expecting */
1993             || !TEST_int_eq(idx, new_called))
1994         goto end;
1995
1996     /* After a post-handshake authentication we should get new tickets issued */
1997     if (!post_handshake_verify(serverssl, clientssl)
1998             || !TEST_int_eq(idx * 2, new_called))
1999         goto end;
2000
2001     SSL_shutdown(clientssl);
2002     SSL_shutdown(serverssl);
2003     SSL_free(serverssl);
2004     SSL_free(clientssl);
2005     serverssl = clientssl = NULL;
2006
2007     /* Stop caching sessions - just count them */
2008     do_cache = 0;
2009
2010     /*
2011      * Check we can resume with all the tickets we created. This time around the
2012      * resumptions should all be successful.
2013      */
2014     if (!check_resumption(idx, sctx, cctx, 1))
2015         goto end;
2016
2017     testresult = 1;
2018
2019  end:
2020     SSL_free(serverssl);
2021     SSL_free(clientssl);
2022     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
2023         SSL_SESSION_free(sesscache[j]);
2024         sesscache[j] = NULL;
2025     }
2026     SSL_CTX_free(sctx);
2027     SSL_CTX_free(cctx);
2028
2029     return testresult;
2030 }
2031
2032 static int test_stateless_tickets(int idx)
2033 {
2034     return test_tickets(0, idx);
2035 }
2036
2037 static int test_stateful_tickets(int idx)
2038 {
2039     return test_tickets(1, idx);
2040 }
2041
2042 static int test_psk_tickets(void)
2043 {
2044     SSL_CTX *sctx = NULL, *cctx = NULL;
2045     SSL *serverssl = NULL, *clientssl = NULL;
2046     int testresult = 0;
2047     int sess_id_ctx = 1;
2048
2049     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2050                                        TLS_client_method(), TLS1_VERSION, 0,
2051                                        &sctx, &cctx, NULL, NULL))
2052             || !TEST_true(SSL_CTX_set_session_id_context(sctx,
2053                                                          (void *)&sess_id_ctx,
2054                                                          sizeof(sess_id_ctx))))
2055         goto end;
2056
2057     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
2058                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
2059     SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
2060     SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
2061     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2062     use_session_cb_cnt = 0;
2063     find_session_cb_cnt = 0;
2064     srvid = pskid;
2065     new_called = 0;
2066
2067     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2068                                       NULL, NULL)))
2069         goto end;
2070     clientpsk = serverpsk = create_a_psk(clientssl);
2071     if (!TEST_ptr(clientpsk))
2072         goto end;
2073     SSL_SESSION_up_ref(clientpsk);
2074
2075     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2076                                                 SSL_ERROR_NONE))
2077             || !TEST_int_eq(1, find_session_cb_cnt)
2078             || !TEST_int_eq(1, use_session_cb_cnt)
2079                /* We should always get 1 ticket when using external PSK */
2080             || !TEST_int_eq(1, new_called))
2081         goto end;
2082
2083     testresult = 1;
2084
2085  end:
2086     SSL_free(serverssl);
2087     SSL_free(clientssl);
2088     SSL_CTX_free(sctx);
2089     SSL_CTX_free(cctx);
2090     SSL_SESSION_free(clientpsk);
2091     SSL_SESSION_free(serverpsk);
2092     clientpsk = serverpsk = NULL;
2093
2094     return testresult;
2095 }
2096
2097 static int test_extra_tickets(int idx)
2098 {
2099     SSL_CTX *sctx = NULL, *cctx = NULL;
2100     SSL *serverssl = NULL, *clientssl = NULL;
2101     BIO *bretry = BIO_new(bio_s_always_retry());
2102     BIO *tmp = NULL;
2103     int testresult = 0;
2104     int stateful = 0;
2105     size_t nbytes;
2106     unsigned char c, buf[1];
2107
2108     new_called = 0;
2109     do_cache = 1;
2110
2111     if (idx >= 3) {
2112         idx -= 3;
2113         stateful = 1;
2114     }
2115
2116     if (!TEST_ptr(bretry) || !setup_ticket_test(stateful, idx, &sctx, &cctx))
2117         goto end;
2118     SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
2119     /* setup_ticket_test() uses new_cachesession_cb which we don't need. */
2120     SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
2121
2122     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2123                                           &clientssl, NULL, NULL)))
2124         goto end;
2125
2126     /*
2127      * Note that we have new_session_cb on both sctx and cctx, so new_called is
2128      * incremented by both client and server.
2129      */
2130     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
2131                                                 SSL_ERROR_NONE))
2132                /* Check we got the number of tickets we were expecting */
2133             || !TEST_int_eq(idx * 2, new_called)
2134             || !TEST_true(SSL_new_session_ticket(serverssl))
2135             || !TEST_true(SSL_new_session_ticket(serverssl))
2136             || !TEST_int_eq(idx * 2, new_called))
2137         goto end;
2138
2139     /* Now try a (real) write to actually send the tickets */
2140     c = '1';
2141     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2142             || !TEST_size_t_eq(1, nbytes)
2143             || !TEST_int_eq(idx * 2 + 2, new_called)
2144             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2145             || !TEST_int_eq(idx * 2 + 4, new_called)
2146             || !TEST_int_eq(sizeof(buf), nbytes)
2147             || !TEST_int_eq(c, buf[0])
2148             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2149         goto end;
2150
2151     /* Try with only requesting one new ticket, too */
2152     c = '2';
2153     new_called = 0;
2154     if (!TEST_true(SSL_new_session_ticket(serverssl))
2155             || !TEST_true(SSL_write_ex(serverssl, &c, sizeof(c), &nbytes))
2156             || !TEST_size_t_eq(sizeof(c), nbytes)
2157             || !TEST_int_eq(1, new_called)
2158             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2159             || !TEST_int_eq(2, new_called)
2160             || !TEST_size_t_eq(sizeof(buf), nbytes)
2161             || !TEST_int_eq(c, buf[0]))
2162         goto end;
2163
2164     /* Do it again but use dummy writes to drive the ticket generation */
2165     c = '3';
2166     new_called = 0;
2167     if (!TEST_true(SSL_new_session_ticket(serverssl))
2168             || !TEST_true(SSL_new_session_ticket(serverssl))
2169             || !TEST_true(SSL_write_ex(serverssl, &c, 0, &nbytes))
2170             || !TEST_size_t_eq(0, nbytes)
2171             || !TEST_int_eq(2, new_called)
2172             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2173             || !TEST_int_eq(4, new_called))
2174         goto end;
2175
2176     /*
2177      * Use the always-retry BIO to exercise the logic that forces ticket
2178      * generation to wait until a record boundary.
2179      */
2180     c = '4';
2181     new_called = 0;
2182     tmp = SSL_get_wbio(serverssl);
2183     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
2184         tmp = NULL;
2185         goto end;
2186     }
2187     SSL_set0_wbio(serverssl, bretry);
2188     bretry = NULL;
2189     if (!TEST_false(SSL_write_ex(serverssl, &c, 1, &nbytes))
2190             || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_WANT_WRITE)
2191             || !TEST_size_t_eq(nbytes, 0))
2192         goto end;
2193     /* Restore a BIO that will let the write succeed */
2194     SSL_set0_wbio(serverssl, tmp);
2195     tmp = NULL;
2196     /* These calls should just queue the request and not send anything. */
2197     if (!TEST_true(SSL_new_session_ticket(serverssl))
2198             || !TEST_true(SSL_new_session_ticket(serverssl))
2199             || !TEST_int_eq(0, new_called))
2200         goto end;
2201     /* Re-do the write; still no tickets sent */
2202     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2203             || !TEST_size_t_eq(1, nbytes)
2204             || !TEST_int_eq(0, new_called)
2205             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2206             || !TEST_int_eq(0, new_called)
2207             || !TEST_int_eq(sizeof(buf), nbytes)
2208             || !TEST_int_eq(c, buf[0])
2209             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2210         goto end;
2211     /* Now the *next* write should send the tickets */
2212     c = '5';
2213     if (!TEST_true(SSL_write_ex(serverssl, &c, 1, &nbytes))
2214             || !TEST_size_t_eq(1, nbytes)
2215             || !TEST_int_eq(2, new_called)
2216             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes))
2217             || !TEST_int_eq(4, new_called)
2218             || !TEST_int_eq(sizeof(buf), nbytes)
2219             || !TEST_int_eq(c, buf[0])
2220             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &nbytes)))
2221         goto end;
2222
2223     SSL_shutdown(clientssl);
2224     SSL_shutdown(serverssl);
2225     testresult = 1;
2226
2227  end:
2228     BIO_free(bretry);
2229     BIO_free(tmp);
2230     SSL_free(serverssl);
2231     SSL_free(clientssl);
2232     SSL_CTX_free(sctx);
2233     SSL_CTX_free(cctx);
2234     clientssl = serverssl = NULL;
2235     sctx = cctx = NULL;
2236     return testresult;
2237 }
2238 #endif
2239
2240 #define USE_NULL            0
2241 #define USE_BIO_1           1
2242 #define USE_BIO_2           2
2243 #define USE_DEFAULT         3
2244
2245 #define CONNTYPE_CONNECTION_SUCCESS  0
2246 #define CONNTYPE_CONNECTION_FAIL     1
2247 #define CONNTYPE_NO_CONNECTION       2
2248
2249 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
2250 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
2251 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
2252 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
2253 #else
2254 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
2255 #endif
2256
2257 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
2258                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
2259                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
2260
2261 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
2262 {
2263     switch (type) {
2264     case USE_NULL:
2265         *res = NULL;
2266         break;
2267     case USE_BIO_1:
2268         *res = bio1;
2269         break;
2270     case USE_BIO_2:
2271         *res = bio2;
2272         break;
2273     }
2274 }
2275
2276
2277 /*
2278  * Tests calls to SSL_set_bio() under various conditions.
2279  *
2280  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
2281  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
2282  * then do more tests where we create a successful connection first using our
2283  * standard connection setup functions, and then call SSL_set_bio() with
2284  * various combinations of valid BIOs or NULL. We then repeat these tests
2285  * following a failed connection. In this last case we are looking to check that
2286  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
2287  */
2288 static int test_ssl_set_bio(int idx)
2289 {
2290     SSL_CTX *sctx = NULL, *cctx = NULL;
2291     BIO *bio1 = NULL;
2292     BIO *bio2 = NULL;
2293     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
2294     SSL *serverssl = NULL, *clientssl = NULL;
2295     int initrbio, initwbio, newrbio, newwbio, conntype;
2296     int testresult = 0;
2297
2298     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
2299         initrbio = idx % 3;
2300         idx /= 3;
2301         initwbio = idx % 3;
2302         idx /= 3;
2303         newrbio = idx % 3;
2304         idx /= 3;
2305         newwbio = idx % 3;
2306         conntype = CONNTYPE_NO_CONNECTION;
2307     } else {
2308         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
2309         initrbio = initwbio = USE_DEFAULT;
2310         newrbio = idx % 2;
2311         idx /= 2;
2312         newwbio = idx % 2;
2313         idx /= 2;
2314         conntype = idx % 2;
2315     }
2316
2317     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2318                                        TLS_client_method(), TLS1_VERSION, 0,
2319                                        &sctx, &cctx, cert, privkey)))
2320         goto end;
2321
2322     if (conntype == CONNTYPE_CONNECTION_FAIL) {
2323         /*
2324          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
2325          * because we reduced the number of tests in the definition of
2326          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
2327          * mismatched protocol versions we will force a connection failure.
2328          */
2329         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
2330         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2331     }
2332
2333     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2334                                       NULL, NULL)))
2335         goto end;
2336
2337     if (initrbio == USE_BIO_1
2338             || initwbio == USE_BIO_1
2339             || newrbio == USE_BIO_1
2340             || newwbio == USE_BIO_1) {
2341         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
2342             goto end;
2343     }
2344
2345     if (initrbio == USE_BIO_2
2346             || initwbio == USE_BIO_2
2347             || newrbio == USE_BIO_2
2348             || newwbio == USE_BIO_2) {
2349         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
2350             goto end;
2351     }
2352
2353     if (initrbio != USE_DEFAULT) {
2354         setupbio(&irbio, bio1, bio2, initrbio);
2355         setupbio(&iwbio, bio1, bio2, initwbio);
2356         SSL_set_bio(clientssl, irbio, iwbio);
2357
2358         /*
2359          * We want to maintain our own refs to these BIO, so do an up ref for
2360          * each BIO that will have ownership transferred in the SSL_set_bio()
2361          * call
2362          */
2363         if (irbio != NULL)
2364             BIO_up_ref(irbio);
2365         if (iwbio != NULL && iwbio != irbio)
2366             BIO_up_ref(iwbio);
2367     }
2368
2369     if (conntype != CONNTYPE_NO_CONNECTION
2370             && !TEST_true(create_ssl_connection(serverssl, clientssl,
2371                                                 SSL_ERROR_NONE)
2372                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
2373         goto end;
2374
2375     setupbio(&nrbio, bio1, bio2, newrbio);
2376     setupbio(&nwbio, bio1, bio2, newwbio);
2377
2378     /*
2379      * We will (maybe) transfer ownership again so do more up refs.
2380      * SSL_set_bio() has some really complicated ownership rules where BIOs have
2381      * already been set!
2382      */
2383     if (nrbio != NULL
2384             && nrbio != irbio
2385             && (nwbio != iwbio || nrbio != nwbio))
2386         BIO_up_ref(nrbio);
2387     if (nwbio != NULL
2388             && nwbio != nrbio
2389             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
2390         BIO_up_ref(nwbio);
2391
2392     SSL_set_bio(clientssl, nrbio, nwbio);
2393
2394     testresult = 1;
2395
2396  end:
2397     BIO_free(bio1);
2398     BIO_free(bio2);
2399
2400     /*
2401      * This test is checking that the ref counting for SSL_set_bio is correct.
2402      * If we get here and we did too many frees then we will fail in the above
2403      * functions.
2404      */
2405     SSL_free(serverssl);
2406     SSL_free(clientssl);
2407     SSL_CTX_free(sctx);
2408     SSL_CTX_free(cctx);
2409     return testresult;
2410 }
2411
2412 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
2413
2414 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
2415 {
2416     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
2417     SSL_CTX *ctx;
2418     SSL *ssl = NULL;
2419     int testresult = 0;
2420
2421     if (!TEST_ptr(ctx = SSL_CTX_new_with_libctx(libctx, NULL, TLS_method()))
2422             || !TEST_ptr(ssl = SSL_new(ctx))
2423             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
2424             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
2425         goto end;
2426
2427     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
2428
2429     /*
2430      * If anything goes wrong here then we could leak memory.
2431      */
2432     BIO_push(sslbio, membio1);
2433
2434     /* Verify changing the rbio/wbio directly does not cause leaks */
2435     if (change_bio != NO_BIO_CHANGE) {
2436         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
2437             goto end;
2438         if (change_bio == CHANGE_RBIO)
2439             SSL_set0_rbio(ssl, membio2);
2440         else
2441             SSL_set0_wbio(ssl, membio2);
2442     }
2443     ssl = NULL;
2444
2445     if (pop_ssl)
2446         BIO_pop(sslbio);
2447     else
2448         BIO_pop(membio1);
2449
2450     testresult = 1;
2451  end:
2452     BIO_free(membio1);
2453     BIO_free(sslbio);
2454     SSL_free(ssl);
2455     SSL_CTX_free(ctx);
2456
2457     return testresult;
2458 }
2459
2460 static int test_ssl_bio_pop_next_bio(void)
2461 {
2462     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
2463 }
2464
2465 static int test_ssl_bio_pop_ssl_bio(void)
2466 {
2467     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
2468 }
2469
2470 static int test_ssl_bio_change_rbio(void)
2471 {
2472     return execute_test_ssl_bio(0, CHANGE_RBIO);
2473 }
2474
2475 static int test_ssl_bio_change_wbio(void)
2476 {
2477     return execute_test_ssl_bio(0, CHANGE_WBIO);
2478 }
2479
2480 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
2481 typedef struct {
2482     /* The list of sig algs */
2483     const int *list;
2484     /* The length of the list */
2485     size_t listlen;
2486     /* A sigalgs list in string format */
2487     const char *liststr;
2488     /* Whether setting the list should succeed */
2489     int valid;
2490     /* Whether creating a connection with the list should succeed */
2491     int connsuccess;
2492 } sigalgs_list;
2493
2494 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
2495 # ifndef OPENSSL_NO_EC
2496 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
2497 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
2498 # endif
2499 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
2500 static const int invalidlist2[] = {NID_sha256, NID_undef};
2501 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
2502 static const int invalidlist4[] = {NID_sha256};
2503 static const sigalgs_list testsigalgs[] = {
2504     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
2505 # ifndef OPENSSL_NO_EC
2506     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
2507     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
2508 # endif
2509     {NULL, 0, "RSA+SHA256", 1, 1},
2510 # ifndef OPENSSL_NO_EC
2511     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
2512     {NULL, 0, "ECDSA+SHA512", 1, 0},
2513 # endif
2514     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
2515     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
2516     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
2517     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
2518     {NULL, 0, "RSA", 0, 0},
2519     {NULL, 0, "SHA256", 0, 0},
2520     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
2521     {NULL, 0, "Invalid", 0, 0}
2522 };
2523
2524 static int test_set_sigalgs(int idx)
2525 {
2526     SSL_CTX *cctx = NULL, *sctx = NULL;
2527     SSL *clientssl = NULL, *serverssl = NULL;
2528     int testresult = 0;
2529     const sigalgs_list *curr;
2530     int testctx;
2531
2532     /* Should never happen */
2533     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
2534         return 0;
2535
2536     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
2537     curr = testctx ? &testsigalgs[idx]
2538                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
2539
2540     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2541                                        TLS_client_method(), TLS1_VERSION, 0,
2542                                        &sctx, &cctx, cert, privkey)))
2543         return 0;
2544
2545     /*
2546      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
2547      * for TLSv1.2 for now until we add a new API.
2548      */
2549     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
2550
2551     if (testctx) {
2552         int ret;
2553
2554         if (curr->list != NULL)
2555             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
2556         else
2557             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
2558
2559         if (!ret) {
2560             if (curr->valid)
2561                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
2562             else
2563                 testresult = 1;
2564             goto end;
2565         }
2566         if (!curr->valid) {
2567             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
2568             goto end;
2569         }
2570     }
2571
2572     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2573                                       &clientssl, NULL, NULL)))
2574         goto end;
2575
2576     if (!testctx) {
2577         int ret;
2578
2579         if (curr->list != NULL)
2580             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
2581         else
2582             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
2583         if (!ret) {
2584             if (curr->valid)
2585                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
2586             else
2587                 testresult = 1;
2588             goto end;
2589         }
2590         if (!curr->valid)
2591             goto end;
2592     }
2593
2594     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
2595                                            SSL_ERROR_NONE),
2596                 curr->connsuccess))
2597         goto end;
2598
2599     testresult = 1;
2600
2601  end:
2602     SSL_free(serverssl);
2603     SSL_free(clientssl);
2604     SSL_CTX_free(sctx);
2605     SSL_CTX_free(cctx);
2606
2607     return testresult;
2608 }
2609 #endif
2610
2611 #ifndef OPENSSL_NO_TLS1_3
2612 static int psk_client_cb_cnt = 0;
2613 static int psk_server_cb_cnt = 0;
2614
2615 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
2616                           size_t *idlen, SSL_SESSION **sess)
2617 {
2618     switch (++use_session_cb_cnt) {
2619     case 1:
2620         /* The first call should always have a NULL md */
2621         if (md != NULL)
2622             return 0;
2623         break;
2624
2625     case 2:
2626         /* The second call should always have an md */
2627         if (md == NULL)
2628             return 0;
2629         break;
2630
2631     default:
2632         /* We should only be called a maximum of twice */
2633         return 0;
2634     }
2635
2636     if (clientpsk != NULL)
2637         SSL_SESSION_up_ref(clientpsk);
2638
2639     *sess = clientpsk;
2640     *id = (const unsigned char *)pskid;
2641     *idlen = strlen(pskid);
2642
2643     return 1;
2644 }
2645
2646 #ifndef OPENSSL_NO_PSK
2647 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
2648                                   unsigned int max_id_len,
2649                                   unsigned char *psk,
2650                                   unsigned int max_psk_len)
2651 {
2652     unsigned int psklen = 0;
2653
2654     psk_client_cb_cnt++;
2655
2656     if (strlen(pskid) + 1 > max_id_len)
2657         return 0;
2658
2659     /* We should only ever be called a maximum of twice per connection */
2660     if (psk_client_cb_cnt > 2)
2661         return 0;
2662
2663     if (clientpsk == NULL)
2664         return 0;
2665
2666     /* We'll reuse the PSK we set up for TLSv1.3 */
2667     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
2668         return 0;
2669     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
2670     strncpy(id, pskid, max_id_len);
2671
2672     return psklen;
2673 }
2674 #endif /* OPENSSL_NO_PSK */
2675
2676 static int find_session_cb(SSL *ssl, const unsigned char *identity,
2677                            size_t identity_len, SSL_SESSION **sess)
2678 {
2679     find_session_cb_cnt++;
2680
2681     /* We should only ever be called a maximum of twice per connection */
2682     if (find_session_cb_cnt > 2)
2683         return 0;
2684
2685     if (serverpsk == NULL)
2686         return 0;
2687
2688     /* Identity should match that set by the client */
2689     if (strlen(srvid) != identity_len
2690             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
2691         /* No PSK found, continue but without a PSK */
2692         *sess = NULL;
2693         return 1;
2694     }
2695
2696     SSL_SESSION_up_ref(serverpsk);
2697     *sess = serverpsk;
2698
2699     return 1;
2700 }
2701
2702 #ifndef OPENSSL_NO_PSK
2703 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
2704                                   unsigned char *psk, unsigned int max_psk_len)
2705 {
2706     unsigned int psklen = 0;
2707
2708     psk_server_cb_cnt++;
2709
2710     /* We should only ever be called a maximum of twice per connection */
2711     if (find_session_cb_cnt > 2)
2712         return 0;
2713
2714     if (serverpsk == NULL)
2715         return 0;
2716
2717     /* Identity should match that set by the client */
2718     if (strcmp(srvid, identity) != 0) {
2719         return 0;
2720     }
2721
2722     /* We'll reuse the PSK we set up for TLSv1.3 */
2723     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
2724         return 0;
2725     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
2726
2727     return psklen;
2728 }
2729 #endif /* OPENSSL_NO_PSK */
2730
2731 #define MSG1    "Hello"
2732 #define MSG2    "World."
2733 #define MSG3    "This"
2734 #define MSG4    "is"
2735 #define MSG5    "a"
2736 #define MSG6    "test"
2737 #define MSG7    "message."
2738
2739 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
2740 #define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
2741
2742
2743 static SSL_SESSION *create_a_psk(SSL *ssl)
2744 {
2745     const SSL_CIPHER *cipher = NULL;
2746     const unsigned char key[] = {
2747         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
2748         0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
2749         0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
2750         0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
2751         0x2c, 0x2d, 0x2e, 0x2f
2752     };
2753     SSL_SESSION *sess = NULL;
2754
2755     cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES);
2756     sess = SSL_SESSION_new();
2757     if (!TEST_ptr(sess)
2758             || !TEST_ptr(cipher)
2759             || !TEST_true(SSL_SESSION_set1_master_key(sess, key,
2760                                                       sizeof(key)))
2761             || !TEST_true(SSL_SESSION_set_cipher(sess, cipher))
2762             || !TEST_true(
2763                     SSL_SESSION_set_protocol_version(sess,
2764                                                      TLS1_3_VERSION))) {
2765         SSL_SESSION_free(sess);
2766         return NULL;
2767     }
2768     return sess;
2769 }
2770
2771 /*
2772  * Helper method to setup objects for early data test. Caller frees objects on
2773  * error.
2774  */
2775 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
2776                                 SSL **serverssl, SSL_SESSION **sess, int idx)
2777 {
2778     if (*sctx == NULL
2779             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
2780                                               TLS_client_method(),
2781                                               TLS1_VERSION, 0,
2782                                               sctx, cctx, cert, privkey)))
2783         return 0;
2784
2785     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
2786         return 0;
2787
2788     if (idx == 1) {
2789         /* When idx == 1 we repeat the tests with read_ahead set */
2790         SSL_CTX_set_read_ahead(*cctx, 1);
2791         SSL_CTX_set_read_ahead(*sctx, 1);
2792     } else if (idx == 2) {
2793         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
2794         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
2795         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
2796         use_session_cb_cnt = 0;
2797         find_session_cb_cnt = 0;
2798         srvid = pskid;
2799     }
2800
2801     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
2802                                       NULL, NULL)))
2803         return 0;
2804
2805     /*
2806      * For one of the run throughs (doesn't matter which one), we'll try sending
2807      * some SNI data in the initial ClientHello. This will be ignored (because
2808      * there is no SNI cb set up by the server), so it should not impact
2809      * early_data.
2810      */
2811     if (idx == 1
2812             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
2813         return 0;
2814
2815     if (idx == 2) {
2816         clientpsk = create_a_psk(*clientssl);
2817         if (!TEST_ptr(clientpsk)
2818                    /*
2819                     * We just choose an arbitrary value for max_early_data which
2820                     * should be big enough for testing purposes.
2821                     */
2822                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
2823                                                              0x100))
2824                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
2825             SSL_SESSION_free(clientpsk);
2826             clientpsk = NULL;
2827             return 0;
2828         }
2829         serverpsk = clientpsk;
2830
2831         if (sess != NULL) {
2832             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
2833                 SSL_SESSION_free(clientpsk);
2834                 SSL_SESSION_free(serverpsk);
2835                 clientpsk = serverpsk = NULL;
2836                 return 0;
2837             }
2838             *sess = clientpsk;
2839         }
2840         return 1;
2841     }
2842
2843     if (sess == NULL)
2844         return 1;
2845
2846     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
2847                                          SSL_ERROR_NONE)))
2848         return 0;
2849
2850     *sess = SSL_get1_session(*clientssl);
2851     SSL_shutdown(*clientssl);
2852     SSL_shutdown(*serverssl);
2853     SSL_free(*serverssl);
2854     SSL_free(*clientssl);
2855     *serverssl = *clientssl = NULL;
2856
2857     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
2858                                       clientssl, NULL, NULL))
2859             || !TEST_true(SSL_set_session(*clientssl, *sess)))
2860         return 0;
2861
2862     return 1;
2863 }
2864
2865 static int test_early_data_read_write(int idx)
2866 {
2867     SSL_CTX *cctx = NULL, *sctx = NULL;
2868     SSL *clientssl = NULL, *serverssl = NULL;
2869     int testresult = 0;
2870     SSL_SESSION *sess = NULL;
2871     unsigned char buf[20], data[1024];
2872     size_t readbytes, written, eoedlen, rawread, rawwritten;
2873     BIO *rbio;
2874
2875     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2876                                         &serverssl, &sess, idx)))
2877         goto end;
2878
2879     /* Write and read some early data */
2880     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2881                                         &written))
2882             || !TEST_size_t_eq(written, strlen(MSG1))
2883             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
2884                                                 sizeof(buf), &readbytes),
2885                             SSL_READ_EARLY_DATA_SUCCESS)
2886             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
2887             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2888                             SSL_EARLY_DATA_ACCEPTED))
2889         goto end;
2890
2891     /*
2892      * Server should be able to write data, and client should be able to
2893      * read it.
2894      */
2895     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
2896                                         &written))
2897             || !TEST_size_t_eq(written, strlen(MSG2))
2898             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2899             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2900         goto end;
2901
2902     /* Even after reading normal data, client should be able write early data */
2903     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
2904                                         &written))
2905             || !TEST_size_t_eq(written, strlen(MSG3)))
2906         goto end;
2907
2908     /* Server should still be able read early data after writing data */
2909     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2910                                          &readbytes),
2911                      SSL_READ_EARLY_DATA_SUCCESS)
2912             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
2913         goto end;
2914
2915     /* Write more data from server and read it from client */
2916     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
2917                                         &written))
2918             || !TEST_size_t_eq(written, strlen(MSG4))
2919             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2920             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
2921         goto end;
2922
2923     /*
2924      * If client writes normal data it should mean writing early data is no
2925      * longer possible.
2926      */
2927     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
2928             || !TEST_size_t_eq(written, strlen(MSG5))
2929             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2930                             SSL_EARLY_DATA_ACCEPTED))
2931         goto end;
2932
2933     /*
2934      * At this point the client has written EndOfEarlyData, ClientFinished and
2935      * normal (fully protected) data. We are going to cause a delay between the
2936      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
2937      * in the read BIO, and then just put back the EndOfEarlyData message.
2938      */
2939     rbio = SSL_get_rbio(serverssl);
2940     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
2941             || !TEST_size_t_lt(rawread, sizeof(data))
2942             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
2943         goto end;
2944
2945     /* Record length is in the 4th and 5th bytes of the record header */
2946     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
2947     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
2948             || !TEST_size_t_eq(rawwritten, eoedlen))
2949         goto end;
2950
2951     /* Server should be told that there is no more early data */
2952     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2953                                          &readbytes),
2954                      SSL_READ_EARLY_DATA_FINISH)
2955             || !TEST_size_t_eq(readbytes, 0))
2956         goto end;
2957
2958     /*
2959      * Server has not finished init yet, so should still be able to write early
2960      * data.
2961      */
2962     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
2963                                         &written))
2964             || !TEST_size_t_eq(written, strlen(MSG6)))
2965         goto end;
2966
2967     /* Push the ClientFinished and the normal data back into the server rbio */
2968     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
2969                                 &rawwritten))
2970             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
2971         goto end;
2972
2973     /* Server should be able to read normal data */
2974     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2975             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
2976         goto end;
2977
2978     /* Client and server should not be able to write/read early data now */
2979     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
2980                                          &written)))
2981         goto end;
2982     ERR_clear_error();
2983     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2984                                          &readbytes),
2985                      SSL_READ_EARLY_DATA_ERROR))
2986         goto end;
2987     ERR_clear_error();
2988
2989     /* Client should be able to read the data sent by the server */
2990     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2991             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
2992         goto end;
2993
2994     /*
2995      * Make sure we process the two NewSessionTickets. These arrive
2996      * post-handshake. We attempt reads which we do not expect to return any
2997      * data.
2998      */
2999     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3000             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
3001                            &readbytes)))
3002         goto end;
3003
3004     /* Server should be able to write normal data */
3005     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
3006             || !TEST_size_t_eq(written, strlen(MSG7))
3007             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3008             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
3009         goto end;
3010
3011     SSL_SESSION_free(sess);
3012     sess = SSL_get1_session(clientssl);
3013     use_session_cb_cnt = 0;
3014     find_session_cb_cnt = 0;
3015
3016     SSL_shutdown(clientssl);
3017     SSL_shutdown(serverssl);
3018     SSL_free(serverssl);
3019     SSL_free(clientssl);
3020     serverssl = clientssl = NULL;
3021     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3022                                       &clientssl, NULL, NULL))
3023             || !TEST_true(SSL_set_session(clientssl, sess)))
3024         goto end;
3025
3026     /* Write and read some early data */
3027     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3028                                         &written))
3029             || !TEST_size_t_eq(written, strlen(MSG1))
3030             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3031                                                 &readbytes),
3032                             SSL_READ_EARLY_DATA_SUCCESS)
3033             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3034         goto end;
3035
3036     if (!TEST_int_gt(SSL_connect(clientssl), 0)
3037             || !TEST_int_gt(SSL_accept(serverssl), 0))
3038         goto end;
3039
3040     /* Client and server should not be able to write/read early data now */
3041     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
3042                                          &written)))
3043         goto end;
3044     ERR_clear_error();
3045     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3046                                          &readbytes),
3047                      SSL_READ_EARLY_DATA_ERROR))
3048         goto end;
3049     ERR_clear_error();
3050
3051     /* Client and server should be able to write/read normal data */
3052     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
3053             || !TEST_size_t_eq(written, strlen(MSG5))
3054             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3055             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
3056         goto end;
3057
3058     testresult = 1;
3059
3060  end:
3061     SSL_SESSION_free(sess);
3062     SSL_SESSION_free(clientpsk);
3063     SSL_SESSION_free(serverpsk);
3064     clientpsk = serverpsk = NULL;
3065     SSL_free(serverssl);
3066     SSL_free(clientssl);
3067     SSL_CTX_free(sctx);
3068     SSL_CTX_free(cctx);
3069     return testresult;
3070 }
3071
3072 static int allow_ed_cb_called = 0;
3073
3074 static int allow_early_data_cb(SSL *s, void *arg)
3075 {
3076     int *usecb = (int *)arg;
3077
3078     allow_ed_cb_called++;
3079
3080     if (*usecb == 1)
3081         return 0;
3082
3083     return 1;
3084 }
3085
3086 /*
3087  * idx == 0: Standard early_data setup
3088  * idx == 1: early_data setup using read_ahead
3089  * usecb == 0: Don't use a custom early data callback
3090  * usecb == 1: Use a custom early data callback and reject the early data
3091  * usecb == 2: Use a custom early data callback and accept the early data
3092  * confopt == 0: Configure anti-replay directly
3093  * confopt == 1: Configure anti-replay using SSL_CONF
3094  */
3095 static int test_early_data_replay_int(int idx, int usecb, int confopt)
3096 {
3097     SSL_CTX *cctx = NULL, *sctx = NULL;
3098     SSL *clientssl = NULL, *serverssl = NULL;
3099     int testresult = 0;
3100     SSL_SESSION *sess = NULL;
3101     size_t readbytes, written;
3102     unsigned char buf[20];
3103
3104     allow_ed_cb_called = 0;
3105
3106     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3107                                        TLS_client_method(), TLS1_VERSION, 0,
3108                                        &sctx, &cctx, cert, privkey)))
3109         return 0;
3110
3111     if (usecb > 0) {
3112         if (confopt == 0) {
3113             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
3114         } else {
3115             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
3116
3117             if (!TEST_ptr(confctx))
3118                 goto end;
3119             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
3120                                             | SSL_CONF_FLAG_SERVER);
3121             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
3122             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
3123                              2)) {
3124                 SSL_CONF_CTX_free(confctx);
3125                 goto end;
3126             }
3127             SSL_CONF_CTX_free(confctx);
3128         }
3129         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
3130     }
3131
3132     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3133                                         &serverssl, &sess, idx)))
3134         goto end;
3135
3136     /*
3137      * The server is configured to accept early data. Create a connection to
3138      * "use up" the ticket
3139      */
3140     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3141             || !TEST_true(SSL_session_reused(clientssl)))
3142         goto end;
3143
3144     SSL_shutdown(clientssl);
3145     SSL_shutdown(serverssl);
3146     SSL_free(serverssl);
3147     SSL_free(clientssl);
3148     serverssl = clientssl = NULL;
3149
3150     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3151                                       &clientssl, NULL, NULL))
3152             || !TEST_true(SSL_set_session(clientssl, sess)))
3153         goto end;
3154
3155     /* Write and read some early data */
3156     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3157                                         &written))
3158             || !TEST_size_t_eq(written, strlen(MSG1)))
3159         goto end;
3160
3161     if (usecb <= 1) {
3162         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3163                                              &readbytes),
3164                          SSL_READ_EARLY_DATA_FINISH)
3165                    /*
3166                     * The ticket was reused, so the we should have rejected the
3167                     * early data
3168                     */
3169                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3170                                 SSL_EARLY_DATA_REJECTED))
3171             goto end;
3172     } else {
3173         /* In this case the callback decides to accept the early data */
3174         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3175                                              &readbytes),
3176                          SSL_READ_EARLY_DATA_SUCCESS)
3177                 || !TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
3178                    /*
3179                     * Server will have sent its flight so client can now send
3180                     * end of early data and complete its half of the handshake
3181                     */
3182                 || !TEST_int_gt(SSL_connect(clientssl), 0)
3183                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3184                                              &readbytes),
3185                                 SSL_READ_EARLY_DATA_FINISH)
3186                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3187                                 SSL_EARLY_DATA_ACCEPTED))
3188             goto end;
3189     }
3190
3191     /* Complete the connection */
3192     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3193             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
3194             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
3195         goto end;
3196
3197     testresult = 1;
3198
3199  end:
3200     SSL_SESSION_free(sess);
3201     SSL_SESSION_free(clientpsk);
3202     SSL_SESSION_free(serverpsk);
3203     clientpsk = serverpsk = NULL;
3204     SSL_free(serverssl);
3205     SSL_free(clientssl);
3206     SSL_CTX_free(sctx);
3207     SSL_CTX_free(cctx);
3208     return testresult;
3209 }
3210
3211 static int test_early_data_replay(int idx)
3212 {
3213     int ret = 1, usecb, confopt;
3214
3215     for (usecb = 0; usecb < 3; usecb++) {
3216         for (confopt = 0; confopt < 2; confopt++)
3217             ret &= test_early_data_replay_int(idx, usecb, confopt);
3218     }
3219
3220     return ret;
3221 }
3222
3223 /*
3224  * Helper function to test that a server attempting to read early data can
3225  * handle a connection from a client where the early data should be skipped.
3226  * testtype: 0 == No HRR
3227  * testtype: 1 == HRR
3228  * testtype: 2 == HRR, invalid early_data sent after HRR
3229  * testtype: 3 == recv_max_early_data set to 0
3230  */
3231 static int early_data_skip_helper(int testtype, int idx)
3232 {
3233     SSL_CTX *cctx = NULL, *sctx = NULL;
3234     SSL *clientssl = NULL, *serverssl = NULL;
3235     int testresult = 0;
3236     SSL_SESSION *sess = NULL;
3237     unsigned char buf[20];
3238     size_t readbytes, written;
3239
3240     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3241                                         &serverssl, &sess, idx)))
3242         goto end;
3243
3244     if (testtype == 1 || testtype == 2) {
3245         /* Force an HRR to occur */
3246 #if defined(OPENSSL_NO_EC)
3247         if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
3248             goto end;
3249 #else
3250         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
3251             goto end;
3252 #endif
3253     } else if (idx == 2) {
3254         /*
3255          * We force early_data rejection by ensuring the PSK identity is
3256          * unrecognised
3257          */
3258         srvid = "Dummy Identity";
3259     } else {
3260         /*
3261          * Deliberately corrupt the creation time. We take 20 seconds off the
3262          * time. It could be any value as long as it is not within tolerance.
3263          * This should mean the ticket is rejected.
3264          */
3265         if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
3266             goto end;
3267     }
3268
3269     if (testtype == 3
3270             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
3271         goto end;
3272
3273     /* Write some early data */
3274     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3275                                         &written))
3276             || !TEST_size_t_eq(written, strlen(MSG1)))
3277         goto end;
3278
3279     /* Server should reject the early data */
3280     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3281                                          &readbytes),
3282                      SSL_READ_EARLY_DATA_FINISH)
3283             || !TEST_size_t_eq(readbytes, 0)
3284             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3285                             SSL_EARLY_DATA_REJECTED))
3286         goto end;
3287
3288     switch (testtype) {
3289     case 0:
3290         /* Nothing to do */
3291         break;
3292
3293     case 1:
3294         /*
3295          * Finish off the handshake. We perform the same writes and reads as
3296          * further down but we expect them to fail due to the incomplete
3297          * handshake.
3298          */
3299         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3300                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
3301                                &readbytes)))
3302             goto end;
3303         break;
3304
3305     case 2:
3306         {
3307             BIO *wbio = SSL_get_wbio(clientssl);
3308             /* A record that will appear as bad early_data */
3309             const unsigned char bad_early_data[] = {
3310                 0x17, 0x03, 0x03, 0x00, 0x01, 0x00
3311             };
3312
3313             /*
3314              * We force the client to attempt a write. This will fail because
3315              * we're still in the handshake. It will cause the second
3316              * ClientHello to be sent.
3317              */
3318             if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2),
3319                                          &written)))
3320                 goto end;
3321
3322             /*
3323              * Inject some early_data after the second ClientHello. This should
3324              * cause the server to fail
3325              */
3326             if (!TEST_true(BIO_write_ex(wbio, bad_early_data,
3327                                         sizeof(bad_early_data), &written)))
3328                 goto end;
3329         }
3330         /* fallthrough */
3331
3332     case 3:
3333         /*
3334          * This client has sent more early_data than we are willing to skip
3335          * (case 3) or sent invalid early_data (case 2) so the connection should
3336          * abort.
3337          */
3338         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3339                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
3340             goto end;
3341
3342         /* Connection has failed - nothing more to do */
3343         testresult = 1;
3344         goto end;
3345
3346     default:
3347         TEST_error("Invalid test type");
3348         goto end;
3349     }
3350
3351     /*
3352      * Should be able to send normal data despite rejection of early data. The
3353      * early_data should be skipped.
3354      */
3355     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3356             || !TEST_size_t_eq(written, strlen(MSG2))
3357             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3358                             SSL_EARLY_DATA_REJECTED)
3359             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3360             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3361         goto end;
3362
3363     testresult = 1;
3364
3365  end:
3366     SSL_SESSION_free(clientpsk);
3367     SSL_SESSION_free(serverpsk);
3368     clientpsk = serverpsk = NULL;
3369     SSL_SESSION_free(sess);
3370     SSL_free(serverssl);
3371     SSL_free(clientssl);
3372     SSL_CTX_free(sctx);
3373     SSL_CTX_free(cctx);
3374     return testresult;
3375 }
3376
3377 /*
3378  * Test that a server attempting to read early data can handle a connection
3379  * from a client where the early data is not acceptable.
3380  */
3381 static int test_early_data_skip(int idx)
3382 {
3383     return early_data_skip_helper(0, idx);
3384 }
3385
3386 /*
3387  * Test that a server attempting to read early data can handle a connection
3388  * from a client where an HRR occurs.
3389  */
3390 static int test_early_data_skip_hrr(int idx)
3391 {
3392     return early_data_skip_helper(1, idx);
3393 }
3394
3395 /*
3396  * Test that a server attempting to read early data can handle a connection
3397  * from a client where an HRR occurs and correctly fails if early_data is sent
3398  * after the HRR
3399  */
3400 static int test_early_data_skip_hrr_fail(int idx)
3401 {
3402     return early_data_skip_helper(2, idx);
3403 }
3404
3405 /*
3406  * Test that a server attempting to read early data will abort if it tries to
3407  * skip over too much.
3408  */
3409 static int test_early_data_skip_abort(int idx)
3410 {
3411     return early_data_skip_helper(3, idx);
3412 }
3413
3414 /*
3415  * Test that a server attempting to read early data can handle a connection
3416  * from a client that doesn't send any.
3417  */
3418 static int test_early_data_not_sent(int idx)
3419 {
3420     SSL_CTX *cctx = NULL, *sctx = NULL;
3421     SSL *clientssl = NULL, *serverssl = NULL;
3422     int testresult = 0;
3423     SSL_SESSION *sess = NULL;
3424     unsigned char buf[20];
3425     size_t readbytes, written;
3426
3427     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3428                                         &serverssl, &sess, idx)))
3429         goto end;
3430
3431     /* Write some data - should block due to handshake with server */
3432     SSL_set_connect_state(clientssl);
3433     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
3434         goto end;
3435
3436     /* Server should detect that early data has not been sent */
3437     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3438                                          &readbytes),
3439                      SSL_READ_EARLY_DATA_FINISH)
3440             || !TEST_size_t_eq(readbytes, 0)
3441             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3442                             SSL_EARLY_DATA_NOT_SENT)
3443             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3444                             SSL_EARLY_DATA_NOT_SENT))
3445         goto end;
3446
3447     /* Continue writing the message we started earlier */
3448     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3449             || !TEST_size_t_eq(written, strlen(MSG1))
3450             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3451             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
3452             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
3453             || !TEST_size_t_eq(written, strlen(MSG2)))
3454         goto end;
3455
3456     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
3457             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3458         goto end;
3459
3460     testresult = 1;
3461
3462  end:
3463     SSL_SESSION_free(sess);
3464     SSL_SESSION_free(clientpsk);
3465     SSL_SESSION_free(serverpsk);
3466     clientpsk = serverpsk = NULL;
3467     SSL_free(serverssl);
3468     SSL_free(clientssl);
3469     SSL_CTX_free(sctx);
3470     SSL_CTX_free(cctx);
3471     return testresult;
3472 }
3473
3474 static const char *servalpn;
3475
3476 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
3477                           unsigned char *outlen, const unsigned char *in,
3478                           unsigned int inlen, void *arg)
3479 {
3480     unsigned int protlen = 0;
3481     const unsigned char *prot;
3482
3483     for (prot = in; prot < in + inlen; prot += protlen) {
3484         protlen = *prot++;
3485         if (in + inlen < prot + protlen)
3486             return SSL_TLSEXT_ERR_NOACK;
3487
3488         if (protlen == strlen(servalpn)
3489                 && memcmp(prot, servalpn, protlen) == 0) {
3490             *out = prot;
3491             *outlen = protlen;
3492             return SSL_TLSEXT_ERR_OK;
3493         }
3494     }
3495
3496     return SSL_TLSEXT_ERR_NOACK;
3497 }
3498
3499 /* Test that a PSK can be used to send early_data */
3500 static int test_early_data_psk(int idx)
3501 {
3502     SSL_CTX *cctx = NULL, *sctx = NULL;
3503     SSL *clientssl = NULL, *serverssl = NULL;
3504     int testresult = 0;
3505     SSL_SESSION *sess = NULL;
3506     unsigned char alpnlist[] = {
3507         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
3508         'l', 'p', 'n'
3509     };
3510 #define GOODALPNLEN     9
3511 #define BADALPNLEN      8
3512 #define GOODALPN        (alpnlist)
3513 #define BADALPN         (alpnlist + GOODALPNLEN)
3514     int err = 0;
3515     unsigned char buf[20];
3516     size_t readbytes, written;
3517     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
3518     int edstatus = SSL_EARLY_DATA_ACCEPTED;
3519
3520     /* We always set this up with a final parameter of "2" for PSK */
3521     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3522                                         &serverssl, &sess, 2)))
3523         goto end;
3524
3525     servalpn = "goodalpn";
3526
3527     /*
3528      * Note: There is no test for inconsistent SNI with late client detection.
3529      * This is because servers do not acknowledge SNI even if they are using
3530      * it in a resumption handshake - so it is not actually possible for a
3531      * client to detect a problem.
3532      */
3533     switch (idx) {
3534     case 0:
3535         /* Set inconsistent SNI (early client detection) */
3536         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
3537         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
3538                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
3539             goto end;
3540         break;
3541
3542     case 1:
3543         /* Set inconsistent ALPN (early client detection) */
3544         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
3545         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
3546         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
3547                                                       GOODALPNLEN))
3548                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
3549                                                    BADALPNLEN)))
3550             goto end;
3551         break;
3552
3553     case 2:
3554         /*
3555          * Set invalid protocol version. Technically this affects PSKs without
3556          * early_data too, but we test it here because it is similar to the
3557          * SNI/ALPN consistency tests.
3558          */
3559         err = SSL_R_BAD_PSK;
3560         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
3561             goto end;
3562         break;
3563
3564     case 3:
3565         /*
3566          * Set inconsistent SNI (server side). In this case the connection
3567          * will succeed and accept early_data. In TLSv1.3 on the server side SNI
3568          * is associated with each handshake - not the session. Therefore it
3569          * should not matter that we used a different server name last time.
3570          */
3571         SSL_SESSION_free(serverpsk);
3572         serverpsk = SSL_SESSION_dup(clientpsk);
3573         if (!TEST_ptr(serverpsk)
3574                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
3575             goto end;
3576         /* Fall through */
3577     case 4:
3578         /* Set consistent SNI */
3579         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
3580                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
3581                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
3582                                 hostname_cb)))
3583             goto end;
3584         break;
3585
3586     case 5:
3587         /*
3588          * Set inconsistent ALPN (server detected). In this case the connection
3589          * will succeed but reject early_data.
3590          */
3591         servalpn = "badalpn";
3592         edstatus = SSL_EARLY_DATA_REJECTED;
3593         readearlyres = SSL_READ_EARLY_DATA_FINISH;
3594         /* Fall through */
3595     case 6:
3596         /*
3597          * Set consistent ALPN.
3598          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
3599          * accepts a list of protos (each one length prefixed).
3600          * SSL_set1_alpn_selected accepts a single protocol (not length
3601          * prefixed)
3602          */
3603         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
3604                                                       GOODALPNLEN - 1))
3605                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
3606                                                    GOODALPNLEN)))
3607             goto end;
3608
3609         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3610         break;
3611
3612     case 7:
3613         /* Set inconsistent ALPN (late client detection) */
3614         SSL_SESSION_free(serverpsk);
3615         serverpsk = SSL_SESSION_dup(clientpsk);
3616         if (!TEST_ptr(serverpsk)
3617                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
3618                                                              BADALPN + 1,
3619                                                              BADALPNLEN - 1))
3620                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
3621                                                              GOODALPN + 1,
3622                                                              GOODALPNLEN - 1))
3623                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
3624                                                    sizeof(alpnlist))))
3625             goto end;
3626         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
3627         edstatus = SSL_EARLY_DATA_ACCEPTED;
3628         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
3629         /* SSL_connect() call should fail */
3630         connectres = -1;
3631         break;
3632
3633     default:
3634         TEST_error("Bad test index");
3635         goto end;
3636     }
3637
3638     SSL_set_connect_state(clientssl);
3639     if (err != 0) {
3640         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3641                                             &written))
3642                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
3643                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
3644             goto end;
3645     } else {
3646         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3647                                             &written)))
3648             goto end;
3649
3650         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3651                                              &readbytes), readearlyres)
3652                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
3653                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
3654                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
3655                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
3656             goto end;
3657     }
3658
3659     testresult = 1;
3660
3661  end:
3662     SSL_SESSION_free(sess);
3663     SSL_SESSION_free(clientpsk);
3664     SSL_SESSION_free(serverpsk);
3665     clientpsk = serverpsk = NULL;
3666     SSL_free(serverssl);
3667     SSL_free(clientssl);
3668     SSL_CTX_free(sctx);
3669     SSL_CTX_free(cctx);
3670     return testresult;
3671 }
3672
3673 /*
3674  * Test that a server that doesn't try to read early data can handle a
3675  * client sending some.
3676  */
3677 static int test_early_data_not_expected(int idx)
3678 {
3679     SSL_CTX *cctx = NULL, *sctx = NULL;
3680     SSL *clientssl = NULL, *serverssl = NULL;
3681     int testresult = 0;
3682     SSL_SESSION *sess = NULL;
3683     unsigned char buf[20];
3684     size_t readbytes, written;
3685
3686     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3687                                         &serverssl, &sess, idx)))
3688         goto end;
3689
3690     /* Write some early data */
3691     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
3692                                         &written)))
3693         goto end;
3694
3695     /*
3696      * Server should skip over early data and then block waiting for client to
3697      * continue handshake
3698      */
3699     if (!TEST_int_le(SSL_accept(serverssl), 0)
3700      || !TEST_int_gt(SSL_connect(clientssl), 0)
3701      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3702                      SSL_EARLY_DATA_REJECTED)
3703      || !TEST_int_gt(SSL_accept(serverssl), 0)
3704      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3705                      SSL_EARLY_DATA_REJECTED))
3706         goto end;
3707
3708     /* Send some normal data from client to server */
3709     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
3710             || !TEST_size_t_eq(written, strlen(MSG2)))
3711         goto end;
3712
3713     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3714             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3715         goto end;
3716
3717     testresult = 1;
3718
3719  end:
3720     SSL_SESSION_free(sess);
3721     SSL_SESSION_free(clientpsk);
3722     SSL_SESSION_free(serverpsk);
3723     clientpsk = serverpsk = NULL;
3724     SSL_free(serverssl);
3725     SSL_free(clientssl);
3726     SSL_CTX_free(sctx);
3727     SSL_CTX_free(cctx);
3728     return testresult;
3729 }
3730
3731
3732 # ifndef OPENSSL_NO_TLS1_2
3733 /*
3734  * Test that a server attempting to read early data can handle a connection
3735  * from a TLSv1.2 client.
3736  */
3737 static int test_early_data_tls1_2(int idx)
3738 {
3739     SSL_CTX *cctx = NULL, *sctx = NULL;
3740     SSL *clientssl = NULL, *serverssl = NULL;
3741     int testresult = 0;
3742     unsigned char buf[20];
3743     size_t readbytes, written;
3744
3745     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
3746                                         &serverssl, NULL, idx)))
3747         goto end;
3748
3749     /* Write some data - should block due to handshake with server */
3750     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
3751     SSL_set_connect_state(clientssl);
3752     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
3753         goto end;
3754
3755     /*
3756      * Server should do TLSv1.2 handshake. First it will block waiting for more
3757      * messages from client after ServerDone. Then SSL_read_early_data should
3758      * finish and detect that early data has not been sent
3759      */
3760     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3761                                          &readbytes),
3762                      SSL_READ_EARLY_DATA_ERROR))
3763         goto end;
3764
3765     /*
3766      * Continue writing the message we started earlier. Will still block waiting
3767      * for the CCS/Finished from server
3768      */
3769     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3770             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3771                                                 &readbytes),
3772                             SSL_READ_EARLY_DATA_FINISH)
3773             || !TEST_size_t_eq(readbytes, 0)
3774             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3775                             SSL_EARLY_DATA_NOT_SENT))
3776         goto end;
3777
3778     /* Continue writing the message we started earlier */
3779     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
3780             || !TEST_size_t_eq(written, strlen(MSG1))
3781             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
3782                             SSL_EARLY_DATA_NOT_SENT)
3783             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
3784             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
3785             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
3786             || !TEST_size_t_eq(written, strlen(MSG2))
3787             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
3788             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
3789         goto end;
3790
3791     testresult = 1;
3792
3793  end:
3794     SSL_SESSION_free(clientpsk);
3795     SSL_SESSION_free(serverpsk);
3796     clientpsk = serverpsk = NULL;
3797     SSL_free(serverssl);
3798     SSL_free(clientssl);
3799     SSL_CTX_free(sctx);
3800     SSL_CTX_free(cctx);
3801
3802     return testresult;
3803 }
3804 # endif /* OPENSSL_NO_TLS1_2 */
3805
3806 /*
3807  * Test configuring the TLSv1.3 ciphersuites
3808  *
3809  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
3810  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
3811  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
3812  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
3813  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
3814  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
3815  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
3816  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
3817  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
3818  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
3819  */
3820 static int test_set_ciphersuite(int idx)
3821 {
3822     SSL_CTX *cctx = NULL, *sctx = NULL;
3823     SSL *clientssl = NULL, *serverssl = NULL;
3824     int testresult = 0;
3825
3826     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3827                                        TLS_client_method(), TLS1_VERSION, 0,
3828                                        &sctx, &cctx, cert, privkey))
3829             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3830                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
3831         goto end;
3832
3833     if (idx >=4 && idx <= 7) {
3834         /* SSL_CTX explicit cipher list */
3835         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
3836             goto end;
3837     }
3838
3839     if (idx == 0 || idx == 4) {
3840         /* Default ciphersuite */
3841         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3842                                                 "TLS_AES_128_GCM_SHA256")))
3843             goto end;
3844     } else if (idx == 1 || idx == 5) {
3845         /* Non default ciphersuite */
3846         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3847                                                 "TLS_AES_128_CCM_SHA256")))
3848             goto end;
3849     }
3850
3851     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3852                                           &clientssl, NULL, NULL)))
3853         goto end;
3854
3855     if (idx == 8 || idx == 9) {
3856         /* SSL explicit cipher list */
3857         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
3858             goto end;
3859     }
3860
3861     if (idx == 2 || idx == 6 || idx == 8) {
3862         /* Default ciphersuite */
3863         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3864                                             "TLS_AES_128_GCM_SHA256")))
3865             goto end;
3866     } else if (idx == 3 || idx == 7 || idx == 9) {
3867         /* Non default ciphersuite */
3868         if (!TEST_true(SSL_set_ciphersuites(clientssl,
3869                                             "TLS_AES_128_CCM_SHA256")))
3870             goto end;
3871     }
3872
3873     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
3874         goto end;
3875
3876     testresult = 1;
3877
3878  end:
3879     SSL_free(serverssl);
3880     SSL_free(clientssl);
3881     SSL_CTX_free(sctx);
3882     SSL_CTX_free(cctx);
3883
3884     return testresult;
3885 }
3886
3887 static int test_ciphersuite_change(void)
3888 {
3889     SSL_CTX *cctx = NULL, *sctx = NULL;
3890     SSL *clientssl = NULL, *serverssl = NULL;
3891     SSL_SESSION *clntsess = NULL;
3892     int testresult = 0;
3893     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
3894
3895     /* Create a session based on SHA-256 */
3896     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
3897                                        TLS_client_method(), TLS1_VERSION, 0,
3898                                        &sctx, &cctx, cert, privkey))
3899             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3900                                                    "TLS_AES_128_GCM_SHA256:"
3901                                                    "TLS_AES_256_GCM_SHA384:"
3902                                                    "TLS_AES_128_CCM_SHA256"))
3903             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
3904                                                    "TLS_AES_128_GCM_SHA256"))
3905             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3906                                           &clientssl, NULL, NULL))
3907             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3908                                                 SSL_ERROR_NONE)))
3909         goto end;
3910
3911     clntsess = SSL_get1_session(clientssl);
3912     /* Save for later */
3913     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
3914     SSL_shutdown(clientssl);
3915     SSL_shutdown(serverssl);
3916     SSL_free(serverssl);
3917     SSL_free(clientssl);
3918     serverssl = clientssl = NULL;
3919
3920     /* Check we can resume a session with a different SHA-256 ciphersuite */
3921     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3922                                             "TLS_AES_128_CCM_SHA256"))
3923             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3924                                              &clientssl, NULL, NULL))
3925             || !TEST_true(SSL_set_session(clientssl, clntsess))
3926             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3927                                                 SSL_ERROR_NONE))
3928             || !TEST_true(SSL_session_reused(clientssl)))
3929         goto end;
3930
3931     SSL_SESSION_free(clntsess);
3932     clntsess = SSL_get1_session(clientssl);
3933     SSL_shutdown(clientssl);
3934     SSL_shutdown(serverssl);
3935     SSL_free(serverssl);
3936     SSL_free(clientssl);
3937     serverssl = clientssl = NULL;
3938
3939     /*
3940      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
3941      * succeeds but does not resume.
3942      */
3943     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3944             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3945                                              NULL, NULL))
3946             || !TEST_true(SSL_set_session(clientssl, clntsess))
3947             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3948                                                 SSL_ERROR_SSL))
3949             || !TEST_false(SSL_session_reused(clientssl)))
3950         goto end;
3951
3952     SSL_SESSION_free(clntsess);
3953     clntsess = NULL;
3954     SSL_shutdown(clientssl);
3955     SSL_shutdown(serverssl);
3956     SSL_free(serverssl);
3957     SSL_free(clientssl);
3958     serverssl = clientssl = NULL;
3959
3960     /* Create a session based on SHA384 */
3961     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3962             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3963                                           &clientssl, NULL, NULL))
3964             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3965                                                 SSL_ERROR_NONE)))
3966         goto end;
3967
3968     clntsess = SSL_get1_session(clientssl);
3969     SSL_shutdown(clientssl);
3970     SSL_shutdown(serverssl);
3971     SSL_free(serverssl);
3972     SSL_free(clientssl);
3973     serverssl = clientssl = NULL;
3974
3975     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3976                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
3977             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3978                                                    "TLS_AES_256_GCM_SHA384"))
3979             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3980                                              NULL, NULL))
3981             || !TEST_true(SSL_set_session(clientssl, clntsess))
3982                /*
3983                 * We use SSL_ERROR_WANT_READ below so that we can pause the
3984                 * connection after the initial ClientHello has been sent to
3985                 * enable us to make some session changes.
3986                 */
3987             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3988                                                 SSL_ERROR_WANT_READ)))
3989         goto end;
3990
3991     /* Trick the client into thinking this session is for a different digest */
3992     clntsess->cipher = aes_128_gcm_sha256;
3993     clntsess->cipher_id = clntsess->cipher->id;
3994
3995     /*
3996      * Continue the previously started connection. Server has selected a SHA-384
3997      * ciphersuite, but client thinks the session is for SHA-256, so it should
3998      * bail out.
3999      */
4000     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
4001                                                 SSL_ERROR_SSL))
4002             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
4003                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
4004         goto end;
4005
4006     testresult = 1;
4007
4008  end:
4009     SSL_SESSION_free(clntsess);
4010     SSL_free(serverssl);
4011     SSL_free(clientssl);
4012     SSL_CTX_free(sctx);
4013     SSL_CTX_free(cctx);
4014
4015     return testresult;
4016 }
4017
4018 /*
4019  * Test TLSv1.3 Key exchange
4020  * Test 0 = Test all ECDHE Key exchange with TLSv1.3 client and server
4021  * Test 1 = Test NID_X9_62_prime256v1 with TLSv1.3 client and server
4022  * Test 2 = Test NID_secp384r1 with TLSv1.3 client and server
4023  * Test 3 = Test NID_secp521r1 with TLSv1.3 client and server
4024  * Test 4 = Test NID_X25519 with TLSv1.3 client and server
4025  * Test 5 = Test NID_X448 with TLSv1.3 client and server
4026  * Test 6 = Test all FFDHE Key exchange with TLSv1.3 client and server
4027  * Test 7 = Test NID_ffdhe2048 with TLSv1.3 client and server
4028  * Test 8 = Test NID_ffdhe3072 with TLSv1.3 client and server
4029  * Test 9 = Test NID_ffdhe4096 with TLSv1.3 client and server
4030  * Test 10 = Test NID_ffdhe6144 with TLSv1.3 client and server
4031  * Test 11 = Test NID_ffdhe8192 with TLSv1.3 client and server
4032  * Test 12 = Test all ECDHE with TLSv1.2 client and server
4033  * Test 13 = Test all FFDHE with TLSv1.2 client and server
4034  */
4035 static int test_key_exchange(int idx)
4036 {
4037     SSL_CTX *sctx = NULL, *cctx = NULL;
4038     SSL *serverssl = NULL, *clientssl = NULL;
4039     int testresult = 0;
4040 # ifndef OPENSSL_NO_EC
4041     int ecdhe_kexch_groups[] = {NID_X9_62_prime256v1, NID_secp384r1,
4042                                 NID_secp521r1, NID_X25519, NID_X448};
4043 # endif
4044 # ifndef OPENSSL_NO_DH
4045     int ffdhe_kexch_groups[] = {NID_ffdhe2048, NID_ffdhe3072, NID_ffdhe4096,
4046                                 NID_ffdhe6144, NID_ffdhe8192};
4047 # endif
4048     int kexch_alg;
4049     int *kexch_groups = &kexch_alg;
4050     int kexch_groups_size = 1;
4051     int max_version = TLS1_3_VERSION;
4052
4053     switch (idx) {
4054 # ifndef OPENSSL_NO_EC
4055 # ifndef OPENSSL_NO_TLS1_2
4056         case 12:
4057             max_version = TLS1_2_VERSION;
4058 # endif
4059             /* Fall through */
4060         case 0:
4061             kexch_groups = ecdhe_kexch_groups;
4062             kexch_groups_size = OSSL_NELEM(ecdhe_kexch_groups);
4063             break;
4064         case 1:
4065             kexch_alg = NID_X9_62_prime256v1;
4066             break;
4067         case 2:
4068             kexch_alg = NID_secp384r1;
4069             break;
4070         case 3:
4071             kexch_alg = NID_secp521r1;
4072             break;
4073         case 4:
4074             kexch_alg = NID_X25519;
4075             break;
4076         case 5:
4077             kexch_alg = NID_X448;
4078             break;
4079 # endif
4080 # ifndef OPENSSL_NO_DH
4081 # ifndef OPENSSL_NO_TLS1_2
4082         case 13:
4083             max_version = TLS1_2_VERSION;
4084 # endif
4085             /* Fall through */
4086         case 6:
4087             kexch_groups = ffdhe_kexch_groups;
4088             kexch_groups_size = OSSL_NELEM(ffdhe_kexch_groups);
4089             break;
4090         case 7:
4091             kexch_alg = NID_ffdhe2048;
4092             break;
4093         case 8:
4094             kexch_alg = NID_ffdhe3072;
4095             break;
4096         case 9:
4097             kexch_alg = NID_ffdhe4096;
4098             break;
4099         case 10:
4100             kexch_alg = NID_ffdhe6144;
4101             break;
4102         case 11:
4103             kexch_alg = NID_ffdhe8192;
4104             break;
4105 # endif
4106         default:
4107             /* We're skipping this test */
4108             return 1;
4109     }
4110
4111     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4112                                        TLS_client_method(), TLS1_VERSION,
4113                                        max_version, &sctx, &cctx, cert,
4114                                        privkey)))
4115         goto end;
4116
4117     if (!TEST_true(SSL_CTX_set_ciphersuites(sctx,
4118                    TLS1_3_RFC_AES_128_GCM_SHA256)))
4119         goto end;
4120
4121     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4122                    TLS1_3_RFC_AES_128_GCM_SHA256)))
4123         goto end;
4124
4125     if (!TEST_true(SSL_CTX_set_cipher_list(sctx,
4126                    TLS1_TXT_RSA_WITH_AES_128_SHA)))
4127         goto end;
4128
4129     /*
4130      * Must include an EC ciphersuite so that we send supported groups in
4131      * TLSv1.2
4132      */
4133 # ifndef OPENSSL_NO_TLS1_2
4134     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
4135                    TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM ":"
4136                    TLS1_TXT_RSA_WITH_AES_128_SHA)))
4137         goto end;
4138 # endif
4139
4140     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4141                                              NULL, NULL)))
4142         goto end;
4143
4144     if (!TEST_true(SSL_set1_groups(serverssl, kexch_groups, kexch_groups_size))
4145         || !TEST_true(SSL_set1_groups(clientssl, kexch_groups, kexch_groups_size)))
4146         goto end;
4147
4148     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
4149         goto end;
4150
4151     /*
4152      * If Handshake succeeds the negotiated kexch alg should be the first one in
4153      * configured, except in the case of FFDHE groups (idx 13), which are
4154      * TLSv1.3 only so we expect no shared group to exist.
4155      */
4156     if (!TEST_int_eq(SSL_get_shared_group(serverssl, 0),
4157                      idx == 13 ? 0 : kexch_groups[0]))
4158         goto end;
4159     if (max_version == TLS1_3_VERSION) {
4160         if (!TEST_int_eq(SSL_get_negotiated_group(serverssl), kexch_groups[0]))
4161             goto end;
4162         if (!TEST_int_eq(SSL_get_negotiated_group(clientssl), kexch_groups[0]))
4163             goto end;
4164     }
4165
4166     testresult = 1;
4167  end:
4168     SSL_free(serverssl);
4169     SSL_free(clientssl);
4170     SSL_CTX_free(sctx);
4171     SSL_CTX_free(cctx);
4172     return testresult;
4173 }
4174
4175 /*
4176  * Test TLSv1.3 Cipher Suite
4177  * Test 0 = Set TLS1.3 cipher on context
4178  * Test 1 = Set TLS1.3 cipher on SSL
4179  * Test 2 = Set TLS1.3 and TLS1.2 cipher on context
4180  * Test 3 = Set TLS1.3 and TLS1.2 cipher on SSL
4181  */
4182 static int test_tls13_ciphersuite(int idx)
4183 {
4184     SSL_CTX *sctx = NULL, *cctx = NULL;
4185     SSL *serverssl = NULL, *clientssl = NULL;
4186     static const struct {
4187         const char *ciphername;
4188         int fipscapable;
4189     } t13_ciphers[] = {
4190         { TLS1_3_RFC_AES_128_GCM_SHA256, 1 },
4191         { TLS1_3_RFC_AES_256_GCM_SHA384, 1 },
4192         { TLS1_3_RFC_AES_128_CCM_SHA256, 1 },
4193 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4194         { TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
4195         { TLS1_3_RFC_AES_256_GCM_SHA384
4196           ":" TLS1_3_RFC_CHACHA20_POLY1305_SHA256, 0 },
4197 # endif
4198         { TLS1_3_RFC_AES_128_CCM_8_SHA256 ":" TLS1_3_RFC_AES_128_CCM_SHA256, 1 }
4199     };
4200     const char *t13_cipher = NULL;
4201     const char *t12_cipher = NULL;
4202     const char *negotiated_scipher;
4203     const char *negotiated_ccipher;
4204     int set_at_ctx = 0;
4205     int set_at_ssl = 0;
4206     int testresult = 0;
4207     int max_ver;
4208     size_t i;
4209
4210     switch (idx) {
4211         case 0:
4212             set_at_ctx = 1;
4213             break;
4214         case 1:
4215             set_at_ssl = 1;
4216             break;
4217         case 2:
4218             set_at_ctx = 1;
4219             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
4220             break;
4221         case 3:
4222             set_at_ssl = 1;
4223             t12_cipher = TLS1_TXT_RSA_WITH_AES_128_SHA256;
4224             break;
4225     }
4226
4227     for (max_ver = TLS1_2_VERSION; max_ver <= TLS1_3_VERSION; max_ver++) {
4228 # ifdef OPENSSL_NO_TLS1_2
4229         if (max_ver == TLS1_2_VERSION)
4230             continue;
4231 # endif
4232         for (i = 0; i < OSSL_NELEM(t13_ciphers); i++) {
4233             if (is_fips && !t13_ciphers[i].fipscapable)
4234                 continue;
4235             t13_cipher = t13_ciphers[i].ciphername;
4236             if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4237                                                TLS_client_method(),
4238                                                TLS1_VERSION, max_ver,
4239                                                &sctx, &cctx, cert, privkey)))
4240                 goto end;
4241
4242             if (set_at_ctx) {
4243                 if (!TEST_true(SSL_CTX_set_ciphersuites(sctx, t13_cipher))
4244                     || !TEST_true(SSL_CTX_set_ciphersuites(cctx, t13_cipher)))
4245                     goto end;
4246                 if (t12_cipher != NULL) {
4247                     if (!TEST_true(SSL_CTX_set_cipher_list(sctx, t12_cipher))
4248                         || !TEST_true(SSL_CTX_set_cipher_list(cctx,
4249                                                               t12_cipher)))
4250                         goto end;
4251                 }
4252             }
4253
4254             if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4255                                               &clientssl, NULL, NULL)))
4256                 goto end;
4257
4258             if (set_at_ssl) {
4259                 if (!TEST_true(SSL_set_ciphersuites(serverssl, t13_cipher))
4260                     || !TEST_true(SSL_set_ciphersuites(clientssl, t13_cipher)))
4261                     goto end;
4262                 if (t12_cipher != NULL) {
4263                     if (!TEST_true(SSL_set_cipher_list(serverssl, t12_cipher))
4264                         || !TEST_true(SSL_set_cipher_list(clientssl,
4265                                                           t12_cipher)))
4266                         goto end;
4267                 }
4268             }
4269
4270             if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4271                                                  SSL_ERROR_NONE)))
4272                 goto end;
4273
4274             negotiated_scipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
4275                                                                  serverssl));
4276             negotiated_ccipher = SSL_CIPHER_get_name(SSL_get_current_cipher(
4277                                                                  clientssl));
4278             if (!TEST_str_eq(negotiated_scipher, negotiated_ccipher))
4279                 goto end;
4280
4281             /*
4282              * TEST_strn_eq is used below because t13_cipher can contain
4283              * multiple ciphersuites
4284              */
4285             if (max_ver == TLS1_3_VERSION
4286                 && !TEST_strn_eq(t13_cipher, negotiated_scipher,
4287                                  strlen(negotiated_scipher)))
4288                 goto end;
4289
4290 # ifndef OPENSSL_NO_TLS1_2
4291             /* Below validation is not done when t12_cipher is NULL */
4292             if (max_ver == TLS1_2_VERSION && t12_cipher != NULL
4293                 && !TEST_str_eq(t12_cipher, negotiated_scipher))
4294                 goto end;
4295 # endif
4296
4297             SSL_free(serverssl);
4298             serverssl = NULL;
4299             SSL_free(clientssl);
4300             clientssl = NULL;
4301             SSL_CTX_free(sctx);
4302             sctx = NULL;
4303             SSL_CTX_free(cctx);
4304             cctx = NULL;
4305         }
4306     }
4307
4308     testresult = 1;
4309  end:
4310     SSL_free(serverssl);
4311     SSL_free(clientssl);
4312     SSL_CTX_free(sctx);
4313     SSL_CTX_free(cctx);
4314     return testresult;
4315 }
4316
4317 /*
4318  * Test TLSv1.3 PSKs
4319  * Test 0 = Test new style callbacks
4320  * Test 1 = Test both new and old style callbacks
4321  * Test 2 = Test old style callbacks
4322  * Test 3 = Test old style callbacks with no certificate
4323  */
4324 static int test_tls13_psk(int idx)
4325 {
4326     SSL_CTX *sctx = NULL, *cctx = NULL;
4327     SSL *serverssl = NULL, *clientssl = NULL;
4328     const SSL_CIPHER *cipher = NULL;
4329     const unsigned char key[] = {
4330         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
4331         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4332         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
4333         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
4334     };
4335     int testresult = 0;
4336
4337     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4338                                        TLS_client_method(), TLS1_VERSION, 0,
4339                                        &sctx, &cctx, idx == 3 ? NULL : cert,
4340                                        idx == 3 ? NULL : privkey)))
4341         goto end;
4342
4343     if (idx != 3) {
4344         /*
4345          * We use a ciphersuite with SHA256 to ease testing old style PSK
4346          * callbacks which will always default to SHA256. This should not be
4347          * necessary if we have no cert/priv key. In that case the server should
4348          * prefer SHA256 automatically.
4349          */
4350         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4351                                                 "TLS_AES_128_GCM_SHA256")))
4352             goto end;
4353     } else {
4354         /*
4355          * As noted above the server should prefer SHA256 automatically. However
4356          * we are careful not to offer TLS_CHACHA20_POLY1305_SHA256 so this same
4357          * code works even if we are testing with only the FIPS provider loaded.
4358          */
4359         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
4360                                                 "TLS_AES_256_GCM_SHA384:"
4361                                                 "TLS_AES_128_GCM_SHA256")))
4362             goto end;
4363     }
4364
4365     /*
4366      * Test 0: New style callbacks only
4367      * Test 1: New and old style callbacks (only the new ones should be used)
4368      * Test 2: Old style callbacks only
4369      */
4370     if (idx == 0 || idx == 1) {
4371         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
4372         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
4373     }
4374 #ifndef OPENSSL_NO_PSK
4375     if (idx >= 1) {
4376         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
4377         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
4378     }
4379 #endif
4380     srvid = pskid;
4381     use_session_cb_cnt = 0;
4382     find_session_cb_cnt = 0;
4383     psk_client_cb_cnt = 0;
4384     psk_server_cb_cnt = 0;
4385
4386     if (idx != 3) {
4387         /*
4388          * Check we can create a connection if callback decides not to send a
4389          * PSK
4390          */
4391         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4392                                                  NULL, NULL))
4393                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4394                                                     SSL_ERROR_NONE))
4395                 || !TEST_false(SSL_session_reused(clientssl))
4396                 || !TEST_false(SSL_session_reused(serverssl)))
4397             goto end;
4398
4399         if (idx == 0 || idx == 1) {
4400             if (!TEST_true(use_session_cb_cnt == 1)
4401                     || !TEST_true(find_session_cb_cnt == 0)
4402                        /*
4403                         * If no old style callback then below should be 0
4404                         * otherwise 1
4405                         */
4406                     || !TEST_true(psk_client_cb_cnt == idx)
4407                     || !TEST_true(psk_server_cb_cnt == 0))
4408                 goto end;
4409         } else {
4410             if (!TEST_true(use_session_cb_cnt == 0)
4411                     || !TEST_true(find_session_cb_cnt == 0)
4412                     || !TEST_true(psk_client_cb_cnt == 1)
4413                     || !TEST_true(psk_server_cb_cnt == 0))
4414                 goto end;
4415         }
4416
4417         shutdown_ssl_connection(serverssl, clientssl);
4418         serverssl = clientssl = NULL;
4419         use_session_cb_cnt = psk_client_cb_cnt = 0;
4420     }
4421
4422     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4423                                              NULL, NULL)))
4424         goto end;
4425
4426     /* Create the PSK */
4427     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
4428     clientpsk = SSL_SESSION_new();
4429     if (!TEST_ptr(clientpsk)
4430             || !TEST_ptr(cipher)
4431             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
4432                                                       sizeof(key)))
4433             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
4434             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
4435                                                            TLS1_3_VERSION))
4436             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
4437         goto end;
4438     serverpsk = clientpsk;
4439
4440     /* Check we can create a connection and the PSK is used */
4441     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
4442             || !TEST_true(SSL_session_reused(clientssl))
4443             || !TEST_true(SSL_session_reused(serverssl)))
4444         goto end;
4445
4446     if (idx == 0 || idx == 1) {
4447         if (!TEST_true(use_session_cb_cnt == 1)
4448                 || !TEST_true(find_session_cb_cnt == 1)
4449                 || !TEST_true(psk_client_cb_cnt == 0)
4450                 || !TEST_true(psk_server_cb_cnt == 0))
4451             goto end;
4452     } else {
4453         if (!TEST_true(use_session_cb_cnt == 0)
4454                 || !TEST_true(find_session_cb_cnt == 0)
4455                 || !TEST_true(psk_client_cb_cnt == 1)
4456                 || !TEST_true(psk_server_cb_cnt == 1))
4457             goto end;
4458     }
4459
4460     shutdown_ssl_connection(serverssl, clientssl);
4461     serverssl = clientssl = NULL;
4462     use_session_cb_cnt = find_session_cb_cnt = 0;
4463     psk_client_cb_cnt = psk_server_cb_cnt = 0;
4464
4465     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4466                                              NULL, NULL)))
4467         goto end;
4468
4469     /* Force an HRR */
4470 #if defined(OPENSSL_NO_EC)
4471     if (!TEST_true(SSL_set1_groups_list(serverssl, "ffdhe3072")))
4472         goto end;
4473 #else
4474     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
4475         goto end;
4476 #endif
4477
4478     /*
4479      * Check we can create a connection, the PSK is used and the callbacks are
4480      * called twice.
4481      */
4482     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
4483             || !TEST_true(SSL_session_reused(clientssl))
4484             || !TEST_true(SSL_session_reused(serverssl)))
4485         goto end;
4486
4487     if (idx == 0 || idx == 1) {
4488         if (!TEST_true(use_session_cb_cnt == 2)
4489                 || !TEST_true(find_session_cb_cnt == 2)
4490                 || !TEST_true(psk_client_cb_cnt == 0)
4491                 || !TEST_true(psk_server_cb_cnt == 0))
4492             goto end;
4493     } else {
4494         if (!TEST_true(use_session_cb_cnt == 0)
4495                 || !TEST_true(find_session_cb_cnt == 0)
4496                 || !TEST_true(psk_client_cb_cnt == 2)
4497                 || !TEST_true(psk_server_cb_cnt == 2))
4498             goto end;
4499     }
4500
4501     shutdown_ssl_connection(serverssl, clientssl);
4502     serverssl = clientssl = NULL;
4503     use_session_cb_cnt = find_session_cb_cnt = 0;
4504     psk_client_cb_cnt = psk_server_cb_cnt = 0;
4505
4506     if (idx != 3) {
4507         /*
4508          * Check that if the server rejects the PSK we can still connect, but with
4509          * a full handshake
4510          */
4511         srvid = "Dummy Identity";
4512         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4513                                                  NULL, NULL))
4514                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4515                                                     SSL_ERROR_NONE))
4516                 || !TEST_false(SSL_session_reused(clientssl))
4517                 || !TEST_false(SSL_session_reused(serverssl)))
4518             goto end;
4519
4520         if (idx == 0 || idx == 1) {
4521             if (!TEST_true(use_session_cb_cnt == 1)
4522                     || !TEST_true(find_session_cb_cnt == 1)
4523                     || !TEST_true(psk_client_cb_cnt == 0)
4524                        /*
4525                         * If no old style callback then below should be 0
4526                         * otherwise 1
4527                         */
4528                     || !TEST_true(psk_server_cb_cnt == idx))
4529                 goto end;
4530         } else {
4531             if (!TEST_true(use_session_cb_cnt == 0)
4532                     || !TEST_true(find_session_cb_cnt == 0)
4533                     || !TEST_true(psk_client_cb_cnt == 1)
4534                     || !TEST_true(psk_server_cb_cnt == 1))
4535                 goto end;
4536         }
4537
4538         shutdown_ssl_connection(serverssl, clientssl);
4539         serverssl = clientssl = NULL;
4540     }
4541     testresult = 1;
4542
4543  end:
4544     SSL_SESSION_free(clientpsk);
4545     SSL_SESSION_free(serverpsk);
4546     clientpsk = serverpsk = NULL;
4547     SSL_free(serverssl);
4548     SSL_free(clientssl);
4549     SSL_CTX_free(sctx);
4550     SSL_CTX_free(cctx);
4551     return testresult;
4552 }
4553
4554 static unsigned char cookie_magic_value[] = "cookie magic";
4555
4556 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
4557                                     unsigned int *cookie_len)
4558 {
4559     /*
4560      * Not suitable as a real cookie generation function but good enough for
4561      * testing!
4562      */
4563     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
4564     *cookie_len = sizeof(cookie_magic_value) - 1;
4565
4566     return 1;
4567 }
4568
4569 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
4570                                   unsigned int cookie_len)
4571 {
4572     if (cookie_len == sizeof(cookie_magic_value) - 1
4573         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
4574         return 1;
4575
4576     return 0;
4577 }
4578
4579 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
4580                                         size_t *cookie_len)
4581 {
4582     unsigned int temp;
4583     int res = generate_cookie_callback(ssl, cookie, &temp);
4584     *cookie_len = temp;
4585     return res;
4586 }
4587
4588 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
4589                                       size_t cookie_len)
4590 {
4591     return verify_cookie_callback(ssl, cookie, cookie_len);
4592 }
4593
4594 static int test_stateless(void)
4595 {
4596     SSL_CTX *sctx = NULL, *cctx = NULL;
4597     SSL *serverssl = NULL, *clientssl = NULL;
4598     int testresult = 0;
4599
4600     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4601                                        TLS_client_method(), TLS1_VERSION, 0,
4602                                        &sctx, &cctx, cert, privkey)))
4603         goto end;
4604
4605     /* The arrival of CCS messages can confuse the test */
4606     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
4607
4608     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4609                                       NULL, NULL))
4610                /* Send the first ClientHello */
4611             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4612                                                  SSL_ERROR_WANT_READ))
4613                /*
4614                 * This should fail with a -1 return because we have no callbacks
4615                 * set up
4616                 */
4617             || !TEST_int_eq(SSL_stateless(serverssl), -1))
4618         goto end;
4619
4620     /* Fatal error so abandon the connection from this client */
4621     SSL_free(clientssl);
4622     clientssl = NULL;
4623
4624     /* Set up the cookie generation and verification callbacks */
4625     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
4626     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
4627
4628     /*
4629      * Create a new connection from the client (we can reuse the server SSL
4630      * object).
4631      */
4632     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4633                                              NULL, NULL))
4634                /* Send the first ClientHello */
4635             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4636                                                 SSL_ERROR_WANT_READ))
4637                /* This should fail because there is no cookie */
4638             || !TEST_int_eq(SSL_stateless(serverssl), 0))
4639         goto end;
4640
4641     /* Abandon the connection from this client */
4642     SSL_free(clientssl);
4643     clientssl = NULL;
4644
4645     /*
4646      * Now create a connection from a new client but with the same server SSL
4647      * object
4648      */
4649     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4650                                              NULL, NULL))
4651                /* Send the first ClientHello */
4652             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4653                                                 SSL_ERROR_WANT_READ))
4654                /* This should fail because there is no cookie */
4655             || !TEST_int_eq(SSL_stateless(serverssl), 0)
4656                /* Send the second ClientHello */
4657             || !TEST_false(create_ssl_connection(serverssl, clientssl,
4658                                                 SSL_ERROR_WANT_READ))
4659                /* This should succeed because a cookie is now present */
4660             || !TEST_int_eq(SSL_stateless(serverssl), 1)
4661                /* Complete the connection */
4662             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4663                                                 SSL_ERROR_NONE)))
4664         goto end;
4665
4666     shutdown_ssl_connection(serverssl, clientssl);
4667     serverssl = clientssl = NULL;
4668     testresult = 1;
4669
4670  end:
4671     SSL_free(serverssl);
4672     SSL_free(clientssl);
4673     SSL_CTX_free(sctx);
4674     SSL_CTX_free(cctx);
4675     return testresult;
4676
4677 }
4678 #endif /* OPENSSL_NO_TLS1_3 */
4679
4680 static int clntaddoldcb = 0;
4681 static int clntparseoldcb = 0;
4682 static int srvaddoldcb = 0;
4683 static int srvparseoldcb = 0;
4684 static int clntaddnewcb = 0;
4685 static int clntparsenewcb = 0;
4686 static int srvaddnewcb = 0;
4687 static int srvparsenewcb = 0;
4688 static int snicb = 0;
4689
4690 #define TEST_EXT_TYPE1  0xff00
4691
4692 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
4693                       size_t *outlen, int *al, void *add_arg)
4694 {
4695     int *server = (int *)add_arg;
4696     unsigned char *data;
4697
4698     if (SSL_is_server(s))
4699         srvaddoldcb++;
4700     else
4701         clntaddoldcb++;
4702
4703     if (*server != SSL_is_server(s)
4704             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
4705         return -1;
4706
4707     *data = 1;
4708     *out = data;
4709     *outlen = sizeof(char);
4710     return 1;
4711 }
4712
4713 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
4714                         void *add_arg)
4715 {
4716     OPENSSL_free((unsigned char *)out);
4717 }
4718
4719 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
4720                         size_t inlen, int *al, void *parse_arg)
4721 {
4722     int *server = (int *)parse_arg;
4723
4724     if (SSL_is_server(s))
4725         srvparseoldcb++;
4726     else
4727         clntparseoldcb++;
4728
4729     if (*server != SSL_is_server(s)
4730             || inlen != sizeof(char)
4731             || *in != 1)
4732         return -1;
4733
4734     return 1;
4735 }
4736
4737 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
4738                       const unsigned char **out, size_t *outlen, X509 *x,
4739                       size_t chainidx, int *al, void *add_arg)
4740 {
4741     int *server = (int *)add_arg;
4742     unsigned char *data;
4743
4744     if (SSL_is_server(s))
4745         srvaddnewcb++;
4746     else
4747         clntaddnewcb++;
4748
4749     if (*server != SSL_is_server(s)
4750             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
4751         return -1;
4752
4753     *data = 1;
4754     *out = data;
4755     *outlen = sizeof(*data);
4756     return 1;
4757 }
4758
4759 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
4760                         const unsigned char *out, void *add_arg)
4761 {
4762     OPENSSL_free((unsigned char *)out);
4763 }
4764
4765 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
4766                         const unsigned char *in, size_t inlen, X509 *x,
4767                         size_t chainidx, int *al, void *parse_arg)
4768 {
4769     int *server = (int *)parse_arg;
4770
4771     if (SSL_is_server(s))
4772         srvparsenewcb++;
4773     else
4774         clntparsenewcb++;
4775
4776     if (*server != SSL_is_server(s)
4777             || inlen != sizeof(char) || *in != 1)
4778         return -1;
4779
4780     return 1;
4781 }
4782
4783 static int sni_cb(SSL *s, int *al, void *arg)
4784 {
4785     SSL_CTX *ctx = (SSL_CTX *)arg;
4786
4787     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
4788         *al = SSL_AD_INTERNAL_ERROR;
4789         return SSL_TLSEXT_ERR_ALERT_FATAL;
4790     }
4791     snicb++;
4792     return SSL_TLSEXT_ERR_OK;
4793 }
4794
4795 /*
4796  * Custom call back tests.
4797  * Test 0: Old style callbacks in TLSv1.2
4798  * Test 1: New style callbacks in TLSv1.2
4799  * Test 2: New style callbacks in TLSv1.2 with SNI
4800  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
4801  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
4802  */
4803 static int test_custom_exts(int tst)
4804 {
4805     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
4806     SSL *clientssl = NULL, *serverssl = NULL;
4807     int testresult = 0;
4808     static int server = 1;
4809     static int client = 0;
4810     SSL_SESSION *sess = NULL;
4811     unsigned int context;
4812
4813 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
4814     /* Skip tests for TLSv1.2 and below in this case */
4815     if (tst < 3)
4816         return 1;
4817 #endif
4818
4819     /* Reset callback counters */
4820     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
4821     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
4822     snicb = 0;
4823
4824     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
4825                                        TLS_client_method(), TLS1_VERSION, 0,
4826                                        &sctx, &cctx, cert, privkey)))
4827         goto end;
4828
4829     if (tst == 2
4830             && !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
4831                                               TLS1_VERSION, 0,
4832                                               &sctx2, NULL, cert, privkey)))
4833         goto end;
4834
4835
4836     if (tst < 3) {
4837         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
4838         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
4839         if (sctx2 != NULL)
4840             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
4841     }
4842
4843     if (tst == 4) {
4844         context = SSL_EXT_CLIENT_HELLO
4845                   | SSL_EXT_TLS1_2_SERVER_HELLO
4846                   | SSL_EXT_TLS1_3_SERVER_HELLO
4847                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
4848                   | SSL_EXT_TLS1_3_CERTIFICATE
4849                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
4850     } else {
4851         context = SSL_EXT_CLIENT_HELLO
4852                   | SSL_EXT_TLS1_2_SERVER_HELLO
4853                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
4854     }
4855
4856     /* Create a client side custom extension */
4857     if (tst == 0) {
4858         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4859                                                      old_add_cb, old_free_cb,
4860                                                      &client, old_parse_cb,
4861                                                      &client)))
4862             goto end;
4863     } else {
4864         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
4865                                               new_add_cb, new_free_cb,
4866                                               &client, new_parse_cb, &client)))
4867             goto end;
4868     }
4869
4870     /* Should not be able to add duplicates */
4871     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
4872                                                   old_add_cb, old_free_cb,
4873                                                   &client, old_parse_cb,
4874                                                   &client))
4875             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
4876                                                   context, new_add_cb,
4877                                                   new_free_cb, &client,
4878                                                   new_parse_cb, &client)))
4879         goto end;
4880
4881     /* Create a server side custom extension */
4882     if (tst == 0) {
4883         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4884                                                      old_add_cb, old_free_cb,
4885                                                      &server, old_parse_cb,
4886                                                      &server)))
4887             goto end;
4888     } else {
4889         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
4890                                               new_add_cb, new_free_cb,
4891                                               &server, new_parse_cb, &server)))
4892             goto end;
4893         if (sctx2 != NULL
4894                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
4895                                                      context, new_add_cb,
4896                                                      new_free_cb, &server,
4897                                                      new_parse_cb, &server)))
4898             goto end;
4899     }
4900
4901     /* Should not be able to add duplicates */
4902     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
4903                                                   old_add_cb, old_free_cb,
4904                                                   &server, old_parse_cb,
4905                                                   &server))
4906             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
4907                                                   context, new_add_cb,
4908                                                   new_free_cb, &server,
4909                                                   new_parse_cb, &server)))
4910         goto end;
4911
4912     if (tst == 2) {
4913         /* Set up SNI */
4914         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
4915                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
4916             goto end;
4917     }
4918
4919     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4920                                       &clientssl, NULL, NULL))
4921             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4922                                                 SSL_ERROR_NONE)))
4923         goto end;
4924
4925     if (tst == 0) {
4926         if (clntaddoldcb != 1
4927                 || clntparseoldcb != 1
4928                 || srvaddoldcb != 1
4929                 || srvparseoldcb != 1)
4930             goto end;
4931     } else if (tst == 1 || tst == 2 || tst == 3) {
4932         if (clntaddnewcb != 1
4933                 || clntparsenewcb != 1
4934                 || srvaddnewcb != 1
4935                 || srvparsenewcb != 1
4936                 || (tst != 2 && snicb != 0)
4937                 || (tst == 2 && snicb != 1))
4938             goto end;
4939     } else {
4940         /* In this case there 2 NewSessionTicket messages created */
4941         if (clntaddnewcb != 1
4942                 || clntparsenewcb != 5
4943                 || srvaddnewcb != 5
4944                 || srvparsenewcb != 1)
4945             goto end;
4946     }
4947
4948     sess = SSL_get1_session(clientssl);
4949     SSL_shutdown(clientssl);
4950     SSL_shutdown(serverssl);
4951     SSL_free(serverssl);
4952     SSL_free(clientssl);
4953     serverssl = clientssl = NULL;
4954
4955     if (tst == 3) {
4956         /* We don't bother with the resumption aspects for this test */
4957         testresult = 1;
4958         goto end;
4959     }
4960
4961     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4962                                       NULL, NULL))
4963             || !TEST_true(SSL_set_session(clientssl, sess))
4964             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4965                                                SSL_ERROR_NONE)))
4966         goto end;
4967
4968     /*
4969      * For a resumed session we expect to add the ClientHello extension. For the
4970      * old style callbacks we ignore it on the server side because they set
4971      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
4972      * them.
4973      */
4974     if (tst == 0) {
4975         if (clntaddoldcb != 2
4976                 || clntparseoldcb != 1
4977                 || srvaddoldcb != 1
4978                 || srvparseoldcb != 1)
4979             goto end;
4980     } else if (tst == 1 || tst == 2 || tst == 3) {
4981         if (clntaddnewcb != 2
4982                 || clntparsenewcb != 2
4983                 || srvaddnewcb != 2
4984                 || srvparsenewcb != 2)
4985             goto end;
4986     } else {
4987         /*
4988          * No Certificate message extensions in the resumption handshake,
4989          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
4990          */
4991         if (clntaddnewcb != 2
4992                 || clntparsenewcb != 8
4993                 || srvaddnewcb != 8
4994                 || srvparsenewcb != 2)
4995             goto end;
4996     }
4997
4998     testresult = 1;
4999
5000 end:
5001     SSL_SESSION_free(sess);
5002     SSL_free(serverssl);
5003     SSL_free(clientssl);
5004     SSL_CTX_free(sctx2);
5005     SSL_CTX_free(sctx);
5006     SSL_CTX_free(cctx);
5007     return testresult;
5008 }
5009
5010 /*
5011  * Test loading of serverinfo data in various formats. test_sslmessages actually
5012  * tests to make sure the extensions appear in the handshake
5013  */
5014 static int test_serverinfo(int tst)
5015 {
5016     unsigned int version;
5017     unsigned char *sibuf;
5018     size_t sibuflen;
5019     int ret, expected, testresult = 0;
5020     SSL_CTX *ctx;
5021
5022     ctx = SSL_CTX_new_with_libctx(libctx, NULL, TLS_method());
5023     if (!TEST_ptr(ctx))
5024         goto end;
5025
5026     if ((tst & 0x01) == 0x01)
5027         version = SSL_SERVERINFOV2;
5028     else
5029         version = SSL_SERVERINFOV1;
5030
5031     if ((tst & 0x02) == 0x02) {
5032         sibuf = serverinfov2;
5033         sibuflen = sizeof(serverinfov2);
5034         expected = (version == SSL_SERVERINFOV2);
5035     } else {
5036         sibuf = serverinfov1;
5037         sibuflen = sizeof(serverinfov1);
5038         expected = (version == SSL_SERVERINFOV1);
5039     }
5040
5041     if ((tst & 0x04) == 0x04) {
5042         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
5043     } else {
5044         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
5045
5046         /*
5047          * The version variable is irrelevant in this case - it's what is in the
5048          * buffer that matters
5049          */
5050         if ((tst & 0x02) == 0x02)
5051             expected = 0;
5052         else
5053             expected = 1;
5054     }
5055
5056     if (!TEST_true(ret == expected))
5057         goto end;
5058
5059     testresult = 1;
5060
5061  end:
5062     SSL_CTX_free(ctx);
5063
5064     return testresult;
5065 }
5066
5067 /*
5068  * Test that SSL_export_keying_material() produces expected results. There are
5069  * no test vectors so all we do is test that both sides of the communication
5070  * produce the same results for different protocol versions.
5071  */
5072 #define SMALL_LABEL_LEN 10
5073 #define LONG_LABEL_LEN  249
5074 static int test_export_key_mat(int tst)
5075 {
5076     int testresult = 0;
5077     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
5078     SSL *clientssl = NULL, *serverssl = NULL;
5079     const char label[LONG_LABEL_LEN + 1] = "test label";
5080     const unsigned char context[] = "context";
5081     const unsigned char *emptycontext = NULL;
5082     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
5083     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
5084     size_t labellen;
5085     const int protocols[] = {
5086         TLS1_VERSION,
5087         TLS1_1_VERSION,
5088         TLS1_2_VERSION,
5089         TLS1_3_VERSION,
5090         TLS1_3_VERSION,
5091         TLS1_3_VERSION
5092     };
5093
5094 #ifdef OPENSSL_NO_TLS1
5095     if (tst == 0)
5096         return 1;
5097 #endif
5098 #ifdef OPENSSL_NO_TLS1_1
5099     if (tst == 1)
5100         return 1;
5101 #endif
5102     if (is_fips && (tst == 0 || tst == 1))
5103         return 1;
5104 #ifdef OPENSSL_NO_TLS1_2
5105     if (tst == 2)
5106         return 1;
5107 #endif
5108 #ifdef OPENSSL_NO_TLS1_3
5109     if (tst >= 3)
5110         return 1;
5111 #endif
5112     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5113                                        TLS_client_method(), TLS1_VERSION, 0,
5114                                        &sctx, &cctx, cert, privkey)))
5115         goto end;
5116
5117     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
5118     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
5119     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
5120
5121     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5122                                       NULL))
5123             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5124                                                 SSL_ERROR_NONE)))
5125         goto end;
5126
5127     if (tst == 5) {
5128         /*
5129          * TLSv1.3 imposes a maximum label len of 249 bytes. Check we fail if we
5130          * go over that.
5131          */
5132         if (!TEST_int_le(SSL_export_keying_material(clientssl, ckeymat1,
5133                                                     sizeof(ckeymat1), label,
5134                                                     LONG_LABEL_LEN + 1, context,
5135                                                     sizeof(context) - 1, 1), 0))
5136             goto end;
5137
5138         testresult = 1;
5139         goto end;
5140     } else if (tst == 4) {
5141         labellen = LONG_LABEL_LEN;
5142     } else {
5143         labellen = SMALL_LABEL_LEN;
5144     }
5145
5146     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
5147                                                 sizeof(ckeymat1), label,
5148                                                 labellen, context,
5149                                                 sizeof(context) - 1, 1), 1)
5150             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
5151                                                        sizeof(ckeymat2), label,
5152                                                        labellen,
5153                                                        emptycontext,
5154                                                        0, 1), 1)
5155             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
5156                                                        sizeof(ckeymat3), label,
5157                                                        labellen,
5158                                                        NULL, 0, 0), 1)
5159             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
5160                                                        sizeof(skeymat1), label,
5161                                                        labellen,
5162                                                        context,
5163                                                        sizeof(context) -1, 1),
5164                             1)
5165             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
5166                                                        sizeof(skeymat2), label,
5167                                                        labellen,
5168                                                        emptycontext,
5169                                                        0, 1), 1)
5170             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
5171                                                        sizeof(skeymat3), label,
5172                                                        labellen,
5173                                                        NULL, 0, 0), 1)
5174                /*
5175                 * Check that both sides created the same key material with the
5176                 * same context.
5177                 */
5178             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
5179                             sizeof(skeymat1))
5180                /*
5181                 * Check that both sides created the same key material with an
5182                 * empty context.
5183                 */
5184             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
5185                             sizeof(skeymat2))
5186                /*
5187                 * Check that both sides created the same key material without a
5188                 * context.
5189                 */
5190             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
5191                             sizeof(skeymat3))
5192                /* Different contexts should produce different results */
5193             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
5194                             sizeof(ckeymat2)))
5195         goto end;
5196
5197     /*
5198      * Check that an empty context and no context produce different results in
5199      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
5200      */
5201     if ((tst < 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
5202                                   sizeof(ckeymat3)))
5203             || (tst >= 3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
5204                                          sizeof(ckeymat3))))
5205         goto end;
5206
5207     testresult = 1;
5208
5209  end:
5210     SSL_free(serverssl);
5211     SSL_free(clientssl);
5212     SSL_CTX_free(sctx2);
5213     SSL_CTX_free(sctx);
5214     SSL_CTX_free(cctx);
5215
5216     return testresult;
5217 }
5218
5219 #ifndef OPENSSL_NO_TLS1_3
5220 /*
5221  * Test that SSL_export_keying_material_early() produces expected
5222  * results. There are no test vectors so all we do is test that both
5223  * sides of the communication produce the same results for different
5224  * protocol versions.
5225  */
5226 static int test_export_key_mat_early(int idx)
5227 {
5228     static const char label[] = "test label";
5229     static const unsigned char context[] = "context";
5230     int testresult = 0;
5231     SSL_CTX *cctx = NULL, *sctx = NULL;
5232     SSL *clientssl = NULL, *serverssl = NULL;
5233     SSL_SESSION *sess = NULL;
5234     const unsigned char *emptycontext = NULL;
5235     unsigned char ckeymat1[80], ckeymat2[80];
5236     unsigned char skeymat1[80], skeymat2[80];
5237     unsigned char buf[1];
5238     size_t readbytes, written;
5239
5240     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
5241                                         &sess, idx)))
5242         goto end;
5243
5244     /* Here writing 0 length early data is enough. */
5245     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
5246             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
5247                                                 &readbytes),
5248                             SSL_READ_EARLY_DATA_ERROR)
5249             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
5250                             SSL_EARLY_DATA_ACCEPTED))
5251         goto end;
5252
5253     if (!TEST_int_eq(SSL_export_keying_material_early(
5254                      clientssl, ckeymat1, sizeof(ckeymat1), label,
5255                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
5256             || !TEST_int_eq(SSL_export_keying_material_early(
5257                             clientssl, ckeymat2, sizeof(ckeymat2), label,
5258                             sizeof(label) - 1, emptycontext, 0), 1)
5259             || !TEST_int_eq(SSL_export_keying_material_early(
5260                             serverssl, skeymat1, sizeof(skeymat1), label,
5261                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
5262             || !TEST_int_eq(SSL_export_keying_material_early(
5263                             serverssl, skeymat2, sizeof(skeymat2), label,
5264                             sizeof(label) - 1, emptycontext, 0), 1)
5265                /*
5266                 * Check that both sides created the same key material with the
5267                 * same context.
5268                 */
5269             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
5270                             sizeof(skeymat1))
5271                /*
5272                 * Check that both sides created the same key material with an
5273                 * empty context.
5274                 */
5275             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
5276                             sizeof(skeymat2))
5277                /* Different contexts should produce different results */
5278             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
5279                             sizeof(ckeymat2)))
5280         goto end;
5281
5282     testresult = 1;
5283
5284  end:
5285     SSL_SESSION_free(sess);
5286     SSL_SESSION_free(clientpsk);
5287     SSL_SESSION_free(serverpsk);
5288     clientpsk = serverpsk = NULL;
5289     SSL_free(serverssl);
5290     SSL_free(clientssl);
5291     SSL_CTX_free(sctx);
5292     SSL_CTX_free(cctx);
5293
5294     return testresult;
5295 }
5296
5297 #define NUM_KEY_UPDATE_MESSAGES 40
5298 /*
5299  * Test KeyUpdate.
5300  */
5301 static int test_key_update(void)
5302 {
5303     SSL_CTX *cctx = NULL, *sctx = NULL;
5304     SSL *clientssl = NULL, *serverssl = NULL;
5305     int testresult = 0, i, j;
5306     char buf[20];
5307     static char *mess = "A test message";
5308
5309     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5310                                        TLS_client_method(),
5311                                        TLS1_3_VERSION,
5312                                        0,
5313                                        &sctx, &cctx, cert, privkey))
5314             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5315                                              NULL, NULL))
5316             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5317                                                 SSL_ERROR_NONE)))
5318         goto end;
5319
5320     for (j = 0; j < 2; j++) {
5321         /* Send lots of KeyUpdate messages */
5322         for (i = 0; i < NUM_KEY_UPDATE_MESSAGES; i++) {
5323             if (!TEST_true(SSL_key_update(clientssl,
5324                                           (j == 0)
5325                                           ? SSL_KEY_UPDATE_NOT_REQUESTED
5326                                           : SSL_KEY_UPDATE_REQUESTED))
5327                     || !TEST_true(SSL_do_handshake(clientssl)))
5328                 goto end;
5329         }
5330
5331         /* Check that sending and receiving app data is ok */
5332         if (!TEST_int_eq(SSL_write(clientssl, mess, strlen(mess)), strlen(mess))
5333                 || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
5334                                          strlen(mess)))
5335             goto end;
5336
5337         if (!TEST_int_eq(SSL_write(serverssl, mess, strlen(mess)), strlen(mess))
5338                 || !TEST_int_eq(SSL_read(clientssl, buf, sizeof(buf)),
5339                                          strlen(mess)))
5340             goto end;
5341     }
5342
5343     testresult = 1;
5344
5345  end:
5346     SSL_free(serverssl);
5347     SSL_free(clientssl);
5348     SSL_CTX_free(sctx);
5349     SSL_CTX_free(cctx);
5350
5351     return testresult;
5352 }
5353
5354 /*
5355  * Test we can handle a KeyUpdate (update requested) message while write data
5356  * is pending.
5357  * Test 0: Client sends KeyUpdate while Server is writing
5358  * Test 1: Server sends KeyUpdate while Client is writing
5359  */
5360 static int test_key_update_in_write(int tst)
5361 {
5362     SSL_CTX *cctx = NULL, *sctx = NULL;
5363     SSL *clientssl = NULL, *serverssl = NULL;
5364     int testresult = 0;
5365     char buf[20];
5366     static char *mess = "A test message";
5367     BIO *bretry = BIO_new(bio_s_always_retry());
5368     BIO *tmp = NULL;
5369     SSL *peerupdate = NULL, *peerwrite = NULL;
5370
5371     if (!TEST_ptr(bretry)
5372             || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5373                                               TLS_client_method(),
5374                                               TLS1_3_VERSION,
5375                                               0,
5376                                               &sctx, &cctx, cert, privkey))
5377             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5378                                              NULL, NULL))
5379             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5380                                                 SSL_ERROR_NONE)))
5381         goto end;
5382
5383     peerupdate = tst == 0 ? clientssl : serverssl;
5384     peerwrite = tst == 0 ? serverssl : clientssl;
5385
5386     if (!TEST_true(SSL_key_update(peerupdate, SSL_KEY_UPDATE_REQUESTED))
5387             || !TEST_true(SSL_do_handshake(peerupdate)))
5388         goto end;
5389
5390     /* Swap the writing endpoint's write BIO to force a retry */
5391     tmp = SSL_get_wbio(peerwrite);
5392     if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
5393         tmp = NULL;
5394         goto end;
5395     }
5396     SSL_set0_wbio(peerwrite, bretry);
5397     bretry = NULL;
5398
5399     /* Write data that we know will fail with SSL_ERROR_WANT_WRITE */
5400     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), -1)
5401             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_WRITE))
5402         goto end;
5403
5404     /* Reinstate the original writing endpoint's write BIO */
5405     SSL_set0_wbio(peerwrite, tmp);
5406     tmp = NULL;
5407
5408     /* Now read some data - we will read the key update */
5409     if (!TEST_int_eq(SSL_read(peerwrite, buf, sizeof(buf)), -1)
5410             || !TEST_int_eq(SSL_get_error(peerwrite, 0), SSL_ERROR_WANT_READ))
5411         goto end;
5412
5413     /*
5414      * Complete the write we started previously and read it from the other
5415      * endpoint
5416      */
5417     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
5418             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
5419         goto end;
5420
5421     /* Write more data to ensure we send the KeyUpdate message back */
5422     if (!TEST_int_eq(SSL_write(peerwrite, mess, strlen(mess)), strlen(mess))
5423             || !TEST_int_eq(SSL_read(peerupdate, buf, sizeof(buf)), strlen(mess)))
5424         goto end;
5425
5426     testresult = 1;
5427
5428  end:
5429     SSL_free(serverssl);
5430     SSL_free(clientssl);
5431     SSL_CTX_free(sctx);
5432     SSL_CTX_free(cctx);
5433     BIO_free(bretry);
5434     BIO_free(tmp);
5435
5436     return testresult;
5437 }
5438 #endif /* OPENSSL_NO_TLS1_3 */
5439
5440 static int test_ssl_clear(int idx)
5441 {
5442     SSL_CTX *cctx = NULL, *sctx = NULL;
5443     SSL *clientssl = NULL, *serverssl = NULL;
5444     int testresult = 0;
5445
5446 #ifdef OPENSSL_NO_TLS1_2
5447     if (idx == 1)
5448         return 1;
5449 #endif
5450
5451     /* Create an initial connection */
5452     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5453                                        TLS_client_method(), TLS1_VERSION, 0,
5454                                        &sctx, &cctx, cert, privkey))
5455             || (idx == 1
5456                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
5457                                                             TLS1_2_VERSION)))
5458             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
5459                                           &clientssl, NULL, NULL))
5460             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5461                                                 SSL_ERROR_NONE)))
5462         goto end;
5463
5464     SSL_shutdown(clientssl);
5465     SSL_shutdown(serverssl);
5466     SSL_free(serverssl);
5467     serverssl = NULL;
5468
5469     /* Clear clientssl - we're going to reuse the object */
5470     if (!TEST_true(SSL_clear(clientssl)))
5471         goto end;
5472
5473     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5474                                              NULL, NULL))
5475             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5476                                                 SSL_ERROR_NONE))
5477             || !TEST_true(SSL_session_reused(clientssl)))
5478         goto end;
5479
5480     SSL_shutdown(clientssl);
5481     SSL_shutdown(serverssl);
5482
5483     testresult = 1;
5484
5485  end:
5486     SSL_free(serverssl);
5487     SSL_free(clientssl);
5488     SSL_CTX_free(sctx);
5489     SSL_CTX_free(cctx);
5490
5491     return testresult;
5492 }
5493
5494 /* Parse CH and retrieve any MFL extension value if present */
5495 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
5496 {
5497     long len;
5498     unsigned char *data;
5499     PACKET pkt, pkt2, pkt3;
5500     unsigned int MFL_code = 0, type = 0;
5501
5502     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
5503         goto end;
5504
5505     memset(&pkt, 0, sizeof(pkt));
5506     memset(&pkt2, 0, sizeof(pkt2));
5507     memset(&pkt3, 0, sizeof(pkt3));
5508
5509     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
5510                /* Skip the record header */
5511             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
5512                /* Skip the handshake message header */
5513             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
5514                /* Skip client version and random */
5515             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
5516                                                + SSL3_RANDOM_SIZE))
5517                /* Skip session id */
5518             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
5519                /* Skip ciphers */
5520             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
5521                /* Skip compression */
5522             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
5523                /* Extensions len */
5524             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
5525         goto end;
5526
5527     /* Loop through all extensions */
5528     while (PACKET_remaining(&pkt2)) {
5529         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
5530                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
5531             goto end;
5532
5533         if (type == TLSEXT_TYPE_max_fragment_length) {
5534             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
5535                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
5536                 goto end;
5537
5538             *mfl_codemfl_code = MFL_code;
5539             return 1;
5540         }
5541     }
5542
5543  end:
5544     return 0;
5545 }
5546
5547 /* Maximum-Fragment-Length TLS extension mode to test */
5548 static const unsigned char max_fragment_len_test[] = {
5549     TLSEXT_max_fragment_length_512,
5550     TLSEXT_max_fragment_length_1024,
5551     TLSEXT_max_fragment_length_2048,
5552     TLSEXT_max_fragment_length_4096
5553 };
5554
5555 static int test_max_fragment_len_ext(int idx_tst)
5556 {
5557     SSL_CTX *ctx;
5558     SSL *con = NULL;
5559     int testresult = 0, MFL_mode = 0;
5560     BIO *rbio, *wbio;
5561
5562     ctx = SSL_CTX_new_with_libctx(libctx, NULL, TLS_method());
5563     if (!TEST_ptr(ctx))
5564         goto end;
5565
5566     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
5567                    ctx, max_fragment_len_test[idx_tst])))
5568         goto end;
5569
5570     con = SSL_new(ctx);
5571     if (!TEST_ptr(con))
5572         goto end;
5573
5574     rbio = BIO_new(BIO_s_mem());
5575     wbio = BIO_new(BIO_s_mem());
5576     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
5577         BIO_free(rbio);
5578         BIO_free(wbio);
5579         goto end;
5580     }
5581
5582     SSL_set_bio(con, rbio, wbio);
5583     SSL_set_connect_state(con);
5584
5585     if (!TEST_int_le(SSL_connect(con), 0)) {
5586         /* This shouldn't succeed because we don't have a server! */
5587         goto end;
5588     }
5589
5590     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
5591         /* no MFL in client hello */
5592         goto end;
5593     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
5594         goto end;
5595
5596     testresult = 1;
5597
5598 end:
5599     SSL_free(con);
5600     SSL_CTX_free(ctx);
5601
5602     return testresult;
5603 }
5604
5605 #ifndef OPENSSL_NO_TLS1_3
5606 static int test_pha_key_update(void)
5607 {
5608     SSL_CTX *cctx = NULL, *sctx = NULL;
5609     SSL *clientssl = NULL, *serverssl = NULL;
5610     int testresult = 0;
5611
5612     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5613                                        TLS_client_method(), TLS1_VERSION, 0,
5614                                        &sctx, &cctx, cert, privkey)))
5615         return 0;
5616
5617     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
5618         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
5619         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
5620         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
5621         goto end;
5622
5623     SSL_CTX_set_post_handshake_auth(cctx, 1);
5624
5625     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5626                                       NULL, NULL)))
5627         goto end;
5628
5629     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5630                                          SSL_ERROR_NONE)))
5631         goto end;
5632
5633     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
5634     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
5635         goto end;
5636
5637     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
5638         goto end;
5639
5640     /* Start handshake on the server */
5641     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
5642         goto end;
5643
5644     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
5645     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5646                                          SSL_ERROR_NONE)))
5647         goto end;
5648
5649     SSL_shutdown(clientssl);
5650     SSL_shutdown(serverssl);
5651
5652     testresult = 1;
5653
5654  end:
5655     SSL_free(serverssl);
5656     SSL_free(clientssl);
5657     SSL_CTX_free(sctx);
5658     SSL_CTX_free(cctx);
5659     return testresult;
5660 }
5661 #endif
5662
5663 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
5664
5665 static SRP_VBASE *vbase = NULL;
5666
5667 DEFINE_STACK_OF(SRP_user_pwd)
5668
5669 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
5670 {
5671     int ret = SSL3_AL_FATAL;
5672     char *username;
5673     SRP_user_pwd *user = NULL;
5674
5675     username = SSL_get_srp_username(s);
5676     if (username == NULL) {
5677         *ad = SSL_AD_INTERNAL_ERROR;
5678         goto err;
5679     }
5680
5681     user = SRP_VBASE_get1_by_user(vbase, username);
5682     if (user == NULL) {
5683         *ad = SSL_AD_INTERNAL_ERROR;
5684         goto err;
5685     }
5686
5687     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
5688                                  user->info) <= 0) {
5689         *ad = SSL_AD_INTERNAL_ERROR;
5690         goto err;
5691     }
5692
5693     ret = 0;
5694
5695  err:
5696     SRP_user_pwd_free(user);
5697     return ret;
5698 }
5699
5700 static int create_new_vfile(char *userid, char *password, const char *filename)
5701 {
5702     char *gNid = NULL;
5703     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
5704     TXT_DB *db = NULL;
5705     int ret = 0;
5706     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
5707     size_t i;
5708
5709     if (!TEST_ptr(dummy) || !TEST_ptr(row))
5710         goto end;
5711
5712     gNid = SRP_create_verifier_ex(userid, password, &row[DB_srpsalt],
5713                                   &row[DB_srpverifier], NULL, NULL, libctx, NULL);
5714     if (!TEST_ptr(gNid))
5715         goto end;
5716
5717     /*
5718      * The only way to create an empty TXT_DB is to provide a BIO with no data
5719      * in it!
5720      */
5721     db = TXT_DB_read(dummy, DB_NUMBER);
5722     if (!TEST_ptr(db))
5723         goto end;
5724
5725     out = BIO_new_file(filename, "w");
5726     if (!TEST_ptr(out))
5727         goto end;
5728
5729     row[DB_srpid] = OPENSSL_strdup(userid);
5730     row[DB_srptype] = OPENSSL_strdup("V");
5731     row[DB_srpgN] = OPENSSL_strdup(gNid);
5732
5733     if (!TEST_ptr(row[DB_srpid])
5734             || !TEST_ptr(row[DB_srptype])
5735             || !TEST_ptr(row[DB_srpgN])
5736             || !TEST_true(TXT_DB_insert(db, row)))
5737         goto end;
5738
5739     row = NULL;
5740
5741     if (!TXT_DB_write(out, db))
5742         goto end;
5743
5744     ret = 1;
5745  end:
5746     if (row != NULL) {
5747         for (i = 0; i < DB_NUMBER; i++)
5748             OPENSSL_free(row[i]);
5749     }
5750     OPENSSL_free(row);
5751     BIO_free(dummy);
5752     BIO_free(out);
5753     TXT_DB_free(db);
5754
5755     return ret;
5756 }
5757
5758 static int create_new_vbase(char *userid, char *password)
5759 {
5760     BIGNUM *verifier = NULL, *salt = NULL;
5761     const SRP_gN *lgN = NULL;
5762     SRP_user_pwd *user_pwd = NULL;
5763     int ret = 0;
5764
5765     lgN = SRP_get_default_gN(NULL);
5766     if (!TEST_ptr(lgN))
5767         goto end;
5768
5769     if (!TEST_true(SRP_create_verifier_BN_ex(userid, password, &salt, &verifier,
5770                                              lgN->N, lgN->g, libctx, NULL)))
5771         goto end;
5772
5773     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
5774     if (!TEST_ptr(user_pwd))
5775         goto end;
5776
5777     user_pwd->N = lgN->N;
5778     user_pwd->g = lgN->g;
5779     user_pwd->id = OPENSSL_strdup(userid);
5780     if (!TEST_ptr(user_pwd->id))
5781         goto end;
5782
5783     user_pwd->v = verifier;
5784     user_pwd->s = salt;
5785     verifier = salt = NULL;
5786
5787     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
5788         goto end;
5789     user_pwd = NULL;
5790
5791     ret = 1;
5792 end:
5793     SRP_user_pwd_free(user_pwd);
5794     BN_free(salt);
5795     BN_free(verifier);
5796
5797     return ret;
5798 }
5799
5800 /*
5801  * SRP tests
5802  *
5803  * Test 0: Simple successful SRP connection, new vbase
5804  * Test 1: Connection failure due to bad password, new vbase
5805  * Test 2: Simple successful SRP connection, vbase loaded from existing file
5806  * Test 3: Connection failure due to bad password, vbase loaded from existing
5807  *         file
5808  * Test 4: Simple successful SRP connection, vbase loaded from new file
5809  * Test 5: Connection failure due to bad password, vbase loaded from new file
5810  */
5811 static int test_srp(int tst)
5812 {
5813     char *userid = "test", *password = "password", *tstsrpfile;
5814     SSL_CTX *cctx = NULL, *sctx = NULL;
5815     SSL *clientssl = NULL, *serverssl = NULL;
5816     int ret, testresult = 0;
5817
5818     vbase = SRP_VBASE_new(NULL);
5819     if (!TEST_ptr(vbase))
5820         goto end;
5821
5822     if (tst == 0 || tst == 1) {
5823         if (!TEST_true(create_new_vbase(userid, password)))
5824             goto end;
5825     } else {
5826         if (tst == 4 || tst == 5) {
5827             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
5828                 goto end;
5829             tstsrpfile = tmpfilename;
5830         } else {
5831             tstsrpfile = srpvfile;
5832         }
5833         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
5834             goto end;
5835     }
5836
5837     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
5838                                        TLS_client_method(), TLS1_VERSION, 0,
5839                                        &sctx, &cctx, cert, privkey)))
5840         goto end;
5841
5842     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
5843             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
5844             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
5845             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
5846             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
5847         goto end;
5848
5849     if (tst % 2 == 1) {
5850         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
5851             goto end;
5852     } else {
5853         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
5854             goto end;
5855     }
5856
5857     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5858                                       NULL, NULL)))
5859         goto end;
5860
5861     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
5862     if (ret) {
5863         if (!TEST_true(tst % 2 == 0))
5864             goto end;
5865     } else {
5866         if (!TEST_true(tst % 2 == 1))
5867             goto end;
5868     }
5869
5870     testresult = 1;
5871
5872  end:
5873     SRP_VBASE_free(vbase);
5874     vbase = NULL;
5875     SSL_free(serverssl);
5876     SSL_free(clientssl);
5877     SSL_CTX_free(sctx);
5878     SSL_CTX_free(cctx);
5879
5880     return testresult;
5881 }
5882 #endif
5883
5884 static int info_cb_failed = 0;
5885 static int info_cb_offset = 0;
5886 static int info_cb_this_state = -1;
5887
5888 static struct info_cb_states_st {
5889     int where;
5890     const char *statestr;
5891 } info_cb_states[][60] = {
5892     {
5893         /* TLSv1.2 server followed by resumption */
5894         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5895         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5896         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
5897         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
5898         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
5899         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5900         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5901         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5902         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
5903         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5904         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
5905         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5906         {SSL_CB_EXIT, NULL}, {0, NULL},
5907     }, {
5908         /* TLSv1.2 client followed by resumption */
5909         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5910         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5911         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
5912         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
5913         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
5914         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5915         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5916         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5917         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5918         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
5919         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
5920         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
5921     }, {
5922         /* TLSv1.3 server followed by resumption */
5923         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5924         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5925         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
5926         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
5927         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
5928         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5929         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
5930         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5931         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5932         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5933         {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"},
5934         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5935         {SSL_CB_LOOP, "TWST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5936     }, {
5937         /* TLSv1.3 client followed by resumption */
5938         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5939         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
5940         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
5941         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
5942         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
5943         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5944         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "},
5945         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL},
5946         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
5947         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
5948         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
5949         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
5950         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5951         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
5952         {SSL_CB_EXIT, NULL}, {0, NULL},
5953     }, {
5954         /* TLSv1.3 server, early_data */
5955         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5956         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
5957         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
5958         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5959         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5960         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
5961         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_LOOP, "TWST"},
5962         {SSL_CB_EXIT, NULL}, {0, NULL},
5963     }, {
5964         /* TLSv1.3 client, early_data */
5965         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
5966         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
5967         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
5968         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
5969         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
5970         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
5971         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
5972         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "},
5973         {SSL_CB_LOOP, "TRST"}, {SSL_CB_EXIT, NULL}, {0, NULL},
5974     }, {
5975         {0, NULL},
5976     }
5977 };
5978
5979 static void sslapi_info_callback(const SSL *s, int where, int ret)
5980 {
5981     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
5982
5983     /* We do not ever expect a connection to fail in this test */
5984     if (!TEST_false(ret == 0)) {
5985         info_cb_failed = 1;
5986         return;
5987     }
5988
5989     /*
5990      * Do some sanity checks. We never expect these things to happen in this
5991      * test
5992      */
5993     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
5994             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
5995             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
5996         info_cb_failed = 1;
5997         return;
5998     }
5999
6000     /* Now check we're in the right state */
6001     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
6002         info_cb_failed = 1;
6003         return;
6004     }
6005     if ((where & SSL_CB_LOOP) != 0
6006             && !TEST_int_eq(strcmp(SSL_state_string(s),
6007                             state[info_cb_this_state].statestr), 0)) {
6008         info_cb_failed = 1;
6009         return;
6010     }
6011
6012     /*
6013      * Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init
6014      */
6015     if ((where & SSL_CB_HANDSHAKE_DONE)
6016             && SSL_in_init((SSL *)s) != 0) {
6017         info_cb_failed = 1;
6018         return;
6019     }
6020 }
6021
6022 /*
6023  * Test the info callback gets called when we expect it to.
6024  *
6025  * Test 0: TLSv1.2, server
6026  * Test 1: TLSv1.2, client
6027  * Test 2: TLSv1.3, server
6028  * Test 3: TLSv1.3, client
6029  * Test 4: TLSv1.3, server, early_data
6030  * Test 5: TLSv1.3, client, early_data
6031  */
6032 static int test_info_callback(int tst)
6033 {
6034     SSL_CTX *cctx = NULL, *sctx = NULL;
6035     SSL *clientssl = NULL, *serverssl = NULL;
6036     SSL_SESSION *clntsess = NULL;
6037     int testresult = 0;
6038     int tlsvers;
6039
6040     if (tst < 2) {
6041 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
6042 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
6043                                     || !defined(OPENSSL_NO_DH))
6044         tlsvers = TLS1_2_VERSION;
6045 #else
6046         return 1;
6047 #endif
6048     } else {
6049 #ifndef OPENSSL_NO_TLS1_3
6050         tlsvers = TLS1_3_VERSION;
6051 #else
6052         return 1;
6053 #endif
6054     }
6055
6056     /* Reset globals */
6057     info_cb_failed = 0;
6058     info_cb_this_state = -1;
6059     info_cb_offset = tst;
6060
6061 #ifndef OPENSSL_NO_TLS1_3
6062     if (tst >= 4) {
6063         SSL_SESSION *sess = NULL;
6064         size_t written, readbytes;
6065         unsigned char buf[80];
6066
6067         /* early_data tests */
6068         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
6069                                             &serverssl, &sess, 0)))
6070             goto end;
6071
6072         /* We don't actually need this reference */
6073         SSL_SESSION_free(sess);
6074
6075         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
6076                               sslapi_info_callback);
6077
6078         /* Write and read some early data and then complete the connection */
6079         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
6080                                             &written))
6081                 || !TEST_size_t_eq(written, strlen(MSG1))
6082                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
6083                                                     sizeof(buf), &readbytes),
6084                                 SSL_READ_EARLY_DATA_SUCCESS)
6085                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
6086                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
6087                                 SSL_EARLY_DATA_ACCEPTED)
6088                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
6089                                                     SSL_ERROR_NONE))
6090                 || !TEST_false(info_cb_failed))
6091             goto end;
6092
6093         testresult = 1;
6094         goto end;
6095     }
6096 #endif
6097
6098     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6099                                        TLS_client_method(),
6100                                        tlsvers, tlsvers, &sctx, &cctx, cert,
6101                                        privkey)))
6102         goto end;
6103
6104     /*
6105      * For even numbered tests we check the server callbacks. For odd numbers we
6106      * check the client.
6107      */
6108     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
6109                               sslapi_info_callback);
6110
6111     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
6112                                           &clientssl, NULL, NULL))
6113         || !TEST_true(create_ssl_connection(serverssl, clientssl,
6114                                             SSL_ERROR_NONE))
6115         || !TEST_false(info_cb_failed))
6116     goto end;
6117
6118
6119
6120     clntsess = SSL_get1_session(clientssl);
6121     SSL_shutdown(clientssl);
6122     SSL_shutdown(serverssl);
6123     SSL_free(serverssl);
6124     SSL_free(clientssl);
6125     serverssl = clientssl = NULL;
6126
6127     /* Now do a resumption */
6128     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6129                                       NULL))
6130             || !TEST_true(SSL_set_session(clientssl, clntsess))
6131             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6132                                                 SSL_ERROR_NONE))
6133             || !TEST_true(SSL_session_reused(clientssl))
6134             || !TEST_false(info_cb_failed))
6135         goto end;
6136
6137     testresult = 1;
6138
6139  end:
6140     SSL_free(serverssl);
6141     SSL_free(clientssl);
6142     SSL_SESSION_free(clntsess);
6143     SSL_CTX_free(sctx);
6144     SSL_CTX_free(cctx);
6145     return testresult;
6146 }
6147
6148 static int test_ssl_pending(int tst)
6149 {
6150     SSL_CTX *cctx = NULL, *sctx = NULL;
6151     SSL *clientssl = NULL, *serverssl = NULL;
6152     int testresult = 0;
6153     char msg[] = "A test message";
6154     char buf[5];
6155     size_t written, readbytes;
6156
6157     if (tst == 0) {
6158         if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6159                                            TLS_client_method(),
6160                                            TLS1_VERSION, 0,
6161                                            &sctx, &cctx, cert, privkey)))
6162             goto end;
6163     } else {
6164 #ifndef OPENSSL_NO_DTLS
6165         if (!TEST_true(create_ssl_ctx_pair(libctx, DTLS_server_method(),
6166                                            DTLS_client_method(),
6167                                            DTLS1_VERSION, 0,
6168                                            &sctx, &cctx, cert, privkey)))
6169             goto end;
6170 #else
6171         return 1;
6172 #endif
6173     }
6174
6175     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6176                                              NULL, NULL))
6177             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6178                                                 SSL_ERROR_NONE)))
6179         goto end;
6180
6181     if (!TEST_int_eq(SSL_pending(clientssl), 0)
6182             || !TEST_false(SSL_has_pending(clientssl))
6183             || !TEST_int_eq(SSL_pending(serverssl), 0)
6184             || !TEST_false(SSL_has_pending(serverssl))
6185             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
6186             || !TEST_size_t_eq(written, sizeof(msg))
6187             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
6188             || !TEST_size_t_eq(readbytes, sizeof(buf))
6189             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
6190             || !TEST_true(SSL_has_pending(clientssl)))
6191         goto end;
6192
6193     testresult = 1;
6194
6195  end:
6196     SSL_free(serverssl);
6197     SSL_free(clientssl);
6198     SSL_CTX_free(sctx);
6199     SSL_CTX_free(cctx);
6200
6201     return testresult;
6202 }
6203
6204 static struct {
6205     unsigned int maxprot;
6206     const char *clntciphers;
6207     const char *clnttls13ciphers;
6208     const char *srvrciphers;
6209     const char *srvrtls13ciphers;
6210     const char *shared;
6211     const char *fipsshared;
6212 } shared_ciphers_data[] = {
6213 /*
6214  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
6215  * TLSv1.3 is enabled but TLSv1.2 is disabled.
6216  */
6217 #if defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
6218     {
6219         TLS1_2_VERSION,
6220         "AES128-SHA:AES256-SHA",
6221         NULL,
6222         "AES256-SHA:DHE-RSA-AES128-SHA",
6223         NULL,
6224         "AES256-SHA",
6225         "AES256-SHA"
6226     },
6227 # if !defined(OPENSSL_NO_CHACHA) \
6228      && !defined(OPENSSL_NO_POLY1305) \
6229      && !defined(OPENSSL_NO_EC)
6230     {
6231         TLS1_2_VERSION,
6232         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
6233         NULL,
6234         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
6235         NULL,
6236         "AES128-SHA:ECDHE-RSA-CHACHA20-POLY1305",
6237         "AES128-SHA"
6238     },
6239 # endif
6240     {
6241         TLS1_2_VERSION,
6242         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
6243         NULL,
6244         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
6245         NULL,
6246         "AES128-SHA:AES256-SHA",
6247         "AES128-SHA:AES256-SHA"
6248     },
6249     {
6250         TLS1_2_VERSION,
6251         "AES128-SHA:AES256-SHA",
6252         NULL,
6253         "AES128-SHA:DHE-RSA-AES128-SHA",
6254         NULL,
6255         "AES128-SHA",
6256         "AES128-SHA"
6257     },
6258 #endif
6259 /*
6260  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
6261  * enabled.
6262  */
6263 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
6264     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
6265     {
6266         TLS1_3_VERSION,
6267         "AES128-SHA:AES256-SHA",
6268         NULL,
6269         "AES256-SHA:AES128-SHA256",
6270         NULL,
6271         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
6272         "TLS_AES_128_GCM_SHA256:AES256-SHA",
6273         "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:AES256-SHA"
6274     },
6275 #endif
6276 #ifndef OPENSSL_NO_TLS1_3
6277     {
6278         TLS1_3_VERSION,
6279         "AES128-SHA",
6280         "TLS_AES_256_GCM_SHA384",
6281         "AES256-SHA",
6282         "TLS_AES_256_GCM_SHA384",
6283         "TLS_AES_256_GCM_SHA384",
6284         "TLS_AES_256_GCM_SHA384"
6285     },
6286 #endif
6287 };
6288
6289 static int int_test_ssl_get_shared_ciphers(int tst, int clnt)
6290 {
6291     SSL_CTX *cctx = NULL, *sctx = NULL;
6292     SSL *clientssl = NULL, *serverssl = NULL;
6293     int testresult = 0;
6294     char buf[1024];
6295     OPENSSL_CTX *tmplibctx = OPENSSL_CTX_new();
6296
6297     if (!TEST_ptr(tmplibctx))
6298         goto end;
6299
6300     /*
6301      * Regardless of whether we're testing with the FIPS provider loaded into
6302      * libctx, we want one peer to always use the full set of ciphersuites
6303      * available. Therefore we use a separate libctx with the default provider
6304      * loaded into it. We run the same tests twice - once with the client side
6305      * having the full set of ciphersuites and once with the server side.
6306      */
6307     if (clnt) {
6308         cctx = SSL_CTX_new_with_libctx(tmplibctx, NULL, TLS_client_method());
6309         if (!TEST_ptr(cctx))
6310             goto end;
6311     } else {
6312         sctx = SSL_CTX_new_with_libctx(tmplibctx, NULL, TLS_server_method());
6313         if (!TEST_ptr(sctx))
6314             goto end;
6315     }
6316
6317     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6318                                        TLS_client_method(),
6319                                        TLS1_VERSION,
6320                                        shared_ciphers_data[tst].maxprot,
6321                                        &sctx, &cctx, cert, privkey)))
6322         goto end;
6323
6324     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
6325                                         shared_ciphers_data[tst].clntciphers))
6326             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
6327                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
6328                                     shared_ciphers_data[tst].clnttls13ciphers)))
6329             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
6330                                         shared_ciphers_data[tst].srvrciphers))
6331             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
6332                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
6333                                     shared_ciphers_data[tst].srvrtls13ciphers))))
6334         goto end;
6335
6336
6337     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6338                                              NULL, NULL))
6339             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6340                                                 SSL_ERROR_NONE)))
6341         goto end;
6342
6343     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
6344             || !TEST_int_eq(strcmp(buf,
6345                                    is_fips
6346                                    ? shared_ciphers_data[tst].fipsshared
6347                                    : shared_ciphers_data[tst].shared),
6348                                    0)) {
6349         TEST_info("Shared ciphers are: %s\n", buf);
6350         goto end;
6351     }
6352
6353     testresult = 1;
6354
6355  end:
6356     SSL_free(serverssl);
6357     SSL_free(clientssl);
6358     SSL_CTX_free(sctx);
6359     SSL_CTX_free(cctx);
6360     OPENSSL_CTX_free(tmplibctx);
6361
6362     return testresult;
6363 }
6364
6365 static int test_ssl_get_shared_ciphers(int tst)
6366 {
6367     return int_test_ssl_get_shared_ciphers(tst, 0)
6368            && int_test_ssl_get_shared_ciphers(tst, 1);
6369 }
6370
6371
6372 static const char *appdata = "Hello World";
6373 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
6374 static int tick_key_renew = 0;
6375 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
6376
6377 static int gen_tick_cb(SSL *s, void *arg)
6378 {
6379     gen_tick_called = 1;
6380
6381     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
6382                                            strlen(appdata));
6383 }
6384
6385 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
6386                                      const unsigned char *keyname,
6387                                      size_t keyname_length,
6388                                      SSL_TICKET_STATUS status,
6389                                      void *arg)
6390 {
6391     void *tickdata;
6392     size_t tickdlen;
6393
6394     dec_tick_called = 1;
6395
6396     if (status == SSL_TICKET_EMPTY)
6397         return SSL_TICKET_RETURN_IGNORE_RENEW;
6398
6399     if (!TEST_true(status == SSL_TICKET_SUCCESS
6400                    || status == SSL_TICKET_SUCCESS_RENEW))
6401         return SSL_TICKET_RETURN_ABORT;
6402
6403     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
6404                                                    &tickdlen))
6405             || !TEST_size_t_eq(tickdlen, strlen(appdata))
6406             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
6407         return SSL_TICKET_RETURN_ABORT;
6408
6409     if (tick_key_cb_called)  {
6410         /* Don't change what the ticket key callback wanted to do */
6411         switch (status) {
6412         case SSL_TICKET_NO_DECRYPT:
6413             return SSL_TICKET_RETURN_IGNORE_RENEW;
6414
6415         case SSL_TICKET_SUCCESS:
6416             return SSL_TICKET_RETURN_USE;
6417
6418         case SSL_TICKET_SUCCESS_RENEW:
6419             return SSL_TICKET_RETURN_USE_RENEW;
6420
6421         default:
6422             return SSL_TICKET_RETURN_ABORT;
6423         }
6424     }
6425     return tick_dec_ret;
6426
6427 }
6428
6429 #ifndef OPENSSL_NO_DEPRECATED_3_0
6430 static int tick_key_cb(SSL *s, unsigned char key_name[16],
6431                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
6432                        HMAC_CTX *hctx, int enc)
6433 {
6434     const unsigned char tick_aes_key[16] = "0123456789abcdef";
6435     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
6436     EVP_CIPHER *aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
6437     EVP_MD *sha256 = EVP_MD_fetch(libctx, "SHA-256", NULL);
6438     int ret;
6439
6440     tick_key_cb_called = 1;
6441     memset(iv, 0, AES_BLOCK_SIZE);
6442     memset(key_name, 0, 16);
6443     if (aes128cbc == NULL
6444             || sha256 == NULL
6445             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
6446             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key), sha256,
6447                              NULL))
6448         ret = -1;
6449     else
6450         ret = tick_key_renew ? 2 : 1;
6451
6452     EVP_CIPHER_free(aes128cbc);
6453     EVP_MD_free(sha256);
6454
6455     return ret;
6456 }
6457 #endif
6458
6459 static int tick_key_evp_cb(SSL *s, unsigned char key_name[16],
6460                            unsigned char iv[EVP_MAX_IV_LENGTH],
6461                            EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int enc)
6462 {
6463     const unsigned char tick_aes_key[16] = "0123456789abcdef";
6464     unsigned char tick_hmac_key[16] = "0123456789abcdef";
6465     OSSL_PARAM params[3];
6466     EVP_CIPHER *aes128cbc = EVP_CIPHER_fetch(libctx, "AES-128-CBC", NULL);
6467     int ret;
6468
6469     tick_key_cb_called = 1;
6470     memset(iv, 0, AES_BLOCK_SIZE);
6471     memset(key_name, 0, 16);
6472     params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
6473                                                  "SHA256", 0);
6474     params[1] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
6475                                                   tick_hmac_key,
6476                                                   sizeof(tick_hmac_key));
6477     params[2] = OSSL_PARAM_construct_end();
6478     if (aes128cbc == NULL
6479             || !EVP_CipherInit_ex(ctx, aes128cbc, NULL, tick_aes_key, iv, enc)
6480             || !EVP_MAC_CTX_set_params(hctx, params)
6481             || !EVP_MAC_init(hctx))
6482         ret = -1;
6483     else
6484         ret = tick_key_renew ? 2 : 1;
6485
6486     EVP_CIPHER_free(aes128cbc);
6487
6488     return ret;
6489 }
6490
6491 /*
6492  * Test the various ticket callbacks
6493  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
6494  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
6495  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
6496  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
6497  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
6498  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
6499  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
6500  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
6501  * Test 8: TLSv1.2, old ticket key callback, ticket, no renewal
6502  * Test 9: TLSv1.3, old ticket key callback, ticket, no renewal
6503  * Test 10: TLSv1.2, old ticket key callback, ticket, renewal
6504  * Test 11: TLSv1.3, old ticket key callback, ticket, renewal
6505  * Test 12: TLSv1.2, ticket key callback, ticket, no renewal
6506  * Test 13: TLSv1.3, ticket key callback, ticket, no renewal
6507  * Test 14: TLSv1.2, ticket key callback, ticket, renewal
6508  * Test 15: TLSv1.3, ticket key callback, ticket, renewal
6509  */
6510 static int test_ticket_callbacks(int tst)
6511 {
6512     SSL_CTX *cctx = NULL, *sctx = NULL;
6513     SSL *clientssl = NULL, *serverssl = NULL;
6514     SSL_SESSION *clntsess = NULL;
6515     int testresult = 0;
6516
6517 #ifdef OPENSSL_NO_TLS1_2
6518     if (tst % 2 == 0)
6519         return 1;
6520 #endif
6521 #ifdef OPENSSL_NO_TLS1_3
6522     if (tst % 2 == 1)
6523         return 1;
6524 #endif
6525 #ifdef OPENSSL_NO_DEPRECATED_3_0
6526     if (tst >= 8 && tst <= 11)
6527         return 1;
6528 #endif
6529
6530     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
6531
6532     /* Which tests the ticket key callback should request renewal for */
6533     if (tst == 10 || tst == 11 || tst == 14 || tst == 15)
6534         tick_key_renew = 1;
6535     else
6536         tick_key_renew = 0;
6537
6538     /* Which tests the decrypt ticket callback should request renewal for */
6539     switch (tst) {
6540     case 0:
6541     case 1:
6542         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
6543         break;
6544
6545     case 2:
6546     case 3:
6547         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
6548         break;
6549
6550     case 4:
6551     case 5:
6552         tick_dec_ret = SSL_TICKET_RETURN_USE;
6553         break;
6554
6555     case 6:
6556     case 7:
6557         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
6558         break;
6559
6560     default:
6561         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
6562     }
6563
6564     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6565                                        TLS_client_method(),
6566                                        TLS1_VERSION,
6567                                        ((tst % 2) == 0) ? TLS1_2_VERSION
6568                                                         : TLS1_3_VERSION,
6569                                        &sctx, &cctx, cert, privkey)))
6570         goto end;
6571
6572     /*
6573      * We only want sessions to resume from tickets - not the session cache. So
6574      * switch the cache off.
6575      */
6576     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
6577         goto end;
6578
6579     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
6580                                                  NULL)))
6581         goto end;
6582
6583     if (tst >= 12) {
6584         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx, tick_key_evp_cb)))
6585             goto end;
6586 #ifndef OPENSSL_NO_DEPRECATED_3_0
6587     } else if (tst >= 8) {
6588         if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
6589             goto end;
6590 #endif
6591     }
6592
6593     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6594                                              NULL, NULL))
6595             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6596                                                 SSL_ERROR_NONE)))
6597         goto end;
6598
6599     /*
6600      * The decrypt ticket key callback in TLSv1.2 should be called even though
6601      * we have no ticket yet, because it gets called with a status of
6602      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
6603      * actually send any ticket data). This does not happen in TLSv1.3 because
6604      * it is not valid to send empty ticket data in TLSv1.3.
6605      */
6606     if (!TEST_int_eq(gen_tick_called, 1)
6607             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
6608         goto end;
6609
6610     gen_tick_called = dec_tick_called = 0;
6611
6612     clntsess = SSL_get1_session(clientssl);
6613     SSL_shutdown(clientssl);
6614     SSL_shutdown(serverssl);
6615     SSL_free(serverssl);
6616     SSL_free(clientssl);
6617     serverssl = clientssl = NULL;
6618
6619     /* Now do a resumption */
6620     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
6621                                       NULL))
6622             || !TEST_true(SSL_set_session(clientssl, clntsess))
6623             || !TEST_true(create_ssl_connection(serverssl, clientssl,
6624                                                 SSL_ERROR_NONE)))
6625         goto end;
6626
6627     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
6628             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW) {
6629         if (!TEST_false(SSL_session_reused(clientssl)))
6630             goto end;
6631     } else {
6632         if (!TEST_true(SSL_session_reused(clientssl)))
6633             goto end;
6634     }
6635
6636     if (!TEST_int_eq(gen_tick_called,
6637                      (tick_key_renew
6638                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
6639                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
6640                      ? 1 : 0)
6641             || !TEST_int_eq(dec_tick_called, 1))
6642         goto end;
6643
6644     testresult = 1;
6645
6646  end:
6647     SSL_SESSION_free(clntsess);
6648     SSL_free(serverssl);
6649     SSL_free(clientssl);
6650     SSL_CTX_free(sctx);
6651     SSL_CTX_free(cctx);
6652
6653     return testresult;
6654 }
6655
6656 /*
6657  * Test bi-directional shutdown.
6658  * Test 0: TLSv1.2
6659  * Test 1: TLSv1.2, server continues to read/write after client shutdown
6660  * Test 2: TLSv1.3, no pending NewSessionTicket messages
6661  * Test 3: TLSv1.3, pending NewSessionTicket messages
6662  * Test 4: TLSv1.3, server continues to read/write after client shutdown, server
6663  *                  sends key update, client reads it
6664  * Test 5: TLSv1.3, server continues to read/write after client shutdown, server
6665  *                  sends CertificateRequest, client reads and ignores it
6666  * Test 6: TLSv1.3, server continues to read/write after client shutdown, client
6667  *                  doesn't read it
6668  */
6669 static int test_shutdown(int tst)
6670 {
6671     SSL_CTX *cctx = NULL, *sctx = NULL;
6672     SSL *clientssl = NULL, *serverssl = NULL;
6673     int testresult = 0;
6674     char msg[] = "A test message";
6675     char buf[80];
6676     size_t written, readbytes;
6677     SSL_SESSION *sess;
6678
6679 #ifdef OPENSSL_NO_TLS1_2
6680     if (tst <= 1)
6681         return 1;
6682 #endif
6683 #ifdef OPENSSL_NO_TLS1_3
6684     if (tst >= 2)
6685         return 1;
6686 #endif
6687
6688     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6689                                        TLS_client_method(),
6690                                        TLS1_VERSION,
6691                                        (tst <= 1) ? TLS1_2_VERSION
6692                                                   : TLS1_3_VERSION,
6693                                        &sctx, &cctx, cert, privkey)))
6694         goto end;
6695
6696     if (tst == 5)
6697         SSL_CTX_set_post_handshake_auth(cctx, 1);
6698
6699     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6700                                              NULL, NULL)))
6701         goto end;
6702
6703     if (tst == 3) {
6704         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
6705                                                   SSL_ERROR_NONE, 1))
6706                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6707                 || !TEST_false(SSL_SESSION_is_resumable(sess)))
6708             goto end;
6709     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
6710                                               SSL_ERROR_NONE))
6711             || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6712             || !TEST_true(SSL_SESSION_is_resumable(sess))) {
6713         goto end;
6714     }
6715
6716     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
6717         goto end;
6718
6719     if (tst >= 4) {
6720         /*
6721          * Reading on the server after the client has sent close_notify should
6722          * fail and provide SSL_ERROR_ZERO_RETURN
6723          */
6724         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
6725                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
6726                                 SSL_ERROR_ZERO_RETURN)
6727                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
6728                                 SSL_RECEIVED_SHUTDOWN)
6729                    /*
6730                     * Even though we're shutdown on receive we should still be
6731                     * able to write.
6732                     */
6733                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
6734             goto end;
6735         if (tst == 4
6736                 && !TEST_true(SSL_key_update(serverssl,
6737                                              SSL_KEY_UPDATE_REQUESTED)))
6738             goto end;
6739         if (tst == 5) {
6740             SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
6741             if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
6742                 goto end;
6743         }
6744         if ((tst == 4 || tst == 5)
6745                 && !TEST_true(SSL_write(serverssl, msg, sizeof(msg))))
6746             goto end;
6747         if (!TEST_int_eq(SSL_shutdown(serverssl), 1))
6748             goto end;
6749         if (tst == 4 || tst == 5) {
6750             /* Should still be able to read data from server */
6751             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
6752                                        &readbytes))
6753                     || !TEST_size_t_eq(readbytes, sizeof(msg))
6754                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0)
6755                     || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
6756                                               &readbytes))
6757                     || !TEST_size_t_eq(readbytes, sizeof(msg))
6758                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
6759                 goto end;
6760         }
6761     }
6762
6763     /* Writing on the client after sending close_notify shouldn't be possible */
6764     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
6765         goto end;
6766
6767     if (tst < 4) {
6768         /*
6769          * For these tests the client has sent close_notify but it has not yet
6770          * been received by the server. The server has not sent close_notify
6771          * yet.
6772          */
6773         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
6774                    /*
6775                     * Writing on the server after sending close_notify shouldn't
6776                     * be possible.
6777                     */
6778                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
6779                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
6780                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6781                 || !TEST_true(SSL_SESSION_is_resumable(sess))
6782                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
6783             goto end;
6784     } else if (tst == 4 || tst == 5) {
6785         /*
6786          * In this test the client has sent close_notify and it has been
6787          * received by the server which has responded with a close_notify. The
6788          * client needs to read the close_notify sent by the server.
6789          */
6790         if (!TEST_int_eq(SSL_shutdown(clientssl), 1)
6791                 || !TEST_ptr_ne(sess = SSL_get_session(clientssl), NULL)
6792                 || !TEST_true(SSL_SESSION_is_resumable(sess)))
6793             goto end;
6794     } else {
6795         /*
6796          * tst == 6
6797          *
6798          * The client has sent close_notify and is expecting a close_notify
6799          * back, but instead there is application data first. The shutdown
6800          * should fail with a fatal error.
6801          */
6802         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
6803                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
6804             goto end;
6805     }
6806
6807     testresult = 1;
6808
6809  end:
6810     SSL_free(serverssl);
6811     SSL_free(clientssl);
6812     SSL_CTX_free(sctx);
6813     SSL_CTX_free(cctx);
6814
6815     return testresult;
6816 }
6817
6818 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
6819 static int cert_cb_cnt;
6820
6821 static int cert_cb(SSL *s, void *arg)
6822 {
6823     SSL_CTX *ctx = (SSL_CTX *)arg;
6824     BIO *in = NULL;
6825     EVP_PKEY *pkey = NULL;
6826     X509 *x509 = NULL, *rootx = NULL;
6827     STACK_OF(X509) *chain = NULL;
6828     char *rootfile = NULL, *ecdsacert = NULL, *ecdsakey = NULL;
6829     int ret = 0;
6830
6831     if (cert_cb_cnt == 0) {
6832         /* Suspend the handshake */
6833         cert_cb_cnt++;
6834         return -1;
6835     } else if (cert_cb_cnt == 1) {
6836         /*
6837          * Update the SSL_CTX, set the certificate and private key and then
6838          * continue the handshake normally.
6839          */
6840         if (ctx != NULL && !TEST_ptr(SSL_set_SSL_CTX(s, ctx)))
6841             return 0;
6842
6843         if (!TEST_true(SSL_use_certificate_file(s, cert, SSL_FILETYPE_PEM))
6844                 || !TEST_true(SSL_use_PrivateKey_file(s, privkey,
6845                                                       SSL_FILETYPE_PEM))
6846                 || !TEST_true(SSL_check_private_key(s)))
6847             return 0;
6848         cert_cb_cnt++;
6849         return 1;
6850     } else if (cert_cb_cnt == 3) {
6851         int rv;
6852
6853         rootfile = test_mk_file_path(certsdir, "rootcert.pem");
6854         ecdsacert = test_mk_file_path(certsdir, "server-ecdsa-cert.pem");
6855         ecdsakey = test_mk_file_path(certsdir, "server-ecdsa-key.pem");
6856         if (!TEST_ptr(rootfile) || !TEST_ptr(ecdsacert) || !TEST_ptr(ecdsakey))
6857             goto out;
6858         chain = sk_X509_new_null();
6859         if (!TEST_ptr(chain))
6860             goto out;
6861         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6862                 || !TEST_int_ge(BIO_read_filename(in, rootfile), 0)
6863                 || !TEST_ptr(rootx = PEM_read_bio_X509(in, NULL, NULL, NULL))
6864                 || !TEST_true(sk_X509_push(chain, rootx)))
6865             goto out;
6866         rootx = NULL;
6867         BIO_free(in);
6868         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6869                 || !TEST_int_ge(BIO_read_filename(in, ecdsacert), 0)
6870                 || !TEST_ptr(x509 = PEM_read_bio_X509(in, NULL, NULL, NULL)))
6871             goto out;
6872         BIO_free(in);
6873         if (!TEST_ptr(in = BIO_new(BIO_s_file()))
6874                 || !TEST_int_ge(BIO_read_filename(in, ecdsakey), 0)
6875                 || !TEST_ptr(pkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL)))
6876             goto out;
6877         rv = SSL_check_chain(s, x509, pkey, chain);
6878         /*
6879          * If the cert doesn't show as valid here (e.g., because we don't
6880          * have any shared sigalgs), then we will not set it, and there will
6881          * be no certificate at all on the SSL or SSL_CTX.  This, in turn,
6882          * will cause tls_choose_sigalgs() to fail the connection.
6883          */
6884         if ((rv & (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE))
6885                 == (CERT_PKEY_VALID | CERT_PKEY_CA_SIGNATURE)) {
6886             if (!SSL_use_cert_and_key(s, x509, pkey, NULL, 1))
6887                 goto out;
6888         }
6889
6890         ret = 1;
6891     }
6892
6893     /* Abort the handshake */
6894  out:
6895     OPENSSL_free(ecdsacert);
6896     OPENSSL_free(ecdsakey);
6897     OPENSSL_free(rootfile);
6898     BIO_free(in);
6899     EVP_PKEY_free(pkey);
6900     X509_free(x509);
6901     X509_free(rootx);
6902     sk_X509_pop_free(chain, X509_free);
6903     return ret;
6904 }
6905
6906 /*
6907  * Test the certificate callback.
6908  * Test 0: Callback fails
6909  * Test 1: Success - no SSL_set_SSL_CTX() in the callback
6910  * Test 2: Success - SSL_set_SSL_CTX() in the callback
6911  * Test 3: Success - Call SSL_check_chain from the callback
6912  * Test 4: Failure - SSL_check_chain fails from callback due to bad cert in the
6913  *                   chain
6914  * Test 5: Failure - SSL_check_chain fails from callback due to bad ee cert
6915  */
6916 static int test_cert_cb_int(int prot, int tst)
6917 {
6918     SSL_CTX *cctx = NULL, *sctx = NULL, *snictx = NULL;
6919     SSL *clientssl = NULL, *serverssl = NULL;
6920     int testresult = 0, ret;
6921
6922 #ifdef OPENSSL_NO_EC
6923     /* We use an EC cert in these tests, so we skip in a no-ec build */
6924     if (tst >= 3)
6925         return 1;
6926 #endif
6927
6928     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
6929                                        TLS_client_method(),
6930                                        TLS1_VERSION,
6931                                        prot,
6932                                        &sctx, &cctx, NULL, NULL)))
6933         goto end;
6934
6935     if (tst == 0)
6936         cert_cb_cnt = -1;
6937     else if (tst >= 3)
6938         cert_cb_cnt = 3;
6939     else
6940         cert_cb_cnt = 0;
6941
6942     if (tst == 2)
6943         snictx = SSL_CTX_new(TLS_server_method());
6944     SSL_CTX_set_cert_cb(sctx, cert_cb, snictx);
6945
6946     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
6947                                       NULL, NULL)))
6948         goto end;
6949
6950     if (tst == 4) {
6951         /*
6952          * We cause SSL_check_chain() to fail by specifying sig_algs that
6953          * the chain doesn't meet (the root uses an RSA cert)
6954          */
6955         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6956                                              "ecdsa_secp256r1_sha256")))
6957             goto end;
6958     } else if (tst == 5) {
6959         /*
6960          * We cause SSL_check_chain() to fail by specifying sig_algs that
6961          * the ee cert doesn't meet (the ee uses an ECDSA cert)
6962          */
6963         if (!TEST_true(SSL_set1_sigalgs_list(clientssl,
6964                            "rsa_pss_rsae_sha256:rsa_pkcs1_sha256")))
6965             goto end;
6966     }
6967
6968     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
6969     if (!TEST_true(tst == 0 || tst == 4 || tst == 5 ? !ret : ret)
6970             || (tst > 0
6971                 && !TEST_int_eq((cert_cb_cnt - 2) * (cert_cb_cnt - 3), 0))) {
6972         goto end;
6973     }
6974
6975     testresult = 1;
6976
6977  end:
6978     SSL_free(serverssl);
6979     SSL_free(clientssl);
6980     SSL_CTX_free(sctx);
6981     SSL_CTX_free(cctx);
6982     SSL_CTX_free(snictx);
6983
6984     return testresult;
6985 }
6986 #endif
6987
6988 static int test_cert_cb(int tst)
6989 {
6990     int testresult = 1;
6991
6992 #ifndef OPENSSL_NO_TLS1_2
6993     testresult &= test_cert_cb_int(TLS1_2_VERSION, tst);
6994 #endif
6995 #ifndef OPENSSL_NO_TLS1_3
6996     testresult &= test_cert_cb_int(TLS1_3_VERSION, tst);
6997 #endif
6998
6999     return testresult;
7000 }
7001
7002 static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
7003 {
7004     X509 *xcert, *peer;
7005     EVP_PKEY *privpkey;
7006     BIO *in = NULL;
7007
7008     /* Check that SSL_get_peer_certificate() returns something sensible */
7009     peer = SSL_get_peer_certificate(ssl);
7010     if (!TEST_ptr(peer))
7011         return 0;
7012     X509_free(peer);
7013
7014     in = BIO_new_file(cert, "r");
7015     if (!TEST_ptr(in))
7016         return 0;
7017
7018     xcert = PEM_read_bio_X509(in, NULL, NULL, NULL);
7019     BIO_free(in);
7020     if (!TEST_ptr(xcert))
7021         return 0;
7022
7023     in = BIO_new_file(privkey, "r");
7024     if (!TEST_ptr(in)) {
7025         X509_free(xcert);
7026         return 0;
7027     }
7028
7029     privpkey = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
7030     BIO_free(in);
7031     if (!TEST_ptr(privpkey)) {
7032         X509_free(xcert);
7033         return 0;
7034     }
7035
7036     *x509 = xcert;
7037     *pkey = privpkey;
7038
7039     return 1;
7040 }
7041
7042 static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
7043 {
7044     return 1;
7045 }
7046
7047 static int test_client_cert_cb(int tst)
7048 {
7049     SSL_CTX *cctx = NULL, *sctx = NULL;
7050     SSL *clientssl = NULL, *serverssl = NULL;
7051     int testresult = 0;
7052
7053 #ifdef OPENSSL_NO_TLS1_2
7054     if (tst == 0)
7055         return 1;
7056 #endif
7057 #ifdef OPENSSL_NO_TLS1_3
7058     if (tst == 1)
7059         return 1;
7060 #endif
7061
7062     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7063                                        TLS_client_method(),
7064                                        TLS1_VERSION,
7065                                        tst == 0 ? TLS1_2_VERSION
7066                                                 : TLS1_3_VERSION,
7067                                        &sctx, &cctx, cert, privkey)))
7068         goto end;
7069
7070     /*
7071      * Test that setting a client_cert_cb results in a client certificate being
7072      * sent.
7073      */
7074     SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
7075     SSL_CTX_set_verify(sctx,
7076                        SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
7077                        verify_cb);
7078
7079     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7080                                       NULL, NULL))
7081             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7082                                                 SSL_ERROR_NONE)))
7083         goto end;
7084
7085     testresult = 1;
7086
7087  end:
7088     SSL_free(serverssl);
7089     SSL_free(clientssl);
7090     SSL_CTX_free(sctx);
7091     SSL_CTX_free(cctx);
7092
7093     return testresult;
7094 }
7095
7096 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OPENSSL_NO_TLS1_3)
7097 /*
7098  * Test setting certificate authorities on both client and server.
7099  *
7100  * Test 0: SSL_CTX_set0_CA_list() only
7101  * Test 1: Both SSL_CTX_set0_CA_list() and SSL_CTX_set_client_CA_list()
7102  * Test 2: Only SSL_CTX_set_client_CA_list()
7103  */
7104 static int test_ca_names_int(int prot, int tst)
7105 {
7106     SSL_CTX *cctx = NULL, *sctx = NULL;
7107     SSL *clientssl = NULL, *serverssl = NULL;
7108     int testresult = 0;
7109     size_t i;
7110     X509_NAME *name[] = { NULL, NULL, NULL, NULL };
7111     char *strnames[] = { "Jack", "Jill", "John", "Joanne" };
7112     STACK_OF(X509_NAME) *sk1 = NULL, *sk2 = NULL;
7113     const STACK_OF(X509_NAME) *sktmp = NULL;
7114
7115     for (i = 0; i < OSSL_NELEM(name); i++) {
7116         name[i] = X509_NAME_new();
7117         if (!TEST_ptr(name[i])
7118                 || !TEST_true(X509_NAME_add_entry_by_txt(name[i], "CN",
7119                                                          MBSTRING_ASC,
7120                                                          (unsigned char *)
7121                                                          strnames[i],
7122                                                          -1, -1, 0)))
7123             goto end;
7124     }
7125
7126     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7127                                        TLS_client_method(),
7128                                        TLS1_VERSION,
7129                                        prot,
7130                                        &sctx, &cctx, cert, privkey)))
7131         goto end;
7132
7133     SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);
7134
7135     if (tst == 0 || tst == 1) {
7136         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
7137                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[0])))
7138                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[1])))
7139                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
7140                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[0])))
7141                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[1]))))
7142             goto end;
7143
7144         SSL_CTX_set0_CA_list(sctx, sk1);
7145         SSL_CTX_set0_CA_list(cctx, sk2);
7146         sk1 = sk2 = NULL;
7147     }
7148     if (tst == 1 || tst == 2) {
7149         if (!TEST_ptr(sk1 = sk_X509_NAME_new_null())
7150                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[2])))
7151                 || !TEST_true(sk_X509_NAME_push(sk1, X509_NAME_dup(name[3])))
7152                 || !TEST_ptr(sk2 = sk_X509_NAME_new_null())
7153                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[2])))
7154                 || !TEST_true(sk_X509_NAME_push(sk2, X509_NAME_dup(name[3]))))
7155             goto end;
7156
7157         SSL_CTX_set_client_CA_list(sctx, sk1);
7158         SSL_CTX_set_client_CA_list(cctx, sk2);
7159         sk1 = sk2 = NULL;
7160     }
7161
7162     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7163                                       NULL, NULL))
7164             || !TEST_true(create_ssl_connection(serverssl, clientssl,
7165                                                 SSL_ERROR_NONE)))
7166         goto end;
7167
7168     /*
7169      * We only expect certificate authorities to have been sent to the server
7170      * if we are using TLSv1.3 and SSL_set0_CA_list() was used
7171      */
7172     sktmp = SSL_get0_peer_CA_list(serverssl);
7173     if (prot == TLS1_3_VERSION
7174             && (tst == 0 || tst == 1)) {
7175         if (!TEST_ptr(sktmp)
7176                 || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
7177                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
7178                                               name[0]), 0)
7179                 || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
7180                                               name[1]), 0))
7181             goto end;
7182     } else if (!TEST_ptr_null(sktmp)) {
7183         goto end;
7184     }
7185
7186     /*
7187      * In all tests we expect certificate authorities to have been sent to the
7188      * client. However, SSL_set_client_CA_list() should override
7189      * SSL_set0_CA_list()
7190      */
7191     sktmp = SSL_get0_peer_CA_list(clientssl);
7192     if (!TEST_ptr(sktmp)
7193             || !TEST_int_eq(sk_X509_NAME_num(sktmp), 2)
7194             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 0),
7195                                           name[tst == 0 ? 0 : 2]), 0)
7196             || !TEST_int_eq(X509_NAME_cmp(sk_X509_NAME_value(sktmp, 1),
7197                                           name[tst == 0 ? 1 : 3]), 0))
7198         goto end;
7199
7200     testresult = 1;
7201
7202  end:
7203     SSL_free(serverssl);
7204     SSL_free(clientssl);
7205     SSL_CTX_free(sctx);
7206     SSL_CTX_free(cctx);
7207     for (i = 0; i < OSSL_NELEM(name); i++)
7208         X509_NAME_free(name[i]);
7209     sk_X509_NAME_pop_free(sk1, X509_NAME_free);
7210     sk_X509_NAME_pop_free(sk2, X509_NAME_free);
7211
7212     return testresult;
7213 }
7214 #endif
7215
7216 static int test_ca_names(int tst)
7217 {
7218     int testresult = 1;
7219
7220 #ifndef OPENSSL_NO_TLS1_2
7221     testresult &= test_ca_names_int(TLS1_2_VERSION, tst);
7222 #endif
7223 #ifndef OPENSSL_NO_TLS1_3
7224     testresult &= test_ca_names_int(TLS1_3_VERSION, tst);
7225 #endif
7226
7227     return testresult;
7228 }
7229
7230 #ifndef OPENSSL_NO_TLS1_2
7231 static const char *multiblock_cipherlist_data[]=
7232 {
7233     "AES128-SHA",
7234     "AES128-SHA256",
7235     "AES256-SHA",
7236     "AES256-SHA256",
7237 };
7238
7239 /* Reduce the fragment size - so the multiblock test buffer can be small */
7240 # define MULTIBLOCK_FRAGSIZE 512
7241
7242 static int test_multiblock_write(int test_index)
7243 {
7244     static const char *fetchable_ciphers[]=
7245     {
7246         "AES-128-CBC-HMAC-SHA1",
7247         "AES-128-CBC-HMAC-SHA256",
7248         "AES-256-CBC-HMAC-SHA1",
7249         "AES-256-CBC-HMAC-SHA256"
7250     };
7251     const char *cipherlist = multiblock_cipherlist_data[test_index];
7252     const SSL_METHOD *smeth = TLS_server_method();
7253     const SSL_METHOD *cmeth = TLS_client_method();
7254     int min_version = TLS1_VERSION;
7255     int max_version = TLS1_2_VERSION; /* Don't select TLS1_3 */
7256     SSL_CTX *cctx = NULL, *sctx = NULL;
7257     SSL *clientssl = NULL, *serverssl = NULL;
7258     int testresult = 0;
7259
7260     /*
7261      * Choose a buffer large enough to perform a multi-block operation
7262      * i.e: write_len >= 4 * frag_size
7263      * 9 * is chosen so that multiple multiblocks are used + some leftover.
7264      */
7265     unsigned char msg[MULTIBLOCK_FRAGSIZE * 9];
7266     unsigned char buf[sizeof(msg)], *p = buf;
7267     size_t readbytes, written, len;
7268     EVP_CIPHER *ciph = NULL;
7269
7270     /*
7271      * Check if the cipher exists before attempting to use it since it only has
7272      * a hardware specific implementation.
7273      */
7274     ciph = EVP_CIPHER_fetch(NULL, fetchable_ciphers[test_index], "");
7275     if (ciph == NULL) {
7276         TEST_skip("Multiblock cipher is not available for %s", cipherlist);
7277         return 1;
7278     }
7279     EVP_CIPHER_free(ciph);
7280
7281     /* Set up a buffer with some data that will be sent to the client */
7282     RAND_bytes(msg, sizeof(msg));
7283
7284     if (!TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, min_version,
7285                                        max_version, &sctx, &cctx, cert,
7286                                        privkey)))
7287         goto end;
7288
7289     if (!TEST_true(SSL_CTX_set_max_send_fragment(sctx, MULTIBLOCK_FRAGSIZE)))
7290         goto end;
7291
7292     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7293                                       NULL, NULL)))
7294             goto end;
7295
7296     /* settings to force it to use AES-CBC-HMAC_SHA */
7297     SSL_set_options(serverssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
7298     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, cipherlist)))
7299        goto end;
7300
7301     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
7302         goto end;
7303
7304     if (!TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
7305         || !TEST_size_t_eq(written, sizeof(msg)))
7306         goto end;
7307
7308     len = written;
7309     while (len > 0) {
7310         if (!TEST_true(SSL_read_ex(clientssl, p, MULTIBLOCK_FRAGSIZE, &readbytes)))
7311             goto end;
7312         p += readbytes;
7313         len -= readbytes;
7314     }
7315     if (!TEST_mem_eq(msg, sizeof(msg), buf, sizeof(buf)))
7316         goto end;
7317
7318     testresult = 1;
7319 end:
7320     SSL_free(serverssl);
7321     SSL_free(clientssl);
7322     SSL_CTX_free(sctx);
7323     SSL_CTX_free(cctx);
7324
7325     return testresult;
7326 }
7327 #endif /* OPENSSL_NO_TLS1_2 */
7328
7329 /*
7330  * Test 0: Client sets servername and server acknowledges it (TLSv1.2)
7331  * Test 1: Client sets servername and server does not acknowledge it (TLSv1.2)
7332  * Test 2: Client sets inconsistent servername on resumption (TLSv1.2)
7333  * Test 3: Client does not set servername on initial handshake (TLSv1.2)
7334  * Test 4: Client does not set servername on resumption handshake (TLSv1.2)
7335  * Test 5: Client sets servername and server acknowledges it (TLSv1.3)
7336  * Test 6: Client sets servername and server does not acknowledge it (TLSv1.3)
7337  * Test 7: Client sets inconsistent servername on resumption (TLSv1.3)
7338  * Test 8: Client does not set servername on initial handshake(TLSv1.3)
7339  * Test 9: Client does not set servername on resumption handshake (TLSv1.3)
7340  */
7341 static int test_servername(int tst)
7342 {
7343     SSL_CTX *cctx = NULL, *sctx = NULL;
7344     SSL *clientssl = NULL, *serverssl = NULL;
7345     int testresult = 0;
7346     SSL_SESSION *sess = NULL;
7347     const char *sexpectedhost = NULL, *cexpectedhost = NULL;
7348
7349 #ifdef OPENSSL_NO_TLS1_2
7350     if (tst <= 4)
7351         return 1;
7352 #endif
7353 #ifdef OPENSSL_NO_TLS1_3
7354     if (tst >= 5)
7355         return 1;
7356 #endif
7357
7358     if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
7359                                        TLS_client_method(),
7360                                        TLS1_VERSION,
7361                                        (tst <= 4) ? TLS1_2_VERSION
7362                                                   : TLS1_3_VERSION,
7363                                        &sctx, &cctx, cert, privkey))
7364             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
7365                                              NULL, NULL)))
7366         goto end;
7367
7368     if (tst != 1 && tst != 6) {
7369         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
7370                                                               hostname_cb)))
7371             goto end;
7372     }
7373
7374     if (tst != 3 && tst != 8) {
7375         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
7376             goto end;
7377         sexpectedhost = cexpectedhost = "goodhost";
7378     }
7379
7380     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
7381         goto end;
7382
7383     if (!TEST_str_eq(SSL_get_servername(clientssl, TLSEXT_NAMETYPE_host_name),
7384                      cexpectedhost)
7385             || !TEST_str_eq(SSL_get_servername(serverssl,
7386                                                TLSEXT_NAMETYPE_host_name),
7387                             sexpectedhost))
7388         goto end;
7389
7390     /* Now repeat with a resumption handshake */
7391
7392     if (!TEST_int_eq(SSL_shutdown(clientssl), 0)
7393             || !TEST_ptr_ne(sess = SSL_get1_session(clientssl), NULL)
7394             || !TEST_true(SSL_SESSION_is_resumable(sess))
7395             || !TEST_int_eq(SSL_shutdown(serverssl), 0))
7396         goto end;
7397
7398     SSL_free(clientssl);
7399     SSL_free(serverssl);
7400     clientssl = serverssl = NULL;
7401
7402     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
7403                                       NULL)))
7404         goto end;
7405
7406     if (!TEST_true(SSL_set_session(clientssl, sess)))
7407         goto end;
7408
7409     sexpectedhost = cexpectedhost = "goodhost";
7410     if (tst == 2 || tst == 7) {
7411         /* Set an inconsistent hostname */
7412         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "altgoodhost")))
7413             goto end;
7414         /*
7415          * In TLSv1.2 we expect the hostname from the original handshake, in
7416          * TLSv1.3 we expect the hostname from this handshake
7417          */
7418         if (tst == 7)
7419             sexpectedhost = cexpectedhost = "altgoodhost";
7420
7421         if (!TEST_str_eq(SSL_get_servername(clientssl,
7422                                             TLSEXT_NAMETYPE_host_name),
7423                          "altgoodhost"))
7424             goto end;
7425     } else if (tst == 4 || tst == 9) {
7426         /*
7427          * A TLSv1.3 session does not associate a session with a servername,
7428          * but a TLSv1.2 session does.
7429          */
7430         if (tst == 9)
7431             sexpectedhost = cexpectedhost = NULL;
7432
7433         if (!TEST_str_eq(SSL_get_servername(clientssl,
7434                                             TLSEXT_NAMETYPE_host_name),
7435                          cexpectedhost))
7436             goto end;
7437     } else {
7438         if (!TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost")))
7439             goto end;
7440         /*
7441          * In a TLSv1.2 resumption where the hostname was not acknowledged
7442          * we expect the hostname on the server to be empty. On the client we
7443          * return what was requested in this case.
7444          *
7445          * Similarly if the client didn't set a hostname on an original TLSv1.2
7446          * session but is now, the server hostname will be empty, but the client
7447          * is as we set it.
7448          */
7449         if (tst == 1 || tst == 3)
7450             sexpectedhost = NULL;
7451
7452         if (!TEST_str_eq(SSL_get_servername(clientssl,
7453                                             TLSEXT_NAMETYPE_host_name),
7454                          "goodhost"))
7455             goto end;
7456     }
7457
7458     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
7459         goto end;
7460
7461     if (!TEST_true(SSL_session_reused(clientssl))
7462             || !TEST_true(SSL_session_reused(serverssl))
7463             || !TEST_str_eq(SSL_get_servername(clientssl,
7464                                                TLSEXT_NAMETYPE_host_name),
7465                             cexpectedhost)
7466             || !TEST_str_eq(SSL_get_servername(serverssl,
7467                                                TLSEXT_NAMETYPE_host_name),
7468                             sexpectedhost))
7469         goto end;
7470
7471     testresult = 1;
7472
7473  end:
7474     SSL_SESSION_free(sess);
7475     SSL_free(serverssl);
7476     SSL_free(clientssl);
7477     SSL_CTX_free(sctx);
7478     SSL_CTX_free(cctx);
7479
7480     return testresult;
7481 }
7482
7483 OPT_TEST_DECLARE_USAGE("certfile privkeyfile srpvfile tmpfile provider config\n")
7484
7485 int setup_tests(void)
7486 {
7487     char *modulename;
7488     char *configfile;
7489
7490     libctx = OPENSSL_CTX_new();
7491     if (!TEST_ptr(libctx))
7492         return 0;
7493
7494     defctxnull = OSSL_PROVIDER_load(NULL, "null");
7495
7496     /*
7497      * Verify that the default and fips providers in the default libctx are not
7498      * available
7499      */
7500     if (!TEST_false(OSSL_PROVIDER_available(NULL, "default"))
7501             || !TEST_false(OSSL_PROVIDER_available(NULL, "fips")))
7502         return 0;
7503
7504     if (!test_skip_common_options()) {
7505         TEST_error("Error parsing test options\n");
7506         return 0;
7507     }
7508
7509     if (!TEST_ptr(certsdir = test_get_argument(0))
7510             || !TEST_ptr(srpvfile = test_get_argument(1))
7511             || !TEST_ptr(tmpfilename = test_get_argument(2))
7512             || !TEST_ptr(modulename = test_get_argument(3))
7513             || !TEST_ptr(configfile = test_get_argument(4)))
7514         return 0;
7515
7516     if (!TEST_true(OPENSSL_CTX_load_config(libctx, configfile)))
7517         return 0;
7518
7519     /* Check we have the expected provider available */
7520     if (!TEST_true(OSSL_PROVIDER_available(libctx, modulename)))
7521         return 0;
7522
7523     /* Check the default provider is not available */
7524     if (strcmp(modulename, "default") != 0
7525             && !TEST_false(OSSL_PROVIDER_available(libctx, "default")))
7526         return 0;
7527
7528     if (strcmp(modulename, "fips") == 0)
7529         is_fips = 1;
7530
7531     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
7532 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
7533         TEST_error("not supported in this build");
7534         return 0;
7535 #else
7536         int i, mcount, rcount, fcount;
7537
7538         for (i = 0; i < 4; i++)
7539             test_export_key_mat(i);
7540         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
7541         test_printf_stdout("malloc %d realloc %d free %d\n",
7542                 mcount, rcount, fcount);
7543         return 1;
7544 #endif
7545     }
7546
7547     cert = test_mk_file_path(certsdir, "servercert.pem");
7548     if (cert == NULL)
7549         return 0;
7550
7551     privkey = test_mk_file_path(certsdir, "serverkey.pem");
7552     if (privkey == NULL) {
7553         OPENSSL_free(cert);
7554         return 0;
7555     }
7556
7557 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_KTLS) \
7558     && !defined(OPENSSL_NO_SOCK)
7559     ADD_TEST(test_ktls_no_txrx_client_no_txrx_server);
7560     ADD_TEST(test_ktls_no_rx_client_no_txrx_server);
7561     ADD_TEST(test_ktls_no_tx_client_no_txrx_server);
7562     ADD_TEST(test_ktls_client_no_txrx_server);
7563     ADD_TEST(test_ktls_no_txrx_client_no_rx_server);
7564     ADD_TEST(test_ktls_no_rx_client_no_rx_server);
7565     ADD_TEST(test_ktls_no_tx_client_no_rx_server);
7566     ADD_TEST(test_ktls_client_no_rx_server);
7567     ADD_TEST(test_ktls_no_txrx_client_no_tx_server);
7568     ADD_TEST(test_ktls_no_rx_client_no_tx_server);
7569     ADD_TEST(test_ktls_no_tx_client_no_tx_server);
7570     ADD_TEST(test_ktls_client_no_tx_server);
7571     ADD_TEST(test_ktls_no_txrx_client_server);
7572     ADD_TEST(test_ktls_no_rx_client_server);
7573     ADD_TEST(test_ktls_no_tx_client_server);
7574     ADD_TEST(test_ktls_client_server);
7575     ADD_TEST(test_ktls_sendfile);
7576 #endif
7577     ADD_TEST(test_large_message_tls);
7578     ADD_TEST(test_large_message_tls_read_ahead);
7579 #ifndef OPENSSL_NO_DTLS
7580     ADD_TEST(test_large_message_dtls);
7581 #endif
7582 #ifndef OPENSSL_NO_OCSP
7583     ADD_TEST(test_tlsext_status_type);
7584 #endif
7585     ADD_TEST(test_session_with_only_int_cache);
7586     ADD_TEST(test_session_with_only_ext_cache);
7587     ADD_TEST(test_session_with_both_cache);
7588 #ifndef OPENSSL_NO_TLS1_3
7589     ADD_ALL_TESTS(test_stateful_tickets, 3);
7590     ADD_ALL_TESTS(test_stateless_tickets, 3);
7591     ADD_TEST(test_psk_tickets);
7592     ADD_ALL_TESTS(test_extra_tickets, 6);
7593 #endif
7594     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
7595     ADD_TEST(test_ssl_bio_pop_next_bio);
7596     ADD_TEST(test_ssl_bio_pop_ssl_bio);
7597     ADD_TEST(test_ssl_bio_change_rbio);
7598     ADD_TEST(test_ssl_bio_change_wbio);
7599 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
7600     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
7601     ADD_TEST(test_keylog);
7602 #endif
7603 #ifndef OPENSSL_NO_TLS1_3
7604     ADD_TEST(test_keylog_no_master_key);
7605 #endif
7606 #ifndef OPENSSL_NO_TLS1_2
7607     ADD_TEST(test_client_hello_cb);
7608     ADD_TEST(test_no_ems);
7609     ADD_TEST(test_ccs_change_cipher);
7610 #endif
7611 #ifndef OPENSSL_NO_TLS1_3
7612     ADD_ALL_TESTS(test_early_data_read_write, 3);
7613     /*
7614      * We don't do replay tests for external PSK. Replay protection isn't used
7615      * in that scenario.
7616      */
7617     ADD_ALL_TESTS(test_early_data_replay, 2);
7618     ADD_ALL_TESTS(test_early_data_skip, 3);
7619     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
7620     ADD_ALL_TESTS(test_early_data_skip_hrr_fail, 3);
7621     ADD_ALL_TESTS(test_early_data_skip_abort, 3);
7622     ADD_ALL_TESTS(test_early_data_not_sent, 3);
7623     ADD_ALL_TESTS(test_early_data_psk, 8);
7624     ADD_ALL_TESTS(test_early_data_not_expected, 3);
7625 # ifndef OPENSSL_NO_TLS1_2
7626     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
7627 # endif
7628 #endif
7629 #ifndef OPENSSL_NO_TLS1_3
7630     ADD_ALL_TESTS(test_set_ciphersuite, 10);
7631     ADD_TEST(test_ciphersuite_change);
7632     ADD_ALL_TESTS(test_tls13_ciphersuite, 4);
7633 # ifdef OPENSSL_NO_PSK
7634     ADD_ALL_TESTS(test_tls13_psk, 1);
7635 # else
7636     ADD_ALL_TESTS(test_tls13_psk, 4);
7637 # endif  /* OPENSSL_NO_PSK */
7638 # ifndef OPENSSL_NO_TLS1_2
7639     /* Test with both TLSv1.3 and 1.2 versions */
7640     ADD_ALL_TESTS(test_key_exchange, 14);
7641 # else
7642     /* Test with only TLSv1.3 versions */
7643     ADD_ALL_TESTS(test_key_exchange, 12);
7644 # endif
7645     ADD_ALL_TESTS(test_custom_exts, 5);
7646     ADD_TEST(test_stateless);
7647     ADD_TEST(test_pha_key_update);
7648 #else
7649     ADD_ALL_TESTS(test_custom_exts, 3);
7650 #endif
7651     ADD_ALL_TESTS(test_serverinfo, 8);
7652     ADD_ALL_TESTS(test_export_key_mat, 6);
7653 #ifndef OPENSSL_NO_TLS1_3
7654     ADD_ALL_TESTS(test_export_key_mat_early, 3);
7655     ADD_TEST(test_key_update);
7656     ADD_ALL_TESTS(test_key_update_in_write, 2);
7657 #endif
7658     ADD_ALL_TESTS(test_ssl_clear, 2);
7659     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
7660 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
7661     ADD_ALL_TESTS(test_srp, 6);
7662 #endif
7663     ADD_ALL_TESTS(test_info_callback, 6);
7664     ADD_ALL_TESTS(test_ssl_pending, 2);
7665     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
7666     ADD_ALL_TESTS(test_ticket_callbacks, 16);
7667     ADD_ALL_TESTS(test_shutdown, 7);
7668     ADD_ALL_TESTS(test_cert_cb, 6);
7669     ADD_ALL_TESTS(test_client_cert_cb, 2);
7670     ADD_ALL_TESTS(test_ca_names, 3);
7671 #ifndef OPENSSL_NO_TLS1_2
7672     ADD_ALL_TESTS(test_multiblock_write, OSSL_NELEM(multiblock_cipherlist_data));
7673 #endif
7674     ADD_ALL_TESTS(test_servername, 10);
7675     return 1;
7676 }
7677
7678 void cleanup_tests(void)
7679 {
7680     OPENSSL_free(cert);
7681     OPENSSL_free(privkey);
7682     bio_s_mempacket_test_free();
7683     bio_s_always_retry_free();
7684     OSSL_PROVIDER_unload(defctxnull);
7685     OPENSSL_CTX_free(libctx);
7686 }