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