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