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