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