cdac8bc4549d912d64051c449f985397e8788891
[openssl.git] / test / sslapitest.c
1 /*
2  * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 #include <string.h>
11
12 #include <openssl/opensslconf.h>
13 #include <openssl/bio.h>
14 #include <openssl/crypto.h>
15 #include <openssl/ssl.h>
16 #include <openssl/ocsp.h>
17 #include <openssl/srp.h>
18 #include <openssl/txt_db.h>
19 #include <openssl/aes.h>
20
21 #include "ssltestlib.h"
22 #include "testutil.h"
23 #include "testutil/output.h"
24 #include "internal/nelem.h"
25 #include "../ssl/ssl_locl.h"
26
27 static char *cert = NULL;
28 static char *privkey = NULL;
29 static char *srpvfile = NULL;
30 static char *tmpfilename = NULL;
31
32 #define LOG_BUFFER_SIZE 2048
33 static char server_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
34 static size_t server_log_buffer_index = 0;
35 static char client_log_buffer[LOG_BUFFER_SIZE + 1] = {0};
36 static size_t client_log_buffer_index = 0;
37 static int error_writing_log = 0;
38
39 #ifndef OPENSSL_NO_OCSP
40 static const unsigned char orespder[] = "Dummy OCSP Response";
41 static int ocsp_server_called = 0;
42 static int ocsp_client_called = 0;
43
44 static int cdummyarg = 1;
45 static X509 *ocspcert = NULL;
46 #endif
47
48 #define NUM_EXTRA_CERTS 40
49 #define CLIENT_VERSION_LEN      2
50
51 /*
52  * This structure is used to validate that the correct number of log messages
53  * of various types are emitted when emitting secret logs.
54  */
55 struct sslapitest_log_counts {
56     unsigned int rsa_key_exchange_count;
57     unsigned int master_secret_count;
58     unsigned int client_early_secret_count;
59     unsigned int client_handshake_secret_count;
60     unsigned int server_handshake_secret_count;
61     unsigned int client_application_secret_count;
62     unsigned int server_application_secret_count;
63     unsigned int early_exporter_secret_count;
64     unsigned int exporter_secret_count;
65 };
66
67
68 static unsigned char serverinfov1[] = {
69     0xff, 0xff, /* Dummy extension type */
70     0x00, 0x01, /* Extension length is 1 byte */
71     0xff        /* Dummy extension data */
72 };
73
74 static unsigned char serverinfov2[] = {
75     0x00, 0x00, 0x00,
76     (unsigned char)(SSL_EXT_CLIENT_HELLO & 0xff), /* Dummy context - 4 bytes */
77     0xff, 0xff, /* Dummy extension type */
78     0x00, 0x01, /* Extension length is 1 byte */
79     0xff        /* Dummy extension data */
80 };
81
82 static void client_keylog_callback(const SSL *ssl, const char *line)
83 {
84     int line_length = strlen(line);
85
86     /* If the log doesn't fit, error out. */
87     if (client_log_buffer_index + line_length > sizeof(client_log_buffer) - 1) {
88         TEST_info("Client log too full");
89         error_writing_log = 1;
90         return;
91     }
92
93     strcat(client_log_buffer, line);
94     client_log_buffer_index += line_length;
95     client_log_buffer[client_log_buffer_index++] = '\n';
96 }
97
98 static void server_keylog_callback(const SSL *ssl, const char *line)
99 {
100     int line_length = strlen(line);
101
102     /* If the log doesn't fit, error out. */
103     if (server_log_buffer_index + line_length > sizeof(server_log_buffer) - 1) {
104         TEST_info("Server log too full");
105         error_writing_log = 1;
106         return;
107     }
108
109     strcat(server_log_buffer, line);
110     server_log_buffer_index += line_length;
111     server_log_buffer[server_log_buffer_index++] = '\n';
112 }
113
114 static int compare_hex_encoded_buffer(const char *hex_encoded,
115                                       size_t hex_length,
116                                       const uint8_t *raw,
117                                       size_t raw_length)
118 {
119     size_t i, j;
120     char hexed[3];
121
122     if (!TEST_size_t_eq(raw_length * 2, hex_length))
123         return 1;
124
125     for (i = j = 0; i < raw_length && j + 1 < hex_length; i++, j += 2) {
126         sprintf(hexed, "%02x", raw[i]);
127         if (!TEST_int_eq(hexed[0], hex_encoded[j])
128                 || !TEST_int_eq(hexed[1], hex_encoded[j + 1]))
129             return 1;
130     }
131
132     return 0;
133 }
134
135 static int test_keylog_output(char *buffer, const SSL *ssl,
136                               const SSL_SESSION *session,
137                               struct sslapitest_log_counts *expected)
138 {
139     char *token = NULL;
140     unsigned char actual_client_random[SSL3_RANDOM_SIZE] = {0};
141     size_t client_random_size = SSL3_RANDOM_SIZE;
142     unsigned char actual_master_key[SSL_MAX_MASTER_KEY_LENGTH] = {0};
143     size_t master_key_size = SSL_MAX_MASTER_KEY_LENGTH;
144     unsigned int rsa_key_exchange_count = 0;
145     unsigned int master_secret_count = 0;
146     unsigned int client_early_secret_count = 0;
147     unsigned int client_handshake_secret_count = 0;
148     unsigned int server_handshake_secret_count = 0;
149     unsigned int client_application_secret_count = 0;
150     unsigned int server_application_secret_count = 0;
151     unsigned int early_exporter_secret_count = 0;
152     unsigned int exporter_secret_count = 0;
153
154     for (token = strtok(buffer, " \n"); token != NULL;
155          token = strtok(NULL, " \n")) {
156         if (strcmp(token, "RSA") == 0) {
157             /*
158              * Premaster secret. Tokens should be: 16 ASCII bytes of
159              * hex-encoded encrypted secret, then the hex-encoded pre-master
160              * secret.
161              */
162             if (!TEST_ptr(token = strtok(NULL, " \n")))
163                 return 0;
164             if (!TEST_size_t_eq(strlen(token), 16))
165                 return 0;
166             if (!TEST_ptr(token = strtok(NULL, " \n")))
167                 return 0;
168             /*
169              * We can't sensibly check the log because the premaster secret is
170              * transient, and OpenSSL doesn't keep hold of it once the master
171              * secret is generated.
172              */
173             rsa_key_exchange_count++;
174         } else if (strcmp(token, "CLIENT_RANDOM") == 0) {
175             /*
176              * Master secret. Tokens should be: 64 ASCII bytes of hex-encoded
177              * client random, then the hex-encoded master secret.
178              */
179             client_random_size = SSL_get_client_random(ssl,
180                                                        actual_client_random,
181                                                        SSL3_RANDOM_SIZE);
182             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
183                 return 0;
184
185             if (!TEST_ptr(token = strtok(NULL, " \n")))
186                 return 0;
187             if (!TEST_size_t_eq(strlen(token), 64))
188                 return 0;
189             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
190                                                        actual_client_random,
191                                                        client_random_size)))
192                 return 0;
193
194             if (!TEST_ptr(token = strtok(NULL, " \n")))
195                 return 0;
196             master_key_size = SSL_SESSION_get_master_key(session,
197                                                          actual_master_key,
198                                                          master_key_size);
199             if (!TEST_size_t_ne(master_key_size, 0))
200                 return 0;
201             if (!TEST_false(compare_hex_encoded_buffer(token, strlen(token),
202                                                        actual_master_key,
203                                                        master_key_size)))
204                 return 0;
205             master_secret_count++;
206         } else if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0
207                     || strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0
208                     || strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0
209                     || strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0
210                     || strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0
211                     || strcmp(token, "EARLY_EXPORTER_SECRET") == 0
212                     || strcmp(token, "EXPORTER_SECRET") == 0) {
213             /*
214              * TLSv1.3 secret. Tokens should be: 64 ASCII bytes of hex-encoded
215              * client random, and then the hex-encoded secret. In this case,
216              * we treat all of these secrets identically and then just
217              * distinguish between them when counting what we saw.
218              */
219             if (strcmp(token, "CLIENT_EARLY_TRAFFIC_SECRET") == 0)
220                 client_early_secret_count++;
221             else if (strcmp(token, "CLIENT_HANDSHAKE_TRAFFIC_SECRET") == 0)
222                 client_handshake_secret_count++;
223             else if (strcmp(token, "SERVER_HANDSHAKE_TRAFFIC_SECRET") == 0)
224                 server_handshake_secret_count++;
225             else if (strcmp(token, "CLIENT_TRAFFIC_SECRET_0") == 0)
226                 client_application_secret_count++;
227             else if (strcmp(token, "SERVER_TRAFFIC_SECRET_0") == 0)
228                 server_application_secret_count++;
229             else if (strcmp(token, "EARLY_EXPORTER_SECRET") == 0)
230                 early_exporter_secret_count++;
231             else if (strcmp(token, "EXPORTER_SECRET") == 0)
232                 exporter_secret_count++;
233
234             client_random_size = SSL_get_client_random(ssl,
235                                                        actual_client_random,
236                                                        SSL3_RANDOM_SIZE);
237             if (!TEST_size_t_eq(client_random_size, SSL3_RANDOM_SIZE))
238                 return 0;
239
240             if (!TEST_ptr(token = strtok(NULL, " \n")))
241                 return 0;
242             if (!TEST_size_t_eq(strlen(token), 64))
243                 return 0;
244             if (!TEST_false(compare_hex_encoded_buffer(token, 64,
245                                                        actual_client_random,
246                                                        client_random_size)))
247                 return 0;
248
249             if (!TEST_ptr(token = strtok(NULL, " \n")))
250                 return 0;
251
252             /*
253              * TODO(TLS1.3): test that application traffic secrets are what
254              * we expect */
255         } else {
256             TEST_info("Unexpected token %s\n", token);
257             return 0;
258         }
259     }
260
261     /* Got what we expected? */
262     if (!TEST_size_t_eq(rsa_key_exchange_count,
263                         expected->rsa_key_exchange_count)
264             || !TEST_size_t_eq(master_secret_count,
265                                expected->master_secret_count)
266             || !TEST_size_t_eq(client_early_secret_count,
267                                expected->client_early_secret_count)
268             || !TEST_size_t_eq(client_handshake_secret_count,
269                                expected->client_handshake_secret_count)
270             || !TEST_size_t_eq(server_handshake_secret_count,
271                                expected->server_handshake_secret_count)
272             || !TEST_size_t_eq(client_application_secret_count,
273                                expected->client_application_secret_count)
274             || !TEST_size_t_eq(server_application_secret_count,
275                                expected->server_application_secret_count)
276             || !TEST_size_t_eq(early_exporter_secret_count,
277                                expected->early_exporter_secret_count)
278             || !TEST_size_t_eq(exporter_secret_count,
279                                expected->exporter_secret_count))
280         return 0;
281     return 1;
282 }
283
284 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
285 static int test_keylog(void)
286 {
287     SSL_CTX *cctx = NULL, *sctx = NULL;
288     SSL *clientssl = NULL, *serverssl = NULL;
289     int testresult = 0;
290     struct sslapitest_log_counts expected = {0};
291
292     /* Clean up logging space */
293     memset(client_log_buffer, 0, sizeof(client_log_buffer));
294     memset(server_log_buffer, 0, sizeof(server_log_buffer));
295     client_log_buffer_index = 0;
296     server_log_buffer_index = 0;
297     error_writing_log = 0;
298
299     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
300                                        TLS_client_method(),
301                                        TLS1_VERSION, TLS_MAX_VERSION,
302                                        &sctx, &cctx, cert, privkey)))
303         return 0;
304
305     /* We cannot log the master secret for TLSv1.3, so we should forbid it. */
306     SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
307     SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
308
309     /* We also want to ensure that we use RSA-based key exchange. */
310     if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "RSA")))
311         goto end;
312
313     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
314             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
315         goto end;
316     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
317     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
318                    == client_keylog_callback))
319         goto end;
320     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
321     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
322                    == server_keylog_callback))
323         goto end;
324
325     /* Now do a handshake and check that the logs have been written to. */
326     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
327                                       &clientssl, NULL, NULL))
328             || !TEST_true(create_ssl_connection(serverssl, clientssl,
329                                                 SSL_ERROR_NONE))
330             || !TEST_false(error_writing_log)
331             || !TEST_int_gt(client_log_buffer_index, 0)
332             || !TEST_int_gt(server_log_buffer_index, 0))
333         goto end;
334
335     /*
336      * Now we want to test that our output data was vaguely sensible. We
337      * do that by using strtok and confirming that we have more or less the
338      * data we expect. For both client and server, we expect to see one master
339      * secret. The client should also see a RSA key exchange.
340      */
341     expected.rsa_key_exchange_count = 1;
342     expected.master_secret_count = 1;
343     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
344                                       SSL_get_session(clientssl), &expected)))
345         goto end;
346
347     expected.rsa_key_exchange_count = 0;
348     if (!TEST_true(test_keylog_output(server_log_buffer, serverssl,
349                                       SSL_get_session(serverssl), &expected)))
350         goto end;
351
352     testresult = 1;
353
354 end:
355     SSL_free(serverssl);
356     SSL_free(clientssl);
357     SSL_CTX_free(sctx);
358     SSL_CTX_free(cctx);
359
360     return testresult;
361 }
362 #endif
363
364 #ifndef OPENSSL_NO_TLS1_3
365 static int test_keylog_no_master_key(void)
366 {
367     SSL_CTX *cctx = NULL, *sctx = NULL;
368     SSL *clientssl = NULL, *serverssl = NULL;
369     SSL_SESSION *sess = NULL;
370     int testresult = 0;
371     struct sslapitest_log_counts expected = {0};
372     unsigned char buf[1];
373     size_t readbytes, written;
374
375     /* Clean up logging space */
376     memset(client_log_buffer, 0, sizeof(client_log_buffer));
377     memset(server_log_buffer, 0, sizeof(server_log_buffer));
378     client_log_buffer_index = 0;
379     server_log_buffer_index = 0;
380     error_writing_log = 0;
381
382     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
383                                        TLS1_VERSION, TLS_MAX_VERSION,
384                                        &sctx, &cctx, cert, privkey))
385         || !TEST_true(SSL_CTX_set_max_early_data(sctx,
386                                                  SSL3_RT_MAX_PLAIN_LENGTH)))
387         return 0;
388
389     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx) == NULL)
390             || !TEST_true(SSL_CTX_get_keylog_callback(sctx) == NULL))
391         goto end;
392
393     SSL_CTX_set_keylog_callback(cctx, client_keylog_callback);
394     if (!TEST_true(SSL_CTX_get_keylog_callback(cctx)
395                    == client_keylog_callback))
396         goto end;
397
398     SSL_CTX_set_keylog_callback(sctx, server_keylog_callback);
399     if (!TEST_true(SSL_CTX_get_keylog_callback(sctx)
400                    == server_keylog_callback))
401         goto end;
402
403     /* Now do a handshake and check that the logs have been written to. */
404     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
405                                       &clientssl, NULL, NULL))
406             || !TEST_true(create_ssl_connection(serverssl, clientssl,
407                                                 SSL_ERROR_NONE))
408             || !TEST_false(error_writing_log))
409         goto end;
410
411     /*
412      * Now we want to test that our output data was vaguely sensible. For this
413      * test, we expect no CLIENT_RANDOM entry because it doesn't make sense for
414      * TLSv1.3, but we do expect both client and server to emit keys.
415      */
416     expected.client_handshake_secret_count = 1;
417     expected.server_handshake_secret_count = 1;
418     expected.client_application_secret_count = 1;
419     expected.server_application_secret_count = 1;
420     expected.exporter_secret_count = 1;
421     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
422                                       SSL_get_session(clientssl), &expected))
423             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
424                                              SSL_get_session(serverssl),
425                                              &expected)))
426         goto end;
427
428     /* Terminate old session and resume with early data. */
429     sess = SSL_get1_session(clientssl);
430     SSL_shutdown(clientssl);
431     SSL_shutdown(serverssl);
432     SSL_free(serverssl);
433     SSL_free(clientssl);
434     serverssl = clientssl = NULL;
435
436     /* Reset key log */
437     memset(client_log_buffer, 0, sizeof(client_log_buffer));
438     memset(server_log_buffer, 0, sizeof(server_log_buffer));
439     client_log_buffer_index = 0;
440     server_log_buffer_index = 0;
441
442     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
443                                       &clientssl, NULL, NULL))
444             || !TEST_true(SSL_set_session(clientssl, sess))
445             /* Here writing 0 length early data is enough. */
446             || !TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
447             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
448                                                 &readbytes),
449                             SSL_READ_EARLY_DATA_ERROR)
450             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
451                             SSL_EARLY_DATA_ACCEPTED)
452             || !TEST_true(create_ssl_connection(serverssl, clientssl,
453                           SSL_ERROR_NONE))
454             || !TEST_true(SSL_session_reused(clientssl)))
455         goto end;
456
457     /* In addition to the previous entries, expect early secrets. */
458     expected.client_early_secret_count = 1;
459     expected.early_exporter_secret_count = 1;
460     if (!TEST_true(test_keylog_output(client_log_buffer, clientssl,
461                                       SSL_get_session(clientssl), &expected))
462             || !TEST_true(test_keylog_output(server_log_buffer, serverssl,
463                                              SSL_get_session(serverssl),
464                                              &expected)))
465         goto end;
466
467     testresult = 1;
468
469 end:
470     SSL_SESSION_free(sess);
471     SSL_free(serverssl);
472     SSL_free(clientssl);
473     SSL_CTX_free(sctx);
474     SSL_CTX_free(cctx);
475
476     return testresult;
477 }
478 #endif
479
480 #ifndef OPENSSL_NO_TLS1_2
481 static int full_client_hello_callback(SSL *s, int *al, void *arg)
482 {
483     int *ctr = arg;
484     const unsigned char *p;
485     int *exts;
486     /* We only configure two ciphers, but the SCSV is added automatically. */
487 #ifdef OPENSSL_NO_EC
488     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0x00, 0xff};
489 #else
490     const unsigned char expected_ciphers[] = {0x00, 0x9d, 0xc0,
491                                               0x2c, 0x00, 0xff};
492 #endif
493     const int expected_extensions[] = {
494 #ifndef OPENSSL_NO_EC
495                                        11, 10,
496 #endif
497                                        35, 22, 23, 13};
498     size_t len;
499
500     /* Make sure we can defer processing and get called back. */
501     if ((*ctr)++ == 0)
502         return SSL_CLIENT_HELLO_RETRY;
503
504     len = SSL_client_hello_get0_ciphers(s, &p);
505     if (!TEST_mem_eq(p, len, expected_ciphers, sizeof(expected_ciphers))
506             || !TEST_size_t_eq(
507                        SSL_client_hello_get0_compression_methods(s, &p), 1)
508             || !TEST_int_eq(*p, 0))
509         return SSL_CLIENT_HELLO_ERROR;
510     if (!SSL_client_hello_get1_extensions_present(s, &exts, &len))
511         return SSL_CLIENT_HELLO_ERROR;
512     if (len != OSSL_NELEM(expected_extensions) ||
513         memcmp(exts, expected_extensions, len * sizeof(*exts)) != 0) {
514         printf("ClientHello callback expected extensions mismatch\n");
515         OPENSSL_free(exts);
516         return SSL_CLIENT_HELLO_ERROR;
517     }
518     OPENSSL_free(exts);
519     return SSL_CLIENT_HELLO_SUCCESS;
520 }
521
522 static int test_client_hello_cb(void)
523 {
524     SSL_CTX *cctx = NULL, *sctx = NULL;
525     SSL *clientssl = NULL, *serverssl = NULL;
526     int testctr = 0, testresult = 0;
527
528     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
529                                        TLS1_VERSION, TLS_MAX_VERSION,
530                                        &sctx, &cctx, cert, privkey)))
531         goto end;
532     SSL_CTX_set_client_hello_cb(sctx, full_client_hello_callback, &testctr);
533
534     /* The gimpy cipher list we configure can't do TLS 1.3. */
535     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
536
537     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
538                         "AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"))
539             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
540                                              &clientssl, NULL, NULL))
541             || !TEST_false(create_ssl_connection(serverssl, clientssl,
542                         SSL_ERROR_WANT_CLIENT_HELLO_CB))
543                 /*
544                  * Passing a -1 literal is a hack since
545                  * the real value was lost.
546                  * */
547             || !TEST_int_eq(SSL_get_error(serverssl, -1),
548                             SSL_ERROR_WANT_CLIENT_HELLO_CB)
549             || !TEST_true(create_ssl_connection(serverssl, clientssl,
550                                                 SSL_ERROR_NONE)))
551         goto end;
552
553     testresult = 1;
554
555 end:
556     SSL_free(serverssl);
557     SSL_free(clientssl);
558     SSL_CTX_free(sctx);
559     SSL_CTX_free(cctx);
560
561     return testresult;
562 }
563 #endif
564
565 static int execute_test_large_message(const SSL_METHOD *smeth,
566                                       const SSL_METHOD *cmeth,
567                                       int min_version, int max_version,
568                                       int read_ahead)
569 {
570     SSL_CTX *cctx = NULL, *sctx = NULL;
571     SSL *clientssl = NULL, *serverssl = NULL;
572     int testresult = 0;
573     int i;
574     BIO *certbio = NULL;
575     X509 *chaincert = NULL;
576     int certlen;
577
578     if (!TEST_ptr(certbio = BIO_new_file(cert, "r")))
579         goto end;
580     chaincert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
581     BIO_free(certbio);
582     certbio = NULL;
583     if (!TEST_ptr(chaincert))
584         goto end;
585
586     if (!TEST_true(create_ssl_ctx_pair(smeth, cmeth, min_version, max_version,
587                                        &sctx, &cctx, cert, privkey)))
588         goto end;
589
590     if (read_ahead) {
591         /*
592          * Test that read_ahead works correctly when dealing with large
593          * records
594          */
595         SSL_CTX_set_read_ahead(cctx, 1);
596     }
597
598     /*
599      * We assume the supplied certificate is big enough so that if we add
600      * NUM_EXTRA_CERTS it will make the overall message large enough. The
601      * default buffer size is requested to be 16k, but due to the way BUF_MEM
602      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
603      * test we need to have a message larger than that.
604      */
605     certlen = i2d_X509(chaincert, NULL);
606     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
607                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
608     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
609         if (!X509_up_ref(chaincert))
610             goto end;
611         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
612             X509_free(chaincert);
613             goto end;
614         }
615     }
616
617     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
618                                       NULL, NULL))
619             || !TEST_true(create_ssl_connection(serverssl, clientssl,
620                                                 SSL_ERROR_NONE)))
621         goto end;
622
623     /*
624      * Calling SSL_clear() first is not required but this tests that SSL_clear()
625      * doesn't leak (when using enable-crypto-mdebug).
626      */
627     if (!TEST_true(SSL_clear(serverssl)))
628         goto end;
629
630     testresult = 1;
631  end:
632     X509_free(chaincert);
633     SSL_free(serverssl);
634     SSL_free(clientssl);
635     SSL_CTX_free(sctx);
636     SSL_CTX_free(cctx);
637
638     return testresult;
639 }
640
641 static int test_large_message_tls(void)
642 {
643     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
644                                       TLS1_VERSION, TLS_MAX_VERSION,
645                                       0);
646 }
647
648 static int test_large_message_tls_read_ahead(void)
649 {
650     return execute_test_large_message(TLS_server_method(), TLS_client_method(),
651                                       TLS1_VERSION, TLS_MAX_VERSION,
652                                       1);
653 }
654
655 #ifndef OPENSSL_NO_DTLS
656 static int test_large_message_dtls(void)
657 {
658     /*
659      * read_ahead is not relevant to DTLS because DTLS always acts as if
660      * read_ahead is set.
661      */
662     return execute_test_large_message(DTLS_server_method(),
663                                       DTLS_client_method(),
664                                       DTLS1_VERSION, DTLS_MAX_VERSION,
665                                       0);
666 }
667 #endif
668
669 #ifndef OPENSSL_NO_OCSP
670 static int ocsp_server_cb(SSL *s, void *arg)
671 {
672     int *argi = (int *)arg;
673     unsigned char *copy = NULL;
674     STACK_OF(OCSP_RESPID) *ids = NULL;
675     OCSP_RESPID *id = NULL;
676
677     if (*argi == 2) {
678         /* In this test we are expecting exactly 1 OCSP_RESPID */
679         SSL_get_tlsext_status_ids(s, &ids);
680         if (ids == NULL || sk_OCSP_RESPID_num(ids) != 1)
681             return SSL_TLSEXT_ERR_ALERT_FATAL;
682
683         id = sk_OCSP_RESPID_value(ids, 0);
684         if (id == NULL || !OCSP_RESPID_match(id, ocspcert))
685             return SSL_TLSEXT_ERR_ALERT_FATAL;
686     } else if (*argi != 1) {
687         return SSL_TLSEXT_ERR_ALERT_FATAL;
688     }
689
690     if (!TEST_ptr(copy = OPENSSL_memdup(orespder, sizeof(orespder))))
691         return SSL_TLSEXT_ERR_ALERT_FATAL;
692
693     SSL_set_tlsext_status_ocsp_resp(s, copy, sizeof(orespder));
694     ocsp_server_called = 1;
695     return SSL_TLSEXT_ERR_OK;
696 }
697
698 static int ocsp_client_cb(SSL *s, void *arg)
699 {
700     int *argi = (int *)arg;
701     const unsigned char *respderin;
702     size_t len;
703
704     if (*argi != 1 && *argi != 2)
705         return 0;
706
707     len = SSL_get_tlsext_status_ocsp_resp(s, &respderin);
708     if (!TEST_mem_eq(orespder, len, respderin, len))
709         return 0;
710
711     ocsp_client_called = 1;
712     return 1;
713 }
714
715 static int test_tlsext_status_type(void)
716 {
717     SSL_CTX *cctx = NULL, *sctx = NULL;
718     SSL *clientssl = NULL, *serverssl = NULL;
719     int testresult = 0;
720     STACK_OF(OCSP_RESPID) *ids = NULL;
721     OCSP_RESPID *id = NULL;
722     BIO *certbio = NULL;
723
724     if (!create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
725                              TLS1_VERSION, TLS_MAX_VERSION,
726                              &sctx, &cctx, cert, privkey))
727         return 0;
728
729     if (SSL_CTX_get_tlsext_status_type(cctx) != -1)
730         goto end;
731
732     /* First just do various checks getting and setting tlsext_status_type */
733
734     clientssl = SSL_new(cctx);
735     if (!TEST_int_eq(SSL_get_tlsext_status_type(clientssl), -1)
736             || !TEST_true(SSL_set_tlsext_status_type(clientssl,
737                                                       TLSEXT_STATUSTYPE_ocsp))
738             || !TEST_int_eq(SSL_get_tlsext_status_type(clientssl),
739                             TLSEXT_STATUSTYPE_ocsp))
740         goto end;
741
742     SSL_free(clientssl);
743     clientssl = NULL;
744
745     if (!SSL_CTX_set_tlsext_status_type(cctx, TLSEXT_STATUSTYPE_ocsp)
746      || SSL_CTX_get_tlsext_status_type(cctx) != TLSEXT_STATUSTYPE_ocsp)
747         goto end;
748
749     clientssl = SSL_new(cctx);
750     if (SSL_get_tlsext_status_type(clientssl) != TLSEXT_STATUSTYPE_ocsp)
751         goto end;
752     SSL_free(clientssl);
753     clientssl = NULL;
754
755     /*
756      * Now actually do a handshake and check OCSP information is exchanged and
757      * the callbacks get called
758      */
759     SSL_CTX_set_tlsext_status_cb(cctx, ocsp_client_cb);
760     SSL_CTX_set_tlsext_status_arg(cctx, &cdummyarg);
761     SSL_CTX_set_tlsext_status_cb(sctx, ocsp_server_cb);
762     SSL_CTX_set_tlsext_status_arg(sctx, &cdummyarg);
763     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
764                                       &clientssl, NULL, NULL))
765             || !TEST_true(create_ssl_connection(serverssl, clientssl,
766                                                 SSL_ERROR_NONE))
767             || !TEST_true(ocsp_client_called)
768             || !TEST_true(ocsp_server_called))
769         goto end;
770     SSL_free(serverssl);
771     SSL_free(clientssl);
772     serverssl = NULL;
773     clientssl = NULL;
774
775     /* Try again but this time force the server side callback to fail */
776     ocsp_client_called = 0;
777     ocsp_server_called = 0;
778     cdummyarg = 0;
779     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
780                                       &clientssl, NULL, NULL))
781                 /* This should fail because the callback will fail */
782             || !TEST_false(create_ssl_connection(serverssl, clientssl,
783                                                  SSL_ERROR_NONE))
784             || !TEST_false(ocsp_client_called)
785             || !TEST_false(ocsp_server_called))
786         goto end;
787     SSL_free(serverssl);
788     SSL_free(clientssl);
789     serverssl = NULL;
790     clientssl = NULL;
791
792     /*
793      * This time we'll get the client to send an OCSP_RESPID that it will
794      * accept.
795      */
796     ocsp_client_called = 0;
797     ocsp_server_called = 0;
798     cdummyarg = 2;
799     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
800                                       &clientssl, NULL, NULL)))
801         goto end;
802
803     /*
804      * We'll just use any old cert for this test - it doesn't have to be an OCSP
805      * specific one. We'll use the server cert.
806      */
807     if (!TEST_ptr(certbio = BIO_new_file(cert, "r"))
808             || !TEST_ptr(id = OCSP_RESPID_new())
809             || !TEST_ptr(ids = sk_OCSP_RESPID_new_null())
810             || !TEST_ptr(ocspcert = PEM_read_bio_X509(certbio,
811                                                       NULL, NULL, NULL))
812             || !TEST_true(OCSP_RESPID_set_by_key(id, ocspcert))
813             || !TEST_true(sk_OCSP_RESPID_push(ids, id)))
814         goto end;
815     id = NULL;
816     SSL_set_tlsext_status_ids(clientssl, ids);
817     /* Control has been transferred */
818     ids = NULL;
819
820     BIO_free(certbio);
821     certbio = NULL;
822
823     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
824                                          SSL_ERROR_NONE))
825             || !TEST_true(ocsp_client_called)
826             || !TEST_true(ocsp_server_called))
827         goto end;
828
829     testresult = 1;
830
831  end:
832     SSL_free(serverssl);
833     SSL_free(clientssl);
834     SSL_CTX_free(sctx);
835     SSL_CTX_free(cctx);
836     sk_OCSP_RESPID_pop_free(ids, OCSP_RESPID_free);
837     OCSP_RESPID_free(id);
838     BIO_free(certbio);
839     X509_free(ocspcert);
840     ocspcert = NULL;
841
842     return testresult;
843 }
844 #endif
845
846 #if !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
847 static int new_called, remove_called, get_called;
848
849 static int new_session_cb(SSL *ssl, SSL_SESSION *sess)
850 {
851     new_called++;
852     /*
853      * sess has been up-refed for us, but we don't actually need it so free it
854      * immediately.
855      */
856     SSL_SESSION_free(sess);
857     return 1;
858 }
859
860 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
861 {
862     remove_called++;
863 }
864
865 static SSL_SESSION *get_sess_val = NULL;
866
867 static SSL_SESSION *get_session_cb(SSL *ssl, const unsigned char *id, int len,
868                                    int *copy)
869 {
870     get_called++;
871     *copy = 1;
872     return get_sess_val;
873 }
874
875 static int execute_test_session(int maxprot, int use_int_cache,
876                                 int use_ext_cache)
877 {
878     SSL_CTX *sctx = NULL, *cctx = NULL;
879     SSL *serverssl1 = NULL, *clientssl1 = NULL;
880     SSL *serverssl2 = NULL, *clientssl2 = NULL;
881 # ifndef OPENSSL_NO_TLS1_1
882     SSL *serverssl3 = NULL, *clientssl3 = NULL;
883 # endif
884     SSL_SESSION *sess1 = NULL, *sess2 = NULL;
885     int testresult = 0, numnewsesstick = 1;
886
887     new_called = remove_called = 0;
888
889     /* TLSv1.3 sends 2 NewSessionTickets */
890     if (maxprot == TLS1_3_VERSION)
891         numnewsesstick = 2;
892
893     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
894                                        TLS1_VERSION, TLS_MAX_VERSION,
895                                        &sctx, &cctx, cert, privkey)))
896         return 0;
897
898     /*
899      * Only allow the max protocol version so we can force a connection failure
900      * later
901      */
902     SSL_CTX_set_min_proto_version(cctx, maxprot);
903     SSL_CTX_set_max_proto_version(cctx, maxprot);
904
905     /* Set up session cache */
906     if (use_ext_cache) {
907         SSL_CTX_sess_set_new_cb(cctx, new_session_cb);
908         SSL_CTX_sess_set_remove_cb(cctx, remove_session_cb);
909     }
910     if (use_int_cache) {
911         /* Also covers instance where both are set */
912         SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT);
913     } else {
914         SSL_CTX_set_session_cache_mode(cctx,
915                                        SSL_SESS_CACHE_CLIENT
916                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
917     }
918
919     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
920                                       NULL, NULL))
921             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
922                                                 SSL_ERROR_NONE))
923             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1)))
924         goto end;
925
926     /* Should fail because it should already be in the cache */
927     if (use_int_cache && !TEST_false(SSL_CTX_add_session(cctx, sess1)))
928         goto end;
929     if (use_ext_cache
930             && (!TEST_int_eq(new_called, numnewsesstick)
931
932                 || !TEST_int_eq(remove_called, 0)))
933         goto end;
934
935     new_called = remove_called = 0;
936     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
937                                       &clientssl2, NULL, NULL))
938             || !TEST_true(SSL_set_session(clientssl2, sess1))
939             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
940                                                 SSL_ERROR_NONE))
941             || !TEST_true(SSL_session_reused(clientssl2)))
942         goto end;
943
944     if (maxprot == TLS1_3_VERSION) {
945         /*
946          * In TLSv1.3 we should have created a new session even though we have
947          * resumed. Since we attempted a resume we should also have removed the
948          * old ticket from the cache so that we try to only use tickets once.
949          */
950         if (use_ext_cache
951                 && (!TEST_int_eq(new_called, 1)
952                     || !TEST_int_eq(remove_called, 1)))
953             goto end;
954     } else {
955         /*
956          * In TLSv1.2 we expect to have resumed so no sessions added or
957          * removed.
958          */
959         if (use_ext_cache
960                 && (!TEST_int_eq(new_called, 0)
961                     || !TEST_int_eq(remove_called, 0)))
962             goto end;
963     }
964
965     SSL_SESSION_free(sess1);
966     if (!TEST_ptr(sess1 = SSL_get1_session(clientssl2)))
967         goto end;
968     shutdown_ssl_connection(serverssl2, clientssl2);
969     serverssl2 = clientssl2 = NULL;
970
971     new_called = remove_called = 0;
972     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
973                                       &clientssl2, NULL, NULL))
974             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
975                                                 SSL_ERROR_NONE)))
976         goto end;
977
978     if (!TEST_ptr(sess2 = SSL_get1_session(clientssl2)))
979         goto end;
980
981     if (use_ext_cache
982             && (!TEST_int_eq(new_called, numnewsesstick)
983                 || !TEST_int_eq(remove_called, 0)))
984         goto end;
985
986     new_called = remove_called = 0;
987     /*
988      * This should clear sess2 from the cache because it is a "bad" session.
989      * See SSL_set_session() documentation.
990      */
991     if (!TEST_true(SSL_set_session(clientssl2, sess1)))
992         goto end;
993     if (use_ext_cache
994             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
995         goto end;
996     if (!TEST_ptr_eq(SSL_get_session(clientssl2), sess1))
997         goto end;
998
999     if (use_int_cache) {
1000         /* Should succeeded because it should not already be in the cache */
1001         if (!TEST_true(SSL_CTX_add_session(cctx, sess2))
1002                 || !TEST_true(SSL_CTX_remove_session(cctx, sess2)))
1003             goto end;
1004     }
1005
1006     new_called = remove_called = 0;
1007     /* This shouldn't be in the cache so should fail */
1008     if (!TEST_false(SSL_CTX_remove_session(cctx, sess2)))
1009         goto end;
1010
1011     if (use_ext_cache
1012             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1013         goto end;
1014
1015 # if !defined(OPENSSL_NO_TLS1_1)
1016     new_called = remove_called = 0;
1017     /* Force a connection failure */
1018     SSL_CTX_set_max_proto_version(sctx, TLS1_1_VERSION);
1019     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl3,
1020                                       &clientssl3, NULL, NULL))
1021             || !TEST_true(SSL_set_session(clientssl3, sess1))
1022             /* This should fail because of the mismatched protocol versions */
1023             || !TEST_false(create_ssl_connection(serverssl3, clientssl3,
1024                                                  SSL_ERROR_NONE)))
1025         goto end;
1026
1027     /* We should have automatically removed the session from the cache */
1028     if (use_ext_cache
1029             && (!TEST_int_eq(new_called, 0) || !TEST_int_eq(remove_called, 1)))
1030         goto end;
1031
1032     /* Should succeed because it should not already be in the cache */
1033     if (use_int_cache && !TEST_true(SSL_CTX_add_session(cctx, sess2)))
1034         goto end;
1035 # endif
1036
1037     /* Now do some tests for server side caching */
1038     if (use_ext_cache) {
1039         SSL_CTX_sess_set_new_cb(cctx, NULL);
1040         SSL_CTX_sess_set_remove_cb(cctx, NULL);
1041         SSL_CTX_sess_set_new_cb(sctx, new_session_cb);
1042         SSL_CTX_sess_set_remove_cb(sctx, remove_session_cb);
1043         SSL_CTX_sess_set_get_cb(sctx, get_session_cb);
1044         get_sess_val = NULL;
1045     }
1046
1047     SSL_CTX_set_session_cache_mode(cctx, 0);
1048     /* Internal caching is the default on the server side */
1049     if (!use_int_cache)
1050         SSL_CTX_set_session_cache_mode(sctx,
1051                                        SSL_SESS_CACHE_SERVER
1052                                        | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1053
1054     SSL_free(serverssl1);
1055     SSL_free(clientssl1);
1056     serverssl1 = clientssl1 = NULL;
1057     SSL_free(serverssl2);
1058     SSL_free(clientssl2);
1059     serverssl2 = clientssl2 = NULL;
1060     SSL_SESSION_free(sess1);
1061     sess1 = NULL;
1062     SSL_SESSION_free(sess2);
1063     sess2 = NULL;
1064
1065     SSL_CTX_set_max_proto_version(sctx, maxprot);
1066     if (maxprot == TLS1_2_VERSION)
1067         SSL_CTX_set_options(sctx, SSL_OP_NO_TICKET);
1068     new_called = remove_called = get_called = 0;
1069     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
1070                                       NULL, NULL))
1071             || !TEST_true(create_ssl_connection(serverssl1, clientssl1,
1072                                                 SSL_ERROR_NONE))
1073             || !TEST_ptr(sess1 = SSL_get1_session(clientssl1))
1074             || !TEST_ptr(sess2 = SSL_get1_session(serverssl1)))
1075         goto end;
1076
1077     if (use_int_cache) {
1078         if (maxprot == TLS1_3_VERSION && !use_ext_cache) {
1079             /*
1080              * In TLSv1.3 it should not have been added to the internal cache,
1081              * except in the case where we also have an external cache (in that
1082              * case it gets added to the cache in order to generate remove
1083              * events after timeout).
1084              */
1085             if (!TEST_false(SSL_CTX_remove_session(sctx, sess2)))
1086                 goto end;
1087         } else {
1088             /* Should fail because it should already be in the cache */
1089             if (!TEST_false(SSL_CTX_add_session(sctx, sess2)))
1090                 goto end;
1091         }
1092     }
1093
1094     if (use_ext_cache) {
1095         SSL_SESSION *tmp = sess2;
1096
1097         if (!TEST_int_eq(new_called, numnewsesstick)
1098                 || !TEST_int_eq(remove_called, 0)
1099                 || !TEST_int_eq(get_called, 0))
1100             goto end;
1101         /*
1102          * Delete the session from the internal cache to force a lookup from
1103          * the external cache. We take a copy first because
1104          * SSL_CTX_remove_session() also marks the session as non-resumable.
1105          */
1106         if (use_int_cache && maxprot != TLS1_3_VERSION) {
1107             if (!TEST_ptr(tmp = SSL_SESSION_dup(sess2))
1108                     || !TEST_true(SSL_CTX_remove_session(sctx, sess2)))
1109                 goto end;
1110             SSL_SESSION_free(sess2);
1111         }
1112         sess2 = tmp;
1113     }
1114
1115     new_called = remove_called = get_called = 0;
1116     get_sess_val = sess2;
1117     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl2,
1118                                       &clientssl2, NULL, NULL))
1119             || !TEST_true(SSL_set_session(clientssl2, sess1))
1120             || !TEST_true(create_ssl_connection(serverssl2, clientssl2,
1121                                                 SSL_ERROR_NONE))
1122             || !TEST_true(SSL_session_reused(clientssl2)))
1123         goto end;
1124
1125     if (use_ext_cache) {
1126         if (!TEST_int_eq(remove_called, 0))
1127             goto end;
1128
1129         if (maxprot == TLS1_3_VERSION) {
1130             if (!TEST_int_eq(new_called, 1)
1131                     || !TEST_int_eq(get_called, 0))
1132                 goto end;
1133         } else {
1134             if (!TEST_int_eq(new_called, 0)
1135                     || !TEST_int_eq(get_called, 1))
1136                 goto end;
1137         }
1138     }
1139
1140     testresult = 1;
1141
1142  end:
1143     SSL_free(serverssl1);
1144     SSL_free(clientssl1);
1145     SSL_free(serverssl2);
1146     SSL_free(clientssl2);
1147 # ifndef OPENSSL_NO_TLS1_1
1148     SSL_free(serverssl3);
1149     SSL_free(clientssl3);
1150 # endif
1151     SSL_SESSION_free(sess1);
1152     SSL_SESSION_free(sess2);
1153     SSL_CTX_free(sctx);
1154     SSL_CTX_free(cctx);
1155
1156     return testresult;
1157 }
1158 #endif /* !defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2) */
1159
1160 static int test_session_with_only_int_cache(void)
1161 {
1162 #ifndef OPENSSL_NO_TLS1_3
1163     if (!execute_test_session(TLS1_3_VERSION, 1, 0))
1164         return 0;
1165 #endif
1166
1167 #ifndef OPENSSL_NO_TLS1_2
1168     return execute_test_session(TLS1_2_VERSION, 1, 0);
1169 #else
1170     return 1;
1171 #endif
1172 }
1173
1174 static int test_session_with_only_ext_cache(void)
1175 {
1176 #ifndef OPENSSL_NO_TLS1_3
1177     if (!execute_test_session(TLS1_3_VERSION, 0, 1))
1178         return 0;
1179 #endif
1180
1181 #ifndef OPENSSL_NO_TLS1_2
1182     return execute_test_session(TLS1_2_VERSION, 0, 1);
1183 #else
1184     return 1;
1185 #endif
1186 }
1187
1188 static int test_session_with_both_cache(void)
1189 {
1190 #ifndef OPENSSL_NO_TLS1_3
1191     if (!execute_test_session(TLS1_3_VERSION, 1, 1))
1192         return 0;
1193 #endif
1194
1195 #ifndef OPENSSL_NO_TLS1_2
1196     return execute_test_session(TLS1_2_VERSION, 1, 1);
1197 #else
1198     return 1;
1199 #endif
1200 }
1201
1202 #ifndef OPENSSL_NO_TLS1_3
1203 static SSL_SESSION *sesscache[6];
1204 static int do_cache;
1205
1206 static int new_cachesession_cb(SSL *ssl, SSL_SESSION *sess)
1207 {
1208     if (do_cache) {
1209         sesscache[new_called] = sess;
1210     } else {
1211         /* We don't need the reference to the session, so free it */
1212         SSL_SESSION_free(sess);
1213     }
1214     new_called++;
1215
1216     return 1;
1217 }
1218
1219 static int post_handshake_verify(SSL *sssl, SSL *cssl)
1220 {
1221     SSL_set_verify(sssl, SSL_VERIFY_PEER, NULL);
1222     if (!TEST_true(SSL_verify_client_post_handshake(sssl)))
1223         return 0;
1224
1225     /* Start handshake on the server and client */
1226     if (!TEST_int_eq(SSL_do_handshake(sssl), 1)
1227             || !TEST_int_le(SSL_read(cssl, NULL, 0), 0)
1228             || !TEST_int_le(SSL_read(sssl, NULL, 0), 0)
1229             || !TEST_true(create_ssl_connection(sssl, cssl,
1230                                                 SSL_ERROR_NONE)))
1231         return 0;
1232
1233     return 1;
1234 }
1235
1236 static int test_tickets(int idx)
1237 {
1238     SSL_CTX *sctx = NULL, *cctx = NULL;
1239     SSL *serverssl = NULL, *clientssl = NULL;
1240     int testresult = 0, i;
1241     size_t j;
1242
1243     /* idx is the test number, but also the number of tickets we want */
1244
1245     new_called = 0;
1246     do_cache = 1;
1247
1248     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1249                                        TLS1_VERSION, TLS_MAX_VERSION, &sctx,
1250                                        &cctx, cert, privkey))
1251             || !TEST_true(SSL_CTX_set_num_tickets(sctx, idx)))
1252         goto end;
1253
1254     SSL_CTX_set_session_cache_mode(cctx, SSL_SESS_CACHE_CLIENT
1255                                          | SSL_SESS_CACHE_NO_INTERNAL_STORE);
1256     SSL_CTX_sess_set_new_cb(cctx, new_cachesession_cb);
1257
1258     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1259                                           &clientssl, NULL, NULL)))
1260         goto end;
1261
1262     SSL_force_post_handshake_auth(clientssl);
1263
1264     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1265                                                 SSL_ERROR_NONE))
1266                /* Check we got the number of tickets we were expecting */
1267             || !TEST_int_eq(idx, new_called))
1268         goto end;
1269
1270     /* After a post-handshake authentication we should get new tickets issued */
1271     if (!post_handshake_verify(serverssl, clientssl)
1272             || !TEST_int_eq(idx * 2, new_called))
1273         goto end;
1274
1275     SSL_shutdown(clientssl);
1276     SSL_shutdown(serverssl);
1277     SSL_free(serverssl);
1278     SSL_free(clientssl);
1279     serverssl = clientssl = NULL;
1280
1281     /* Stop caching sessions - just count them */
1282     do_cache = 0;
1283
1284     /* Test that we can resume with all the tickets we got given */
1285     for (i = 0; i < idx * 2; i++) {
1286         new_called = 0;
1287         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1288                                               &clientssl, NULL, NULL))
1289                 || !TEST_true(SSL_set_session(clientssl, sesscache[i])))
1290             goto end;
1291
1292         SSL_force_post_handshake_auth(clientssl);
1293
1294         if (!TEST_true(create_ssl_connection(serverssl, clientssl,
1295                                                     SSL_ERROR_NONE))
1296                 || !TEST_true(SSL_session_reused(clientssl))
1297                    /* Following a resumption we only get 1 ticket */
1298                 || !TEST_int_eq(new_called, 1))
1299             goto end;
1300
1301         new_called = 0;
1302         /* After a post-handshake authentication we should get 1 new ticket */
1303         if (!post_handshake_verify(serverssl, clientssl)
1304                 || !TEST_int_eq(new_called, 1))
1305             goto end;
1306
1307         SSL_shutdown(clientssl);
1308         SSL_shutdown(serverssl);
1309         SSL_free(serverssl);
1310         SSL_free(clientssl);
1311         serverssl = clientssl = NULL;
1312         SSL_SESSION_free(sesscache[i]);
1313         sesscache[i] = NULL;
1314     }
1315
1316     testresult = 1;
1317
1318  end:
1319     SSL_free(serverssl);
1320     SSL_free(clientssl);
1321     for (j = 0; j < OSSL_NELEM(sesscache); j++) {
1322         SSL_SESSION_free(sesscache[j]);
1323         sesscache[j] = NULL;
1324     }
1325     SSL_CTX_free(sctx);
1326     SSL_CTX_free(cctx);
1327
1328     return testresult;
1329 }
1330 #endif
1331
1332 #define USE_NULL            0
1333 #define USE_BIO_1           1
1334 #define USE_BIO_2           2
1335 #define USE_DEFAULT         3
1336
1337 #define CONNTYPE_CONNECTION_SUCCESS  0
1338 #define CONNTYPE_CONNECTION_FAIL     1
1339 #define CONNTYPE_NO_CONNECTION       2
1340
1341 #define TOTAL_NO_CONN_SSL_SET_BIO_TESTS         (3 * 3 * 3 * 3)
1342 #define TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS    (2 * 2)
1343 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2)
1344 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       (2 * 2)
1345 #else
1346 # define TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS       0
1347 #endif
1348
1349 #define TOTAL_SSL_SET_BIO_TESTS TOTAL_NO_CONN_SSL_SET_BIO_TESTS \
1350                                 + TOTAL_CONN_SUCCESS_SSL_SET_BIO_TESTS \
1351                                 + TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS
1352
1353 static void setupbio(BIO **res, BIO *bio1, BIO *bio2, int type)
1354 {
1355     switch (type) {
1356     case USE_NULL:
1357         *res = NULL;
1358         break;
1359     case USE_BIO_1:
1360         *res = bio1;
1361         break;
1362     case USE_BIO_2:
1363         *res = bio2;
1364         break;
1365     }
1366 }
1367
1368
1369 /*
1370  * Tests calls to SSL_set_bio() under various conditions.
1371  *
1372  * For the first 3 * 3 * 3 * 3 = 81 tests we do 2 calls to SSL_set_bio() with
1373  * various combinations of valid BIOs or NULL being set for the rbio/wbio. We
1374  * then do more tests where we create a successful connection first using our
1375  * standard connection setup functions, and then call SSL_set_bio() with
1376  * various combinations of valid BIOs or NULL. We then repeat these tests
1377  * following a failed connection. In this last case we are looking to check that
1378  * SSL_set_bio() functions correctly in the case where s->bbio is not NULL.
1379  */
1380 static int test_ssl_set_bio(int idx)
1381 {
1382     SSL_CTX *sctx = NULL, *cctx = NULL;
1383     BIO *bio1 = NULL;
1384     BIO *bio2 = NULL;
1385     BIO *irbio = NULL, *iwbio = NULL, *nrbio = NULL, *nwbio = NULL;
1386     SSL *serverssl = NULL, *clientssl = NULL;
1387     int initrbio, initwbio, newrbio, newwbio, conntype;
1388     int testresult = 0;
1389
1390     if (idx < TOTAL_NO_CONN_SSL_SET_BIO_TESTS) {
1391         initrbio = idx % 3;
1392         idx /= 3;
1393         initwbio = idx % 3;
1394         idx /= 3;
1395         newrbio = idx % 3;
1396         idx /= 3;
1397         newwbio = idx % 3;
1398         conntype = CONNTYPE_NO_CONNECTION;
1399     } else {
1400         idx -= TOTAL_NO_CONN_SSL_SET_BIO_TESTS;
1401         initrbio = initwbio = USE_DEFAULT;
1402         newrbio = idx % 2;
1403         idx /= 2;
1404         newwbio = idx % 2;
1405         idx /= 2;
1406         conntype = idx % 2;
1407     }
1408
1409     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1410                                        TLS1_VERSION, TLS_MAX_VERSION,
1411                                        &sctx, &cctx, cert, privkey)))
1412         goto end;
1413
1414     if (conntype == CONNTYPE_CONNECTION_FAIL) {
1415         /*
1416          * We won't ever get here if either TLSv1.3 or TLSv1.2 is disabled
1417          * because we reduced the number of tests in the definition of
1418          * TOTAL_CONN_FAIL_SSL_SET_BIO_TESTS to avoid this scenario. By setting
1419          * mismatched protocol versions we will force a connection failure.
1420          */
1421         SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION);
1422         SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1423     }
1424
1425     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
1426                                       NULL, NULL)))
1427         goto end;
1428
1429     if (initrbio == USE_BIO_1
1430             || initwbio == USE_BIO_1
1431             || newrbio == USE_BIO_1
1432             || newwbio == USE_BIO_1) {
1433         if (!TEST_ptr(bio1 = BIO_new(BIO_s_mem())))
1434             goto end;
1435     }
1436
1437     if (initrbio == USE_BIO_2
1438             || initwbio == USE_BIO_2
1439             || newrbio == USE_BIO_2
1440             || newwbio == USE_BIO_2) {
1441         if (!TEST_ptr(bio2 = BIO_new(BIO_s_mem())))
1442             goto end;
1443     }
1444
1445     if (initrbio != USE_DEFAULT) {
1446         setupbio(&irbio, bio1, bio2, initrbio);
1447         setupbio(&iwbio, bio1, bio2, initwbio);
1448         SSL_set_bio(clientssl, irbio, iwbio);
1449
1450         /*
1451          * We want to maintain our own refs to these BIO, so do an up ref for
1452          * each BIO that will have ownership transferred in the SSL_set_bio()
1453          * call
1454          */
1455         if (irbio != NULL)
1456             BIO_up_ref(irbio);
1457         if (iwbio != NULL && iwbio != irbio)
1458             BIO_up_ref(iwbio);
1459     }
1460
1461     if (conntype != CONNTYPE_NO_CONNECTION
1462             && !TEST_true(create_ssl_connection(serverssl, clientssl,
1463                                                 SSL_ERROR_NONE)
1464                           == (conntype == CONNTYPE_CONNECTION_SUCCESS)))
1465         goto end;
1466
1467     setupbio(&nrbio, bio1, bio2, newrbio);
1468     setupbio(&nwbio, bio1, bio2, newwbio);
1469
1470     /*
1471      * We will (maybe) transfer ownership again so do more up refs.
1472      * SSL_set_bio() has some really complicated ownership rules where BIOs have
1473      * already been set!
1474      */
1475     if (nrbio != NULL
1476             && nrbio != irbio
1477             && (nwbio != iwbio || nrbio != nwbio))
1478         BIO_up_ref(nrbio);
1479     if (nwbio != NULL
1480             && nwbio != nrbio
1481             && (nwbio != iwbio || (nwbio == iwbio && irbio == iwbio)))
1482         BIO_up_ref(nwbio);
1483
1484     SSL_set_bio(clientssl, nrbio, nwbio);
1485
1486     testresult = 1;
1487
1488  end:
1489     BIO_free(bio1);
1490     BIO_free(bio2);
1491
1492     /*
1493      * This test is checking that the ref counting for SSL_set_bio is correct.
1494      * If we get here and we did too many frees then we will fail in the above
1495      * functions. If we haven't done enough then this will only be detected in
1496      * a crypto-mdebug build
1497      */
1498     SSL_free(serverssl);
1499     SSL_free(clientssl);
1500     SSL_CTX_free(sctx);
1501     SSL_CTX_free(cctx);
1502     return testresult;
1503 }
1504
1505 typedef enum { NO_BIO_CHANGE, CHANGE_RBIO, CHANGE_WBIO } bio_change_t;
1506
1507 static int execute_test_ssl_bio(int pop_ssl, bio_change_t change_bio)
1508 {
1509     BIO *sslbio = NULL, *membio1 = NULL, *membio2 = NULL;
1510     SSL_CTX *ctx;
1511     SSL *ssl = NULL;
1512     int testresult = 0;
1513
1514     if (!TEST_ptr(ctx = SSL_CTX_new(TLS_method()))
1515             || !TEST_ptr(ssl = SSL_new(ctx))
1516             || !TEST_ptr(sslbio = BIO_new(BIO_f_ssl()))
1517             || !TEST_ptr(membio1 = BIO_new(BIO_s_mem())))
1518         goto end;
1519
1520     BIO_set_ssl(sslbio, ssl, BIO_CLOSE);
1521
1522     /*
1523      * If anything goes wrong here then we could leak memory, so this will
1524      * be caught in a crypto-mdebug build
1525      */
1526     BIO_push(sslbio, membio1);
1527
1528     /* Verify changing the rbio/wbio directly does not cause leaks */
1529     if (change_bio != NO_BIO_CHANGE) {
1530         if (!TEST_ptr(membio2 = BIO_new(BIO_s_mem())))
1531             goto end;
1532         if (change_bio == CHANGE_RBIO)
1533             SSL_set0_rbio(ssl, membio2);
1534         else
1535             SSL_set0_wbio(ssl, membio2);
1536     }
1537     ssl = NULL;
1538
1539     if (pop_ssl)
1540         BIO_pop(sslbio);
1541     else
1542         BIO_pop(membio1);
1543
1544     testresult = 1;
1545  end:
1546     BIO_free(membio1);
1547     BIO_free(sslbio);
1548     SSL_free(ssl);
1549     SSL_CTX_free(ctx);
1550
1551     return testresult;
1552 }
1553
1554 static int test_ssl_bio_pop_next_bio(void)
1555 {
1556     return execute_test_ssl_bio(0, NO_BIO_CHANGE);
1557 }
1558
1559 static int test_ssl_bio_pop_ssl_bio(void)
1560 {
1561     return execute_test_ssl_bio(1, NO_BIO_CHANGE);
1562 }
1563
1564 static int test_ssl_bio_change_rbio(void)
1565 {
1566     return execute_test_ssl_bio(0, CHANGE_RBIO);
1567 }
1568
1569 static int test_ssl_bio_change_wbio(void)
1570 {
1571     return execute_test_ssl_bio(0, CHANGE_WBIO);
1572 }
1573
1574 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
1575 typedef struct {
1576     /* The list of sig algs */
1577     const int *list;
1578     /* The length of the list */
1579     size_t listlen;
1580     /* A sigalgs list in string format */
1581     const char *liststr;
1582     /* Whether setting the list should succeed */
1583     int valid;
1584     /* Whether creating a connection with the list should succeed */
1585     int connsuccess;
1586 } sigalgs_list;
1587
1588 static const int validlist1[] = {NID_sha256, EVP_PKEY_RSA};
1589 # ifndef OPENSSL_NO_EC
1590 static const int validlist2[] = {NID_sha256, EVP_PKEY_RSA, NID_sha512, EVP_PKEY_EC};
1591 static const int validlist3[] = {NID_sha512, EVP_PKEY_EC};
1592 # endif
1593 static const int invalidlist1[] = {NID_undef, EVP_PKEY_RSA};
1594 static const int invalidlist2[] = {NID_sha256, NID_undef};
1595 static const int invalidlist3[] = {NID_sha256, EVP_PKEY_RSA, NID_sha256};
1596 static const int invalidlist4[] = {NID_sha256};
1597 static const sigalgs_list testsigalgs[] = {
1598     {validlist1, OSSL_NELEM(validlist1), NULL, 1, 1},
1599 # ifndef OPENSSL_NO_EC
1600     {validlist2, OSSL_NELEM(validlist2), NULL, 1, 1},
1601     {validlist3, OSSL_NELEM(validlist3), NULL, 1, 0},
1602 # endif
1603     {NULL, 0, "RSA+SHA256", 1, 1},
1604 # ifndef OPENSSL_NO_EC
1605     {NULL, 0, "RSA+SHA256:ECDSA+SHA512", 1, 1},
1606     {NULL, 0, "ECDSA+SHA512", 1, 0},
1607 # endif
1608     {invalidlist1, OSSL_NELEM(invalidlist1), NULL, 0, 0},
1609     {invalidlist2, OSSL_NELEM(invalidlist2), NULL, 0, 0},
1610     {invalidlist3, OSSL_NELEM(invalidlist3), NULL, 0, 0},
1611     {invalidlist4, OSSL_NELEM(invalidlist4), NULL, 0, 0},
1612     {NULL, 0, "RSA", 0, 0},
1613     {NULL, 0, "SHA256", 0, 0},
1614     {NULL, 0, "RSA+SHA256:SHA256", 0, 0},
1615     {NULL, 0, "Invalid", 0, 0}
1616 };
1617
1618 static int test_set_sigalgs(int idx)
1619 {
1620     SSL_CTX *cctx = NULL, *sctx = NULL;
1621     SSL *clientssl = NULL, *serverssl = NULL;
1622     int testresult = 0;
1623     const sigalgs_list *curr;
1624     int testctx;
1625
1626     /* Should never happen */
1627     if (!TEST_size_t_le((size_t)idx, OSSL_NELEM(testsigalgs) * 2))
1628         return 0;
1629
1630     testctx = ((size_t)idx < OSSL_NELEM(testsigalgs));
1631     curr = testctx ? &testsigalgs[idx]
1632                    : &testsigalgs[idx - OSSL_NELEM(testsigalgs)];
1633
1634     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
1635                                        TLS1_VERSION, TLS_MAX_VERSION,
1636                                        &sctx, &cctx, cert, privkey)))
1637         return 0;
1638
1639     /*
1640      * TODO(TLS1.3): These APIs cannot set TLSv1.3 sig algs so we just test it
1641      * for TLSv1.2 for now until we add a new API.
1642      */
1643     SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION);
1644
1645     if (testctx) {
1646         int ret;
1647
1648         if (curr->list != NULL)
1649             ret = SSL_CTX_set1_sigalgs(cctx, curr->list, curr->listlen);
1650         else
1651             ret = SSL_CTX_set1_sigalgs_list(cctx, curr->liststr);
1652
1653         if (!ret) {
1654             if (curr->valid)
1655                 TEST_info("Failure setting sigalgs in SSL_CTX (%d)\n", idx);
1656             else
1657                 testresult = 1;
1658             goto end;
1659         }
1660         if (!curr->valid) {
1661             TEST_info("Not-failed setting sigalgs in SSL_CTX (%d)\n", idx);
1662             goto end;
1663         }
1664     }
1665
1666     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
1667                                       &clientssl, NULL, NULL)))
1668         goto end;
1669
1670     if (!testctx) {
1671         int ret;
1672
1673         if (curr->list != NULL)
1674             ret = SSL_set1_sigalgs(clientssl, curr->list, curr->listlen);
1675         else
1676             ret = SSL_set1_sigalgs_list(clientssl, curr->liststr);
1677         if (!ret) {
1678             if (curr->valid)
1679                 TEST_info("Failure setting sigalgs in SSL (%d)\n", idx);
1680             else
1681                 testresult = 1;
1682             goto end;
1683         }
1684         if (!curr->valid)
1685             goto end;
1686     }
1687
1688     if (!TEST_int_eq(create_ssl_connection(serverssl, clientssl,
1689                                            SSL_ERROR_NONE),
1690                 curr->connsuccess))
1691         goto end;
1692
1693     testresult = 1;
1694
1695  end:
1696     SSL_free(serverssl);
1697     SSL_free(clientssl);
1698     SSL_CTX_free(sctx);
1699     SSL_CTX_free(cctx);
1700
1701     return testresult;
1702 }
1703 #endif
1704
1705 #ifndef OPENSSL_NO_TLS1_3
1706
1707 static SSL_SESSION *clientpsk = NULL;
1708 static SSL_SESSION *serverpsk = NULL;
1709 static const char *pskid = "Identity";
1710 static const char *srvid;
1711
1712 static int use_session_cb_cnt = 0;
1713 static int find_session_cb_cnt = 0;
1714 static int psk_client_cb_cnt = 0;
1715 static int psk_server_cb_cnt = 0;
1716
1717 static int use_session_cb(SSL *ssl, const EVP_MD *md, const unsigned char **id,
1718                           size_t *idlen, SSL_SESSION **sess)
1719 {
1720     switch (++use_session_cb_cnt) {
1721     case 1:
1722         /* The first call should always have a NULL md */
1723         if (md != NULL)
1724             return 0;
1725         break;
1726
1727     case 2:
1728         /* The second call should always have an md */
1729         if (md == NULL)
1730             return 0;
1731         break;
1732
1733     default:
1734         /* We should only be called a maximum of twice */
1735         return 0;
1736     }
1737
1738     if (clientpsk != NULL)
1739         SSL_SESSION_up_ref(clientpsk);
1740
1741     *sess = clientpsk;
1742     *id = (const unsigned char *)pskid;
1743     *idlen = strlen(pskid);
1744
1745     return 1;
1746 }
1747
1748 #ifndef OPENSSL_NO_PSK
1749 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *id,
1750                                   unsigned int max_id_len,
1751                                   unsigned char *psk,
1752                                   unsigned int max_psk_len)
1753 {
1754     unsigned int psklen = 0;
1755
1756     psk_client_cb_cnt++;
1757
1758     if (strlen(pskid) + 1 > max_id_len)
1759         return 0;
1760
1761     /* We should only ever be called a maximum of twice per connection */
1762     if (psk_client_cb_cnt > 2)
1763         return 0;
1764
1765     if (clientpsk == NULL)
1766         return 0;
1767
1768     /* We'll reuse the PSK we set up for TLSv1.3 */
1769     if (SSL_SESSION_get_master_key(clientpsk, NULL, 0) > max_psk_len)
1770         return 0;
1771     psklen = SSL_SESSION_get_master_key(clientpsk, psk, max_psk_len);
1772     strncpy(id, pskid, max_id_len);
1773
1774     return psklen;
1775 }
1776 #endif /* OPENSSL_NO_PSK */
1777
1778 static int find_session_cb(SSL *ssl, const unsigned char *identity,
1779                            size_t identity_len, SSL_SESSION **sess)
1780 {
1781     find_session_cb_cnt++;
1782
1783     /* We should only ever be called a maximum of twice per connection */
1784     if (find_session_cb_cnt > 2)
1785         return 0;
1786
1787     if (serverpsk == NULL)
1788         return 0;
1789
1790     /* Identity should match that set by the client */
1791     if (strlen(srvid) != identity_len
1792             || strncmp(srvid, (const char *)identity, identity_len) != 0) {
1793         /* No PSK found, continue but without a PSK */
1794         *sess = NULL;
1795         return 1;
1796     }
1797
1798     SSL_SESSION_up_ref(serverpsk);
1799     *sess = serverpsk;
1800
1801     return 1;
1802 }
1803
1804 #ifndef OPENSSL_NO_PSK
1805 static unsigned int psk_server_cb(SSL *ssl, const char *identity,
1806                                   unsigned char *psk, unsigned int max_psk_len)
1807 {
1808     unsigned int psklen = 0;
1809
1810     psk_server_cb_cnt++;
1811
1812     /* We should only ever be called a maximum of twice per connection */
1813     if (find_session_cb_cnt > 2)
1814         return 0;
1815
1816     if (serverpsk == NULL)
1817         return 0;
1818
1819     /* Identity should match that set by the client */
1820     if (strcmp(srvid, identity) != 0) {
1821         return 0;
1822     }
1823
1824     /* We'll reuse the PSK we set up for TLSv1.3 */
1825     if (SSL_SESSION_get_master_key(serverpsk, NULL, 0) > max_psk_len)
1826         return 0;
1827     psklen = SSL_SESSION_get_master_key(serverpsk, psk, max_psk_len);
1828
1829     return psklen;
1830 }
1831 #endif /* OPENSSL_NO_PSK */
1832
1833 #define MSG1    "Hello"
1834 #define MSG2    "World."
1835 #define MSG3    "This"
1836 #define MSG4    "is"
1837 #define MSG5    "a"
1838 #define MSG6    "test"
1839 #define MSG7    "message."
1840
1841 #define TLS13_AES_256_GCM_SHA384_BYTES  ((const unsigned char *)"\x13\x02")
1842 #define TLS13_AES_128_GCM_SHA256_BYTES  ((const unsigned char *)"\x13\x01")
1843
1844 /*
1845  * Helper method to setup objects for early data test. Caller frees objects on
1846  * error.
1847  */
1848 static int setupearly_data_test(SSL_CTX **cctx, SSL_CTX **sctx, SSL **clientssl,
1849                                 SSL **serverssl, SSL_SESSION **sess, int idx)
1850 {
1851     if (*sctx == NULL
1852             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(),
1853                                               TLS_client_method(),
1854                                               TLS1_VERSION, TLS_MAX_VERSION,
1855                                               sctx, cctx, cert, privkey)))
1856         return 0;
1857
1858     if (!TEST_true(SSL_CTX_set_max_early_data(*sctx, SSL3_RT_MAX_PLAIN_LENGTH)))
1859         return 0;
1860
1861     if (idx == 1) {
1862         /* When idx == 1 we repeat the tests with read_ahead set */
1863         SSL_CTX_set_read_ahead(*cctx, 1);
1864         SSL_CTX_set_read_ahead(*sctx, 1);
1865     } else if (idx == 2) {
1866         /* When idx == 2 we are doing early_data with a PSK. Set up callbacks */
1867         SSL_CTX_set_psk_use_session_callback(*cctx, use_session_cb);
1868         SSL_CTX_set_psk_find_session_callback(*sctx, find_session_cb);
1869         use_session_cb_cnt = 0;
1870         find_session_cb_cnt = 0;
1871         srvid = pskid;
1872     }
1873
1874     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
1875                                       NULL, NULL)))
1876         return 0;
1877
1878     /*
1879      * For one of the run throughs (doesn't matter which one), we'll try sending
1880      * some SNI data in the initial ClientHello. This will be ignored (because
1881      * there is no SNI cb set up by the server), so it should not impact
1882      * early_data.
1883      */
1884     if (idx == 1
1885             && !TEST_true(SSL_set_tlsext_host_name(*clientssl, "localhost")))
1886         return 0;
1887
1888     if (idx == 2) {
1889         /* Create the PSK */
1890         const SSL_CIPHER *cipher = NULL;
1891         const unsigned char key[] = {
1892             0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
1893             0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
1894             0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
1895             0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
1896             0x2c, 0x2d, 0x2e, 0x2f
1897         };
1898
1899         cipher = SSL_CIPHER_find(*clientssl, TLS13_AES_256_GCM_SHA384_BYTES);
1900         clientpsk = SSL_SESSION_new();
1901         if (!TEST_ptr(clientpsk)
1902                 || !TEST_ptr(cipher)
1903                 || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
1904                                                           sizeof(key)))
1905                 || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
1906                 || !TEST_true(
1907                         SSL_SESSION_set_protocol_version(clientpsk,
1908                                                          TLS1_3_VERSION))
1909                    /*
1910                     * We just choose an arbitrary value for max_early_data which
1911                     * should be big enough for testing purposes.
1912                     */
1913                 || !TEST_true(SSL_SESSION_set_max_early_data(clientpsk,
1914                                                              0x100))
1915                 || !TEST_true(SSL_SESSION_up_ref(clientpsk))) {
1916             SSL_SESSION_free(clientpsk);
1917             clientpsk = NULL;
1918             return 0;
1919         }
1920         serverpsk = clientpsk;
1921
1922         if (sess != NULL) {
1923             if (!TEST_true(SSL_SESSION_up_ref(clientpsk))) {
1924                 SSL_SESSION_free(clientpsk);
1925                 SSL_SESSION_free(serverpsk);
1926                 clientpsk = serverpsk = NULL;
1927                 return 0;
1928             }
1929             *sess = clientpsk;
1930         }
1931         return 1;
1932     }
1933
1934     if (sess == NULL)
1935         return 1;
1936
1937     if (!TEST_true(create_ssl_connection(*serverssl, *clientssl,
1938                                          SSL_ERROR_NONE)))
1939         return 0;
1940
1941     *sess = SSL_get1_session(*clientssl);
1942     SSL_shutdown(*clientssl);
1943     SSL_shutdown(*serverssl);
1944     SSL_free(*serverssl);
1945     SSL_free(*clientssl);
1946     *serverssl = *clientssl = NULL;
1947
1948     if (!TEST_true(create_ssl_objects(*sctx, *cctx, serverssl,
1949                                       clientssl, NULL, NULL))
1950             || !TEST_true(SSL_set_session(*clientssl, *sess)))
1951         return 0;
1952
1953     return 1;
1954 }
1955
1956 static int test_early_data_read_write(int idx)
1957 {
1958     SSL_CTX *cctx = NULL, *sctx = NULL;
1959     SSL *clientssl = NULL, *serverssl = NULL;
1960     int testresult = 0;
1961     SSL_SESSION *sess = NULL;
1962     unsigned char buf[20], data[1024];
1963     size_t readbytes, written, eoedlen, rawread, rawwritten;
1964     BIO *rbio;
1965
1966     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
1967                                         &serverssl, &sess, idx)))
1968         goto end;
1969
1970     /* Write and read some early data */
1971     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
1972                                         &written))
1973             || !TEST_size_t_eq(written, strlen(MSG1))
1974             || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
1975                                                 sizeof(buf), &readbytes),
1976                             SSL_READ_EARLY_DATA_SUCCESS)
1977             || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
1978             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
1979                             SSL_EARLY_DATA_ACCEPTED))
1980         goto end;
1981
1982     /*
1983      * Server should be able to write data, and client should be able to
1984      * read it.
1985      */
1986     if (!TEST_true(SSL_write_early_data(serverssl, MSG2, strlen(MSG2),
1987                                         &written))
1988             || !TEST_size_t_eq(written, strlen(MSG2))
1989             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
1990             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
1991         goto end;
1992
1993     /* Even after reading normal data, client should be able write early data */
1994     if (!TEST_true(SSL_write_early_data(clientssl, MSG3, strlen(MSG3),
1995                                         &written))
1996             || !TEST_size_t_eq(written, strlen(MSG3)))
1997         goto end;
1998
1999     /* Server should still be able read early data after writing data */
2000     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2001                                          &readbytes),
2002                      SSL_READ_EARLY_DATA_SUCCESS)
2003             || !TEST_mem_eq(buf, readbytes, MSG3, strlen(MSG3)))
2004         goto end;
2005
2006     /* Write more data from server and read it from client */
2007     if (!TEST_true(SSL_write_early_data(serverssl, MSG4, strlen(MSG4),
2008                                         &written))
2009             || !TEST_size_t_eq(written, strlen(MSG4))
2010             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2011             || !TEST_mem_eq(buf, readbytes, MSG4, strlen(MSG4)))
2012         goto end;
2013
2014     /*
2015      * If client writes normal data it should mean writing early data is no
2016      * longer possible.
2017      */
2018     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
2019             || !TEST_size_t_eq(written, strlen(MSG5))
2020             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2021                             SSL_EARLY_DATA_ACCEPTED))
2022         goto end;
2023
2024     /*
2025      * At this point the client has written EndOfEarlyData, ClientFinished and
2026      * normal (fully protected) data. We are going to cause a delay between the
2027      * arrival of EndOfEarlyData and ClientFinished. We read out all the data
2028      * in the read BIO, and then just put back the EndOfEarlyData message.
2029      */
2030     rbio = SSL_get_rbio(serverssl);
2031     if (!TEST_true(BIO_read_ex(rbio, data, sizeof(data), &rawread))
2032             || !TEST_size_t_lt(rawread, sizeof(data))
2033             || !TEST_size_t_gt(rawread, SSL3_RT_HEADER_LENGTH))
2034         goto end;
2035
2036     /* Record length is in the 4th and 5th bytes of the record header */
2037     eoedlen = SSL3_RT_HEADER_LENGTH + (data[3] << 8 | data[4]);
2038     if (!TEST_true(BIO_write_ex(rbio, data, eoedlen, &rawwritten))
2039             || !TEST_size_t_eq(rawwritten, eoedlen))
2040         goto end;
2041
2042     /* Server should be told that there is no more early data */
2043     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2044                                          &readbytes),
2045                      SSL_READ_EARLY_DATA_FINISH)
2046             || !TEST_size_t_eq(readbytes, 0))
2047         goto end;
2048
2049     /*
2050      * Server has not finished init yet, so should still be able to write early
2051      * data.
2052      */
2053     if (!TEST_true(SSL_write_early_data(serverssl, MSG6, strlen(MSG6),
2054                                         &written))
2055             || !TEST_size_t_eq(written, strlen(MSG6)))
2056         goto end;
2057
2058     /* Push the ClientFinished and the normal data back into the server rbio */
2059     if (!TEST_true(BIO_write_ex(rbio, data + eoedlen, rawread - eoedlen,
2060                                 &rawwritten))
2061             || !TEST_size_t_eq(rawwritten, rawread - eoedlen))
2062         goto end;
2063
2064     /* Server should be able to read normal data */
2065     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2066             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
2067         goto end;
2068
2069     /* Client and server should not be able to write/read early data now */
2070     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
2071                                          &written)))
2072         goto end;
2073     ERR_clear_error();
2074     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2075                                          &readbytes),
2076                      SSL_READ_EARLY_DATA_ERROR))
2077         goto end;
2078     ERR_clear_error();
2079
2080     /* Client should be able to read the data sent by the server */
2081     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2082             || !TEST_mem_eq(buf, readbytes, MSG6, strlen(MSG6)))
2083         goto end;
2084
2085     /*
2086      * Make sure we process the two NewSessionTickets. These arrive
2087      * post-handshake. We attempt reads which we do not expect to return any
2088      * data.
2089      */
2090     if (!TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2091             || !TEST_false(SSL_read_ex(clientssl, buf, sizeof(buf),
2092                            &readbytes)))
2093         goto end;
2094
2095     /* Server should be able to write normal data */
2096     if (!TEST_true(SSL_write_ex(serverssl, MSG7, strlen(MSG7), &written))
2097             || !TEST_size_t_eq(written, strlen(MSG7))
2098             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2099             || !TEST_mem_eq(buf, readbytes, MSG7, strlen(MSG7)))
2100         goto end;
2101
2102     SSL_SESSION_free(sess);
2103     sess = SSL_get1_session(clientssl);
2104     use_session_cb_cnt = 0;
2105     find_session_cb_cnt = 0;
2106
2107     SSL_shutdown(clientssl);
2108     SSL_shutdown(serverssl);
2109     SSL_free(serverssl);
2110     SSL_free(clientssl);
2111     serverssl = clientssl = NULL;
2112     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2113                                       &clientssl, NULL, NULL))
2114             || !TEST_true(SSL_set_session(clientssl, sess)))
2115         goto end;
2116
2117     /* Write and read some early data */
2118     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2119                                         &written))
2120             || !TEST_size_t_eq(written, strlen(MSG1))
2121             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2122                                                 &readbytes),
2123                             SSL_READ_EARLY_DATA_SUCCESS)
2124             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
2125         goto end;
2126
2127     if (!TEST_int_gt(SSL_connect(clientssl), 0)
2128             || !TEST_int_gt(SSL_accept(serverssl), 0))
2129         goto end;
2130
2131     /* Client and server should not be able to write/read early data now */
2132     if (!TEST_false(SSL_write_early_data(clientssl, MSG6, strlen(MSG6),
2133                                          &written)))
2134         goto end;
2135     ERR_clear_error();
2136     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2137                                          &readbytes),
2138                      SSL_READ_EARLY_DATA_ERROR))
2139         goto end;
2140     ERR_clear_error();
2141
2142     /* Client and server should be able to write/read normal data */
2143     if (!TEST_true(SSL_write_ex(clientssl, MSG5, strlen(MSG5), &written))
2144             || !TEST_size_t_eq(written, strlen(MSG5))
2145             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2146             || !TEST_size_t_eq(readbytes, strlen(MSG5)))
2147         goto end;
2148
2149     testresult = 1;
2150
2151  end:
2152     SSL_SESSION_free(sess);
2153     SSL_SESSION_free(clientpsk);
2154     SSL_SESSION_free(serverpsk);
2155     clientpsk = serverpsk = NULL;
2156     SSL_free(serverssl);
2157     SSL_free(clientssl);
2158     SSL_CTX_free(sctx);
2159     SSL_CTX_free(cctx);
2160     return testresult;
2161 }
2162
2163 static int allow_ed_cb_called = 0;
2164
2165 static int allow_early_data_cb(SSL *s, void *arg)
2166 {
2167     int *usecb = (int *)arg;
2168
2169     allow_ed_cb_called++;
2170
2171     if (*usecb == 1)
2172         return 0;
2173
2174     return 1;
2175 }
2176
2177 /*
2178  * idx == 0: Standard early_data setup
2179  * idx == 1: early_data setup using read_ahead
2180  * usecb == 0: Don't use a custom early data callback
2181  * usecb == 1: Use a custom early data callback and reject the early data
2182  * usecb == 2: Use a custom early data callback and accept the early data
2183  * confopt == 0: Configure anti-replay directly
2184  * confopt == 1: Configure anti-replay using SSL_CONF
2185  */
2186 static int test_early_data_replay_int(int idx, int usecb, int confopt)
2187 {
2188     SSL_CTX *cctx = NULL, *sctx = NULL;
2189     SSL *clientssl = NULL, *serverssl = NULL;
2190     int testresult = 0;
2191     SSL_SESSION *sess = NULL;
2192     size_t readbytes, written;
2193     unsigned char buf[20];
2194
2195     allow_ed_cb_called = 0;
2196
2197     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2198                                        TLS1_VERSION, TLS_MAX_VERSION, &sctx,
2199                                        &cctx, cert, privkey)))
2200         return 0;
2201
2202     if (usecb > 0) {
2203         if (confopt == 0) {
2204             SSL_CTX_set_options(sctx, SSL_OP_NO_ANTI_REPLAY);
2205         } else {
2206             SSL_CONF_CTX *confctx = SSL_CONF_CTX_new();
2207
2208             if (!TEST_ptr(confctx))
2209                 goto end;
2210             SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
2211                                             | SSL_CONF_FLAG_SERVER);
2212             SSL_CONF_CTX_set_ssl_ctx(confctx, sctx);
2213             if (!TEST_int_eq(SSL_CONF_cmd(confctx, "Options", "-AntiReplay"),
2214                              2)) {
2215                 SSL_CONF_CTX_free(confctx);
2216                 goto end;
2217             }
2218             SSL_CONF_CTX_free(confctx);
2219         }
2220         SSL_CTX_set_allow_early_data_cb(sctx, allow_early_data_cb, &usecb);
2221     }
2222
2223     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2224                                         &serverssl, &sess, idx)))
2225         goto end;
2226
2227     /*
2228      * The server is configured to accept early data. Create a connection to
2229      * "use up" the ticket
2230      */
2231     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2232             || !TEST_true(SSL_session_reused(clientssl)))
2233         goto end;
2234
2235     SSL_shutdown(clientssl);
2236     SSL_shutdown(serverssl);
2237     SSL_free(serverssl);
2238     SSL_free(clientssl);
2239     serverssl = clientssl = NULL;
2240
2241     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2242                                       &clientssl, NULL, NULL))
2243             || !TEST_true(SSL_set_session(clientssl, sess)))
2244         goto end;
2245
2246     /* Write and read some early data */
2247     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2248                                         &written))
2249             || !TEST_size_t_eq(written, strlen(MSG1)))
2250         goto end;
2251
2252     if (usecb <= 1) {
2253         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2254                                              &readbytes),
2255                          SSL_READ_EARLY_DATA_FINISH)
2256                    /*
2257                     * The ticket was reused, so the we should have rejected the
2258                     * early data
2259                     */
2260                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2261                                 SSL_EARLY_DATA_REJECTED))
2262             goto end;
2263     } else {
2264         /* In this case the callback decides to accept the early data */
2265         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2266                                              &readbytes),
2267                          SSL_READ_EARLY_DATA_SUCCESS)
2268                 || !TEST_mem_eq(MSG1, strlen(MSG1), buf, readbytes)
2269                    /*
2270                     * Server will have sent its flight so client can now send
2271                     * end of early data and complete its half of the handshake
2272                     */
2273                 || !TEST_int_gt(SSL_connect(clientssl), 0)
2274                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2275                                              &readbytes),
2276                                 SSL_READ_EARLY_DATA_FINISH)
2277                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2278                                 SSL_EARLY_DATA_ACCEPTED))
2279             goto end;
2280     }
2281
2282     /* Complete the connection */
2283     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
2284             || !TEST_int_eq(SSL_session_reused(clientssl), (usecb > 0) ? 1 : 0)
2285             || !TEST_int_eq(allow_ed_cb_called, usecb > 0 ? 1 : 0))
2286         goto end;
2287
2288     testresult = 1;
2289
2290  end:
2291     SSL_SESSION_free(sess);
2292     SSL_SESSION_free(clientpsk);
2293     SSL_SESSION_free(serverpsk);
2294     clientpsk = serverpsk = NULL;
2295     SSL_free(serverssl);
2296     SSL_free(clientssl);
2297     SSL_CTX_free(sctx);
2298     SSL_CTX_free(cctx);
2299     return testresult;
2300 }
2301
2302 static int test_early_data_replay(int idx)
2303 {
2304     int ret = 1, usecb, confopt;
2305
2306     for (usecb = 0; usecb < 3; usecb++) {
2307         for (confopt = 0; confopt < 2; confopt++)
2308             ret &= test_early_data_replay_int(idx, usecb, confopt);
2309     }
2310
2311     return ret;
2312 }
2313
2314 /*
2315  * Helper function to test that a server attempting to read early data can
2316  * handle a connection from a client where the early data should be skipped.
2317  * testtype: 0 == No HRR
2318  * testtype: 1 == HRR
2319  * testtype: 2 == recv_max_early_data set to 0
2320  */
2321 static int early_data_skip_helper(int testtype, int idx)
2322 {
2323     SSL_CTX *cctx = NULL, *sctx = NULL;
2324     SSL *clientssl = NULL, *serverssl = NULL;
2325     int testresult = 0;
2326     SSL_SESSION *sess = NULL;
2327     unsigned char buf[20];
2328     size_t readbytes, written;
2329
2330     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2331                                         &serverssl, &sess, idx)))
2332         goto end;
2333
2334     if (testtype == 1) {
2335         /* Force an HRR to occur */
2336         if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
2337             goto end;
2338     } else if (idx == 2) {
2339         /*
2340          * We force early_data rejection by ensuring the PSK identity is
2341          * unrecognised
2342          */
2343         srvid = "Dummy Identity";
2344     } else {
2345         /*
2346          * Deliberately corrupt the creation time. We take 20 seconds off the
2347          * time. It could be any value as long as it is not within tolerance.
2348          * This should mean the ticket is rejected.
2349          */
2350         if (!TEST_true(SSL_SESSION_set_time(sess, (long)(time(NULL) - 20))))
2351             goto end;
2352     }
2353
2354     if (testtype == 2
2355             && !TEST_true(SSL_set_recv_max_early_data(serverssl, 0)))
2356         goto end;
2357
2358     /* Write some early data */
2359     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2360                                         &written))
2361             || !TEST_size_t_eq(written, strlen(MSG1)))
2362         goto end;
2363
2364     /* Server should reject the early data */
2365     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2366                                          &readbytes),
2367                      SSL_READ_EARLY_DATA_FINISH)
2368             || !TEST_size_t_eq(readbytes, 0)
2369             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2370                             SSL_EARLY_DATA_REJECTED))
2371         goto end;
2372
2373     if (testtype == 1) {
2374         /*
2375          * Finish off the handshake. We perform the same writes and reads as
2376          * further down but we expect them to fail due to the incomplete
2377          * handshake.
2378          */
2379         if (!TEST_false(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2380                 || !TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf),
2381                                &readbytes)))
2382             goto end;
2383     } else if (testtype == 2) {
2384         /*
2385          * This client has sent more early_data than we are willing to skip so
2386          * the connection should abort.
2387          */
2388         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2389                 || !TEST_int_eq(SSL_get_error(serverssl, 0), SSL_ERROR_SSL))
2390             goto end;
2391
2392         /* Connection has failed - nothing more to do */
2393         testresult = 1;
2394         goto end;
2395     }
2396
2397     /*
2398      * Should be able to send normal data despite rejection of early data. The
2399      * early_data should be skipped.
2400      */
2401     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2402             || !TEST_size_t_eq(written, strlen(MSG2))
2403             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2404                             SSL_EARLY_DATA_REJECTED)
2405             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2406             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2407         goto end;
2408
2409     testresult = 1;
2410
2411  end:
2412     SSL_SESSION_free(clientpsk);
2413     SSL_SESSION_free(serverpsk);
2414     clientpsk = serverpsk = NULL;
2415     SSL_SESSION_free(sess);
2416     SSL_free(serverssl);
2417     SSL_free(clientssl);
2418     SSL_CTX_free(sctx);
2419     SSL_CTX_free(cctx);
2420     return testresult;
2421 }
2422
2423 /*
2424  * Test that a server attempting to read early data can handle a connection
2425  * from a client where the early data is not acceptable.
2426  */
2427 static int test_early_data_skip(int idx)
2428 {
2429     return early_data_skip_helper(0, idx);
2430 }
2431
2432 /*
2433  * Test that a server attempting to read early data can handle a connection
2434  * from a client where an HRR occurs.
2435  */
2436 static int test_early_data_skip_hrr(int idx)
2437 {
2438     return early_data_skip_helper(1, idx);
2439 }
2440
2441 /*
2442  * Test that a server attempting to read early data will abort if it tries to
2443  * skip over too much.
2444  */
2445 static int test_early_data_skip_abort(int idx)
2446 {
2447     return early_data_skip_helper(2, idx);
2448 }
2449
2450 /*
2451  * Test that a server attempting to read early data can handle a connection
2452  * from a client that doesn't send any.
2453  */
2454 static int test_early_data_not_sent(int idx)
2455 {
2456     SSL_CTX *cctx = NULL, *sctx = NULL;
2457     SSL *clientssl = NULL, *serverssl = NULL;
2458     int testresult = 0;
2459     SSL_SESSION *sess = NULL;
2460     unsigned char buf[20];
2461     size_t readbytes, written;
2462
2463     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2464                                         &serverssl, &sess, idx)))
2465         goto end;
2466
2467     /* Write some data - should block due to handshake with server */
2468     SSL_set_connect_state(clientssl);
2469     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2470         goto end;
2471
2472     /* Server should detect that early data has not been sent */
2473     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2474                                          &readbytes),
2475                      SSL_READ_EARLY_DATA_FINISH)
2476             || !TEST_size_t_eq(readbytes, 0)
2477             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2478                             SSL_EARLY_DATA_NOT_SENT)
2479             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2480                             SSL_EARLY_DATA_NOT_SENT))
2481         goto end;
2482
2483     /* Continue writing the message we started earlier */
2484     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2485             || !TEST_size_t_eq(written, strlen(MSG1))
2486             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2487             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2488             || !SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written)
2489             || !TEST_size_t_eq(written, strlen(MSG2)))
2490         goto end;
2491
2492     if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
2493             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2494         goto end;
2495
2496     testresult = 1;
2497
2498  end:
2499     SSL_SESSION_free(sess);
2500     SSL_SESSION_free(clientpsk);
2501     SSL_SESSION_free(serverpsk);
2502     clientpsk = serverpsk = NULL;
2503     SSL_free(serverssl);
2504     SSL_free(clientssl);
2505     SSL_CTX_free(sctx);
2506     SSL_CTX_free(cctx);
2507     return testresult;
2508 }
2509
2510 static int hostname_cb(SSL *s, int *al, void *arg)
2511 {
2512     const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2513
2514     if (hostname != NULL && strcmp(hostname, "goodhost") == 0)
2515         return  SSL_TLSEXT_ERR_OK;
2516
2517     return SSL_TLSEXT_ERR_NOACK;
2518 }
2519
2520 static const char *servalpn;
2521
2522 static int alpn_select_cb(SSL *ssl, const unsigned char **out,
2523                           unsigned char *outlen, const unsigned char *in,
2524                           unsigned int inlen, void *arg)
2525 {
2526     unsigned int protlen = 0;
2527     const unsigned char *prot;
2528
2529     for (prot = in; prot < in + inlen; prot += protlen) {
2530         protlen = *prot++;
2531         if (in + inlen < prot + protlen)
2532             return SSL_TLSEXT_ERR_NOACK;
2533
2534         if (protlen == strlen(servalpn)
2535                 && memcmp(prot, servalpn, protlen) == 0) {
2536             *out = prot;
2537             *outlen = protlen;
2538             return SSL_TLSEXT_ERR_OK;
2539         }
2540     }
2541
2542     return SSL_TLSEXT_ERR_NOACK;
2543 }
2544
2545 /* Test that a PSK can be used to send early_data */
2546 static int test_early_data_psk(int idx)
2547 {
2548     SSL_CTX *cctx = NULL, *sctx = NULL;
2549     SSL *clientssl = NULL, *serverssl = NULL;
2550     int testresult = 0;
2551     SSL_SESSION *sess = NULL;
2552     unsigned char alpnlist[] = {
2553         0x08, 'g', 'o', 'o', 'd', 'a', 'l', 'p', 'n', 0x07, 'b', 'a', 'd', 'a',
2554         'l', 'p', 'n'
2555     };
2556 #define GOODALPNLEN     9
2557 #define BADALPNLEN      8
2558 #define GOODALPN        (alpnlist)
2559 #define BADALPN         (alpnlist + GOODALPNLEN)
2560     int err = 0;
2561     unsigned char buf[20];
2562     size_t readbytes, written;
2563     int readearlyres = SSL_READ_EARLY_DATA_SUCCESS, connectres = 1;
2564     int edstatus = SSL_EARLY_DATA_ACCEPTED;
2565
2566     /* We always set this up with a final parameter of "2" for PSK */
2567     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2568                                         &serverssl, &sess, 2)))
2569         goto end;
2570
2571     servalpn = "goodalpn";
2572
2573     /*
2574      * Note: There is no test for inconsistent SNI with late client detection.
2575      * This is because servers do not acknowledge SNI even if they are using
2576      * it in a resumption handshake - so it is not actually possible for a
2577      * client to detect a problem.
2578      */
2579     switch (idx) {
2580     case 0:
2581         /* Set inconsistent SNI (early client detection) */
2582         err = SSL_R_INCONSISTENT_EARLY_DATA_SNI;
2583         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2584                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "badhost")))
2585             goto end;
2586         break;
2587
2588     case 1:
2589         /* Set inconsistent ALPN (early client detection) */
2590         err = SSL_R_INCONSISTENT_EARLY_DATA_ALPN;
2591         /* SSL_set_alpn_protos returns 0 for success and 1 for failure */
2592         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN,
2593                                                       GOODALPNLEN))
2594                 || !TEST_false(SSL_set_alpn_protos(clientssl, BADALPN,
2595                                                    BADALPNLEN)))
2596             goto end;
2597         break;
2598
2599     case 2:
2600         /*
2601          * Set invalid protocol version. Technically this affects PSKs without
2602          * early_data too, but we test it here because it is similar to the
2603          * SNI/ALPN consistency tests.
2604          */
2605         err = SSL_R_BAD_PSK;
2606         if (!TEST_true(SSL_SESSION_set_protocol_version(sess, TLS1_2_VERSION)))
2607             goto end;
2608         break;
2609
2610     case 3:
2611         /*
2612          * Set inconsistent SNI (server detected). In this case the connection
2613          * will succeed but reject early_data.
2614          */
2615         SSL_SESSION_free(serverpsk);
2616         serverpsk = SSL_SESSION_dup(clientpsk);
2617         if (!TEST_ptr(serverpsk)
2618                 || !TEST_true(SSL_SESSION_set1_hostname(serverpsk, "badhost")))
2619             goto end;
2620         edstatus = SSL_EARLY_DATA_REJECTED;
2621         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2622         /* Fall through */
2623     case 4:
2624         /* Set consistent SNI */
2625         if (!TEST_true(SSL_SESSION_set1_hostname(sess, "goodhost"))
2626                 || !TEST_true(SSL_set_tlsext_host_name(clientssl, "goodhost"))
2627                 || !TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx,
2628                                 hostname_cb)))
2629             goto end;
2630         break;
2631
2632     case 5:
2633         /*
2634          * Set inconsistent ALPN (server detected). In this case the connection
2635          * will succeed but reject early_data.
2636          */
2637         servalpn = "badalpn";
2638         edstatus = SSL_EARLY_DATA_REJECTED;
2639         readearlyres = SSL_READ_EARLY_DATA_FINISH;
2640         /* Fall through */
2641     case 6:
2642         /*
2643          * Set consistent ALPN.
2644          * SSL_set_alpn_protos returns 0 for success and 1 for failure. It
2645          * accepts a list of protos (each one length prefixed).
2646          * SSL_set1_alpn_selected accepts a single protocol (not length
2647          * prefixed)
2648          */
2649         if (!TEST_true(SSL_SESSION_set1_alpn_selected(sess, GOODALPN + 1,
2650                                                       GOODALPNLEN - 1))
2651                 || !TEST_false(SSL_set_alpn_protos(clientssl, GOODALPN,
2652                                                    GOODALPNLEN)))
2653             goto end;
2654
2655         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
2656         break;
2657
2658     case 7:
2659         /* Set inconsistent ALPN (late client detection) */
2660         SSL_SESSION_free(serverpsk);
2661         serverpsk = SSL_SESSION_dup(clientpsk);
2662         if (!TEST_ptr(serverpsk)
2663                 || !TEST_true(SSL_SESSION_set1_alpn_selected(clientpsk,
2664                                                              BADALPN + 1,
2665                                                              BADALPNLEN - 1))
2666                 || !TEST_true(SSL_SESSION_set1_alpn_selected(serverpsk,
2667                                                              GOODALPN + 1,
2668                                                              GOODALPNLEN - 1))
2669                 || !TEST_false(SSL_set_alpn_protos(clientssl, alpnlist,
2670                                                    sizeof(alpnlist))))
2671             goto end;
2672         SSL_CTX_set_alpn_select_cb(sctx, alpn_select_cb, NULL);
2673         edstatus = SSL_EARLY_DATA_ACCEPTED;
2674         readearlyres = SSL_READ_EARLY_DATA_SUCCESS;
2675         /* SSL_connect() call should fail */
2676         connectres = -1;
2677         break;
2678
2679     default:
2680         TEST_error("Bad test index");
2681         goto end;
2682     }
2683
2684     SSL_set_connect_state(clientssl);
2685     if (err != 0) {
2686         if (!TEST_false(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2687                                             &written))
2688                 || !TEST_int_eq(SSL_get_error(clientssl, 0), SSL_ERROR_SSL)
2689                 || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()), err))
2690             goto end;
2691     } else {
2692         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2693                                             &written)))
2694             goto end;
2695
2696         if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2697                                              &readbytes), readearlyres)
2698                 || (readearlyres == SSL_READ_EARLY_DATA_SUCCESS
2699                     && !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1)))
2700                 || !TEST_int_eq(SSL_get_early_data_status(serverssl), edstatus)
2701                 || !TEST_int_eq(SSL_connect(clientssl), connectres))
2702             goto end;
2703     }
2704
2705     testresult = 1;
2706
2707  end:
2708     SSL_SESSION_free(sess);
2709     SSL_SESSION_free(clientpsk);
2710     SSL_SESSION_free(serverpsk);
2711     clientpsk = serverpsk = NULL;
2712     SSL_free(serverssl);
2713     SSL_free(clientssl);
2714     SSL_CTX_free(sctx);
2715     SSL_CTX_free(cctx);
2716     return testresult;
2717 }
2718
2719 /*
2720  * Test that a server that doesn't try to read early data can handle a
2721  * client sending some.
2722  */
2723 static int test_early_data_not_expected(int idx)
2724 {
2725     SSL_CTX *cctx = NULL, *sctx = NULL;
2726     SSL *clientssl = NULL, *serverssl = NULL;
2727     int testresult = 0;
2728     SSL_SESSION *sess = NULL;
2729     unsigned char buf[20];
2730     size_t readbytes, written;
2731
2732     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2733                                         &serverssl, &sess, idx)))
2734         goto end;
2735
2736     /* Write some early data */
2737     if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
2738                                         &written)))
2739         goto end;
2740
2741     /*
2742      * Server should skip over early data and then block waiting for client to
2743      * continue handshake
2744      */
2745     if (!TEST_int_le(SSL_accept(serverssl), 0)
2746      || !TEST_int_gt(SSL_connect(clientssl), 0)
2747      || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2748                      SSL_EARLY_DATA_REJECTED)
2749      || !TEST_int_gt(SSL_accept(serverssl), 0)
2750      || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2751                      SSL_EARLY_DATA_REJECTED))
2752         goto end;
2753
2754     /* Send some normal data from client to server */
2755     if (!TEST_true(SSL_write_ex(clientssl, MSG2, strlen(MSG2), &written))
2756             || !TEST_size_t_eq(written, strlen(MSG2)))
2757         goto end;
2758
2759     if (!TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2760             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2761         goto end;
2762
2763     testresult = 1;
2764
2765  end:
2766     SSL_SESSION_free(sess);
2767     SSL_SESSION_free(clientpsk);
2768     SSL_SESSION_free(serverpsk);
2769     clientpsk = serverpsk = NULL;
2770     SSL_free(serverssl);
2771     SSL_free(clientssl);
2772     SSL_CTX_free(sctx);
2773     SSL_CTX_free(cctx);
2774     return testresult;
2775 }
2776
2777
2778 # ifndef OPENSSL_NO_TLS1_2
2779 /*
2780  * Test that a server attempting to read early data can handle a connection
2781  * from a TLSv1.2 client.
2782  */
2783 static int test_early_data_tls1_2(int idx)
2784 {
2785     SSL_CTX *cctx = NULL, *sctx = NULL;
2786     SSL *clientssl = NULL, *serverssl = NULL;
2787     int testresult = 0;
2788     unsigned char buf[20];
2789     size_t readbytes, written;
2790
2791     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
2792                                         &serverssl, NULL, idx)))
2793         goto end;
2794
2795     /* Write some data - should block due to handshake with server */
2796     SSL_set_max_proto_version(clientssl, TLS1_2_VERSION);
2797     SSL_set_connect_state(clientssl);
2798     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written)))
2799         goto end;
2800
2801     /*
2802      * Server should do TLSv1.2 handshake. First it will block waiting for more
2803      * messages from client after ServerDone. Then SSL_read_early_data should
2804      * finish and detect that early data has not been sent
2805      */
2806     if (!TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2807                                          &readbytes),
2808                      SSL_READ_EARLY_DATA_ERROR))
2809         goto end;
2810
2811     /*
2812      * Continue writing the message we started earlier. Will still block waiting
2813      * for the CCS/Finished from server
2814      */
2815     if (!TEST_false(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2816             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
2817                                                 &readbytes),
2818                             SSL_READ_EARLY_DATA_FINISH)
2819             || !TEST_size_t_eq(readbytes, 0)
2820             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
2821                             SSL_EARLY_DATA_NOT_SENT))
2822         goto end;
2823
2824     /* Continue writing the message we started earlier */
2825     if (!TEST_true(SSL_write_ex(clientssl, MSG1, strlen(MSG1), &written))
2826             || !TEST_size_t_eq(written, strlen(MSG1))
2827             || !TEST_int_eq(SSL_get_early_data_status(clientssl),
2828                             SSL_EARLY_DATA_NOT_SENT)
2829             || !TEST_true(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
2830             || !TEST_mem_eq(buf, readbytes, MSG1, strlen(MSG1))
2831             || !TEST_true(SSL_write_ex(serverssl, MSG2, strlen(MSG2), &written))
2832             || !TEST_size_t_eq(written, strlen(MSG2))
2833             || !SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes)
2834             || !TEST_mem_eq(buf, readbytes, MSG2, strlen(MSG2)))
2835         goto end;
2836
2837     testresult = 1;
2838
2839  end:
2840     SSL_SESSION_free(clientpsk);
2841     SSL_SESSION_free(serverpsk);
2842     clientpsk = serverpsk = NULL;
2843     SSL_free(serverssl);
2844     SSL_free(clientssl);
2845     SSL_CTX_free(sctx);
2846     SSL_CTX_free(cctx);
2847
2848     return testresult;
2849 }
2850 # endif /* OPENSSL_NO_TLS1_2 */
2851
2852 /*
2853  * Test configuring the TLSv1.3 ciphersuites
2854  *
2855  * Test 0: Set a default ciphersuite in the SSL_CTX (no explicit cipher_list)
2856  * Test 1: Set a non-default ciphersuite in the SSL_CTX (no explicit cipher_list)
2857  * Test 2: Set a default ciphersuite in the SSL (no explicit cipher_list)
2858  * Test 3: Set a non-default ciphersuite in the SSL (no explicit cipher_list)
2859  * Test 4: Set a default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2860  * Test 5: Set a non-default ciphersuite in the SSL_CTX (SSL_CTX cipher_list)
2861  * Test 6: Set a default ciphersuite in the SSL (SSL_CTX cipher_list)
2862  * Test 7: Set a non-default ciphersuite in the SSL (SSL_CTX cipher_list)
2863  * Test 8: Set a default ciphersuite in the SSL (SSL cipher_list)
2864  * Test 9: Set a non-default ciphersuite in the SSL (SSL cipher_list)
2865  */
2866 static int test_set_ciphersuite(int idx)
2867 {
2868     SSL_CTX *cctx = NULL, *sctx = NULL;
2869     SSL *clientssl = NULL, *serverssl = NULL;
2870     int testresult = 0;
2871
2872     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2873                                        TLS1_VERSION, TLS_MAX_VERSION,
2874                                        &sctx, &cctx, cert, privkey))
2875             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
2876                            "TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256")))
2877         goto end;
2878
2879     if (idx >=4 && idx <= 7) {
2880         /* SSL_CTX explicit cipher list */
2881         if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-GCM-SHA384")))
2882             goto end;
2883     }
2884
2885     if (idx == 0 || idx == 4) {
2886         /* Default ciphersuite */
2887         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2888                                                 "TLS_AES_128_GCM_SHA256")))
2889             goto end;
2890     } else if (idx == 1 || idx == 5) {
2891         /* Non default ciphersuite */
2892         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2893                                                 "TLS_AES_128_CCM_SHA256")))
2894             goto end;
2895     }
2896
2897     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2898                                           &clientssl, NULL, NULL)))
2899         goto end;
2900
2901     if (idx == 8 || idx == 9) {
2902         /* SSL explicit cipher list */
2903         if (!TEST_true(SSL_set_cipher_list(clientssl, "AES256-GCM-SHA384")))
2904             goto end;
2905     }
2906
2907     if (idx == 2 || idx == 6 || idx == 8) {
2908         /* Default ciphersuite */
2909         if (!TEST_true(SSL_set_ciphersuites(clientssl,
2910                                             "TLS_AES_128_GCM_SHA256")))
2911             goto end;
2912     } else if (idx == 3 || idx == 7 || idx == 9) {
2913         /* Non default ciphersuite */
2914         if (!TEST_true(SSL_set_ciphersuites(clientssl,
2915                                             "TLS_AES_128_CCM_SHA256")))
2916             goto end;
2917     }
2918
2919     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
2920         goto end;
2921
2922     testresult = 1;
2923
2924  end:
2925     SSL_free(serverssl);
2926     SSL_free(clientssl);
2927     SSL_CTX_free(sctx);
2928     SSL_CTX_free(cctx);
2929
2930     return testresult;
2931 }
2932
2933 static int test_ciphersuite_change(void)
2934 {
2935     SSL_CTX *cctx = NULL, *sctx = NULL;
2936     SSL *clientssl = NULL, *serverssl = NULL;
2937     SSL_SESSION *clntsess = NULL;
2938     int testresult = 0;
2939     const SSL_CIPHER *aes_128_gcm_sha256 = NULL;
2940
2941     /* Create a session based on SHA-256 */
2942     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
2943                                        TLS1_VERSION, TLS_MAX_VERSION,
2944                                        &sctx, &cctx, cert, privkey))
2945             || !TEST_true(SSL_CTX_set_ciphersuites(cctx,
2946                                                    "TLS_AES_128_GCM_SHA256"))
2947             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
2948                                           &clientssl, NULL, NULL))
2949             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2950                                                 SSL_ERROR_NONE)))
2951         goto end;
2952
2953     clntsess = SSL_get1_session(clientssl);
2954     /* Save for later */
2955     aes_128_gcm_sha256 = SSL_SESSION_get0_cipher(clntsess);
2956     SSL_shutdown(clientssl);
2957     SSL_shutdown(serverssl);
2958     SSL_free(serverssl);
2959     SSL_free(clientssl);
2960     serverssl = clientssl = NULL;
2961
2962 # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
2963     /* Check we can resume a session with a different SHA-256 ciphersuite */
2964     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
2965                                             "TLS_CHACHA20_POLY1305_SHA256"))
2966             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2967                                              NULL, NULL))
2968             || !TEST_true(SSL_set_session(clientssl, clntsess))
2969             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2970                                                 SSL_ERROR_NONE))
2971             || !TEST_true(SSL_session_reused(clientssl)))
2972         goto end;
2973
2974     SSL_SESSION_free(clntsess);
2975     clntsess = SSL_get1_session(clientssl);
2976     SSL_shutdown(clientssl);
2977     SSL_shutdown(serverssl);
2978     SSL_free(serverssl);
2979     SSL_free(clientssl);
2980     serverssl = clientssl = NULL;
2981 # endif
2982
2983     /*
2984      * Check attempting to resume a SHA-256 session with no SHA-256 ciphersuites
2985      * succeeds but does not resume.
2986      */
2987     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
2988             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
2989                                              NULL, NULL))
2990             || !TEST_true(SSL_set_session(clientssl, clntsess))
2991             || !TEST_true(create_ssl_connection(serverssl, clientssl,
2992                                                 SSL_ERROR_SSL))
2993             || !TEST_false(SSL_session_reused(clientssl)))
2994         goto end;
2995
2996     SSL_SESSION_free(clntsess);
2997     clntsess = NULL;
2998     SSL_shutdown(clientssl);
2999     SSL_shutdown(serverssl);
3000     SSL_free(serverssl);
3001     SSL_free(clientssl);
3002     serverssl = clientssl = NULL;
3003
3004     /* Create a session based on SHA384 */
3005     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx, "TLS_AES_256_GCM_SHA384"))
3006             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3007                                           &clientssl, NULL, NULL))
3008             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3009                                                 SSL_ERROR_NONE)))
3010         goto end;
3011
3012     clntsess = SSL_get1_session(clientssl);
3013     SSL_shutdown(clientssl);
3014     SSL_shutdown(serverssl);
3015     SSL_free(serverssl);
3016     SSL_free(clientssl);
3017     serverssl = clientssl = NULL;
3018
3019     if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3020                    "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384"))
3021             || !TEST_true(SSL_CTX_set_ciphersuites(sctx,
3022                                                    "TLS_AES_256_GCM_SHA384"))
3023             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3024                                              NULL, NULL))
3025             || !TEST_true(SSL_set_session(clientssl, clntsess))
3026                /*
3027                 * We use SSL_ERROR_WANT_READ below so that we can pause the
3028                 * connection after the initial ClientHello has been sent to
3029                 * enable us to make some session changes.
3030                 */
3031             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3032                                                 SSL_ERROR_WANT_READ)))
3033         goto end;
3034
3035     /* Trick the client into thinking this session is for a different digest */
3036     clntsess->cipher = aes_128_gcm_sha256;
3037     clntsess->cipher_id = clntsess->cipher->id;
3038
3039     /*
3040      * Continue the previously started connection. Server has selected a SHA-384
3041      * ciphersuite, but client thinks the session is for SHA-256, so it should
3042      * bail out.
3043      */
3044     if (!TEST_false(create_ssl_connection(serverssl, clientssl,
3045                                                 SSL_ERROR_SSL))
3046             || !TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
3047                             SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED))
3048         goto end;
3049
3050     testresult = 1;
3051
3052  end:
3053     SSL_SESSION_free(clntsess);
3054     SSL_free(serverssl);
3055     SSL_free(clientssl);
3056     SSL_CTX_free(sctx);
3057     SSL_CTX_free(cctx);
3058
3059     return testresult;
3060 }
3061
3062 /*
3063  * Test TLSv1.3 PSKs
3064  * Test 0 = Test new style callbacks
3065  * Test 1 = Test both new and old style callbacks
3066  * Test 2 = Test old style callbacks
3067  * Test 3 = Test old style callbacks with no certificate
3068  */
3069 static int test_tls13_psk(int idx)
3070 {
3071     SSL_CTX *sctx = NULL, *cctx = NULL;
3072     SSL *serverssl = NULL, *clientssl = NULL;
3073     const SSL_CIPHER *cipher = NULL;
3074     const unsigned char key[] = {
3075         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
3076         0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3077         0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
3078         0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
3079     };
3080     int testresult = 0;
3081
3082     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3083                                        TLS1_VERSION, TLS_MAX_VERSION,
3084                                        &sctx, &cctx, idx == 3 ? NULL : cert,
3085                                        idx == 3 ? NULL : privkey)))
3086         goto end;
3087
3088     if (idx != 3) {
3089         /*
3090          * We use a ciphersuite with SHA256 to ease testing old style PSK
3091          * callbacks which will always default to SHA256. This should not be
3092          * necessary if we have no cert/priv key. In that case the server should
3093          * prefer SHA256 automatically.
3094          */
3095         if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
3096                                                 "TLS_AES_128_GCM_SHA256")))
3097             goto end;
3098     }
3099
3100     /*
3101      * Test 0: New style callbacks only
3102      * Test 1: New and old style callbacks (only the new ones should be used)
3103      * Test 2: Old style callbacks only
3104      */
3105     if (idx == 0 || idx == 1) {
3106         SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
3107         SSL_CTX_set_psk_find_session_callback(sctx, find_session_cb);
3108     }
3109 #ifndef OPENSSL_NO_PSK
3110     if (idx >= 1) {
3111         SSL_CTX_set_psk_client_callback(cctx, psk_client_cb);
3112         SSL_CTX_set_psk_server_callback(sctx, psk_server_cb);
3113     }
3114 #endif
3115     srvid = pskid;
3116     use_session_cb_cnt = 0;
3117     find_session_cb_cnt = 0;
3118     psk_client_cb_cnt = 0;
3119     psk_server_cb_cnt = 0;
3120
3121     if (idx != 3) {
3122         /*
3123          * Check we can create a connection if callback decides not to send a
3124          * PSK
3125          */
3126         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3127                                                  NULL, NULL))
3128                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
3129                                                     SSL_ERROR_NONE))
3130                 || !TEST_false(SSL_session_reused(clientssl))
3131                 || !TEST_false(SSL_session_reused(serverssl)))
3132             goto end;
3133
3134         if (idx == 0 || idx == 1) {
3135             if (!TEST_true(use_session_cb_cnt == 1)
3136                     || !TEST_true(find_session_cb_cnt == 0)
3137                        /*
3138                         * If no old style callback then below should be 0
3139                         * otherwise 1
3140                         */
3141                     || !TEST_true(psk_client_cb_cnt == idx)
3142                     || !TEST_true(psk_server_cb_cnt == 0))
3143                 goto end;
3144         } else {
3145             if (!TEST_true(use_session_cb_cnt == 0)
3146                     || !TEST_true(find_session_cb_cnt == 0)
3147                     || !TEST_true(psk_client_cb_cnt == 1)
3148                     || !TEST_true(psk_server_cb_cnt == 0))
3149                 goto end;
3150         }
3151
3152         shutdown_ssl_connection(serverssl, clientssl);
3153         serverssl = clientssl = NULL;
3154         use_session_cb_cnt = psk_client_cb_cnt = 0;
3155     }
3156
3157     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3158                                              NULL, NULL)))
3159         goto end;
3160
3161     /* Create the PSK */
3162     cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
3163     clientpsk = SSL_SESSION_new();
3164     if (!TEST_ptr(clientpsk)
3165             || !TEST_ptr(cipher)
3166             || !TEST_true(SSL_SESSION_set1_master_key(clientpsk, key,
3167                                                       sizeof(key)))
3168             || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
3169             || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
3170                                                            TLS1_3_VERSION))
3171             || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
3172         goto end;
3173     serverpsk = clientpsk;
3174
3175     /* Check we can create a connection and the PSK is used */
3176     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3177             || !TEST_true(SSL_session_reused(clientssl))
3178             || !TEST_true(SSL_session_reused(serverssl)))
3179         goto end;
3180
3181     if (idx == 0 || idx == 1) {
3182         if (!TEST_true(use_session_cb_cnt == 1)
3183                 || !TEST_true(find_session_cb_cnt == 1)
3184                 || !TEST_true(psk_client_cb_cnt == 0)
3185                 || !TEST_true(psk_server_cb_cnt == 0))
3186             goto end;
3187     } else {
3188         if (!TEST_true(use_session_cb_cnt == 0)
3189                 || !TEST_true(find_session_cb_cnt == 0)
3190                 || !TEST_true(psk_client_cb_cnt == 1)
3191                 || !TEST_true(psk_server_cb_cnt == 1))
3192             goto end;
3193     }
3194
3195     shutdown_ssl_connection(serverssl, clientssl);
3196     serverssl = clientssl = NULL;
3197     use_session_cb_cnt = find_session_cb_cnt = 0;
3198     psk_client_cb_cnt = psk_server_cb_cnt = 0;
3199
3200     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3201                                              NULL, NULL)))
3202         goto end;
3203
3204     /* Force an HRR */
3205     if (!TEST_true(SSL_set1_groups_list(serverssl, "P-256")))
3206         goto end;
3207
3208     /*
3209      * Check we can create a connection, the PSK is used and the callbacks are
3210      * called twice.
3211      */
3212     if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE))
3213             || !TEST_true(SSL_session_reused(clientssl))
3214             || !TEST_true(SSL_session_reused(serverssl)))
3215         goto end;
3216
3217     if (idx == 0 || idx == 1) {
3218         if (!TEST_true(use_session_cb_cnt == 2)
3219                 || !TEST_true(find_session_cb_cnt == 2)
3220                 || !TEST_true(psk_client_cb_cnt == 0)
3221                 || !TEST_true(psk_server_cb_cnt == 0))
3222             goto end;
3223     } else {
3224         if (!TEST_true(use_session_cb_cnt == 0)
3225                 || !TEST_true(find_session_cb_cnt == 0)
3226                 || !TEST_true(psk_client_cb_cnt == 2)
3227                 || !TEST_true(psk_server_cb_cnt == 2))
3228             goto end;
3229     }
3230
3231     shutdown_ssl_connection(serverssl, clientssl);
3232     serverssl = clientssl = NULL;
3233     use_session_cb_cnt = find_session_cb_cnt = 0;
3234     psk_client_cb_cnt = psk_server_cb_cnt = 0;
3235
3236     if (idx != 3) {
3237         /*
3238          * Check that if the server rejects the PSK we can still connect, but with
3239          * a full handshake
3240          */
3241         srvid = "Dummy Identity";
3242         if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3243                                                  NULL, NULL))
3244                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
3245                                                     SSL_ERROR_NONE))
3246                 || !TEST_false(SSL_session_reused(clientssl))
3247                 || !TEST_false(SSL_session_reused(serverssl)))
3248             goto end;
3249
3250         if (idx == 0 || idx == 1) {
3251             if (!TEST_true(use_session_cb_cnt == 1)
3252                     || !TEST_true(find_session_cb_cnt == 1)
3253                     || !TEST_true(psk_client_cb_cnt == 0)
3254                        /*
3255                         * If no old style callback then below should be 0
3256                         * otherwise 1
3257                         */
3258                     || !TEST_true(psk_server_cb_cnt == idx))
3259                 goto end;
3260         } else {
3261             if (!TEST_true(use_session_cb_cnt == 0)
3262                     || !TEST_true(find_session_cb_cnt == 0)
3263                     || !TEST_true(psk_client_cb_cnt == 1)
3264                     || !TEST_true(psk_server_cb_cnt == 1))
3265                 goto end;
3266         }
3267
3268         shutdown_ssl_connection(serverssl, clientssl);
3269         serverssl = clientssl = NULL;
3270     }
3271     testresult = 1;
3272
3273  end:
3274     SSL_SESSION_free(clientpsk);
3275     SSL_SESSION_free(serverpsk);
3276     clientpsk = serverpsk = NULL;
3277     SSL_free(serverssl);
3278     SSL_free(clientssl);
3279     SSL_CTX_free(sctx);
3280     SSL_CTX_free(cctx);
3281     return testresult;
3282 }
3283
3284 static unsigned char cookie_magic_value[] = "cookie magic";
3285
3286 static int generate_cookie_callback(SSL *ssl, unsigned char *cookie,
3287                                     unsigned int *cookie_len)
3288 {
3289     /*
3290      * Not suitable as a real cookie generation function but good enough for
3291      * testing!
3292      */
3293     memcpy(cookie, cookie_magic_value, sizeof(cookie_magic_value) - 1);
3294     *cookie_len = sizeof(cookie_magic_value) - 1;
3295
3296     return 1;
3297 }
3298
3299 static int verify_cookie_callback(SSL *ssl, const unsigned char *cookie,
3300                                   unsigned int cookie_len)
3301 {
3302     if (cookie_len == sizeof(cookie_magic_value) - 1
3303         && memcmp(cookie, cookie_magic_value, cookie_len) == 0)
3304         return 1;
3305
3306     return 0;
3307 }
3308
3309 static int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie,
3310                                         size_t *cookie_len)
3311 {
3312     unsigned int temp;
3313     int res = generate_cookie_callback(ssl, cookie, &temp);
3314     *cookie_len = temp;
3315     return res;
3316 }
3317
3318 static int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie,
3319                                       size_t cookie_len)
3320 {
3321     return verify_cookie_callback(ssl, cookie, cookie_len);
3322 }
3323
3324 static int test_stateless(void)
3325 {
3326     SSL_CTX *sctx = NULL, *cctx = NULL;
3327     SSL *serverssl = NULL, *clientssl = NULL;
3328     int testresult = 0;
3329
3330     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3331                                        TLS1_VERSION, TLS_MAX_VERSION,
3332                                        &sctx, &cctx, cert, privkey)))
3333         goto end;
3334
3335     /* The arrival of CCS messages can confuse the test */
3336     SSL_CTX_clear_options(cctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
3337
3338     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3339                                       NULL, NULL))
3340                /* Send the first ClientHello */
3341             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3342                                                  SSL_ERROR_WANT_READ))
3343                /*
3344                 * This should fail with a -1 return because we have no callbacks
3345                 * set up
3346                 */
3347             || !TEST_int_eq(SSL_stateless(serverssl), -1))
3348         goto end;
3349
3350     /* Fatal error so abandon the connection from this client */
3351     SSL_free(clientssl);
3352     clientssl = NULL;
3353
3354     /* Set up the cookie generation and verification callbacks */
3355     SSL_CTX_set_stateless_cookie_generate_cb(sctx, generate_stateless_cookie_callback);
3356     SSL_CTX_set_stateless_cookie_verify_cb(sctx, verify_stateless_cookie_callback);
3357
3358     /*
3359      * Create a new connection from the client (we can reuse the server SSL
3360      * object).
3361      */
3362     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3363                                              NULL, NULL))
3364                /* Send the first ClientHello */
3365             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3366                                                 SSL_ERROR_WANT_READ))
3367                /* This should fail because there is no cookie */
3368             || !TEST_int_eq(SSL_stateless(serverssl), 0))
3369         goto end;
3370
3371     /* Abandon the connection from this client */
3372     SSL_free(clientssl);
3373     clientssl = NULL;
3374
3375     /*
3376      * Now create a connection from a new client but with the same server SSL
3377      * object
3378      */
3379     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3380                                              NULL, NULL))
3381                /* Send the first ClientHello */
3382             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3383                                                 SSL_ERROR_WANT_READ))
3384                /* This should fail because there is no cookie */
3385             || !TEST_int_eq(SSL_stateless(serverssl), 0)
3386                /* Send the second ClientHello */
3387             || !TEST_false(create_ssl_connection(serverssl, clientssl,
3388                                                 SSL_ERROR_WANT_READ))
3389                /* This should succeed because a cookie is now present */
3390             || !TEST_int_eq(SSL_stateless(serverssl), 1)
3391                /* Complete the connection */
3392             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3393                                                 SSL_ERROR_NONE)))
3394         goto end;
3395
3396     shutdown_ssl_connection(serverssl, clientssl);
3397     serverssl = clientssl = NULL;
3398     testresult = 1;
3399
3400  end:
3401     SSL_free(serverssl);
3402     SSL_free(clientssl);
3403     SSL_CTX_free(sctx);
3404     SSL_CTX_free(cctx);
3405     return testresult;
3406
3407 }
3408 #endif /* OPENSSL_NO_TLS1_3 */
3409
3410 static int clntaddoldcb = 0;
3411 static int clntparseoldcb = 0;
3412 static int srvaddoldcb = 0;
3413 static int srvparseoldcb = 0;
3414 static int clntaddnewcb = 0;
3415 static int clntparsenewcb = 0;
3416 static int srvaddnewcb = 0;
3417 static int srvparsenewcb = 0;
3418 static int snicb = 0;
3419
3420 #define TEST_EXT_TYPE1  0xff00
3421
3422 static int old_add_cb(SSL *s, unsigned int ext_type, const unsigned char **out,
3423                       size_t *outlen, int *al, void *add_arg)
3424 {
3425     int *server = (int *)add_arg;
3426     unsigned char *data;
3427
3428     if (SSL_is_server(s))
3429         srvaddoldcb++;
3430     else
3431         clntaddoldcb++;
3432
3433     if (*server != SSL_is_server(s)
3434             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3435         return -1;
3436
3437     *data = 1;
3438     *out = data;
3439     *outlen = sizeof(char);
3440     return 1;
3441 }
3442
3443 static void old_free_cb(SSL *s, unsigned int ext_type, const unsigned char *out,
3444                         void *add_arg)
3445 {
3446     OPENSSL_free((unsigned char *)out);
3447 }
3448
3449 static int old_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in,
3450                         size_t inlen, int *al, void *parse_arg)
3451 {
3452     int *server = (int *)parse_arg;
3453
3454     if (SSL_is_server(s))
3455         srvparseoldcb++;
3456     else
3457         clntparseoldcb++;
3458
3459     if (*server != SSL_is_server(s)
3460             || inlen != sizeof(char)
3461             || *in != 1)
3462         return -1;
3463
3464     return 1;
3465 }
3466
3467 static int new_add_cb(SSL *s, unsigned int ext_type, unsigned int context,
3468                       const unsigned char **out, size_t *outlen, X509 *x,
3469                       size_t chainidx, int *al, void *add_arg)
3470 {
3471     int *server = (int *)add_arg;
3472     unsigned char *data;
3473
3474     if (SSL_is_server(s))
3475         srvaddnewcb++;
3476     else
3477         clntaddnewcb++;
3478
3479     if (*server != SSL_is_server(s)
3480             || (data = OPENSSL_malloc(sizeof(*data))) == NULL)
3481         return -1;
3482
3483     *data = 1;
3484     *out = data;
3485     *outlen = sizeof(*data);
3486     return 1;
3487 }
3488
3489 static void new_free_cb(SSL *s, unsigned int ext_type, unsigned int context,
3490                         const unsigned char *out, void *add_arg)
3491 {
3492     OPENSSL_free((unsigned char *)out);
3493 }
3494
3495 static int new_parse_cb(SSL *s, unsigned int ext_type, unsigned int context,
3496                         const unsigned char *in, size_t inlen, X509 *x,
3497                         size_t chainidx, int *al, void *parse_arg)
3498 {
3499     int *server = (int *)parse_arg;
3500
3501     if (SSL_is_server(s))
3502         srvparsenewcb++;
3503     else
3504         clntparsenewcb++;
3505
3506     if (*server != SSL_is_server(s)
3507             || inlen != sizeof(char) || *in != 1)
3508         return -1;
3509
3510     return 1;
3511 }
3512
3513 static int sni_cb(SSL *s, int *al, void *arg)
3514 {
3515     SSL_CTX *ctx = (SSL_CTX *)arg;
3516
3517     if (SSL_set_SSL_CTX(s, ctx) == NULL) {
3518         *al = SSL_AD_INTERNAL_ERROR;
3519         return SSL_TLSEXT_ERR_ALERT_FATAL;
3520     }
3521     snicb++;
3522     return SSL_TLSEXT_ERR_OK;
3523 }
3524
3525 /*
3526  * Custom call back tests.
3527  * Test 0: Old style callbacks in TLSv1.2
3528  * Test 1: New style callbacks in TLSv1.2
3529  * Test 2: New style callbacks in TLSv1.2 with SNI
3530  * Test 3: New style callbacks in TLSv1.3. Extensions in CH and EE
3531  * Test 4: New style callbacks in TLSv1.3. Extensions in CH, SH, EE, Cert + NST
3532  */
3533 static int test_custom_exts(int tst)
3534 {
3535     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3536     SSL *clientssl = NULL, *serverssl = NULL;
3537     int testresult = 0;
3538     static int server = 1;
3539     static int client = 0;
3540     SSL_SESSION *sess = NULL;
3541     unsigned int context;
3542
3543 #if defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_TLS1_3)
3544     /* Skip tests for TLSv1.2 and below in this case */
3545     if (tst < 3)
3546         return 1;
3547 #endif
3548
3549     /* Reset callback counters */
3550     clntaddoldcb = clntparseoldcb = srvaddoldcb = srvparseoldcb = 0;
3551     clntaddnewcb = clntparsenewcb = srvaddnewcb = srvparsenewcb = 0;
3552     snicb = 0;
3553
3554     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3555                                        TLS1_VERSION, TLS_MAX_VERSION,
3556                                        &sctx, &cctx, cert, privkey)))
3557         goto end;
3558
3559     if (tst == 2
3560             && !TEST_true(create_ssl_ctx_pair(TLS_server_method(), NULL,
3561                                               TLS1_VERSION, TLS_MAX_VERSION,
3562                                               &sctx2, NULL, cert, privkey)))
3563         goto end;
3564
3565
3566     if (tst < 3) {
3567         SSL_CTX_set_options(cctx, SSL_OP_NO_TLSv1_3);
3568         SSL_CTX_set_options(sctx, SSL_OP_NO_TLSv1_3);
3569         if (sctx2 != NULL)
3570             SSL_CTX_set_options(sctx2, SSL_OP_NO_TLSv1_3);
3571     }
3572
3573     if (tst == 4) {
3574         context = SSL_EXT_CLIENT_HELLO
3575                   | SSL_EXT_TLS1_2_SERVER_HELLO
3576                   | SSL_EXT_TLS1_3_SERVER_HELLO
3577                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
3578                   | SSL_EXT_TLS1_3_CERTIFICATE
3579                   | SSL_EXT_TLS1_3_NEW_SESSION_TICKET;
3580     } else {
3581         context = SSL_EXT_CLIENT_HELLO
3582                   | SSL_EXT_TLS1_2_SERVER_HELLO
3583                   | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS;
3584     }
3585
3586     /* Create a client side custom extension */
3587     if (tst == 0) {
3588         if (!TEST_true(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3589                                                      old_add_cb, old_free_cb,
3590                                                      &client, old_parse_cb,
3591                                                      &client)))
3592             goto end;
3593     } else {
3594         if (!TEST_true(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1, context,
3595                                               new_add_cb, new_free_cb,
3596                                               &client, new_parse_cb, &client)))
3597             goto end;
3598     }
3599
3600     /* Should not be able to add duplicates */
3601     if (!TEST_false(SSL_CTX_add_client_custom_ext(cctx, TEST_EXT_TYPE1,
3602                                                   old_add_cb, old_free_cb,
3603                                                   &client, old_parse_cb,
3604                                                   &client))
3605             || !TEST_false(SSL_CTX_add_custom_ext(cctx, TEST_EXT_TYPE1,
3606                                                   context, new_add_cb,
3607                                                   new_free_cb, &client,
3608                                                   new_parse_cb, &client)))
3609         goto end;
3610
3611     /* Create a server side custom extension */
3612     if (tst == 0) {
3613         if (!TEST_true(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3614                                                      old_add_cb, old_free_cb,
3615                                                      &server, old_parse_cb,
3616                                                      &server)))
3617             goto end;
3618     } else {
3619         if (!TEST_true(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1, context,
3620                                               new_add_cb, new_free_cb,
3621                                               &server, new_parse_cb, &server)))
3622             goto end;
3623         if (sctx2 != NULL
3624                 && !TEST_true(SSL_CTX_add_custom_ext(sctx2, TEST_EXT_TYPE1,
3625                                                      context, new_add_cb,
3626                                                      new_free_cb, &server,
3627                                                      new_parse_cb, &server)))
3628             goto end;
3629     }
3630
3631     /* Should not be able to add duplicates */
3632     if (!TEST_false(SSL_CTX_add_server_custom_ext(sctx, TEST_EXT_TYPE1,
3633                                                   old_add_cb, old_free_cb,
3634                                                   &server, old_parse_cb,
3635                                                   &server))
3636             || !TEST_false(SSL_CTX_add_custom_ext(sctx, TEST_EXT_TYPE1,
3637                                                   context, new_add_cb,
3638                                                   new_free_cb, &server,
3639                                                   new_parse_cb, &server)))
3640         goto end;
3641
3642     if (tst == 2) {
3643         /* Set up SNI */
3644         if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(sctx, sni_cb))
3645                 || !TEST_true(SSL_CTX_set_tlsext_servername_arg(sctx, sctx2)))
3646             goto end;
3647     }
3648
3649     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
3650                                       &clientssl, NULL, NULL))
3651             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3652                                                 SSL_ERROR_NONE)))
3653         goto end;
3654
3655     if (tst == 0) {
3656         if (clntaddoldcb != 1
3657                 || clntparseoldcb != 1
3658                 || srvaddoldcb != 1
3659                 || srvparseoldcb != 1)
3660             goto end;
3661     } else if (tst == 1 || tst == 2 || tst == 3) {
3662         if (clntaddnewcb != 1
3663                 || clntparsenewcb != 1
3664                 || srvaddnewcb != 1
3665                 || srvparsenewcb != 1
3666                 || (tst != 2 && snicb != 0)
3667                 || (tst == 2 && snicb != 1))
3668             goto end;
3669     } else {
3670         /* In this case there 2 NewSessionTicket messages created */
3671         if (clntaddnewcb != 1
3672                 || clntparsenewcb != 5
3673                 || srvaddnewcb != 5
3674                 || srvparsenewcb != 1)
3675             goto end;
3676     }
3677
3678     sess = SSL_get1_session(clientssl);
3679     SSL_shutdown(clientssl);
3680     SSL_shutdown(serverssl);
3681     SSL_free(serverssl);
3682     SSL_free(clientssl);
3683     serverssl = clientssl = NULL;
3684
3685     if (tst == 3) {
3686         /* We don't bother with the resumption aspects for this test */
3687         testresult = 1;
3688         goto end;
3689     }
3690
3691     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
3692                                       NULL, NULL))
3693             || !TEST_true(SSL_set_session(clientssl, sess))
3694             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3695                                                SSL_ERROR_NONE)))
3696         goto end;
3697
3698     /*
3699      * For a resumed session we expect to add the ClientHello extension. For the
3700      * old style callbacks we ignore it on the server side because they set
3701      * SSL_EXT_IGNORE_ON_RESUMPTION. The new style callbacks do not ignore
3702      * them.
3703      */
3704     if (tst == 0) {
3705         if (clntaddoldcb != 2
3706                 || clntparseoldcb != 1
3707                 || srvaddoldcb != 1
3708                 || srvparseoldcb != 1)
3709             goto end;
3710     } else if (tst == 1 || tst == 2 || tst == 3) {
3711         if (clntaddnewcb != 2
3712                 || clntparsenewcb != 2
3713                 || srvaddnewcb != 2
3714                 || srvparsenewcb != 2)
3715             goto end;
3716     } else {
3717         /*
3718          * No Certificate message extensions in the resumption handshake,
3719          * 2 NewSessionTickets in the initial handshake, 1 in the resumption
3720          */
3721         if (clntaddnewcb != 2
3722                 || clntparsenewcb != 8
3723                 || srvaddnewcb != 8
3724                 || srvparsenewcb != 2)
3725             goto end;
3726     }
3727
3728     testresult = 1;
3729
3730 end:
3731     SSL_SESSION_free(sess);
3732     SSL_free(serverssl);
3733     SSL_free(clientssl);
3734     SSL_CTX_free(sctx2);
3735     SSL_CTX_free(sctx);
3736     SSL_CTX_free(cctx);
3737     return testresult;
3738 }
3739
3740 /*
3741  * Test loading of serverinfo data in various formats. test_sslmessages actually
3742  * tests to make sure the extensions appear in the handshake
3743  */
3744 static int test_serverinfo(int tst)
3745 {
3746     unsigned int version;
3747     unsigned char *sibuf;
3748     size_t sibuflen;
3749     int ret, expected, testresult = 0;
3750     SSL_CTX *ctx;
3751
3752     ctx = SSL_CTX_new(TLS_method());
3753     if (!TEST_ptr(ctx))
3754         goto end;
3755
3756     if ((tst & 0x01) == 0x01)
3757         version = SSL_SERVERINFOV2;
3758     else
3759         version = SSL_SERVERINFOV1;
3760
3761     if ((tst & 0x02) == 0x02) {
3762         sibuf = serverinfov2;
3763         sibuflen = sizeof(serverinfov2);
3764         expected = (version == SSL_SERVERINFOV2);
3765     } else {
3766         sibuf = serverinfov1;
3767         sibuflen = sizeof(serverinfov1);
3768         expected = (version == SSL_SERVERINFOV1);
3769     }
3770
3771     if ((tst & 0x04) == 0x04) {
3772         ret = SSL_CTX_use_serverinfo_ex(ctx, version, sibuf, sibuflen);
3773     } else {
3774         ret = SSL_CTX_use_serverinfo(ctx, sibuf, sibuflen);
3775
3776         /*
3777          * The version variable is irrelevant in this case - it's what is in the
3778          * buffer that matters
3779          */
3780         if ((tst & 0x02) == 0x02)
3781             expected = 0;
3782         else
3783             expected = 1;
3784     }
3785
3786     if (!TEST_true(ret == expected))
3787         goto end;
3788
3789     testresult = 1;
3790
3791  end:
3792     SSL_CTX_free(ctx);
3793
3794     return testresult;
3795 }
3796
3797 /*
3798  * Test that SSL_export_keying_material() produces expected results. There are
3799  * no test vectors so all we do is test that both sides of the communication
3800  * produce the same results for different protocol versions.
3801  */
3802 static int test_export_key_mat(int tst)
3803 {
3804     int testresult = 0;
3805     SSL_CTX *cctx = NULL, *sctx = NULL, *sctx2 = NULL;
3806     SSL *clientssl = NULL, *serverssl = NULL;
3807     const char label[] = "test label";
3808     const unsigned char context[] = "context";
3809     const unsigned char *emptycontext = NULL;
3810     unsigned char ckeymat1[80], ckeymat2[80], ckeymat3[80];
3811     unsigned char skeymat1[80], skeymat2[80], skeymat3[80];
3812     const int protocols[] = {
3813         TLS1_VERSION,
3814         TLS1_1_VERSION,
3815         TLS1_2_VERSION,
3816         TLS1_3_VERSION
3817     };
3818
3819 #ifdef OPENSSL_NO_TLS1
3820     if (tst == 0)
3821         return 1;
3822 #endif
3823 #ifdef OPENSSL_NO_TLS1_1
3824     if (tst == 1)
3825         return 1;
3826 #endif
3827 #ifdef OPENSSL_NO_TLS1_2
3828     if (tst == 2)
3829         return 1;
3830 #endif
3831 #ifdef OPENSSL_NO_TLS1_3
3832     if (tst == 3)
3833         return 1;
3834 #endif
3835     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
3836                                        TLS1_VERSION, TLS_MAX_VERSION,
3837                                        &sctx, &cctx, cert, privkey)))
3838         goto end;
3839
3840     OPENSSL_assert(tst >= 0 && (size_t)tst < OSSL_NELEM(protocols));
3841     SSL_CTX_set_max_proto_version(cctx, protocols[tst]);
3842     SSL_CTX_set_min_proto_version(cctx, protocols[tst]);
3843
3844     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
3845                                       NULL))
3846             || !TEST_true(create_ssl_connection(serverssl, clientssl,
3847                                                 SSL_ERROR_NONE)))
3848         goto end;
3849
3850     if (!TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat1,
3851                                                 sizeof(ckeymat1), label,
3852                                                 sizeof(label) - 1, context,
3853                                                 sizeof(context) - 1, 1), 1)
3854             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat2,
3855                                                        sizeof(ckeymat2), label,
3856                                                        sizeof(label) - 1,
3857                                                        emptycontext,
3858                                                        0, 1), 1)
3859             || !TEST_int_eq(SSL_export_keying_material(clientssl, ckeymat3,
3860                                                        sizeof(ckeymat3), label,
3861                                                        sizeof(label) - 1,
3862                                                        NULL, 0, 0), 1)
3863             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat1,
3864                                                        sizeof(skeymat1), label,
3865                                                        sizeof(label) - 1,
3866                                                        context,
3867                                                        sizeof(context) -1, 1),
3868                             1)
3869             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat2,
3870                                                        sizeof(skeymat2), label,
3871                                                        sizeof(label) - 1,
3872                                                        emptycontext,
3873                                                        0, 1), 1)
3874             || !TEST_int_eq(SSL_export_keying_material(serverssl, skeymat3,
3875                                                        sizeof(skeymat3), label,
3876                                                        sizeof(label) - 1,
3877                                                        NULL, 0, 0), 1)
3878                /*
3879                 * Check that both sides created the same key material with the
3880                 * same context.
3881                 */
3882             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
3883                             sizeof(skeymat1))
3884                /*
3885                 * Check that both sides created the same key material with an
3886                 * empty context.
3887                 */
3888             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
3889                             sizeof(skeymat2))
3890                /*
3891                 * Check that both sides created the same key material without a
3892                 * context.
3893                 */
3894             || !TEST_mem_eq(ckeymat3, sizeof(ckeymat3), skeymat3,
3895                             sizeof(skeymat3))
3896                /* Different contexts should produce different results */
3897             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
3898                             sizeof(ckeymat2)))
3899         goto end;
3900
3901     /*
3902      * Check that an empty context and no context produce different results in
3903      * protocols less than TLSv1.3. In TLSv1.3 they should be the same.
3904      */
3905     if ((tst != 3 && !TEST_mem_ne(ckeymat2, sizeof(ckeymat2), ckeymat3,
3906                                   sizeof(ckeymat3)))
3907             || (tst ==3 && !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), ckeymat3,
3908                                         sizeof(ckeymat3))))
3909         goto end;
3910
3911     testresult = 1;
3912
3913  end:
3914     SSL_free(serverssl);
3915     SSL_free(clientssl);
3916     SSL_CTX_free(sctx2);
3917     SSL_CTX_free(sctx);
3918     SSL_CTX_free(cctx);
3919
3920     return testresult;
3921 }
3922
3923 #ifndef OPENSSL_NO_TLS1_3
3924 /*
3925  * Test that SSL_export_keying_material_early() produces expected
3926  * results. There are no test vectors so all we do is test that both
3927  * sides of the communication produce the same results for different
3928  * protocol versions.
3929  */
3930 static int test_export_key_mat_early(int idx)
3931 {
3932     static const char label[] = "test label";
3933     static const unsigned char context[] = "context";
3934     int testresult = 0;
3935     SSL_CTX *cctx = NULL, *sctx = NULL;
3936     SSL *clientssl = NULL, *serverssl = NULL;
3937     SSL_SESSION *sess = NULL;
3938     const unsigned char *emptycontext = NULL;
3939     unsigned char ckeymat1[80], ckeymat2[80];
3940     unsigned char skeymat1[80], skeymat2[80];
3941     unsigned char buf[1];
3942     size_t readbytes, written;
3943
3944     if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl, &serverssl,
3945                                         &sess, idx)))
3946         goto end;
3947
3948     /* Here writing 0 length early data is enough. */
3949     if (!TEST_true(SSL_write_early_data(clientssl, NULL, 0, &written))
3950             || !TEST_int_eq(SSL_read_early_data(serverssl, buf, sizeof(buf),
3951                                                 &readbytes),
3952                             SSL_READ_EARLY_DATA_ERROR)
3953             || !TEST_int_eq(SSL_get_early_data_status(serverssl),
3954                             SSL_EARLY_DATA_ACCEPTED))
3955         goto end;
3956
3957     if (!TEST_int_eq(SSL_export_keying_material_early(
3958                      clientssl, ckeymat1, sizeof(ckeymat1), label,
3959                      sizeof(label) - 1, context, sizeof(context) - 1), 1)
3960             || !TEST_int_eq(SSL_export_keying_material_early(
3961                             clientssl, ckeymat2, sizeof(ckeymat2), label,
3962                             sizeof(label) - 1, emptycontext, 0), 1)
3963             || !TEST_int_eq(SSL_export_keying_material_early(
3964                             serverssl, skeymat1, sizeof(skeymat1), label,
3965                             sizeof(label) - 1, context, sizeof(context) - 1), 1)
3966             || !TEST_int_eq(SSL_export_keying_material_early(
3967                             serverssl, skeymat2, sizeof(skeymat2), label,
3968                             sizeof(label) - 1, emptycontext, 0), 1)
3969                /*
3970                 * Check that both sides created the same key material with the
3971                 * same context.
3972                 */
3973             || !TEST_mem_eq(ckeymat1, sizeof(ckeymat1), skeymat1,
3974                             sizeof(skeymat1))
3975                /*
3976                 * Check that both sides created the same key material with an
3977                 * empty context.
3978                 */
3979             || !TEST_mem_eq(ckeymat2, sizeof(ckeymat2), skeymat2,
3980                             sizeof(skeymat2))
3981                /* Different contexts should produce different results */
3982             || !TEST_mem_ne(ckeymat1, sizeof(ckeymat1), ckeymat2,
3983                             sizeof(ckeymat2)))
3984         goto end;
3985
3986     testresult = 1;
3987
3988  end:
3989     SSL_SESSION_free(sess);
3990     SSL_SESSION_free(clientpsk);
3991     SSL_SESSION_free(serverpsk);
3992     clientpsk = serverpsk = NULL;
3993     SSL_free(serverssl);
3994     SSL_free(clientssl);
3995     SSL_CTX_free(sctx);
3996     SSL_CTX_free(cctx);
3997
3998     return testresult;
3999 }
4000 #endif /* OPENSSL_NO_TLS1_3 */
4001
4002 static int test_ssl_clear(int idx)
4003 {
4004     SSL_CTX *cctx = NULL, *sctx = NULL;
4005     SSL *clientssl = NULL, *serverssl = NULL;
4006     int testresult = 0;
4007
4008 #ifdef OPENSSL_NO_TLS1_2
4009     if (idx == 1)
4010         return 1;
4011 #endif
4012
4013     /* Create an initial connection */
4014     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4015                                        TLS1_VERSION, TLS_MAX_VERSION,
4016                                        &sctx, &cctx, cert, privkey))
4017             || (idx == 1
4018                 && !TEST_true(SSL_CTX_set_max_proto_version(cctx,
4019                                                             TLS1_2_VERSION)))
4020             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4021                                           &clientssl, NULL, NULL))
4022             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4023                                                 SSL_ERROR_NONE)))
4024         goto end;
4025
4026     SSL_shutdown(clientssl);
4027     SSL_shutdown(serverssl);
4028     SSL_free(serverssl);
4029     serverssl = NULL;
4030
4031     /* Clear clientssl - we're going to reuse the object */
4032     if (!TEST_true(SSL_clear(clientssl)))
4033         goto end;
4034
4035     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4036                                              NULL, NULL))
4037             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4038                                                 SSL_ERROR_NONE))
4039             || !TEST_true(SSL_session_reused(clientssl)))
4040         goto end;
4041
4042     SSL_shutdown(clientssl);
4043     SSL_shutdown(serverssl);
4044
4045     testresult = 1;
4046
4047  end:
4048     SSL_free(serverssl);
4049     SSL_free(clientssl);
4050     SSL_CTX_free(sctx);
4051     SSL_CTX_free(cctx);
4052
4053     return testresult;
4054 }
4055
4056 /* Parse CH and retrieve any MFL extension value if present */
4057 static int get_MFL_from_client_hello(BIO *bio, int *mfl_codemfl_code)
4058 {
4059     long len;
4060     unsigned char *data;
4061     PACKET pkt = {0}, pkt2 = {0}, pkt3 = {0};
4062     unsigned int MFL_code = 0, type = 0;
4063
4064     if (!TEST_uint_gt( len = BIO_get_mem_data( bio, (char **) &data ), 0 ) )
4065         goto end;
4066
4067     if (!TEST_true( PACKET_buf_init( &pkt, data, len ) )
4068                /* Skip the record header */
4069             || !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH)
4070                /* Skip the handshake message header */
4071             || !TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
4072                /* Skip client version and random */
4073             || !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
4074                                                + SSL3_RANDOM_SIZE))
4075                /* Skip session id */
4076             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4077                /* Skip ciphers */
4078             || !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
4079                /* Skip compression */
4080             || !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
4081                /* Extensions len */
4082             || !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
4083         goto end;
4084
4085     /* Loop through all extensions */
4086     while (PACKET_remaining(&pkt2)) {
4087         if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
4088                 || !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
4089             goto end;
4090
4091         if (type == TLSEXT_TYPE_max_fragment_length) {
4092             if (!TEST_uint_ne(PACKET_remaining(&pkt3), 0)
4093                     || !TEST_true(PACKET_get_1(&pkt3, &MFL_code)))
4094                 goto end;
4095
4096             *mfl_codemfl_code = MFL_code;
4097             return 1;
4098         }
4099     }
4100
4101  end:
4102     return 0;
4103 }
4104
4105 /* Maximum-Fragment-Length TLS extension mode to test */
4106 static const unsigned char max_fragment_len_test[] = {
4107     TLSEXT_max_fragment_length_512,
4108     TLSEXT_max_fragment_length_1024,
4109     TLSEXT_max_fragment_length_2048,
4110     TLSEXT_max_fragment_length_4096
4111 };
4112
4113 static int test_max_fragment_len_ext(int idx_tst)
4114 {
4115     SSL_CTX *ctx;
4116     SSL *con = NULL;
4117     int testresult = 0, MFL_mode = 0;
4118     BIO *rbio, *wbio;
4119
4120     ctx = SSL_CTX_new(TLS_method());
4121     if (!TEST_ptr(ctx))
4122         goto end;
4123
4124     if (!TEST_true(SSL_CTX_set_tlsext_max_fragment_length(
4125                    ctx, max_fragment_len_test[idx_tst])))
4126         goto end;
4127
4128     con = SSL_new(ctx);
4129     if (!TEST_ptr(con))
4130         goto end;
4131
4132     rbio = BIO_new(BIO_s_mem());
4133     wbio = BIO_new(BIO_s_mem());
4134     if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
4135         BIO_free(rbio);
4136         BIO_free(wbio);
4137         goto end;
4138     }
4139
4140     SSL_set_bio(con, rbio, wbio);
4141     SSL_set_connect_state(con);
4142
4143     if (!TEST_int_le(SSL_connect(con), 0)) {
4144         /* This shouldn't succeed because we don't have a server! */
4145         goto end;
4146     }
4147
4148     if (!TEST_true(get_MFL_from_client_hello(wbio, &MFL_mode)))
4149         /* no MFL in client hello */
4150         goto end;
4151     if (!TEST_true(max_fragment_len_test[idx_tst] == MFL_mode))
4152         goto end;
4153
4154     testresult = 1;
4155
4156 end:
4157     SSL_free(con);
4158     SSL_CTX_free(ctx);
4159
4160     return testresult;
4161 }
4162
4163 #ifndef OPENSSL_NO_TLS1_3
4164 static int test_pha_key_update(void)
4165 {
4166     SSL_CTX *cctx = NULL, *sctx = NULL;
4167     SSL *clientssl = NULL, *serverssl = NULL;
4168     int testresult = 0;
4169
4170     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4171                                        TLS1_VERSION, TLS_MAX_VERSION,
4172                                        &sctx, &cctx, cert, privkey)))
4173         return 0;
4174
4175     if (!TEST_true(SSL_CTX_set_min_proto_version(sctx, TLS1_3_VERSION))
4176         || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_3_VERSION))
4177         || !TEST_true(SSL_CTX_set_min_proto_version(cctx, TLS1_3_VERSION))
4178         || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_3_VERSION)))
4179         goto end;
4180
4181
4182     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4183                                       NULL, NULL)))
4184         goto end;
4185
4186     SSL_force_post_handshake_auth(clientssl);
4187
4188     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4189                                          SSL_ERROR_NONE)))
4190         goto end;
4191
4192     SSL_set_verify(serverssl, SSL_VERIFY_PEER, NULL);
4193     if (!TEST_true(SSL_verify_client_post_handshake(serverssl)))
4194         goto end;
4195
4196     if (!TEST_true(SSL_key_update(clientssl, SSL_KEY_UPDATE_NOT_REQUESTED)))
4197         goto end;
4198
4199     /* Start handshake on the server */
4200     if (!TEST_int_eq(SSL_do_handshake(serverssl), 1))
4201         goto end;
4202
4203     /* Starts with SSL_connect(), but it's really just SSL_do_handshake() */
4204     if (!TEST_true(create_ssl_connection(serverssl, clientssl,
4205                                          SSL_ERROR_NONE)))
4206         goto end;
4207
4208     SSL_shutdown(clientssl);
4209     SSL_shutdown(serverssl);
4210
4211     testresult = 1;
4212
4213  end:
4214     SSL_free(serverssl);
4215     SSL_free(clientssl);
4216     SSL_CTX_free(sctx);
4217     SSL_CTX_free(cctx);
4218     return testresult;
4219 }
4220 #endif
4221
4222 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
4223
4224 static SRP_VBASE *vbase = NULL;
4225
4226 static int ssl_srp_cb(SSL *s, int *ad, void *arg)
4227 {
4228     int ret = SSL3_AL_FATAL;
4229     char *username;
4230     SRP_user_pwd *user = NULL;
4231
4232     username = SSL_get_srp_username(s);
4233     if (username == NULL) {
4234         *ad = SSL_AD_INTERNAL_ERROR;
4235         goto err;
4236     }
4237
4238     user = SRP_VBASE_get1_by_user(vbase, username);
4239     if (user == NULL) {
4240         *ad = SSL_AD_INTERNAL_ERROR;
4241         goto err;
4242     }
4243
4244     if (SSL_set_srp_server_param(s, user->N, user->g, user->s, user->v,
4245                                  user->info) <= 0) {
4246         *ad = SSL_AD_INTERNAL_ERROR;
4247         goto err;
4248     }
4249
4250     ret = 0;
4251
4252  err:
4253     SRP_user_pwd_free(user);
4254     return ret;
4255 }
4256
4257 static int create_new_vfile(char *userid, char *password, const char *filename)
4258 {
4259     char *gNid = NULL;
4260     OPENSSL_STRING *row = OPENSSL_zalloc(sizeof(row) * (DB_NUMBER + 1));
4261     TXT_DB *db = NULL;
4262     int ret = 0;
4263     BIO *out = NULL, *dummy = BIO_new_mem_buf("", 0);
4264     size_t i;
4265
4266     if (!TEST_ptr(dummy) || !TEST_ptr(row))
4267         goto end;
4268
4269     gNid = SRP_create_verifier(userid, password, &row[DB_srpsalt],
4270                                &row[DB_srpverifier], NULL, NULL);
4271     if (!TEST_ptr(gNid))
4272         goto end;
4273
4274     /*
4275      * The only way to create an empty TXT_DB is to provide a BIO with no data
4276      * in it!
4277      */
4278     db = TXT_DB_read(dummy, DB_NUMBER);
4279     if (!TEST_ptr(db))
4280         goto end;
4281
4282     out = BIO_new_file(filename, "w");
4283     if (!TEST_ptr(out))
4284         goto end;
4285
4286     row[DB_srpid] = OPENSSL_strdup(userid);
4287     row[DB_srptype] = OPENSSL_strdup("V");
4288     row[DB_srpgN] = OPENSSL_strdup(gNid);
4289
4290     if (!TEST_ptr(row[DB_srpid])
4291             || !TEST_ptr(row[DB_srptype])
4292             || !TEST_ptr(row[DB_srpgN])
4293             || !TEST_true(TXT_DB_insert(db, row)))
4294         goto end;
4295
4296     row = NULL;
4297
4298     if (!TXT_DB_write(out, db))
4299         goto end;
4300
4301     ret = 1;
4302  end:
4303     if (row != NULL) {
4304         for (i = 0; i < DB_NUMBER; i++)
4305             OPENSSL_free(row[i]);
4306     }
4307     OPENSSL_free(row);
4308     BIO_free(dummy);
4309     BIO_free(out);
4310     TXT_DB_free(db);
4311
4312     return ret;
4313 }
4314
4315 static int create_new_vbase(char *userid, char *password)
4316 {
4317     BIGNUM *verifier = NULL, *salt = NULL;
4318     const SRP_gN *lgN = NULL;
4319     SRP_user_pwd *user_pwd = NULL;
4320     int ret = 0;
4321
4322     lgN = SRP_get_default_gN(NULL);
4323     if (!TEST_ptr(lgN))
4324         goto end;
4325
4326     if (!TEST_true(SRP_create_verifier_BN(userid, password, &salt, &verifier,
4327                                           lgN->N, lgN->g)))
4328         goto end;
4329
4330     user_pwd = OPENSSL_zalloc(sizeof(*user_pwd));
4331     if (!TEST_ptr(user_pwd))
4332         goto end;
4333
4334     user_pwd->N = lgN->N;
4335     user_pwd->g = lgN->g;
4336     user_pwd->id = OPENSSL_strdup(userid);
4337     if (!TEST_ptr(user_pwd->id))
4338         goto end;
4339
4340     user_pwd->v = verifier;
4341     user_pwd->s = salt;
4342     verifier = salt = NULL;
4343
4344     if (sk_SRP_user_pwd_insert(vbase->users_pwd, user_pwd, 0) == 0)
4345         goto end;
4346     user_pwd = NULL;
4347
4348     ret = 1;
4349 end:
4350     SRP_user_pwd_free(user_pwd);
4351     BN_free(salt);
4352     BN_free(verifier);
4353
4354     return ret;
4355 }
4356
4357 /*
4358  * SRP tests
4359  *
4360  * Test 0: Simple successful SRP connection, new vbase
4361  * Test 1: Connection failure due to bad password, new vbase
4362  * Test 2: Simple successful SRP connection, vbase loaded from existing file
4363  * Test 3: Connection failure due to bad password, vbase loaded from existing
4364  *         file
4365  * Test 4: Simple successful SRP connection, vbase loaded from new file
4366  * Test 5: Connection failure due to bad password, vbase loaded from new file
4367  */
4368 static int test_srp(int tst)
4369 {
4370     char *userid = "test", *password = "password", *tstsrpfile;
4371     SSL_CTX *cctx = NULL, *sctx = NULL;
4372     SSL *clientssl = NULL, *serverssl = NULL;
4373     int ret, testresult = 0;
4374
4375     vbase = SRP_VBASE_new(NULL);
4376     if (!TEST_ptr(vbase))
4377         goto end;
4378
4379     if (tst == 0 || tst == 1) {
4380         if (!TEST_true(create_new_vbase(userid, password)))
4381             goto end;
4382     } else {
4383         if (tst == 4 || tst == 5) {
4384             if (!TEST_true(create_new_vfile(userid, password, tmpfilename)))
4385                 goto end;
4386             tstsrpfile = tmpfilename;
4387         } else {
4388             tstsrpfile = srpvfile;
4389         }
4390         if (!TEST_int_eq(SRP_VBASE_init(vbase, tstsrpfile), SRP_NO_ERROR))
4391             goto end;
4392     }
4393
4394     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(), TLS_client_method(),
4395                                        TLS1_VERSION, TLS_MAX_VERSION,
4396                                        &sctx, &cctx, cert, privkey)))
4397         goto end;
4398
4399     if (!TEST_int_gt(SSL_CTX_set_srp_username_callback(sctx, ssl_srp_cb), 0)
4400             || !TEST_true(SSL_CTX_set_cipher_list(cctx, "SRP-AES-128-CBC-SHA"))
4401             || !TEST_true(SSL_CTX_set_max_proto_version(sctx, TLS1_2_VERSION))
4402             || !TEST_true(SSL_CTX_set_max_proto_version(cctx, TLS1_2_VERSION))
4403             || !TEST_int_gt(SSL_CTX_set_srp_username(cctx, userid), 0))
4404         goto end;
4405
4406     if (tst % 2 == 1) {
4407         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, "badpass"), 0))
4408             goto end;
4409     } else {
4410         if (!TEST_int_gt(SSL_CTX_set_srp_password(cctx, password), 0))
4411             goto end;
4412     }
4413
4414     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4415                                       NULL, NULL)))
4416         goto end;
4417
4418     ret = create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE);
4419     if (ret) {
4420         if (!TEST_true(tst % 2 == 0))
4421             goto end;
4422     } else {
4423         if (!TEST_true(tst % 2 == 1))
4424             goto end;
4425     }
4426
4427     testresult = 1;
4428
4429  end:
4430     SRP_VBASE_free(vbase);
4431     vbase = NULL;
4432     SSL_free(serverssl);
4433     SSL_free(clientssl);
4434     SSL_CTX_free(sctx);
4435     SSL_CTX_free(cctx);
4436
4437     return testresult;
4438 }
4439 #endif
4440
4441 static int info_cb_failed = 0;
4442 static int info_cb_offset = 0;
4443 static int info_cb_this_state = -1;
4444
4445 static struct info_cb_states_st {
4446     int where;
4447     const char *statestr;
4448 } info_cb_states[][60] = {
4449     {
4450         /* TLSv1.2 server followed by resumption */
4451         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4452         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4453         {SSL_CB_LOOP, "TWSC"}, {SSL_CB_LOOP, "TWSKE"}, {SSL_CB_LOOP, "TWSD"},
4454         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWSD"}, {SSL_CB_LOOP, "TRCKE"},
4455         {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWST"},
4456         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4457         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4458         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4459         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
4460         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4461         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TRCCS"},
4462         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4463         {SSL_CB_EXIT, NULL}, {0, NULL},
4464     }, {
4465         /* TLSv1.2 client followed by resumption */
4466         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4467         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4468         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRSC"}, {SSL_CB_LOOP, "TRSKE"},
4469         {SSL_CB_LOOP, "TRSD"}, {SSL_CB_LOOP, "TWCKE"}, {SSL_CB_LOOP, "TWCCS"},
4470         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWFIN"},
4471         {SSL_CB_LOOP, "TRST"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
4472         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {SSL_CB_ALERT, NULL},
4473         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4474         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4475         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TRCCS"}, {SSL_CB_LOOP, "TRFIN"},
4476         {SSL_CB_LOOP, "TWCCS"},  {SSL_CB_LOOP, "TWFIN"},
4477         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4478     }, {
4479         /* TLSv1.3 server followed by resumption */
4480         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4481         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4482         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWSC"},
4483         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"},
4484         {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
4485         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4486         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4487         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TWST"},
4488         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4489         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4490         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"},
4491         {SSL_CB_LOOP, "TWSH"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"},
4492         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_LOOP, "TED"}, {SSL_CB_EXIT, NULL},
4493         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRFIN"},
4494         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4495         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4496         {SSL_CB_EXIT, NULL}, {0, NULL},
4497     }, {
4498         /* TLSv1.3 client followed by resumption */
4499         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4500         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL}, {SSL_CB_LOOP, "TWCH"},
4501         {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"}, {SSL_CB_LOOP, "TRSC"},
4502         {SSL_CB_LOOP, "TRSCV"}, {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"},
4503         {SSL_CB_LOOP, "TWFIN"},  {SSL_CB_HANDSHAKE_DONE, NULL},
4504         {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4505         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4506         {SSL_CB_HANDSHAKE_DONE, NULL},  {SSL_CB_EXIT, NULL},
4507         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "SSLOK "},
4508         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4509         {SSL_CB_HANDSHAKE_DONE, NULL},  {SSL_CB_EXIT, NULL},
4510         {SSL_CB_ALERT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4511         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TWCH"}, {SSL_CB_EXIT, NULL},
4512         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TRSH"},  {SSL_CB_LOOP, "TREE"},
4513         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWFIN"},
4514         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4515         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "SSLOK "},
4516         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4517         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4518     }, {
4519         /* TLSv1.3 server, early_data */
4520         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4521         {SSL_CB_LOOP, "PINIT "}, {SSL_CB_LOOP, "TRCH"}, {SSL_CB_LOOP, "TWSH"},
4522         {SSL_CB_LOOP, "TWCCS"}, {SSL_CB_LOOP, "TWEE"}, {SSL_CB_LOOP, "TWFIN"},
4523         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4524         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
4525         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TWEOED"}, {SSL_CB_LOOP, "TRFIN"},
4526         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4527         {SSL_CB_LOOP, "TWST"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4528         {SSL_CB_EXIT, NULL}, {0, NULL},
4529     }, {
4530         /* TLSv1.3 client, early_data */
4531         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "PINIT "},
4532         {SSL_CB_LOOP, "TWCH"}, {SSL_CB_LOOP, "TWCCS"},
4533         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL},
4534         {SSL_CB_HANDSHAKE_START, NULL}, {SSL_CB_LOOP, "TED"},
4535         {SSL_CB_LOOP, "TED"}, {SSL_CB_LOOP, "TRSH"}, {SSL_CB_LOOP, "TREE"},
4536         {SSL_CB_LOOP, "TRFIN"}, {SSL_CB_LOOP, "TPEDE"}, {SSL_CB_LOOP, "TWEOED"},
4537         {SSL_CB_LOOP, "TWFIN"}, {SSL_CB_HANDSHAKE_DONE, NULL},
4538         {SSL_CB_EXIT, NULL}, {SSL_CB_HANDSHAKE_START, NULL},
4539         {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "SSLOK "}, {SSL_CB_LOOP, "TRST"},
4540         {SSL_CB_HANDSHAKE_DONE, NULL}, {SSL_CB_EXIT, NULL}, {0, NULL},
4541     }, {
4542         {0, NULL},
4543     }
4544 };
4545
4546 static void sslapi_info_callback(const SSL *s, int where, int ret)
4547 {
4548     struct info_cb_states_st *state = info_cb_states[info_cb_offset];
4549
4550     /* We do not ever expect a connection to fail in this test */
4551     if (!TEST_false(ret == 0)) {
4552         info_cb_failed = 1;
4553         return;
4554     }
4555
4556     /*
4557      * Do some sanity checks. We never expect these things to happen in this
4558      * test
4559      */
4560     if (!TEST_false((SSL_is_server(s) && (where & SSL_ST_CONNECT) != 0))
4561             || !TEST_false(!SSL_is_server(s) && (where & SSL_ST_ACCEPT) != 0)
4562             || !TEST_int_ne(state[++info_cb_this_state].where, 0)) {
4563         info_cb_failed = 1;
4564         return;
4565     }
4566
4567     /* Now check we're in the right state */
4568     if (!TEST_true((where & state[info_cb_this_state].where) != 0)) {
4569         info_cb_failed = 1;
4570         return;
4571     }
4572     if ((where & SSL_CB_LOOP) != 0
4573             && !TEST_int_eq(strcmp(SSL_state_string(s),
4574                             state[info_cb_this_state].statestr), 0)) {
4575         info_cb_failed = 1;
4576         return;
4577     }
4578
4579     /* Check that, if we've got SSL_CB_HANDSHAKE_DONE we are not in init */
4580     if ((where & SSL_CB_HANDSHAKE_DONE) && SSL_in_init((SSL *)s) != 0) {
4581         info_cb_failed = 1;
4582         return;
4583     }
4584 }
4585
4586 /*
4587  * Test the info callback gets called when we expect it to.
4588  *
4589  * Test 0: TLSv1.2, server
4590  * Test 1: TLSv1.2, client
4591  * Test 2: TLSv1.3, server
4592  * Test 3: TLSv1.3, client
4593  * Test 4: TLSv1.3, server, early_data
4594  * Test 5: TLSv1.3, client, early_data
4595  */
4596 static int test_info_callback(int tst)
4597 {
4598     SSL_CTX *cctx = NULL, *sctx = NULL;
4599     SSL *clientssl = NULL, *serverssl = NULL;
4600     SSL_SESSION *clntsess = NULL;
4601     int testresult = 0;
4602     int tlsvers;
4603
4604     if (tst < 2) {
4605 /* We need either ECDHE or DHE for the TLSv1.2 test to work */
4606 #if !defined(OPENSSL_NO_TLS1_2) && (!defined(OPENSSL_NO_EC) \
4607                                     || !defined(OPENSSL_NO_DH))
4608         tlsvers = TLS1_2_VERSION;
4609 #else
4610         return 1;
4611 #endif
4612     } else {
4613 #ifndef OPENSSL_NO_TLS1_3
4614         tlsvers = TLS1_3_VERSION;
4615 #else
4616         return 1;
4617 #endif
4618     }
4619
4620     /* Reset globals */
4621     info_cb_failed = 0;
4622     info_cb_this_state = -1;
4623     info_cb_offset = tst;
4624
4625 #ifndef OPENSSL_NO_TLS1_3
4626     if (tst >= 4) {
4627         SSL_SESSION *sess = NULL;
4628         size_t written, readbytes;
4629         unsigned char buf[80];
4630
4631         /* early_data tests */
4632         if (!TEST_true(setupearly_data_test(&cctx, &sctx, &clientssl,
4633                                             &serverssl, &sess, 0)))
4634             goto end;
4635
4636         /* We don't actually need this reference */
4637         SSL_SESSION_free(sess);
4638
4639         SSL_set_info_callback((tst % 2) == 0 ? serverssl : clientssl,
4640                               sslapi_info_callback);
4641
4642         /* Write and read some early data and then complete the connection */
4643         if (!TEST_true(SSL_write_early_data(clientssl, MSG1, strlen(MSG1),
4644                                             &written))
4645                 || !TEST_size_t_eq(written, strlen(MSG1))
4646                 || !TEST_int_eq(SSL_read_early_data(serverssl, buf,
4647                                                     sizeof(buf), &readbytes),
4648                                 SSL_READ_EARLY_DATA_SUCCESS)
4649                 || !TEST_mem_eq(MSG1, readbytes, buf, strlen(MSG1))
4650                 || !TEST_int_eq(SSL_get_early_data_status(serverssl),
4651                                 SSL_EARLY_DATA_ACCEPTED)
4652                 || !TEST_true(create_ssl_connection(serverssl, clientssl,
4653                                                     SSL_ERROR_NONE))
4654                 || !TEST_false(info_cb_failed))
4655             goto end;
4656
4657         testresult = 1;
4658         goto end;
4659     }
4660 #endif
4661
4662     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4663                                        TLS_client_method(),
4664                                        tlsvers, tlsvers, &sctx, &cctx, cert,
4665                                        privkey)))
4666         goto end;
4667
4668     /*
4669      * For even numbered tests we check the server callbacks. For odd numbers we
4670      * check the client.
4671      */
4672     SSL_CTX_set_info_callback((tst % 2) == 0 ? sctx : cctx,
4673                               sslapi_info_callback);
4674
4675     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
4676                                           &clientssl, NULL, NULL))
4677         || !TEST_true(create_ssl_connection(serverssl, clientssl,
4678                                             SSL_ERROR_NONE))
4679         || !TEST_false(info_cb_failed))
4680     goto end;
4681
4682
4683
4684     clntsess = SSL_get1_session(clientssl);
4685     SSL_shutdown(clientssl);
4686     SSL_shutdown(serverssl);
4687     SSL_free(serverssl);
4688     SSL_free(clientssl);
4689     serverssl = clientssl = NULL;
4690
4691     /* Now do a resumption */
4692     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
4693                                       NULL))
4694             || !TEST_true(SSL_set_session(clientssl, clntsess))
4695             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4696                                                 SSL_ERROR_NONE))
4697             || !TEST_true(SSL_session_reused(clientssl))
4698             || !TEST_false(info_cb_failed))
4699         goto end;
4700
4701     testresult = 1;
4702
4703  end:
4704     SSL_free(serverssl);
4705     SSL_free(clientssl);
4706     SSL_SESSION_free(clntsess);
4707     SSL_CTX_free(sctx);
4708     SSL_CTX_free(cctx);
4709     return testresult;
4710 }
4711
4712 static int test_ssl_pending(int tst)
4713 {
4714     SSL_CTX *cctx = NULL, *sctx = NULL;
4715     SSL *clientssl = NULL, *serverssl = NULL;
4716     int testresult = 0;
4717     char msg[] = "A test message";
4718     char buf[5];
4719     size_t written, readbytes;
4720
4721     if (tst == 0) {
4722         if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4723                                            TLS_client_method(),
4724                                            TLS1_VERSION, TLS_MAX_VERSION,
4725                                            &sctx, &cctx, cert, privkey)))
4726             goto end;
4727     } else {
4728 #ifndef OPENSSL_NO_DTLS
4729         if (!TEST_true(create_ssl_ctx_pair(DTLS_server_method(),
4730                                            DTLS_client_method(),
4731                                            DTLS1_VERSION, DTLS_MAX_VERSION,
4732                                            &sctx, &cctx, cert, privkey)))
4733             goto end;
4734 #else
4735         return 1;
4736 #endif
4737     }
4738
4739     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4740                                              NULL, NULL))
4741             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4742                                                 SSL_ERROR_NONE)))
4743         goto end;
4744
4745     if (!TEST_int_eq(SSL_pending(clientssl), 0)
4746             || !TEST_false(SSL_has_pending(clientssl))
4747             || !TEST_int_eq(SSL_pending(serverssl), 0)
4748             || !TEST_false(SSL_has_pending(serverssl))
4749             || !TEST_true(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
4750             || !TEST_size_t_eq(written, sizeof(msg))
4751             || !TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf), &readbytes))
4752             || !TEST_size_t_eq(readbytes, sizeof(buf))
4753             || !TEST_int_eq(SSL_pending(clientssl), (int)(written - readbytes))
4754             || !TEST_true(SSL_has_pending(clientssl)))
4755         goto end;
4756
4757     testresult = 1;
4758
4759  end:
4760     SSL_free(serverssl);
4761     SSL_free(clientssl);
4762     SSL_CTX_free(sctx);
4763     SSL_CTX_free(cctx);
4764
4765     return testresult;
4766 }
4767
4768 static struct {
4769     unsigned int maxprot;
4770     const char *clntciphers;
4771     const char *clnttls13ciphers;
4772     const char *srvrciphers;
4773     const char *srvrtls13ciphers;
4774     const char *shared;
4775 } shared_ciphers_data[] = {
4776 /*
4777  * We can't establish a connection (even in TLSv1.1) with these ciphersuites if
4778  * TLSv1.3 is enabled but TLSv1.2 is disabled.
4779  */
4780 #if defined(OPENSSL_NO_TLS1_3) || !defined(OPENSSL_NO_TLS1_2)
4781     {
4782         TLS1_2_VERSION,
4783         "AES128-SHA:AES256-SHA",
4784         NULL,
4785         "AES256-SHA:DHE-RSA-AES128-SHA",
4786         NULL,
4787         "AES256-SHA"
4788     },
4789     {
4790         TLS1_2_VERSION,
4791         "AES128-SHA:DHE-RSA-AES128-SHA:AES256-SHA",
4792         NULL,
4793         "AES128-SHA:DHE-RSA-AES256-SHA:AES256-SHA",
4794         NULL,
4795         "AES128-SHA:AES256-SHA"
4796     },
4797     {
4798         TLS1_2_VERSION,
4799         "AES128-SHA:AES256-SHA",
4800         NULL,
4801         "AES128-SHA:DHE-RSA-AES128-SHA",
4802         NULL,
4803         "AES128-SHA"
4804     },
4805 #endif
4806 /*
4807  * This test combines TLSv1.3 and TLSv1.2 ciphersuites so they must both be
4808  * enabled.
4809  */
4810 #if !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_TLS1_2) \
4811     && !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
4812     {
4813         TLS1_3_VERSION,
4814         "AES128-SHA:AES256-SHA",
4815         NULL,
4816         "AES256-SHA:AES128-SHA256",
4817         NULL,
4818         "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:"
4819         "TLS_AES_128_GCM_SHA256:AES256-SHA"
4820     },
4821 #endif
4822 #ifndef OPENSSL_NO_TLS1_3
4823     {
4824         TLS1_3_VERSION,
4825         "AES128-SHA",
4826         "TLS_AES_256_GCM_SHA384",
4827         "AES256-SHA",
4828         "TLS_AES_256_GCM_SHA384",
4829         "TLS_AES_256_GCM_SHA384"
4830     },
4831 #endif
4832 };
4833
4834 static int test_ssl_get_shared_ciphers(int tst)
4835 {
4836     SSL_CTX *cctx = NULL, *sctx = NULL;
4837     SSL *clientssl = NULL, *serverssl = NULL;
4838     int testresult = 0;
4839     char buf[1024];
4840
4841     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
4842                                        TLS_client_method(),
4843                                        TLS1_VERSION,
4844                                        shared_ciphers_data[tst].maxprot,
4845                                        &sctx, &cctx, cert, privkey)))
4846         goto end;
4847
4848     if (!TEST_true(SSL_CTX_set_cipher_list(cctx,
4849                                         shared_ciphers_data[tst].clntciphers))
4850             || (shared_ciphers_data[tst].clnttls13ciphers != NULL
4851                 && !TEST_true(SSL_CTX_set_ciphersuites(cctx,
4852                                     shared_ciphers_data[tst].clnttls13ciphers)))
4853             || !TEST_true(SSL_CTX_set_cipher_list(sctx,
4854                                         shared_ciphers_data[tst].srvrciphers))
4855             || (shared_ciphers_data[tst].srvrtls13ciphers != NULL
4856                 && !TEST_true(SSL_CTX_set_ciphersuites(sctx,
4857                                     shared_ciphers_data[tst].srvrtls13ciphers))))
4858         goto end;
4859
4860
4861     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
4862                                              NULL, NULL))
4863             || !TEST_true(create_ssl_connection(serverssl, clientssl,
4864                                                 SSL_ERROR_NONE)))
4865         goto end;
4866
4867     if (!TEST_ptr(SSL_get_shared_ciphers(serverssl, buf, sizeof(buf)))
4868             || !TEST_int_eq(strcmp(buf, shared_ciphers_data[tst].shared), 0)) {
4869         TEST_info("Shared ciphers are: %s\n", buf);
4870         goto end;
4871     }
4872
4873     testresult = 1;
4874
4875  end:
4876     SSL_free(serverssl);
4877     SSL_free(clientssl);
4878     SSL_CTX_free(sctx);
4879     SSL_CTX_free(cctx);
4880
4881     return testresult;
4882 }
4883
4884 static const char *appdata = "Hello World";
4885 static int gen_tick_called, dec_tick_called, tick_key_cb_called;
4886 static int tick_key_renew = 0;
4887 static SSL_TICKET_RETURN tick_dec_ret = SSL_TICKET_RETURN_ABORT;
4888
4889 static int gen_tick_cb(SSL *s, void *arg)
4890 {
4891     gen_tick_called = 1;
4892
4893     return SSL_SESSION_set1_ticket_appdata(SSL_get_session(s), appdata,
4894                                            strlen(appdata));
4895 }
4896
4897 static SSL_TICKET_RETURN dec_tick_cb(SSL *s, SSL_SESSION *ss,
4898                                      const unsigned char *keyname,
4899                                      size_t keyname_length,
4900                                      SSL_TICKET_STATUS status,
4901                                      void *arg)
4902 {
4903     void *tickdata;
4904     size_t tickdlen;
4905
4906     dec_tick_called = 1;
4907
4908     if (status == SSL_TICKET_EMPTY)
4909         return SSL_TICKET_RETURN_IGNORE_RENEW;
4910
4911     if (!TEST_true(status == SSL_TICKET_SUCCESS
4912                    || status == SSL_TICKET_SUCCESS_RENEW))
4913         return SSL_TICKET_RETURN_ABORT;
4914
4915     if (!TEST_true(SSL_SESSION_get0_ticket_appdata(ss, &tickdata,
4916                                                    &tickdlen))
4917             || !TEST_size_t_eq(tickdlen, strlen(appdata))
4918             || !TEST_int_eq(memcmp(tickdata, appdata, tickdlen), 0))
4919         return SSL_TICKET_RETURN_ABORT;
4920
4921     if (tick_key_cb_called)  {
4922         /* Don't change what the ticket key callback wanted to do */
4923         switch (status) {
4924         case SSL_TICKET_NO_DECRYPT:
4925             return SSL_TICKET_RETURN_IGNORE_RENEW;
4926
4927         case SSL_TICKET_SUCCESS:
4928             return SSL_TICKET_RETURN_USE;
4929
4930         case SSL_TICKET_SUCCESS_RENEW:
4931             return SSL_TICKET_RETURN_USE_RENEW;
4932
4933         default:
4934             return SSL_TICKET_RETURN_ABORT;
4935         }
4936     }
4937     return tick_dec_ret;
4938
4939 }
4940
4941 static int tick_key_cb(SSL *s, unsigned char key_name[16],
4942                        unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
4943                        HMAC_CTX *hctx, int enc)
4944 {
4945     const unsigned char tick_aes_key[16] = "0123456789abcdef";
4946     const unsigned char tick_hmac_key[16] = "0123456789abcdef";
4947
4948     tick_key_cb_called = 1;
4949     memset(iv, 0, AES_BLOCK_SIZE);
4950     memset(key_name, 0, 16);
4951     if (!EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, tick_aes_key, iv, enc)
4952             || !HMAC_Init_ex(hctx, tick_hmac_key, sizeof(tick_hmac_key),
4953                              EVP_sha256(), NULL))
4954         return -1;
4955
4956     return tick_key_renew ? 2 : 1;
4957 }
4958
4959 /*
4960  * Test the various ticket callbacks
4961  * Test 0: TLSv1.2, no ticket key callback, no ticket, no renewal
4962  * Test 1: TLSv1.3, no ticket key callback, no ticket, no renewal
4963  * Test 2: TLSv1.2, no ticket key callback, no ticket, renewal
4964  * Test 3: TLSv1.3, no ticket key callback, no ticket, renewal
4965  * Test 4: TLSv1.2, no ticket key callback, ticket, no renewal
4966  * Test 5: TLSv1.3, no ticket key callback, ticket, no renewal
4967  * Test 6: TLSv1.2, no ticket key callback, ticket, renewal
4968  * Test 7: TLSv1.3, no ticket key callback, ticket, renewal
4969  * Test 8: TLSv1.2, ticket key callback, ticket, no renewal
4970  * Test 9: TLSv1.3, ticket key callback, ticket, no renewal
4971  * Test 10: TLSv1.2, ticket key callback, ticket, renewal
4972  * Test 11: TLSv1.3, ticket key callback, ticket, renewal
4973  */
4974 static int test_ticket_callbacks(int tst)
4975 {
4976     SSL_CTX *cctx = NULL, *sctx = NULL;
4977     SSL *clientssl = NULL, *serverssl = NULL;
4978     SSL_SESSION *clntsess = NULL;
4979     int testresult = 0;
4980
4981 #ifdef OPENSSL_NO_TLS1_2
4982     if (tst % 2 == 0)
4983         return 1;
4984 #endif
4985 #ifdef OPENSSL_NO_TLS1_3
4986     if (tst % 2 == 1)
4987         return 1;
4988 #endif
4989
4990     gen_tick_called = dec_tick_called = tick_key_cb_called = 0;
4991
4992     /* Which tests the ticket key callback should request renewal for */
4993     if (tst == 10 || tst == 11)
4994         tick_key_renew = 1;
4995     else
4996         tick_key_renew = 0;
4997
4998     /* Which tests the decrypt ticket callback should request renewal for */
4999     switch (tst) {
5000     case 0:
5001     case 1:
5002         tick_dec_ret = SSL_TICKET_RETURN_IGNORE;
5003         break;
5004
5005     case 2:
5006     case 3:
5007         tick_dec_ret = SSL_TICKET_RETURN_IGNORE_RENEW;
5008         break;
5009
5010     case 4:
5011     case 5:
5012         tick_dec_ret = SSL_TICKET_RETURN_USE;
5013         break;
5014
5015     case 6:
5016     case 7:
5017         tick_dec_ret = SSL_TICKET_RETURN_USE_RENEW;
5018         break;
5019
5020     default:
5021         tick_dec_ret = SSL_TICKET_RETURN_ABORT;
5022     }
5023
5024     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5025                                        TLS_client_method(),
5026                                        TLS1_VERSION,
5027                                        ((tst % 2) == 0) ? TLS1_2_VERSION
5028                                                         : TLS1_3_VERSION,
5029                                        &sctx, &cctx, cert, privkey)))
5030         goto end;
5031
5032     /*
5033      * We only want sessions to resume from tickets - not the session cache. So
5034      * switch the cache off.
5035      */
5036     if (!TEST_true(SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_OFF)))
5037         goto end;
5038
5039     if (!TEST_true(SSL_CTX_set_session_ticket_cb(sctx, gen_tick_cb, dec_tick_cb,
5040                                                  NULL)))
5041         goto end;
5042
5043     if (tst >= 8
5044             && !TEST_true(SSL_CTX_set_tlsext_ticket_key_cb(sctx, tick_key_cb)))
5045         goto end;
5046
5047     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5048                                              NULL, NULL))
5049             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5050                                                 SSL_ERROR_NONE)))
5051         goto end;
5052
5053     /*
5054      * The decrypt ticket key callback in TLSv1.2 should be called even though
5055      * we have no ticket yet, because it gets called with a status of
5056      * SSL_TICKET_EMPTY (the client indicates support for tickets but does not
5057      * actually send any ticket data). This does not happen in TLSv1.3 because
5058      * it is not valid to send empty ticket data in TLSv1.3.
5059      */
5060     if (!TEST_int_eq(gen_tick_called, 1)
5061             || !TEST_int_eq(dec_tick_called, ((tst % 2) == 0) ? 1 : 0))
5062         goto end;
5063
5064     gen_tick_called = dec_tick_called = 0;
5065
5066     clntsess = SSL_get1_session(clientssl);
5067     SSL_shutdown(clientssl);
5068     SSL_shutdown(serverssl);
5069     SSL_free(serverssl);
5070     SSL_free(clientssl);
5071     serverssl = clientssl = NULL;
5072
5073     /* Now do a resumption */
5074     if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl, NULL,
5075                                       NULL))
5076             || !TEST_true(SSL_set_session(clientssl, clntsess))
5077             || !TEST_true(create_ssl_connection(serverssl, clientssl,
5078                                                 SSL_ERROR_NONE)))
5079         goto end;
5080
5081     if (tick_dec_ret == SSL_TICKET_RETURN_IGNORE
5082             || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW) {
5083         if (!TEST_false(SSL_session_reused(clientssl)))
5084             goto end;
5085     } else {
5086         if (!TEST_true(SSL_session_reused(clientssl)))
5087             goto end;
5088     }
5089
5090     if (!TEST_int_eq(gen_tick_called,
5091                      (tick_key_renew
5092                       || tick_dec_ret == SSL_TICKET_RETURN_IGNORE_RENEW
5093                       || tick_dec_ret == SSL_TICKET_RETURN_USE_RENEW)
5094                      ? 1 : 0)
5095             || !TEST_int_eq(dec_tick_called, 1))
5096         goto end;
5097
5098     testresult = 1;
5099
5100  end:
5101     SSL_SESSION_free(clntsess);
5102     SSL_free(serverssl);
5103     SSL_free(clientssl);
5104     SSL_CTX_free(sctx);
5105     SSL_CTX_free(cctx);
5106
5107     return testresult;
5108 }
5109
5110 /*
5111  * Test bi-directional shutdown.
5112  * Test 0: TLSv1.2
5113  * Test 1: TLSv1.2, server continues to read/write after client shutdown
5114  * Test 2: TLSv1.3, no pending NewSessionTicket messages
5115  * Test 3: TLSv1.3, pending NewSessionTicket messages
5116  * Test 4: TLSv1.3, server continues to read/write after client shutdown, client
5117  *                  reads it
5118  * Test 5: TLSv1.3, server continues to read/write after client shutdown, client
5119  *                  doesn't read it
5120  */
5121 static int test_shutdown(int tst)
5122 {
5123     SSL_CTX *cctx = NULL, *sctx = NULL;
5124     SSL *clientssl = NULL, *serverssl = NULL;
5125     int testresult = 0;
5126     char msg[] = "A test message";
5127     char buf[80];
5128     size_t written, readbytes;
5129
5130 #ifdef OPENSSL_NO_TLS1_2
5131     if (tst <= 1)
5132         return 1;
5133 #endif
5134 #ifdef OPENSSL_NO_TLS1_3
5135     if (tst >= 2)
5136         return 1;
5137 #endif
5138
5139     if (!TEST_true(create_ssl_ctx_pair(TLS_server_method(),
5140                                        TLS_client_method(),
5141                                        TLS1_VERSION,
5142                                        (tst <= 1) ? TLS1_2_VERSION
5143                                                   : TLS1_3_VERSION,
5144                                        &sctx, &cctx, cert, privkey))
5145             || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
5146                                              NULL, NULL)))
5147         goto end;
5148
5149     if (tst == 3) {
5150         if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
5151                                                   SSL_ERROR_NONE)))
5152             goto end;
5153     } else if (!TEST_true(create_ssl_connection(serverssl, clientssl,
5154                                               SSL_ERROR_NONE))) {
5155         goto end;
5156     }
5157
5158     if (!TEST_int_eq(SSL_shutdown(clientssl), 0))
5159         goto end;
5160
5161     if (tst >= 4) {
5162         /*
5163          * Reading on the server after the client has sent close_notify should
5164          * fail and provide SSL_ERROR_ZERO_RETURN
5165          */
5166         if (!TEST_false(SSL_read_ex(serverssl, buf, sizeof(buf), &readbytes))
5167                 || !TEST_int_eq(SSL_get_error(serverssl, 0),
5168                                 SSL_ERROR_ZERO_RETURN)
5169                 || !TEST_int_eq(SSL_get_shutdown(serverssl),
5170                                 SSL_RECEIVED_SHUTDOWN)
5171                    /*
5172                     * Even though we're shutdown on receive we should still be
5173                     * able to write.
5174                     */
5175                 || !TEST_true(SSL_write(serverssl, msg, sizeof(msg)))
5176                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
5177             goto end;
5178         if (tst == 4) {
5179                    /* Should still be able to read data from server */
5180             if (!TEST_true(SSL_read_ex(clientssl, buf, sizeof(buf),
5181                                           &readbytes))
5182                     || !TEST_size_t_eq(readbytes, sizeof(msg))
5183                     || !TEST_int_eq(memcmp(msg, buf, readbytes), 0))
5184                 goto end;
5185         }
5186     }
5187
5188     /* Writing on the client after sending close_notify shouldn't be possible */
5189     if (!TEST_false(SSL_write_ex(clientssl, msg, sizeof(msg), &written)))
5190         goto end;
5191
5192     if (tst < 4) {
5193         /*
5194          * For these tests the client has sent close_notify but it has not yet
5195          * been received by the server. The server has not sent close_notify
5196          * yet.
5197          */
5198         if (!TEST_int_eq(SSL_shutdown(serverssl), 0)
5199                    /*
5200                     * Writing on the server after sending close_notify shouldn't
5201                     * be possible.
5202                     */
5203                 || !TEST_false(SSL_write_ex(serverssl, msg, sizeof(msg), &written))
5204                 || !TEST_int_eq(SSL_shutdown(clientssl), 1)
5205                 || !TEST_int_eq(SSL_shutdown(serverssl), 1))
5206             goto end;
5207     } else if (tst == 4) {
5208         /*
5209          * In this test the client has sent close_notify and it has been
5210          * received by the server which has responded with a close_notify. The
5211          * client needs to read the close_notify sent by the server.
5212          */
5213         if (!TEST_int_eq(SSL_shutdown(clientssl), 1))
5214             goto end;
5215     } else {
5216         /*
5217          * tst == 5
5218          *
5219          * The client has sent close_notify and is expecting a close_notify
5220          * back, but instead there is application data first. The shutdown
5221          * should fail with a fatal error.
5222          */
5223         if (!TEST_int_eq(SSL_shutdown(clientssl), -1)
5224                 || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
5225             goto end;
5226     }
5227
5228     testresult = 1;
5229
5230  end:
5231     SSL_free(serverssl);
5232     SSL_free(clientssl);
5233     SSL_CTX_free(sctx);
5234     SSL_CTX_free(cctx);
5235
5236     return testresult;
5237 }
5238
5239 int setup_tests(void)
5240 {
5241     if (!TEST_ptr(cert = test_get_argument(0))
5242             || !TEST_ptr(privkey = test_get_argument(1))
5243             || !TEST_ptr(srpvfile = test_get_argument(2))
5244             || !TEST_ptr(tmpfilename = test_get_argument(3)))
5245         return 0;
5246
5247     if (getenv("OPENSSL_TEST_GETCOUNTS") != NULL) {
5248 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
5249         TEST_error("not supported in this build");
5250         return 0;
5251 #else
5252         int i, mcount, rcount, fcount;
5253
5254         for (i = 0; i < 4; i++)
5255             test_export_key_mat(i);
5256         CRYPTO_get_alloc_counts(&mcount, &rcount, &fcount);
5257         test_printf_stdout("malloc %d realloc %d free %d\n",
5258                 mcount, rcount, fcount);
5259         return 1;
5260 #endif
5261     }
5262
5263     ADD_TEST(test_large_message_tls);
5264     ADD_TEST(test_large_message_tls_read_ahead);
5265 #ifndef OPENSSL_NO_DTLS
5266     ADD_TEST(test_large_message_dtls);
5267 #endif
5268 #ifndef OPENSSL_NO_OCSP
5269     ADD_TEST(test_tlsext_status_type);
5270 #endif
5271     ADD_TEST(test_session_with_only_int_cache);
5272     ADD_TEST(test_session_with_only_ext_cache);
5273     ADD_TEST(test_session_with_both_cache);
5274 #ifndef OPENSSL_NO_TLS1_3
5275     ADD_ALL_TESTS(test_tickets, 3);
5276 #endif
5277     ADD_ALL_TESTS(test_ssl_set_bio, TOTAL_SSL_SET_BIO_TESTS);
5278     ADD_TEST(test_ssl_bio_pop_next_bio);
5279     ADD_TEST(test_ssl_bio_pop_ssl_bio);
5280     ADD_TEST(test_ssl_bio_change_rbio);
5281     ADD_TEST(test_ssl_bio_change_wbio);
5282 #if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
5283     ADD_ALL_TESTS(test_set_sigalgs, OSSL_NELEM(testsigalgs) * 2);
5284     ADD_TEST(test_keylog);
5285 #endif
5286 #ifndef OPENSSL_NO_TLS1_3
5287     ADD_TEST(test_keylog_no_master_key);
5288 #endif
5289 #ifndef OPENSSL_NO_TLS1_2
5290     ADD_TEST(test_client_hello_cb);
5291 #endif
5292 #ifndef OPENSSL_NO_TLS1_3
5293     ADD_ALL_TESTS(test_early_data_read_write, 3);
5294     /*
5295      * We don't do replay tests for external PSK. Replay protection isn't used
5296      * in that scenario.
5297      */
5298     ADD_ALL_TESTS(test_early_data_replay, 2);
5299     ADD_ALL_TESTS(test_early_data_skip, 3);
5300     ADD_ALL_TESTS(test_early_data_skip_hrr, 3);
5301     ADD_ALL_TESTS(test_early_data_skip_abort, 3);
5302     ADD_ALL_TESTS(test_early_data_not_sent, 3);
5303     ADD_ALL_TESTS(test_early_data_psk, 8);
5304     ADD_ALL_TESTS(test_early_data_not_expected, 3);
5305 # ifndef OPENSSL_NO_TLS1_2
5306     ADD_ALL_TESTS(test_early_data_tls1_2, 3);
5307 # endif
5308 #endif
5309 #ifndef OPENSSL_NO_TLS1_3
5310     ADD_ALL_TESTS(test_set_ciphersuite, 10);
5311     ADD_TEST(test_ciphersuite_change);
5312 #ifdef OPENSSL_NO_PSK
5313     ADD_ALL_TESTS(test_tls13_psk, 1);
5314 #else
5315     ADD_ALL_TESTS(test_tls13_psk, 4);
5316 #endif  /* OPENSSL_NO_PSK */
5317     ADD_ALL_TESTS(test_custom_exts, 5);
5318     ADD_TEST(test_stateless);
5319     ADD_TEST(test_pha_key_update);
5320 #else
5321     ADD_ALL_TESTS(test_custom_exts, 3);
5322 #endif
5323     ADD_ALL_TESTS(test_serverinfo, 8);
5324     ADD_ALL_TESTS(test_export_key_mat, 4);
5325 #ifndef OPENSSL_NO_TLS1_3
5326     ADD_ALL_TESTS(test_export_key_mat_early, 3);
5327 #endif
5328     ADD_ALL_TESTS(test_ssl_clear, 2);
5329     ADD_ALL_TESTS(test_max_fragment_len_ext, OSSL_NELEM(max_fragment_len_test));
5330 #if !defined(OPENSSL_NO_SRP) && !defined(OPENSSL_NO_TLS1_2)
5331     ADD_ALL_TESTS(test_srp, 6);
5332 #endif
5333     ADD_ALL_TESTS(test_info_callback, 6);
5334     ADD_ALL_TESTS(test_ssl_pending, 2);
5335     ADD_ALL_TESTS(test_ssl_get_shared_ciphers, OSSL_NELEM(shared_ciphers_data));
5336     ADD_ALL_TESTS(test_ticket_callbacks, 12);
5337     ADD_ALL_TESTS(test_shutdown, 6);
5338     return 1;
5339 }
5340
5341 void cleanup_tests(void)
5342 {
5343     bio_s_mempacket_test_free();
5344 }