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