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