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